Esempio n. 1
0
def main():
	
	original_string = "Hello world!"

	# Create an object f of type Functions. Internal f.__string is set to original_string at initialization
	f = Functions(original_string)

	
	# If the internal variable f.__string has been changed, we check if it was changed using the setter f.setString()
	if f.getString() != original_string and f.setterUsed() == False:
		print "ERROR! Something is wrong here! Did you manipulate private variables in the Functions class directly??"
		# Hint: We didn't, there is a bug in the Functions class	
	else:
		f.printString() # Print out f.__string	
Esempio n. 2
0
class Game(object):
    def __init__(self):
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode(self.settings.screen_size)
        self.compass = Compass()
        self.place = Place(self.settings, self.screen, self.compass)
        self.form = Form(self.settings, self.screen, self.compass)
        self.functions = Functions(self.settings, self.screen, self.compass,
                                   self.place, self.form)

    def start(self):
        while True:
            self.functions.check_events()
            self.functions.draw_screen()
Esempio n. 3
0
 def test_upload_objects(self):
     self.__moto_setup()
     f = Functions(parameter)
     f.upload_objects()
     s3_client = boto3.client("s3")
     s3_bucket_object_count = 0
     response = s3_client.list_objects_v2(Bucket='shivam1052061')
     if response:
         try:
             for _object in response['Contents']:
                 s3_bucket_object_count = s3_bucket_object_count + 1
         except KeyError:
             print("KeyError. No such key exists in the specified bucket")
     # print(s3_bucket_object_count)
     self.assertEqual(s3_bucket_object_count, 10)
Esempio n. 4
0
class Game(object):
    def __init__(self):
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode(self.settings.screen_size)
        self.data = Data()
        self.block = Block(self.settings, self.screen, self.data)
        self.functions = Functions(self.settings, self.screen, self.block,
                                   self.data)

    def start(self):
        while True:
            if self.functions.check_event():
                self.data.random_display()
            self.functions.draw_screen()
Esempio n. 5
0
    def __init__(self, address):

        super().__init__(address)

        self.about = About(self)
        self.access = Access(self)
        self.adjustment = Adjustment(self)
        self.axis = Axis(self)
        self.displacement = Displacement(self)
        self.ecu = Ecu(self)
        self.functions = Functions(self)
        self.manual = Manual(self)
        self.network = Network(self)
        self.nlc = Nlc(self)
        self.pilotlaser = Pilotlaser(self)
        self.realtime = Realtime(self)
        self.system = System(self)
        self.system_service = System_service(self)
        self.update = Update(self)
        try:
            self.streaming = Streaming(self)
        except NameError as e:
            if "Streaming" in str(e):
                print("Warning: Streaming is not supported on your platform")
            else:
                raise e
Esempio n. 6
0
 def __init__(self, serial_port):
     self.scorbot = Functions(serial_port)
     self.pos_ini = 'ini'
     self.pos_end = 'end'
     self.pos_user = '******'
     self.current_x = 97
     self.current_y = -1959
Esempio n. 7
0
    def get_category_name(self, category_index):
        li_elements = self.take_category_elements()
        category_name = li_elements[category_index].text

        Functions(self.driver).click_dynamic_element(
            li_elements[category_index])

        return category_name
Esempio n. 8
0
    def learn(self, M_x, v_y, learning_rate, max_loops=1000):
        loop_nr = 0
        while True:
            for i in range(M_x.shape[0]):  # for each example - index: i
                # Just copy the input into INPUT of layer 0
                self.layers[0].IN = M_x[i]

                # Now propagate a[0] forward and store the interim results a[l] for the layers l
                for l in range(
                        self.num_layers
                ):  # for each layer except of the first - index l
                    layer = self.layers[l]
                    y = np.empty((layer.num_nodes))
                    res = np.empty((layer.num_nodes))
                    for j in range(
                            layer.num_nodes
                    ):  # for each row in weight matrix of layer l - index j
                        res[j] = np.dot(layer.weight_matrix[j], layer.IN)
                        y[j] = layer.activation(res[j])

                    layer.OUT = y  # = g(RAW_OUT) = g(SUM(wv))
                    layer.RAW_OUT = res  # = SUM(wv)
                    if l < self.num_layers - 1:
                        self.layers[l + 1].IN = self.layers[l].OUT

                # Compute the error at the output layer
                out_layer = self.layers[self.num_layers - 1]  # output layer
                out_layer.DELTA = out_layer.deriv_act(out_layer.RAW_OUT) * (
                    v_y[i] - out_layer.OUT)  # i = example index

                # Compute the other deltas, backwards running through the layers
                for l in reversed(range(self.num_layers - 1)):
                    layer_m = self.layers[l]
                    layer_m_plus_1 = self.layers[l + 1]
                    delta_m = layer_m.deriv_act(layer_m.RAW_OUT) * \
                              np.dot(layer_m_plus_1.weight_matrix.T, layer_m_plus_1.DELTA)
                    layer_m.DELTA = delta_m

                # And finally adjust weights.
                # This may be done in forward order because all data are available here.
                for l in range(self.num_layers):
                    layer = self.layers[l]
                    for j in range(layer.num_nodes):
                        delta_w = learning_rate * layer.DELTA[j] * layer.IN
                        layer.weight_matrix[
                            j] = layer.weight_matrix[j] + delta_w

            # Calculate a more or less reasonable error metric
            error = Functions.squared_error(
                v_y[i], self.layers[self.num_layers - 1].OUT)
            error = math.sqrt(error)
            loop_nr += 1

            if error < 0.001 or loop_nr > max_loops:
                # print("learning loops: ", loop_nr)
                break  # while

        return
