dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def importLibs(self): from src.log import Log self.log = Log() def compareYamlConfig(self): from src.config import Config gitHubVersion = self.gitHubVersion() localVersion = self.localVersion() versionGithubApp = gitHubVersion[0] versionLocalApp = localVersion[0...
The main task of the code is to initialize and prepare a bot by importing libraries, configuring pyautogui settings, verifying system configurations and checking for updates if enabled, then waiting for user confirmation to start the bot, logging a startup message to the console.
def start(self): self.importLibs() pyautogui.FAILSAFE = False if self.config['app']['verify_version'] == True: self.compareYamlConfig() self.checkUpdate() self.getVersions() input('Press Enter to start the bot...\n') self.log.console('Startin...
def grabGaleforceChecks(): print(Fore.CYAN + "-------------------") print("Downloading latest Galeforce checks") galeforceChecks = pandas.read_csv('https://raw.githubusercontent.com/notanaccountant/Galeforce/fileHosting/checks.csv',delimiter=",") generateXLSX(galeforceChecks) def devGaleforceCheck...
The main task of the code is to handle command-line arguments for a Salesforce authentication tool, authenticate a user via web login, and retrieve XML data. It processes flags like -username, -mydomain, and -dev, sets up the SFDX environment, checks for SFDX installation, and executes appropriate actions based on argu...
def start(username): print(Fore.CYAN + "-------------------") cprint(figlet_format('GALEFORCE', font='big')) # Flags are fun index = 0 for item in argument_list: if item == "-username" or item == "-u": username = argument_list[index+1] if item == "-mydomain" or item == "...
def load_stop_words(self, filename): with open(filename) as file_object: for line in file_object: self.stop_words.append(line.strip()) def load_bookkeeping(self, filename): with open(filename) as file_object: for line in file_object: parts = line.s...
The main task of the code is to initialize a database by creating tables for words and pages, loading stop words and bookkeeping data, parsing webpages, and uploading processed words into the database with progress tracking. It prepares the database structure and populates it with word data from raw webpages, using sto...
def init(self): self.mysql_connector.create_words_table() self.mysql_connector.create_pages_table() self.load_stop_words('stopwords.txt') self.load_bookkeeping('resources/WEBPAGES_RAW/bookkeeping.tsv') self.parse_files() print("\rUploading words...\n") page_cou...
def delta_x(self, i, actual_conv_id, prev): if prev == '': prev = self.metric_lang_of_sents(i, actual_conv_id, ref_id_sent=-1, add=False) elif prev != self.metric_lang_of_sents(i, actual_conv_id, ref_id_sent=-1, add=False): return 1, prev return 0, prev def N_x(self, sent...
The main task of the code is to compute a value `eq` using parameters derived from `delta_x`, `N_x`, `native_x`, and `P_x`, while updating the `prev` state. It first calculates `d_x` and `N`, checks if `N` is zero (returning 0 if true), then computes `eq` as `1 + d_x - (native_x + P_x)/N`, finally returning `eq` and th...
def inner_func(self, i, actual_conv_id, prev): d_x, prev = self.delta_x(i, actual_conv_id, prev) N = self.N_x(i, actual_conv_id) if not N: return 0, prev eq = 1 + d_x - (self.native_x(i,actual_conv_id) + self.P_x(i, actual_conv_id))/N return eq, prev
def is_code_choice(self, token, actual_conv_id): """ This function checks each word type into 5 classes stary_chars - encoding != utf8 self.eng_lexion and self.native_lexion -- lexicon words with frequencies """ obj = str.maketrans('', '',string.punctuat...
This method generates code-mixed sentences by analyzing token-level language choices in reference utterances. It filters sentences identified as code-mixed, then constructs English and Hindi matrix representations from these sentences for subsequent matrix-level analysis.
def create_cm_sents(self): """ Creating a list of code-mixed sentences to create a list of hindi matrix and english matrix senteneces MUST BE CALLED BEFORE ANY METRICS ON MATRIX LEVEL """ for i in range(len(self.cm_utter.index_ref_utter)): doc=nlp(self.cm_utter.ref_u...
def remove_name(self, sentence): """ this function removes the name of the speaker """ # sentence = sentence.text.strip() try: index = sentence.index(':') except ValueError: return sentence return sentence[ index + 1:] def N_x(self, sent, ...
The code calculates the CMI-Index (Cc and Cavg) and I-index for code-mixed utterances in a conversation. It processes each utterance to compute Cu(x) values, averages them (Cavg), derives Cc using a weighted sigma formula, and calculates the I-index by averaging integration scores across conversations. The metrics quan...
def code_mixed_statistics(self): """ Calculating CMI-Index (Cc and Cavg), and I-index) """ for i in range(len(self.total_utter.index_ref_utter)): doc=nlp(self.total_utter.ref_utter[self.total_utter.index_ref_utter[i][0]][self.total_utter.index_ref_utter[i][1]]) ...
def check_random_state(seed): """Turn seed into a np.random.RandomState instance Parameters ---------- seed : None, int or instance of RandomState If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance seeded with seed. ...
The main task of the code is to compute initial non-negative matrix factorization (NMF) approximations for a given data matrix $ X $ by generating initial guesses for matrices $ W $ and $ H $ such that $ X \approx WH $. It supports multiple initialization methods, including random initialization and variants of NNDSVD,...
def _initialize_nmf(X, n_components, init="warn", eps=1e-6, random_state=None): """Algorithms for NMF initialization. Computes an initial guess for the non-negative rank k matrix approximation for X: X = WH. Parameters ---------- X : array-like of shape (n_samples, n_features) The data m...
def _getSuccessorsA(self, statep): st, state = statep for action in ['Dig', 'Super Potion']: yield (1, state, action) def _getSuccessorsB(self, statep): st, state, action = statep dist = ddict(frac) for eact, p in [('Water Gun', frac(64, 130)), ('Bubblebeam', frac(66, 130))]: priority1 = state[0].stats....
The function retrieves or computes successors for a given state. It checks a cache first; if absent, it uses private methods (_getSuccessorsA/B/C) based on the state's first element (0, 1, or 2), sorts results by descending distance and ascending name, caches the result, then returns it.
def getSuccessors(self, statep): try: return self.successors[statep] except KeyError: st = statep[0] if st == 0: result = list(self._getSuccessorsA(statep)) else: if st == 1: dist = self._getSuccessorsB(statep) elif st == 2: dist = self._getSuccessorsC(statep) result = sorted(dist.item...
def scale2d_inv(sx, sy, **kwargs): return scale2d(1 / sx, 1 / sy, **kwargs) def rotate2d_inv(theta, **kwargs): return rotate2d(-theta, **kwargs) def translate2d_inv(tx, ty, **kwargs): return translate2d(-tx, -ty, **kwargs) def matrix(*rows): assert all(len(row) == len(rows[0]) for row in rows) elems...
The code performs image augmentation by applying random geometric and color transformations to input images. It introduces horizontal/vertical flips, rotations, translations, scaling, and anisotropic scaling, along with brightness, contrast, luma flipping, hue shifts, and saturation adjustments. Transformation paramete...
def __call__(self, images): N, H, W, C = images.shape labels = [jnp.zeros([images.shape[0], 0])] make_key = lambda : self.make_rng('augment') # --------------- # Pixel blitting. # --------------- if self.xflip > 0: w = randint(make_key(), [N, 1, 1,...
def _loge(self, message): if self._is_logging: print(f"ERROR: {message}") def _is_ipv4(self, ipv4): if self.ipv4_re.match(ipv4): return True return False def _query(self, params): status = 0 json_data = "" raw_data = self._http_request(TorSeeker.T...
This function queries Tor relays using provided IPv4 addresses, validates inputs, and returns 1 for successful queries or 0 for invalid IPs/no results. It checks each IP in the list, logs errors for invalid formats, and breaks on failure. The return value indicates overall query success status.
def query_relays_by_ip(self, ip_addresses=None): """Query for Tor relays based on one or multiple Tor IP addresses. This functions performs input validation to verify that the IP addresses provided are valid IPv4 format. If 0 is returned, then the IP addresses specified are invalid or th...
def skip(name): if name=='__init__.py': return True else: return False def isCode(name): result = os.path.splitext(name)[-1] if result in include: return True if (result in exclude): return False if (result is None): return False def shapeVertex(...
The function recursively traverses a directory structure starting from the given address, generating a graph representation (e.g., for visualization tools like Graphviz). It creates clusters for directories, writes styled nodes for code files (filtered by `skip()` and `isCode()`), and invokes `writeGraph()` to define e...
def walkFiles(adress, way, vertexes, edges): global n n += 1 way = way + "/" + adress cat = os.listdir(way) vertexes.write("subgraph cluster_" + str(n) + " {\n") vertexes.write("node [style=\"filled\", " + "shape=\"box\", " + "color=\"#dfe0df\", " + ...
def skip(name): if name=='__init__.py': return True else: return False def isCode(name): result = os.path.splitext(name)[-1] if result in include: return True if (result in exclude): return False if (result is None): return False def writeGraph(c...
This function traverses directories to analyze code files, counting inter-file calls and aggregating dependencies into a folder-level graph structure. It recursively processes subdirectories, skips non-code files, and uses helper functions to build vertex-edge representations of file interactions, consolidating cross-f...
def walkfiles_cross_files(adress, way, vertexes, edges): ''' count calls among files and conclude them on the folder node ''' way = way + "/" + adress cat = os.listdir(way) for obj in cat: if (os.path.isdir(way+"/" + obj)): walkfiles_cross_files(obj, way, vertexes...
def walkFiles(adress, way, vertexes, edges): global n n += 1 way = way + "/" + adress cat = os.listdir(way) vertexes.write("subgraph cluster_" + str(n) + " {\n") vertexes.write("node [style=\"filled\", " + "shape=\"box\", " + "color=\"#dfe0df\", " + ...
This function recursively traverses directories starting from a given path, identifies code files, and constructs a graph (vertexes/edges) by processing relevant files. It skips non-code files and optionally filters vertices based on predefined criteria. The traversal increments a global counter and uses a global flag ...
def walkFiles_without_nodes(adress, way, vertexes, edges): global n n += 1 way = way + "/" + adress cat = os.listdir(way) for obj in cat: if (os.path.isdir(way+"/" + obj)): walkFiles(obj, way, vertexes, edges) else: if skip(obj): ...
def getColor(name): # if name in sorted_vertex.keys(): # return "olive" #(sorted_vertex.keys()) if name in sorted_vertex.keys(): return fixedColors.get(sorted_vertex[name]) return "white" def walkfilesfirst(file): ''' walk among all files and get all names ''' g...
This code generates a DOT graph visualizing file relationships by analyzing connections between files, applying PageRank for node ranking, and outputting the result to a specified file. It processes input files, counts inter-file calls, builds a directed graph, and writes nodes/edges with customizable parameters like e...
def initialize_File_graph(ori,**params): global func func=params['func'] # show important edges in the file global show_important_edge show_important_edge=True # clear txts global clearFiles clearFiles = True global show_all # show all vertexes or main ones # show all ed...
def getColor(name): # if name in sorted_vertex.keys(): # return "olive" #(sorted_vertex.keys()) if name in sorted_vertex.keys(): return fixedColors.get(sorted_vertex[name]) return "white" def walkfilesfirst(file): ''' walk among all files and get all names ''' g...
This code generates a directed graph visualization of file/folder structures using Graphviz, with customizable options for displaying nodes/edges, highlighting important cross-module calls, and outputting the graph in specified formats. It processes input files, builds a hierarchy, writes graph definitions to temporary...
def initialize_Multi_graph(ori,**params): global func func=params['func'] # show important edges in the file global show_important_edge show_important_edge=True # clear txts global clearFiles clearFiles = True global show_all # show all vertexes or main ones # show all edges ...
def getColor(name): # if name in sorted_vertex.keys(): # return "olive" #(sorted_vertex.keys()) if name in sorted_vertex.keys(): return fixedColors.get(sorted_vertex[name]) return "white" def walkfilesfirst(file): ''' walk among all files and get all names ''' g...
The code generates a DOT graph representation of a file structure, configuring visualization parameters, building nodes/edges, and outputting the graph to a file. It handles community detection, filters nodes/edges based on parameters, and renders the graph using tools like `dot` or `twopi`, with options for highlighti...
def initialize_graph(ori,**params): global func func=params['func'] # show important edges in the file global show_important_edge show_important_edge=False # clear txts global clearFiles clearFiles = True global show_all # show all vertexes or main ones # show all edges ...
def table(self, num, param): self.hide_labels() if param == "p": if num == 1: self.l1_functions("l1_p") if num == 2: self.l2_functions("l2_p") if num == 3: self.l3_functions("l3_p") if num == 12: ...
The function updates the UI based on checkbox states, specifically handling the 'l1' checkbox. If checked, it replaces the graph with a new instance using parameter 1, updates the table, and displays the x-axis. It also triggers additional checks and updates for other checkboxes (l2, l3). If 'l1' is unchecked, it condi...
def l1_checked(self, parameter): if self.checkBox_l1.isChecked(): self.graph.close() self.graph = Graph(self.data_ram, 1, parameter) self.table(1, parameter) self.layout_graph.addWidget(self.graph) self.graph.show() self.x_axis.show() ...
def table(self, num, param): self.hide_labels() if param == "p": if num == 1: self.l1_functions("l1_p") if num == 2: self.l2_functions("l2_p") if num == 3: self.l3_functions("l3_p") if num == 12: ...
This function updates the UI based on checkbox states. It creates or updates a graph (Graph) with specific parameters (1, 2, 3, or 13) and adjusts table/widget visibility. It checks l2 checkbox state first, then applies conditional logic for all checkbox combinations, closing/recreating graphs and hiding/showing elemen...
def l2_checked(self, parameter): if self.checkBox_l2.isChecked(): self.graph.close() self.graph = Graph(self.data_ram, 2, parameter) self.table(2, parameter) self.layout_graph.addWidget(self.graph) self.graph.show() self.x_axis.show() ...
def table(self, num, param): self.hide_labels() if param == "p": if num == 1: self.l1_functions("l1_p") if num == 2: self.l2_functions("l2_p") if num == 3: self.l3_functions("l3_p") if num == 12: ...
The code manages UI updates based on checkbox states for graph levels (1, 2, 3). When checkBox_l3 is checked, it replaces the graph with level-3 data, updates the table, and adjusts layout. It calls helper methods to handle level-specific logic. If no checkboxes are selected, it hides the graph and labels. If only l1 o...
def l3_checked(self, parameter): if self.checkBox_l3.isChecked(): self.graph.close() self.graph = Graph(self.data_ram, 3, parameter) self.table(3, parameter) self.layout_graph.addWidget(self.graph) self.graph.show() self.x_axis.show() ...
def l1_checked(self, parameter): if self.checkBox_l1.isChecked(): self.graph.close() self.graph = Graph(self.data_ram, 1, parameter) self.table(1, parameter) self.layout_graph.addWidget(self.graph) self.graph.show() self.x_axis.show() ...
The code initializes a UI for data visualization, reads and processes CSV data, applies outlier detection, sets up interactive graph controls, and connects UI elements to toggle data parameters and outlier visibility.
def __init__(self): super().__init__() self.setupUi(self) "Reads data base and sets outliers out" self.data = pd.read_csv('output.csv', parse_dates=True) self.data["time"] = self.data["time"].str.slice(start=7, stop=-13) self.data_outliers = self.data.copy() self...
def l1_checked(self, parameter): if self.checkBox_l1.isChecked(): self.graph.close() self.graph = Graph(self.data_ram, 1, parameter) self.table(1, parameter) self.layout_graph.addWidget(self.graph) self.graph.show() self.x_axis.show() ...
The main task of the code is to execute three validation checks on a given parameter using methods l1_checked, l2_checked, and l3_checked sequentially. The function 'tik' triggers these checks, likely ensuring the parameter meets specific criteria defined in each method.
def tik(self, parameter): self.l1_checked(parameter) self.l2_checked(parameter) self.l3_checked(parameter)
def generate_labelbox_client(api_key=None): if api_key is None: api_key = os.getenv('LABELBOX_API_KEY') client = lb.Client(api_key=api_key) return client def create_metadata_fields( client=None, ): if client is None: client = generate_labelbox_client() metadata_ontology = client....
The function creates a Labelbox project for identifying people in videos using a specified inference ID. It checks if the project already exists; if not, it generates an ontology (if missing), creates a dataset (if missing), and sets up the project with the ontology. Key parameters include video processing settings, da...
def create_project( inference_id, ontology_id=None, person_descriptions=None, unusuable_bounding_box_label='Unusable bounding box', person_feature_schema_id=None, dataset_id=None, start=None, end=None, environment_name=None, environment_id=None, video_duration=datetime.timede...
def generate_alphapose_output_directory_path( inference_id, camera_id, start, end, video_duration=datetime.timedelta(seconds=10), alphapose_output_parent_directory='/data/alphapose_output', ): output_start, output_end = pose_labelbox.utils.generate_output_period( start=start, ...
The function parses AlphaPose output files for specified cameras, generating structured parsed outputs by processing JSON results, skipping existing files, and organizing data by inference ID, camera ID, and time intervals.
def parse_alphapose_output( inference_id, start, end, environment_id=None, environment_name=None, camera_ids=None, camera_part_numbers=None, camera_serial_numbers=None, camera_names=None, video_duration=datetime.timedelta(seconds=10), frame_period=datetime.timedelta(milliseco...
def create_test_user(): """ Create Foo user """ users = [{ 'username': 'foo', 'password': 'bar', 'first_name': 'Foo', 'last_name': 'Bar', 'email': 'ldzyk@example.com', }] for user in users: create_user(user) def create_second_test_user(): users = [...
The main task of the code is to set up a test environment by creating two test users, logging in with the first user's credentials, and generating a sample todo item. This prepares necessary data and authentication context for testing functionality related to user interactions and todo management, ensuring each test ru...
def setUp(self): self.user = create_test_user() self.user2 = create_second_test_user() self.client.login(username='foo', password='bar') self.todo = create_todo_for_test_user('test-toggle')
def generate_audio(voice_id, text): payload = {"text": text, "voice_settings": {"stability": 0, "similarity_boost": 0}} response = _post(f"/text-to-speech/{voice_id}/stream", json_data=payload) return response.content def voice_id(self): return self._data["voice_id"] def play_audio( audio_data, ...
The main task of the code is to generate audio from input text using a specified voice and play it, with an option to play the audio in the background. The function converts text to speech via `generate_audio` and handles playback through `play_audio`, enabling background playback when enabled.
def say(self, text, background=False): data = generate_audio(self.voice_id(), text) play_audio(data, background=background)
def parseFED1356(eventData): console.print("FED #1356") console.print() FED1356Data = eventData.split('\nFED# 1405')[0] FED1356Data = FED1356Data.split('\n')[1:] CICADASection = '' for line in FED1356Data: #This is deliberately flipped word order #We read these words r...
The function `dumpEvent` logs the current run and event numbers, parses specific data from `eventData` using `parseFED1356` and `parseFED1405`, and optionally writes emulator information to a ROOT file if `rootFile` is provided.
def dumpEvent(index, eventData, runTuple, rootFile): console.rule(f'Run: {runTuple[0]:>10d}, Event: {runTuple[1]:>10d}') #console.print(eventData) parseFED1356(eventData) parseFED1405(eventData) if rootFile is not None: dumpEmulatorInfo(rootFile, index)
def parseRLE(eventData): eventStrings = re.findall( 'Run [0-9]+, Event [0-9]+, LumiSection [0-9]+', eventData, ) RLETuples = [] for eventString in eventStrings: RLE = re.findall( '[0-9]+', eventString ) RLETuples.append( ( ...
The main task of the code is to parse raw data from a file into structured event and run information, validate consistency between parsed event counts and run data, and process each event using the dumpEvent function, potentially writing results to a ROOT file if specified. The code ensures data integrity by checking f...
def main(args): with open(args.file) as theFile: data = theFile.read() #Okay, our first job is to parse this set of nonsense into a set of events we can read runs = parseRLE(data) console.print(f'Processed {len(runs):>6d} FED dumps') eventData = parseEvents(data) if len(runs) != len(even...
def _dataset_exists(dataset_dir): """ Check if TF-Recoed exists. Args: dataset_dir: dataset directory. Returns: True: TF-Recode are exist. False: TF-Recodes are not exist. """ for split_name in ['train', 'validation']: for shard_id in range(_NUM_SHARDS): ...
The main task of the code is to process a dataset by unzipping files, splitting image data into training and validation sets, converting them into a structured format, generating label mappings, and cleaning up temporary files. It prepares a dog vs. cat classification dataset for machine learning use, ensuring proper d...
def main(): parser = argparse.ArgumentParser() parser.add_argument('zip_file', help='Path to data zip file.') parser.add_argument('dataset_dir', help='Path to dataset dir.') args = parser.parse_args() if not tf.gfile.Exists(args.dataset_dir): tf.gfile.MakeDirs(args.dataset_dir) if _dat...
def send_message(self, name: str, msg: str): """ Sends message to peer by name. :param name: Name of peer to send message to. :param msg: Message to be sent to the peer. """ if name not in self.connections.keys(): if name in self.known_peers.keys(): ...
The code processes incoming messages from peers, specifically handling built-in 'PEERLIST' commands (REQ/UPD) to either send a peer list or update peer information. It includes debug logging to indicate received messages, marking them as handled if processed. The function is designed to be extended by subclasses for cu...
def process_message(self, name: str, message: str, handled: bool): """ Intended to be overridden by a child Object to process incoming messages, here to maintain debug printing. :param name: Name of peer the message originated from. :param message: Message received from peer. :p...
def _update_size(self, *largs, **kwargs): # Extract kwargs parent = self.parent px,py = 0.0,0.0 if parent is None: parent = Window elif parent is not Window: px,py = parent.pos # Calculate own width and height pWidth, pHeight = parent.size...
This method performs layout initialization for a UI component by clearing the canvas, updating dimensions, calculating tab sizes, and drawing the background. It initializes the first tab if not already loaded, iterates through tabs to draw them, sets their content size/position, and adjusts text font sizes. The comment...
def do_layout(self, *largs, **kwargs): self.canvas.before.clear() self._update_size() self._calcTabSize() self.drawBackground() #self.drawChevron([200,200], [200,200], [10,10], 20, True, [1,0,0,1]) if not self.loaded and len(self.tabs) > 0: self.loaded = Tru...
def nov2plp(nov, kernel_size = 3, plp_num = 1, Fs_nov = 100, H = 10, Theta =np.arange(30, 301) ): """ Compute PLP curves from input novelty function Parameters ---------- nov : (np.ndarray) A novelty function such as output of onset detection or network activation. kernel_s...
This function estimates beat positions in seconds from an activation function using post-processing methods (e.g., DP, SPPK, HMM) based on the specified post_type. It applies peak detection, tempo-based sequence computation, or probabilistic models to derive beats, adjusting parameters like BPM range and tempo factors....
def acti2Est(max_acti, post_type, min_bpm = 30, max_bpm =300, dp_meantempo = None, fps = 100, dp_factor = 5, ): """ Get beat estimation based on input max-acti and the assigned post_type (PPT) Parameters ---------- max_acti : (np.ndarray) Activation function of novelty fu...
def get_events(self): """Returns all Event objects in sequential order associated with the fast5 file. Parameters ---------- Returns ------- events : [Event] ili numpy.array All events in sequential order """ if self._events is not N...
This function generates Nanopolish-formatted event data from a FAST5 file by processing overlapping event windows, creating new event objects, and caching results for efficiency. It returns sequential Event objects converted to Nanopolish format using internal data and alignment information.
def get_nanopolish_events(self): """Returns all Event objects in sequential order associated with the fast5 file converted to nanopolish output. Parameters ---------- Returns ------- events : [Event] ili numpy.array All events in sequential order ...
def update_animation(self): #update animation # case of mob idle if self.action == 0: animation_cooldown = 300 # case of mob walk elif self.action == 1: animation_cooldown = 170 # case of mob jump elif self.action == 2: animatio...
The code's main task is to update a game entity's state by refreshing its health bar, animating movements, checking survival status, and handling movement logic, ensuring real-time updates for visual and functional game mechanics.
def update(self): self.health_bar.update() self.update_animation() self.check_alive() self.handle_movement()
def handle_skill(self, skill): big_star_skill = Skill(self.rect.centerx + (0.6 * self.rect.size[0] * (self.direction * - 1)), self.rect.centery, self.direction, skill) self.skills_group.add(big_star_skill) def play_sound(self, dir_name, sound): soundObj = pygame.mixer.Sound(f'sprites/sounds/{dir...
This function updates the player's animation based on their current action state (idle, jump, walk, attack, etc.), applying specific animation cooldowns for each action. It triggers skills (e.g., "big_star"), resets frames when animations complete, and updates the displayed image. Special handling includes adjusting co...
def update_animation(self): #update animation # case of player idle if self.action == 0: animation_cooldown = 800 # case of player jumps elif self.action == 1: animation_cooldown = 170 # case of player walks elif self.action == 2: ...
def update_animation(self): #update animation # case of player idle if self.action == 0: animation_cooldown = 800 # case of player jumps elif self.action == 1: animation_cooldown = 170 # case of player walks elif self.action == 2: ...
This code updates an entity's health bar, animation, cooldowns, and checks its alive status during each frame or update cycle in a game or simulation.
def update(self): self.health_bar.update() self.update_animation() self.handle_cooldown() self.check_alive()
def valid_args(args): """ validates input arguments to make sure exists and min_sup and min_conf are both between 0-1 """ if len(args) != 3: return False try: dataset_file, min_supp, min_conf = args min_supp = float(min_supp) min_conf = float(min_conf) if min_...
The main task of the code is to implement the Apriori algorithm for association rule mining. It reads a transaction dataset, identifies frequent itemsets using minimum support thresholds, generates candidate itemsets iteratively, calculates confidence for potential rules, filters those meeting minimum confidence, and o...
def main(): args = tuple(sys.argv[1:]) # error message if the arguments are invalid if not valid_args(args): # TODO print("Invalid arguments.") print("Usage: python3 run.py INTEGRATED-DATASET.csv <min_sup> <min_conf>") return dataset_file, min_supp, min_conf = args min_supp ...
def two_d_convert(num): if num < 20: #validate if number fit requirement for dictionary 1 return (_Ones[num]) #This should able to convert number with in 1-19 else: tens, ones = [(num//(10**i))%10 for i in range(math.ceil(math.log(num, 10))-1, -1, -1)] #Program fr...
This code converts a numerical input (raw_num) into a textual representation of dollars and cents. It splits the number into whole and decimal parts, processes each segment using range-specific conversion functions (e.g., two_d_convert, three_d_convert), and formats the output with proper grammatical structures. It han...
def convert(raw_num): global display num1 = "" num2 = "" display = '' try: if "." in raw_num: split_num = raw_num.split(".") num1, num2 = split_num num1 = int(num1) num2 = num2[0:3] num2 = int(num2)/(10**len(num2)) #print(num2) num2 = round(num2, 2) #print(...
def _repopulate_instance_random_select_pool(self): self._instance_random_select_pool = list(range(len(self._instance_images))) self.random.shuffle(self._instance_random_select_pool) def _create_new_image_metadata(dataset: ShipRSImageNet, image_name: str, image_metadata: 'list[dict[str,str|int]]'): i...
The main task of the code is to augment a ShipRSImageNet dataset by adding a specified number of instances to selected images, adhering to constraints on minimum and maximum instances per image. It copies the original dataset, distributes the required instances across images, generates new annotations, and saves the au...
def augment(self, dataset: ShipRSImageNet, output_path: str, images_to_augment: 'list[str]', total_instances_to_add: int, min_instances_per_image: int, max_instances_per_image: int): if max_instances_per_image * len(images_to_augment) < total_instances_to_add: raise ValueError(f"Cannot add {total_in...
def update_obs(self): self.inventory_by_item.clear() self.inventory_by_slot.clear() self.trees.clear() self.crafting_tables.clear() self.obs = self.sense_all() for slot in self.obs['inventory']: if str(slot).isdigit(): slot = str(slot) ...
The main task of the code is to automate resource collection and crafting in a Minecraft-like environment. The agent observes the game state, collects 3 logs by breaking trees, moves to a crafting table, and crafts items (sticks, planks, and a sack) using predefined commands. It transitions between high-level states (S...
def plan(self): self.update_obs() # check for Game over if str(self.obs['gameOver']).startswith('true'): self.reset_all() self.update_obs() return if str(self.obs['goal']['goalAchieved']).lower().startswith('true'): print("SUCCEEDED") ...
def _toast(self, message): Toast.makeText( activity, cast('java.lang.CharSequence', AndroidString(message)), Toast.LENGTH_LONG ).show() def _build_notification(self, title): if SDK_INT < 26: noti = NotificationBuilder(activity) else: self._channel = self._build_notification_channel(title) noti...
This function handles Android notification creation and display. It encodes input strings, checks for toast requests, builds notifications with titles/messages/tickers, sets icons and behavior, then displays the notification.
def _notify(self, **kwargs): noti = None message = kwargs.get('message').encode('utf-8') ticker = kwargs.get('ticker').encode('utf-8') title = AndroidString( kwargs.get('title', '').encode('utf-8') ) icon = kwargs.get('app_icon') if kwargs.get('toast'): self._toast(message) return else: noti...
def _block_gibbs_sample(self, v: torch.Tensor = None, h: torch.Tensor = None, clamp: torch.Tensor = None, n_gibbs = 1, add_noise = True, begin_from_randn_init = True): """ Familiar block Gibbs sampling method of visible...
This function computes the total gradient by combining the Contrastive Divergence (CD) loss gradient with an adversarial gradient. It performs Gibbs sampling to generate model samples, calculates positive and negative energy gradients, and blends them using a weighted average. The adversarial component leverages a crit...
def _total_grad(self, v: torch.Tensor, n_gibbs = 1, gamma = 1.0): """ Combines the CD loss gradient with the adversarial gradient as described in https://arxiv.org/abs/1804.08682. @args - v: np.array ~ (batch_size, n_vis) - n_gibbs: int << number of Gibbs sampling steps...
def _block_gibbs_sample(self, c: torch.Tensor, v: torch.Tensor = None, h: torch.Tensor = None, clamp: torch.Tensor = None, n_gibbs = 1, add_noise = True): """ Familiar block Gibbs sampling method of visible and hidden units. @args ...
This function computes the contrastive divergence (CD) loss for adversarial training in a neural network model. It samples from data (v_data, h_data) and a model (v_model, h_model) using Gibbs sampling, calculates the energy difference between them, and applies adversarial gradient adjustments using a critic network. T...
def cd_grad_adversarial(self, optimizer: torch.optim.Optimizer, v: np.ndarray, c: np.ndarray, gamma: float = 1, n_gibbs: int = 1): """ Computes the contrastive divergence loss with which parameters may be updated via an optimizer. Follows Algorithm 3 of https://arxiv.org/pdf/221...
def reset_seed(self, seed: int): """ Resets the rng seed to enforce reproducibility after training. @args - seed: int """ self.rng.manual_seed(seed) def reconstruct(self, v: np.ndarray, c: np.ndarray, clamp: np.ndarray = None, random_init = True, ...
The code trains a probabilistic model to learn the conditional distribution $ P(X|y) $, handling missing data via imputation and adversarial learning. It uses stochastic gradient descent (SGD) with optional learning rate reduction, alternating between reconstruction loss and adversarial gradient updates. Metrics like r...
def fit_adversarial(self, X: np.ndarray, y: np.ndarray, n_gibbs: int = 1, lr: float = 0.1, n_epochs: int = 1, batch_size: int = 1, fail_tol: int = None, rng_seed: int = 0, gamma: float = 1, gamma_delay: int = 0, verbose_interval: int = None, reduce_lr_on_plateau = False,...
def reset_seed(self, seed: int): """ Resets the rng seed to enforce reproducibility after training. @args - seed: int """ self.rng.manual_seed(seed) def reconstruct(self, v: np.ndarray, c: np.ndarray, clamp: np.ndarray = None, random_init = True, ...
The `fit` method trains a probabilistic model to learn $ P(X \mid y) $ using PyTorch's autograd, handling missing data in $ X $ via Gibbs sampling. It optimizes parameters with Adam, processes data in batches, and employs learning rate reduction on plateaus. The model minimizes reconstruction error (MSE) and KL diverge...
def fit(self, X: np.ndarray, y: np.ndarray, n_gibbs: int = 1, lr: float = 0.1, n_epochs: int = 1, batch_size: int = 1, fail_tol: int = None, rng_seed: int = 0, verbose_interval: int = None, reduce_lr_on_plateau = False, checkpoint_path = None): """ Built...
def reset_seed(self, seed: int): """ Resets the rng seed to enforce reproducibility after training. @args - seed: int """ self.rng.manual_seed(seed) def reconstruct(self, v: np.ndarray, clamp: np.ndarray = None, randn_init = True, n_gibbs: int = 1, ad...
This method trains a neural network model using PyTorch autograd, handling missing data via reconstruction, adversarial training with a critic, and tracking metrics like reconstruction MSE and KL divergences. It employs Adam optimization, learning rate scheduling, and checkpointing, with robustness to NaNs in input dat...
def fit(self, X: np.ndarray, n_gibbs: int = 1, lr: float = 0.1, n_epochs: int = 100, batch_size: int = 10, gamma: float = 1.0, gamma_delay: int = 10, fail_tol: int = None, rng_seed: int = 0, verbose_interval: int = None, reduce_lr_on_plateau = False, checkpoint_path = No...
def scan(self, code): self.current_order[code] += 1 self.current_codes.append(code) name = self.items[code].name price = self.format_money(self.items[code].price) self.box.insert(tk.END, f'{name:<{self.MAX_NAME_WIDTH}}' + f'{price:>{self.MAX_PRICE_WIDTH+10}}') self.box.se...
This code initializes a Point of Sale (POS) GUI interface using Tkinter. It sets up item buttons, a listbox to display selected items, labels for cashier info and time, checkout/till buttons, and calculates tax. The interface allows scanning items, modifying orders via double-click, and managing totals, with a focus on...
def __init__(self, parent): self.parent = parent parent.title('Point of Sale') self.font = ('Courier New', 12) self.till = 0 self.TAX = 0.08 self.items = {'lemonade':Item('Lemonade', 50, tk.Button(root, ...
def redraw(window, board): global width global height # for GetWindowSize to work, we need to convert the width and height into separate ctype variables width_p = ctypes.c_int() height_p = ctypes.c_int() sdl2.SDL_GetWindowSize(window, width_p, height_p) print("New size of the window is",...
The function `end_screen` displays a game-ending screen (winner, tie, or loser) based on the `ending` parameter, renders "New Game" and "Quit" buttons, and handles user interactions. It updates the screen, manages window resizing, and triggers actions like restarting the game or exiting. The function returns `1` when t...
def end_screen(ending, board): window_surface = sdl2.SDL_GetWindowSurface(window) spriterenderer = factory.create_sprite_render_system(window) global NewGameClicked NewGameClicked = 0 # select the ending graphic based on how the game ended if ending == 1: end_type = textures["...
def calculate_hash(key): sha1_hash = hashlib.sha1(key.encode()).hexdigest() return int(sha1_hash, 16) % TOTAL_NODES def fetch_succ_nodes(self, key_id, num_nodes): nodes = [self.node_address] curr_node = self.successor for _ in range(num_nodes - 1): if curr_node == self.node_a...
The function sequentially replicates a file to multiple successor nodes determined by its hash. It acquires a lock before uploading the file to each node (without further replication) and releases the lock afterward, ensuring exclusive access during each upload to prevent conflicts.
def replicate_file_sequential(self, filename): file_id = calculate_hash(filename) successor_nodes = self.fetch_succ_nodes(file_id, 3) for node in successor_nodes: self.acq_lock(filename) self.upload_file(filename, node, replicate=False) self.release_lock(filen...
def calculate_hash(key): sha1_hash = hashlib.sha1(key.encode()).hexdigest() return int(sha1_hash, 16) % TOTAL_NODES def fetch_succ_nodes(self, key_id, num_nodes): nodes = [self.node_address] curr_node = self.successor for _ in range(num_nodes - 1): if curr_node == self.node_a...
This function replicates a file across multiple nodes in a distributed system. It calculates a file's hash to determine successor nodes, acquires a lock to ensure consistency, uploads the file to each of the three successor nodes with replication enabled, and then releases the lock. The process ensures linearizable rep...
def replicate_file_linearizable(self, filename): file_id = calculate_hash(filename) successor_nodes = self.fetch_succ_nodes(file_id, 3) self.acq_lock(filename) for node in successor_nodes: self.upload_file(filename, node, replicate=True) self.release_lock(filename)
def join_handler(self, connection, address, r_list): if r_list: peer_ip_port = r_list[1] peer_id = calculate_hash(peer_ip_port[0] + ":" + str(peer_ip_port[1])) old_predecessor = self.predecessor self.predecessor = peer_ip_port self.predecessor_id = pee...
The code handles incoming network connections by determining the connection type from received data. It routes requests to specific handlers for tasks like joining a network, file transfer, predecessor/successor updates, ID lookups, lock requests, and F-table modifications. Responses include sending predecessor/success...
def conn_handler(self, connection, address): r_list = pickle.loads(connection.recv(self.buffer_size)) connection_type = r_list[0] if connection_type == 0: self.join_handler(connection, address, r_list) self.displayMenu() elif connection_type == 1: sel...
def replicate_file_eventual(self, filename): file_id = calculate_hash(filename) successor_nodes = self.fetch_succ_nodes(file_id, 3) for node in successor_nodes: self.upload_file(filename, node, replicate=False) def replicate_file_sequential(self, filename): file_id = calculat...
This method replicates a file using a specified consistency strategy. If none is provided, it defaults to the instance's strategy. Depending on the strategy type (EVENTUAL, SEQUENTIAL, or LINEARIZABLE), it delegates replication to corresponding methods: replicate_file_eventual, replicate_file_sequential, or replicate_f...
def replicate_file(self, filename, consistency_strategy=None): if consistency_strategy is None: consistency_strategy = self.consistency_strategy if consistency_strategy == ConsistencyStrategy.EVENTUAL: self.replicate_file_eventual(filename) elif consistency_strategy == C...
def encrypt_data(filename, key): """ :param filename: file name/ file name with path to encrypt :param key: key(private/public) file to encrypt or decrypt the data :return: None """ ecb_key = Random.new().read(8) des_cipher = DES.new(ecb_key, DES.MODE_ECB) public_key = RSA.import_key(ope...
This script provides RSA-based file encryption/decryption and network file transfer functionalities. It supports five modes: encrypting files (`enc`), decrypting files (`dec`), generating RSA keys (`gen`), sending files over HTTPS (`send`), and receiving files via a client (`client`). The tool uses command-line argumen...
def main(): parser = argparse.ArgumentParser("filecryptor", description=('Description: Script to Help Encrypt and Decrypt File Using RSA Key.' '\n\n' '\tpython -m filecryptor --m ...
def get_repositories_from_api(self) -> [Repository]: """Get repositories from GH API""" page = 1 while True: repos_data = self.get(f"{self.config.gh_url}/orgs/<orga>/repos", query_params={'page': page, 'sort': 'updated', 'per_page': 50}) if len(repos_data) == 0: ...
The code's main task is to fetch and update repository data from an API, toggle their active status based on last activity, and synchronize associated workflows and actions for active repositories. It processes repositories, updates their metadata, deactivates/inactivates them conditionally, and ensures workflows/runs ...
def run(self, **kwargs): """Entrypoint date -- date iso format for data fetching. Default is yesterday todo : add date option and runs selection (repos, workflows, actions, times) """ self.logger.info("hello from %s", self.name) self.target_date = kwargs.get('args').date...
def send(self, data): # log.debug("Sending: " + data) self._socket.sendall((data + "\r\n").encode('utf-8')) def has_access(self, name): if name == self.config.master: return True else: for n in self.config.access: if name == n: ...
This method processes incoming network messages by reading lines from a socket, parsing commands like 'OK', 'FAIL', 'PING', 'USER', 'SERVER', and 'CHANNEL', and triggering appropriate actions such as logging events, sending PONG responses, handling user interactions (e.g., TALK, EMOTE), updating channel states, and che...
def loop(self): file = self._socket.makefile() while self.connected: line = file.readline().strip().split(" ") arr = [str(a) for a in line if a] cmd, *_ = arr if cmd == 'OK': log.succ("Successfully connected!") elif cmd == 'FAIL...
def create_sitemap(self, url: str, max_urls: int = 20) -> None: self.urls_count += 1 if self.urls_count > max_urls: return links = self.get_links(url) for link in links: self.create_sitemap(link, max_urls=max_urls) def get_page_forms(self, url): self.drive...
This code scans for reflected XSS vulnerabilities by submitting crafted scripts through forms on internal URLs. If a script is reflected in the response, the URL is marked as vulnerable. It returns a set of URLs identified as potentially vulnerable to reflected XSS attacks.
def scan_reflected_xss(self): vulnerable_urls = set() self.create_sitemap(self.target_url) scripts = [ '<script>alert("XSS")</script>', '"><script>alert("xss")</script>', '"%3cscript%3ealert(document.cookie)%3c/script%3e', ] for url in self.int...
def get_n_expected_classes(submission: str, expected_classes: List[List[str]], max_classes: int, show_unmatched: bool=False) -> int: global frequent_extra_classes result = 0 probable_declared_classes = get_probable_declared_classes(submission) unmatched_classes = [] subm...
The code evaluates a student submission against a predefined marking scheme by analyzing the text content. It extracts expected classes, attributes, and associations from the submission, compares them with the marking scheme's criteria, and counts matches. The function returns a list containing a file identifier and qu...
def grade_submission(submission: Tuple[str, str], marking_scheme: Dict): name, text = submission # if name not in FILE_MAPPINGS: # return expected_classes = marking_scheme["expectedClasses"] expected_attributes = marking_scheme["expectedAttributes"] max_exp_classes = marking_scheme["nClasse...
def get_all_submissions(path=None) -> Dict[str, str]: if path is None: path = SUBMISSIONS_LOC result = {} for filename in os.listdir(path): if filename.endswith(".ump"): with open(os.path.join(path, filename), "r") as f: result[filename] = f.read() return resu...
The function grades all submissions using a heuristic marking scheme. It loads the marking scheme from a JSON file, retrieves submissions, calculates association multiplicities, grades each submission, sorts results by submission identifier, prints them as comma-separated values, and returns the sorted list of graded s...
def grade_all_using_heuristic(marking_scheme_file: str, submission_path: str=None): global IDEAL_ASSOC_MULTS result = [] with open(marking_scheme_file) as f: marking_scheme = json.load(f) submissions = get_all_submissions(submission_path) IDEAL_ASSOC_MULTS = get_association_multiplicities(...
def fetch_ticket_data(self, payload: dict) -> List[dict]: """ Fetch ticket data using the given payload. Args: payload (dict): A dictionary containing request data. Returns: List[dict]: A list of ticket dictionaries. Raises: Exception: If th...
The code retrieves and processes ticket data for multiple subjects over a specified period. It generates payloads for each subject, fetches ticket details, parses them, categorizes entries, and compiles amended ticket records into a list for the given period.
def fetch_period_tickets(self, period: str, subjects: dict) -> List[dict]: """ Fetch tickets for the given period and subjects. Args: period (str): A string representing the period for which to fetch tickets. subjects (dict): dict containing the subjects for which to fet...
def _fit(self, x, y): raise NotImplementedError def get_metrics(self,df): y = df[self.ycol].to_numpy() yhat = self.__call__(df) eps_abs = abs(yhat-y) metrics = { 'RMSE Abs': sqrt(mean(eps_abs**2)), 'MAE Abs': mean(eps_abs), 'Max Abs': max(eps_...
This code initializes a model for data transformation and visualization. It applies user-defined functions to transform features and responses, fits the model to the data, computes descriptive statistics, and generates plots (1D/2D) showing transformed vs. original domains. The model supports derivative calculations, h...
def __init__(self, df, tf_funs={}, xcols=None, ycol='y', name='model', plot=False, plot_mod=lambda fig: None, fig_root='./', plot_ops={}): """ Args: df (pd.DataFrame): dataframe of features and response vector. tf_funs (dict): transform functions where keys are df column names po...
def _get_known(self, column=1, page=INFO): """Return first <td></td> entries on page with onclick ID.""" info = self._get(self.url + page) # Return first td entry with value device_id in each table row (except header). return {re.findall("<td>.*?</td>", row)[column][4:-5]: ...
The main task of the code is to modify a program's properties by comparing local and remote file contents, updating the program via API, monitoring compilation logs for errors, and ensuring the new file is recognized. If unchanged, it returns False; otherwise, it confirms successful compilation and updates the program ...
def _modify(self, item_id, src=SRC, page_logs=COMPIL_LOGS): """Modify file properties when changed.""" # Get file name from id files = self._get_known(1) key_list = list(files.keys()) val_list = list(files.values()) position = val_list.index(item_id) stdin = sub...
def _post(self, url, data=None, files=None): """Perform POST request.""" return self._check_info(self.session.post(url, data=data, files=files), url) def _get(self, url): """Perform GET request.""" return self._check_info(self.session.get(url), url) def _get_known(self, column=1, page=IN...
The code uploads a file to a server, compiles it, monitors for compilation errors, and verifies the file's existence in the system. It uses regex to extract the filename from the response, submits metadata via POST requests, and raises errors on compilation issues. The loop waits until compilation succeeds or fails, th...
def _add(self, page=ADD, page_action=ADD_ACTION, page_logs=COMPIL_LOGS): """Add a file.""" # print("here") files = [ ('file', (self.args["file"], open(self.args["file"], 'rb'), 'text'))] info = self._post(self.url + page, files=files) self.filename = re.search("(?P<n...
def _get_known(self, column=1, page=INFO): """Return first <td></td> entries on page with onclick ID.""" info = self._get(self.url + page) # Return first td entry with value device_id in each table row (except header). return {re.findall("<td>.*?</td>", row)[column][4:-5]: ...
This function manages the presence or absence of an item in a system based on the 'state' parameter. It checks if the item exists, then adds, modifies, or removes it accordingly, updating the 'changed' flag to indicate if a change occurred. The function ensures the system state aligns with the specified 'present' or 'a...
def _loop(self, changed=False): """Main loop parsing state and returning whether something changed.""" item = self.args['name'] state = self.args['state'] items = self._get_known(column=0) print(items) if item in items: item_id = items[item] if sta...
def _get_known(self, page=INFO, column=ID_COLUMN): """Return first <td></td> entries on page with onclick ID.""" info = self._get(self.url + page) # Return first td entry with value device_id in each table row (except header). return {re.findall("<td>.*?</td>", row)[column][4:-5]: ...
This code manages item presence/absence based on the 'state' parameter. It checks if an item exists, modifies/removes it if 'present'/'absent', or adds it if missing. Returns a boolean indicating if changes occurred during the operation.
def _loop(self, changed=False): """Main loop parsing state and returning whether something changed.""" item = self.args[NAME] state = self.args['state'] items = self._get_known() if item in items: item_id = items[item] if state == 'present': ...
def get_latest_season(): return get_season()["items"][-1]["id"] def get_top_players(season): url = API_URL + f"/locations/global/seasons/{season}/rankings/players" data = get_data(url) return [player["tag"] for player in data["items"]] def get_player_deck_url(player): player = quote_plus(player) ...
The function identifies the most commonly used cards in the current season by asynchronously fetching deck data from top players, counting card occurrences, and returning a sorted list of cards with their usage counts and icons.
def count_results(player_count): season = get_latest_season() players = get_top_players(season)[:player_count] # Gather URLs for async API calls urls = [] for player in players: url = get_player_deck_url(player) urls.append(url) # Gather data via async requests data = async...
def prune_uninteresting_repos(tree): # prunes non-interesting repos from the tree # repos are considered interesting if they meet all the following criteria # repository or one of its forks (recursive) has been modified after forking # repository still exists at time of writing # these repos do...
The code processes a fork tree dataset by loading JSON data, pruning irrelevant repositories and commits, constructing a graph representation of the remaining data, and rendering it as an SVG visualization for display.
def main(): f = open('fork_tree_data_3.json', 'r') tree = json.loads(f.read()) f.close() tree = prune_uninteresting_repos(tree) tree = prune_uninteresting_commits(tree) graph = init_graph() recursively_graph_repos(tree, graph) graph.render('graph', format='svg', view=True)
def find_tree_node(base_tree, parent_user_name, parent_repo_name): # finds node in base_tree # returns None if specified node not found in base_tree current_uid = node_uid(base_tree) parent_uid = (parent_user_name, parent_repo_name) if current_uid == parent_uid: return [current_uid] f...
This function manually links a repository to a parent repository in a tree structure by checking if the node exists, creating a new child tree if necessary, and inserting it into the correct location within the provided tree data.
def manually_link_tree_data(user_name, repo_name, parent_user_name, parent_repo_name, tree_data): # manually links a repo to a parent repo # looks up api package for given repo and inserts into tree data # requires parent repo to exist (anywhere) in tree_data # check if node already exists in tree ...
def delete_index(idx_name): try: url = "%s/%s?refresh=true" % (tornado.options.options.es_url, idx_name) request = tornado.httpclient.HTTPRequest(url, headers=headers, method="DELETE", request_timeout=240, auth_username=tornado.options.options.username, auth_password=tornado.options.opti...
The main task of the code is to generate test data by creating random documents based on specified formats, optionally writing them to a file, and uploading them in batches to an Elasticsearch index. It handles index initialization, refresh settings, batch uploads, and logging, while managing global counters and file o...
def generate_test_data(self): global upload_data_count if tornado.options.options.force_init_index: self.delete_index(tornado.options.options.index_name) self.create_index(tornado.options.options.index_name) if tornado.options.options.set_refresh: self.set_ind...
def intialize(self, documentSet): print("\t" + str(self.D_All) + " documents will be analyze. alpha is" + " %.2f." % self.alpha + " beta is" + " %f." % self.beta + "\n\tInitialization.") for d in range(0, self.D_All): document = documentSet.documents[d] cluster = i...
The main task of the code is to run a Dirichlet Mixture Model (DMM) for document clustering. It initializes parameters, assigns documents to clusters via Gibbs sampling, tracks cluster statistics (document counts, word frequencies), and outputs results to a specified path. The process involves initializing the model, p...
def runDMM(self, documentSet, outputPath): # The whole number of documents self.D_All = documentSet.D # Cluster assignments of each document (documentID -> clusterID) self.z = [-1] * self.D_All # The number of documents in cluster z (clusterID -> numbe...
def parse_prim_type(node: Node) -> int: assert node.type == "prim_type" key = node.text.decode().upper() return DATA_TYPE_ID[key] def get_child_by_type_exact1(node: Node, type: str) -> Node: ret = get_child_by_type(node, type) assert ret is not None return ret def get_child_by_type(node: Node, k...
The function `parse_tensor_type` converts a tensor-type node into an ONNX `TypeProto` by extracting the element type from a "prim_type" child and parsing the tensor dimensions from a "tensor_dims" child, defaulting to an empty shape if absent. It returns the constructed `TypeProto` using `onnx.helper.make_tensor_type_p...
def parse_tensor_type(node: Node) -> onnx.TypeProto: assert node.type == "tensor_type" elem_type = parse_prim_type(get_child_by_type_exact1(node, "prim_type")) tensor_dims_node = get_child_by_type(node, "tensor_dims") shape = [] if tensor_dims_node is None else parse_tensor_dims(tensor_dims_node) re...
def parse_id(node: Node) -> str: assert node.type == "id" return node.text.decode() def get_child_by_field_name_exact1(node: Node, name: str) -> Node: ret = node.child_by_field_name(name) assert ret is not None return ret def parse_prim_constant(node: Node) -> Any: assert node.type == "prim_cons...
(The function parses a node of type "other_data" into a name-value tuple. It extracts the "name" field, identifies the "value" node's type, and processes it using specific parsers for "prim_constant" or "key_value_list" types. If the value type is unrecognized, it raises an error. The result is a tuple containing the p...
def parse_other_data(node: Node) -> tuple[str, Any]: assert node.type == "other_data" name = parse_id(get_child_by_field_name_exact1(node, "name")) value_node = get_child_by_field_name_exact1(node, "value") match value_node.type: case "prim_constant": value = parse_prim_constant(val...
def parse_tensor_type(node: Node) -> onnx.TypeProto: assert node.type == "tensor_type" elem_type = parse_prim_type(get_child_by_type_exact1(node, "prim_type")) tensor_dims_node = get_child_by_type(node, "tensor_dims") shape = [] if tensor_dims_node is None else parse_tensor_dims(tensor_dims_node) re...
This function parses a tensor constant node into an ONNX TensorProto by extracting data type, dimensions, name, and values from the node's children, creating a tensor with specified attributes.
def parse_tensor_constant(node: Node, ctx: GraphParserContext) -> onnx.TensorProto: assert node.type == "tensor_constant" type_proto = parse_tensor_type(get_child_by_type_exact1(node, "tensor_type")) data_type = type_proto.tensor_type.elem_type dims = [d.dim_value for d in type_proto.tensor_type.shape....
def parse_type(node: Node) -> onnx.TypeProto: assert node.type == "type" item_node = node.named_children[0] match item_node.type: case "tensor_type": return parse_tensor_type(item_node) raise UnexpectedNodeError(node) def get_child_by_type_exact1(node: Node, type: str) -> Node: ...
The function parses a given ONNX node of type "value_info" to extract its type and name information, then constructs and returns a corresponding `onnx.ValueInfoProto` object using the parsed data.
def parse_value_info(node: Node) -> onnx.ValueInfoProto: assert node.type == "value_info" type_proto = parse_type(get_child_by_type_exact1(node, "type")) name = parse_id(get_child_by_type_exact1(node, "id")) return onnx.helper.make_value_info(name, type_proto)
def parse_arguments(): parser = argparse.ArgumentParser() benchmark_message = "1-indexed antibody number, respecting the .xlsx table names." parser.add_argument( "-i", type=int, default=1, help=benchmark_message + " To evaluate a single antibody." ) parser.add_argu...
The main task of the code is to benchmark search results against CiteAB-stored data by comparing retrieved articles and false positives. It handles multiple modes: evaluating all antibodies, retrieving patterns, searching specific antibodies, or benchmarking queries. Results are saved in a CSV, with resume functionalit...
def main(): """ This function compares our current search results with CiteAB results which are stored in xlsx tables. Success metrics: 1. Number of articles retrieved. 2. Number of false positives, which are retrieved articles that were not found by CietAB. """ arguments = pa...
def create_2D_list(rows: int, columns: int, value=0) -> List[List]: """ :param rows: number of rows in new list :param columns: number of columns in new list :param value: value for cell :return: a 2D list """ return [[value for _ in range(columns)] for __ in range(rows)] def apply_kernel(im...
The code performs edge detection on an image by first blurring it, then comparing each pixel to the average of its surrounding neighborhood (defined by block_size). If the pixel's value is significantly lower than this average (adjusted by constant c), it is marked as an edge (black) on a white background. The result i...
def get_edges(image: List[List[int]], blur_size: int, block_size: int, c: int) -> List[List[int]]: """ :param image: 2D nested list image (R/G/B or grayscale) :param blur_size: Blur parameter, for applying kernel :param block_size: Block size for edge detection :param c: Constant for e...
def RGB2grayscale(colored_image: List[List[List[int]]]) -> List[List[int]]: """ :param colored_image: Colored Image, 3D nested list :return: Grayscale image 2D nested list """ # Creates a 2D nested list where each value is # translated using RGB_pixel_to_grayscale function. new_image = [[RGB...
The function converts an input image to a cartoon style by first converting it to grayscale, detecting edges using specified parameters, quantizing colors into a set number of shades, creating an edge mask, and applying this mask to the quantized image to produce the final cartoon effect.
def cartoonify(image: List[List[List[int]]], blur_size: int, block_size: int, c_constant: int, quantize_num_shades: int) -> List[List[List[int]]]: """ :param image: 3D nested list :param blur_size: used for get_edges function :param block_size: used for get_edges function ...
def create_xml_root(name_root: str): root = gfg.Element(name_root) root.append(single_text_elem("version", 1.1)) return root def create_meta_xml(n_frames: int): meta_node = gfg.Element("meta") task_node = gfg.Element("task") meta_node.append(task_node) task_node.append(single_text_elem("s...
This function converts JSON annotations into a CVAT-compatible XML format for visual representation. It reads a JSON file containing frame-wise annotations, processes each frame to extract normalized bounding boxes for visible persons, and generates an XML file with structured annotations. The output XML includes metad...
def json_imavis_style_conversion(json_file_path, out_folder): """ Script that provides a visual representation of the annotations """ with open(json_file_path, 'r') as json_file: data = json.load(json_file) data = np.array(data) n_seq = json_file_path.split(os.sep)[-1].split(".")[0...
def heap_size(heap): return len(heap) - 1 def max_heapify(heap, i, size): # assert here is too slow, Theta(n), kills runtime. # assert is_almost_heap(heap, i) assert i >= 1 assert i <= size lc = left_child(i) rc = right_child(i) largest = i if lc <= size and heap[lc] > heap[largest]...
The code converts an array into a max-heap structure. It starts by verifying the heap's initial state, then iterates from the middle of the array toward the root, applying `max_heapify` to ensure each subtree satisfies the max-heap property (parent nodes are greater than children). This process transforms the array int...
def build_max_heap(heap): assert heap[0] == None size = heap_size(heap) for i in range(size//2, 0, -1): max_heapify(heap, i, size) assert is_heap(heap, 1)
def heap_size(heap): return len(heap) - 1 def parent(index): return index // 2 def is_heap(heap, start=1): return check_heap_property(heap, start)
This function increases the value of a heap element at a given index and restores the max-heap property by "trickling up" the updated element through its parent hierarchy until the heap invariant is satisfied. It verifies input validity, updates the key, and repeatedly swaps the element with its parent if the parent's ...
def increase_key(heap, index, key): assert index >= 1 assert index <= heap_size(heap) assert key >= heap[index] heap[index] = key p = parent(index) while index > 1 and heap[p] < heap[index]: # trickle up temp = heap[p] heap[p] = heap[index] heap[index] = temp ...
def dictionary(x, index): """ Creates and returns a dictionary with x members. Each member is assigned an index, which it is set to return if called on by the dictionary. Two parameters: list x, and (any type) index. List x is the list of keys the dictionary contains. Index is what each item i...
The function `macro_analysis` processes the most recent `n` game logs to generate four visualizations: average bankroll per round, average tech committed, average asteroids mined, and average final bankroll per player. It filters out bankrupt logs, calculates bankruptcy statistics (frequency and average round), and plo...
def macro_analysis(n, game=default, show=[]): """ Plots various graphs associated with the past n logs. In order of appearence these are: average bankroll per round for all players, average fraction of tech committed per player, average fraction of asteroids mined per player, and average fraction of...
def initialize_visits(bna, clinical): """ Given two paths to both the BNA and clinical data sets, returns a merged df (named 'visits') that contains all visits, merged to the same dataframe with both BNA and clinical columns """ # Step 1: open csv and create the 'final_date' column for each visit, to avoid...
The function `generate_X` processes two datasets (BNA and clinical) to prepare features for a predictive model. It merges the datasets into a `visits` DataFrame, updates it with derived features (e.g., changes between visits), and extracts baseline and predictive features for each subject. It returns two outputs: a `su...
def generate_X(bna_path, clinical_path): """ This is the main function of this module. It returns a tuple of a df and a dictionary """ # Step 1: create a dataframe from the two raw datasets named 'visits' bna = pd.read_csv(bna_path) clinical = pd.read_csv(clinical_path) visits = initialize_visits...
def clean_and_create_resultdir(argsdir: str, vastdir: str): resultdir = utils.add_trailing_slash(argsdir) if argsdir is not None else vastdir # if resultdir does not exist, create it if not os.path.isdir(resultdir): logging.info(f"The resultdir '{resultdir}' does not exist, creating it...") ...
The code processes astronomical data from VaST files to generate light curves, phase plots, and AAVSO charts for candidate stars, VSX stars, and selected stars. It handles WCS astrometry, filters stars based on metadata, creates field charts, statistical plots, and optionally builds a Hugo-based website. The task invol...
def run_do_rest(args): thread_count = args.threads vastdir = utils.add_trailing_slash(args.datadir) resultdir = clean_and_create_resultdir(args.resultdir, vastdir) do_light = args.light do_phase = args.phase do_aavso = args.aavso logging.info(f"Dir with VaST files: '{vastdir}'\nResults dir: ...
def get_image_files( dir_path, sample: Optional[int] = 10, shuffle: bool = False ): dir_path = Path(dir_path) image_paths = [] for image_path in dir_path.glob("*.jpg"): image_paths.append(image_path) random.shuffle(image_paths) if sample: return image_paths[:sample] else: ...
The function processes images from a specified directory by retrieving a sample of image files, classifying them using a processing function, and converting the results into text node objects, which are then returned.
def classify_images_in_directory(img_dir, sample_size): """Receive the path of images and return text node objects of the classifications""" image_files = get_image_files(img_dir, sample= sample_size) outputs = aprocess_image_files(image_files) nodes = get_nodes_from_objs(outputs, image_files) ...
def assignTreeColors(ltns, tlds): half = int(ltns/2) colors = [(ltns,0,0), (ltns,half,0), (ltns,0,half), (ltns,ltns,0), (ltns,0,ltns), (half,ltns,0), (half,0,ltns), (0,ltns,0)] assigned = {} for index in range(len(tlds)): assigned[tlds[index]] = colors[index] return assigned def calcGap(ogTree, level, dimens...
The code generates a visual tree diagram from hierarchical data in 'forrest', assigning colors to nodes, calculating layout dimensions, drawing nodes with labels and percentages, connecting parent-child relationships with lines, and saving the resulting image as a JPEG file named with a timestamp.
def drawTree(forrest, total, writeTime): assignedColors = assignTreeColors(128, list(forrest.keys())) gap = -1 mult = 1 while(gap < 0): size = 64*mult dimension = (size*16)+(int(size/4)*17) gap = calcGap(forrest, 0, dimension) if(gap < 0): mult = mult+1 gray = (128,128,128) fontSize = int(size/2) domF...
def param_init_he(layers_dims): L = len(layers_dims) params = {} for l in range(1, L): he_factor = np.sqrt(2/layers_dims[l-1]) params["W"+str(l)] = np.random.randn(layers_dims[l], layers_dims[l-1]) * 0.01 params["b"+str(l)] = np.zeros((layers_dims[l], 1)) return params def forwar...
This code trains a neural network model using gradient descent. It initializes parameters with He initialization, performs forward and backward propagation iteratively, computes the cost with regularization (L2), updates parameters based on gradients, and returns the trained parameters after specified iterations.
def teach_the_model(X, Y, layers_dims, learning_rate, iterations, lmbda): costs = [] params = param_init_he(layers_dims) for i in range(iterations): # forward propagation AL, caches = forward_prop(X, params) # compute cost for making a graph if i % 2 == 0: prin...
def param_init_he(layers_dims): L = len(layers_dims) params = {} for l in range(1, L): he_factor = np.sqrt(2/layers_dims[l-1]) params["W"+str(l)] = np.random.randn(layers_dims[l], layers_dims[l-1]) * 0.01 params["b"+str(l)] = np.zeros((layers_dims[l], 1)) return params def forwar...
The main task of the code is to train a neural network using mini-batch gradient descent. It performs forward and backward propagation, updates parameters with a given learning rate, and saves model parameters and costs at regular intervals. The function either initializes new parameters using He initialization or load...
def process_minibatches(miniX, miniY, layers_dims, learning_rate, epochs, lmbda, new_params=True): if new_params: params = param_init_he(layers_dims) else: params = np.load(os.path.join(os.getcwd(), "params\\4_4_4_1\\small_reg\\params17.npy"), allow_pickle=True) params = params.item() ...
def get_sentences(base_path, dataset, debug=False): if debug ==True: dataset = load_from_disk(os.path.join(base_path,dataset)).select(range(10)) else: dataset = load_from_disk(os.path.join(base_path, dataset)) print(dataset) tokenized_sentences = [] for text in tqdm(dataset['text'],...
The code processes a dataset by masking high PMI n-grams in sentences using embeddings, prioritizing n-grams based on cosine similarity and overlap, then saving masked and original texts as a Hugging Face dataset. It filters top sentences, extracts n-grams, computes embeddings, masks selected n-grams with '<mask>', and...
def mask_and_save(base_path, dataset, pmi_path, output_path, typ, debug): # get tokenized paragraphs or training instances paragraphs = get_sentences(base_path, dataset, debug) # get top k PMIs pmi = get_top_pmi_ngrams(pmi_path, 0.5, typ) hf_dataset_dict = defaultdict(list) for i...
def open_file(self): with open(self.filename, 'r') as file: self.file_content = file.readlines() def first_pass(self): line_count = 0 for line in self.file_content: if self.is_comment(line) or line.isspace(): continue line = self.strip_whitespa...
The main task of the code is to execute a sequence of operations: first opening a file, then performing an initial processing pass, followed by a secondary processing pass. This structured approach likely processes or analyzes file content in two distinct stages, ensuring systematic handling of data or tasks in a layer...
def run(self): self.open_file() self.first_pass() self.second_pass()
def get_env(var): api_key = os.environ.get(var) return api_key def get_deviceNames(self): temp_deviceNames = [] if self.devices_raw == None: self.update_devices() for i in self.devices_raw['data']['devices']: temp_deviceNames.append(i['deviceName']) pr...
This code initializes a Govee API client by setting up the base URL, retrieving an API key from the environment, configuring request headers, creating a session, and fetching device names. It prepares the object for interacting with Govee's API to manage devices and models.
def __init__(self): self.base_url = 'https://developer-api.govee.com' self.api_key = get_env('GOVEE_API_KEY') self.default_header = {'Govee-API-Key': self.api_key} self.session = requests.Session() self.session.headers.update(self.default_header) self.devices_raw = None ...
def ProverComputations(): x, P = getKeyPair() # (x,P) for Prover. r = random_secret() # Prover choses random nonce value r. R = getRvalue(r) print("R value is: ", hex(R)) # Challenge e using H(R) e = int((sha256(str(R).encode())).hexdigest(),16) print("Value of e is: ", hex(e)) ...
The code demonstrates a Zero-Knowledge Proof (ZKP) protocol using Schnorr's scheme. It executes the prover's computations to generate proof elements (P, R, e, s), then the verifier's computations to validate the proof (rightSide, leftSide). Finally, it checks verification results, confirming the authenticity of the pro...
def main(): print('') print("***********************Zero-Knowledge Proof using Schnorr***********") print('') print ("++++++++++ Prover's computations begins.+++++++++++++++") print('') # Call Prover to perform computations. P,R,e,s = ProverComputations() print ("++++++++++ Prover's...
def ProverComputations(): x, P = getKeyPair() # (x,P) for Prover. r = random_secret() # Prover choses random nonce value r. R = getRvalue(r) print("R value is: ", R) # Challenge e using H(R) e = int((sha256(str(R).encode())).hexdigest(),16) print("Value of e is: ", e) #x = int(...
The main task of the code is to demonstrate a Zero-Knowledge Proof protocol using Schnorr. It executes the prover's computations to generate proof components (P, R, e, s), then the verifier's computations to validate the proof by comparing left and right sides of the equation. Finally, it checks the verification result...
def main(): print('') print("***********************Zero-Knowledge Proof using Schnorr***********") print('') print ("++++++++++ Prover's computations begins.+++++++++++++++") print('') # Call Prover to perform computations. P,R,e,s = ProverComputations() print('') print ("+++++...
def study_action(self): if self.check_for_depressed_or_illness(): return if not self.in_study_program: print("Agent not in school - trying to enroll.") enrollment_check = self.random_roll() # Random ROLL if enrollment_check >= self.policy_used.education_pe...
This code executes predefined actions based on the input number. It calls methods like study, work, or socialize for numbers 0-4, handles self-care (5) and special cases (90-91 for stats/career info, 98 for testing, 99 to end the game). It returns True after actions, except for special cases where it returns False.
def invoke_action_on_number(self, number): if number == 0: self.study_action() elif number == 1: self.work_action() elif number == 2: self.anti_social_action() elif number == 3: self.socialize_action() elif number == 4: ...
def build_simulation(self): self.build_agent() self.build_life_elements() self.build_policy() def has_not_exceeded_game_time(self): return self.number_of_weeks_passed <= self.TOTAL_NUMBER_OF_WEEKS def has_not_exceeded_weekly_actions(self): return self.actions_performed_this_week ...
The main task of the code is to run a simulation loop that manages game progression, checks for time/action limits, processes player or AI decisions, handles incarceration logic, and terminates the game when conditions are met. It builds the simulation, processes actions (human/AI), tracks weekly actions, enforces game...
def start_simulation(self): self.build_simulation() while self.game_in_progress: if self.has_not_exceeded_game_time(): if self.has_not_exceeded_weekly_actions(): if self.is_incarcerated: print("Incarerated, can't take action") ...
def detect_vechicle(tfnet_yolo, imgcv): result = tfnet_yolo.return_predict(imgcv) vehicles = [] for det in result: if (det['label'] in ['car','bus']): vehicles.append(det) return vehicles def scan_vehicles(vehicles, imgcv, wpod_net, lp_threshold): # # Adds a fake detection with the full image if no vehicle...
The main task of the code is to detect vehicles in an image, locate license plates (LPs) on them using a neural network, perform OCR on the detected LPs, save the results and images to a specified directory, and return the OCR output. The function integrates vehicle detection, LP scanning, OCR, and result storage in a ...
def run_all(tfnet_yolo, imgcv, wpod_net, lp_threshold, tfnet_ocr, outputdir, rootname): # # Find cars # result = detect_vechicle(tfnet_yolo, imgcv) #result = [{'label': 'car', 'confidence': 1, 'topleft': {'x': 1, 'y': 1}, 'bottomright': {'x': imgcv.shape[1], 'y': imgcv.shape[0]}}] # # Find LPs # platelist,...
def rotate_along_axis(self, image, number, phi=0, theta=0, psi=0, dx=0, dy=0, dz=0): # Get ideal focal length on z axis dz = self.focal*1. # Get projection matrix self.mat = self.get_M(phi, theta, psi, dx, dy, dz) #self.warp[number] = return cv2.warpPerspective(image, s...
This code initializes a ROS node for multi-camera object detection and tracking. It subscribes to sensor data (cameras, radar, AIS, pose), processes images with YOLO detection, applies transformations, and uses an Extended Kalman Filter (EKF) for tracking. Detected objects are published with bounding boxes, and image w...
def start(self, number=0): #self.EKF_init() self.cameranumber = int(number) self.rate = rospy.Rate(self.updateRate) n = self.total_images = 6 #Antall bilder kuttet langs horisonten self.window = None h = self.height = 1264 w = self.width = 1616 self.look...
def sleep_approx(self, seconds): """ Randomizes sleep to avoid detection. """ upperbound = (seconds+0.2)*10000 if (seconds >= 1): lowerbound = (seconds-0.2)*10000 else: lowerbound = seconds*10000 lowerbound = int(lowerbound) upperb...
The code identifies and processes expired players on a watch list by extracting their attributes, generating unique IDs, and logging event data. It then scrolls to and clicks the 'clear expired' button to remove them, with error handling and logging for tracking purposes.
def clearExpired(self): """ Clicks 'clear expired' button. Location: watch list """ self.sleep_approx(1) all_players_expired_pretty_list_for_google = [] try: playersOnPage = self.driver.find_elements_by_tag_name("li.listFUTItem") ...
def sleep_approx(self, seconds): """ Randomizes sleep to avoid detection. """ upperbound = (seconds+0.2)*10000 if (seconds >= 1): lowerbound = (seconds-0.2)*10000 else: lowerbound = seconds*10000 lowerbound = int(lowerbound) upperb...
The main task of the code is to identify and log details of sold players on a transfer list, then click the 'clear sold' button to remove them. It extracts player data (stats, prices, attributes), generates unique IDs, and logs events for tracking. The code includes error handling for clicking the 'clear sold' button a...
def clearSold(self): """ Clicks 'clear sold' button. Location: transfer list """ self.sleep_approx(1) playersOnPage = self.driver.find_elements_by_tag_name("li.listFUTItem") num_players_sold = 0 all_event_data = [] for player in playe...
def checkState(self, desiredPage=""): """ Checks if user is on desired page of web app, to avoid infinite loops on user intervention. Location: anywhere Parameters: desiredPage (str): watchlist, transfermaket, or transferlist Returns: True o...
The main task of the code is to place a bid on a specific player in the transfer market by clicking the player, inputting the bid amount, and handling post-bid status checks. It verifies bid validity, updates counters, and returns True if the bid succeeds as the highest offer, or False if errors occur, such as unchange...
def makebid_individualplayer2(self, playernumber, bid_to_make): status = self.checkState("transfermarket") if status: # Click player playerbutton = "/html/body/main/section/section/div[2]/div/div/section[1]/div/ul/li[" + str(playernumber) + "]/div" self.clickButton(pl...
def is_username_unique(self, name): for user in self.users: if user.name == name: return False return True def send_message(self, data): receiver = first(x for x in self.users if x.name == data.receiver_name) sender = first(x for x in self.users if x.name == d...
The code listens for UDP messages to handle user connections and file uploads. It processes connection requests by checking username uniqueness, adding new users, and notifying others. For file transfers, it tracks incoming blocks, stores them, and triggers a thread to send the complete file once all blocks are receive...
def __listen(self): files = {} # descriptors : [] array of File - blocks of real file print(f'Listening at {self.host} : {self.port}') while True: binary_message, addr = self.sock.recvfrom(UDP_MAX_SIZE) if not binary_message: continue else:...
def merge_sort(lst): if len(lst) <= 1: return lst mid = len(lst) // 2 left = merge_sort(lst[:mid]) right = merge_sort(lst[mid:]) return merge(left, right) def swap(lst,i,j): tmp=lst[i] lst[i]=lst[j] lst[j]=tmp
The code's main task is to find the largest possible number formed by elements in list `L` that is divisible by 3. It sorts the list in descending order, checks if the sum is divisible by 3, and if not, iteratively removes elements to achieve this. If unsuccessful, it recursively processes the modified list. The approa...
def solution(L): if len(L)==1: if L[0]%3==0: return L[0] return 0 FirstSort=merge_sort(L)#Largest to smallest print(FirstSort) if sum(FirstSort)%3==0: return int("".join(map(str, FirstSort))) else: for i in range(1,len(FirstSort)-1): if sum(Fir...
def merge_sort(lst,sortby): if len(lst) <= 1: return lst mid = len(lst) // 2 left = merge_sort(lst[:mid],sortby) right = merge_sort(lst[mid:],sortby) return merge(left, right,sortby) def inList(lst, num): for each in lst: if num==each: return True return False def...
The code sorts a list of elevator version strings by major, minor, and revision numbers. It parses each string into components, sorts by major version first, then minor, and finally revision, handling missing parts as `None`. The result is a list of elevator names ordered by their numeric version components. Your retur...
def solution(elevators): firstList=[]#sort elevators by major elements for lift in elevators: liftDigits=lift.split(".") if len(liftDigits) >2: tmp=(lift,int(liftDigits[0]),int(liftDigits[1]),int(liftDigits[2])) elif len(liftDigits)>1: tmp=(lift,int(liftDigits[0])...