dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _load_combined_attributes(self): """This function loads data set specific attributes and combines them with hydroatlas attributes""" dfs = [] # load dataset specific attributes from the subclass if self.cfg.static_attributes: df = self._load_attributes() # r...
The main task of the code is to load and preprocess hydrometeorological data for a hydrological model. It first loads attributes to validate features, then loads or creates an xarray dataset. Depending on the loss function (NSE/WeightedNSE), it calculates basin-specific discharge standard deviations. If normalization i...
def _load_data(self): # load attributes first to sanity-check those features before doing the compute expensive time series loading self._load_combined_attributes() xr = self._load_or_create_xarray_dataset() if self.cfg.loss.lower() in ['nse', 'weightednse']: # get the std ...
def _initialize_frequency_configuration(self): """Checks and extracts configuration values for 'use_frequency', 'seq_length', and 'predict_last_n'""" # If use_frequencies is not supplied, we'll fill it with the native frequency while loading the df. self.frequencies = self.cfg.use_frequencies ...
This code initializes a dataset for time series analysis, handling different modes (train/validation/test), basin-specific configurations, and data preprocessing. It validates inputs, loads basin data, manages feature scaling, and sets up structures for storing data, dates, and metadata. The constructor also prepares f...
def __init__(self, cfg: Config, is_train: bool, period: str, basin: str = None, additional_features: List[Dict[str, pd.DataFrame]] = [], id_to_int: Dict[str, int] = {}, scaler: Dict[str, Union[pd.Serie...
def set_up_sim(self, population_parameters): self.output_file = open(self.general_output_filename + "_" + population_parameters["pop_name"] + ".slim" , "w") #Set up the initialize and fitness functions for the new script self.write_initialize(population_parameters) self.write_fitness() ...
The code defines a subpopulation in a simulation, either as a new population or a split from an existing one. It generates strings for population setup, handles fixations, population sizes, and writes these to an output file. It also calls methods to write repeated commands and end population definitions, ensuring prop...
def write_subpop(self, population_parameters): if(population_parameters["parent_pop_name"] == None): self.set_up_sim(population_parameters) else: #Not the starting population, break off from existing population define_population_string = (str(int(population_para...
def set_up_sim(self, population_parameters): self.output_file = open(self.general_output_filename + "_" + population_parameters["pop_name"] + ".slim" , "w") #Set up the initialize and fitness functions for the new script self.write_initialize(population_parameters) self.write_fitness() ...
This method generates simulation code for creating subpopulations derived from existing ones. It either initializes a new population or splits off from a parent, handling migrant counts (full or half), copying fixation parameters, and writing fitness scaling events. It outputs code snippets for simulation setup, early ...
def write_subpop_nonwf(self, population_parameters): if(population_parameters["parent_pop_name"] == None): self.set_up_sim(population_parameters) else: #Not the starting population, break off from existing population define_population_string = (str(int(population_...
def new_game(self): self.__world.reset() self.setup() self.__iteration += 1 def state_to_xy(self, state): return (state[1] + 0.5) * Consts.SPRITE_SIZE, \ (self.__world.environment.height - state[0] - 0.5) * Consts.SPRITE_SIZE def state_to_xy_tool(self, state): retu...
This code handles game updates by checking the agent's state. If the agent dies or collects treasure, it triggers a game over screen. Otherwise, it updates positions, processes collisions with obstacles (rocks, bees), removes collided objects, and manages player health by removing hearts when the agent is hurt.
def on_update(self, delta_time): agent_state = self.__world.agent.state if self.__world.agent.is_dead(): self.new_game() game_over_view = GameOverView( self, self.__width, self.__height, is_won=False, restart_automatically=Consts.RESTART_AUTOMATIC...
def read_code_and_save(in_file:str)->str: with open(in_file,"rb") as fd: code = fd.read() md = Cs(CS_ARCH_X86, CS_MODE_16) md.detail = True in_file_name, in_file_extension = os.path.splitext(in_file) out_file = open(in_file_name+"_disass.s","w") for i in md.disasm(code, 0x0): i_a...
The main task of the code is to disassemble a binary file, analyze its control flow structure by separating code blocks, identifying branch points and basic blocks, generating a control flow graph, and visualizing it. It processes input files, validates existence, and outputs graph representations for program analysis,...
def main(): des="Hausaufgabe 1 Blatt 4 Programmanalyse SoSe20." epi="Built by Qu@ntumH@ck3er Thi Altenschmidt" parser=argparse.ArgumentParser(description=des,epilog=epi) parser.add_argument("--file","-f",action="store",type=str,dest="in_file", help="Specify the input binary file for disassem...
def frame(x,y,win): p = Rectangle(Point(x-8,y-8),Point(x+248,y)) p.setFill('gray') p.setOutline('gray') p.draw(win) p = Rectangle(Point(x-8,y-8),Point(x,y+248)) p.setFill('gray') p.setOutline('gray') p.draw(win) p = Rectangle(Point(x-8,y+240),Point(x+248,y+248)) p.setFill('gray')...
This code implements a "Unblock Me" puzzle game where the player moves colored blocks within a grid. The main task is to move the red block to specific exit positions (17 and 18) by highlighting blocks and validating moves. The loop handles mouse clicks for block selection, movement checks, and exit condition verificat...
def main(): win = GraphWin("Unblock me",280,280) x = 20 y = 20 frame(x,y,win) grid(win) blocks = initConfig(x,y,win) hilited_block = 0 # main loop -- until the red block is succesfully moved out of grid while True: click = win.getMouse() if hilited_block == 0: ...
def globalPass(flag=None): files_path = loc() #terminators call if flag == 1: try: with open(f'{files_path}/.accman/data.yml', 'r') as d: y = yaml.safe_load(d) #check check globalPass = getpass('Please enter global password to proceed: ') ...
The code securely collects user account details (website name, address, username, password, and other info), encrypts them using a generated Fernet key, and stores the encrypted data in a YAML file. It checks if the file exists, updates it if so, or creates a new one, ensuring sensitive information is protected through...
def data_writer(): #setting up global password globalPass(0) #getting account information name = input('Name of the website: ') doesAccountExists(name) website_addr = input('Website address: ') usr_name = input('Account username: ') passwd = getpass(prompt='Account password: ') other...
def data_reader(usr_input): files_path = loc() try: #fetching file information with open(f'{files_path}/.accman/information.yml', 'r') as d: y = yaml.safe_load(d) try: encrypted_account = y[usr_input] encryptedItems = [] for...
This code defines a command-line account manager that allows users to read, write, list, delete, clean, or set a global password for account data. It uses argparse to parse mutually exclusive commands, executing corresponding functions like data_reader(), data_writer(), or globalPass() based on user input.
def main(): parser = argparse.ArgumentParser(description = 'Your own very secure account manager.') group_parser = parser.add_mutually_exclusive_group() group_parser.add_argument('--read', help='name of the account you want to find. e.g "python accman.py --read twitter"') group_parser.add_argument('--wr...
def printifascii(buf,newline): for n in range(len(buf)): if((buf[n] < 32 or buf[n] > 126) and buf[n] != 0 and buf[n] != 10 and buf[n] != 13): if newline != 0: print() return(0) # non-ascii char xbuf = buf.rstrip(b'\r\n') print("\"" + xbuf.decode() + "\"",end = '') if newline != 0: p...
This function processes client commands in a server application, handling file transfers, connection control, and parameter settings. It checks the first byte of received data to identify commands like 'Ping', 'Disconnect', 'Send File', 'Set Destination Directory', 'Set Block Size', or 'Get File'. It sends appropriate ...
def classic_node_callback(clientnode,dat,datlen): global endchar global gdestdir global gnblock dlen = len(dat) if(dlen > 0): firstc = dat[0] else: firstc = 0 print("Received from " + btfpy.Device_name(clientnode) + " =",end = ' ') if printifascii(dat,1) == 0: btfpy.Print_data(dat) ...
def inputint(ps): flag = 1 val = -1 while flag != 0: print(ps + " (x=cancel)") s = input("? ") flag = 0 if(len(s) > 0): for n in range(len(s)): if(s[n] < '0' or s[n] > '9'): flag = 1 if flag == 0: val = int(s) elif s[0] == 'x': val = -1 ...
The code facilitates file transfer (send or get) via a btferret protocol server. It prompts the user to select transfer mode, connects to a server node, validates file paths and directories, sets block size for data transmission, and initiates the transfer using either `send_file` or `get_file` functions based on user ...
def sendgetfile(): flag = inputint("FILE TRANSFER\n 0 = SEND file\n 1 = GET file\nInput one of the above options") if flag == 0: print("SEND",end = ' ') elif flag == 1: print("GET",end = ' ') else: print("Invalid option") return print("file - must be connected to a btferret transfer protoc...
def mencari_nilai_A(): # varibel tahun_A = TmpilTabeldataTh() # masih ada bug yakni di tahunya apabila hanya 1 data harus 2 data ui2_A = hasil2 nilaiC_A = mencarinilai_C() YIjumlah_A = TmpilanTabelYi() # perhitungan perkalina_Th_dan_nilaic = nilaiC_A * ui2_A pengurangan_tahun = YIjumlah...
The main task of the code is to compute and print the values of variables A, B, and C by calling three separate functions: mencari_nilai_A(), mencarinilai_B(), and mencarinilai_C(). The function A_B_C_nilia() serves as a wrapper to execute these calculations and display their results in a formatted manner.
def A_B_C_nilia(): print('A =', mencari_nilai_A()) print('B =', mencarinilai_B()) print('C =', mencarinilai_C())
def mencari_nilai_A(): # varibel tahun_A = TmpilTabeldataTh() # masih ada bug yakni di tahunya apabila hanya 1 data harus 2 data ui2_A = hasil2 nilaiC_A = mencarinilai_C() YIjumlah_A = TmpilanTabelYi() # perhitungan perkalina_Th_dan_nilaic = nilaiC_A * ui2_A pengurangan_tahun = YIjumlah...
This function calculates the result of a quadratic equation using coefficients a, b, and c obtained from separate functions, along with a year value. It computes the formula yn = a + b*(tahun) + c*(tahun)^2 by squaring the year, multiplying coefficients with respective terms, and summing them to return the final result...
def mencarinilai_yn(): # rumus dasar = yn = a + b(tahun) + c x (9)pangat 2 # variabel a_yn = mencari_nilai_A() b_yn = mencarinilai_B() c_yn = mencarinilai_C() tahun_yn = TmpilTabeldataTh() tahun2_yn = tahun_yn ** 2 bxtahu_yn = b_yn * tahun_yn cxtahun2_yn = c_yn * tahun2_y...
def SemuaTabel(): #jumlah banyak tabel a = TmpilTabeldataTh() # jumlaha yi keseluruhan b = TmpilanTabelYi() #Ui non pangkat jumlah c = TmpilanTbelUi() #Ui pangakat2 penjumlahan dan data tabel d = Uipangakat2() d2 = Uipangakat2(lihatHsil2='countUi2') # Ui pangkat4 penjumla...
This function displays a calculation menu with six options, executes corresponding functions based on user input, and navigates between menus. It clears the screen, runs selected operations (e.g., table summation, A/B/C calculations, population counting), waits for user confirmation, and returns to the main menu. Optio...
def menuhitung(): print("="*50, "MENU HITUNG", "="*50) print("\n") print("[1] ~ Tampilkan hasil penjumlahan tabel") print("[2] ~ Perhitungan A,B,C") print("[3] ~ Perhitungan Yn") print("[4] ~ Perhitungan jumlah penduduk") print("[5] ~ Perhitungan ysst") print("[6] ~ Perhitungan kabel") ...
def fill_missing_geodesics(self, elements, minassigned): """ Spin off more geodesics in elements that contain no geodesics (i.e. fill holes in the initially spawned geodesics) :param elements: Elements without an geodesics :param minassigned: Minimum number of neighbors that contain geo...
The main task of the code is to generate a UV parameterization using geodesic paths, handling missed vertices by filling gaps through iterative geodesic additions, coordinate assignment, interpolation, and averaging. It ensures all vertices are assigned valid coordinates, checks for geometric errors like flipped triang...
def create_parameterization(self): """ Create the uv parameterization based on the computed geodesic paths If vertices can't be assigned or are missed cleanup methods are employed to attempt to solve coordinates for all vertices. This is difficult to make robust as geometric complexities...
def find_startpoints(self, initpoint, initdirection, normal, cfpoint, directions=(1, -1)): """ Determines starting location, direction, and element for each geodesic Spawns geodesics perpendicular to initdirection Geodesic start points are dropped in self.fiberint intervals :par...
The code evaluates a surface's intrinsic parameterization by generating geodesic paths if none exists. It initializes start points, calculates geodesics, constructs a parameterization, and timestamps the process. If a pre-existing parameterization exists, it directly uses it. The task ensures the surface is parameteriz...
def evaluate(self): if self.model_loaded: if not self.obj.implpart.surfaces[0].intrinsicparameterization: # Find start points for all geodesics # Start from initpoint, go in the positive initdirection and the negative initdirection # Starting parameter...
def gen_base(self, traits): if traits: # Defining the conditions for the parameters given in traits is_racial = RACE in traits is_cultural = CULTURE in traits is_gendered = GENDER in traits if is_racial and is_cultural: self.culture = ...
The main task of the code is to generate structured data by sequentially initializing base parameters, applying traits, configuring voice settings, and compiling these into a final data structure using the `make_data()` method. The function `quick_gen` orchestrates these steps to create a cohesive output based on provi...
def quick_gen(self, **traits): self.gen_base(traits) self.gen_traits() self.gen_voice() self.make_data()
def gen_base(self, traits): if traits: # Defining the conditions for the parameters given in traits is_racial = RACE in traits is_cultural = CULTURE in traits is_gendered = GENDER in traits if is_racial and is_cultural: self.culture = ...
This code loads and parses a JSON file to populate an NPC's attributes. It extracts culture, race, gender, name, and surname from the 'BASE' field, assigns traits, personality, and voice details from specific keys, and generates defaults if keys are missing. Finally, it compiles the data into a structured format.
def load(self, file): with open(file) as g: npc = json.load(g) if BASE in npc: self.culture = npc[BASE].split(" | ")[1].split(" - ")[0] self.race = npc[BASE].split(" | ")[1].split(" - ")[1] self.gender = npc[BASE].split(" | ")[0] self.name = np...
def is_lab(string): match = re.fullmatch(r"\b\w+[78]\b", string) if match != None: return string in match.group() else: return False def remove_overlap(tt, slot): if 1 == int(slot[1]) or 2 == int(slot[1]): tt.pop((slot[0], 8), None) elif 3 == int(slot[1]) or 4 == int(slot[1])...
The main task of the code is to allocate subjects to a timetable by prioritizing lab subjects first, then assigning remaining subjects based on faculty preferences while avoiding overlaps. It checks for available slots, adjusts for insufficient or excess hours, and ensures all subjects meet their required hours. The fu...
def allot3 (sem3_info_tuple, sem3_slot_tuple): sem3_info = [] for x in sem3_info_tuple: sem3_info.append(list(x)) sem3_slot = [] for x in sem3_slot_tuple: sem3_slot.append(list(x)) #create a dictionary to hold timetable tt = {} for day in days: for slot in range(1, ...
def is_lab(string): match = re.fullmatch(r"\b\w+[78]\b", string) if match != None: return string in match.group() else: return False def check_clash(tt3, fac_id, slot): if slot in tt3.keys() and tt3[slot] is not None and fac_id == tt3[slot][0]: return True else: retur...
The main task of the code is to allocate subjects from `sem5_info` and `sem5_slot` into a timetable (`tt5`), prioritizing lab subjects first, then assigning remaining subjects based on faculty preferences, availability, and avoiding clashes with a third-semester timetable (`tt3`). It ensures all subjects meet their req...
def allot5 (sem5_info_tuple, sem5_slot_tuple, tt3): sem5_info = [] for x in sem5_info_tuple: sem5_info.append(list(x)) sem5_slot = [] for x in sem5_slot_tuple: sem5_slot.append(list(x)) #create a dictionary to hold timetable tt5 = {} for day in days: for slot in ran...
def get_ts_trappist(bnet_path, var_names): """Compute the minimal trap spaces using trappist.""" command = ["trappist", bnet_path] try: result = subprocess.run(command, stdout=subprocess.PIPE) result = result.stdout.decode('utf-8').split('\n') var_order = result[0].strip().split() ...
The main task of the code is to identify one representative state for each attractor in the asynchronous dynamics of a Boolean network (bnet). It achieves this by first simplifying the network, calculating minimal trap spaces, reducing the network's complexity through variable elimination, generating candidate states u...
def find_attractors_with_reduction(bnet_path, stop_at=None, max_product=None, candidate_method="AEON", simplify=True, verbose=False): """Find one state in each attractor of the asynchronous dynamics of the bnet, by first removing variables, finding attractors of the reduced network, then screening the c...
def parse_file_path_obj(file_path, prop): if type(file_path) == dict: value = file_path.get('value') if not value: return None condition = file_path.get('condition') if condition.lower() == 'contains': return "*{0}*".format(value) elif condition.lower...
The main task of the code is to parse file metadata (name, size, path) and hashes from the input properties, then add them as a "File Object" artifact in CEF format to the observation JSON. It prioritizes hash data, and if unavailable, adds basic file details as a fallback.
def parse_file_obj_type(prop, obs_json): # Check if hashes are present hashes = prop.get('hashes') file_name = prop.get('file_name') file_size = prop.get('size_in_bytes') file_path = prop.get('file_path') if file_path: file_path = parse_file_path_obj(file_path, prop) if file_name: ...
def parse_file_obj_type(prop, obs_json): # Check if hashes are present hashes = prop.get('hashes') file_name = prop.get('file_name') file_size = prop.get('size_in_bytes') file_path = prop.get('file_path') if file_path: file_path = parse_file_path_obj(file_path, prop) if file_name: ...
The function `parse_property` identifies the type of a property using its `xsi:type` attribute and delegates parsing to specialized functions (e.g., `parse_file_obj_type`, `parse_domain_obj_type`) based on the type. It processes properties like files, domains, addresses, and network connections, populating `obs_json` w...
def parse_property(prop, obs_json): try: if prop['xsi:type'] == 'FileObjectType': parse_file_obj_type(prop, obs_json) elif prop['xsi:type'] == 'DomainNameObjectType': parse_domain_obj_type(prop, obs_json) elif prop['xsi:type'] == 'AddressObjectType': parse...
def read_rarity_charm(elem, list_elem, list_elem_name): return read_info(elem, list_elem, list_elem_name, th_rarity) def read_skill_charm(elem, list_elem, list_elem_name): return read_info(elem, list_elem, list_elem_name, th_skill) def read_value_charm(elem, list_elem, list_elem_name): return read_info(elem...
This function maps raw charm data from the 'infos' dictionary to a structured pandas Series using predefined mappings from the 'data' parameter, converting attributes like rarity, skills, values, and slots into named categories for organized data representation.
def read_infos_charm(infos, data): res = pd.Series(index=index, dtype=str) res['rarity'] = read_rarity_charm( infos['rarity'], data['rarities'], data['rarities_name']) res['skill_1'] = read_skill_charm( infos['skill_1'], data['skills'], data['skills_name']) res['value_1'] = read_value_ch...
def createRobot(self, system): try: del self.robot except: pass self.robot = theRobot.theRobot(system) def createApplication(self): # Create an Irrlicht application to visualize the system self.myapplication = chronoirr.ChIrrApp(self.mysystem, 'PyChrono ...
The code initializes a simulation environment by setting up parameters like speed limits, scores, and a DQNAgent for reinforcement learning. It configures a physics system (Chrono), creates a battleground and robot, initializes application components, and prepares to run the simulation. The main task is to set up a phy...
def __init__(self): self.amountOfSimulations = 0 self.maxSpeed = 4 self.score = 0 self.previousScore = 0 self.highscore = 0 self.highscoreTime = 0 #self.delayCounter = 0 #self.delay = randint(5,10) self.keepRunning = True self.agent = DQNA...
def Tag(self,metadata): return { 'Name': 'Raw Tag', 'Type':'Signal', 'Formula':'$signal', 'Formula Parameters': { '$signal': metadata['ID'].iloc[0] }, 'Description': metadata['Description'].il...
This method defines a condition to check if a raw tag value is outside inner boundaries but within outer boundaries, using parameters like inner/outer thresholds. It returns a structured description with a formula: ($rt > $h or $rt < $l) and not (($rt < $ll or $rt > $hh)), where $rt is the raw tag, $h/$l are inner limi...
def L_or_H(self, metadata): return { 'Name': 'Outside of L or H', 'Type':'Condition', 'Formula':'($rt > $h or $rt < $l) and not (($rt < $ll or $rt > $hh))', 'Formula Parameters': { '$rt': self.Tag(), '$h'...
def Tag(self,metadata): return { 'Name': 'Raw Tag', 'Type':'Signal', 'Formula':'$signal', 'Formula Parameters': { '$signal': metadata['ID'].iloc[0] }, 'Description': metadata['Description'].il...
The code defines a method that returns a structured condition checking if a raw tag value ($rt) exceeds upper ($hh) or lower ($ll) boundaries. It outputs a dictionary with a formula, parameters, and description for monitoring out-of-range values.
def LL_or_HH(self, metadata): return { 'Name': 'Outside of LL or HH', 'Type':'Condition', 'Formula':'($rt > $hh or $rt < $ll)', 'Formula Parameters': { '$rt': self.Tag(), '$ll': self.Lower_Outer(), ...
def Grade_Keep_Properties_Filtered(self,metadata): uptime_filter = [ asset.uptime_filter() for asset in self.all_assets() if (isinstance(asset, Config_Parameters) and (asset.definition['Name'] == self.definition['Name'])) ] return { ...
This function defines a conditional check named 'On Grade While Running (Filtered by Uptime and Speed)', combining three criteria: maintaining a grade ($grade), meeting uptime thresholds ($online), and adhering to speed limits ($withinSpeed). It returns a structured description of this composite condition for use in sy...
def OnGrade_Running_Filtered_Uptime_Speed(self,metadata): #OnGrade_NoBreak_Filtered_Uptime_Speed return { 'Name': 'On Grade While Running (Filtered by Uptime and Speed)', 'Type':'Condition', 'Formula': '$grade and $online and $withinSpeed', 'F...
def L_or_H(self, metadata): return { 'Name': 'Outside of L or H', 'Type':'Condition', 'Formula':'($rt > $h or $rt < $l) and not (($rt < $ll or $rt > $hh))', 'Formula Parameters': { '$rt': self.Tag(), '$h'...
This code defines a method returning a structured signal priority configuration. It generates a 'Priority' signal with a formula combining threshold-based splices using parameters from L_or_H(), LL_or_HH(), and Raw_Invalid(). The priority indicates deviation levels: 1 for inner limit breaches, 2 for outer limit breache...
def Priority(self, metadata): return { 'Name': 'Priority', 'Type':'Signal', 'Formula':'0.tosignal()\n.splice(1.tosignal(), $oolo)\n.splice(2.tosignal(), $oolo2)\n.splice(SCALAR.INVALID.tosignal(), $rtnv)', 'Formula Parameters': { ...
def get_dataframe(indicators: List) -> Iterator: """ Iterate over all indicators. """ for indicator in indicators: yield from get_indicator_data(indicator) def invert(d): """ Invert dictionary. >>> d = { ... "cat1": ["a", "b"], ... "cat2": ["c", "d"], ... } ...
The main task is to generate a pandas DataFrame from a generator, process its columns by converting 'year' to integers and mapping 'iso3' and 'id' to region/country names and categories, then save the raw data, filtered cases, and year-specific subsets to Excel files for further analysis.
def main(): """ Create pd.DataFrame from generator and save it. """ df = pd.DataFrame(get_dataframe(INDICATOR_PARAM)) df["year"] = df["year"].astype(int) df["region"] = df["iso3"].map(invert(COUNTRIES)) df["category"] = df["id"].map(invert(INDICATORS)) df.to_excel(f"{CURRENT_DIR}/../../data/raw/...
def evaluation(model, data_loader, device, args, config): # test model.eval() metric_logger = utils.MetricLogger(delimiter=" ") header = 'Evaluation:' print('Computing features for evaluation...') start_time = time.time() texts = data_loader.dataset.text num_text = ...
The code evaluates a multi-modal model on multiple tasks by loading pre-trained checkpoints, creating test/query/gallery datasets, and computing retrieval metrics (R1, R5, R10, MAP) for image-text and text-image retrieval. It iterates over tasks, loads model states, runs evaluations, and aggregates results for reportin...
def eval_all(args, config, device, model_without_ddp): results = {} results_map={} task_list=[] for iteration, task_i in enumerate(config['task']): task_list.append(task_i) print(task_i) test_dataset = create_dataset('product_test', config, task_i_list=task_list, min_scale=0.2) ...
def finetune_forward(self, image, caption): raw_image_feat, raw_text_feat, image_embeds, image_atts, text, text_output = self.get_feature(image,caption) mlm_output, input_ids_new, labels_new = self.get_mlm_loss(text, image_embeds, image_atts ,image.device) loss_mlm = mlm_output.loss ...
This function processes different training modes by dispatching to corresponding forward methods, computing and returning task-specific loss components like image-text alignment (loss_ita), masked language modeling (loss_mlm), and discriminative losses (loss_dis, loss_mlm_dis) depending on the mode, which includes fine...
def forward(self, mode, image, caption, iteration=0, epoch=0, ref_model=None, momentum_model=None): if mode == 'finetune': loss_ita, loss_mlm= self.finetune_forward(image, caption) return loss_ita, loss_mlm elif mode == 'LWF': loss_ita, loss_mlm, loss_dis, loss_mlm_...
def sendImageAndVideo(_message): """Send image and video match with timestamp in message""" img_up_res = False vid_up_res = False timestamp = getTimestampFromMessage(_message) new_timestamp = convertUTC0ToUTC7(timestamp) timestamp = new_timestamp if (timestamp != None): local_imag...
The code processes incoming messages by uploading image/video data, sends a cloud message if the image upload succeeds, and acknowledges message receipt. It handles queue messages, triggers uploads, checks results, and confirms processing via delivery acknowledgment.
def local_callback(ch, method, properties, body): image_upload_res, video_upload_res = sendImageAndVideo(body) if image_upload_res: # print(f"{cloudMessageGenerate(body)}\n") sendMessage(cloudMessageGenerate(body)) ch.basic_ack(delivery_tag=method.delivery_tag)
def equalize_areas(mb_areas, wiki_areas, cols, common_index): wiki_areas, mb_areas = _equate_dataframes_columns( wiki_areas, mb_areas, cols, common_index ) return wiki_areas, mb_areas def _comparator(wiki_df, mb_df, output_rename_dict, area_type_id): """Compares mb and wiki dataframes, and adda...
The code compares country data from two sources (mb_areas and wiki_areas), aligns them using specified columns, identifies discrepancies (additions, edits), and writes the differences. It uses predefined mappings to standardize field names and categorizes changes based on area type (1 for countries). The main task is t...
def process_countries(mb_areas, wiki_areas): print("Comparing countries...") COUNTRY_COLS = [ "country_idx", "country_gid", "countryLabel", "iso_3166_1_code", "iso_3166_3_code", "country_url", ] COUNTRY_INDEX = "country_idx" COUNTRY_RENAME_DICT = { ...
def equalize_areas(mb_areas, wiki_areas, cols, common_index): wiki_areas, mb_areas = _equate_dataframes_columns( wiki_areas, mb_areas, cols, common_index ) return wiki_areas, mb_areas def _comparator(wiki_df, mb_df, output_rename_dict, area_type_id): """Compares mb and wiki dataframes, and adda...
The code compares and synchronizes subdivision data from two sources (mb_areas and wiki_areas). It aligns datasets using specified columns, identifies discrepancies (additions, edits), and generates a report of differences for "subdivisions," including renaming fields and handling area type identifiers.
def process_subdivisions(mb_areas, wiki_areas): print("Comparing subdivisions...") SUBDIVISION_COLS = [ "subdivision_idx", "subdivision_gid", "subdivisionLabel", "iso_3166_2_code", "subdivision_url", ] SUBDIVISION_INDEX = "subdivision_idx" SUBDIVISION_RENAME_...
def equalize_areas(mb_areas, wiki_areas, cols, common_index): wiki_areas, mb_areas = _equate_dataframes_columns( wiki_areas, mb_areas, cols, common_index ) return wiki_areas, mb_areas def _comparator(wiki_df, mb_df, output_rename_dict, area_type_id): """Compares mb and wiki dataframes, and adda...
The code compares city data from two sources (mb_areas and wiki_areas), aligning them using specified columns and identifiers. It identifies discrepancies, categorizing cities to add, edit, or retain, then generates reports for these differences.
def process_cities(mb_areas, wiki_areas): print("Comparing cities...") CITY_COLS = [ "city_idx", "city_gid", "cityLabel", "city_url", ] CITY_INDEX = "city_idx" CITY_RENAME_DICT = { "city_gid": "mbid", "cityLabel": "name", "city_url": "url", ...
def load_data(mb_area_path, wiki_area_path): mb_areas = pd.read_pickle(mb_area_path) wiki_areas = pd.read_pickle(wiki_area_path) return mb_areas, wiki_areas def generate_url_index(mb_area_df, wiki_area_df): areatype_index_col_lookup = { "city_idx": "city_url", "subdivision_idx": "subdiv...
The main task of the code is to compare two geographical datasets (mb_areas and wiki_areas) by generating URL indexes and processing country, subdivision, and city data to produce differences. It measures and reports the execution time of this comparison process.
def main(): start = time() print("Comparing Data...") mb_areas, wiki_areas = load_data(DEFAULT_MB_AREA_PATH, DEFAULT_WIKI_AREA_PATH) print("Generating index...") mb_areas, wiki_areas = generate_url_index(mb_areas, wiki_areas) process_countries(mb_areas, wiki_areas) process_subdivisions(mb_...
def getDataset(): patients = getFiles() qutoas = getQuotas(patients) test = [] train = [] clean_quota = {'A': qutoas[1], 'B': qutoas[3], 'C': qutoas[5], 'D': qutoas[7], 'E': qutoas[9]} art_quota = {'A': qutoas[0], 'B': qutoas[2], 'C': qutoas[4], 'D': qutoas[6], 'E': qutoas[8]} print(f'{clean...
The code trains a ResNet-18 model on MRI datasets using multi-GPU support (if available), applying a weighted BCEWithLogitsLoss to address class imbalance. It loads training/test data, initializes the model, optimizes via Adam, tracks training/test accuracy, and saves model checkpoints periodically. The model predicts ...
def train(GPU=True): # shape = [64, 64, 64] test, train = getDataset() print(f'Test len = {len(test)} --- Train len = {len(train)}') testset = MRIDataset(test) trainset = MRIDataset(train) device = torch.device('cuda:0,1,2,3' if torch.cuda.is_available() else 'cpu') model = resnet18() # was ...
def evaluate_interval(nonmg: pd.DataFrame, mg: pd.DataFrame, lb: float, ub: float)->None: """Evaluate PC2-based interval for MG diagnosis""" X_mg=df2array(mg) X_nonmg, pc2_RI, _, z_transform, pc_transform = derive_interval(nonmg,lb,ub) performances=[] performances.append(pd.DataFrame.from_dict(evaluate.SeSp_sFLCR(...
The main task of the code is to generate, evaluate, or apply PC2-based statistical intervals using user-specified input files (nonmg, mg, or cases). It loads data from CSVs or a default pickle file, then conditionally executes interval derivation, evaluation, or application based on provided parameters, with lb/ub defi...
def main(nonmg_fpath: str = None,mg_fpath: str = None,cases_fpath: str = None,lb: float = 2.5,ub: float = 97.5)->None: """Generates output per user specified options""" if nonmg_fpath: nonmg = pd.read_csv(options.nonmg_fpath) else: with open('./Data/WashU.p', 'rb') as file: nonmg=pickle.load(file) #generate...
def start(self): # use parent class start() function super(VMX_vcp, self).start() # add interface to internal control plane bridge if not self.install_mode: vrnetlab.run_command(["brctl", "addif", "int_cp", "vcp-int"]) vrnetlab.run_command(["ip", "link", "set", "v...
The function periodically checks a serial console for specific prompts (e.g., login or root shell) during device boot. If no match is found, it increments a spin counter; if exceeding 300 spins, it restarts the process. Upon detecting prompts, it authenticates, executes configuration commands, or initiates power-off. I...
def bootstrap_spin(self): """ This function should be called periodically to do work. returns False when it has failed and given up, otherwise True """ if self.spins > 300: # too many spins with no result -> restart self.logger.warning("no output from serial...
def pnl0(df,s): ret=np.array(df.ret) UW=pd.DataFrame() for col in s.columns: UW[col]=s[col].shift(1)*ret return UW def nulloutput(): f = open(os.devnull, 'w') sys.stdout = f def normaloutput(): global SYSNORMALSTDOUT sys.stdout = SYSNORMALSTDOUT def leverage(w): global F ...
The code performs a backtest for portfolio optimization by minimizing a loss function using the SLSQP method to find optimal asset weights. It calculates unweighted PNL, enforces weight bounds, and stores results like optimized weights, leverage, and cumulative PNL. The goal is to determine the best portfolio allocatio...
def backtest(): global F # calculate the unweighted pnl F['UW'] = pnl0(F['d'],F['s']) #random init of weights. Set bounds. n = len(F['s'].columns) w0 = n * [ 1/n ] BNDS = ((-1,1),)*n #cons = ({'type': 'ineq','fun': tradeConstraintsFunc }) print ('** Minimize: Target:'+F['optTa...
def pnl0(df,s): ret=np.array(df.ret) UW=pd.DataFrame() for col in s.columns: UW[col]=s[col].shift(1)*ret return UW def nulloutput(): f = open(os.devnull, 'w') sys.stdout = f def normaloutput(): global SYSNORMALSTDOUT sys.stdout = SYSNORMALSTDOUT def leverage(w): global F ...
The code performs a backtest to optimize portfolio weights by minimizing a loss function using the SLSQP method. It calculates unweighted PNL, initializes equal weights, and applies bounds. After optimization, it stores the optimal weights, computes leverage, cumulative PNL, and outputs results. The goal is to find opt...
def backtest(): global F # calculate the unweighted pnl F['UW'] = pnl0(F['d'],F['s']) #random init of weights. Set bounds. n = len(F['s'].columns) w0 = n * [ 1/n ] BNDS = ((-1,1),)*n #cons = ({'type': 'ineq','fun': tradeConstraintsFunc }) print ('** Minimize: Target:'+F['optTa...
def pnl0(df,s): ret=np.array(df.ret) UW=pd.DataFrame() for col in s.columns: UW[col]=s[col].shift(1)*ret return UW def nulloutput(): f = open(os.devnull, 'w') sys.stdout = f def normaloutput(): global SYSNORMALSTDOUT sys.stdout = SYSNORMALSTDOUT def leverage(w): global F ...
The code performs a backtest to optimize portfolio weights by minimizing a loss function using the SLSQP method, subject to bounds on weights. It calculates unweighted PNL, initializes equal weights, and computes optimized weights (`F['x']`). Post-optimization, it derives leverage, cumulative PNL, and logs PNL for anal...
def backtest(): global F # calculate the unweighted pnl F['UW'] = pnl0(F['d'],F['s']) #random init of weights. Set bounds. n = len(F['s'].columns) w0 = n * [ 1/n ] BNDS = ((-1,1),)*n #cons = ({'type': 'ineq','fun': tradeConstraintsFunc }) print ('** Minimize: Target:'+F['optTarg...
def bbload(ticker, start_date, end_date): global BBCACHE global BBDATACACHEPATH name = ticker[:3] CSVcachefilename = BBDATACACHEPATH + ticker + '.' + start_date + end_date + '.csv' if ticker in BBCACHE: a = BBCACHE[ticker] print('USING CACHED') else: ...
The code performs backtesting and optimization of a trading strategy for a given asset. It loads Bloomberg data, generates features/signals, sets the optimization target to Sharpe ratio, executes backtesting with parameter optimization, and plots results to evaluate performance.
def run(asset,start_date,end_date): #load Bloomberg data for the asset between start_date and end_date df = bbload(asset,start_date,end_date) # create features and signals df = feature(df,start_date,end_date) s = signal(df) #backtest and optimize the x vector. All results in p.F F['optTar...
def bbload(ticker, start_date, end_date): name = ticker[:3] con = pdblp.BCon(debug=False, port=8194, timeout=5000) con.start() a = con.bdh(ticker, ['PX_LAST'], start_date, end_date ) a.columns=['close'] # save in global global F F['ticker'] = ticker #keep the ticker ...
The code loads Bloomberg data for a specified asset between given dates, generates features/signals, sets the optimization target to 'sharpe', executes backtesting with parameter optimization per asset, and plots results to evaluate trading strategies.
def run(asset,start_date,end_date): #load Bloomberg data for the asset between start_date and end_date df = bbload(asset,start_date,end_date) # create features and signals df = feature(df,start_date,end_date) s = signal(df) #backtest and optimize the x vector. All results in p.F F['optTar...
def is_processed(item: modo.Item) -> bool: """checks if item has processed mark Args: item (modo.Item): item to check Returns: bool: True if item contains the mark, False otherwise """ tag = get_description_tag(item) if h3dc.PROCESSED_MARK in tag: return True retur...
The code processes 3D meshes in a scene by reparenting them under their respective hierarchy roots or selected superlocators, ensuring each mesh is processed only once by checking and marking a "processed" status. It handles both global scene items and user-selected elements, adapting to different command contexts (e.g...
def main(): if not lx.args(): superlocators = modo.Scene().items(itype=c.LOCATOR_TYPE, superType=True) meshes = {i for i in superlocators if is_mesh_prefix(i)} for mesh in meshes: if not is_processed(mesh): reparent(mesh=mesh) add_processed_mark(me...
def user_is_mod(self, e): ''' Returns whether user has mod permissions. ''' val = [d['value'] for d in e.tags if d['key'] == 'mod'][0] return (val == '1') def splat3_reveal_day_count(self): # reveal_date = datetime.strptime('2/17/2021', '%m/%d/%Y') release_date = datetime.strptim...
This function processes chat commands in a bot, executing actions like revealing counts, managing Flowermons game features, and handling moderator-only tasks. It checks user permissions, processes command arguments, and triggers methods for actions such as updating death counts, providing game help, and managing shouto...
def do_command(self, e, cmd_issuer, cmd, cmd_args): c = self.connection user_has_mod_privileges = False if self.user_is_mod(e) or cmd_issuer in self.trusted_users_list: user_has_mod_privileges = True user_is_sub = True #self.user_is_sub(e) if cmd == 'splat3': ...
def auto_streamer_shoutout(self, e): ''' Gives an automated streamer shoutout. ''' c = self.connection user = self.get_username(e) if user in USERS_CHECKED: return if user in APPROVED_AUTO_SHOUTOUT_USERS and not APPROVED_AUTO_SHOUTOUT_USERS[user]: APPROVED...
This code handles chat messages by triggering automatic streamer shoutouts, processing user messages for predefined bot responses, parsing commands starting with '!', and executing corresponding actions. It logs commands, handles errors, and uses keyword matching for responses, while avoiding duplicate shoutouts and Un...
def on_pubmsg(self, c, e): ''' Handles message in chat. ''' # give a streamer shoutout if viewer is in the approved streamers set # and streamer has not already gotten a shout out # (i.e., manual shoutout with !so <username> command) self.auto_streamer_shoutout(e) user_m...
def show_box(self, box): box.set_state(True) mine_count = self.get_mine_count_in_neighboord( box.get_xCoord(), box.get_yCoord() ) if mine_count > 0: box.set_tag(str(mine_count) + ":o") else: box.set_tag("C:o") self.__set_box(box.get_xCo...
This function reveals a box and recursively reveals all adjacent boxes if the initial box contains no mines, expanding the visible area in a Minesweeper-like game.
def show_box_and_neighbors(self, box): mine_count = self.show_box(box) if mine_count == 0: xCoord = box.get_xCoord() yCoord = box.get_yCoord() neighbors = util.get_neighboord( xCoord, yCoord, self.level.row_count, self.level.column_count ) ...
def __get_box(self, xCoord, yCoord): result = None for box in self.boxes: if box.get_xCoord() == xCoord and box.get_yCoord() == yCoord: result = box return result def show_mines(self): for mine in self.__mines: if mine.get_is_flagged() is False: ...
This function determines if opening a box at specified coordinates ends the game. It checks if the box contains a mine; if so, reveals all mines, locks the board, and returns True (game over). If not, it reveals the box and its neighbors, returning False (game continues).
def open_box(self, xCoord, yCoord): box = self.__get_box(xCoord, yCoord) game_over = False if box is not None and box.get_is_flagged() is False: if box.get_is_mine(): self.show_mines() self.lock_boxes() game_over = True else...
def fingers_up(self): fingers = [None] * 5 hand = self.calculate_hand() if(hand!= None): for j, tip in enumerate(self.calculate_tips_position(hand)): if self.is_open(hand, tip): finger = self.calculate_finger(hand, j) finge...
The code detects hand gestures by analyzing the number of fingers raised. It checks if the fingers match predefined patterns for signs like "V SIGN," "INDEX SIGN," "OK SIGN," "OPEN HAND SIGN," or "CLOSE HAND SIGN" using helper methods, returning the corresponding gesture name as a string.
def detect_sign(self): fingers = self.fingers_up() if(self.victory_sign(fingers) == True): return "V SIGN" if(self.index_sign(fingers) == True): return "INDEX SIGN" if(self.ok_sign(fingers) == True): return "OK SIGN" if(self.gimme5_sign(finger...
def print_image(image): print("") for row in image: print(''.join(row)) def enhance(algo, image, border='.'): pad_image(image, 2, border) result = image_copy(image) row_count, col_count = len(image), len(image[0]) for row in range(1, row_count-1): for col in range(1, col_count-1...
The code processes an image through two enhancement steps using specified algorithms and symbols ('.' and '#'), printing each modified image. Finally, it outputs the count of lit pixels in the twice-enhanced image.
def part_one(algo, image): print_image(image) image1 = enhance(algo, image, '.') print_image(image1) image2 = enhance(algo, image1, '#') print_image(image2) print(lit_pixels(image2))
def basic_algorithm(self): total_features, total_classes, total_samples = self.get_paramaters(self.linearly_separable_train_file_path) data_frame = self.get_data_frame(self.linearly_separable_train_file_path, total_features) weight_vector = np.zeros((total_features + 1, 1)) learning...
The code computes classification accuracy using different algorithms (Basic, RP, or Pocket) on a dataset. It selects a data file based on linear separability, calculates predicted classes via a weight vector, and compares them to actual labels to determine accuracy as a percentage.
def compute_accuracy(self, option): if option == "Basic": total_features, weight_vector = self.basic_algorithm() file_path = self.linearly_separable_test_file_path elif option == "RP": total_features, weight_vector = self.rp_algorithm() file_path = self.li...
def exhaustive_search_on_entire_matrix(self, reference_image_matrix, grayscale_frame_matrix): reference_image_matrix_height, reference_image_matrix_width = reference_image_matrix.shape frame_matrix_height, frame_matrix_width = grayscale_frame_matrix.shape best_location = -1, -1 minimum_...
The code performs a search across video frames to locate a reference image using specified methods (exhaustive, 2D logarithmic, or hierarchical). It iteratively updates the best match location, draws bounding rectangles on frames, accumulates search operations, and generates a video with marked locations. The total sea...
def execute_search(self, method, p): frame_matrices = self.original_frame_matrices.copy() best_location, search_counter = self.exhaustive_search_on_entire_matrix(self.reference_image_matrix, self.grayscale_frame_matrices[0]) total_search_counter = search_counter for i in range(1, len(fra...
def list_available_games(): print("Available Games:") for index, (game, details) in enumerate(game_library.items(), start=1): print(f"{index}. {game} - Copies available: {details['copies_available']}, Cost: ${details['cost']}") def register_user(): while True: print("Registration Page") ...
The main task of the code is to display a menu-driven interface allowing users to select options like viewing available games, registering, logging in as a user or admin, or exiting the system. It processes user input in a loop, invoking corresponding functions based on the choice, and ensures valid selections while ha...
def main_menu(): while True: print("Main Menu") print("1. Show Available Games") print("2. Register") print("3. User Login") print("4. Admin Login") print("5. Exit") choice = input("Enter your choice: ") if choice == '1': list_available_gam...
def isConnected(self): """Returns true if device acks at the I2C address """ try: self.i2c.writeto(NAU7802_DeviceAddress, bytearray()) return True except OSError: return False def reset(self): """Resets all registers to Power Of Defaults ...
The code initializes a sensor via I2C, checks communication, and configures settings like power, gain, and sample rate if reset is enabled. It returns True if all setup steps succeed, otherwise False.
def begin(self, i2c: busio.I2C = None, reset: bool = True): """Check communication and initialize sensor Args: i2c (busio.I2C, optional): [description]. Defaults to None. reset (bool, optional): [description]. Defaults to True. Returns: [type]: [description]...
def get_transactions_local(address, chain): """Get details of all transactions by a given address. It only requests FULLSTACK_LIMIT transactions at a time due to the limit. :param address: The address to query :type address: ``str`` :param chain: The blockchain to query :param chain: ``str``` ...
The function searches for transactions involving a specified address on a given blockchain that contain a BoCA post matching the provided file hash. It retrieves transactions (via `get_transactions_local` for BCH/tBCH or `get_eth_transactions` for ETH/tETH), checks each for a BoCA post using `get_boc_hash`, and collect...
def search_address(address, filehash, chain): """Search all transactions by the provided address and finds all that have a BoCA post with the matching file hash :param address: The address to query :type address: ``str`` :param filehash: The filehash to look for :type filehash: ``str`` :par...
def send_memo_bch(key, message, chain): """Posts the provided message to the BCH blockchain using the memo.cash protocol :param key: The key needed to post to the blockchain :type key: ``bitcash.wallet.PrivateKey`` or ``bitcash.wallet.PrivateKeyTestnet`` :param message: The message to be posted...
The main task of the code is to post a message to a specified blockchain (BCH, tBCH, ETH, or tETH) using a private key. It routes the request to the appropriate blockchain-specific function (send_memo_bch, send_memo_eth, etc.) based on the 'chain' parameter and returns a dictionary containing the transaction ID and add...
def send_memo(key, message, chain): """Use the correct function to post the message based on the chain :param key: The private key needed to post :type key: ``bitcash.wallet.PrivateKey`` or ``bitcash.wallet.PrivateKeyTestnet`` or ``eth_account.signers.local.LocalAccount`` :param message: The me...
def bch_get_version(address_string): """Determine if the provided BCH address is main or testnet :param address_string: The address to be tested :type address_string: ``str`` :raises ValueError: If the address is not BCH/tBCH address :rtype: ``str`` """ address = Address.from_string(address...
This function verifies if a given blockchain address (BCH/tBCH) has posted a filehash matching a specified file. It checks address validity for the chain, searches blockchain posts, and outputs matches with timestamps, source addresses, confirmations, and transaction IDs. If 'getcid' is enabled, it retrieves and verifi...
def check_post_from_address_bch(provider_address, chain, filehash, file_to_verify, getcid, key): """ Find all posts by an address that have a BoCA post matching a filehash in the BCH/tBCH blockchain. :param provider_address: Address to check :type provider_address: ``str...
def get_img_array(img_path: str, size: Tuple = (299, 299)) -> np.array: """Get image array given image path. Args: img_path (str): image path. size (Tuple, optional): image size. Defaults to (299, 299). Returns: np.array: image array. """ img = keras.preprocessing.image.loa...
The main task of the code is to apply Integrated Gradients to an image using a pre-trained Xception model, generating visual explanations for the model's predictions. It processes an input image, computes gradients and integrated gradients, then visualizes attribution maps with different clipping parameters and cleanup...
def main(args: argparse.Namespace): """Run Integrated Gradients. Args: args (argparse.Namespace): input arguments. """ os.makedirs(args.image_dir, exist_ok=True) img_size = (299, 299, 3) model = xception.Xception(weights="imagenet") img_path = keras.utils.get_file("elephant.jpg",...
def get_model() -> tf.keras.Model: """Get pretrained model. Returns: tf.keras.Model: Inception V1 model. """ model = tf.keras.Sequential( [ hub.KerasLayer( name="inception_v1", handle="https://tfhub.dev/google/imagenet/inception_v1/classificat...
The main task of the code is to demonstrate the Integrated Gradients method for visualizing model attributions in neural networks. It loads a pre-trained model, processes two images, generates predictions, creates baseline interpolations, and computes integrated gradients to highlight image regions contributing to spec...
def main(args: argparse.Namespace) -> None: """Run Integrated Gradients. Args: args (argparse.Namespace): input arguments. """ os.makedirs(args.image_dir, exist_ok=True) model = get_model() imagenet_labels = load_imagenet_labels( "https://storage.googleapis.com/download.tensorfl...
def window_size(self): return self._ts_list[-1] - self._ts_list[0] def disorder_check(self, ts): for i in range(self._ooo_buffer_size): # ooo_buffer is append at right side, so first element is the oldest # element in ooo_buffer is list [ts, hits] ...
This code manages a sliding window of timestamps to enforce a rate limit. It removes outdated timestamps to maintain the window size, adjusts hit counts accordingly, and checks for out-of-order timestamps. If detected, it triggers disorder checks for previous timestamps. Finally, it verifies if current hits exceed the ...
def check(self, ts): # While sliding windows size, the most recent timestamp - the earliest timestamp, # is bigger than configured size, pop the earliest timestamp, reduce hits at # earliest timestamp from total hits of sliding window. while self.window_size() > self._w_s...
def generate_population(self, num=100): population = [] rand_node_list = random.sample(list(self.geodata.nodes.keys()), num) for node in rand_node_list: route1, _, _ = self.dijkstra_find_route(self.geodata, self.orig_node, node) route2, _, _ = self.dijkstra_find_route(sel...
The code's main task is to implement a genetic algorithm to find the optimal route with the highest elevation gain. It generates an initial population, iteratively evolves it over a set number of iterations, evaluates each path's fitness, selects the best-performing route, and returns its coordinates, length, and eleva...
def cal_result(self): result = [] res = 0 population = self.generate_population() for i in tqdm(range(self.max_iteration)): population = self.generate_new_population(population) # Return the route with the highest elevation gain for path in population: ...
def check_collisions(self): """Check for collisions""" player_hitting_apple = arcade.check_for_collision_with_list( self.player, self.scene["apple"] ) if player_hitting_apple: apple = player_hitting_apple[0] self.player.eat(apple) self.spa...
This method updates the game scene by handling physics, player movement, and collision checks. It resets the game if the player goes out of bounds, removes existing snake body sprites, and adds new ones based on the player's historical positions to visually represent the snake's trail.
def on_update(self, delta_time): """Update the scene""" self.physics_engine.update() self.player.update() self.check_collisions() if not self.is_in_bounds(self.player): self.setup() try: self.scene.remove_sprite_list_by_name("snake_body") ...
def create_mini_batches(n_features: int, batch_size: int) -> List[np.ndarray]: """ Creates mini batches with batch_size equal to batch_size The n:th batch will contain the remaining features """ assert isinstance(n_features, int), 'n_features should be an int' assert isinstance(batch_size, int),...
This code trains a neural network model by iterating over epochs, using mini-batches to update model layers via an optimizer. It tracks training loss and metrics, supports validation data, and optionally prints progress based on the verbose setting. The function returns an array of training losses over epochs.
def fit(self, features, labels, epochs=5, batch_size=1, validation_data=None, verbose=0): # Check that the model is compiled if not self.is_compiled: raise RuntimeError('The model must be compiled first') # Extract validation data if it exists if validation_data: ...
def bracketMaker(fname) -> Bracket: ''' bracketMaker This function will produce a tournament bracket with matchups from a list of Competitors. Returns a bracket. ''' # correct for user not entering file extension file = fileAdjust(fname) teams = loadTeams(file) if len(teams)...
This code provides a menu-driven interface for managing tournament brackets, allowing users to create new tournaments, edit existing ones (by adding/removing teams or reseeding), display brackets from files, and save changes. It includes file handling, logging, and error handling for user inputs, ensuring data persiste...
def main(): ''' main method ''' # creat log file for this program logging.basicConfig(filename="tournament.log", level=logging.DEBUG, format='%(asctime)s :: %(message)s') # Welcome message print("*** Welcome to the Tournament Bracket Creator! ***") teams = [] # put code in...
def sanitized(sanType: str,msg: str): value = "" data = "" try: if sanType == "yn": while True: data = input(msg) if len(data) >= 5: data[:5] data = data.lower() value = re.sub('[^yn]','*',data) ...
The main task of the code is to handle user login authentication with retry logic. It tracks failed login attempts for each username, terminates access after three failed attempts, and allows users to retry or exit. The function returns `True` if too many failures occur, `False` otherwise.
def log_in(): i = 0 triedUserName = {} tooMany = False while True: username = sanitized("usr","Enter Username: ") password = sanitized("pass","Enter Password: ") userid = authenticate(username,password) if userid: display_user(userid) break ...
def sanitized(sanType: str,msg: str): value = "" data = "" try: if sanType == "yn": while True: data = input(msg) if len(data) >= 5: data[:5] data = data.lower() value = re.sub('[^yn]','*',data) ...
The code provides a menu-driven interface allowing users to create new accounts, log in, or shut down the system. It loops indefinitely, prompting for actions until a shutdown is requested or a login succeeds, which terminates the loop.
def main(): while True: # create new user if sanitized("yn","New user y/n: ") == "y": sign_in() # login as old user if sanitized("yn","Log in y/n: ") == "y": terminated = log_in() if terminated: break if sanitized("yn"...
def get_current_shape(self): return PIECES[self.current_piece].centered_on(self.current_position, self.current_orientation) def end_game(self): self.game_over = True dead_cells = [] for row in range(TETRIS_FIELD_ROWS): for col in range(TETRIS_FIELD_COLS): if s...
This code handles the insertion of "garbage" lines in a Tetris game. It generates random columns for garbage pieces, adjusts the current piece's position if it cannot drop the required lines, ends the game if the piece exceeds the field height, and prepends the garbage rows to the game field. The function also triggers...
def garbage(self, lines: int): well_col = random.randint(0, TETRIS_FIELD_COLS-1) garbage_rows = [[-1 for _ in range(TETRIS_FIELD_COLS)] for _ in range(lines)] for row in garbage_rows: row[well_col] = None drop_distance = self.field.get_drop_distance(s...
def get_current_shape(self): return PIECES[self.current_piece].centered_on(self.current_position, self.current_orientation) def spawn_piece(self): if self.use_view: self.view.redraw(field=self.field, queue=self.queue) self.current_position = (4, 20) self.current_orientation ...
This function locks the current Tetris piece into the game field by updating the field's cells, resets locking variables, checks for cleared rows, updates the score based on row clears, sets attack status, spawns a new piece, and handles IndexError by ending the game.
def lock_in_piece(self): try: for (sx, sy) in self.get_current_shape(): self.field.cells[sy][sx] = self.current_piece self.locking_in = False self.lock_frames = LOCK_IN_FRAMES self.lock_resets = 0 cleared = self.field.clear_rows() ...
def get_offset_shape(self, offset, rotation=0): (x, y) = self.current_position (x_off, y_off) = offset return ( PIECES[self.current_piece] .centered_on( (x + x_off, y + y_off), (self.current_orientation + rotation) % 4 ) ...
This function attempts to move a falling game piece down by one unit. If the move is valid, it updates the piece's position and resets a drop timer. If invalid, it initiates a locking sequence to finalize the piece's position, returning True for successful movement and False otherwise.
def drop_piece(self): (px, py) = self.current_position next_position = (px, py - 1) if self.field.test_shape_fit(self.get_offset_shape((0, -1))): self.erase_current_piece() self.current_position = next_position self.draw_current_piece() self.drop...
def auto_shift_piece(self, direction: -1 | 1) -> bool: if self.shift_frames: self.shift_frames -= 1 elif self.delay_auto_shift: self.delay_auto_shift = False self.shift_frames = DAS_FRAMES self.shift_piece(direction) else: self.shift_fr...
This function processes Tetris input actions to control game mechanics: shifts the piece left/right, resets auto-shift, handles soft/hard drops, updates rotation states, and triggers piece holding. It maps key presses to corresponding actions, enabling player interactions like movement, rotation, dropping, and holding ...
def execute_actions(self, actions: Dict[TetrisAction, bool]): if actions[TetrisAction.SHIFT_L] and not actions[TetrisAction.SHIFT_R]: self.auto_shift_piece(-1) elif actions[TetrisAction.SHIFT_R] and not actions[TetrisAction.SHIFT_L]: self.auto_shift_piece(1) elif not (act...
def writeRegions(): ''' Write each region/country available on spotify charts to regions.json Format example follows the example; Argentina: [ar, 2017/01/2017] First item in array is the country abbreviation and second line a date ''' # Note the starting date here is used to check ...
The code processes Spotify artist chart data across multiple regions and dates using multithreading. It loads region configurations, partitions date ranges into thread-specific intervals, initializes browser drivers, and concurrently fetches artist rankings while handling login synchronization. The main task is to effi...
def main(): jsonPath = 'region.json' if(not os.path.exists(jsonPath)): writeRegions() with open(jsonPath, 'r') as json_file: regionDict = json.load(json_file) # Initialize needed variables and split dates into n-thread-partitions startDate = '2021-10-21' endDate = '2023-12...
def get_param_mean_var(net: Net) -> Tuple[float]: linear_1_params = ( t.nn.utils.parameters_to_vector(net.linear1.parameters()) .detach() .cpu() .flatten() ) return linear_1_params.mean().item(), linear_1_params.std().item() def gen_data(m_0: int, p_on: float, dataset_size: i...
The main task of the code is to train a neural network to perform logical operations (AND/XOR) on sparse boolean vectors using specified loss functions. It generates training data, employs Adam optimization, computes loss, tracks accuracy, and optionally plots error histograms. The network is trained in batches, adjust...
def train( net: Net, dataset_size: int, batch_size: int, l: float, lr: float, test_dataset_size: int, epsilons: List[float], n_plots: Optional[int], n_prints: int, device: t.device, loss_p: int, loss_type: Literal["normal", "reweighted"], operation: Literal["and", "xo...
def muchoPlus(name): random.seed(4) alpha = string.ascii_lowercase for i in range(0,11): index = randomizer(len(name)) alphChar = randomizer(len(alpha)) name.insert(index,alpha[alphChar]) return name def special(webChar): specials = ['a','s','o','h','v','i'] toChange ...
The main task of the code is to encrypt a given string by applying a series of transformations: converting the input to lowercase, modifying characters with 'muchoplus' and 'special' functions, processing with 'bigFib', and finally reversing the string with 'flipper' to produce an encrypted output.
def do_encrypt(prompt): if(prompt==''): return 'No prompt entered' webName = prompt.lower() nameList = list(webName) muchoPlus(nameList) for i in range (0,len(nameList)): nameList[i] = special(nameList[i]) bigFib(nameList) webName = ''.join(nameList) we...
def writeToArduino(self,num): self.s.write(str(num).encode('UTF-8')) def waitForArduino(self): ard = 'x' while not ard == 'a': ard = self.s.read_until("\n").decode('utf-8') if ard == 'l': self.stopFocus() ...
The code scans for optimal focus by adjusting position and direction based on focus values. It inverts scanning direction if focus decreases, stops if no response is detected, and terminates scanning when peak focus is achieved, updating positions and signaling completion.
def scan(self): if debug: print("Position : {} \t Focus Value : {} \t Max focus : {}".format(self.current_position,self.position_focus[int(self.current_position)],self.max_focus)) skip = False #inverting logic if ((self.current_position == self.init_position + int(3*self...
def checkStartButton(self): ard = self.s.read_until("\n").decode('utf-8') if ard == 's': self.start = True return True def scan(self): if debug: print("Position : {} \t Focus Value : {} \t Max focus : {}".format(self.current_position,self.position_focus[int(s...
The code continuously captures video frames, computes focus metrics using Laplacian variance, updates the UI with real-time focus scores and maximum values, and manages autofocus scanning. It displays the camera feed initially, then transitions to autofocus processing, storing focus data and triggering scan steps until...
def update(self): # Get a frame from the video source ret, frame = self.vid.get_frame() if ret: if not self.start: #Before starting the focus program, this will keep displaying the camera feed. self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fro...
def initVariables(self): #Variables self.max_focus = 0 # Stores the max focus value self.position_focus = [0] * 40000 # This is an array saving the focus values for each position (lenght 40000) self.current_position = int...
This code initializes a GUI application for autofocus control using a webcam and Arduino. It sets up a Tkinter window with video capture, manual focus buttons (forward/backward), an autofocus button, and real-time video display. The main task is to create an interface for adjusting camera focus manually or automaticall...
def __init__(self, comport, video_source=0): self.window = tkinter.Tk() self.window.title("AutoFocus v0.1") self.video_source = video_source self.initVariables() self.openArduino(comport) #Opens arduino for communication # open video source (by default this ...
def windows_sdk_setenv(self, pyver): if (pyver.major, pyver.minor) >= (3, 3): path = "v7.1" sdkver = (7, 1) else: path = "v7.0" sdkver = (7, 0) setenv = os.path.join(SDK_ROOT, path, 'Bin', 'SetEnv.cmd') if not os.path.exists(setenv): ...
This method generates a temporary Windows batch script to configure the SDK environment, execute a command, and clean up. It sets environment variables, changes directories, and runs the specified command via the SDK setup, handling verbose output based on SDK version. The temporary file is automatically deleted after ...
def _build_windows(self, pyver, cmd): setenv, sdkver = self.windows_sdk_setenv(pyver) temp = tempfile.NamedTemporaryFile(mode="w", suffix=".bat", delete=False) with temp: temp.write("SETLOCAL EnableDelayedExpansion\n") temp.writ...
def cleanup(self): if self.verbose: print("Cleanup") self.remove_directory('build') self.remove_directory('dist') self.remove_file('_overlapped.pyd') self.remove_file(os.path.join(PROJECT, '_overlapped.pyd')) def _build_windows(self, pyver, cmd): setenv, sdkve...
The code's main task is to build a package using the specified Python version and commands. It cleans up previous artifacts, constructs a command list with 'setup.py' and additional arguments, then executes platform-specific build processes (Windows or Unix) to compile or package the software.
def build(self, pyver, *cmds): self.cleanup() python = pyver.get_executable(self) cmd = [python, 'setup.py'] + list(cmds) if WINDOWS: self._build_windows(pyver, cmd) else: self._build_unix(pyver, cmd)
def isOpen(board,rowNum,lineNum): if(board[rowNum][lineNum] == 0): return True else: return False def findEmptySide(board): if isOpen(board,0,1): return 0,1 elif isOpen(board,1,0): return 1,0 elif isOpen(board,1,2): return 1,2 elif isOpen(board,2,1): ...
The function `strategicPlay` implements a game strategy prioritizing board control. It first checks if the center (1,1) is open, returning it if so. If not, it evaluates diagonal conditions to identify empty corners (0,0) or (2,2) for potential moves, aiming to secure strategic positions. If these conditions fail, it d...
def strategicPlay(board,diagonals): #smarter approach - dealing with the specific strategy of 3 corners conquer if isOpen(board,1,1): print("center") return 1,1 else: if (diagonals[0]<0 and board[0][0]==-1 and board[2][2]==-1): # I want to deal with the first time only, so t...
def findEmptyPointOnDgnl(board, idx): if (idx ==0): if isOpen(board,0,0): return 0,0 elif isOpen(board,1,1): return 1,1 elif isOpen(board,2,2): return 2,2 else: # the board is already full return -1,-1 else: if isOpen(board...
The function determines the next move by checking if an immediate win or block is possible by examining rows, lines, and diagonals. If a critical state (value ≥2 or ≤-2) is found, it returns the position to play. Otherwise, it defaults to a strategic move.
def calculateStep(board, rows, lines, diagonals): # return AIRow, AILine # winning the next round or preventing the player from winning for idx, diagonal in enumerate(diagonals): if (diagonal >=2 or diagonal <=-2): return findEmptyPointOnDgnl(board,idx) for idx, row in enumerate(rows): ...
def isOpen(board,rowNum,lineNum): if(board[rowNum][lineNum] == 0): return True else: return False def updateboardAIInfo(RowNum,LineNum,playerOrAi, rows, lines, diagonals): # player is -1 Ai is +1 rows[RowNum] = rows[RowNum] + playerOrAi lines[LineNum] = lines[LineNum] + playerOrAi if...
The function handles a player's move on a board by checking if the selected cell is open. If valid, it marks the cell as -1, updates the board, and lets the AI calculate its move. If the AI finds a valid position, it marks it as 1 and updates the board again, returning 1. Otherwise, it returns 0. Invalid input returns ...
def playRound(playerInput, board, rows, lines, diagonals): rowNum = int(playerInput[0]) lineNum = int(playerInput[1]) if isOpen(board, rowNum,lineNum): print(isOpen) board[rowNum][lineNum] = -1 updateboardAIInfo(rowNum,lineNum ,-1, rows, lines, diagonals) printBoard(board) ...
def execute_turn(self, row = None, col = None): print(self.turn + "turn") if row == None: row = int(input("Row")) if col == None: col = int(input("Column ")) self.board.mark_spot(row, col, self.turn) def game_over(self): star_counter = 0 for row i...
The main task of the code is to run a Tic Tac Toe game by initializing the board, alternating player turns, executing moves, updating the board display after each turn, checking for game-over conditions, and announcing the winner if the game is won. It loops until the game ends, ensuring players take turns and the boar...
def run_game(self): print("Hello! starting a new TicTacToe Game") self.board.show_board() self.execute_turn() print(self.board.show_board()) while self.game_over() == False: self.change_turn() self.execute_turn() print(self.board.show_board()) ...
def interpolated(self): try: return self._interpolated except AttributeError: self._interpolated = _calculate_interpolation(self) return self._interpolated def _year_to_period(year, freq_dict): """ Convert a year (int) to the best-matching period given in the ...
This function retrieves a frequency value from a frequency table, using parameters like period, year, and interpolated. It handles cases with or without explicit inputs, defaults to 'modern' data, and uses interpolation for missing values. The result is either a direct lookup, interpolated value, or a mean of interpola...
def frequency(self, **kwargs): """ Return a raw frequency value from the frequency table. Keyword arguments: -- 'period' -- 'year' -- 'interpolated' (defaults to False) Defaults to 'modern' if no arguments are supplied. """ period = kwargs.get(...
def generate_grid(num_points): x_min, y_min, x_max, y_max = area step_x = (x_max - x_min) / num_points step_y = (y_max - y_min) / num_points center_points = [] for i in range(num_points): for j in range(num_points): x = int(x_min + i * step_x + step_x / 2) y = int(y_...
The code automates a game by identifying clickable white pixels in a generated grid, waiting for the board to clear, then clicking all white pixels. It increments the level, waits for the next round, repeats the process, and initiates gameplay. The main task involves detecting, waiting, and interacting with game elemen...
def start(): global level points = generate_grid(3) level+=1 #imediatly look for white pixels click_this = get_white_list(points) #wait till boards clear wait_til_clear(click_this[0]) #click them all click_em(click_this) level+=1 #wait till next round starts next_ro...
def get_annotator(self, img): return Annotator(img, line_width=self.args.line_thickness, example=str(self.model.names)) def xyxy_to_xywh(*xyxy): """" Calculates the relative bounding box from absolute pixel values. """ bbox_left = min([xyxy[0].item(), xyxy[2].item()]) bbox_top = min([xyxy[1].item(),...
This function processes object detection results by counting detected classes, updating global counters, logging frame details, and saving results to a CSV. It handles image/video frames, applies tracking with DeepSORT, draws bounding boxes, and returns a log string summarizing detections.
def write_results(self, idx, preds, batch): p, im, im0 = batch all_outputs = [] log_string = "" if len(im.shape) == 3: im = im[None] # expand for batch dim self.seen += 1 im0 = im0.copy() if self.webcam: # batch_size >= 1 log_string += f'...
def load_logged_in_user(): postal_code = session.get('user_id') if postal_code is None: g.user = None else: conn = get_dbConn() cur = conn.cursor() cur.execute( 'SELECT * FROM pa_user WHERE postal_code = %s', (postal_code,) ) g.user = cur.fetchone...
The code allows logged-in users to generate a bar plot visualizing statistical analysis of litter data from a specified bin area. It validates input, queries spatial data, checks for empty results, and displays the plot if valid. Errors trigger messages and redirects, while unauthenticated users are redirected to login...
def create_image(): if load_logged_in_user(): if request.method == 'POST': id_bin = request.form['bin_id'] id_bin= int(id_bin) error = None if not id_bin: error = 'Bin id is required!' if error is not None: flash(e...
def customized_engine(): #NOTE: dbConfig.txt MUST be modified with the comfiguration of your DB # build the string for the customized engine #open the configuration parameter from a txt file the table myFile = open('dbConfig.txt') connStr = myFile.readline() myFile.close() dbD = connStr.spl...
The code creates an interactive map using Bokeh to visualize litter points and classify bins as critical or non-critical based on litter statistics. It retrieves geospatial data from a database, processes coordinates, and generates two maps: one showing litter points with tooltips and another displaying bins (red for c...
def interactive_map(city_boundaries): engine = customized_engine() bins_gdf = gpd.GeoDataFrame.from_postgis('bins', engine, geom_col='geom') t_srs = 4326 bins_gdf.set_geometry('geom', crs=(u'epsg:'+str(t_srs)), inplace=True) bins_buffer_gdf = gpd.GeoDataFrame.from_postgis('bins', engine, geo...
def is_valid_date(date_str): if not date_str or date_str == 'null': return True try: # Use the full module path for strptime datetime.strptime(date_str, '%Y-%m-%d') return False except ValueError: return True def filter_order_by_date( request, start_date_str, end_date...
This function generates an admin sales report by filtering orders based on start/end dates and status. It retrieves GET parameters, validates dates, applies filters (by date, status, or both), and renders the 'sales-report.html' template with the filtered orders and context data including dates, status, and current dat...
def admn_sales_report(request): start_date = request.GET.get('start_date', None) end_date = request.GET.get('end_date', None) status_filter = int(request.GET.get('status_filter', 0)) current_date = timezone.now().strftime("%Y-%m-%d") orders = [] print(start_date,end_date,status_filter) if ...
def extract_features(PATH): img = image.load_img(PATH,target_size=(IMG_SIZE,IMG_SIZE)) #image loaded as 2 dimensional array # blob = cv2.dnn.blobFromImage(img_yolo,1/255,(512,512),swapRB = True, crop=False) img_array=image.img_to_array(img) # 3 dimension numpy array expanded_img_array =...
The function performs reverse image search by extracting features from a target image, using k-nearest neighbors to find similar images, and returns tags of the original image. It loads an image, extracts its features, identifies similar images via feature matching, retrieves tags, and returns them for use in image sea...
def reverse_image_search(): img_path = r'C:\Users\Aneesh Kulkarni\web_dev\flask projects\web page for yolo\static\input\target.jpg' global img_features img_features = extract_features(img_path)#features of the random input image #img_features=get_random_image_from_dataset() # pr...
def _cut_edges(self, edge_tuple_list): """ Remove the edge with the highest betweeness value """ edge_pair = edge_tuple_list[0][0] # In this implementation, all the edges with the highest betweenness are cut at once if self.edges[edge_pair[0]] i...
This code identifies optimal communities in a network by iteratively cutting edges with highest betweenness, recalculating modularity, and stopping when modularity no longer improves. It returns the best community structure sorted by size and node order.
def getCommunities(self): # initialize a min-max value first max_mod = float("-inf") # print(self.sorted_betwenness_list) if len(self.sorted_betwenness_list) > 0: self._cut_edges(self.sorted_betwenness_list) self.best_communities, max_mod = self._getModularity() ...
def writeExcel(self): ''' Function that writes last row introduced in the excel It assumes the firts two rows of the excel are: 1.- Date of delivery 2.- Column heads ''' if self.dfValues.empty: self.formatExcel() else: lastRow = sel...
The function processes Excel changes by parsing user input to extract AI identifiers and values. It updates a DataFrame with these values, handles deletion of cells, and manages updates or errors by re-reading Excel data. It also writes changes back to Excel and updates a parent table if required.
def processChanges(self,n,m,x): '''Function that process changes on excel Splits last value changed by () to get AI and values Adds dictionary with AI as keys and values as values to existing df ''' readQR = str(variableFile.changedValue.get()) valsAI = [tuple(i.split(')...
def compute_yloss(self, cf_instances): yloss = 0 if self.yloss_type == 'l2_loss': yloss = torch.pow((self.model_interface.predict_tensor(cf_instances)[1] - self.target_cf_class), 2) elif self.yloss_type == "log_loss": logits = torch.log(torch.abs(self.model_interface.pred...
The code computes an aggregated loss by combining a base loss (yloss), proximity loss (if weighted), diversity loss (if weighted), and regularization loss, each scaled by respective coefficients, to guide counterfactual instance generation with controlled similarity, diversity, and regularization.
def compute_loss(self, query_instance, cf_instances, proximity_weight, diversity_weight, categorical_penalty): """Computes the overall loss""" yloss = self.compute_yloss(cf_instances) proximity_loss = self.compute_proximity_loss(query_instance, cf_instances) if proximity_weight > 0 else 0.0 ...
def find_eta(self, radius_eta, observation_n, query_instance, mask, target): eta = radius_eta zs = self.make_z(eta, 0, eta, query_instance, mask, observation_n) tmp = self.binary_eta(zs, eta, target) while tmp is not None: eta = tmp zs = self.make_z(tmp, 0, tmp, q...
The code generates counterfactual examples by perturbing specific features in a query instance to achieve a target prediction. It calculates necessary perturbation magnitudes (eta), identifies minimal modifications (enemy) to reach the target, and ensures sparsity in changes. The result, enemy_star, represents feasible...
def generate_counterfactuals(self, query_instance, features_to_vary, eta = 5, target = 0.7, observation_n = 20): start_time = time.time() if isinstance(query_instance, dict) or isinstance(query_instance, list): query_instance = self.data_interface.prepare_query(query_instance, normalized = ...
def print(self, *values, sep=' ', end='\n'): if self.should_print: print(*values, sep=sep, end=end) def is_game_finished(self): return len(self.alivePlayers) <= 1 def damage_player(self, index: int, damage: int): assert index in range(len(self.alivePlayers)) assert damage >= ...
This code simulates a turn-based dice game where players take turns rolling a die. Rolling below 30 damages the player, rolling above 30 damages the next player, and rolling exactly 30 causes no effect. The game continues until only one player remains alive, with the code handling turn order, damage calculations, and a...
def play(self): self.print("Welcome to 30 Berg ab. A german dice game that breaks relationships and separates families. This game is totally based on skill. The skill to roll good. Have fun! \n") self.print("The players order is: ") for player in self.alivePlayers: self.print(f"{pla...
def get_sentences_from_file(infile): sentences = [] sentence = [] for line in open(infile): line = line.strip(os.linesep) if '\t' in line: columns = line.split('\t') sentence.append(columns) else: sentences.append(sentence) sentence = [...
The code generates average word embedding vectors from text in a file, using unigram, bigram, and trigram models with two distinct embedding methods (normal and "slash" variants). It processes each sentence to extract and average these vectors, returning a list of 10 averaged embeddings representing different n-gram st...
def make_prediction_embeddings(infile,prediction): ## global spacy_nlp backward_trigram_vectors = [] backward_bigram_vectors = [] unigram_vectors = [] forward_bigram_vectors = [] forward_trigram_vectors = [] backward_trigram_slash_vectors = [] backward_bigram_slash_vectors = [] u...
def determineAddress(address, port): if port == None or port == "": return address else: return "http://" + address + ":" + str(port) def fullTreeGetFiles(tree, basePath, individualFilesWithHashes, individualFilesWithPaths): for item in tree['contents']: if item['type'] == "directory...
The main task of the code is to synchronize files between a local system and a remote server by checking for new, updated, or deleted files. It fetches encryption keys, queries existing sync tasks, triggers remote syncs, encrypts files, updates metadata, handles file changes, checks available space, and manages sync st...
def syncFilesToRemote(conn: psycopg.connection, task, tempPlace): cur = conn.cursor() cur.execute(f"select file_encryption_key from authenticated_user where 'admin' = any(scopes)") token = cur.fetchone() if token is None: raise Exception('No admin key found') token = token['file_encryption_k...
def handleImageQuery(self): logging.debug("Handling image query...") output_img = self.image.split( ".")[0] + "_out." + self.image.split(".")[-1] detection = self.vision.detectImage(self.image, output_img) logging.debug(detection) self.reply['media_url'] = self.imgu...
This function parses an incoming request by extracting sender/receiver details, handling media content by downloading and processing images, and either processing existing user queries or registering new users, then sending a formatted response.
def parseRequest(self, body): logging.debug("Parsing request...") self.reply = { "to": None, "from_": None, "body": None, "media_url": None } self.body = body self.reply['to'] = self.body['From'] self.reply['from_'] = sel...
def fda(self, image: List[Union[str, np.ndarray]], beta_limit=0.13): augmentation = A.Compose( [A.FDA(self.get_random_img(flag='grayscale'), beta_limit=beta_limit, p=1, read_fn=lambda x: x)]) image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) transfer_image = augmentation(image=ima...
The code defines an `apply` method that processes a source image using one of three techniques based on the `method` attribute: FDA, pixel distribution, or histogram matching. It returns the processed image after applying the selected method.
def apply(self, source_img): if self.method == 'fda': return self.fda(source_img) if self.method == 'pixel_distribution': return self.pixel_distribution(source_img) else: return self.hist_matching(source_img)