Esempio n. 9
0
	def __init__(self):
		super().__init__(
			command_prefix = Config.prefix,
			description = "Host crowd sources Q&As directly in your Discord guild. https://github.com/wwwaffles/amabot"
		)

		self.config = Config()
		self.db: AsyncIOMotorDatabase
		self.functions = Functions()
Esempio n. 10
0
	def __init__(self):
		super().__init__(
			command_prefix = "//",
			description = ""
		)

		self.config = Config()
		self.db: AsyncIOMotorDatabase
		self.functions = Functions()
Esempio n. 11
0
    def __init__(self):
        # Set Config files
        self.home = os.path.expanduser("~")
        self.configDir = self.home + "/.config/favoritesAppsIndicator"
        self.iconDefault = APP_DIR + "/icon/favoritesApps.png"

        # Init functions class
        self.functions = Functions(APP_DIR, self.iconDefault)

        # Read Json File
        self.json_file = self.configDir + "/favoritesApps.json"
        self.json_data = self.functions.read_json_file(self.json_file)
        self.cmd_stat_json_file = "stat -c '%y' \"" + self.json_file + "\""
        self.stats_config_file = self.functions.exec_command_get_output(
            self.cmd_stat_json_file)

        # Init other class
        self.path_desktop_files = DesktopFilesInterface()
        self.favorites_files_manager = FavoritesFilesManagerInterface(
            self.json_data)
        self.app_info = AppInfoInterface(APP_DIR, self.iconDefault)

        # Other
        self.applicationID = 'favorites_apps_indicator'
        self.stop_thread = False
        self.locale = self.functions.get_locale_code()

        # Keys
        self.key_comment_JsonFile = "INFO"
        self.key_app_no_menu = "EXTERNALAPP"
        self.key_separator = "separator_"

        # Define Indicator
        self.indicator = AppIndicator3.Indicator.new(
            self.applicationID, self.iconDefault,
            AppIndicator3.IndicatorCategory.OTHER)
        self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)

        # start service
        self.start_service_update_menu()

        # Create Set Menu
        self.indicator.set_menu(self.create_menu())
Esempio n. 12
0
    def create_widgets(self):
        child = LabelFrame(self.parent, text="Text Box", padx=5, pady=5)
        child.grid(row=1,
                   column=0,
                   columnspan=3,
                   padx=10,
                   pady=10,
                   sticky=E + W + N + S)
        self.parent.columnconfigure(0, weight=1)
        self.parent.rowconfigure(1, weight=1)
        child.rowconfigure(0, weight=1)
        child.columnconfigure(0, weight=1)

        self.textBox = scrolledtext.ScrolledText(child, width=50, height=20)
        self.textBox.grid(column=0, row=0, sticky=E + W + N + S)
        self.t = Functions(self.textBox)
        self.t.pack(fill='both', expand=1)
        self.textBox.config(background='black', foreground='green')
        self.t.config(background='black', foreground='green')
Esempio n. 13
0
 def __init__(self):
     super().__init__()
     self.setWindowTitle("Harmonisation")
     self.functions = Functions()
     self.functions.setFFromText(
         """def f(x, stats, alpha=1, beta=1, note_max=20):
                                     if stats['max'] == 0:
                                         return 0
                                     a = note_max/stats['max']**3*(alpha-2+beta)
                                     b = note_max/stats['max']**2*(3-beta-2*alpha)
                                     c = alpha*note_max/stats['max']
                                     d = 0
                                     return a*x**3+b*x**2+c*x+d""")
     #        self.setF("""def f(x, a=1, b=0):
     #                        return a*x+b""")
     self.data = Data(self.functions)
     self.createMenu()
     self.setCentralWidget(self.mainWidget())
     self.show()
