dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def writeOut(repeat=False): if not Entity['Connected']['Connected']: sys.stdout.write(json.dumps({ "text": "Not connected", "alt": "not-connected", "tooltip": "Not connected" }) + "\n") sys.stdout.flush() return True try: if int(Entity[...
This callback function handles the removal of a Bluetooth service interface. It updates the connection status to disconnected, triggers output writing, checks for AMS service absence (quitting the loop and restarting if absent), and initiates a client if the specific device's interface is removed.
def interfaces_removed_cb(object_path, interfaces): print('remove') global mainloop global Entity Entity['Connected']['Connected'] = False writeOut() if not ams_service: print('No AMS Service found') mainloop.quit() global buss global busself dbus.service...
def _on_child_added(self, child): print(f"⚡ child_added: {child}") self._instrument(child.pid) def _on_child_removed(self, child): print(f"⚡ child_removed: {child}") def _on_output(self, pid, fd, data): print(f"⚡ output: pid={pid}, fd={fd}, data={repr(data)}")
This code initializes a Frida device monitor to asynchronously handle device events (child process additions/removals and output data) using a reactor thread. It sets up event listeners for "child-added", "child-removed", and "output" events, scheduling corresponding callback methods to process these events. The reacto...
def __init__(self): self._stop_requested = threading.Event() self._reactor = Reactor( run_until_return=lambda reactor: self._stop_requested.wait() ) self._device = frida.get_local_device() self._sessions = set() self._device.on( "child-added", ...
def define_forcefield_library(present_beads, prefix): forcefieldlibrary = ForceFieldLibrary( present_beads=present_beads, vdw_bond_cutoff=2, prefix=prefix, ) if "2p3" in prefix: bonds = ( ("a1", "c1", "Ba", "Ag", (1.5,), (1e5,)), ("a1", "b1", "Ba", "P...
The code generates and optimizes coarse-grained (CG) cage structures using predefined bead types and force fields. It creates directories for outputs, defines building blocks, iterates over topology-force field combinations, constructs and optimizes cages, saves optimized molecules, and performs analysis. The main task...
def main(): first_line = f"Usage: {__file__}.py path " if not len(sys.argv) == 2: logging.info(f"{first_line}") sys.exit() else: path = sys.argv[1] prefix = "cg_model_test" struct_output = pathlib.Path().absolute() / path / "structures" check_directory(struct_output) ...
def get_theme(pkg): settings = get_settings(pkg) if pkg is SUBLIME_LINTER: items = settings.get('user', '') if items != '': return items.get('gutter_theme', '') if pkg in (PLAIN_TASKS, PLAIN_NOTES): return settings.get('color_scheme', '') def revert_theme(pkg, path): ...
This code handles user selections by executing specific commands or switching themes in a Sublime Text plugin. If the index is 0 or 1, it runs 'boxy_plain_notes' or 'boxy_plain_tasks' commands. For index 2, it checks the current theme for Sublime Linter, reverting to a default theme if the current one is 'boxy', or act...
def on_done(self, index): if index is NO_SELECTION: return if index is 0: self.window.run_command('boxy_plain_notes') if index is 1: self.window.run_command('boxy_plain_tasks') if index is 2: current = get_theme(SUBLIME_LINTER) ...
def revert_theme(pkg, path): if path is '': get_settings(pkg).erase('color_scheme') else: set_theme(pkg, path) return save_settings(pkg) def activate_theme(pkg, path): set_theme(pkg, path) return save_settings(pkg) def _quick_list_to_theme(self, index): return ('Packages/Box...
The function `on_done` handles theme activation based on user selection. If `index` is `NO_SELECTION`, it reverts the theme to the initial state using `revert_theme`. Otherwise, it activates a theme derived from the selected index via `activate_theme` and `quick_list_to_theme`, updating the interface accordingly.
def on_done(self, index): if index is NO_SELECTION: revert_theme(PLAIN_TASKS, self.initial_theme) return activate_theme(PLAIN_TASKS, self._quick_list_to_theme(index))
def revert_theme(pkg, path): if path is '': get_settings(pkg).erase('color_scheme') else: set_theme(pkg, path) return save_settings(pkg) def activate_theme(pkg, path): set_theme(pkg, path) return save_settings(pkg) def _quick_list_to_theme(self, index): return ('Packages/Box...
The code's main task is to handle the completion of a selection by checking if an index is unselected (NO_SELECTION). If so, it reverts the theme to the initial state. Otherwise, it activates a new theme based on the selected index using the _quick_list_to_theme method, ensuring the UI theme updates accordingly.
def on_done(self, index): if index is NO_SELECTION: revert_theme(PLAIN_NOTES, self.initial_theme) return activate_theme(PLAIN_NOTES, self._quick_list_to_theme(index))
def plot_from_filename( full_file_path : str, adjacency_matrix : torch_sparse.SparseTensor, ax : plt.Axes = None, set_legend : bool = False, legend_kwargs : dict[str,object] = None, ) -> None: """ Takes a filename in form <path_to_file>/{src}_{tar}_{gamma}_{epsilo...
This function generates and displays subplots analyzing parameters from multiple files in a specified folder, each corresponding to different gamma and epsilon values. It sorts files by numerical suffixes, plots data using an adjacency matrix, labels subplots with letters, adjusts layout, and saves the figure if a path...
def plot_all_parameters_for_src_tar(path_to_folder : str, adjacency_matrix : torch_sparse.SparseTensor, src : int, tar : int, save : str = "", **kwargs) -> None: files = glob.glob(os.path.join(path_to_folder,f"{src}_{tar}_*.th")) files = sorted(files, key= lambda s: [float(_s.replace(',', '.')) for _s in os.pat...
def crop_center( img: torch.Tensor, frac: float = 0.5 ) -> torch.Tensor: r""" Crop center square from image. """ h_offset = round(img.shape[0] * (frac / 2)) w_offset = round(img.shape[1] * (frac / 2)) return img[h_offset:-h_offset, w_offset:-w_offset] def get_rays( height: int, width: int, focal_l...
The code trains a Neural Radiance Field (NeRF) model by iteratively rendering RGB images from random target images, computing mean squared error loss between predicted and actual RGB values, and optimizing model parameters via backpropagation. It periodically evaluates the model on a test image, tracks training/validat...
def train(): r""" Launch training session for NeRF. """ train_psnrs = [] val_psnrs = [] iternums = [] for i in trange(n_iters): model.train() # Randomly pick an image as the target. target_img_idx = np.random.randint(images.shape[0]) target_img = images[target_img_idx].to(device) if...
def load_labels(self) -> torch.Tensor: """ Loads the labels for the dataset from a saved file, or creates them if they don't exist. Returns: torch.Tensor: A tensor containing the labels. """ print('Loading labels...', end=' ') path = os.path.join(self.root, 'la...
The main task of the code is to load and process the Twibot20 dataset's features, including embedding textual data, preprocessing numeric and categorical properties, constructing a graph structure, and generating index ranges for training, validation, and testing. It returns tensors for descriptions, tweets, properties...
def dataloader(self): """ Loads and processes various features of the Twibot20 dataset, preparing them for model training and evaluation. This includes embedding textual data, processing numeric and categorical properties, building a graph structure, and preparing index r...
def goForward(distance_m): stop() counter = 0 setDirection("forward") startPosition = abs(positionLinear(leftWheelPositionSensor, rightWheelPositionSensor)) while robot.step(timestep) != -1: if(abs(positionLinear(leftWheelPositionSensor, rightWheelPositionSensor)) - startPosition < distance_...
This function executes a sequence of directional commands to control a robot's movement, adjusting its direction (rotate) and position (goForward) based on state transitions between "start", "gore", "dole", "levo", and "desno". It processes each step in the input list, applying specific motions depending on the current...
def execDirections1(directions1): i = 0 prevState = directions1[0] curState = directions1[0] while(directions1[i] != "end"): if curState == "start": pass elif curState == "gore": if prevState == "start": goForward(x_step) ...
def goForward(distance_m): stop() counter = 0 setDirection("forward") startPosition = abs(positionLinear(leftWheelPositionSensor, rightWheelPositionSensor)) while robot.step(timestep) != -1: if(abs(positionLinear(leftWheelPositionSensor, rightWheelPositionSensor)) - startPosition < distance_...
The main task of the code is to execute a sequence of movement directions for a robot, adjusting its rotation and forward motion based on transitions between states ("start", "gore", "dole", "levo", "desno"). It uses conditional logic to determine rotation angles and step distances (x_step/y_step) depending on the prev...
def execDirections2(directions2): i = 0 prevState = directions1[-2] curState = directions1[-2] while(directions2[i] != "end"): if curState == "start": pass elif curState == "gore": #proveri sva prev stanja if prevState == "start": ...
def CTR_update(self, data): """ CTR_update() may be called multiple times if need to chunk large datasets data is a bytestring of any reasonable length """ self.data = self.data + data ciphertext = [] while len(self.data) > 8: ci...
The CTR_final method processes residual data in self.data using CTR mode encryption, appending encrypted data and XOR-combining it with a cipherstream derived from the counter block. It ensures all remaining bytes are encrypted, resets the data buffer, and returns the final ciphertext.
def CTR_final(self, data=b''): """ CTR_final() must be called last to ensure the processing of any residual bytes in self.data data is an optional bytestring """ ciphertext = [] if data: ciphertext.append(self.CTR_update(data)) ci...
def getNewBoard(): board = [] for x in range(BOARDWIDTH): board.append([EMPTY] * BOARDHEIGHT) return board def getHumanMove(board): draggingToken = False tokenx, tokeny = None, None while True: for event in pygame.event.get(): # event handling loop if event.type == QU...
The main task of the code is to run a two-player game where a human (RED) plays against a computer (BLACK) on a board, alternating turns, checking for wins or ties, and displaying the winner or tie image until the player exits by clicking the mouse or pressing ESC.
def runGame(): if random.randint(0, 1) == 0: turn = BLACK # black goes first else: turn = RED # red goes first # Set up a blank board data structure. mainBoard = getNewBoard() while True: # main game loop if turn == RED: # RED player's turn. getHu...
def find_interest_points(image, max_points = 200, scale = 1.0, mask = None): # check that image is grayscale assert image.ndim == 2, 'image should be grayscale' ########################################################################## # TODO: YOUR CODE HERE # 1. Set the variables harris_constant = 0...
The code detects objects in a test image by matching each template's foreground features with the test image's features using interest points and descriptors. It applies Hough voting to estimate template positions, averages coordinates across templates, and returns a bounding box (x_min, y_min, x_max, y_max) enclosing ...
def object_detection(template_images, template_masks, test_img): ########################################################################## # TODO: YOUR CODE HERE x_min = 0 y_min = 0 x_max = 0 y_max = 0 for i in range(len(template_images)): template_count = i # 1. Leave only the foregr...
def load_cropped (): global ref_rects ref_rects = road['cropped_rects'] print('Loaded ref_rects from settings.json!') def process_frame(frame_number, frame, bg_subtractor, car_counter): processed = frame.copy() gray = cv2.cvtColor(processed, cv2.COLOR_BGR2GRAY) # remove specified cropped regions cropped, pro...
The code implements real-time vehicle counting using OpenCV's KNN background subtraction. It processes video frames to detect moving objects, displays original and processed frames, and allows user interaction for cropping regions and saving data. The script maintains frame rate stability, uses a VehicleCounter for tra...
def main (): # I think KNN works better than MOG2, specifically with trucks/large vehicles # TODO: Block out snowbank where shadows are strongly reflected! bg_subtractor = cv2.createBackgroundSubtractorKNN(detectShadows=True) car_counter = None load_cropped() cap = cv2.VideoCapture(road['stream_url']) cap.set(...
def menu_list_item1(self): print("\n********* Menu List **********") FoodID=1 Food_Name="Tandoori Chicken" Quantity="4 pieces" Price=240.0 Discount=20.0 Stock=7000.0 admin_obj = Admin(FoodID,Food_Name,Quantity,Price,Discount,Stock) Admin_operations...
This function authenticates an admin user with 3 login attempts using predefined credentials. It validates entered ID/password against stored values, displays an error and remaining attempts on failure, and invokes menu options upon successful login.
def admin_login(self): admin_id="Admin" admin_password="Pass@123" # Ask for Admin ID and password for login admin_login_count=1 while admin_login_count<=3: # Admin has been provided 3 attempts to log in, if his 3 attempts fail, after that it will stop. print("\n**...
def get_funcs(cls, base = True, inherited = True): funcs = [] classes = [] current_cls = cls while True: classes.append(current_cls) if base and is_base_class(current_cls.get_parent_name()): for func in get_base_funcs(current_cls): funcs.append( func ) ...
The code generates C# structure members and delegates for interop with native code, handling proxy/handler classes. It validates base class compatibility, creates base member fields, processes static functions, and generates platform-specific delegates. For proxy classes, it adds delegate storage and method wrappers. H...
def make_struct_members(cls): result = [] static_funcs = [] funcs = get_funcs(cls) delegate_visibility = "internal" if schema.is_proxy(cls): delegate_visibility = "private" for func in cls.get_static_funcs(): static_funcs.append( get_func_parts(func, 0) ) parentClassName ...
def get_funcs(cls, base = True, inherited = True): funcs = [] classes = [] current_cls = cls while True: classes.append(current_cls) if base and is_base_class(current_cls.get_parent_name()): for func in get_base_funcs(current_cls): funcs.append( func ) ...
This function generates C# method stubs for a proxy class, creating placeholder implementations for both static and instance methods of the input class. It processes function signatures, adjusts parameters by removing 'self' for instance methods, adds XML documentation comments, and inserts NotImplementedExceptions as ...
def make_proxy_impl_tmpl_body(cls): csname = schema.cpp2csname(cls.get_name()) iname = schema.get_iname(cls) funcs = get_funcs(cls, False, False) static_funcs = [] for func in cls.get_static_funcs(): static_funcs.append( get_func_parts(func, 0) ) result = [] for func in static_func...
def get_funcs(cls, base = True, inherited = True): funcs = [] classes = [] current_cls = cls while True: classes.append(current_cls) if base and is_base_class(current_cls.get_parent_name()): for func in get_base_funcs(current_cls): funcs.append( func ) ...
The main task of the code is to generate C# implementation templates for a class's handler methods, including stubs for static and instance functions with NotImplementedException placeholders, abstract method declarations, and XML documentation. It processes function signatures, adds validation checks, and structures c...
def make_handler_impl_tmpl_body(cls): csname = schema.cpp2csname(cls.get_name()) iname = schema.get_iname(cls) funcs = get_funcs(cls, False) static_funcs = [] for func in cls.get_static_funcs(): static_funcs.append( get_func_parts(func, 0) ) result = [] for func in static_funcs: ...
def make_proxy_g_body(cls): csname = schema.cpp2csname(cls.get_name()) iname = schema.get_iname(cls) isRefCountedImpl = cls.get_parent_capi_name() == "cef_base_ref_counted_t" isScopedImpl = cls.get_parent_capi_name() == "cef_base_scoped_t" isImpl = isRefCountedImpl or isScopedImpl isRefCounted ...
This function generates C# wrapper code for CEF (Chromium Embedded Framework) classes by creating partial, unsafe classes with appropriate modifiers and inheritance. It handles proxy classes for COM interop, abstract handlers, and includes necessary namespaces and comments. The output is structured as a C# file with a ...
def make_wrapper_g_file(cls): body = [] body.append('using System;') body.append('using System.Collections.Generic;') body.append('using System.Diagnostics;') body.append('using System.Runtime.InteropServices;') # body.append('using System.Diagnostics.CodeAnalysis;') body.append('using %s;'...
def append_xmldoc(result, lines): result.append('/// <summary>') for line in lines: if line != '/' and not (line is None): line = line.strip() if line != '': temp = line.strip() temp = temp.replace("<", "&lt;") temp = temp.replace("...
This function generates a C# template file for implementing proxy or handler classes based on schema definitions. It constructs using directives, adds XML comments, and conditionally creates sealed partial classes for proxies or abstract partial classes for handlers, populating their method bodies. The output is a form...
def make_impl_tmpl_file(cls): body = [] body.append('using System;') body.append('using System.Collections.Generic;') body.append('using System.Diagnostics;') body.append('using System.Runtime.InteropServices;') # body.append('using System.Diagnostics.CodeAnalysis;') body.append('using %s;'...
def make_struct_file(cls): body = [] body.append('using System;') body.append('using System.Diagnostics.CodeAnalysis;') body.append('using System.Runtime.InteropServices;') body.append('using System.Security;') body.append(''); body.append('[StructLayout(LayoutKind.Sequential, Pack = %s)]' ...
The code generates C# interop files from a C++ header using a schema, validating class roles, creating structs, wrappers, templates, and project configuration files. It writes files to specified paths, handles backups, and returns the count of files written.
def write_interop(header, filepath, backup, schema_name, cppheaderdir): writect = 0 project_props_filename = "CefGlue.g.props" project_props_compile_items = [] schema.load(schema_name, header) # validate: class role must be defined for all header classes for cls in header.get_classes(): ...
def get_loc_tri_arr(): # This function is to model human observer's search performance and scanpth in the preformed # experiment, so the deafult size of the input image is 666 by 666 and there are 84 potential # locations for the fixation. To extend the model to other search experimental setups, the # whole fun...
The code simulates visual search processes by running iterative trials for each background (BG) and target location, calculating average fixation counts to locate targets. It stores results (fixation numbers, locations, and statistics) in CSV files, generates plots with error bars for eccentricity-based performance, an...
def get_scanpath_simul(save_dir,iter_num,output_type): if output_type=="simul": ddash_params=pd.read_csv('files/'+output_type+"_ddash_params.csv") elif output_type=="human": ddash_params=pd.read_csv('files/'+output_type+"_ddash_params.csv") poten_locs=get_loc_tri_arr() print('potential t...
def ray_cast_player_enemy(self): if self.game.player.map_pos == self.map_pos: return True wall_distance_vertical, wall_distance_horizontal = 0, 0 player_distance_vertical, player_distance_horizontal = 0, 0 ox, oy = self.game.player.pos x_map, y_map = self.game.playe...
This code handles an entity's behavior in a game, checking if it's alive, performing raycasting to detect enemies, triggering attacks or movement based on proximity, animating actions like pain, walking, attacking, or idling, and playing a death animation if the entity is not alive. It manages game logic for interactio...
def run_logic(self): if self.alive: self.ray_cast_value = self.ray_cast_player_enemy() self.check_hit_in_enemy() if self.pain: self.animate_pain() elif self.ray_cast_value: self.player_search_trigger = True if self...
def initialize_images(self): self.imgRubik = PhotoImage(file="img/rubiks_logo.gif") self.imgArrowUp = PhotoImage(file="img/up_arrow.gif") self.imgArrowRight = PhotoImage(file="img/right_arrow.gif") self.imgArrowDown = PhotoImage(file="img/down_arrow.gif") self.imgArrowLeft = Phot...
This code initializes a GUI application for a Pocket Cube solver. It sets up the main window, creates frames for color selection, Rubik's cube visualization, solution display, and control buttons. The interface includes background configuration, image initialization, and layout management to organize the application's ...
def __init__(self, root): root.title("Pocket Cube Solver") root["bg"] = bg="#E2E2E2" self.initialize_images() self.reset_rubik() fColor = Frame(root, height=75, width=660, bg="#FFFFFF") fColor.pack_propagate(0) fColor.pack() self.create_color_picker(fCol...
def reset_rubik(self): for f in self.faces.keys(): for i in range(4): self.faces[f][i] = self.faces_color[f] return None def update_rubik(self): for btn in self.faceButtons: self.update_cell(btn) self.lblInfo["text"] = "" def hide_sol_controllers(s...
This function resets the Rubik's cube by calling reset_rubik() and update_rubik(), clears solution steps and history, hides solution controls, resets the info label, and restores the Rubik's cube image on the button when the reset action is triggered.
def btnReset_clicked(self): self.reset_rubik() self.update_rubik() self.steps = [] self.solution = [] self.hide_sol_controllers() self.lblInfo["text"] = "" self.btnLogo["image"] = self.imgRubik
def get_rvalue(self, definition): return (ValueDefinition(self.builder.load(definition.addr), definition.type) if isinstance(definition, VariableDefinition) else definition) def visitVarDeclaration(self, ctx:ArcaneParser.VarDeclarationContext): var_name = ctx.ID().getTex...
This method evaluates expressions in a parser, handling binary operations (e.g., +, -, *, /) by converting operands to a common type and applying the operation. It also processes variable declarations, assignments, return statements, and atomic expressions, ensuring type consistency and generating appropriate IR instru...
def visitExpr(self, ctx:ArcaneParser.ExprContext): if ctx.getChildCount() == 3: lhs = self.get_rvalue(self.visit(ctx.getChild(0))) rhs = self.get_rvalue(self.visit(ctx.getChild(2))) target_type = TypeDefinition.get_convertible_type(lhs.type, rhs.type) lhs = lhs.co...
def dog_detector(img_path): """ Returns True if dog is detected in the specified image and False otherwise. Uses ResNet50 model trained on the ImageNet dataset for this. Parameters ---------- img_path Path to the image file Returns ------- boolean True if dog is det...
The code predicts a dog breed from an image using a pre-trained Inception model. It first checks if the image contains a dog or human face. If detected, it predicts the breed using the model, formats the result, and returns a message specifying the breed or face similarity. If neither is detected, it prompts the user t...
def predict_dog_breed(img_path, Inception_model, dog_names): """ Predict the breed of the dog based on input image and model (Inceptionv3). If the input image is detected as a human face or a dog, the output is the closest dog breed. If the input image is detected as neither a dog or a human face, ...
def get_subfolder_names(): """ Get a list of all subfolders in the root directory of the py file. Parameters ---------- The function doesn't take any parameters Returns ------- list of strings A list of all subfolders in the directory of the app. """ # function to g...
The code creates a Streamlit app for classifying dog breeds in images. Users select a folder and image file, which is displayed. A pre-trained model predicts the dog breed, with error handling for invalid files or model loading failures.
def main(): # output title of the app st.title('Dog Breed Classifier') # select the folder in which the test images are stored folder_select =\ st.sidebar.selectbox('Select the folder name where the images are stored', get_subfolder_names()) # search the test_images f...
def db_put(block): global last_seen_addrs # reset the set of last seen addresses last_seen_addrs = set() # iterate through transactions and write to database with BtcTransactions.batch_write() as batch: ctr = 0 for tx in block.transactions[1:]: try: Btc...
The function attempts to process a block by calling `db_put(block)`. If it fails, it logs the error, waits for a specified interval, and retries recursively, increasing the interval by 60 seconds and incrementing the attempt counter. This repeats up to 5 times. If all attempts fail, it logs the block as failed and proc...
def wait_and_load(block, interval_wait, num_times, log_file): if num_times < 5: try: db_put(block) return except Exception as e: write_to_file("error in parsing block: %s" % str(e), log_file) write_to_file("proceeding to wait...", log_file) ...
def db_put(block): global last_seen_addrs # reset the set of last seen addresses last_seen_addrs = set() # iterate through transactions and write to database with BtcTransactions.batch_write() as batch: ctr = 0 for tx in block.transactions[1:]: try: Btc...
This function attempts to process a data block by calling `db_put(block)`, retrying up to 5 times with exponentially increasing intervals (adding 60s each attempt) if exceptions occur. If all retries fail, it logs a failure message to a file and exits. The function avoids logging errors explicitly, only printing them d...
def wait_and_load_no_log(block, interval_wait, num_times): if num_times < 5: try: db_put(block) return except Exception as e: print("error in parsing block: %s" % str(e)) print("proceeding to wait...") time.sleep(interval_wait) ...
def observe(fSearch, iPos, iStats, xObserve, xNoFind, mapLim, sItem, sLoc, state): new_state = agent_host.getWorldState() if new_state.is_mission_running: if new_state.number_of_observations_since_last_state > 0: state = new_state msg = state.observations[-1].text obs...
The function `followPath` navigates an agent along a predefined path in a maze, using observation, prediction, and correction mechanisms. It updates the agent's position, avoids obstacles via corrections, and recalculates paths if stuck. The process times out after 60 seconds to prevent excessive computation, returning...
def followPath(fSearch, iPos, iStats, path, mapLim, xObserve, xNoFind, sItem, sLoc, state): #start timer searchTime = 0.0 maxTime = 60.0 initTime = np.round(time.time(), 1) while len(path)>1: #loop until path ...
def abstract_scaling(pMod, pSrc, iSet): abstract = pd.read_excel(pSrc, keep_default_na=False) col = 'set' + str(iSet) + '_lev' + str(pMod) ans = abstract[col].apply(eval) # if pMod == 0: # ans = abstract.L0.apply(eval) # ans = list(ans) # elif pMod == 1: # ans = abstract.L1.a...
The function `reason` determines an abstraction method based on the `pAbs` parameter. If `pAbs` is 0, it applies `abstract_scaling`; if 1, `abstract_similar`; if 2, `abstract_cluster`; if `None`, it returns `yBelief`. For invalid inputs, it returns an empty list and a warning. The task is to select and execute the appr...
def reason(yBelief, matFeature, pLoc, pAbs, pSrc, pMod, iSet): if pAbs == 0: ans = abstract_scaling(pMod, pSrc, iSet) elif pAbs == 1: ans = abstract_similar(yBelief, matFeature, pMod) elif pAbs == 2: ans = abstract_cluster(yBelief, matFeature, pMod, pLoc) elif pAbs is None: ans = yBelief else: ...
def is_pair(self): is_pair = False count = 0 pair = 0 for i in range(len(self.hand) - 1): if self.hand[i].value == self.hand[i + 1].value: pair = self.hand[i].value count += 1 if count == 1: is_pair = True return [is...
This code evaluates a poker hand's rank (0-9) based on standard poker hierarchy, updating the rank and high card value. It checks for pairs, two pairs, three of a kind, straights, flushes, full houses, four of a kind, straight flushes, and royal flushes, returning [rank, high_card] as the result.
def rank(self): rank = 0 high_card = self.hand[0].value if self.is_pair()[0]: rank = 1 high_card = self.hand[0].value if self.is_two_pair(): rank = 2 high_card = self.hand[0].value if self.is_three_of_a_kind(): rank = 3 ...
def rank(self): rank = 0 high_card = self.hand[0].value if self.is_pair()[0]: rank = 1 high_card = self.hand[0].value if self.is_two_pair(): rank = 2 high_card = self.hand[0].value if self.is_three_of_a_kind(): rank = 3 ...
The function compares two poker hands by evaluating their ranks and specific card values to determine which hand is stronger, returning 1 if self is stronger, -1 if other_hand is stronger, or 0 for a tie. It handles different hand types (e.g., straight flush, four of a kind) with rank-based logic, comparing kickers, hi...
def compare_hand(self, other_hand): if self.rank()[0] > other_hand.rank()[0]: return 1 elif other_hand.rank()[0] > self.rank()[0]: return -1 elif self.rank()[0] == other_hand.rank()[0]: if self.rank()[0] == 9: return 0 if self.rank(...
def reset_board(self): self.board = chess.Board() def make_moves(self, moves: list): for move in moves: self.make_move(move) def get_next_move(self) -> MoveWithType: move = MoveWithType(self.get_best_move(), MoveType.Best) if flip_coin(self.strategy.blunder_chance): ...
The main task of the code is to process chess game data by parsing strategies and move lists, applying them to a board, determining the next move, and returning the move type along with an analysis score. If no valid move is found, it resets the board and returns None. The function returns a list containing the move, i...
def process_data(self, data) -> list: self.reset_board() receivedStrategy = ChessDataParser.get_strategy(data) if receivedStrategy is not None: self.strategy = receivedStrategy receivedMoves = ChessDataParser.get_move_list(data) self.make_moves(receivedMoves) ...
def normalize_rut(raw_rut): rut = stringify_rut(raw_rut) if not rut or not valid_rut_values(rut): return None rut = rut.replace(".", "").replace("-", "") return rut.upper() def valid_rut_values(raw_rut): rut = stringify_rut(raw_rut) if not rut: return False return all(valid...
This code calculates the verifier digit for a Chilean RUT (Rol Único Tributario) by normalizing the input, validating its format, applying a weighted sum algorithm with alternating multipliers, and translating the modulo 11 result into the correct verification digit.
def get_verifier(raw_rut): rut = normalize_rut(raw_rut) if not rut or not valid_rut_values(rut): return None sum = 0 mul = 2 for i in reversed(rut): sum += int(i) * mul mul = 2 if mul == 7 else mul + 1 res = sum % 11 return translate_verifier_result(res)
def normalize_rut(raw_rut): rut = stringify_rut(raw_rut) if not rut or not valid_rut_values(rut): return None rut = rut.replace(".", "").replace("-", "") return rut.upper() def valid_rut_values(raw_rut): rut = stringify_rut(raw_rut) if not rut: return False return all(valid...
The function verifies if a given RUT (Rol Único Tributario) is valid by checking if its calculated check digit matches the provided one. It normalizes the input, validates its format, extracts the numeric part, computes the expected check digit, and compares it to the last character of the RUT.
def valid_rut_verifier(raw_rut): rut = normalize_rut(raw_rut) if not rut or not valid_rut_values(rut): return False r = rut[:-1] return get_verifier(r) == rut[-1]
def stringify_rut(raw_rut): if raw_rut is None or not isinstance(raw_rut, (str, int)): return None return str(raw_rut) def valid_rut_values(raw_rut): rut = stringify_rut(raw_rut) if not rut: return False return all(valid_rut_value(i) for i in rut) def normalize_rut(raw_rut): ru...
The function `format_rut` validates and formats a Chilean RUT (tax ID) based on the specified format. It first converts the input to a string, checks its validity, and returns `None` if invalid. Depending on the `format` parameter, it applies normalization, dash-only formatting, or the classic format to the RUT, return...
def format_rut(raw_rut, format="classic"): rut = stringify_rut(raw_rut) if not rut or not valid_rut_values(rut): return None if format == "normalized": return normalize_rut(rut) elif format == "dash_only": return dash_only_rut(rut) elif format == "classic": return cl...
def normalize_rut(raw_rut): rut = stringify_rut(raw_rut) if not rut or not valid_rut_values(rut): return None rut = rut.replace(".", "").replace("-", "") return rut.upper() def valid_rut_values(raw_rut): rut = stringify_rut(raw_rut) if not rut: return False return all(valid...
The function validates a Chilean RUT (Rol Único Tributario) by normalizing the input, checking if the RUT values are valid, and verifying the checksum digit. It returns True if all checks pass, otherwise False.
def valid_rut(raw_rut): rut = normalize_rut(raw_rut) if not rut or not valid_rut_values(rut): return False return valid_rut_verifier(rut)
def reset(self) -> None: # Begin data frame 4 bytes self._frame() # 4 bytes for each led (checksum, blue, green, red) for _i in self.controllers: self._write_byte(0xC0) for _j in range(3): self._write_byte(0) # End data frame 4 bytes ...
This code initializes an LED controller system by configuring GPIO pins for clock and data signals, resetting the system, loading existing controllers, and adding a default controller if none are present. It sets up hardware communication for controlling LED chains.
def __init__(self, clockPin: int = 27, dataPin: int = 17): self.cid: int = -1 # Chain id self.controllers: list[LEDController] = [] self.dataPin: int = dataPin self.clockPin: int = clockPin # Set GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(self.clockPin, GPIO.OUT) ...
def emptyfiles(): dirs = ["images", "pdfs"] for directory in dirs: for f in os.listdir(directory): os.remove(os.path.join(directory, f)) def convert_pdf_to_image(filepath): try: pages = convert_from_path(filepath, 350) except Exception as err: logging.error(f...
The main task of the code is to automate the processing of PDF files from an FTP server. It connects to the FTP, downloads files, converts them to images, and processes the images to extract data. If conversion or processing fails, files are moved to a "Corrupted" folder. Successful files are archived, with extracted d...
def start(): logging.info("Starting Extractor") ftpclient = ftp.FTP_CLIENT() logging.info("Checking FTP for files to download") full_files = ftpclient.download() ftpclient.disconnect() if len(full_files) == 0: logging.info("No files were found in FTP") return l...
def get_command(cmd) : command = [] try : command = cmd.split('(') except : command[0] = cmd.strip(' ') return command def get_argument(command) : arguments = [] try : args = command[1].split(')')[0].split(',') n = 0 while(len(args) > n ) : ...
This code creates an interactive command-line interface with history support, autocompletion, and command execution. It continuously prompts the user for input, processes commands using a completer for suggestions, extracts command names and arguments, and executes them via command_line_function in a loop.
def command_user(): our_history = FileHistory(".history-file") session = PromptSession(history=our_history) while(True) : res = six.print_(colored('cmd - : ', 'green'), end='') cmd = session.prompt( res, completer=function_completer, complete_while_typin...
def getChangeDuration(self, duration): start_date = datetime.datetime.now() end_date = start_date + datetime.timedelta(hours=duration) return { 'start_date' : str(start_date), 'end_date' : str(end_date) } def getChangeForm(self): environments = dict(os.environ) ...
The main task of the code is to create a change request by retrieving a duration period, populating a template with start/end dates and an approval status of "Requested," then submitting the structured change data. This involves fetching configuration values, assembling a formatted change payload, and triggering the su...
def createNormalChange(self): print('\n- Creating change...\n') change_duration = self.getChangeDuration( int(os.getenv('RD_OPTION_CHANGE_DURATION', '1'))) template = self.getChangeForm() template['start_date'] = change_duration['start_date'] template['end_date'] = ch...
def getRundeckJobInfo(self, job_id): endpoint = f'/api/43/execution/{job_id}' req = requests.get( f'{self.ARGUMENTS.RD_SERVER}/{endpoint}', headers={ 'X-Rundeck-Auth-Token': self.ARGUMENTS.RD_TOKEN, 'Accept': 'application/json'}, ...
This function closes a change request associated with a Rundeck job by determining its status (successful/unsuccessful) based on the job's execution result, then updating the change's state to "closed" (state 3) with detailed notes including job metadata and closure reason. It uses environment variables to identify the...
def closeNormalChange(self): if os.getenv('RD_OPTION_JOB_ID') == '' or os.getenv('RD_OPTION_JOB_ID') is None: job_id = int(os.getenv('RD_JOB_EXECID')) current = True else: job_id = int(os.getenv('RD_OPTION_JOB_ID')) current = False job_info = self....
def measure_and_document_acceleration(self, osc_list): ''' measures acceleration of all oscillators in experiment ''' for i in range(len(osc_list)): new_a = 0 new_a = osc_list[i].a = self.calculate_acceleration_n_oscillators(osc_list, i) osc_list[i].update_a(new_a) d...
This function runs multiple experiments by iterating through each experiment and its frames. For each frame, it measures and documents acceleration, velocity, and coordinates of oscillators. After each experiment (except the last), it resets the setup. Finally, it executes post-experiment analysis on the collected data...
def run_experiment(self, osc_list): ''' a function to run the experiment loop''' for j in range(self.number_of_experiments): for frame in range(self.frames_num[j]): self.measure_and_document_acceleration(osc_list) self.measure_and_document_velocity(osc_li...
def get_ebay_quantity_data(ls, vendor, sheet): for dt in ls: # Extracting data from dict ( url, title_gender, gender, age_group, title, style_code, color, sizes, price, cost, ...
The code extracts product data from a list, processes it with lookup information, and appends structured eBay listing data (including variations) to an Excel workbook. It formats product details, maps attributes to eBay categories, handles size/stock variations, and populates worksheets with standardized fields for e-c...
def get_ebay_product_data(ls, vendor, workbook): # Replace with the path to your existing Excel file qty_sheet = workbook["eBay.Qty"] get_ebay_quantity_data(ls, vendor, qty_sheet) sheet = workbook["eBay"] for dt in ls: # Extracting data from dict ( url, title_...
def get_amazon_quantity_data(ls, vendor, sheet): # Replace with the path to your existing Excel file # file_path = 'TemplateEbayProduct.xlsx' # Replace with the path to your existing Excel file # file_path = 'Templates/AmazonQuantityTemplate.xlsx' # workbook = openpyxl.load_workbook(file_path) #...
The code extracts product data from a list, formats it into Amazon-specific fields, and appends it to an Excel workbook. It processes parent product details, including images, bullet points, and features, then adds child product variations with size, price, and quantity data to the "Amazon" sheet for Amazon product lis...
def get_amazon_product_data(ls, vendor, workbook): # Replace with the path to your existing Excel file # file_path = 'TemplateEbayProduct.xlsx' # Replace with the path to your existing Excel file # file_path = 'Templates/AmazonProductTemplate.xlsx' # workbook = openpyxl.load_workbook(file_path) ...
def __handle_instructions(self, lines): result = [] for line in lines: if self.__is_a_instruction(line): result.append(self.__translate_a_instruction(line)) else: result.append(self.__translate_c_instruction(line)) return result def __handl...
This code processes input lines through a sequence of transformations: handling comments, spaces, symbols, and instructions, returning the final processed result after applying all four steps in order.
def translate(self, lines): return self.__handle_instructions( self.__handle_symbols(self.__handle_spaces(self.__handle_comments(lines))) )
def get_metadata(self, src_meta, fieldname=None, src_img=None, datasize=None): src_meta_abs = os.path.join(self.src_meta_parent, src_meta) if src_meta.split('.')[-1] == 'csv': logging.info('{}:Reading CSV metadata'.format(datetime.datetime.now())) metadata = self.CSVtoJSON(src_me...
The main task of the code is to process images by reading them from a local folder, zip file, or online source, converting metadata to JSON format, extracting VGG16/VGG19 feature predictions, and performing clustering on the processed data. It handles metadata conversion, image loading, feature extraction, and clusteri...
def process_images(self, src_img=None, zip_folder="", src_meta=None, fieldname=None, datasize=None): """ Process images stored in src_img, creating or converting src_meta into json format for image processing Args: src_img (String): Folder in which the images are stored ...
def get_youtube_video_comments(video_id: str) -> list[str]: """Returns a list of all comments from a YouTube video for a specified videoId. Reponses for YouTube API commentThreads().list() requests are returned with the maximum of 100 commentThreads per page. Each commentThread contains one top level...
This function analyzes comments from a YouTube video or manual input, predicts their classification, and returns a response rendering the results. It retrieves YouTube comments via API or uses manual text, processes predictions, combines data, and handles errors with tailored error messages. The response includes analy...
def analyse_comments(source: str) -> Response: """Analyse comments view function. If the source is "youtube_video" treat the request form data as a YouTube videoId and retireve all comments from the YouTube video with that VideoId. Otherwise, treat the request form data as a single string comment. ...
def list_css(themes, sites): "Return list of CSS files for THEMES and SITES." return [CSS("%s/%s/%s-%s.css" % (css_dir, theme.name, theme.name, site.strip('_')), dependencies(theme, site), theme, site) for theme in themes for site in ...
The main task of the code is to generate and build CSS files for specified themes and sites by creating necessary directories to prevent race conditions, then utilizing multiprocessing to efficiently execute the build process across multiple CPU cores.
def update_css_files(): "Build CSS files that need to be built." css_files = list_css(themes(), sites()) # Make directories first to avoid race condition for css in css_files: dir = os.path.join(css_dir, css.theme.name) if not os.path.isdir(dir): os.makedirs(dir) pool ...
def list_css(themes, sites): "Return list of CSS files for THEMES and SITES." return [CSS("%s/%s/%s-%s.css" % (css_dir, theme.name, theme.name, site.strip('_')), dependencies(theme, site), theme, site) for theme in themes for site in ...
The main task of the code is to update screenshots by generating them for each CSS theme using parallel processing. It ensures the screenshots directory exists, sets up a git worktree if necessary, creates theme-specific directories, and processes CSS files concurrently with multiprocessing to generate and commit scree...
def update_screenshots(): "Update screenshots." css_files = list_css(themes(), sites()) if not os.path.isdir(screenshots_dir): # If the directory does not exist, create a new worktree for it. # Assumes the screenshots branch exists. subprocess.call(["git", "worktree", "prune"]) ...
def create_doc_list(self, knw_graph): u = [] for _, maps in enumerate(knw_graph.maps): if maps: if maps["para_list"]: pl = maps["para_list"] for _, p in enumerate(pl): u.append(maps["url"]) ...
This code reduces text redundancy in a corpus by identifying and removing similar documents. It preprocesses documents, computes embeddings using SBERT, calculates pairwise cosine similarities, and recursively drops redundant entries. The result is a cleaned DataFrame with unique, non-redundant texts and associated met...
def remove_text_redundancy(self, knw_graph): print(Fore.GREEN+"[*] truncating corpus using similarity metric") st.info("Truncating corpus using similarity metric") self.docs, u = self.create_doc_list(knw_graph) tic = time.perf_counter() for _, text in enumerate(self.docs): ...
def remove_text_redundancy(self, knw_graph): print(Fore.GREEN+"[*] truncating corpus using similarity metric") st.info("Truncating corpus using similarity metric") self.docs, u = self.create_doc_list(knw_graph) tic = time.perf_counter() for _, text in enumerate(self.docs): ...
The code processes a knowledge graph by cleaning text, generating n-grams, extracting named entities (NER), tokenizing sentences, computing TF-IDF features, and generating summaries using a pipeline. It aims to summarize large text data efficiently, with timing metrics for performance tracking.
def process(self, knw_graph): self.documents_df = self.remove_text_redundancy(knw_graph) self.n_grams = self.n_gram_generator(self.doc_clean) self.nlp = self.get_ner_pipeline() print(Fore.GREEN+"[*] generating NER tokens ") st.info("Generating NER tokens ") self.document...
def crawl(self, max_urls): self.total_urls_visited += 1 links, data = self.get_all_website_links(self.url) if data: self.knw_graph = self.knw_graph.new_child(data) # print(Fore.YELLOW + f"[*] fetching {self.url}") # print(Style.RESET_ALL) for link in links: ...
The code's main task is to initiate a web crawling process by setting up an HTTP cache, crawling up to `max_urls`, extracting email addresses, and dumping collected data. It manages caching, data retrieval, email validation, and storage in a structured workflow.
def begin(self, max_urls): requests_cache.install_cache( 'http_cache', expire_after=timedelta(days=1)) self.crawl(max_urls) self.__check_emails() self.__dump_data()
def crawl(self, max_urls): self.total_urls_visited += 1 links, data = self.get_all_website_links(self.url) if data: self.knw_graph = self.knw_graph.new_child(data) # print(Fore.YELLOW + f"[*] fetching {self.url}") # print(Style.RESET_ALL) self.pbar.update(self...
The main task of the code is to initiate a crawling process with a progress bar, crawl up to `max_urls`, close the progress bar, check for emails, and dump collected data. It manages URL crawling, progress tracking, email validation, and data storage in a structured workflow.
def begin(self, max_urls): self.pbar = tqdm(total=max_urls, desc="crawling") self.crawl(max_urls) self.pbar.close() self.__check_emails() self.__dump_data()
def get_filter_and_cfa_crops(cfa_image, filter_channels, subsample_crop): cfa_crop = cfa_image[subsample_crop[0]:subsample_crop[0] + subsample_crop[2], subsample_crop[1]:subsample_crop[1] + subsample_crop[3]] filters_crop = [filter_channel[subsample_crop[0]:subsample_crop[0] + subsample_crop[2], subsample_crop[...
The function processes a CFA image by iterating over subsamples to compute color cross-correlation matrices (CCMs) for both quantized CFA data and true filter data. It applies quantization, generates 5-filter CFA and true CCMs for each subsample, and returns lists of these matrices for further analysis.
def calculate_crops_ccms(cfa_image, filter_channels, subsamples_crops, quant): cfa_ccms = [] true_ccms = [] for subsample_crop in subsamples_crops: cfa_crop, filters_crop = get_filter_and_cfa_crops(cfa_image, filter_channels, subsample_crop) cfa_crop_quant, filters_crop_quant = get_filter_a...
def get_specific_quant_ccms_paths(paths, quant): return [path for path in paths if str(quant) + ".pkl" in path] def load_obj(file_name): with open(file_name, 'rb') as f: return pickle.load(f) def calculate_metrics(ccms_test, ccms_tar): return similarity(ccms_test, ccms_tar), dissimilarity(ccms_test,...
The function evaluates quantization methods by comparing test subsamples against target subsamples using intersection and divergence metrics. It calculates classification accuracy across varying neighbor counts and distance types, storing results in matrices. After processing all test cases, it saves accuracy percentag...
def quantization_loop(quant, ccms_paths, ccms_type): specific_quant_ccms_paths = get_specific_quant_ccms_paths(ccms_paths, quant) correct_inter_image = np.zeros((len(CCM_DISTANCES), len(M_LIST))) correct_inter_class = np.zeros((len(CCM_DISTANCES), len(M_LIST))) correct_dive_image = np.zeros((len(CCM_DIS...
def initialize_parameters(self): np.random.seed(1) for l in range(1, len(self.layers_size)): self.parameters["W" + str(l)] = np.random.randn(self.layers_size[l], self.layers_size[l - 1]) / np.sqrt( self.layers_size[l - 1]) self.parameters["b" + str(l)] = np.zero...
This code trains a neural network using gradient descent by initializing parameters, performing forward and backward propagation, updating weights with calculated gradients, and tracking the cost during iterations. It iteratively minimizes the loss function by adjusting model parameters over specified iterations, print...
def fit(self, X, Y, learning_rate=0.01, n_iterations=2500): np.random.seed(1) self.n = X.shape[0] self.layers_size.insert(0, X.shape[1]) self.initialize_parameters() for loop in range(n_iterations): A, store = self.forward(X) cost = -np.mean(Y * np.l...
def normalize_gdf( gdf, start_datetime=None, end_datetime=None, date=None, dtime=None, timedelta_slice=None, ): """return a normalized gdf list start/stop date name will be 'start_datetime' and 'end_datetime' """ # add the index of each rows of input gdf gdf["id_original_quer...
The function fetches geospatial data from URLs based on parameters like time ranges, filtering criteria, and processing modes (sequential/multithreaded). It normalizes input GeoDataFrames, generates URLs, retrieves data, deduplicates it, converts multipolygons to polygons, and applies a sea percentage filter. The resul...
def fetch_data( gdf, date=None, dtime=None, timedelta_slice=None, start_datetime=None, end_datetime=None, min_sea_percent=None, fig=None, top=None, cache_dir=None, mode="seq", ): """ Fetches data based on provided parameters. Args: gdf (GeoDataFrame): cont...
def to_dataset(x, y, y_real): torch_x = torch.tensor(x, dtype=torch.long) torch_y = torch.tensor(y, dtype=torch.float) torch_real_y = torch.tensor(y_real, dtype=torch.long) return TensorDataset(torch_x, torch_y, torch_real_y) def model(self, text_field): raise NotImplementedError...
The code preprocesses text data by splitting, normalizing, and padding sequences, then converts them to indexes using a vocabulary. It splits data into train/test sets, creates datasets, initializes a model, trains it, and saves the vocabulary for future use.
def train(self, X, y, y_real, output_dir): X_split = [normalize(t.split()) for t in X] split_arrays = train_test_split(X_split, y, y_real, test_size=self.settings['test_size'], stratify=y_real) X_train, X_test, y_train, y_test, y_real_train, y_real_test = split_arrays text_field = dat...
def read_file(file_name): file_object = open('musicscore/' + file_name,'r') music_info = {} music_score = [] read_step = 1 try: for line in file_object: # get music info for key_word in music_info_key_word: info = re.match(music_info_key_word[key_wor...
The code processes a song file by reading its data, extracting notes, and generating metadata based on the specified level and fever flag. It returns structured metadata derived from the song's information and score.
def process_song(file_name, level, fever = False): info, score = read_file(file_name) notes = process_notes(info, score) meta = get_score_meta(notes, level, fever) return meta
def is_solvable(self): state=self.state # Detemina si un estado es soluble, algunos no lo son por ejemplo https://www.youtube.com/watch?v=YI1WqYKHi78 width = len(state[0]) #Vemos si esta en el rango especificado if width!=len(state): raise NameError('Las dimensiones d...
The code solves a sliding puzzle using the A* algorithm with Manhattan distance heuristic. It checks solvability, generates a goal state, and iteratively displays each step until the puzzle is solved, printing messages for progress and completion.
def solvePuzzle(self): # Solucion del rompecabeza if not self.is_solvable(): print('No es soluble se retorna None') return None n=len(self.state[0]) flattened= flatten(self.state) goal = list(range(1, len(flattened)))+[0] #Checa que la matriz sea cuadr...
def loginGate(message): global my_username if message[1] == "$TRUE_DATA~": print("login details verified") my_username = entered_uname login_status_frame["fg"] = correct_fg login_status_frame["text"] = "Verifying credentials" chatpage_raiser() return 1 elif m...
The function `requestReceive` processes incoming client messages by continuously receiving data, parsing message headers, and handling specific message types. It validates login info, updates user lists, sends direct/broadcast messages, and notifies disconnections. It uses global variables to track list states and user...
def requestReceive(activeUser): global list_flag global previous_list previous_list = [] list_flag = 0 while True: try: message_header = client_socket.recv(1024) message_length = int(message_header.decode('utf-8').strip()) message = client_socket.recv(mes...
def grid(x, y=None): global gridarr if y == None: x, y = x return gridarr[y][x] def car(p): if grid(p) < 0: return (p, None) return list(filter(lambda x: grid(p) == grid(x[0]), otherdir(p)))[0] def otherdir(p): return [(adj(p, direc), direc) for direc in directions if not oob(adj(p,direc))] def moveinempty(p...
This code implements a depth-first search (DFS) to find the shortest path in a grid while avoiding obstacles (notcar). It recursively explores valid car movements, filters positions based on direction and grid state, and updates the shortest path when a valid route is found. The function returns whether a path exists a...
def dfs(p, notcar): if grid(c,r) == -1: return (True, []) carpos = filter(lambda x: x[1] == car(x[0])[1] and grid(car(x[0])[0]) != notcar, otherdir(p)) cars = map(lambda x: car(x[0]), carpos) pathfound = False shortestlength = float("inf") shortestpath = [] for i in cars: carval = grid(i[0]) empty = movein...
def add_elem_queue(self, elem): self.queue.append(elem) def has_token(self): return self.number == self.holder def is_using(self): return self.using def send_token(self, requestor): if self.number == requestor : print(" [*] I made the request") self.holder = self.number self.asked = False self.start...
This code handles message callbacks in a distributed system, managing token requests and transfers. It initializes requests, processes token acquisition/transfer logic, simulates token usage delays, and resets states upon detecting a dead node. The function responds to messages like "REQUEST INIT", "REQUEST TOKEN", "SE...
def callback(ch, method, properties, body): if body.count("REQUEST INIT".encode()): print(" [*] I initialize a request ") self.add_elem_queue(self.number) self.asked = True elif body.count("REQUEST TOKEN".encode()): requestor = int(body.replace("REQUEST TOKEN from node ".encode(),"".encode())) ...
def train_on_batch(self, batch_x, batch_y): self.model.train() preds = self.model(batch_x) loss = self.criterion(preds, batch_y) self.optimizer.zero_grad() loss.backward() self.optimizer.step() self.writer.add_scalar('Training loss', loss.item(), self.steps) ...
The main task of the code is to perform one training epoch by iterating through training batches, training the model on each batch, running validation, generating test predictions, saving model checkpoints, and incrementing the epoch counter. This encapsulates the complete training cycle including training, evaluation,...
def epoch_train(self): for batch_x, batch_y in self.train_loader: self.train_on_batch(batch_x.to(device), batch_y.to(device)) self.validation_run() self.make_test_predictions() self.checkpoint_model() self.epochs += 1
def createWorld(m): for mI in range(1, 5): for aI in range(1, 5): if (mI == 1 and aI == 1): continue number = random.randint(0, 3) m[mI][aI] = 2 if number == 1 else 0 renderMatrix(matrix) global process_map global presentationMatrix process...
The code implements a pathfinding algorithm to clean a grid world by discovering and marking paths, updating the environment, and displaying the total moves made to clean the map. It uses depth-first search with backtracking, tracks the solution path, and presents the result via a GUI message box showing the number of ...
def main(): global matrix global process_map global stack global currCol global currLine createWorld(matrix) while (mapNotClean()): path = discoverPath() x = path.get_x() y = path.get_y() aux_list = [] while (path.get_parent() is not None): ...
def reset(self): print("Environement reset!") self.left_queue, self.right_queue = self.generate_queue() print("Queue: ", self.left_queue, self.right_queue ) self.orig_left_queue, self.orig_right_queue = self.left_queue.copy(), self.right_queue.copy() self.left_vehicle_queue = deq...
The main task of the code is to determine the appropriate high-level action and the number of vehicles to exit based on the current state of left and right queues. It processes input high-level actions, maps them to specific movement tuples, and evaluates queue configurations to decide coalition-specific exit counts, d...
def process_high_level_action(self, high_level_actions): ''' high-level actions: 0 -> (1,0), 1 -> (0,1), 2 -> (1,1) human :1, coalition: 2, empty:0 ''' print("Left queue len : ",len(self.left_queue)) print("Right queue len: ", len(self.right_queue)) if ...
def take_step(self, high_level_action): print ("This is the action: ", high_level_action) HLA = [2,2] # initialize with the SR print(high_level_action) # breakpoint() # ray.util.pdb.set_trace() for agent_id, action in high_level_action.items(): print("agent_i...
The main task of the code is to execute a given action in the environment, update the system state via `take_step`, track time progression, compute observations, rewards for active agents, check termination conditions, and return the new state, rewards, done status, and agent-specific information for reinforcement lear...
def step(self, action): # av_2 = self.get_company_action()[0] # w_s1, w_s2 = self.take_step([action, av_2]) print("+++++++++++++++++++++++++++++++++++++++") print("HLA", action) print("+++++++++++++++++++++++++++++++++++++++") w_s1, w_s2 = self.take_step(action) ...
def get(self, url: str) -> dict: if DEBUG: print(">>> FETCHING: ", url) url = f"{BASE_URL}{url}" if not url.startswith("https://") else url request = urllib.request.Request(url, headers=self.get_headers()) try: with urllib.request.urlopen(request) as response: ...
The code retrieves the latest build status of a specific GitHub Actions job on the same branch by querying completed and partial workflow runs, filters relevant jobs by name, and returns the most recent conclusion ("success" or "failure") based on the latest job completion time.
def get_previous_build_status(self) -> Literal["success", "failure"]: """We need the previous build status of the job of the **SAME** branch https://docs.github.com/en/rest/actions/workflows """ completed = self.get( f"/repos/{GITHUB_REPOSITORY}/actions/workflows/{self.get_wo...
def _get_env_vars(test_username: str, plugin_data: Dict, data_names: List) -> Dict[str, str]: """Return a dictionary containing all environment variables to pass to the next test""" env_vars = {"AUTOTESTENV": "true", **set_up_plugins(test_username, plugin_data), **get_data_environment(data_names)} worker_co...
The function executes test scripts specified in test_settings within the given tests_path directory using the provided command. It filters tests based on categories, manages environment variables, handles timeouts by terminating processes, and collects results including output, errors, duration, and feedback. The resul...
def _run_test_specs( cmd: str, test_settings: dict, categories: List[str], tests_path: str, test_username: str, test_id: Union[int, str], test_env_vars: Dict[str, str], ) -> List[ResultData]: """ Run each test script in test_scripts in the tests_path directory using the command c...
def redis_connection() -> redis.Redis: """ Return a connection to a redis database. """ return rq.get_current_job().connection def tester_user() -> Tuple[str, str]: """ Get the workspace for the tester user specified by the WORKERUSER environment variable, return the user_name and path to th...
The function `run_test` executes a test using specified settings and files, retrieves settings from Redis, updates access time, sets up test files, runs test specifications, and stores results back in Redis with the test ID. It handles environment variables, cleans up resources, and logs errors, ensuring test execution...
def run_test( settings_id: Union[int, str], test_id: Union[int, str], files_url: str, categories: List[str], user: str, test_env_vars: Dict[str, str], ) -> None: """ Run a single test with the files from files_url using the settings with id settings_id that match the category in cate...
def _build_resources(self): self.template = Template() self.template.set_version("2010-09-09") self.template_initial = Template() self.template.set_version("2010-09-09") # S3 Bucket s3_bucket_obj = Bucket("S3Bucket", AccessControl=Private) s3_bucket = self.templ...
The code deploys a CloudFormation stack (create or update) with AWS resources, uploads deployment artifacts to S3, handles errors, deploys an API via API Gateway, and executes pre/post-deploy module hooks. It checks stack existence, uses boto3 clients, and ensures infrastructure synchronization with resource templates ...
def deploy(self): cf_client = self.boto_session.client("cloudformation") api_gateway_client = self.boto_session.client("apigateway") s3_client = self.boto_session.client("s3") stack_created = False self._build_resources() # modules pre deploy if self.exists: ...
def _build_resources(self): self.template = Template() self.template.set_version("2010-09-09") self.template_initial = Template() self.template.set_version("2010-09-09") # S3 Bucket s3_bucket_obj = Bucket("S3Bucket", AccessControl=Private) s3_bucket = self.templ...
The main task of the code is to destroy an AWS CloudFormation stack by first deleting contents from an associated S3 bucket, executing pre-destruction logic for modules, deleting the stack, waiting for deletion completion, and running post-destruction module logic, while handling potential errors during the process.
def destroy(self): cf_client = self.boto_session.client("cloudformation") self._build_resources() if self.exists_or_exit(): # empty bucket - only empty can be deleted afterwards bucket_name = self.get_output("S3BucketName") echo.enum_elm(f"deleting files in ...
def grad_loss(w,x,y,k): S=0 for i,j in zip(x,y): S+=(np.dot(w,addDegre(i,k))-j)*addDegre(i,k) return (2*S)/m def loss(w,x,y,k): S=0 for i,j in zip(x,y): S+=(np.dot(w,addDegre(i,k))-j)**2 return S/m def alphaSearch(w,x,y,k): grad = grad_loss(w,x,y,k) a = sp.Symbol("a") ...
The code performs polynomial regression using gradient descent. It iteratively updates the model's weights (w) by computing the gradient of the loss function, adjusting weights with a learning rate (alpha), and visualizing the polynomial fit. After 38 iterations, it returns the final loss value and optimized weights.
def Regression(w,x,y,k): grad=grad_loss(w,x,y,k) ls=loss(w,x,y,k) numIter=0 a = np.linspace(np.min(x)-5, np.max(x)+5, 50) while numIter<38: alpha=alphaSearch(w,x,y,k) print(alpha , k) w=w-alpha*grad draw_Polynomial_Line(x,y,w,a,k) grad=grad_loss(w,x,...
def GetStartAndEndObject(start_YYYYMMDDhhmm, end_YYYYMMDDhhmm): splited_start_YYYYMMDDhhmm = FindDate(start_YYYYMMDDhhmm) splited_end_YYYYMMDDhhmm = FindDate(end_YYYYMMDDhhmm) start = datetime(year = splited_start_YYYYMMDDhhmm[0], month = splited_start_YYYYMMDDhhmm[1], day = splited_st...
This function generates an array of timestamp values starting from a given start date, incrementing by specified hours and minutes, until reaching or exceeding the end date. It calculates the total number of intervals, initializes a numpy array, and populates it by iteratively rolling the date forward using helper func...
def GetDateArray(start_YYYYMMDDhhmm, end_YYYYMMDDhhmm, int_hour, int_minute): target_date = start_YYYYMMDDhhmm start,end = GetStartAndEndObject(start_YYYYMMDDhhmm,end_YYYYMMDDhhmm) amount = FindDateAmount(start_YYYYMMDDhhmm, end_YYYYMMDDhhmm, int_hour, int_minute) DATE_array = np.empty([1,amount],dtype...
def __take_out_driver_from_team(self, team: Team, idx: int): driver = team.drivers[idx] team.drivers[idx] = None team.driver_contracts[idx] = -1 driver.team = None if driver.age > 38 or (driver.age > 30 and random.random() < 0.2): if PRINT_DRIVER_UPDATES: ...
This method ensures all teams have valid drivers by removing drivers with expired contracts and replacing missing drivers with new ones from a perception-based pool, updating contracts and team assignments accordingly.
def __teams_pick_drivers(self, team_results: List[Tuple[Team, int]]): for team in self.teams: drv1_valid, drv2_valid = team.is_drivers_contracts_still_valid() if not drv1_valid: self.__take_out_driver_from_team(team, 0) if not drv2_valid: self....
def __update_directions(self, team_results: List[Tuple[Team, int]]): total_teams = len(self.teams) for idx, team_result in enumerate(team_results, 1): team = team_result[0] old_stats = team.direction.get_stats() new_direction = team.direction.yearly_update(idx, total_...
(The code simulates a racing world over multiple seasons, tracking driver, team, and engine statistics. It runs each season, records winners, updates statistics, and adjusts in-world parameters like team directions, driver ages, and engine choices. After all seasons, it compiles and displays historical results and fina...
def run_world(self): history_driver = [] history_team = [] statistics_driver = {} statistics_team = {} statistics_engine = {} for n_season in range(self.n_seasons): console.rule(f"[bold red]Season {n_season + 1}") s = Season(self.tracks, self.team...
def random_grid(self, n_particles, T, y): raise NotImplementedError("Please Implement this method") def forwardHMM(self, x): T = x.shape[0] N = x.shape[1] predlike=np.zeros(T) filter_state=np.zeros((T,N)) #init winit = self._w_init_func(x) fi...
This code performs a sampling step in a particle filter for a Hidden Markov Model (HMM). It generates candidate states, computes forward and backward probabilities, calculates acceptance probabilities, and uses a Metropolis-Hastings criterion to accept or reject samples. The main task is to sample from the posterior di...
def sample_one(self, n_particles, T, y): cand_x = [] paccs = [] accepted = False n_trial = 0 while not accepted: n_trial += 1 xcand=np.zeros((T,self.dimension)) x = self.random_grid(n_particles, T, y) logZ, _, fil...
def __check_solution(self, guess): if self.__valid_guess(guess): self.attempts.append(guess) if guess.lower() == self.solution.lower(): self.__game_over( colored("You Win! Thanks for playing :)", "green"), True ) return ...
This function processes a player's guess in a word game. It normalizes the input word, checks if it matches the solution, updates the game state, and triggers a game-over message if attempts are exhausted without solving. It returns the result of the solution check.
def guess(self, word): word = word.lower().strip() result = self.__check_solution(word) self.display_state() if self.attempts_left() < 1 and not self.solved: self.__game_over( colored( f"Looks like you lose! The correct answer was {self.so...
def calc_height(self, given_node: Node): if given_node is None: return -1 return given_node.height def handle_balance(self, given_node: Node): # check the nodes from given node we have inserted up to the root node while given_node is not None: given_node.height = ...
This function inserts a new node with given data into an AVL tree recursively. It places the node in the left or right subtree based on data comparison, updates node heights, and ensures AVL balance by calling handle_balance after insertion.
def insert_node(self, data, current_node: Node): if data < current_node.data: if current_node.left_node is not None: self.insert_node(data, current_node.left_node) else: current_node.left_node = Node(data, parent=current_node) current_node....
def handle_balance(self, given_node: Node): # check the nodes from given node we have inserted up to the root node while given_node is not None: given_node.height = max(self.calc_height(given_node.left_node), self.calc_height(given_node.right_node)) + 1 ...
This function removes a node with specified data from a binary search tree. It recursively locates the node, handles four cases (leaf, single child, two children), adjusts tree structure by updating parent pointers, deletes the node, and maintains balance via handle_balance. For two children, it swaps data with predece...
def remove_node(self, data, current_node): # First we have to find the node to remove if current_node is None: return elif data < current_node.data: self.remove_node(data, current_node.left_node) elif data > current_node.data: self.remove_node(data, cu...
def make_sheet(): sheet_len = int(input("Enter the length of the word puzzle:\n")) # n * n sheet = [] for i in range(sheet_len): sheet_i_str = input(f"Enter the {i+1}th line: ({sheet_len-1-i} lines left)\n") sheet_i_lst = [letter for letter in sheet_i_str] sheet.append(sheet_i_lst) ...
The main task of the code is to interactively search for words in a dynamically modifiable sheet. It allows users to rewrite the sheet, modify it, or input words to search, returning results. The loop continues until the user chooses to exit, with options to leave, rewrite, or adjust the sheet during execution.
def main(): sheet = make_sheet() while True: word = input("Enter a word: (l to leave, r to rewrite the sheet, c to modify the sheet)\n") if word == 's': break elif word == 'r': sheet = make_sheet() elif word == 'c': sheet = modify_sheet(sheet) ...
def around_grid(self, grid): if self.board.get_player(grid) is None: x = grid[C.GRIDX] y = grid[C.GRIDY] x_min = max(C.START, x-C.STEP) y_min = max(C.START, y-C.STEP) x_max = min(self.board.size, x+2) y_max = min(self.board.size, y+2) ...
This code checks if any player can form a specific pattern (n, m) in their row on the grid by iterating through all grid positions, verifying surrounding pieces, and using a helper function to validate the pattern. If successful, it prints the player's name, pattern details, and position, then returns True. If no valid...
def n_m_ends(self, n, m): for player in self.players: for i in C.GRID: if self.around_grid(i): if self.n_m_ends_helper(i, n, m, player): print(player.name + " row " + str( n) + ", " + str(m) + " at " + str(i)) ...
def random_around(self): oplm = self.opposite.last_move plmX = oplm[C.GRIDX] plmY = oplm[C.GRIDY] x_min = max(C.START, plmX - C.STEP) y_min = max(C.START, plmY - C.STEP) x_max = min(self.board.size, plmX + 2) y_max = min(self.board.size, plmY + 2) find = ...
The function determines the next move in a game by checking for immediate winning conditions, strategic intersections, and specific patterns (e.g., 2-2, 1+0+1). If none apply, it falls back to random moves. It prioritizes winning moves, avoids forks, and uses heuristics to decide the optimal action based on the game st...
def find_move(self): # First step! Milestone! if self.last_move == (): self.random_around() else: # 1 - when 1 step last to win if self.n_m_ends(5, 2) or self.n_m_ends(5, 1) or\ self.n_m_ends(5, 0): return # interse...
def addClausesWithLabelInCellConstraint(self): for i in range(1, self.height + 1): for j in range(1, self.width + 1): variables = [self.convertLabel(i, j, character) for character in self.characters] self.exactOneConstraint(variables) def addClausesWithLinkConstraint(...
The code solves a SAT problem by adding constraints for label-in-cell, link, and clue rules, then checks satisfiability. It returns a result object with satisfiability status, solution, clause count, and solving time in milliseconds.
def solve(self): startTime = time.time() self.addClausesWithLabelInCellConstraint() self.addClausesWithLinkConstraint() self.addClausesWithClues() numberOfClause = len(self.clauses) result, satisfiable = self.satSolving() stopTime = time.time() return Res...
def sign_up(self): username = input("Enter username: ") password = input("Enter password: ") user, created = User.objects.get_or_create(username=username, defaults={'password': password}) if created: self.stdout.write(self.style.SUCCESS(f'User {username} signed up successfu...
This code implements a console-based booking system with a menu-driven interface, allowing users to sign up, log in, search flights, book tickets, and access admin functions, while maintaining a logged-in user state until exiting the system.
def handle(self, *args, **options): self.stdout.write(self.style.SUCCESS('Console Booking System')) self.logged_in_user = None # Initialize logged-in user as None while True: self.stdout.write("\n1. Sign Up") self.stdout.write("2. Log In") self.stdout.write(...
def set_row_kinds(self): def check_rows(): if len(self.rows) < 2: raise ColumnsException('Too few rows') if self.rows[1].is_all_separator(): self.rows[0].kind = Kinds.header del self.rows[1] check_rows() while not self.rows[-1].te...
This code initializes a table by processing input lines with specified column stops, creating TableRow objects, categorizing rows, determining column alignments, organizing column data, replacing calculated fields, and logging debug information for validation.
def __init__(self, lines, col_stops): self.rows = [TableRow(line, col_stops) for line in lines] self.set_row_kinds() self.col_alignment = self.find_column_alignments() self.organize_column_lists() self.replace_calc_fields() debug_table(f"cols: {col_stops}") debug_...
def chooseBesslerSpreads(): try: symbol = input("Enter Symbol: ").upper() topStrike = float(input("Enter TOP Strike: ")) bottomStrike = float(input("Enter BOTTOM Strike: ")) spreads.printBesslerSpreads(symbol, topStrike, bottomStrike) print("\nHit ENTER to start another Bess...
The function `menuOptions()` processes user input to navigate a menu system. It checks the first character of the input (b, c, p, s) to call corresponding functions for different spreads or account switching. If input is 'end', it exits with a prompt. Invalid inputs trigger an error message and re-prompt the user recur...
def menuOptions(): whatNow = input("-> ").lower() if whatNow.startswith("b"): chooseBesslerSpreads() elif whatNow.startswith("c"): chooseCallSpreads() elif whatNow.startswith("p"): choosePutSpreads() elif whatNow.startswith("s"): sw...
def __load_local_parameters__(self): default_values_file = os.path.join( self.execution_folder, "default.values.json") self.__load_parameters__(default_values_file) def __load_global_parameters__(self): for path in Path(self.current_folder).rglob('default.values.json'): s...
The code initializes a class instance by setting up a working directory, loading local and global parameters from files, and configuring AWS credentials. It establishes the current folder path, initializes parameter dictionaries, and prints loaded parameters for verification. The `set_aws_credentials()` method likely h...
def __init__(self, working_folder: str): self.current_folder = os.path.abspath(os.path.join(working_folder, '..')) self.__kube_config_file = "" self.working_folder = working_folder self.local_parameters = {} self.default_values = "" self.global_parameters = {} se...
def non_lfr_runs(algorithms): # Karate Club graph karate_g = generate_karate_club_graph() pos = nx.spring_layout(karate_g) results = [alg(karate_g) for alg in algorithms] partitions = [r[0] for r in results] metrics = [(coverage(karate_g, r[1]), performance(karate_g, r[1]), ...
The code runs community detection algorithms on different graph types, evaluates their performance (coverage, NMI, runtime), and saves results. It processes small graphs first, then generates LFR benchmark graphs for varying sizes, computes metrics for each algorithm, and stores data in JSON files. Command-line flags c...
def main(): global VERBOSE h, v, w, mu, mu_val = parse(' '.join(sys.argv[1:])) if h: print("- Use -v to activate Verbose") print("- Use -w to exclude the genetic algorithm from the run") print("- Use -mu value to set the value of mu in the graph generators; value should be in th...
def set_desired_columns(self) -> None: if len(self.desiredColumns) == 0: self.desiredColumns = ['measure-id'] + \ self.getSheetColumns(self.sheet1Name) + \ self.getSheetColumns(self.sheet2Name) def check_static_data_for_sheet(self, deviceSheetName) -> []: try:...
This function populates an appendix data structure with device-specific static data, ensuring column headers match predefined desired columns. It iterates through device names, retrieves their data, checks for column mismatches, and exits if discrepancies are found.
def fill_appendix_data(self) -> None: self.set_desired_columns() for device in self.device_name_list: deviceName = device[0] appendixData = self.check_static_data_for_sheet(deviceName) self.appendixData[deviceName] = appendixData if len(self.appendixData...
def shortest_path(self, location, goal): """ Finds shortest path between any location and centrenode using BFS """ graph = self.map.map_data['node_graph'] #keeps track of explored nodes explored = [] #keeps track of all paths to be checked queue = [[locati...
The main task of the code is for an agent to decide its next action in a simulated environment, prioritizing goal achievement by navigating markets, researching new locations, and purchasing products based on price and inventory constraints. It tracks turn progression, updates market/product information, calculates opt...
def take_turn(self, location, this_market, info, bm, gm): self.turn_tracker += 1 # store necessary information self.loc = location self.black_market = copy.deepcopy(bm) self.grey_market = copy.deepcopy(gm) for market, information in info.items(): if...
def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.fitting_equation_label.setText(_translate("MainWindow", "The fitting equation")) self.percentage_error_label.setText(_translate("Main...
This code sets up a graphical user interface (GUI) for a data analysis or signal processing application. It creates a window with split layouts to display equations, error metrics, and interactive graphs. The interface includes input controls (e.g., line edits, spin boxes, combo boxes) for parameters like chunk count, ...
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1241, 987) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout_main_window = QtWidgets.QHBoxLayout(self.centralwidget) ...
def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.label_extra.setText(_translate("MainWindow", "Precentage Slider for extrapolation")) self.label.setText(_translate("MainWindow", "Ent...
This code sets up a GUI for a data analysis tool, creating layouts with plots, sliders, input fields, and buttons. It initializes matplotlib figures for signal and error visualization, connects UI elements to functions for file handling, parameter updates, and error map generation, and organizes widgets using Qt layout...
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(829, 577) # MainWindow.setStyleSheet("background-color: rgb(229, 229, 229);") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.h...
def _initActionData(actionId, data, inputParams, envId): global _actions global _envs if actionId not in _actions: raise Exception("actionId '" + actionId + "' is not found") data = copy.deepcopy(_actions[actionId]) data["inputParams"] = inputParams ...
The main task of the code is to send an API request by initializing action data with given parameters, configuring HTTP variables, and executing the request. It takes an API name, variables, environment, and folder, processes them into a structured request, and returns the vendor's response. The function abstracts requ...
def request(apiName, variables={}, env=None, folder="default"): data = _initActionData(folder + '/' + apiName, {}, variables, env) # Prepare for request _configureHTTPVariables(data) vendorResponse = _makeRequest(data) return vendorResponse
def get_refill_cryptocompare_rates_df( currency : str, endpoint : str, ) -> pd.DataFrame: aux_min_time = read_mysql_query( table_name = 'cryptocompare_currencies_exchange_rates', query_type = 'get_min_time_query', time_column_name = 'time', )['min_time'][0] min_time = datetim...
The function inserts cryptocurrency exchange rate data into a specified MySQL table by fetching rates using a designated method, converting numpy types to Python types, and executing batch inserts with a built query. It returns 200 upon successful database updates.
def insert_rates_values( currency : str, table_name : str, endpoint : str, method : str, ): rates_df = get_refill_cryptocompare_rates_df(currency = currency, endpoint = endpoint) if method == 'refill' else get_fill_cryptocompare_rates_df(currency = currency, endpoint = endpoint) insert_query = b...
def _get_provider_per_lag(self, trip) -> list[dict, TicketProvider]: return [(leg, self._get_provider_from_key(leg["company"])) for leg in trip] def _all_tickets_are_available(self, leg_details: list[dict, TicketProvider]) -> bool: availabilities = [provider.is_ticket_available(leg) ...
This function books an entire journey by checking ticket availability, calculating total cost, verifying payment with billing info, and booking tickets. It returns a tuple indicating success/failure and ticket details or None if unsuccessful.
def book_journey(self, journey: dict[str, str], billing_information: dict) -> tuple[bool, list[dict]]: """ Books entire journey. Returns tuple of success state and the acquired ticket details which is a ``list[dict]``: ``(success, details)``. If success is ``...