dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def print_and_pause(message, seconds): print(message) pause(seconds) def riddle_challenge_one(): print_and_pause("Here is a riddle to solve:", 1) print_and_pause( "\nTroll: 'Tidings to you, mortal one. In order to pass, partake in my class : What belongs to only you, but those around you use it,...
The function `level_two()` advances a text-based adventure game's narrative, guiding the player through a forest encounter with a troll, solving a riddle to proceed, navigating a path choice (Dead Ahead, Left, or Right), confronting a ghost child, solving another riddle, and completing Level 2. It integrates storytelli...
def level_two(): # story print_and_pause( "\nYou ran for as far and as fast as you could, eventually coming to a halt in the centre of the forest. You looked around, the darkness hindered your ability to see. A tall stature loomed in front of you, or at least that's what you thought it was. You noticed ...
def print_and_pause(message, seconds): print(message) pause(seconds) def level_three_book_choice(): print_and_pause("Which book do you choose?. You can choose ONE book...", 1) print_and_pause("1 for the Blue Book", 1) print_and_pause("2 for the Red Book", 1) print_and_pause("3 for the Green Boo...
The code narrates a text-based adventure game level where the player navigates a collapsing, eerie school, overcoming obstacles like locked doors and ghostly encounters. The player collects critical items—books and bandages—to confront a shadow demon, escapes the crumbling school, and survives as the building collapses...
def level_three(): # story print_and_pause( "\nAs you made your hasty ascent up the school steps, you peer into the windows of the school - there was nothing but thick gloom that consumed each room, not a single trace of human life. You thought it was odd to have cars parked outside if no-one was here, ...
def dealer_face_down_card_render(dealer: base.Player): offset = 0.15555 * card_width button = GUI_Button.Button(pygame.Color(1,2,3), (width / 2) - (card_width / 2) + 50, 150, card_width, card_height, "Good Luck") button.draw(screen) def dealer_face_up_card_render(dealer: base.Player): offset = 0.15555 ...
The main task of the code is to render the current game state in a Pygame window, including the dealer's visible and hidden cards, game buttons, player hands, and status bars, then update the display with `pygame.display.flip()` to visualize the gameplay interface.
def render_gameplay(): global game_state screen.fill(pygame.Color(78,106,84)) dealer_face_down_card_render(game.dealer) dealer_face_up_card_render(game.dealer) exit_button(None) render_buttons() render_hands(0) render_all_game_bar() pygame.display.flip()
def render_all_game_bar(): global current_player, colors card_offset = ((card_width + 55) / 2) render_player(game.dealer,(width / 2) - (card_width / 2 + card_offset) + 117, 76, pygame.Color(155,166,178)) for curr in range(number_players): if (curr % 2 == 1): render_game_bar(w...
The main task of the code is to initialize a game by rendering the game interface, dealing cards to players and the dealer, displaying the dealer's face-down and face-up cards, rendering player hands, buttons, and updating the display to prepare for gameplay.
def setup_game(): render_all_game_bar() pygame.display.flip() game.deal_cards_players() dealer_face_down_card_render(game.dealer) render_hands(0) render_all_game_bar() dealer_face_up_card_render(game.dealer) game.deal_cards_players() render_hands(0) render_buttons() render_al...
def render_bet_player(pos, x: int, y: int, player: base.Player): global colors card_offset = ((card_width + 55) / 2) render_bet_button(x, y, player.player_wager.amount, pos, 255) render_balance(player, x, y - 50) def render_player(player: base.Player, x: int, y: int, color: pygame.Color): button = G...
The code renders betting interfaces and player cards for multiple players, positioning them differently based on their index (odd/even). It places bet displays and player cards at varying Y-coordinates, with a confirm button rendered specifically for the current player at a position dependent on their index.
def process_bets(pos): card_offset = ((card_width + 55) / 2) for curr in range(number_players): if (curr % 2 == 1): render_bet_player(pos, width - (curr + 1)*(width / 4) - card_offset + 50, height - 300, game.players[curr]) render_player(game.players[curr], width - (curr + 1)*(w...
def apply_rule(w: str, r: tuple) -> tuple[str, tuple]: ww = w rr = None if r[0] == Operation.REP: ww = w.replace(r[1], r[2]) rr = Operation.REP, r[2], r[1] elif r[0] == Operation.FLP: ww = w[::-1] rr = Operation.FLP, elif r[0] == Operation.ROL: ww = w[1:] + w...
The code explores word transformations using given rules to find valid words from an initial word `w1`. It uses BFS (via a deque) to apply rules iteratively, tracking applied rules and avoiding cycles. When a word from the target list `words` is found, it checks if the transformation path is unique. The task is to iden...
def solve_any_word(w1: str, words: list[str], rules: list[tuple], rules_repeatable: bool): words_found = set() words_found.add(w1) states = deque() states.append( (w1, []) ) state_processed = 0 last_print_time = datetime.now() while len(states) > 0: t = datetime.now() if (...
def num_combinations(n, r): if r < n // 2: r = n - r num = 1 for i in range(r + 1, n + 1): num *= i num //= factorial(n - r) return num def apply_rule(w: str, r: tuple) -> tuple[str, tuple]: ww = w rr = None if r[0] == Operation.REP: ww = w.replace(r[1], r[2...
The code searches for a unique solution by applying permutations of rule combinations to transform the input word `w1`. It iterates through all possible rule selections and their permutations, applies each rule to generate a new word `w2`, records reversed rules, and checks if `w2` has a unique solution path back to `w...
def find_puzzle(w1: str, rule_num: int, rules: list[tuple]): for rules_sel in tqdm(itertools.combinations(rules, rule_num), total=num_combinations(len(rules), rule_num)): for rules_sel_perm in itertools.permutations(rules_sel): w2 = w1 rules_rev = [] for rule in rules_se...
def apply_rule(w: str, r: tuple) -> str: if r[0] == Operation.REP: return w.replace(r[1], r[2]) elif r[0] == Operation.FLP: return w[::-1] elif r[0] == Operation.ROL: return w[1:] + w[0] elif r[0] == Operation.ROR: return w[-1] + w[:-1] elif r[0] == Operation.SHL: ...
This code performs a breadth-first search (BFS) to explore all possible word transformations starting from `w1` using given rules. It tracks visited words and applied rules, checking if generated words match any in the `words` list. When a match is found, it verifies if the solution is unique and prints details. The BF...
def solve_any_word(w1: str, words: list[str], rules: list[tuple], rules_repeatable: bool): words_found = set() words_found.add(w1) states = deque() states.append( (w1, []) ) state_processed = 0 last_print_time = datetime.now() while len(states) > 0: t = datetime.now() if (...
def run_command(command): return check_output(command, shell=True) def run_bench(command): total = defaultdict(lambda: defaultdict(float)) for i in range(REPEAT): stats = get_stats(run_command(command)) for (key, values) in stats.items(): for (bench, value) in values.items(): ...
The code's main task is to clean up specific files (e.g., snapshots, logs, databases) using shell commands, execute a benchmark via `cargo run` with release settings and command-line arguments, capture benchmark statistics, and print the final results.
def main(): try: run_command('rm *-snapshot_id; rm *-log-*.json; rm *.bin; rm *.db; rm *.db-journal') except: pass command = 'cargo run --release --manifest-path benchmarks/Cargo.toml --bin vote -- %s' % ' '.join(sys.argv[1:]) stats = run_bench(command) print('\n\n#######\nfinal sta...
def send_stop_recursively(self, pid): """stops pid process and, recursively, all of its children, returning their pids in an array if any". """ glog.info("Stopping: {0}".format(pid)) self.really_kill(pid, signal.SIGSTOP) kids = self.children(pid) for kid in kids[:]: ...
This function terminates a specified process and its descendants by sending a kill signal. If `two_phase` is True, it uses SIGABRT instead of SIGKILL. It first lists processes, logs them, then recursively sends SIGSTOP to prevent new processes. For SIGKILL, it kills children first, then the parent. For other signals, i...
def exterminator(self, the_pid, kill_signal=signal.SIGKILL, two_phase=False): if two_phase: kill_signal = signal.SIGABRT cmd = "ps faux" out = subprocess.Popen( cmd, stdout=subprocess.PIPE, shell=True).communicate()[0] glog.info(out) if kill_signal == si...
def sma_cross_detect(df:object): previous_candle = df.iloc[-2] current_candle = df.iloc[-1] if previous_candle.FastSMA > previous_candle.SlowSMA: previous_sma = 'up' elif previous_candle.FastSMA < previous_candle.SlowSMA: previous_sma = 'down' else: previous_sma = 'unknown' ...
This function implements a Simple Moving Average (SMA) crossover trading strategy. It checks for SMA trend changes (from up/down to down/up) and aligns them with the overall market trend. If conditions are met (volume > VolumeMA), it executes buy/sell orders with take-profit levels calculated via percentage. Logs trade...
def sma_cross_entry_strategy(df:object,symbol:str,tp_percentage:float): previous_sma = sma_cross_detect(df)[0] current_sma = sma_cross_detect(df)[1] qty = get_quantity(df.close.iloc[-1]) current_price = df.close.iloc[-1] current_volume = df.volume.iloc[-1] current_VolumeMA = df.VolumeMA.iloc[-1]...
def sma_cross_detect(df:object): previous_candle = df.iloc[-2] current_candle = df.iloc[-1] if previous_candle.FastSMA > previous_candle.SlowSMA: previous_sma = 'up' elif previous_candle.FastSMA < previous_candle.SlowSMA: previous_sma = 'down' else: previous_sma = 'unknown' ...
This function implements an exit strategy for trading positions based on Simple Moving Average (SMA) crossover signals and take-profit levels. It checks if a long or short position should be closed when the current price reaches the take-profit threshold or when the SMA trend reverses. It logs the exit reason, order de...
def sma_cross_exit_strategy(df:object,symbol:str,tp_override:bool): previous_sma = sma_cross_detect(df)[0] current_sma = sma_cross_detect(df)[1] order_id = get_last_order_id(trading_symbol) current_price = df.close.iloc[-1] current_volume = df.volume.iloc[-1] current_VolumeMA = df.VolumeMA.iloc[...
def _update_target_params(self, max_patches=None, split_ratios=None, balance=None): # update number of patches, default: use all self.max_patches = int(self.tot) if max_patches is not None: # use all patches self.max_patches = min(max_patches, self.max_patches) # update and ...
This function configures data splits by reinserting patches according to specified split ratios, class balances, and user-provided bags. It initializes random seeds, updates dataset parameters, divides data into bags, calculates split statistics, and fills splits with patches. Key parameters include max_patches, split_...
def split_setup( self, max_patches=None, split_ratios=None, balance=None, seed=None, bags=None, ): """(Re)Insert the patches in the splits, according to split and class ratios :param max_patches: Number of patches to be read. If None use all patches. ...
def init_listmanager( self, table, id_col, label_col="label", label_map=[], grouping_cols=[], num_classes=2, metatable=None, ): """Initialize the Cassandra list manager. It takes care of loading/saving the full list of rows from the ...
The main task of the code is to load split data from a file, initialize data structures like `clm_table` and `datatable`, and reload split configurations. It also updates parameters such as batch size and augmentations, enabling the class to manage data splits for processing.
def load_splits(self, filename, augs=None): """Load list of split ids and optionally set batch_size and augmentations. :param filename: Local filename, as string :param augs: Data augmentations to be used. If None use the current ones. :returns: :rtype: """ prin...
def compute_fill(self, return_full_length=False): """ Compute the fill of the current dataset :param return_full_length: Not implemented! :type return_full_length: bool """ # Compute fill and check if multiple chunks of data to loop over if self.chunks == 1: ...
The code computes the number of zero crossings in a dataset, normalizing by the number of non-zero points and applying a correction factor. It uses Bae et al.'s (1996) method, calculating squared differences between consecutive data points. For single or multiple data chunks, it divides zero-crossing counts by segment ...
def compute_zero_crossings(self): """ Compute the number of zero crossings in the dataset following Bae et al. (1996) :math:`D_{1} = \sum^{N}_{i=2}(X_{i}-X_{i-1})^{2}\;\textrm{where } 0 \leq D_{1} \leq N-1` """ # Normalise by number of NON-ZERO points, try to alleviate ...
def calculate_fill(self, x, y): """ Compute the fill of the current dataset :param y: array of which to calculate the fill. :type y: array """ # 11/01/2021 Make sure to round up to avoid odd case where fill can be greater than 1 full_npts = np.ceil((x[-1] - x[0])...
The code computes higher-order crossings (HOCs) by calculating k crossings from signal y, adjusting with correction factors derived from fill values and sigmoid coefficients. It compares these crossings to pre-defined Gaussian values, computes a similarity measure (ψ) as the sum of squared differences normalized by Gau...
def compute_hocs(self, x, y, k): """ Compute higher order crossings (HOC) Parameters ----------- k (int) : number of k crossings to compute (inclusive) """ zc_gauss = np.array([ 0.49912 , 0.666367, 0.732079, 0.769869, 0.795083, 0.81284 , 0.827098, 0...
def find_frequent_items(transactions, threshold): items = {} for transaction in transactions: for item in transaction: if item in items: items[item] += 1 else: items[item] = 1 for key in list(items.keys()): ...
This code initializes an FP-Tree for frequent pattern mining by processing transactions to identify frequent items, constructing a header table for item frequencies, and building the FP-Tree structure using the transactions, root parameters, and frequent itemsets. The main task is to prepare the FP-Tree for efficient m...
def __init__(self, transactions, threshold, root_value, root_count): self.frequent = self.find_frequent_items(transactions, threshold) self.headers = self.build_header_table(self.frequent) self.root = self.build_fptree( transactions, root_value, root_count, self.frequent,...
def read_data(): linkage_matrix = pd.read_csv( "normalized_linkage.csv", delimiter=',') # convert labels to start at 0 linkage_matrix.rename(columns=lambda x: "window " + str(int(x) - 69716), index=lambda y: "window " + str(int(y) - 69716), inplac...
The main task of the code is to analyze a network by calculating centrality metrics, identifying communities, and visualizing hub-related features. It reads a linkage matrix, computes centrality statistics, detects communities using edge data, and prints feature percentages for "Hist1" and "LAD" attributes. Heatmaps ar...
def main(): linkage_matrix = read_data() calculate_centrality(linkage_matrix) centrality_df = calculate_stats(calculate_centrality(linkage_matrix)) edge_matrix = contains_edge(linkage_matrix) my_network = find_communities(centrality_df, edge_matrix) feature_df = read_feature_data() print("Fe...
def set_seq(self, new_seq): self.payload_seq = new_seq def _publish_birth(self): self._publish_node_birth() for device_name in self.birth_certificate.devices: self._publish_device_birth(device_name) def metric_value_from_type(metric, data_type: sparkplug.MetricDataType): if d...
This function processes incoming Node Control Messages (NCMDs) by checking each metric in the payload. It handles specific commands like "Next Server," "Rebirth," and "Reboot," updating the device's state or triggering retransmissions. For recognized metrics, it updates values, logs changes, and allows user-defined han...
def _handle_ncmd(self, inbound_payload): for metric in inbound_payload.metrics: if metric.name == "Node Control/Next Server": # 'Node Control/Next Server' is an NCMD used to tell the device/client application to # disconnect from the current MQTT server and connect to...
def set_irradiance(self, dawn=6.0, dusk=18.0, max=1000.0, noise=0.0): hours_since_midnight = self.time_secs/3600 % 24 if hours_since_midnight < dawn or hours_since_midnight > dusk: self.state.set_node_metric('irradiance', 0) else: A = -4*max/(dusk - dawn)**2 i...
This code simulates a time-stepped control loop for a power system. It updates time metrics, environmental conditions (weather, irradiance, temperature), battery state-of-charge, and power output. It toggles local control every 10 minutes and applies different control modes (local, manual, PoC control) to adjust batter...
def sim_loop(self): # Time now = datetime.datetime.now() self.time_secs = now.microsecond*1e-6 + now.second + 60*now.minute + 3600*now.hour dt = self.time_secs - self.last_time_secs self.state.set_node_metric('uptime', int(1000*(self.time_secs - self.start_time))) self.s...
def left_condition(y): c0 = c(y[0]) c12 = func_plus_half(y[0], t, c) k12 = func_plus_half(y[0], t, KK) p0 = p(0) p12 = p(h / 2) K0 = h / 8 * c12 + h / 4 * c0 + \ k12 * t / h + \ t * h / 8 * p12 + t * h / 4 * p0 M0 = h / 8 * c12 - \ k12 * t / h + \ t * h * p...
The code computes a solution vector `y` using iterative updates based on initial conditions from `left_condition` and `right_condition`, applying recursive formulas involving functions `D`, `B`, `A`, and `F`. It initializes `eps` and `eta` arrays, iterates over steps with step size `h`, updates these arrays, and finall...
def calculate(prev): K0,M0,P0 = left_condition(prev) KN,MN,PN = right_condition(prev) eps = [0, -M0 / K0] eta = [0, P0 / K0] x = h n = 1 while (x + h < l): new_eps = D(prev[n]) / (B(x, prev[n]) - A(prev[n]) * eps[n]) new_eta = (F(x, prev[n]) + A(prev[n]) * eta[n]...
def encode_custom_properties(self, obj, obj_json, exclude): for key, val in obj_json.items(): if not (key in exclude): self.encode_property(key, val, obj.custom_properties, obj.values) def encode_id(self, obj, id): if id is not None: if isinstance(id, int): obj.in...
This function encodes a geometry object from JSON data by setting its type, coordinates, and properties. It handles different geometry types (e.g., Point, Polygon) by calling specific encoding methods, processes topological data if enabled, and assigns custom properties. It recursively processes nested geometries for c...
def encode_geometry(self, geometry, geometry_json): gt = geometry_json['type'] coords = geometry_json.get('coordinates') coords_or_arcs = coords geometry.type = self.geometry_types[gt] self.encode_custom_properties(geometry, geometry_json, ('type', 'id', 'coordinat...
def decode_properties(self, props, values, dest=None): if dest is None: dest = {} for i in range(0, len(props), 2): key = self.data.keys[props[i]] val = values[props[i + 1]] value_type = val.WhichOneof('value_type') if value_type == 'string_value': dest[k...
This function decodes a geometry object into a structured dictionary representation, handling various geometry types (e.g., Point, LineString, Polygon) and their properties. It uses recursion for GeometryCollections, applies specific decoding logic for coordinates/arcs based on topology flags, and incorporates custom p...
def decode_geometry(self, geometry): obj = collections.OrderedDict() gt = obj['type'] = self.geometry_types[geometry.type] coords_or_arcs = 'coordinates' self.decode_properties(geometry.custom_properties, geometry.values, obj) if self.is_topo: self.decode_id(geometr...
def encode_id(self, obj, id): if id is not None: if isinstance(id, int): obj.int_id = id else: obj.id = str(id) def encode_properties(self, obj, props_json): if props_json is None: return for key, val in props_json.items(): self.encode_property(key, val, obj....
This method encodes a geographic feature's components from JSON data. It extracts and processes the feature's ID, properties, custom properties (excluding 'type', 'id', 'properties', 'geometry'), and geometry, mapping them to the feature object using specialized encoding methods.
def encode_feature(self, feature, feature_json): self.encode_id(feature, feature_json.get('id')) self.encode_properties(feature, feature_json.get('properties')) self.encode_custom_properties(feature, feature_json, ('type', 'id', 'properties', 'geometry')) self.encode_geometry(feature.geo...
def encode_custom_properties(self, obj, obj_json, exclude): for key, val in obj_json.items(): if not (key in exclude): self.encode_property(key, val, obj.custom_properties, obj.values) def add_point(self, coords, point): for x in point: self.add_coord(coords, x) def encode_ge...
This code encodes geometric topology data from a JSON structure into a topology object. It applies scaling/translation transformations, processes arc coordinates, stores arc lengths, adds points to coordinate lists, and encodes named geometry objects. The function sets flags for topology processing, handles coordinate ...
def encode_topology(self, topology, data_json): self.is_topo = True transform_json = data_json.get('transform') if transform_json: scale_json = transform_json.get('scale') translate_json = transform_json.get('translate') transform = topology.transform ...
def decode_properties(self, props, values, dest=None): if dest is None: dest = {} for i in range(0, len(props), 2): key = self.data.keys[props[i]] val = values[props[i + 1]] value_type = val.WhichOneof('value_type') if value_type == 'string_value': dest[k...
This function converts a feature object into a structured dictionary with 'type', 'properties', 'id', and 'geometry' keys. It initializes the dictionary, decodes properties and IDs, processes geometry, and conditionally adds properties if present, using helper methods for each step.
def decode_feature(self, feature): obj = collections.OrderedDict() obj['type'] = 'Feature' self.decode_properties(feature.custom_properties, feature.values, obj) self.decode_id(feature, obj) obj['geometry'] = self.decode_geometry(feature.geometry) if len(feature.propert...
def decode_properties(self, props, values, dest=None): if dest is None: dest = {} for i in range(0, len(props), 2): key = self.data.keys[props[i]] val = values[props[i + 1]] value_type = val.WhichOneof('value_type') if value_type == 'string_value': dest[k...
This function decodes a topology object into a structured dictionary, including properties, transformations, geometric objects, and arcs. It processes custom properties, extracts transformation parameters if present, maps geometry objects to names, and constructs arc coordinates from coordinate lists. The result is a n...
def decode_topology(self, topology): obj = collections.OrderedDict() obj['type'] = 'Topology' self.is_topo = True self.decode_properties(topology.custom_properties, topology.values, obj) if topology.HasField('transform'): tr = topology.transform obj['tr...
def encode_feature_collection(self, feature_collection, feature_collection_json): self.encode_custom_properties(feature_collection, feature_collection_json, ('type', 'features')) for feature_json in feature_collection_json.get('features'): self.encode_feature(feature_collection.features.add(...
This code encodes geographic data (GeoJSON) into a binary GeoBuf format. It initializes parameters, processes input data based on its type (FeatureCollection, Feature, etc.), transforms coordinates using specified precision, and serializes the result into a byte string for efficient storage/transfer.
def encode(self, data_json, precision=6, dim=2): obj = self.json = data_json data = self.data = geobuf_pb2.Data() self.precision = precision self.dim = dim self.e = pow(10, precision) # multiplier for converting coordinates into integers self.keys = collections.OrderedD...
def new_line(): print(".") def three_lines(): new_line() new_line() new_line() def nine_lines(): three_lines() three_lines() three_lines()
The code's main task is to clear the screen by sequentially printing a new line, three lines, and nine lines, likely overwriting or spacing out previous content to simulate a screen reset.
def clear_screen(): new_line() three_lines() nine_lines()
def get_combinations(length, alphabet=ALPHABET): combinations = {} for x in range(length): combinations[x + 1] = list(itertools.product(alphabet, repeat=(x+1))) return combinations def generate_guids(words, combinations=None, length=5, alphabet=ALPHABET): guids = set() if not combinations: ...
The main task of the code is to generate a blacklist of "bad" GUIDs by combining blacklisted words of lengths 3-5 with predefined character combinations, time the generation process, and save the results to a file. It first creates a merged blacklist, generates GUIDs using combinations, adds additional GUIDs from a 69s...
def main(): blacklist_all = wordlist.dict_by_length() blacklist = blacklist_all[3].union(blacklist_all[4]).union(blacklist_all[5]) combinations = get_combinations(3) tick = time.time() bad_guids = generate_guids(blacklist, combinations=combinations) print('Time: {}, Length: {}'.format(time.time(...
def test_validate_image(): tests = [ ([], True), # Empty image. (None, False), # Image not list. ([[1]], True), # Single row, single pixel. ([[1], [None], [2]], False), # Not integer pixel. ([[1], None, [2]], False), ...
The code executes multiple test functions, aggregates their success and failure counts, and prints the total number of passed and failed tests.
def run_all_tests(): tests = [ test_validate_image(), test_histogram(), test_cumulative(), test_equalize(), ] total_success, total_fail = 0, 0 for success, fail in tests: total_success += success total_fail += fail print("{0} tests passed, {1} tests fa...
def test_message_to_bits(): "Test cases for the message_to_bits function" tests = [ ([''], ''), (['A'], '01000001'), (['hello'], '0110100001100101011011000110110001101111'), (['ABC\n123'], '01000001010000100100001100001010001100010011001000110011'), (["je t'aime"...
The code runs all test cases for key functions, aggregates pass/fail counts from each test, and prints the total number of passed and failed tests.
def run_all_tests(): '''Run all the test cases for each of the key functions. Count and print the number of passes and failures. ''' tests = [ test_message_to_bits(), test_bits_to_message(), test_round_trip(), test_encode_small(), test_decode_small(), test...
def close_browser(): global browser_flag if browser_flag: pg.moveTo(965, 1060,0.2) pg.click() browser_flag = False pg.moveTo(1895, 15, 0.2) pg.click() def menu(): global param1, param2 data1 = int(input("Enter your following count:\n")) data2 = int(input("Enter your f...
The code's main task is to execute a sequence of operations: closing a browser, displaying a menu, performing web scraping, and analyzing the scraped data, likely automating a workflow for data collection and analysis.
def run(): close_browser() menu() scraping() analysis()
def get_data_by_console(self, data_type, message): # Function that reads a console entry asking for data to store into a variable valid = False output = None if data_type == int: while not valid: try: output = int(input(message)) ...
The main task of the code is to manage a vehicle's Virtual Network Function (VNF) request process, including connecting to a Fog/Edge Computing (FEC) node, handling network interface configurations, and simulating vehicle movement between locations. It interacts with a server to request resources, updates the vehicle's...
def start_cav(self, nodes_to_evaluate): # Main function try: # Get user_id if self.general['training_if'] != 'y' and self.general['training_if'] != 'Y': self.user_id = self.get_data_by_console(int, '[*] Introduce your user ID: ') else: ...
def feature_normalize(df): mean_mapping = {} std_mapping = {} for col in df.columns: mean_mapping[col] = df[col].mean() std_mapping[col] = df[col].std() for col in df.columns: df[col] = df[col] - mean_mapping[col] df[col] = df[col].div(std_mapping[col]) return df def ...
The function trains a linear regression model using gradient descent with regularization on normalized training data, then predicts target values for test data by applying the learned parameters to normalized test features.
def linear_regr_train(test_data, df, y, alpha, lamb, num_iterations): # m = df.shape[0] n = len(df.columns) df_norm = feature_normalize(df) df_norm.insert(0, 'ones', 1, allow_duplicates=True) initial_theta = np.zeros(n + 1) test_data_norm = feature_normalize(test_data) test_data_norm.insert(...
def conv_bn(input, filter_size, num_filters, strides=(1,1), init=uniform(0.00001)): c = Convolution(filter_size, num_filters, activation=None, init=init, pad=True, strides=strides, bias=False)(input) r = BatchNormalization(map_rank=1, normalization_time_constant=4096, use_cntk_engine=True)(c) return r def r...
This function constructs a ResNet-based model with multi-scale feature fusion for image segmentation. It processes input channels (R, G, B, I), applies convolutional layers, builds hierarchical ResNet blocks with increasing channels, and uses transposed convolutions for upsampling. Skip connections combine features acr...
def resu_model(input, num_stack_layers, c_map, num_classes, block_size): r = cntk.slice(input, 0, 0, 1) g = cntk.slice(input, 0, 1, 2) b = cntk.slice(input, 0, 2, 3) i = cntk.slice(input, 0, 3, 4) r -= reduce_mean(r) g -= reduce_mean(g) b -= reduce_mean(b) #i -= reduce_mean(i) inpu...
def can_move(self, x, y): return self.get_content(self.worker()[0] + x, self.worker()[1] + y) not in ['#', '*', '$'] def worker(self): x = 0 y = 0 for row in self.matrix: for pos in row: if pos == '@' or pos == '+': return (x, y, pos) ...
This code handles a worker's movement and box pushing in a grid-based environment. It checks if the worker can move or push a box to coordinates (x, y), updates the grid state by modifying worker and box positions, and saves moves in a queue if 'save' is True. It manages different terrain interactions, like empty space...
def move(self, x, y, save): if self.can_move(x, y): current = self.worker() future = self.next(x, y) if current[2] == '@' and future == ' ': self.set_content(current[0] + x, current[1] + y, '@') self.set_content(current[0], current[1], ' ') ...
def worker(self): x = 0 y = 0 for row in self.matrix: for pos in row: if pos == '@' or pos == '+': return (x, y, pos) else: x = x + 1 y = y + 1 x = 0 def move(self, x, y, save): if...
The code processes movement commands from a queue. If the command indicates a box is involved, it moves the worker and updates the box's position in the opposite direction. Otherwise, it moves the worker alone. The task is to execute stored movement instructions, handling both worker-only and box-related movements base...
def unmove(self): if not self.queue.empty(): movement = self.queue.get() if movement[2]: current = self.worker() self.move(movement[0] * -1, movement[1] * -1, False) self.move_box(current[0] + movement[0], current[1] + movement[1], movement...
def clean_query(query): query.pop("csrf_token", None) query.pop("search", None) for key, value in query.items(): # convert from lists to appropriate format if value == ['']: query[key] = '' else: if key not in ["artist", "album_name", "song_title", "genres", "...
The main task of the code is to generate song recommendations based on user input. It processes form data, cleans and categorizes the query, selects appropriate recommendation methods (e.g., song-based, single/multi-parameter queries), and returns results. If no specific method applies, it randomly samples songs from a...
def recommend_songs(form_data): print(form_data) query = clean_query(form_data) query.pop("explicit") n = int(query.pop('num_tracks')) recommendations = None c, fields = case(query) if c in [1, 19, 20, 21]: # Treat query as a song recommendations = find_songs(query, n) elif c in...
def input_matrix(M, N): P = np.zeros((M, N)) for i in range(M): for j in range(N): while True: value = float(input(f"\tEnter P(x{i+1}, y{j+1}): ")) if value >= 0: P[i, j] = value break else: ...
The main task of the code is to compute and print key information-theoretic measures (entropy, joint entropy, conditional entropy, mutual information, and Kullback-Leibler divergence) for a given probability matrix input by the user. It calculates marginal probabilities, derives statistical properties, and outputs resu...
def main(): # Sample matrix # P = [[0.0625, 0.0625, 0], # [0.375, 0.1875, 0.1875], # [0.0625, 0, 0.0625]] # P = np.array(P) # Enter the number of rows and columns of the matrix M = int(input("Enter number of rows: ")) N = int(input("Enter number of columns: ")) P = input_m...
def is_moving(self): return (self._movement_status & MOVING) == MOVING def is_walking(self): return (self._movement_status & WALKING) == WALKING def is_jumping(self): return (self._movement_status & JUMPING) == JUMPING def _jump(self): # Get values for img array indexing val = self._jump_frame_counter//(self...
This function determines the character's animation frame based on movement state. It returns walking/jumping frames with position if moving, jump animation if jumping, or a default frame when idle.
def frame_movement(self): # Checking if the character is moving if self.is_moving(): # Checking for movement status type if self.is_walking(): if self.is_jumping(): return self._jump() + [self.get_pos()] if self._facing == "R": return self._to_right() + [self.get_pos()] return self._to_l...
def table_exists(self, table_name: str) -> bool: c = self.execute(f'''SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}' ''') return c.fetchone() is not None def create_table(self, *, table_name: str, columns: List[str], ...
This code writes a pandas DataFrame into a SQL table by converting data to strings, creating the table if it doesn't exist, and using REPLACE queries to insert/update records row-by-row, then commits the transaction and logs the operation.
def write(self, df: pd.DataFrame, *, table_name: str, index: Union[str, List[str]]): df = df.astype(str) if not self.table_exists(table_name): self.create_table(table_name=table_name, columns=list(df.columns), index=index) que...
def get_next_transaction_id(): return len(get_transactions())+1 def get_user_balance(name): accounts = get_accounts() return accounts[name][1] def queryTransactions(): global transactions cur = conn.cursor() cur.execute("SELECT * FROM transactions") rows = cur.fetchall() transactions.cl...
The main task of the code is to insert a new transaction record into a database, including generating a transaction ID, retrieving the user's balance, and handling potential SQL errors. It uses parameterized queries to add transaction details (name, action, amount, balance, status) to the "transactions" table, commits ...
def create_transaction(name,action,amount): transaction_id = get_next_transaction_id() balance = get_user_balance(name) sql_add_transaction = """INSERT INTO transactions (transaction_id, name, action, amount, balance, status) VALUES (?,?,?,?,?,?)""" para = (transaction_id,name, action, amount, balance, ...
def queryAccounts(): global accounts cur = conn.cursor() cur.execute("SELECT * FROM accounts") rows = cur.fetchall() accounts.clear() for row in rows: accounts[row[0]] = (row[1], row[2], row[3]) def get_status(name): accounts = get_accounts() if accounts[name][2] == 1: ...
This code allows a user to withdraw funds from their account by validating the withdrawal amount, updating the database balance, and recording the transaction if the account is active and the amount is non-negative and sufficient.
def withdraw(name): queryAccounts() if get_status(name): while True: amount = input("What amount would you like to withdraw? ") try: amount = float(amount) if amount < 0: print("Must be non-negative!") else: ...
def queryAccounts(): global accounts cur = conn.cursor() cur.execute("SELECT * FROM accounts") rows = cur.fetchall() accounts.clear() for row in rows: accounts[row[0]] = (row[1], row[2], row[3]) def get_status(name): accounts = get_accounts() if accounts[name][2] == 1: ...
This function handles a deposit transaction for a user's account. It checks if the account is active, validates the deposit amount (non-negative), updates the user's balance in the database, records the transaction, and commits changes. If the account is disabled, it notifies the user and exits.
def deposit(name): queryAccounts() if get_status(name): while True: amount = input("What amount would you like to deposit? ") try: amount = float(amount) if amount < 0: print("Must be non-negative!") else: ...
def getiddepByName(h_name,dep_name): # URL to get root process group information id=get_id_hospital_by_name(h_name) resource_url = host_url + "/flow/process-groups/"+str(id) auth_header = {'Authorization': 'Bearer ' + get_auth_token()} response = requests.get(resource_url, headers=auth_header,...
The main task of the code is to delete a specific process group (pipeline) in a hospital's workflow management system. It retrieves the hospital's ID, fetches the target process group's details, constructs a DELETE request URL with authentication, sends the request, handles errors, and returns the JSON response. The fu...
def deleteDep(name_hopital,name_dep,name_p): id_hopital = getiddepByName(name_hopital,name_dep) inf_processor= getInfo_pipline(id_hopital,name_p) # URL to get root process group information resource_url = host_url + "/process-groups/"+inf_processor["id"]+"?clientId="+inf_processor["revision"]["clie...
def getiddepByName(h_name,dep_name): # URL to get root process group information id=get_id_hospital_by_name(h_name) resource_url = host_url + "/flow/process-groups/"+str(id) auth_header = {'Authorization': 'Bearer ' + get_auth_token()} response = requests.get(resource_url, headers=auth_header,...
This function initiates or updates a pipeline process by retrieving hospital/department IDs, authenticating, and sending a PUT request to set the pipeline's state to "RUNNING" via an API, handling errors afterward.
def run_pipeline(name_hopital,name_dep,name_pipeline): id_hopital = getiddepByName(name_hopital,name_dep) info_processor= getInfo_pipline(id_hopital,name_pipeline) id = info_processor["id"] url = host_url + "/flow/process-groups/"+id auth_header = {'Authorization': 'Bearer ' + get_auth_token()}...
def getiddepByName(h_name,dep_name): # URL to get root process group information id=get_id_hospital_by_name(h_name) resource_url = host_url + "/flow/process-groups/"+str(id) auth_header = {'Authorization': 'Bearer ' + get_auth_token()} response = requests.get(resource_url, headers=auth_header,...
This function stops a specified pipeline in a hospital department by retrieving its ID, sending a PUT request to an API endpoint with the "STOPPED" state, and handling potential errors. It uses authentication, constructs a URL, and executes the request to halt the pipeline's operation.
def stop_pipeline(name_hopital,name_dep,name_pipeline): id_hopital = getiddepByName(name_hopital,name_dep) info_processor= getInfo_pipline(id_hopital,name_pipeline) id = info_processor["id"] url = host_url + "/flow/process-groups/"+id auth_header = {'Authorization': 'Bearer ' + get_auth_token()} ...
def get_root_resource_id(): # URL to get root process group information conn=sqlite3.connect('db.sqlite') cursor = conn.cursor() cursor.execute("""SELECT name_hospital FROM db_pipline order by id desc""") user1 = cursor.fetchall() name1=user1[0][0] cursor.execute("""SELECT name_departement ...
This function creates a template instance in a process group by sending a POST request with parameters like template ID and adjusted coordinates, using authentication and error handling.
def instantiate_template(template_file_name, originX, originY): create_instance_url = host_url + "/process-groups/" + get_root_resource_id() + "/template-instance" payload = {"templateId": get_template_id(template_file_name), "originX": originX, "originY": originY} originX = originX + 600 originY = orig...
def remove_template(template_id): if template_id != "": delete_template_url = host_url + "/templates/" + template_id auth_header = {'Authorization': 'Bearer ' + get_auth_token()} response = requests.delete(delete_template_url, headers= auth_header, verify=cert_file, proxies={'https': ''}) ...
The function deploys a template by removing any existing version with the same name, uploading the new template file, instantiating it at specified coordinates, and optionally removing it afterward if 'remove_after_create' is set to 'true'
def deploy_template(template_file, origin_x, origin_y): remove_template(get_template_id(template_file.name)) upload_template(template_file.name) instantiate_template(template_file.name, origin_x, origin_y) if remove_after_create == "true": remove_template(get_template_id(template_file.name))
def load_data(input_file): input_sentences = [] with open(input_file) as istr: for l in istr.readlines(): input_sentences.append(l.strip()) return input_sentences def load_messages_glossary(msg_file): with open(msg_file, 'r') as istr: messages_glossary = json.load(istr) r...
The code processes input and output sentence pairs from files, using a predefined glossary to generate feedback messages. It writes input/output pairs and their associated feedback (with offsets) to 'feedback_v2.txt' for analysis.
def main(args): input_sentences = load_data(args.input_file) output_sentences = load_data(args.output_file) messages_glossary = load_messages_glossary('src/utils/messages.txt') with open('feedback_v2.txt', 'w') as ostr: for input_sent, output_sent in zip(input_sentences, output_sentences): ...
def tokenize_and_segment(input_text: str) -> 'list(str)': """Returns a list of tokenized sentences.""" tokenized_sentences = [] sentences = sentencize(input_text) tok = TweetTokenizer() for sent in sentences: tokenized_sentences.append(tok.tokenize(sent)) return tokenized_sentences def ...
The code's main task is to correct input text by tokenizing, segmenting, applying corrections with a model, and optionally reordering sentences. It returns tagged input/output showing changes and statistics, with reordering handled via a dedicated model if enabled.
def predict(input_text: str, reorder:bool) -> dict: """Predicts a correction for an input text and returns the tagged input and output.""" input_text = unidecode(input_text) tokenized_sentences = tokenize_and_segment(input_text) corrected_sentences = predict_for_sentences(tokenized_sentences, model...
def get_hausdorff(mesh1, mesh2): ms = ml.MeshSet() ms.add_mesh(ml.Mesh(mesh1.V, mesh1.F)) mesh1_id = ms.current_mesh_id() ms.add_mesh(ml.Mesh(mesh2.V, mesh2.F)) mesh2_id = ms.current_mesh_id() dist12 = ms.get_hausdorff_distance(sampledmesh=mesh1_id, targetmesh=mesh2_id) dist21 = ms.get_hausd...
This function computes and returns key statistical metrics of a 3D mesh, such as average aspect ratio, minimum angles, edge lengths, and face counts. If a comparison mesh is provided, it calculates Hausdorff distances. It optionally updates a stats_dict with detailed metrics and returns a dictionary containing selected...
def get_mesh_stats(mesh, comparison_mesh=None, run_haus=True, stats_dict=None, name="placeholder"): if run_haus and comparison_mesh: haus_max, haus_mean = get_hausdorff(mesh, comparison_mesh) else: haus_max = None haus_mean = None if stats_dict is None: Q_exp, AR_avg, min_ang...
def get_new_filename(filename, alg_descriptor): # Handle cases where we are working with faces.dat, vertices.dat file pairs if "faces.dat" in filename.lower(): # Often these .dat pairs are simply named "Faces.dat" and "Vertices.dat" # We ultimately want to write out a "x.ply" file, so we need to...
This function executes a mesh processing algorithm, checks for existing output files, runs the provided function on the input mesh, handles errors, plots results, computes and prints mesh statistics, and optionally cleans and resaves the mesh if issues are detected.
def run_alg(func, orig_mesh, params, mesh_filename, alg_descriptor, outfile=sys.stdout, plot=True, force_rerun=False, to_bem=False, stats_dict=None, clean_flag=False, run_haus=True): new_filename = get_new_filename(mesh_filename, alg_descriptor) if Path(new_filename).exists() and not force_rerun: print(...
def mergeGuards(aut1, aut2, g1, g2): LOG.debug("Merging guards {0} and {1}".format(g1, g2)) conditions = [] guards = [] if g1 == ["e == front()"]: LOG.debug("replacing g1 {0}".format(g1)) g1 = "q0 == {0}".format(aut2.id) conditions.append(g1) else: LOG.debug("g1 remai...
The function merges two communicating transitions from two automata (aut1 and aut2) by combining their source states, conditions, guards, destination states, labels, resets, and updates. It filters out conflicting "qCommitted" states, merges guards and labels, and generates new transitions by cross-combining merged lab...
def mergeCommunicatingTransitions(nTrains, aut1, aut2, t1, t2): LOG.debug("merging communicating transitions {0} and {1}".format(t1, t2)) (source1, condition1, guard1, dest1, label1, reset1, update1) = t1.encoding(aut1) (source2, condition2, guard2, dest2, label2, reset2, update2) = t2.encoding(aut2) ...
def generateProperty(property, gate, trains): global LABELSTORE if property == "canreachcross1": return '''EQUATIONS: {{ 1: mu X = {{ {0} == {1} }} || \exists time(\ExistAct(X)) }}\n'''.format(trains[0].controlName(), trains[0].stateIndexByName("Cross")) elif property == "canreachcross2": re...
The main task of the code is to generate a formal model file describing interactions between trains and a gate, including state definitions, clocks, control variables, invariants, and transitions. It writes these components to a specified output file, incorporating user-defined properties. The model includes local tran...
def generateTrainGate(nTrains, outputFile, property): LOG.info("Generating train/gate for {0} trains".format(nTrains)) outfile = open(outputFile, 'w') gate = Gate() trains = [Train(id) for id in range(1,nTrains+1)] LOG.info("Generating defines for state names of the gate") # Defin...
def _git_repo_status(repo): """Get current git repo status. :param repo: Path to directory containing a git repo :type repo: :class:`pathlib.Path()` :return: Repo status :rtype: dict """ repo_status = { 'path': repo } options = ['git', '-C', str(repo), 'status', '-s'] ...
The code checks if any Git repositories under the specified development root directory are in a "dirty" state (uncommitted changes). It identifies all directories containing a `.git` subdirectory, evaluates their status, and returns a list of repositories with uncommitted changes.
def check_repo_status(dev_root): """Check status of all directories with a .git child under DEV_ROOT for is_dirty. :param dev_root: Path to dev root directory :type repo: :class:`pathlib.Path()` :return: A list of repos where status == dirty :rtype: [dict] """ repo_status = [_git_repo_stat...
def write_artwork_image(self, swap_on_vsync: bool = False) -> None: """Writes the artwork image to the canvas Args: swap_on_vsync (bool, optional): whether to swap the canvas on vsync. Defaults to False. """ self.canvas.SetImage( self.artwork_imag...
This code sets the display's brightness and updates all canvas content to reflect the change. It adjusts the matrix brightness, redraws artwork, and conditionally redraws non-scrollable artist/media title elements to prevent glitches, then swaps the updated canvas with VSync for smooth display.
def brightness(self, value: int) -> None: """Sets the brightness of the display. Force updates all canvas content to apply the brightness Args: value (int): the brightness of the display """ self.matrix.brightness = value self.write_artwork_image() ...
def infonce_lower_bound(scores): '''Bound from Van Den Oord and al. (2018)''' nll = torch.mean(torch.diag(scores) - torch.logsumexp(scores, dim=1)) k = scores.size()[0] mi = np.log(k) + nll return mi def infonce_lower_bound_weighted_clipping(scores, lamb=4e-2, c=20): '''Bound from Van Den Oord a...
The function `estimate_mutual_information` computes a variational lower bound on mutual information between variables `x` and `y` using a specified estimator method (e.g., NWJ, InfoNCE, TUBA). It leverages a critic function to generate pairwise scores and applies the chosen estimator's formula, optionally incorporating...
def estimate_mutual_information(estimator, x, y, critic_fn, baseline_fn=None, alpha_logit=None): """Estimate variational lower bounds on mutual information. Args: estimator: string specifying estimator, one of: 'nwj', 'infonce', 'tuba', 'js', 'interpolated' x: [bat...
def __transform(self, treatment_file=None): """ Perform all the necessary treatments for missing values and outliers for all the columns :param treatment_file: Path to the generated Excel file :return df: Dataframe which contains all the treated data """ print('transform...
The function performs variable profiling by transforming data, applying numerical and categorical binning, hierarchical clustering, and generating summaries. It uses parameters to control binning methods, thresholds, cluster constraints, and saves results to a specified path.
def variable_profiling(self, summary_path=None, numerical_binning=None, dep_var=None, depth=None, no_of_bins=None, ordinal_binning_type='naive', max_threshold=10, min_threshold=5, tolerence=2, flag='ignore', min_cluster_size=0.05, max_clusters=10): """ This function calls all the required function to pe...
def h(p1, p2): x1, y1 = p1 x2, y2 = p2 return abs(x1 - x2) + abs(y1 - y2) def reconstruct_path(came_from, current, draw): while current in came_from: current = came_from[current] current.create_path() draw() def draw(win, grid, rows, width): win.fill(BLACK) for ...
This function implements the A* pathfinding algorithm to find a path from a start node to an end node on a grid. It uses a priority queue to explore nodes, calculates heuristic (h) and cost (g) values, updates neighbors, and visualizes the search process by marking open/closed nodes. If a path is found, it reconstructs...
def a_path_algorithm(draw, grid, start, end): count = 0 open_set = PriorityQueue() open_set.put((0, count, start)) came_from = {} g = {node: float('inf') for row in grid for node in row} g[start] = 0 f = {node: float('inf') for row in grid for node in row} f[start] = h(start.get_position...
def create_grid(rows, width): grid = [] gap = width // rows for i in range(rows): grid.append([]) for j in range(rows): node = Node(i, j, gap, rows) grid[i].append(node) return grid def draw(win, grid, rows, width): win.fill(BLACK) for row in grid: ...
The main task of the code is to create a pathfinding visualization using Pygame, allowing users to set start/end points, add walls, and execute the A* algorithm. It handles mouse interactions for grid modification, triggers pathfinding on spacebar press, and resets the grid with 'r', drawing the grid dynamically in a l...
def main(win, width): ROWS = 60 grid = create_grid(ROWS, width) start = None end = None run = True while run: draw(win, grid, ROWS, WIDTH) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if pygame.mouse.ge...
def loadLookupLemmatizer(file_name): lemmatizerHashmap={} with open(file_name, 'r+') as f: text = f.readlines() for line in text: line=line.replace("[\\s]+", "\t").strip() split_list = line.lower().split("\t") lemma = split_list[0].strip().lower() ...
The main task of the code is to process text data by loading a spaCy model and a lemmatizer, then generating citation networks (`.cites` files) from input files. It ensures output directories exist, removes disconnected nodes, rebuilds citation structures, and finally constructs an adjacency matrix for the processed da...
def main(): top_k = 100 spacy_nlp = spacy.load('en_core_web_sm', disable=["parser", "ner", "entity_linker", "textcat", "entity_ruler"]) lemmatizerHashmap = loadLookupLemmatizer(PATH_LEMMA_FILE) if not os.path.exists(PATH_OUTPUT): os.makedirs(PATH_OUTPUT) for folder in ['1', '2', '3', '4'...
def loadLookupLemmatizer(file_name): lemmatizerHashmap={} with open(file_name, 'r+') as f: text = f.readlines() for line in text: line=line.replace("[\\s]+", "\t").strip() split_list = line.lower().split("\t") lemma = split_list[0].strip().lower() ...
The main task of the code is to process text data using a Spacy model and custom lemmatizer, build a citation network (cites) for a specified output directory, and generate an adjacency matrix. It ensures output directories exist, disables unnecessary Spacy components for efficiency, and focuses on constructing graph s...
def main(): spacy_nlp = spacy.load('en_core_web_sm', disable=["parser", "ner", "entity_linker", "textcat", "entity_ruler"]) lemmatizerHashmap = loadLookupLemmatizer(PATH_LEMMA_FILE) if not os.path.exists(PATH_OUTPUT_UPDOWNSAMPLE_first): os.makedirs(PATH_OUTPUT_UPDOWNSAMPLE_first) #up_downsample(...
def get_raid_duration(self): data = self.data raid_start = self.__from_timestamp(data.get("start", 0)) raid_end = self.__from_timestamp(data.get("end", 0)) duration = raid_end - raid_start return duration.total_seconds() def get_active_time(self): data = self.data ...
The code generates a time report by aggregating three time-related metrics: RAID duration, active time, and inactive time. It calls three separate methods to retrieve these values, compiles them into a dictionary, and returns the structured data for further processing or analysis.
def get_time_report(self): time_report = {"raid_duration": self.get_raid_duration(), "active_time": self.get_active_time(), "inactive_time": self.get_inactive_time()} return time_report
def same_box_associate_matrix(bboxs): N = len(bboxs) matrix = np.zeros((N, N)) for i in range(N): for j in range(i, N): if j == i: matrix[i, i] = 1.0 else: if is_same_bbox(bboxs[i], bboxs[j]): matrix[i, j] = matrix[j, i] =...
The function merges overlapping bounding boxes by creating an association matrix to identify overlaps, filtering these associations, updating labels based on thresholds, and combining matched boxes into merged regions. It handles empty inputs, uses helper functions for association, label updates, and merging, then retu...
def merge_bboxs(bboxs): if not bboxs: return [] associate_matrix = same_box_associate_matrix(bboxs) print('associate_matrix', associate_matrix) flatten_matrix = filter_and_flatten_associate_matrix(associate_matrix) matched_bboxs = [MatchedBbox(bbox, match_id) for match_id, bbox in enumerate(...
def filter_sports_ball_action(hois): sports_ball_hois = list() for hoi in hois: action_id, bbox_human, bbox_obj, connection, invis = hoi if action_id in sport_ball_action_ids and invis == 0: sports_ball_hois.append(hoi) return sports_ball_hois def merge_bboxs(bboxs): if not b...
The code transforms the HICO dataset annotations into a JSON format focused on sports ball actions. It processes 'train' and 'test' subsets, extracts bounding boxes, filters relevant actions, merges overlapping boxes, detects keypoints, and constructs structured JSON entries with human/object boxes, connections, and ke...
def transform_hoi_to_small_json_dataset(annotation_path): annotation = scio.loadmat(annotation_path) parts = ['train', 'test'] for part in parts: sport_ball_json_dataset_path = '/home/icicle/Documents/Datasets/hico_20160224_det/sports_ball_action_{}.json'.format(part) actions = annotation...
def encode(text: str, coding=consts.ENCODING) -> bytes: return text.encode(coding) def decode(msg: bytes, coding=consts.ENCODING) -> str: return msg.decode(coding) def parse_msg(msg: str, name: str, client: socket) -> bool: global users, users_lock match msg: case str(consts.DISCONNECT): ...
This function handles a new client connection by authenticating them. It checks if the provided username is already taken or if the user is banned. If valid, it registers the user, sends an authentication success message, and starts a new thread to handle the client's communication.
def new_client(client: socket, cl_address: tuple) -> str: global users, users_lock client.send(encode(consts.GREETING)) while True: msg = decode(client.recv(1024)) if not parse_msg(msg, str(cl_address), client): return with users_lock: if msg in users.keys(): ...
def get_source_categories(config_db_url, category_no=None): # t1.be_data_source_id source_id, source_categories_query = "select distinct t1.category_no from be_attributes_data_rules t1 " +\ " join be_data_sources t2 on t2._id = t1.be_data_source_id and t2.active = 1" \ ...
The main task of the code is to initiate and manage data quality (DQ) processes by executing rules or upgrading categories based on the specified `dq_type`. It initializes parameters, retrieves source categories, and iterates through them to apply DQ rules (for `dq_type=1` or None) or perform category upgrades (for `dq...
def start_dq(self, process_no, cpu_num_workers, dq_type=None, dq_category_no=None, p_source_id=None, p_be_att_id=None, p_be_att_dr_id=None, p_join_with_f=None): # print('process_no, cpu_num_workers, dq_type=None, dq_category_no=None') # print(process_no, cpu_num_workers, dq_type, dq_cat...
def load_parameters(): js = json.load(open(r'./parameters.json', 'r')) return js def load_config_template(): template_conf = json.load(open(TEMPLATE_PARAM_PATH, 'r')) template_dsl = json.load(open(TEMPLATE_DSL_PATH, 'r')) return template_conf, template_dsl def generate_configs(param, para_list): ...
The main task of the code is to execute a batch of tests using varying configurations generated from parameter lists. It loads template parameters, generates configuration names, saves a DSL file, iterates through each configuration to run tests, logs results to a history file, and prints progress updates. The function...
def run_batch_test(batch_test_name='cwj', stop_cv_iter=50): para_list = load_parameters() param, dsl = load_config_template() conf_names = generate_configs(param, para_list) check_cpn = list(param["algorithm_parameters"].keys())[0] dsl_path = './dsls/{}_dsl.json'.format(batch_test_name) json.du...
def approve_token_and_check_balance(): # check token allowance token_allowance = oracle_token_contract.functions.allowance( acct.address, autopay_contract.address).call() logging.info("token allowance: %s", token_allowance) if token_allowance < config.token_approval_amount / 10: # approv...
The main task of the code is to monitor Chainlink oracle data, check balance sufficiency, and trigger a tipping sequence when conditions like insufficient reporting intervals, Chainlink anomalies, or collateral price thresholds are met. If not, it rechecks balances and waits until the next interval, looping indefinitel...
def main(): query_id = config.query_id query_data = config.query_data interval = config.interval start_time = config.start_time collateral_token_price = 0 balances = approve_token_and_check_balance() while True: last_report_time = get_last_report_time(query_id=query_id) seco...
def class_subMsk(ip, dec=True, outClass=False): subMask = 'NA' ipBin = ip_to_bin(ip, join=True) if ipBin[0] == '0': subMask = '1'* 8 + '0' * 24 # 8/24 elif ipBin[1] == '0': subMask = '1'* 16 + '0' * 16 # 16/16 elif ipBin[2] == '0': subMask = '1'* 24 + '0' * 8 # 24/8 elif ipBin[3] == '0': pr...
The function `get_subMsk` calculates a subnet mask based on an IP address's class and specified subnet bits. It first determines the default subnet mask, splits it into network and host portions, then constructs a new subnet mask by allocating the given subnet bits to the host portion. If valid, it returns the mask in ...
def get_subMsk(ip, subnetBits, slash=False): # Determine the default class subnet mask ipDefSubMask = class_subMsk(ip, dec=False) # Determine the network and host portion if ipDefSubMask != 'NA': netPortion = count_01(ipDefSubMask)[0] hostPortion = count_01(ipDefSubMask)[1] # Determine the sub...
def class_subMsk(ip, dec=True, outClass=False): subMask = 'NA' ipBin = ip_to_bin(ip, join=True) if ipBin[0] == '0': subMask = '1'* 8 + '0' * 24 # 8/24 elif ipBin[1] == '0': subMask = '1'* 16 + '0' * 16 # 16/16 elif ipBin[2] == '0': subMask = '1'* 24 + '0' * 8 # 24/8 elif ipBin[3] == '0': pr...
The main task of the code is to calculate the number of subnets and hosts per subnet for a given IP address and subnet bits. It verifies if the subnet bits are within valid limits, computes total subnets as 2^subnetBits, and hosts per subnet as 2^(hostBits - subnetBits) - 2, returning these values in a dictionary. If i...
def classful_count(ip, subnetBits=0): classSubMask = class_subMsk(ip, dec=False) if classSubMask != 'NA': hostBitsCount = count_01(classSubMask)[1] if subnetBits >= 0 and subnetBits <= hostBitsCount - 2: subnetNum = 2 ** subnetBits hostNum = 2**(hostBitsCount - subnetBits) - 2 # if hostNum...
def ip_to_bin(ip, join=True): splitIP = ip.split(".") octetBin = [] if len(splitIP) != 4: pr_info("[-] Please provide a valid IPv4 address.") else: try: for octet in splitIP: if int(octet) >= 0 and int(octet) <= 255: octet = bin(int(octet))[2:] else: pr_info('[-...
The function `get_subnet_id` calculates a specific subnet ID based on an input IP address, subnet bits, and subnet number. It converts the IP to binary, determines the default subnet mask, and checks validity of subnet parameters. If valid, it constructs the subnet ID by combining network bits, the specified subnet num...
def get_subnet_id(ip, subnetBits=0, subnetNum=0, dec=True): ipBin = ip_to_bin(ip) defSubMsk = class_subMsk(ip, dec=False) if len(defSubMsk) == 32: netCount = classful_count(ip,subnetBits) totSubnets = netCount['Total subnets'] if subnetBits == 0: if dec == True: return ip else...
def get_subnet_id(ip, subnetBits=0, subnetNum=0, dec=True): ipBin = ip_to_bin(ip) defSubMsk = class_subMsk(ip, dec=False) if len(defSubMsk) == 32: netCount = classful_count(ip,subnetBits) totSubnets = netCount['Total subnets'] if subnetBits == 0: if dec == True: return ip else...
This function calculates a specific host's IP address within a given subnet by combining network, subnet, and host bits. It validates the hostID range, constructs the binary address from the subnet base, and returns the resulting IP. If hostID is invalid, it provides warnings or returns the subnet base address.
def get_sub_hostAdd(ip, subnetBits=0, subnetNum=0, hostID=0): subBaseAddr = get_subnet_id(ip, subnetBits, subnetNum, dec=True) baseAddClass = class_subMsk(subBaseAddr, dec=False) if len(baseAddClass) == 32: netCount = classful_count(ip,subnetBits) # totSubnets = netCount['Total subnets'] hostsPerSubne...
def read_modbus(self, parameter: str, force_full_register_read=False): command_name = f"{parameter}_READ" response: list = self.execute_modbus_command(command_name) if not response: return None result = self.scale_response(response, command_name, force_full_register_read) ...
This function writes values to a Modbus device by configuring command parameters, handling bit manipulation or scaling, executing the write command, and validating the response. It processes input values based on device-specific settings, logs errors for invalid responses, and returns a structured result with written v...
def write_modbus(self, parameter: str, values: list): command_name = f"{parameter}_WRITE" command_config = self.device_config[command_name] starting_address = self.device_config[command_name].get("start") register_length = self.device_config[command_name].get("length") data_for...
def is_disjoint(self, working_path: Path, backup_path: Path) -> bool: # takes working and backup as parameters if working_path.node_list != backup_path.node_list: for i in range(1, len(working_path.node_list) - 1): # for each value of the working_path node list, if working_path.no...
The main task of the code is to process a service request by evaluating and allocating working and backup paths with specific spectrum slots, ensuring path disjointness and resource availability. It tracks metrics like failure rates, path lengths, and resource utilization, updates the network state, and computes a rewa...
def step(self, action: [int]): # We can refuse the service if one of the two is not working working_path, initial_slot_working, backup_path, initial_slot_backup, backup_dpp_path, initial_slot_backup_dpp = action[0], action[1], action[2], action[ 3], action[4], action[5] self.actions_output[ ...
def parsetotree(l): # take a list and parse to a tree root = Node() if isinstance(l,int): root.val = l return root root.left = parsetotree(l[0]) root.right = parsetotree(l[1]) root.left.par = root root.right.par = root return root def printTree(root): if root is Non...
The code reads numbers from a file, converts them into tree structures, sequentially adds these trees, and outputs the final tree structure along with its calculated magnitude.
def p1(f): numlist = [eval(line.strip('\n')) for line in f.readlines()] # transform numlist to list of tree numlist = [parsetotree(num) for num in numlist] for tree in numlist: printTree(tree) print() currentNum = numlist[0] numlist = numlist[1:] while numlist != []: ...
def magnitude(node): if node.val != None: return node.val return 3 * magnitude(node.left) + 2 * magnitude(node.right) def add(t1,t2): root = Node() root.left = t1 root.right = t2 root.left.par = root root.right.par = root reduce(root) return root def parsetotree(l): # tak...
The main task of the code is to compute the maximum magnitude achievable by adding every possible pair of numbers from the input file, where each number is parsed into a tree structure, summed, and their magnitude calculated. The result is printed as "Max magnitude: [value]".
def p2(f): numlist = [eval(line.strip('\n')) for line in f.readlines()] maxMag = 0 for i in range(len(numlist)): for j in range(len(numlist)): if i != j: magsum = magnitude(add(parsetotree(numlist[i]),parsetotree(numlist[j]))) if magsum > maxMag: ...
def valid_matrix(self, m): #TODO: implement return True def set_from_list(self, m): self.mat = [] if isinstance(m[0], list) or isinstance(m[0], Mat): for n in m: if isinstance(n, Mat): n = n.mat # Should self.mat.append(Mat...
This code initializes a matrix object by either constructing it from a list (if provided) or from a specified shape. It validates input formats, ensures correct parameters, and sets internal attributes like the matrix data, shape, and rank.
def __init__(self, firstElement, *args, **kwargs): if isinstance(firstElement, list): assert self.valid_matrix(firstElement), 'Invalid Matrix' assert len(args) == 0, 'Setting using iterable' self.set_from_list(firstElement) else: assert self.valid_shape(fi...
def normalize_data(data): x = (data - np.min(data, axis=0)) / (np.max(data, axis=0) - np.min(data, axis=0) + 1e-10) for i in range(x.shape[0]): x[i] = x[i] / np.linalg.norm(x[i]) return x def get_v(): v1p, v2p, v3p = np.random.normal(0, 1, NUMBER_OF_FEATURES), np.random.normal(0, 1, ...
The code processes TCGA RNAseq data by normalizing it and generating continuous datasets using predefined vectors. It splits data into training, validation, and test sets for multiple runs, saving each subset as CSV files. Additionally, it computes and stores output grids for both input and test data, organizing all re...
def save_files(dir='../dataset/tcga/', run_n=50): tcga_data = pickle.load(open(dir + 'tcga.p', 'rb')) data = normalize_data(tcga_data['rnaseq']) v1, v2, v3 = get_v() for _ in range(run_n): print("generating dataset: ", str(_)) curr_dir = dir + str(_) if not os.path.exists(curr_di...
def _random_phrase(self, label: str) -> str: index = randint(0, len(self.phrases[label]) - 1) return self.phrases[label][index] def _get_valid_attacks(self, character: Character) -> List[str]: def predicate(attack_name): return self.attacks[attack_name]['mana_required'] <= character....
This function handles a player's turn in a combat scenario by displaying a turn prompt, presenting available attacks via a menu, and executing the chosen attack against an enemy.
def _player_turn(self, player: Character, enemy: Character) -> None: self.text_engine.print() self.text_engine.print(self._random_phrase('player_turn').format(enemy_name=enemy.name)) valid_attacks = self._get_valid_attacks(player) attack = self.text_engine.menu(valid_attacks, ">") ...
def _random_phrase(self, label: str) -> str: index = randint(0, len(self.phrases[label]) - 1) return self.phrases[label][index] def _get_valid_attacks(self, character: Character) -> List[str]: def predicate(attack_name): return self.attacks[attack_name]['mana_required'] <= character....
The function handles an enemy's turn in a combat scenario by printing a random attack message, selecting a random valid attack from the enemy's available options, and executing that attack against the player.
def _enemy_turn(self, player: Character, enemy: Character) -> None: self.text_engine.print() self.text_engine.print(self._random_phrase('enemy_turn').format(enemy_name=enemy.name)) valid_attacks = self._get_valid_attacks(enemy) attack_index = randint(0, len(valid_attacks) - 1) a...
def _random_phrase(self, label: str) -> str: index = randint(0, len(self.phrases[label]) - 1) return self.phrases[label][index] def _player_turn(self, player: Character, enemy: Character) -> None: self.text_engine.print() self.text_engine.print(self._random_phrase('player_turn').format(e...
This code simulates a turn-based combat between a player and an enemy. It alternates between player and enemy actions, checks for health status after each turn, awards experience and gold upon victory, handles level progression if applicable, and returns True for victory or False for defeat.
def fight(self, player: PlayerCharacter, enemy: Character) -> bool: self.text_engine.set_player_status(player) self.text_engine.print(self._random_phrase('encounter').format(enemy_name=enemy.name)) old_level = player.level() while True: self._player_turn(player, enemy) ...
def calculate_hhm(threads, a3m_base_path, hhm_base_path): """Calculate hhm using a3m Args: threads (int): Number of cpus to use a3m_base_path (string): Path to a3m database hhm_base_path (string): Path to hhm database """ tmp_dir = tempfile.mkdtemp() large_a3ms = get_l...
The function checks the existence and integrity of FASTA database files (a3m, hhm, cs219), creates missing files, modifies file entries for consistency, and validates formats, sorting, duplicates, and data completeness. It ensures databases meet required conditions for downstream analysis, with placeholders for additio...
def check_database(output_basename, threads, force_mode): """Check for the fasta database and the metadata of the fasta database . Args: output_basename (string): Path to the database folder with the prefix threads (int): number of cpus force_mode (bool): if value need to be forced or n...
def read_rc_examples(input_file, tokenizer: BertTokenizer, first_answer_only=False, include_source_info=False): """Read a RC jsonl file into a list of RCExample.""" #filter_pattern = re.compile("[\d{}]+$".format(re.escape(string.punctuation))) filter_pattern = re.compile("[{}]+$".format(re.escape(string.pun...
This function processes a JSONL input file into training batches for a reading comprehension model. It reads examples, converts them into tokenized features, shuffles them, and yields batches of specified size. The output is a generator providing tokenized training data with answer information, suitable for model train...
def _get_rc_dataset(input_file, tokenizer, max_seq_length, doc_stride, max_query_length, train_batch_size): """ NOTE: not suitable for distributed setting - see RCData instead The input_file is jsonl. Each record has: id : string id for this question/passage combo question : question string pass...
def open_sentences(sentencesFile): sentences = open(sentencesFile, 'r') return sentences def open_outputfile(outfile): outfile = open(outfile, 'w') return outfile def parse_cyk(start, grammar, sent): #this function performs the primary cky algorithm using a table (T) and a pointer, which will be used fo...
The main task of the code is to parse sentences using a probabilistic context-free grammar (PCFG) via the CYK algorithm. It reads a grammar file, tokenizes sentences from an input file, parses each sentence with the grammar, and writes the parsing results to an output file. The code uses command-line arguments to speci...
def main(): sentencesFile = sys.argv[2] sentences = open_sentences(sentencesFile) strng = '' grammar_file = sys.argv[1] outfile = sys.argv[3] outfile = open_outputfile(outfile) grammar = open(grammar_file, 'r') for i in grammar: strng += i #input pcfg as s...
def open_sentences(sentencesFile): sentences = open(sentencesFile, 'r') return sentences def open_outputfile(outfile): outfile = open(outfile, 'w') return outfile def parse_cyk(start, grammar, sent): #this function performs the primary cky algorithm using a table (T) and a pointer, which will be used #f...
The code parses sentences using a CYK parser with a given grammar, writing each sentence's parse tree and number of valid parses to an output file. It reads input sentences, loads a grammar, tokenizes sentences, and applies the CYK algorithm to generate parsing results and counts for each sentence.
def main(): sentencesFile = sys.argv[2] sentences = open_sentences(sentencesFile) grammarFile = sys.argv[1] grammar = nltk.data.load(grammarFile) productions = grammar.productions() start = grammar.start() outfile = sys.argv[3] outfile = open_outputfile(outfile) counts...
def applyKernel(im, kernel): ''' return Mx, where x is im ''' return convolve3(im, kernel) def applyConjugatedKernel(im, kernel): ''' return M^T x, where x is im ''' return convolve3(im, kernel.transpose()) def computeResidual(kernel, x, y): ''' return Mx - y ''' Mx = applyKernel(x, kernel) out = np.subtr...
The code implements an iterative gradient descent algorithm for image deblurring. It applies a convolution kernel to a blurred image, computes residuals, adjusts the deblurred image estimate using step sizes, and iteratively refines the result over 'niter' steps to reconstruct a sharper image.
def deconvGradDescent(im_blur, kernel, niter=10): ''' return deblurred image ''' for i in range(niter): x = np.empty([im_blur.size(), im_blur.size(), 3]) x[:, :]= 0 if(i == 0): im = x mx = applyKernel(im_blur, kernel) mtmx = applyConjugatedKernel(mx, kernel) r = computeResidual(kernel....
def applyConjugatedKernel(im, kernel): ''' return M^T x, where x is im ''' return convolve3(im, kernel.transpose()) def computeResidual(kernel, x, y): ''' return Mx - y ''' Mx = convolve3(x, kernel) out = y - Mx return out def computeStepSize(r, kernel): ''' alpha = r dot r / (r dot (M^T * M * r)) ''' r...
The code performs iterative deblurring of an image using gradient descent. It initializes a deblurred image `x` and updates it by computing a residual `r` via the conjugated kernel and step size `alpha`, adjusting `x` in each iteration to minimize the blur. The process repeats for `niter` steps, returning the refined d...
def deconvGradDescent(im_blur, kernel, niter=10): ''' return deblurred image ''' x = io.constantIm(im_blur.shape[0], im_blur.shape[1], 0.0) for i in range(niter): '''r = M^Ty - M^TMx''' r = applyConjugatedKernel(computeResidual(kernel, x, im_blur), kernel) alpha = computeStepSize(r, kernel) x = x ...
def applyConjugatedKernel(im, kernel): ''' return M^T x, where x is im ''' return convolve3(im, kernel.transpose()) def computeResidual(kernel, x, y): ''' return Mx - y ''' Mx = convolve3(x, kernel) out = y - Mx return out def computeGradientStepSize(r, d, kernel): ''' write A as MtM ''' ''' alpha = r d...
This function performs deblurring of an input image using a conjugate gradient algorithm. It iteratively updates an initial estimate of the deblurred image (x) by computing residual errors (r), gradient step sizes (alpha), and conjugate directions (d), adjusting x to minimize the discrepancy between the blurred image a...
def deconvCG(im_blur, kernel, niter=10): ''' return deblurred image ''' x = io.constantIm(im_blur.shape[0], im_blur.shape[1], 0.0) r = applyConjugatedKernel(computeResidual(kernel, x, im_blur), kernel) d = r for i in range(niter): '''r = M^Ty - M^TMx''' alpha = computeGradientStepSize(r, d, kernel) ...
def applyKernel(im, kernel): ''' return Mx, where x is im ''' return convolve3(im, kernel) def applyRegularizedOperator(im, kernel, lamb): ''' (A + lambda L )x = Ax + lambda * Lx''' Ax = applyKernel(im, kernel) L = applyLaplacian(im) Lx = np.multiply(lamb, L) return Ax + Lx def computeGradientStepSize_reg...
This code performs regularized deconvolution on a blurred image using the Conjugate Gradient (CG) method. It iteratively updates an initial zero image (x) by minimizing the difference between the blurred image and the kernel-convolved result, incorporating a regularization term (λ) to prevent overfitting. The algorithm...
def deconvCG_reg(im_blur, kernel, lamb=0.05, niter=10): ''' return deblurred and regularized im ''' x = io.constantIm(im_blur.shape[0], im_blur.shape[1], 0.0) r = applyKernel(im_blur, kernel) - applyRegularizedOperator(x,kernel,lamb) d = r for i in range(niter): alpha = computeGradientStepSize_reg(r, d, k...
def clear() -> None: os.system('cls' if os.name == 'nt' else 'clear') def __display_decks(self) -> None: print('Loaded decks:\n') for name, url in self.__config.decklist.items(): print(name) def __print_options(self, has_decks: bool) -> None: print('\nOptions:\n') print( ...
The main task of the code is to display a command-line menu interface, including the application logo, scraper status, available decks (if any), and interactive options. It clears the screen, updates the UI dynamically, and redirects user input handling based on deck availability. The loop continuously refreshes the me...
def display_menu(self) -> None: while 1: if self.__clear_screen: clear() self.__clear_screen = True has_decks = len(self.__config.decklist) > 0 print(self.__logo + '\n\n') if self.__running: print('SCRAPER IS RUNNING\n'...
def escape_latex_code(text): "Escape verbatim Mathics input" text = escape_latex_output(text) escape_char = get_latex_escape_char(text) return "\\lstinline%s%s%s" % (escape_char, text, escape_char) def get_results_by_test(test_expr: str, full_test_key: list, doc_data: dict) -> list: """ Sometim...
The code generates LaTeX-formatted test case documentation by embedding test content, output messages/prints, and results into a structured LaTeX environment. It escapes LaTeX special characters, handles dynamic data retrieval via `doc_data`, and conditionally includes results based on test outcomes, returning the comp...
def latex(self, doc_data: dict) -> str: text = "" text += "\\begin{testcase}\n" text += "\\test{%s}\n" % escape_latex_code(self.test) if self.key is None: return "" output_for_key = doc_data.get(self.key, None) if output_for_key is None: output_for...
def create_config_file(self): if not os.path.exists(self.CONFIG_FILE_NAME): f = open(self.CONFIG_FILE_NAME, 'w') f.write('{}') f.close() def request_new_license(self): response = self.send_request( 'post', self.get_endpoint_url('licenses') ...
This method reads a configuration file, parses its JSON content, sets default values for missing keys like 'api_host', requests and stores a license if not present, and retrieves a viewer token if needed. It then updates the internal configuration with these values and writes the updated config back.
def read_config(self): self.create_config_file() with open(self.CONFIG_FILE_NAME, 'r') as config_file: try: data = json.load(config_file) self._config = data except json.decoder.JSONDecodeError: data = {} if 'api_host'...
def change_file_status(self, file_id, new_status): response = self.send_request( 'patch', self.get_endpoint_url('files', file_id), {'status': new_status} ) return response.json() def send_request(self, request_type, endpoint, data=None): if data is Non...
The function `add_file_stats` updates file statistics by sending a POST request to a server endpoint. If `stats` is invalid (e.g., file not found), it marks the file as 'Unavailable' and returns `False`. Otherwise, it transmits the file ID and stats to the server, returning the JSON response.
def add_file_stats(self, file_id, stats): # If status == False it means file was not found if not stats: self.change_file_status(file_id, 'Unavailable') return False response = self.send_request( 'post', self.get_endpoint_url('file_stats'), ...
def update_position(self, person, old_pos, new_position): # self.alive_people[person] = new_position self.alive_people.update_pos(person, old_pos, new_position) def spread_diesase(self, person): neighbors = self.find_neighbors(person) for neighbor in list(neighbors): if neigh...
This code simulates a single time step in a disease spread model. It processes each alive person's movement, checks if they die, updates their positions, spreads disease if transmissible, and removes dead individuals from the alive list while recording their positions in the dead_people dictionary.
def step(self): people_dead_in_this_step = {} for person, pos in self.alive_people.items(): new_pos, died = person.step() # TODO: use observer pattern if died: people_dead_in_this_step[person] = pos self.update_position(person, pos, new_pos) ...
def calculate_max_and_min(offense, defense, special_teams, teams, won): offense_max = max_team(offense) offense_min = min_team(offense) defense_max = max_team(defense) defense_min = min_team(defense) special_teams_max = max_team(special_teams) special_teams_min = min_team(special_teams) prin...
The function analyzes sports team statistics across offense, defense, and special teams phases. It calculates goal-meeting teams, evaluates win rates, and generates visualizations. It processes input data to determine how many teams met goals in individual and combined phases, adjusts special teams metrics, and outputs...
def calculate_stats(conference, data_base): if conference == 'ALL': sort = database.get_all(data_base) else: sort = database.conference_sort(conference, data_base) teams = sort[0] offense = sort[1] defense = sort[2] special_teams = sort[3] won = sort[4] calculate_max_and_...
def _throw_exception(self, message: str, code: int) -> None: body = {"message": message, 'status_code': code} self._response_handler(body) def _validate_token(self) -> bool: token = self.headers.get('Authorization') if not token: self._throw_exception('Token is missing.', 401...
This method handles HTTP requests by routing based on the request method and path, validating tokens for protected routes, parsing headers/query parameters, processing JSON payloads for POST requests, and invoking the appropriate handler with injected dependencies like the database and parsed data, then passing the res...
def _request_handler(self) -> None: handler_dict: Dict[str, Any] = self.REQUEST_METHODS.get( self.command, {}) parsed_path = urlparse(self.path) path = parsed_path.path if handler_dict is not None and path not in handler_dict: self._throw_exception(message='Not F...
def navigate_to_county_page(self, county_link) -> None: self.driver.get(county_link) self.wait.until(EC.presence_of_element_located((By.TAG_NAME, "body"))) self.random_wait() self.driver.find_element( By.ID, "ContentPlaceHolder1_ButtonAccept").click() self.wait.until(...
This function retrieves case data for a specified case number by navigating to the relevant county webpage, filling out a form, and fetching the case details. It uses the county name to locate the correct link, performs necessary actions on the page, and returns the extracted data as a tuple.
def get_single_case_data(self, case_number) -> tuple: county_link = self.counties[self.county_name] self.navigate_to_county_page(county_link) self.fill_form() return self.get_case_data(case_number)