Esempio n. 14
0
class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Harmonisation")
        self.functions = Functions()
        self.functions.setFFromText(
            """def f(x, stats, alpha=1, beta=1, note_max=20):
                                        if stats['max'] == 0:
                                            return 0
                                        a = note_max/stats['max']**3*(alpha-2+beta)
                                        b = note_max/stats['max']**2*(3-beta-2*alpha)
                                        c = alpha*note_max/stats['max']
                                        d = 0
                                        return a*x**3+b*x**2+c*x+d""")
        #        self.setF("""def f(x, a=1, b=0):
        #                        return a*x+b""")
        self.data = Data(self.functions)
        self.createMenu()
        self.setCentralWidget(self.mainWidget())
        self.show()

    def createMenu(self):
        exitAction = QAction("&Quitter", self)
        exitAction.triggered.connect(self.close)
        menu = self.menuBar()
        fileMenu = menu.addMenu("&Fichier")
        fileMenu.addAction(exitAction)

    def mainWidget(self):
        mainSplitter = QSplitter()
        leftSplitter = QSplitter(Qt.Vertical)
        listContainer = ListContainer(self.functions)
        tableContainer = TableContainer(self.data)
        leftSplitter.addWidget(listContainer)
        leftSplitter.addWidget(tableContainer)
        rightSplitter = QSplitter(Qt.Vertical)
        parametersContainer = ParametersContainer(self.functions)
        statContainer = StatContainer(self.data)
        rightSplitter.addWidget(parametersContainer)
        rightSplitter.addWidget(statContainer)
        mainSplitter.addWidget(leftSplitter)
        mainSplitter.addWidget(rightSplitter)
        return mainSplitter
Esempio n. 15
0
    def __init__(self):
        super().__init__(
            command_prefix='!',
            description=
            "A simple yet powerful moderation bot. Written in discord.py",
            intents=intents)

        self.config = Config()
        self.db: AsyncIOMotorDatabase
        self.functions = Functions()
Esempio n. 16
0
 def __init__(self, symbol, function, apiKey):
     self.symbol = symbol
     self.apiKey = apiKey
     functionEnum = Functions()
     if function == 1:
         self.function = functionEnum.Daily
     elif function == 2:
         self.function = functionEnum.Intraday
     else:
         self.function = functionEnum.DailyAdjusted
Esempio n. 17
0
    def create_groups_keys(self):
        modifier = [GROUPS_KEY]
        swap_modifier = [GROUPS_KEY, SWAP_GROUP_KEY]
        screen_modifier = [MOVEMENT_KEY]

        move_next = Key(modifier, NEXT_GROUP, lazy.screen.next_group())
        move_prev = Key(modifier, PREV_GROUP, lazy.screen.prev_group())

        swap_next = Key(swap_modifier, NEXT_GROUP,
                        Functions.window_to_next_group())
        swap_prev = Key(swap_modifier, PREV_GROUP,
                        Functions.window_to_prev_group())

        move_next_screen = Key(screen_modifier, NEXT_GROUP, lazy.next_screen())
        move_prev_screen = Key(screen_modifier, PREV_GROUP, lazy.next_screen())

        self.keys += [
            move_next, move_prev, swap_next, swap_prev, move_next_screen,
            move_prev_screen
        ]
Esempio n. 18
0
 def __init__(self, dimensions): # first element = input-dim, the following = layer-dims
     self.num_layers = len(dimensions) - 1   # -1 : subtract input-dim
     self.layers = []
     # and now the specified layers
     for i in range(self.num_layers):
         num_in = dimensions[i]
         num_out = dimensions[i+1]
         self.layers.append(Layer(num_in, num_out))
     # activation functions
     self.activation_str = None
     self.functions = Functions()
     return
Esempio n. 19
0
def marketMenu():
    os.system("cls")
    try:
        option = int(
            input(
                "Digite para selecionar:\n\n1 - Verificar informações do mercado\n2 - Editar informações do mercado\n\nQualquer outro numero para voltar ao menu principal o programa: "
            ))
        if option == 1:
            os.system("cls")
            Functions.getMarketInfo()
            input("\nAperte enter para voltar a tela anterior")
            marketMenu()
        if option == 2:
            os.system("cls")
            Functions.getMarketInfo()
            Functions.editMarketInfo()
            input("\nAperte enter para voltar a tela anterior")
            marketMenu()
        if option not in [1, 2]:
            mainMenu()
    except:
        os.system("cls")
        print("\nPor favor digite uma opcao valida\n")
        time.sleep(2)
        marketMenu()
Esempio n. 20
0
def salesMenu():
    os.system("cls")
    try:
        option = int(
            input(
                "Digite para selecionar:\n\n1 - Registrar nova venda\n2 - Para ver uma venda especifica\n3 - Para ver a lista de vendas\n\nQualquer outro numero para voltar ao menu principal o programa: "
            ))
        if option == 1:
            os.system("cls")
            Functions.registerSale()
            input("\nAperte enter para voltar a tela anterior")
            salesMenu()
        if option == 2:
            os.system("cls")
            Functions.showSale()
            input("\nAperte enter para voltar a tela anterior")
            salesMenu()
        if option == 3:
            os.system("cls")
            Functions.showAllSales()
            input("\nAperte enter para voltar a tela anterior")
            salesMenu()
        if option not in [1, 2, 3]:
            mainMenu()
    except Exception as e:
        print(e)
        os.system("cls")
        print("\nPor favor digite uma opcao valida\n")
        time.sleep(2)
        salesMenu()
Esempio n. 21
0
def main():
    xdim = int(input('Enter the x dimension: \n'))
    ydim = int(input('Enter the y dimension: \n'))
    num_bomb = int(input('Enter the number of bombs: \n'))
    gameboard = Board(xdim, ydim, num_bomb)
    gameboard.make_board()
    Functions.print_board(gameboard)
    first_x, first_y = xdim + 1, ydim + 1

    while first_x > (xdim - 1):
        first_x = int(input('Enter x location: \n'))
        if first_x > (xdim - 1):
            print('Please enter a value less than ' + xdim)
    while first_y > (ydim - 1):
        first_y = int(input('Enter y location\n'))
        if first_y > (ydim - 1):
            print('Please enter a value less than ' + ydim)

    if not Functions.reveal_space(gameboard, int(first_x), int(first_y)):
        print('Tough luck! You hit a bomb, restarting...', end='')
        main()

    while Functions.move(gameboard):
        if Functions.check_won(gameboard):
            print('You Won! ', end='')
            restart = input('You hit a bomb! Restart?\n[Y] Yes    [N] No\n')
            if restart.capitalize() == 'Y':
                main()
                break
            else:
                break
        if gameboard.is_lost:
            restart = input('You hit a bomb! Restart?\n[Y] Yes    [N] No\n')
            if restart.capitalize() == 'Y':
                main()
            else:
                break

    print('Thanks for playing!')
Esempio n. 22
0
class Test_LoginPage():
    def setup(self):
        self.links = Links()
        self.locators = Locator()
        self.functions = Functions(self.driver)
        self.login_page = LoginPage(self.driver)

        self.driver.get(self.links.login)

    @pytest.mark.smoke
    @pytest.mark.lol
    @pytest.mark.sanity
    @allure.title("Correct login")
    @allure.severity("Critical")
    def test_login(self):

        with allure.step("Login in account"):
            self.login_page.login_in_account()
            self.functions.getScreenshot("Login")

        with allure.step("Account page title checking"):
            self.functions.TitleCheck(Locator.ACCOUNT_INFO)
Esempio n. 23
0
    def learn(self, m_x, m_y, learning_rate, max_loops=1000):
        loop_nr = 0
        while True:
            error = 0.0
            for ex in range(len(m_x)):                  # for each example - index: ex
                # Just copy the input into INPUT of layer 0
                self.layers[0].input = m_x[ex]

                # Now propagate a[0] forward and store the interim results a[l] for the layers l
                for l in range(self.num_layers):
                    self.layers[l].sum = np.dot(self.layers[l].weights, self.layers[l].input)
                    self.layers[l].output = self.activation(self.layers[l].sum)
                    if (l < self.num_layers - 1):
                        self.layers[l + 1].input = self.layers[l].output
                        # self.layers[l + 1].input = np.copy(self.layers[l].output)

                # Compute the error at the output layer
                out_layer = self.layers[self.num_layers - 1]  # output layer
                # m_y is not an mdarray! ToDo!
                out_layer.delta = self.deriv_act(out_layer.sum) * (m_y[ex] - out_layer.output) # ex = example index

                # Compute the other deltas, backwards running through the layers
                for l in reversed(range(self.num_layers - 1)):
                    layer_m = self.layers[l]
                    layer_m_plus_1 = self.layers[l+1]
                    delta_m = self.deriv_act(layer_m.sum) * \
                              np.dot(layer_m_plus_1.weights.T, layer_m_plus_1.delta)
                    layer_m.delta = delta_m

                # And finally adjust weights.
                # This can be done in forward order because all data are available here.
                for l in range(self.num_layers):
                    layer = self.layers[l]
                    for i in range(layer.num_out):
                        delta_w = learning_rate * layer.delta[i] * layer.input
                        row = layer.weights[i] + delta_w
                        layer.weights[i] = row
                        # layer.weights[j] = layer.weights[j] + delta_w

                # Calculate a more or less reasonable error metric
                error += Functions.squared_error(m_y[ex], self.layers[self.num_layers - 1].output)

            # Calculate a more or less reasonable error metric
            error /= len(m_x)
            loop_nr += 1

            if error < 1.0E-9 or loop_nr >= max_loops * len(m_x):
                print("learning loops: ", loop_nr / len(m_x))
                break  # while

        return
Esempio n. 24
0
    def identify_func(self, function):
        l.debug("function at %#x", function.addr)
        if function.is_syscall:
            return None

        func_info = self.get_func_info(function)
        if func_info is None:
            l.debug("func_info is none")
            return None

        l.debug("num args %d", len(func_info.stack_args))

        try:
            calls_other_funcs = len(
                self._cfg.functions.callgraph.successors(function.addr)) > 0
        except NetworkXError:
            calls_other_funcs = False

        for name, f in Functions.iteritems():
            # check if we should be finding it
            if self.only_find is not None and name not in self.only_find:
                continue
            if name in Identifier._special_case_funcs:
                continue

            # generate an object of the class
            f = f()
            # test it
            if f.num_args() != len(func_info.stack_args) or f.var_args(
            ) != func_info.var_args:
                continue
            if calls_other_funcs and not f.can_call_other_funcs():
                continue

            l.debug("testing: %s", name)
            if not self.check_tests(function, f):
                continue
            # match!
            return f

        if len(func_info.stack_args) == 2 and func_info.var_args and len(
                function.graph.nodes()) < 5:
            match = Functions["fdprintf"]()
            l.warning(
                "%#x assuming fd printf for var_args func with 2 args although we don't really know",
                function.addr)
            return match

        return None
Esempio n. 25
0
    def about_author(self):
        """Tworzy stronę z informacjami o autorze"""

        author = True
        while author:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        pygame.quit()
                        quit()

            self.screen.fill(self.grey)

            Functions.message(self,
                              "Author:",
                              self.white,
                              y_displace=-100,
                              size="small")
            Functions.message(self,
                              "Rakus Karolina",
                              self.white,
                              y_displace=0,
                              size="big")
            self.button("back",
                        330,
                        500,
                        140,
                        60,
                        self.light_grey,
                        self.dark_grey,
                        action="back to menu")

            pygame.display.update()
Esempio n. 26
0
 def __init__(self, num_in, num_out):
     self.num_in = num_in
     self.num_out = num_out
     self.num_weights = num_in * num_out
     # vectors and weight matrix needed for learning and running
     self.input = None
     self.output = None
     self.weights = None
     self.sum = None
     self.delta = None
     self.delta_w = None
     # vectors for interim values
     self.derived = None
     self.diff = None
     self.tmp_col = None
     #
     self.functions = Functions()
Esempio n. 27
0
    def __init__(self, driver):
        self.driver = driver
        self.driver.implicitly_wait(30)  # Обьявляем ожидания для страниц
        # self.driver.set_window_size(1920, 1080) # Указываем размер окна
        self.driver.set_window_size(1920, 1080)  # Указываем размер окна
        self.wait = WebDriverWait(self.driver,
                                  30)  # Указываем ожидания для элементов
        self.functions = Functions(
            self.driver
        )  # Создаем обьект для того чтобы использовать функции в pages

        #######################################################
        # Тут обьявляем все константы, локаторы, ссылки, данные
        #######################################################
        self.links = Links()
        self.Locator = Locator()
        self.data = Data()
Esempio n. 28
0
    def from_conf(conf,
                  init_fields=True,
                  init_equations=True,
                  init_solvers=True):
        if conf.options.get('absolute_mesh_path', False):
            conf_dir = None
        else:
            conf_dir = op.dirname(conf.funmod.__file__)

        functions = Functions.from_conf(conf.functions)

        mesh = Mesh.from_file(conf.filename_mesh, prefix_dir=conf_dir)

        trans_mtx = conf.options.get('mesh_coors_transform', None)

        if trans_mtx is not None:
            mesh.transform_coors(trans_mtx)

        domain = Domain(mesh.name, mesh)
        if conf.options.get('ulf', False):
            domain.mesh.coors_act = domain.mesh.coors.copy()

        obj = ProblemDefinition('problem_from_conf',
                                conf=conf,
                                functions=functions,
                                domain=domain,
                                auto_conf=False,
                                auto_solvers=False)

        obj.set_regions(conf.regions, obj.functions)

        obj.clear_equations()

        if init_fields:
            obj.set_fields(conf.fields)

            if init_equations:
                obj.set_equations(conf.equations, user={'ts': obj.ts})

        if init_solvers:
            obj.set_solvers(conf.solvers, conf.options)

        return obj
Esempio n. 29
0
 def getAllInformation(self, openid):
     function = Functions.Function(self.__username, self.__url, self.__sessionid, self.__deskey, self.__nowtime)
     xn = "0000"
     xq = "0"
     informationlist = function.InquiryGrades(xn, xq, self.__username, xn + "-" + xq)
     exam_infor = function.examination()
     classInfor = function.myclass()
     for i in range(len(classInfor)):
         information = classInfor[i]
         classes = Classes(openid=openid, class_name=information)
         classes.save()
     for i in range(len(informationlist)):
         information = informationlist[i]
         grade = Grade(openid=openid, class_name=information[0], class_credit=information[1], class_grade=information[3])
         grade.save()
     for i in range(len(exam_infor)):
         information = exam_infor[i]
         exam = Exam(openid=openid, class_name=information[0], class_credit=information[1], class_type=information[2], class_way=information[3], class_time=information[4], class_location=information[5], class_seat=information[6])
         exam.save()
Esempio n. 30
0
    def __init__(self, data, myfuncs):
        npoints = len(data.time)

        self.model = np.zeros(npoints)
        self.model_sys = np.zeros(npoints)
        self.model_astro = np.zeros(npoints)
        self.norm_flux = np.zeros(npoints)
        self.phase = np.zeros(npoints)
        self.resid = np.zeros(npoints)
        self.norm_resid = np.zeros(npoints)
        self.chi2 = 0.
        self.chi2red = 0.
        self.rms = 0.
        self.rms_predicted = 1.0e6*np.sqrt(np.mean((data.err/data.flux)**2))
        #self.rms_predicted = 1.0e6*np.sqrt(np.mean(np.sqrt((1./data.flux))**2))                #wong because we binned over several pixels
        self.ln_like = 0.
        self.bic = 0.
        self.params = []
        self.myfuncs = Functions(data, myfuncs)
Esempio n. 31
0
    def __init__(self, data, myfuncs):
        npoints = len(data.time)

        self.model = np.zeros(npoints)
        self.model_sys = np.zeros(npoints)
        self.model_astro = np.zeros(npoints)
        self.model_gp = np.zeros(npoints)
        self.norm_flux = np.zeros(npoints)
        self.phase = np.zeros(npoints)
        self.resid = np.zeros(npoints)
        self.norm_resid = np.zeros(npoints)
        self.chi2 = 0.
        self.chi2red = 0.
        self.rms = 0.
        self.rms_predicted = 1.0e6*np.sqrt(np.mean((data.err/data.flux)**2))
        self.ln_like = 0.
        self.bic = 0.
        self.params = []
        self.myfuncs = Functions(data, myfuncs)
Esempio n. 32
0
    def setUp(self):
        self.f = Functions(Request())
        self.graph = []

        async def add_connection(x, y):
            if (x, y) not in self.graph:
                self.graph.append((x, y))
                self.graph.append((y, x))

        async def neighbours(node):
            neighbourhood = list()
            for g in self.graph:
                if (g[0] == node) or (g[1] == node):
                    if g[0] != node:
                        neighbourhood.append(g[0])
                    else:
                        neighbourhood.append(g[1])

        self.f.request.add_connection = Mock(side_effect=add_connection)
        self.f.request.neighbours = Mock(side_effect=neighbours)
Esempio n. 33
0
    def from_conf(conf, init_fields=True, init_equations=True,
                  init_solvers=True):
        if conf.options.get('absolute_mesh_path', False):
            conf_dir = None
        else:
            conf_dir = op.dirname(conf.funmod.__file__)

        functions = Functions.from_conf(conf.functions)

        if conf.get('filename_mesh') is not None:
            from sfepy.discrete.fem.domain import FEDomain

            mesh = Mesh.from_file(conf.filename_mesh, prefix_dir=conf_dir)
            domain = FEDomain(mesh.name, mesh)
            if conf.options.get('ulf', False):
                domain.mesh.coors_act = domain.mesh.coors.copy()

        elif conf.get('filename_domain') is not None:
            from sfepy.discrete.iga.domain import IGDomain
            domain = IGDomain.from_file(conf.filename_domain)

        else:
            raise ValueError('missing filename_mesh or filename_domain!')

        obj = Problem('problem_from_conf', conf=conf, functions=functions,
                      domain=domain, auto_conf=False, auto_solvers=False)

        obj.set_regions(conf.regions, obj.functions)

        obj.clear_equations()

        if init_fields:
            obj.set_fields(conf.fields)

            if init_equations:
                obj.set_equations(conf.equations, user={'ts' : obj.ts})

        if init_solvers:
            obj.set_solvers(conf.solvers, conf.options)

        return obj
Esempio n. 34
0
    def from_conf(conf, init_fields=True, init_equations=True,
                  init_solvers=True):
        if conf.options.get_default_attr('absolute_mesh_path', False):
            conf_dir = None
        else:
            conf_dir = op.dirname(conf.funmod.__file__)

        functions = Functions.from_conf(conf.functions)

        mesh = Mesh.from_file(conf.filename_mesh, prefix_dir=conf_dir)

        trans_mtx = conf.options.get_default_attr('mesh_coors_transform', None)

        if trans_mtx is not None:
            mesh.transform_coors(trans_mtx)

        domain = Domain(mesh.name, mesh)
        if get_default_attr(conf.options, 'ulf', False):
            domain.mesh.coors_act = domain.mesh.coors.copy()

        obj = ProblemDefinition('problem_from_conf', conf=conf,
                                functions=functions, domain=domain,
                                auto_conf=False, auto_solvers=False)

        obj.set_regions(conf.regions, obj.functions)

        obj.clear_equations()

        if init_fields:
            obj.set_fields( conf.fields )

            if init_equations:
                obj.set_equations(conf.equations, user={'ts' : obj.ts})

        if init_solvers:
            obj.set_solvers( conf.solvers, conf.options )

        return obj
Esempio n. 35
0
class Logic:
    PITCH = -933
    ROLL = -6
    Z = 1864
    
    MIN_X = -700
    MAX_X = 900
    MIN_Y = -3100
    MAX_Y = -910
    
    INI_X = 97
    INI_Y = -1959
    
    END_X = 97
    END_Y = -3683
    
    INTERVAL = 100
    
    def __init__(self, serial_port):
        self.scorbot = Functions(serial_port)
        self.pos_ini = 'ini'
        self.pos_end = 'end'
        self.pos_user = '******'
        self.current_x = 97
        self.current_y = -1959
        
    
    def close_con(self):
        self.scorbot.close_con()
        
    
    def fast(self):
        self.scorbot.speed(50)
        
    def medium(self):
        self.scorbot.speed(20)
        
        
    def slow(self):
        self.scorbot.speed(7)
        
    
    def initialize(self):
        self.scorbot.open_con()
        self.scorbot.home()
        
        self.scorbot.def_pos(self.pos_ini, self.pos_end, self.pos_user)
        
        self.scorbot.teach_pos(self.pos_ini, Logic.INI_X, Logic.INI_Y, Logic.Z, Logic.PITCH, Logic.ROLL)
        self.scorbot.teach_pos(self.pos_end, Logic.END_X, Logic.END_Y, Logic.Z, Logic.PITCH, Logic.ROLL)
        
        self.fast()
        self.scorbot.move(self.pos_ini)
        
        self.scorbot.open()
        self.slow()
        self.scorbot.setp(self.pos_user, self.pos_ini)
        
    
    def calculate_z(self, y):
        '''
        pos     y        z
        fin     -3683    224
        maxy    -913     845
        
        (-3683, 224) - (-913, 845) = [-2770, -621] = V
        N = [-621, 2770]
        -621(y + 913) + 2770 (z - 845) = 0
        -621y - 566973 + 2770z - 2340650 = 0
        -621y + 2770z - 2907623 = 0
        '''
        return ((2907623 + (621 * y)) / 2770) - 50
        
    
    def update_x_y(self, x = None, y = None):
        if x != None:
            self.current_x = x
        if y != None:
            self.current_y = y
        
    
    def more_x(self):
        if self.current_x + Logic.INTERVAL <= Logic.MAX_X:
            self.update_x_y(self.current_x + Logic.INTERVAL, None)
            self.scorbot.set_x(self.pos_user, self.current_x)
            self.scorbot.move(self.pos_user)
        else:
            print 'more_x maximo: ' + str(self.current_x)
        
    
    def less_x(self):
        if self.current_x - Logic.INTERVAL >= Logic.MIN_X:
            self.update_x_y(self.current_x - Logic.INTERVAL, None)
            self.scorbot.set_x(self.pos_user, self.current_x)
            self.scorbot.move(self.pos_user)
        else:
            print 'less_x minimo: ' + str(self.current_x)
        
    
    def more_y(self):
        if self.current_y + Logic.INTERVAL <= Logic.MAX_Y:
            self.update_x_y(None, self.current_y + Logic.INTERVAL)
            self.scorbot.set_y(self.pos_user, self.current_y)
            self.scorbot.move(self.pos_user)
        else:
            print 'more_y maximo: ' + str(self.current_y)
        
    
    def less_y(self):
        if self.current_y - Logic.INTERVAL >= Logic.MIN_Y:
            self.update_x_y(None, self.current_y - Logic.INTERVAL)
            self.scorbot.set_y(self.pos_user, self.current_y)
            self.scorbot.move(self.pos_user)
        else:
            print 'less_y minimo: ' + str(self.current_y)
        
    
    def home(self):
        self.medium()
        self.update_x_y(Logic.INI_X, Logic.INI_Y)
        self.scorbot.move(self.pos_ini)
        self.scorbot.setp(self.pos_user, self.pos_ini)
        self.slow()
        
    
    def catch(self):
        z = self.calculate_z(self.current_y)
        self.scorbot.set_z(self.pos_user, z)
        
        self.fast()
        self.scorbot.move(self.pos_user)
        
        time.sleep(1)
        self.scorbot.close()
        self.scorbot.set_z(self.pos_user, Logic.Z)
        self.scorbot.move(self.pos_user)
        
        self.update_x_y(Logic.END_X, Logic.END_Y)
        self.scorbot.move(self.pos_end)
        
        z = self.calculate_z(self.current_y)
        self.scorbot.setp(self.pos_user, self.pos_end)
        self.scorbot.set_z(self.pos_user, z)
        self.scorbot.move(self.pos_user)
        
        time.sleep(4)
        self.scorbot.open()
        self.scorbot.set_z(self.pos_user, Logic.Z)
        self.scorbot.move(self.pos_user)
        self.scorbot.move(self.pos_ini)
        self.update_x_y(Logic.INI_X, Logic.INI_Y)
        self.scorbot.setp(self.pos_user, self.pos_ini)
        
        self.slow()
Esempio n. 36
0
parser.add_argument("--lib_dir", type=str, help="Specify the library directory", default="library")
parser.add_argument("--stage_dir", type=str, help="Specify the staging directory", default="stage")
parser.add_argument("--verbose", help="Set to verbose mode", action="store_true")

group = parser.add_mutually_exclusive_group()
group.add_argument("--init", action="store_true", help="Init and store a library")
group.add_argument("-l", "--list_collections", action="store_true", help="List all collections")
group.add_argument("-c", "--display_collection", type=int, default=-1, help="Display the collection with the specified id")
group.add_argument("-i", "--display_item", type=int, default=-1, help="Delete the item with the specified id")
group.add_argument("--del_coll", type=int, default=-1, help="Delete the collection with the specified id")
group.add_argument("--del_item", type=int, default=-1, help="Delete the item with the specified id")
group.add_argument("-p", "--process", action="store_true", help="Process the staging directory")

args = parser.parse_args()

functions = Functions(args.lib_db, args.lib_dir, args.stage_dir, args.verbose)

#todo: Check existence of stage, library, and db
makedirs(args.lib_dir, exist_ok=True)
makedirs(args.stage_dir, exist_ok=True)

functions.init_db()

if args.init:
    print("Init with the following settings (Structure of 'library' will be inited as collection)?")
    print("Database location: " + args.lib_db)
    print("Library location: " + args.lib_dir)
    print("WARNING:  THIS WILL MOVE ALL FILES IN 2ND LEVEL DIRECTORIES AND LOWER")
    print("          INTO THE FIRST-LEVEL DIRECTORY.")
    choice = input("Y/N : ")
    if choice == "Y" or choice == "y":
Esempio n. 37
0
	def get_value(self, values):
		function = Functions(self.fg)
		return function.calculate(self.name, values)
debug = False
writeFile = False

#retrieving data from mongodb 
client = MongoClient() #get mongodb client
db= client.UpcomingAnime #get database named test_database
collection_Anime= db.Anime #get table named <insert name>  inside db named <insert name>
#create upcoming anime dictionary 
UpcomingData={}
for items in collection_Anime.find():
    del items["_id"]
    UpcomingData[items["a_name"]]=items
   
print "Content-Type: text/html\n"
if not debug:
    UserData= Functions.read_line( data["UserAnime"].value)
 
if debug and writeFile:
    U_f = open('./UserAnimei', 'w')
    U_f.write(data["UserAnime"].value)
    U_f.close()
elif debug and not writeFile:
    U_f=open('./UserAnimei', 'r')
    line=U_f.read()
    UserData= Functions.read_line(line)

return_type=[] #a list that will store all relevant animes be used to send back
if len(UserData) >0:
    train= Functions.classify(UserData)
    # array of tuples holding a (dict of genres genre:true, relevant/nonrelevant)
    if debug: 
Esempio n. 39
0
# -*- coding: utf-8 -*-
"""
Created on 26/04/2013

@author: José M. Camacho - camachososa@josemazocom
@author: Gabriel E. Muñoz - [email protected]
"""

"""
Module to place the SCORBOT in the home position
"""


from functions import Functions


f = Functions("/dev/cu.PL2303-00002006")
f.open_con()
f.home()
f.close_con()