dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _testIfEatFruit(self): eatFruit = [] fruitIndex = -1 isEaten = False for fruitObj in gameCore.Field.fruit: fruitIndex += 1 isEaten = self.object.colliderect(fruitObj.object) if isEaten == True: eatFruit.append(fruitIndex) if...
The tick method handles a game entity's update logic by checking collision with food, out-of-bounds death, and self-collision. It updates movement, processes turns, executes motion, and recursively updates all child segments, returning whether the entity is dead due to any fatal condition.
def tick(self): self._testIfEatFruit() deadByOutOfBounds = self._outOfBoundsLogic() deadByCollisionWithSelf = self._collideWithSelfLogic() isDead = deadByOutOfBounds or deadByCollisionWithSelf self._turnLogic() self._doRun() for bodySegment in self.__children: ...
def __repr__(self): """String of funds unique identifying trait: self.symbol. Args: None Returns: self.symbol (str): The symbol for the Fund. """ log.debug(f'__repr__ ({self.symbol}) complete.') return self.symbol def __str__(self): """...
The code generates a formatted string containing a fund's performance data for specified timeframes (24 hours, week, year) based on input parameters, combining textual metrics with a graphical representation. It uses boolean arguments to conditionally include each timeframe's performance, formats numerical results with...
def generate_fund_performance_str(self, day=True, week=True, year=True): """Generates previous 24 hour, week, and year performance of fund depending on arguments. Args: day (Bool): Defaults to True. When true includes previous day fund performance in return. ...
def validate_ignored(ignored, arguments): args = get_args(arguments) for arg in ignored: if arg not in args: print("Invalid --ignore arguments! '{}' not recognized. Terminating.".format(arg)) quit() def grab_repos(): repos = [] config = os.getcwd() + "\\config\\reposito...
The code defines a `main()` function that parses command-line arguments to control the execution of various analyses on code repositories. It supports options for verbosity, running all analyses, excluding specific tasks, overwriting files, cloning repositories, and performing specific analyses like biclustering, centr...
def main(): parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", help="increase output verbosity.", action="store_true") parser.add_argument("-r", "--runall", help="run all generative, and analytical functio...
def fix_path(path): newPath = path.replace(os.path.sep, '/') # switch \ to / newPath = newPath[0].lower() + newPath[1:] # make drive lowercase C: -> c: newPath = newPath.replace(':','') # delete : from drive if(newPath[0] != '/'): # if it's already formatted to UX path, don't add another '/' fin...
This code processes a repository's SonarQube analysis results by linking authors to code flaws (vulnerabilities/bugs), generating connectivity networks between flaws, and producing Lynksoft XLSX files for visualizing author-flaw, file-flaw, and author-coworker relationships. It offers interactive prompts to selectively...
def runner(repoAddress): print('Before running this program please conduct analysis using SonarQube' +' and export the results.\n') # Download Repo folderName = repoAddress.rsplit('/', 1)[-1] # last part of gitURL #getrep.download(repoAddress) # Path data for analysis steps cwd =...
def auth_bug(verbose, overwrite, repo): if(verbose): print("Finding Authors of Bugs in {}...".format(repo)) check.folder(verbose, repo) cwd = os.getcwd() authbugIN = cwd + '\input\{}-bug.csv'.format(repo, repo) authbugOUT = cwd + '\output\{}\{}-authbug.txt'.format(repo, repo) flawType ...
The function `auth_flaw` merges authentication-related bug and vulnerability analysis results into a single output file. It checks if files exist, prompts for overwriting if needed, generates missing files via `auth_bug`/`auth_vuln`, and combines them using `merge_files` for the specified repository. Special handling o...
def auth_flaw(verbose, overwrite, repo): cwd = os.getcwd() authflawOUT = cwd + '\output\{}\{}-authflaw.txt'.format(repo, repo) response = 'y' if(not(overwrite)): if(os.path.isfile(authflawOUT)): response = input("Overwrite {}? [y]/n\n".format(authflawOUT)) if response =...
def create_sample_sequence(self, num_samples): """ create a random sequence of microtrips from population (seq_pop)... such that total duration is in (duration_range) and.. size of sequence in (size_range) """ pop_samples = [] go = True while...
The code implements a genetic algorithm to optimize a target objective function. It initializes or loads a population of candidate solutions, iteratively evaluates their fitness, performs crossover and mutation to generate new candidates, retains top performers, and tracks the best solution. It also saves intermediate ...
def main(self,filtered_raw_df,filtered_agg_df,validity_matrix,num_iter): last_best_score = 1000000 start_time = time.time() # initialize the population self.raw_df=filtered_raw_df self.agg_df=filtered_agg_df self.validity_matrix=validity_matrix # ...
def arg_parser(): parser = argparse.ArgumentParser(description = 'Script to create extractive summarization dataset') parser.add_argument('--dataset_path', type=str, default="ccdv/arxiv-summarization", help="Path of dataset repo in Hugginface or path to dataset in local system") parser.add_argument("--file_extens...
The code processes a dataset by splitting text into sentences, then generates gold standard summaries and extractive summarization datasets for training, validation, and testing, using specified paths and parameters for data organization and splitting.
def main(): parser = arg_parser() args = parser.parse_args() dataset_path = args.dataset_path extension = args.file_extension max_no_of_sentences = args.max_no_of_sentences train_ext_path = args.extractive_summ_train_path val_ext_path = args.extractive_summ_val_path test_ext_path = args.extractive_summ_...
def load_file_list(self, path = default_out_path): files = [f.split('.')[0] for f in os.listdir(path) if f.endswith('.json')] files.sort(key=lambda x: int(x) if x.isdigit() else -1, reverse=True) self.file_list = list(map(lambda f: "%s/%s.json" % (path, f), files)) if len(self.file_list)...
This code initializes an NFT viewer GUI with an image display area, a scrollable info panel, and navigation buttons. It sets up the window layout, loads file lists, and configures interactive elements like 'Prev'/'Next' buttons for item navigation. The interface includes grid-based resizing, disabled buttons initially,...
def __init__(self, **kwargs): tk.Tk.__init__(self, **kwargs) self.load_file_list() self.title("NFT Viewer") self.minsize(900,600) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.nft_viewer = image_viewer.ImageViewer(self, highlightthicknes...
def set_text(self, label: tk.Label, text: str, max_chars: int = None) -> None: if max_chars != None and len(text) > max_chars: text = text[0:max_chars]+'...' label.configure(text=text, anchor='w') else: label.configure(text=text, anchor='center') def prev_trait(self, ...
The main task of this code is to generate a GUI element for displaying and navigating a specific "trait" in a Tkinter application. It creates a frame with labels for the trait's group name, current title, and status, along with "Previous" and "Next" buttons to navigate between traits. The layout includes separators and...
def add_to_choice(self, trait): font = ('system', 12) font_bold = ('system', 12, 'bold') lbl_width = 20 choice = tk.Frame(master=self.choice_frame.inner, name=trait['group']) choice.trait = trait choice.columnconfigure(1, weight=1) title = tk.Label(master=choice,...
def load_traits(self, file): self.traits = traits.load(file) def load_blueprint_template(self, file): with open(file) as json_file: self.blueprint_template = json.load(json_file) def combine_image(self, layers: list) -> Optional[Image.Image]: result = None for layer in layers...
This code initializes a GUI application for generating NFTs by loading traits, configuring SVG settings, and setting up a window with an image viewer, trait selection panel, and save functionality. It creates a Tkinter interface with interactive elements to combine traits into NFTs, display results, and save outputs, u...
def __init__(self, args, **kwargs): tk.Tk.__init__(self, **kwargs) self.load_traits('traits.json') self.load_blueprint_template(args.blueprint) self.svg_options['default']['width'] = args.svg_width self.svg_options['default']['height'] = args.svg_height self.name_prefix...
def get_index(node): return pow(7, node[0]) * pow(5, node[1]) def is_goal(path, goal_amount): return path[-1][0] == goal_amount or path[-1][1] == goal_amount def next_transitions(jugs, path, check_dict): result = [] next_nodes = [] node = [] a_max = jugs[0] b_max = jugs[1] a = path[-1][0...
This code implements a breadth-first search (BFS) to solve a jug problem. It starts from a given node, explores all possible transitions, checks if the goal amount is reached, and returns the solution path if found. The check_dict prevents revisiting states. If no solution exists, it outputs "Problem cannot be solved."...
def search(starting_node, jugs, goal_amount, check_dict): goal = [] solved = False q = deque() q.appendleft(starting_node) while len(q) != 0: path = q.popleft() check_dict[get_index(path[-1])] = True if is_goal(path, goal_amount): solved = True goal = ...
def get_index(node): return pow(7, node[0]) * pow(5, node[1]) def is_goal(path, goal_amount): return path[-1][0] == goal_amount or path[-1][1] == goal_amount def next_transitions(jugs, path, check_set): result = [] a_max, b_max = jugs a, b = path[-1] next_nodes = [(a_max, b), (a, b_max), (min(a_...
The code performs a Breadth-First Search (BFS) to solve a water jug problem, aiming to find a sequence of actions (path) that reaches a specified goal amount using given jugs. It starts from a `starting_node`, explores all possible transitions, avoids revisiting states via `check_set`, and prints the solution path if t...
def search(starting_node, jugs, goal_amount, check_set): goal = [] solved = False q = deque() q.appendleft(starting_node) while len(q) != 0: path = q.popleft() check_set.add(get_index(path[-1])) if is_goal(path, goal_amount): solved = True goal = path ...
def entr(x): y = [val * np.log2(val) if val != 0 else 0 for val in x] return y def indexgroup10(ind, sizevector): bin_size = sizevector // 10 for r in range(bin_size): for i in range(r*10, (r+1)*10): ind[i] = r+1 for k in range((bin_size-1)*10, sizevector): ind[k] = bin_s...
The code processes multiple data files by loading, concatenating, and deduplicating them. It calculates nucleotide entropy for each position, filters by coverage, and handles under/over-covered regions through sampling and aggregation. Parallel processing is used for efficiency, and final results are combined, transfor...
def main(): ###Start### files = glob.glob('*_grp' + args.regex) list_df = [] print("loading begin time is:" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) for file in files: # df = pd.read_csv(file, header=0,sep='\t', quoting=csv.QUOTE_NONE) # df.to_pickle(file+'.pkl') ...
def replace0(x): cols_to_replace = ['event_stdv.m', 'event_stdv.s', 'event_stdv.A', 'count.m', 'count.s', 'ins3.m', 'ins1.m', 'ins2.m', 'ins4.m', 'ins5.m', 'ins3.s', 'ins1.s', 'ins2.s', 'ins4.s', 'ins5.s'] x[cols_to_replace] = np.where(x[cols_to_replace] == 0, 0.00001, x[cols_to_replace]) return x def check...
The main task of the code is to preprocess and normalize genomic data from a CSV file using parameters from an RData file. It filters, logs, and scales features, merges with reference data, and saves processed data in a structured NumPy format for downstream analysis or machine learning.
def main(): filepath = "./test/minmax_Xen_5pos_012_10bin_morefts_combine.RData" result = pyreadr.read_r(filepath) mm_df = result['mm.df'] print(args.input) file_df = pd.read_csv(args.input, header=0,sep='\t', quoting=csv.QUOTE_NONE,nrows=1000000) dat = file_df[file_df['reference_kmer'] != ""] ...
def decode(x,chroms,chromid): x = pd.DataFrame(x) x['contig'] = replace_list(chroms, chromid, x['contig']) x['contig'] = pd.to_numeric(x['contig']) x['reference_kmer'] = x['reference_kmer'].str.replace("A", "1") x['reference_kmer'] = x['reference_kmer'].str.replace("C", "2") x['reference_kmer']...
The code processes genomic data by filtering and normalizing features from input CSV files, splitting data into training and test sets, generating contextual sequences (before/after positions), and transforming data into structured matrices for machine learning. It maps chromosomes, encodes positions, applies logarithm...
def main(): print(args.input) file_df = pd.read_csv(args.input, header=0, sep='\t', quoting=csv.QUOTE_NONE, nrows=1000000) df = file_df[file_df['reference_kmer'] != ""] # Read the truth file truth = pd.read_csv(args.classref, sep='\t') # Create a mapping for chromosomes chroms = np.sort(...
def sendPacket(self, packet): self.sock.send(packet + "\r\n") def output(self, data): print(">>%s: %s" % (self.server, data)) def splitData(self): self.x = self.data.split(" ") return self.x def handleMessage(self, message): channel = message.split(" ") channel = channel[...
This code establishes an IRC client connection to a server, sends authentication commands (NICK, USER), and processes incoming data by handling PRIVMSG messages, responding to PING requests with PONG, and joining channels. It uses SSL if enabled and continuously listens for server events in a loop.
def connect(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.server, self.ip)) if self.ssl == True: self.sock = ssl.wrap_socket(self.sock) self.sendPacket("NICK %s" %self.nick) self.sendPacket("USER %s %s %s :%s" %(self.use...
def cat(*args): as_lazy_tensor = (LazyTensor(a) if isinstance(a, int) else a for a in args) return reduce(lambda a, b: a.concat(b), as_lazy_tensor) def rmat(angle, axes=cat(0, 1)): if angle._shape[-1] > 1: angle = cat(1, 1).tensorprod(angle) # repeat twice return ((angle - axes.concat(axes - 1)) * (PI ...
The function performs a tensor-based interaction computation involving geometric transformations and conditional operations. It processes input tensors (x, a, b, f) by applying rotation matrices, projections, and filters defined by the profile function. The result is a reduction operation combining transformed data wit...
def interact(x, a, b, f, ranges, profile): j_out = Pm(torch.tensor([0, 1], device=f.k.device).float().repeat(len(f.k))) f = DotDict(val_map(lambda v: Pm(v.repeat_interleave(2)), f)) i = x._shape[-1] // 2 o = f.k._shape[-1] rp = a.p - b.p skip_same_point = 1 - (-rp.sqnorm2()).step() filter_re...
def align_elements(elements, names, order, skip=set(), end=set()): return [_align_element(e, n, [*chain(*order)], skip, end) for e, n in zip(elements, names)] def ax_to_j(x, axis=-1): return torch.view_as_complex(fix_stride(x.unsqueeze(-1).transpose(-1, axis - (axis < 0)))) def j_pow(v): v = torch.as_tensor...
This function applies weights to input tensors through aligned batch matrix multiplication, handling complex number adjustments and axis alignment. It aligns dimensions of x, weights, and descriptors, adjusts complex phases, gathers required weights, and performs the multiplication with specified order, returning the r...
def apply_weights_bmm(x, weights, filter_desc, data_b_desc, align=None): b_ = {k: data_b_desc[k] for k in {'k', 'j'}} order = [['bw_k'], ['b_p', 'b_j'], ['adw_c', 'adw_k', 'w_f', 'xw_j'], ['bw_c']] x, b, f, w = align_elements([x, b_, filter_desc, weights], ':bww', order, end={'xyz'}) # align inputs x =...
def create_net(self): net_dict = OrderedDict() net_dict["linear_layer_0"] = nn.Linear(self.num_inputs, self.hidden_size[0]) if self.layer_norm: net_dict["layer_norm_0"] = nn.LayerNorm(self.hidden_size[0]) net_dict["activation_0"] = self.get_activation(self.activation) ...
The main task of the code is to dynamically add a new layer to a neural network if the hidden layer size has fewer than three elements. It extends the hidden size, creates a new network, preserves parameters from the old network, and updates the network. If the hidden size already has three or more elements, it instead...
def add_layer(self): if len(self.hidden_size) < 3: self.hidden_size += [self.hidden_size[-1]] new_net = self.create_net() new_net = self.preserve_parameters(old_net=self.net, new_net=new_net) self.net = new_net else: self.add_node()
def create_net(self): net_dict = OrderedDict() net_dict["linear_layer_0"] = nn.Linear(self.num_inputs, self.hidden_size[0]) if self.layer_norm: net_dict["layer_norm_0"] = nn.LayerNorm(self.hidden_size[0]) net_dict["activation_0"] = self.get_activation(self.activation) ...
The code removes a layer from a neural network by reducing the hidden size, creating a new network, and preserving parameters through shrinking. If the hidden size has only one element, it adds a node instead.
def remove_layer(self): if len(self.hidden_size) > 1: self.hidden_size = self.hidden_size[:1] new_net = self.create_net() new_net = self.shrink_preserve_parameters(old_net=self.net, new_net=new_net) self.net = new_net else: self.add_node()
def read_distance_file(file_name): """ Reads the distance information from <file_name> and stores it in a suitable data structure (you decide what kind of data structure to use). This data structure is also the return value, unless an error happens during the file reading operation. :param file...
This code processes a distance data file, allowing users to display data, add/remove cities, find neighboring cities, or calculate routes between cities. It reads input, handles user actions in a loop, validates inputs, and delegates tasks to functions like display(), add_city(), and find_route(). The program exits whe...
def main(): input_file = input("Enter input file name: ") distance_data = read_distance_file(input_file) if distance_data is None: print(f"Error: '{input_file}' can not be read.") return while True: action = input("Enter action> ") if action == "": print("...
def list_services( self ): self.list = [] if self.newWindow: self.getControl( SERVICES_LIST ).reset() for serv in self.service_list: listitem = xbmcgui.ListItem( serv ) self.list.append(serv) listitem.setProperty( "man", "false" ) self.getControl( SERVICES_LIST ).addI...
The main task of the code is to search for subtitles using a dynamically imported service module, handle network errors, and update the UI with results. It initializes controls, executes a search, processes responses, and either auto-downloads matching subtitles or lists available options. If no results are found, it a...
def Search_Subtitles( self ): self.subtitles_list = [] self.getControl( SUBTITLES_LIST ).reset() self.getControl( LOADING_IMAGE ).setImage( xbmc.translatePath( os.path.join( SERVICE_DIR, self.service, "logo.png") ) ) exec ( "from services.%s import service as Service" % (self.service)) self.Service...
def LegendasLanguage(lang1,lang2,lang3): if lang1 == "PortugueseBrazil" or lang1 == "Brazilian": ltv_flag1 = "pb" langid1 = "1" elif lang1 == "Portuguese": ltv_flag1 = "pt" langid1 = "10" elif lang1 == "English": ltv_flag1 = "en" langid1 = "2" elif lang1 == "Spanish": ltv_flag1 = "es" langid1 = "3" ...
The main task of the code is to search for movie subtitles on LegendasTV by comparing parsed/original movie titles with database entries, handling multiple languages, and returning a list of matching subtitle files with metadata such as titles, release names, language flags, ratings, and download IDs.
def LegendasTVMovies(file_original_path, title, year, lang1, lang2, lang3 ): # Initiating variables and languages. lang1, ltv_flag1, langid1, lang2, ltv_flag2, langid2, lang3, ltv_flag3, langid3 = LegendasLanguage(lang1,lang2,lang3) tipo = "2" subtitles, sub1, sub2, sub3, PartialSubtitles = [], [], [], [], [] #...
def LegendasLanguage(lang1,lang2,lang3): if lang1 == "PortugueseBrazil" or lang1 == "Brazilian": ltv_flag1 = "pb" langid1 = "1" elif lang1 == "Portuguese": ltv_flag1 = "pt" langid1 = "10" elif lang1 == "English": ltv_flag1 = "en" langid1 = "2" elif lang1 == "Spanish": ltv_flag1 = "es" langid1 = "3" ...
The function searches LegendasTV for TV show subtitles matching specified parameters (title, year, season, episode, and languages). It retrieves subtitles by querying a database, parsing results, validating season/episode matches, and filtering by language codes. Subtitles are categorized into primary and partial match...
def LegendasTVSeries(tvshow, year, season, episode, lang1, lang2, lang3 ): # Initiating variables and languages. lang1, ltv_flag1, langid1, lang2, ltv_flag2, langid2, lang3, ltv_flag3, langid3 = LegendasLanguage(lang1,lang2,lang3) tipo = "1" subtitles, sub1, sub2, sub3, PartialSubtitles = [], [], [], [], [] # S...
def rem_files( self, directory): try: for root, dirs, files in os.walk(directory, topdown=False): for items in dirs: shutil.rmtree(os.path.join(root, items), ignore_errors=True, onerror=None) for name in files: os.remove(os.path.join(root, name)) except: try: ...
This function initializes parameters for subtitle handling in a media player (e.g., XBMC/Kodi). It processes the currently playing media's file path, detects if it's an HTTP link, RAR archive, or stacked file, sets subtitle directories, extracts metadata (year, season, episode, title), normalizes language settings, pre...
def set_allparam(self): temp = False rar = False self.newWindow = True self.stack = False self.stackSecond = "" self.autoDownload = False self.list = [] movieFullPath = urllib.unquote(xbmc.Player().getPlayingFile())...
def LegendasLogin(cj=0): if cj: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) else: cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) username = __settings__.getSetting( "LTVuser" ) pas...
The function searches for subtitles using either LegendasTVSeries (for TV shows) or LegendasTVMovies (for movies), based on input parameters like title, year, season/episode, and languages. It returns found subtitles, an authentication cookie, and an empty string, facilitating subtitle retrieval from a database with co...
def search_subtitles( file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack ): #standard input cookie = LegendasLogin() if len(tvshow) > 0: subtitles = LegendasTVSeries(tvshow, year, season, episode, lang1, lang2, lang3 ) else: subtitles = LegendasTVMovies(file_ori...
def Download_Subtitles( self, pos, auto = False ): if auto: self.getControl( STATUS_LABEL ).setLabel( _( 763 ) ) else: self.getControl( STATUS_LABEL ).setLabel( _( 649 ) ) zip_subs = os.path.join( self.tmp_sub_dir, "zipsubs.zip") zipped, language, file = self.Service.download_subtitles(sel...
This code handles user interactions for subtitle and service selection in a GUI. When controlId is 120, it downloads subtitles if a numeric selection is made, triggers keyboard input for "Man/Par", or searches subtitles for other options. For controlId 150, it processes service list selections, opens settings for "Set"...
def onClick( self, controlId ): if controlId == 120: if self.newWindow: self.Download_Subtitles( self.getControl( SUBTITLES_LIST ).getSelectedPosition() ) else: selection = str(self.list[self.getControl( SUBTITLES_LIST ).getSelectedPosition()]) log( __name__ ,"In 'On click' selec...
def withUmi(self, source, umiSource): readCounter = 0 try: # 'rt' mode for text mode reading with xopen(source, 'rt') as readHandle, \ xopen(umiSource, 'rt') as umiHandle: readIter = FastqGeneralIterator(readHandle) umiIter = Fast...
This code processes FASTQ files by splitting them into chunks based on user-specified parameters. It handles UMI (Unique Molecular Identifier) data if provided, sets output directories and filenames, and writes results with compression. The function parses command-line arguments, validates input, and ensures proper fil...
def run(self, args = None, quiet = False): if not args: args = self.parser.parse_args() self.perChunk = args.reads self.outdir = args.out if args.out else os.getcwd() self.prefix = args.prefix if args.prefix else re.search(r"(?i)^(.+?)(\.(fq|fastq))?(\.gz)?$", os.path.basen...
def recovery_drones(): # pyautogui.press("r") print("should") def choose_to_shoot(): return get_the_frigate() is not None or get_the_cruiser() is not None def get_none_selected(): return pyautogui.locateOnScreen(NONE_LOCKED, confidence=0.8) def select_to_shoot(): ship_icon = select_frig_or_cruise() ...
The code continuously monitors conditions to handle threats, alarms, and shooting actions. It toggles threat responses, triggers alarms with messages and processes, locks targets if shooting is selected, waits for lock confirmation, sends drones, and logs status updates. The loop runs indefinitely with delays, incremen...
def loop_running_small_stuff(q=None): threat = False temp = 0 while True: if should_i_play_closer_threat(): if not threat: played, threat = start_threat() else: stop_playing(played) threat = False if should_i_play_alarm(...
def process_marc_recs(m): m.rmd = b'' while True: batch = m.rmd + m.file['fd'].read(m.read_size) m.cur_batch = batch m.rmd = b'' if not batch: break fetch_recs(m) create_vufind_dict(m) create_vufind_bin(m) create_pod_dict(m) create_pod_bin(...
The code processes files in a given object `m` by iterating through its `files` attribute. Depending on the `file_format` of each file, it routes the file to specific processing functions: `process_marc_recs` for binary files, `process_delete_recs` for text files, and `process_marcxml_recs` for XML files. The main task...
def process_recs(m): for file in m.files: m.file = file if m.file['file_format'] in ['binary']: process_marc_recs(m) elif m.file['file_format'] in ['text']: process_delete_recs(m) elif m.file['file_format'] in ['xml']: process_marcxml_recs(m)
def initialize_logging(m): d = dict([['debug',logging.DEBUG],['info',logging.INFO], ['warning',logging.WARN], ['error',logging.ERROR],['critical',logging.CRITICAL]]) logging.basicConfig( level=d[m.log_level], format = '%(asctime)s %(name)-7s %(levelname)-6s %(message...
The main task of the code is to execute a series of processing steps (database initialization, job processing, file handling, and record processing) while logging start/end times, handling exceptions with stack traces, and ensuring resource cleanup (closing database connections and files). The function returns the main...
def main(): ts = time() m = main_class() initialize_logging(m) m.pdb = pdb_class(m) m.log.info('Time started: %s' % ctime()) try: init_db(m) process_job(m) process_files(m) process_recs(m) except Exception as e: m.log.error("Fatal error", exc_info=m.st...
def change_site_hashtag(name): while name[0] == '#': name = name[1:] url = f"https://www.instagram.com/explore/tags/{name}/" logger = Logger.getInstance() logger.set_current_site(url) driver.get(url) def change_site_main(): url = "https://www.instagram.com" logger = Logger.getInsta...
This function routes requests to different site-handling functions based on the input 'name'. If 'name' starts with '#', it processes hashtags; if empty, it calls the main site function; if 'profile', it handles profile-related tasks; otherwise, it delegates to a person-specific function.
def change_site(name=""): if name[0] == '#': change_site_hashtag(name) elif name == "": change_site_main() elif name == "profile": change_site_profile() else: change_site_person(name)
def get_following_count(): change_site_profile() time.sleep(random.uniform(0.5,2)) following_div = driver.find_element_by_css_selector('a[href*="following"]') global followings followings = int(following_div.find_element_by_css_selector("span.g47SY").text) logger = Logger.getInstance() logg...
The function automates unfollowing users on a social media profile, adhering to configured limits (hourly/dayly max unfollows) and preferences (prioritizing non-followers or using a whitelist). It navigates to the "following" list, filters users, and unfollows them randomly or selectively, updating statistics, checking...
def unfollow_in_profile(): logger = Logger.getInstance() logger.set_bot_status(BotStatus.UNFOLLOWING_IN_PROFILE) # Get count of people you're following global followings get_following_count() # Check limit unfollow_limit = not (config.data.chance_of_unfollow > 0 and statistics.ge...
def choose_direction(self, walls: ComponentSet): has_places_to_explore = len(self.non_visited) > 0 or len(self.trash_points) > 0 if walls == self.FOUR_WALLS or not has_places_to_explore: return self.messenger.build_stop_message() x, y = self.x, self.y non_visited = [] ...
The function devises a recharge plan by calculating the shortest path to a recharge point, avoiding obstacles and visited areas. It updates movement instructions, adjusts energy-based recharge targets, and returns either a recharge or move message depending on detected components and pathfinding results.
def devise_recharge_plan(self, perceived: ComponentSet): if len(self.recharge_points) == 0: return self.choose_direction(self.get_perceived_wall_info(perceived)) self.plan = Plan.RECHARGE self.nrecharge_points = int((self.MAX_ENERGY - self.energy) / 10) if self.components.R...
def choose_direction(self, walls: ComponentSet): has_places_to_explore = len(self.non_visited) > 0 or len(self.trash_points) > 0 if walls == self.FOUR_WALLS or not has_places_to_explore: return self.messenger.build_stop_message() x, y = self.x, self.y non_visited = [] ...
The code plans a path for a robot to deposit trash by calculating the shortest route to a trash bin using a matrix representation of the environment, updating movement instructions, and sending a move command.
def devise_deposit_plan(self, perceived: ComponentSet): if len(self.trash_bins) == 0: return self.choose_direction(self.get_perceived_wall_info(perceived)) if self.components.BIN in perceived: self.movements = [] self.plan = Plan.NONE return self.messenge...
def memorize(self, perceived: ComponentSet): if (self.x, self.y) in self.non_visited: self.non_visited.remove((self.x, self.y)) self.wall_map[(self.x, self.y)] = self.get_perceived_wall_info(perceived) self.visited.add((self.x, self.y)) if self.components.WALLN not in perceiv...
The code manages an agent's actions based on its current plan (e.g., explore, deposit, recharge, clean) and environmental perceptions. It processes movements, updates position, handles energy thresholds, and sends messages for navigation, task completion, or state changes. If no active plan exists, it decides actions b...
def act(self, perceived: ComponentSet): self.memorize(perceived) if self.energy <= 0: return self.messenger.build_stop_message() if self.plan != Plan.NONE: if self.plan == Plan.EXPLORE: if len(self.movements) == 0: raise ZephyrusExcepti...
def preprocess_input(img, w, h): ih, iw, _ = img.shape scale = min(w/iw, h/ih) nw = int(iw*scale) nh = int(ih*scale) image_data = cv2.resize(img, (nw,nh)) new_image = np.full((h,w,3), (128,128,128), dtype='uint8') new_image[(h-nh)//2 : (h+nh)//2, (w-nw)//2:(w+nw)//2] = image_data image_data = new_image...
The main task of the code is to process a batch of images through a YOLO model, decode predicted bounding boxes from the model's outputs using specified anchors and thresholds, adjust box sizes to original image dimensions, and apply non-max suppression (NMS) to refine detections, returning final bounding boxes for eac...
def get_yolo_boxes(model, images, net_h, net_w, anchors, obj_thresh, nms_thresh): image_h, image_w, _ = images[0].shape nb_images = len(images) batch_input = np.zeros((nb_images, net_h, net_w, 3)) # preprocess the input for i in range(nb_images): batch_input[i] = preproces...
def stopRecording(self): global _key_press_rec_iter, _key_press_rec_label_uni, _key_press_rec_label_bil, _key_press_rec, recording_start_time #audio_record.stop() subjID = '' aasanaID = '' self.audio_stop_flag = True while self.audio_is_stopped == False: pass ...
This code handles a button's toggle functionality to start/stop recording. It detects mouse clicks on a specified area, switches between start and stop states, updates visual feedback (color and text), and manages recording state variables. The button's appearance changes based on recording status, using Pygame for ren...
def recordingButton(self, start_msg, stop_msg, x, y, w, h, start_col, stop_col): global _key_press_rec_iter, _key_press_rec_label_uni, _key_press_rec_label_bil, _key_press_rec, recording_start_time mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() # print(click) i...
def csv_writer(self, filename, data): with open(filename, "a") as csv_file: writer = csv.writer(csv_file, delimiter=',') for line in data: writer.writerow(line) def draw_body(self, joints, jointPoints, color): # Torso self.draw_body_bone(joints, jointPoint...
The code records and saves Kinect sensor data (color, depth, infrared frames and body joint positions) along with keyboard inputs during a session. It handles window events, captures real-time frames, timestamps them, and stores them in CSV and numpy files for later analysis, while maintaining a 60 FPS loop for real-ti...
def run(self): global _key_press_rec_iter, _key_press_rec_label_uni, _key_press_rec_label_bil, _key_press_rec, recording_start_time # -------- Main Program Loop ----------- while not self._done: # --- Main event loop for event in pygame.event.get(): # User did something ...
def loss_function(self): # Computes the Cross Entropy Loss Function for all the training samples total_loss = -(1 / self.n) * np.sum(self.Y * np.log(probability(self.theta, self.X)) + (1 - self.Y) * np.log(1 - probability(self.theta, self.X))) return t...
The code performs batch gradient descent for multi-class classification, initializing parameters theta as a k×d array. It iteratively updates theta using the gradient of the loss function, tracks cost progression, and stops when convergence (loss change < 1e-6) or max iterations are reached. Returns final theta and cos...
def train(self, verbose=False): # Runs batch gradient descent for a specified number of iterations on a dataset # with theta initialized to the all-zeros array. Here, theta is a k by d NumPy array # where row j represents the parameters of our model for label j for # j = 0, 1, ..., k-1 ...
def normalize(x): return (x - x.mean(axis=0)) / x.std(axis=0) def augment_feature_vector(x): # Adds the x[i][0] = 1 feature for each data point x[i]. # Args: x - a NumPy matrix of n data points, each with d - 1 features # Returns: x augmented, an (n, d) NumPy array with the added feature for each dat...
The code initializes a logistic regression model by preparing input data (normalizing features and adding bias terms), setting hyperparameters (learning rate, iterations), initializing weight parameters (`theta`), and triggering the training process. It handles multi-class classification by determining the number of cl...
def __init__(self, x, y, eta=0.001, max_iter=1000, normal=True, biases=True, verbose=False): # data preparation and parameter initialization if normal: # normalize each feature (column) of X self.X = normalize(x) else: self.X = x if biases: ...
def get_datasets(args, num_expand_x, num_expand_u): precomputed_mean, precomputed_std = get_precomputed_mean_and_std(args) train_sampler = RandomSampler if args.local_rank == -1 else DistributedSampler tokenizer = ( BertTokenizer.from_pretrained(args.bert_model, do_lower_case=True).tokeni...
The function `get_data_loaders` prepares data loaders for training and evaluation by selecting appropriate data splits (labeled, unlabeled, dev, test) and formatting (`classic` or `multimodal`). It delegates loader creation to specialized functions based on the `args.my_format` parameter, ensuring compatibility with di...
def get_data_loaders(args): labeled_set, unlabeled_set, dev_set, test_set = get_datasets(args, args.k_img, args.k_img*args.mu) if args.local_rank == 0: torch.distributed.barrier() if args.my_format == 'classic': return get_classic_data_loaders(labeled_set, unlabeled_set, de...
def measure_index_set(spec, ref='lepine2007', index_info=None, plot=False, no_trials=1000, diag_path=None): index_info = None for reference in list(kastclassify.defs.index_dict): if ref in reference: index_info = kastclassify.defs.index_dict[reference] ...
The function classifies a spectrum by calculating spectral types using Lepine and Gizis indices, estimating uncertainties via Monte Carlo simulations, and determining metallicity class based on zeta values. It returns spectral type measurements, their errors, and metallicity classification.
def classify_by_index(spec, index_dict=None, no_trials=100, plot=False): if index_dict is not None: lepine_indices = index_dict['lepine2007'] gizis_indices = index_dict['gizis'] else: lepine_indices = measure_index_set(spec, ref='lepine2007', no_trials=no_trials, plot=plo...
def classify_by_standard(spec, ref='lepine', plot=False, diag_path=None): lepine_str = 'lepine' kirkpatrick_str = 'kirkpatrick' burgasser_str = 'burgasser' sdss_str = 'SDSS' all_str = 'all' STANDARD_SPECTRA = [] LEPINE_STANDARDS = [] KIRKPATRICK_STANDARDS = [] BURGASSER_STA...
The main task of the code is to process an astronomical spectrum file by reading its data, extracting metadata, classifying the spectral type using standard comparisons and indices, measuring spectral indices and equivalent widths, calculating luminosity ratios, and packaging all results into a structured dictionary fo...
def calc_spec_info(filepath, plot=False, no_index_trials=100, no_EW_trials=30, diag_path=None): t1 = datetime.datetime.now() #collecting header info print('Reading in {}'.format(filepath)) spec = kastredux.readSpectrum(filepath) spec.name = fits.getheader(filepath)['OBJECT'] ...
def animate_pacman_movement(self, pacman, prevPacman, image): if self.frame_t < 0: print('Press any key to step forward, "q" to play') keys = wait_for_keys() if 'q' in keys: self.frame_t = 0.1 if self.frame_t > 0.01 or self.frame_t < 0: sta...
This method updates agent positions (Pac-Man or ghost) based on the new state, animates their movement, removes eaten coins/big food, updates the score, and tracks ghost distances. It uses the new_state to determine which agent moved, applies specific movement logic for Pac-Man or ghosts, and modifies game elements lik...
def update(self, new_state): #updating the agent moved agent_index = new_state.agent_moved agentState = new_state.agent_states[agent_index] prevState, prevImage = self.agent_img[agent_index] if agentState.is_pac: self.animate_pacman_movement(agentState, prevState, pr...
def start_graphic(self, state): #initializing the graphics onto the screen self.maze = state.maze maze = self.maze self.width = maze.width self.height = maze.height self.make_window(self.width, self.height) self.info_p = info_p(maze, self.grid_size) self.c_state =...
The code initializes an object's state by setting the `isBlue` attribute, starting graphical rendering with the provided state, lazily initializing distribution images, creating static and agent objects based on the state, and storing the previous state for reference.
def initialize(self, state, isBlue = False): self.isBlue = isBlue self.start_graphic(state) self.distributionImages = None # Initialized lazily self.make_static_obj(state) self.make_agent_obj(state) # Information self.previousState = state
def getBackupPath(self): backup_path = os.path.join(f'{self.getGDFSDrivePath()}', 'AppLovin_Backup') return backup_path def getGDFSDrivePath(self): if sys.platform == 'win32': drive_letter = '' try: drive_letter = self.getDriveLetter() except: ...
The code initializes OS-specific paths and configurations for backup/restore operations, setting up user directories, Google Drive app locations, download links, and restore file paths for Windows and macOS. It prepares environment variables, executable paths, and drive mappings to interact with Google Drive across pla...
def __init__(self): self._user_path = os.path.expanduser('~') self._dest_path = self.getBackupPath() if sys.platform == 'win32': script_path = sys.argv[0] script_dir = os.path.split(script_path)[0] restore_file_win = f'{os.path.join(script_dir, "Restore.exe")}...
def precision_metric(predictions, labels, category): tp = 0 fp = 0 for i, p in enumerate(predictions): if p != category: continue elif p == labels[i]: tp += 1 elif p != labels[i]: fp += 1 return tp/(tp+fp+1e-20) def recall_metric(predictions, ...
The main task of the code is to evaluate model performance by calculating precision, recall, accuracy, confusion matrix, and macro-averaged F1 score for 4 classes, then formatting these metrics into a structured string for reporting.
def evaluate(predictions, labels): precisions = [] recalls = [] for i in range(1, 5): precisions.append(precision_metric(predictions, labels, i)) recalls.append(recall_metric(predictions, labels, i)) acc = accuracy_metric(predictions, labels) confusion_matrix = confusion_matrix_metri...
def init(): global configdict global configlist global ver global renamefile wd = os.path.dirname(os.path.abspath(__file__)) + '/' + configfile if not is_valid_file(wd): print(f"Config file {configfile} missing") return try: configdict = dict(CF.Config(wd).Fetc...
The code provides a command-line interface (CLI) for managing reservation data stored in a JSON file. It initializes the system, loads the specified file, and allows users to list/edit reservations, search records, add new entries, or quit. The main loop processes user choices and executes corresponding functions, hand...
def main(): global keajson intt = init() if not intt: quit() if len(sys.argv) >= 2: keajson = sys.argv[1] else: print('enter filename') quit() res = get_file() #parse_reservation(res) clears() while True: border_text(title) answe...
def get_tokens(self) -> list[Tokens]: pass def init_vars(self): # Details self.name_var: StringVar = StringVar() self.address_var: StringVar = StringVar() self.dex_var: StringVar = StringVar() self.slippage_var: DoubleVar = DoubleVar() self.buy_tax_var: DoubleVar ...
This code initializes a GUI layout by configuring grid columns for different frames (token list, details, logging), setting minimum sizes and weights for responsive resizing, initializing token data, and creating UI components like token lists and logging panels.
def __init__(self, parent: Tk): super().__init__(parent, padding=5) # self.grid(row=0, column=0, sticky=self.NEWS) # placed in main.py self.rowconfigure(0, weight=1, minsize=500) self.columnconfigure(0, weight=0, minsize=240) # token_list_frame self.columnconfigure(1, weight=0,...
def init_web3(self): """Initiate Web3 with HTTP node (For WSS you need Python 3.9)""" node = self.settings.bcs_node one_minute = int(time.time()) while True: if node.startswith("w"): # self.web3 = Web3(Web3.WebsocketProvider(node)) print("Sorry...
The code's main task is to initialize a web3 connection, retrieve account balance and token data, prepare transaction layers, and execute a trading loop. It then terminates the bot, printing a stop message.
def run(self): self.init_web3() self.account_balance() self.fetch_token_data() self.create_transactions_layer_list() self.main_loop() print("========================================") print("Info: Bot stopped trading.")
def gamma_m(om,k,M,u1,u2,eta = 1e-3): # Gamma_m matrix A = sp.lil_matrix((M-1,M-1),dtype=complex) for i in range(M-1): A[i,i] = -(om+1j*eta-U(u1,u2,i+1,M-i-1)) for i in range(M-2): A[i,i+1] = -np.exp(-1j*k) for i in range(M-2): A[i+1,i] = -np.exp(1j*k) return A.tocsc() def alpha_m(M): # Alpha_m mat...
This function iteratively computes the matrix A₃ by adjusting dimensions and applying matrix operations involving gamma_m, beta_m, and alpha_m. Starting with an initial matrix calculation, it reduces Mc until reaching 3, updating the matrix through inversion, multiplication, and resizing at each step. The result is the...
def find_Am__help(om,k,Mc,u1,u2,eta=1e-3): # Find A_3 matrix by iteration aa = inv(gamma_m(om,k,Mc,u1,u2,eta))*alpha_m(Mc) while(Mc>3): aa = beta_m(Mc)*aa Mc -= 1 aa. resize((Mc-1,Mc-1)) aa = gamma_m(om,k,Mc,u1,u2,eta)-aa aa = inv(aa)*alpha_m(Mc) return aa
def gamma_m(om,k,M,u1,u2,eta = 1e-3): # Gamma_m matrix A = []#sp.lil_matrix((M-1,M-1),dtype=complex) row =[] col =[] for i in range(M-1): A.append(-(om+1j*eta-U(u1,u2,i+1,M-i-1))) row.append(i) col.append(i) for i in range(M-2): A.append(-np.exp(-1j*k)) row...
The function iteratively computes a matrix 'aa' (likely A₃) by solving linear systems involving gamma_m, alpha_m, and beta_m functions. It starts with an initial matrix calculation and repeatedly adjusts 'aa' and reduces Mc until Mc ≤ 3, returning the final matrix result.
def find_Am__help(om,k,Mc,u1,u2,eta=1e-3): # Find A_3 matrix by iteration ident = sp.identity(Mc-1,dtype=complex) aa = spsolve(gamma_m(om,k,Mc,u1,u2,eta),ident)*alpha_m(Mc) while(Mc>3): aa = beta_m(Mc)*aa Mc -= 1 aa. resize((Mc-1,Mc-1)) aa = gamma_m(om,k,Mc,u1,u2,eta)-aa ...
def get_output(self, img_path, aspectRatios=None): cmd = self.cmd_template.format(img_path.absolute()) if aspectRatios is None: aspectRatios = self.aspectRatios if aspectRatios is not None: aspectRatio_str = " ".join(str(ar) for ar in aspectRatios) cmd = f"{cm...
The function `plot_img_crops` visualizes image crops generated from saliency maps for specified aspect ratios. It arranges crops, saliency heatmaps, and top salient points in a grid layout, adjusting figure dimensions and subplot configurations based on input parameters like `topK`, `aspectRatios`, and `col_wrap`. It h...
def plot_img_crops( self, img_path, heatmap_path, topK=1, aspectRatios=None, checkSymmetry=True, sample=False, col_wrap=None, add_saliency_line=True, ): # print("2. HELLO, starting plot_img_crops") img = mpimg.imread(img_path) ...
def process_averages(): x = pd.read_csv("all_matches_filtered.csv") first_serve_made = x["first_serve_made"].sum() first_serve_attempted = x["first_serve_attempted"].sum() second_serve_made = x["second_serve_points_made"].sum() second_serve_attempted = x["second_serve_points_attempted"].su...
The code generates performance statistics by processing player averages and raw data, matching players with their opponents, and exporting the combined data as a JSON file named "performanceStats.json"
def generate_performance_stats(): averages = process_averages() raw_data = process_all_players_performance_stats() data = match_player_with_opponents(averages, raw_data) json_data = json.dumps(data) with open("performanceStats.json", "w") as outfile: outfile.write(json_data)
def Profile(Motifs): t = len(Motifs) counts = Count(Motifs) for key in counts: arr = counts[key] counts[key] = [x/t for x in arr] return counts def ProfileMostProbableKmer(text, k, profile): l = len(text) best = 0.0 bestval = text[:k] for j in range(l - k + 1): km...
(GreedyMotifSearch identifies the best set of k-length motifs from t DNA sequences by iteratively selecting a starting position in the first sequence, then greedily choosing the most probable k-mers in subsequent sequences based on a profile matrix. It updates the best motifs if the current set has a lower score, aimin...
def GreedyMotifSearch(Dna, k, t): assert len(Dna) == t BestMotifs = [] for i in range(0, t): BestMotifs.append(Dna[i][0:k]) n = len(Dna[0]) for i in range(n-k+1): Motifs = [] Motifs.append(Dna[0][i:i+k]) for j in range(1, t): P = Profile(Motifs[0:j]) ...
def ProfileWithPseudocounts(Motifs): t = len(Motifs) + 4.0 counts = CountWithPseudocounts(Motifs) for key in counts: arr = counts[key] counts[key] = [x/t for x in arr] return counts def ProfileMostProbableKmer(text, k, profile): l = len(text) best = 0.0 bestval = text[:k] ...
(GreedyMotifSearchWithPseudocounts identifies the best set of k-length motifs in t DNA sequences using a greedy algorithm. It initializes BestMotifs with the first k-mers of each sequence, then iterates through all possible k-mer positions in the first sequence. For each position, it constructs Motifs by selecting the ...
def GreedyMotifSearchWithPseudocounts(Dna, k, t): assert len(Dna) == t BestMotifs = [] for i in range(0, t): BestMotifs.append(Dna[i][0:k]) n = len(Dna[0]) for i in range(n-k+1): Motifs = [] Motifs.append(Dna[0][i:i+k]) for j in range(1, t): P = ProfileWi...
def RandomMotifs(Dna, k, t): assert len(Dna) == t l = len(Dna[0]) res = [] for seq in Dna: index = random.randint(0, l - k) res.append(seq[index:index+k]) return res def ProfileWithPseudocounts(Motifs): t = len(Motifs) + 4.0 counts = CountWithPseudocounts(Motifs) for key ...
The GibbsSampler function iteratively refines a set of motifs from DNA sequences using Gibbs sampling. It starts with random motifs, then repeatedly selects a random motif, generates a profile from the remaining motifs, finds the most probable k-mer in the corresponding DNA string using the profile, replaces the select...
def GibbsSampler(Dna, k, t, N): M = RandomMotifs(Dna, k, t) assert len(M) == t BestMotifs = M for j in range(N): i = random.randint(0, t-1) noti = [v for index, v in enumerate(M) if index != i] assert len(noti) == t - 1 prof = ProfileWithPseudocounts(noti) kmer =...
def RandomMotifs(Dna, k, t): assert len(Dna) == t l = len(Dna[0]) res = [] for seq in Dna: index = random.randint(0, l - k) res.append(seq[index:index+k]) return res def ProfileWithPseudocounts(Motifs): t = len(Motifs) + 4.0 counts = CountWithPseudocounts(Motifs) for key ...
The function performs randomized motif search to identify the best set of k-length motifs in t DNA sequences. It starts with random motifs, iteratively generates new motifs using a probability profile with pseudocounts, and updates the best motifs if the new score is lower. The loop terminates when no improvement is fo...
def RandomizedMotifSearch(Dna, k, t): M = RandomMotifs(Dna, k, t) BestMotifs = M while True: Profile = ProfileWithPseudocounts(M) M = Motifs(Profile, Dna) if Score(M) < Score(BestMotifs): BestMotifs = M else: return BestMotifs
def _rotate_proxies_and_check_results(url=amzn_ps5_url): if len(proxy_stack) == 0: update_proxy_stack() i = 0 while proxy_stack: proxy = proxy_stack.pop() if proxy in bad_proxies: continue print(f" -Trying proxy: {proxy}") i += 1 is_bad, result = ...
The main task of the code is to monitor the availability of a PS5 product on a specified URL using proxy rotation. It checks stock status, availability, and pricing, logs results to Firebase, and sends FCM notifications based on conditions like stock presence, price ranges, and button existence. If all proxy attempts f...
def _report_availability_thread(url=amzn_ps5_url): start_time = datetime.datetime.now().replace(microsecond=0) print(f"New job: {start_time.strftime(time_format)}") result = _rotate_proxies_and_check_results(url) if result is None: print(f" -- CURRENT TIME: {datetime.datetime.now().replace(mic...
def get_c_filelist(path_c): print_red('get_c_filelist()') files_c = [f for f in listdir(path_c) if isfile(join(path_c, f))] files_c = sorted(files_c, key=str.lower) if 0: for x in files_c: print_green(x) if 0: cmd = "echo test" os.system(cm...
The function processes assembly files by converting binary to assembly code, prepares data for doc2vec models, saves CSV files if enabled, and triggers model training or comparison based on specified modes.
def ctrl_file_lines( path_asm, learnnning_mode, compare_mode, save_mode, split_mode): eachlines = [] str_temp = '' texts = [] filelist = get_c_filelist(path_asm) for x in filelist: eachlines.append(bin2asm.get_elf_textsection2asm(path_asm + '/' + x, s...
def parse_preambles(path): global chan_to_part, part_to_chan """ Creates 2 id mappings 1) Dict: (meeting_id) -> (dict(chan_id -> participant_id)) 2) Dict: (meeting_id) -> (dict(participant_id -> chan_id)) """ dirname = os.path.dirname(__file__) preambles_path = os.path.join(dirname, path...
The function `parse_transcripts` processes transcripts from a specified path to generate mappings between communication channels and participants, and to identify specific event types. It parses preamble files, extracts transcript data, and creates two dataframes: one for laugh-only events and another for invalid segme...
def parse_transcripts(path): """ Function executed on import of this module. Parses transcripts (including preamble.mrt) and creates: - chan_to_part: index mapping channel to participant per meeting - part_to_chan: index mapping participant to channel per meeting - laugh_only_df: dat...
def __compute_null_space_projection(self, q): """Returns null space projector. Args: q (ndarray): Robot configuration. Returns: np.array(18,18) """ J_c = self.__compute_J_c(q) p = np.eye((self.__nv)) - pinv(J_c) @ J_c return p def __compu...
This function computes the time derivative of the centroidal momentum (h_g_dot) in a dynamically constrained robotic system. It uses the constrained inverse mass matrix, null-space projection, nonlinear dynamics terms, and torque input to calculate h_g_dot via matrix operations involving the centroidal map and its time...
def dynamic_model_h_g_dot(self, q, dq, tau): p = self.__compute_null_space_projection(q) m_c_inv = self.__compute_constraint_consistent_mass_matrix_inv(q, p) nonlinear_terms_h = self.__compute_nonlinear_terms_h(q, dq) torque_input = np.concatenate((np.zeros(6), tau), axis=0) A_g_...
def integrate_model(self, a_tilde, omega_tilde): """Calculates the 'a priori estimate of the mean of the state vector' from deterministic transient model by first_order integration. Args: a_tilde (np.array(3,1)): IMU accelerometer in the IMU frame. omega_tilde (np.array(3,1)): I...
The main task of the code is to update a filter's state using IMU accelerometer and gyroscope data, along with contact schedule and joint information. It integrates the model, performs a prediction step, and executes an update step to refine the state estimate based on sensor inputs and contact dynamics.
def update_filter( self, a_tilde, omega_tilde, contacts_schedule, joint_positions, joint_velocities, ): """Updates the filter. Args: a_tilde (np.array(3,1)): IMU accelerometer in the IMU frame. omega_tilde (np.array(3,1)): IMU ...
def __compute_null_space_projection(self, q): """Returns null space projector. Args: q (ndarray): Robot configuration. Returns: np.array(18,18) """ J_c = self.__compute_J_c(q) p = np.eye((self.__nv)) - pinv(J_c) @ J_c return p def __compu...
This function computes the 'a priori' state estimate by updating the momentum states (μ_pre) using the dynamic model's centroidal momenta (h_g) and their time derivatives (h_g_dot). It projects the robot's configuration into the null space, calculates time derivatives, and applies a time-step integration to update the ...
def integrate_model(self, q, dq, tau): """Calculates the 'a priori" estimate of the state vector. Args: q (ndarray): Robot configuration. dq (ndarray): Robot velocity. tau (ndarray): Joint torques. """ self.__p = self.__compute_null_space_projection(q...
def com_position(self, q): com = pin.centerOfMass(self.__rmodel, self.__rdata, q, False) return com def dynamic_model_h_g_dot(self, q, dq, tau): p = self.__compute_null_space_projection(q) m_c_inv = self.__compute_constraint_consistent_mass_matrix_inv(q, p) nonlinear_terms_h = se...
The main task of the code is to compute the discrete prediction Jacobian matrix (Fk) by numerically differentiating the robot's centroidal momenta and center-of-mass dynamics. It calculates partial derivatives of the dynamic model's output with respect to the center-of-mass position and centroidal momenta, combines the...
def compute_discrete_prediction_jacobain(self, q, dq, tau): """Returns the discrete prediction jacobian. Args: q (ndarray): Robot configuration. dq (ndarray): Robot velocity. tau (ndarray): Joint torques. Returns: np.array(9,9) """ ...
def integrate_model(self, q, dq, tau): """Calculates the 'a priori" estimate of the state vector. Args: q (ndarray): Robot configuration. dq (ndarray): Robot velocity. tau (ndarray): Joint torques. """ self.__p = self.__compute_null_space_projection(q...
The function `update_filter` updates a filter in a robotic system by integrating the robot's dynamics model using its current configuration (`q`), velocity (`dq`), joint torques (`tau`), and contact schedule. It performs a prediction step to estimate future states and an update step to refine these estimates, incorpora...
def update_filter(self, q, dq, contact_schedule, tau): """Updates the filter. Args: q (ndarray): Robot configuration. dq (ndarray): Robot velocity. contacts_schedule (list): Contact schedule of the feet. tau (ndarray): Joint torques. """ s...
def DoorBell(): global IsHome os.system("amixer -c 0 cset numid=3 1") y = SaveToPicF() os.system("aplay /home/pi/pythonok/match3.wav") if (IsHome == 1): SendEmail(y) def checkid(): ID = idread() try: f = open(rffile, "r") for x in f: x=x[:-1] ...
This code continuously monitors keypad inputs to control a door system. It triggers actions like ringing a doorbell, checking an ID, resetting a password, or opening the door based on pressed keys. The global `pwd` variable accumulates numeric inputs, and if it matches a predefined password, the door opens. The loop re...
def poll(): global pwd keys = keypad.pressed_keys if (str(keys) == "['A']"): DoorBell() time.sleep(0.3) elif (str(keys) == "['B']"): checkid() time.sleep(0.3) elif (str(keys) == "['*']"): pwd="" time.sleep(0.3) elif...
def _isUnderAttack(self, row, col): self.whiteMove = not self.whiteMove opponentMoves = self.getAllPossibleMoves() self.whiteMove = not self.whiteMove for move in opponentMoves: if move.endSqRow == row and move.endSqCol == col: return True return False...
This function generates valid castling moves for the king based on current castling rights and whether the king is under attack. It checks for king-side and queen-side castling eligibility, adding corresponding moves to the 'moves' list if conditions are met.
def _getCastleMoves(self, row, col, moves): if self._isUnderAttack(row, col): return if (self.whiteMove and self.currentCastlingRights.wks) or ( not self.whiteMove and self.currentCastlingRights.bks ): self._getKingSideCastleMoves(row, col, moves) if (...
def checkForPinsAndChecks(self): pins = [] checks = [] inCheck = False allyColor, opponentColor, startRow, startCol = ( ("w", "b", self.whiteKingLocation[0], self.whiteKingLocation[1]) if self.whiteMove else ("b", "w", self.blackKingLocation[0], self....
The code generates valid chess moves by checking for pins/checks, filtering moves if in check, handling castling, and determining checkmate/stalemate. It considers the current player's king position, validates moves against threats, and updates game state conditions.
def getValidMoves(self): tempCastleRights = CastleRights( self.currentCastlingRights.wks, self.currentCastlingRights.bks, self.currentCastlingRights.wqs, self.currentCastlingRights.bqs, ) moves = [] self.inCheck, self.pins, self.checks = se...
def calculate_input(): velocity = 1.0 yaw_rate = 1.0 control_input = np.array([[velocity], [yaw_rate]]) return control_input def observation(true_state, control_input): true_state = motion_model(true_state, control_input) measurement = observation_model(true_state) + np.array([[np.random.norm...
The code implements an Extended Kalman Filter (EKF) for state estimation in a robotic system. It initializes state and covariance variables, then runs a loop to update the true state, process measurements, and estimate the state using EKF. The estimated trajectory, true state, and measurement history are recorded, with...
def main(): print(__file__ + " start!!") # State Vector [x y yaw v]' state_estimate = np.zeros((4, 1)) true_state = np.zeros((4, 1)) covariance_estimate = np.eye(4) history_state_estimate = state_estimate history_true_state = true_state history_measurement = np.zeros((2, 1)) plt.f...
def display_title(): """Prints title to terminal.""" print(TITLE) def display_main_menu(): """Prints main manu options to terminal.""" global viewing_main_menu, viewing_game_options_menu viewing_main_menu = True viewing_game_options_menu = False text = "" for i, option in enumerate(MAIN...
The main task of the code is to load environment variables, display a title and main menu, handle menu navigation via a loop with custom key bindings, and execute the game logic while handling keyboard interrupts to exit gracefully. It initializes the game interface, manages user input, and ensures proper shutdown on i...
def main(): """Loads environment variables and run display and game functions.""" load_dotenv() display_title() display_main_menu() while True: while not is_playing_game: toolkit_prompt( "", key_bindings=MENU_NAVIGATION_BINDINGS, bottom_toolbar=ge...
def updateFactbase(self): self.updateXML() rules = self.root.findall("rule") counter=0 if self.state=="conclusion": return for rule in rules: antecedent_count=0 # print(f"rule number = {counter}") facts = rule.findall(".//...
This function transitions the system's state by updating the fact base, checking the current state, and either prompting for user input via questions or concluding the process if the state is "conclusion". It handles state validation, rule checks, and user interaction based on dynamic conditions.
def changeState2(self): print(f"current state : {self.state} \n") if self.state=="conclusion": print("===== END =====") return self.updateFactbase() self.checkState() if self.state=="": rules = self.checkRules() self.askRelatedQuest...
def battleRound(player, boss, spell, verbose=True): winner = None loser = None player.hitPoints -= 1 if player.hitPoints > 0: evaluateTurn(player, boss, spell, verbose=verbose) if boss.hitPoints <= 0: winner = player loser = boss elif player.hitPoin...
This function recursively explores all possible spell combinations a player can cast to defeat a boss, tracking the minimum mana required for victory. It clones the player and boss states, simulates battles with each spell, and updates the least mana spent when a winning combination is found. If no winner emerges, it c...
def tryAllSpells(player, boss, verbose=True): global leastMana, winningPlayer availableSpells = player.getAvailableSpells() for spell in availableSpells: clonedPlayer = copy(player) clonedBoss = copy(boss) if len(clonedPlayer.castSpells) < 4: print("The tri...
def get_userid(username): """ Returns the numeric ID of the username given or False if no user matches :param username: :return: int """ try: userid = queries.get_id_from_name(username=username)['id'] return userid except Exception: return False def get_permissions(us...
The main task of the code is to handle the home/entry page of a URL shortener. It processes POST requests to validate user-submitted URLs and optional keywords, checks for format and uniqueness, stores valid entries in the database, generates short URLs, and renders the `home.html` template with results, errors, or per...
def home(): """ Display the home/entry page for the shortener :return: jinja template for /home.html """ errors = [] # Set the username once so we don't have to keep querying it username = g.ldap_username # Get the numeric ID of teh user (maybe make it so we userid = get_userid(user...
def register_model_hooks(model): model.layer1.register_forward_hook(get_activation('layer1')) model.layer2.register_forward_hook(get_activation('layer2')) model.layer3.register_forward_hook(get_activation('layer3')) model.fc.register_forward_hook(get_activation('layer4')) return model def calibrate_...
The code trains a neural network model with configurable parameters, handling different prediction types (e.g., 'mann', 'mlp') by adding noise to model blocks, calibrating weights, and using inner-loop optimization. It logs training/validation metrics (loss, accuracy, block predictions) via Weights & Biases, performs f...
def train(): run = wandb.init() print(wandb.config) model = utils.get_model() orig_model = copy.deepcopy(model) inner_model = None if "mann" in wandb.config.pred_type: input_dim = 3 * 32 * 32 + 16 * 32 * 32 + 32 * 16 * 16 + 64 * 8 * 8 + 10 inner_model = utils.get_inner_model(inp...
def check_for_errors(self): """ Checks if the code has the errors or not specified data """ if ( DRIVER_PATH == '' ): raise Exception('You must specify the path to the Webdriver') def greeting_message(self): """ Output the Greeting message """ self.clear_screen() print('Welcome to Steam Bulk Buye...
The main task of the code is to execute a structured process: check for errors, greet the user, retrieve items from input, display retrieved items, prompt user confirmation, issue a warning, process purchases, and finalize with a success message, ensuring a guided interaction for item handling and transaction completio...
def main(self): self.check_for_errors() self.greeting_message() self.get_items_from_user() self.output_retrieved_items() input('Press ENTER to Proceed...\n') self.warning_message() self.purchase_items() self.success_message()
def generate_byte(proc, value, size="2", offset="1", payload='A'): gotcha = False tries = 0 while not gotcha: if tries % 256 == 0 : print("Already tried generating %d times" % tries) print("Proc size is : {}".format(sys.getsizeof(proc.buff))) tries += 1 read_u...
The main task of the code is to interact with a process by sending specific inputs, extract a string from the response, analyze its 4-character substrings to identify the most frequent one, determine its position, and return the corresponding page index. It leverages a Counter to track substring frequencies, selects th...
def determine_service_index(proc): generate_byte(proc, 0x40, offset=str(-0x8000000)) print(read_until(proc, value=': ')) write_string(proc, "c") read_until(proc, value=': ') write_string(proc, "0") read_until(proc, value=': ') write_string(proc, "g") read_until(proc, value=': ') writ...
def eat_header(proc): print(read_until(proc)) print(read_until(proc, value=': ')) def prepare_trustlets(proc): write_string(proc, "l") print(read_until(proc, value=': ')) write_string(proc, "0") print(read_until(proc, value=': ')) write_string(proc, "l") print(read_until(proc, value=': ...
The code connects to a remote service or starts a local process, prepares a secure environment, injects and executes shellcode to exploit a target system, likely for CTF challenges, by generating a bootstrap payload and interacting with a daemon process.
def main(): # set to None for local process usage # remote_target = None remote_target = (('microservicedaemonos.ctfcompetition.com', 1337)) if not remote_target: ll_proc = subprocess.Popen('./MicroServiceDaemonOS', stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) p...
def encoder_layer(inp, n_out, fil, dil_rate, std, swtch, alpha_val, reg_val): y = con2d(inp, n_out, fil, dil_rate, std, swtch, alpha_val, reg_val) y = con2d(y, n_out, fil, dil_rate, std, swtch, alpha_val, reg_val) y = y+con2d(inp, n_out, 1, dil_rate, std, swtch, alpha_val, reg_val) y_crop = center_crop(...
The code defines a PAUNet model with an encoder-decoder architecture, incorporating multi-head attention. It processes input data (latitude, longitude, channels) through encoder layers that progressively double output dimensions, followed by attention blocks for feature refinement. The decoder upscales features using d...
def PAUNet(n_blocks, MHA_blocks, lat, lon, chnl, out_days, n_out, fil, dil_rate, std, swtch, alpha_val, reg_val, num_heads, key_dim, attention_axes): inp = layers.Input(shape = (lat, lon, chnl)) y = inp # --- Encoder route ---# for n_block in range(n_blocks): if n_block == n_blocks-1...
def get_mini_batches(self, X, y, batch_size): m = X.shape[1] mini_batches = list() num_batches = math.floor(m/batch_size) for i in range(0, num_batches): mb_X = X[:, i * batch_size : (i+1) * batch_size] mb_y = y[:, i * batch_size : (i+1) * batch_size] ...
The code trains a neural network using mini-batch gradient descent. It shuffles data, divides it into mini-batches, performs forward and backward passes, updates weights/biases, and tracks training accuracy/loss per epoch.
def train(self, X, Y): for epoch in range(self.num_epochs): # shuffle data random = np.arange(len(X[1])) np.random.shuffle(random) X_shuffle = X[:, random] Y_shuffle = Y[:, random] mini_batches = self.get_mini_batches(X_shuffle, Y_...
def forward_pass(self, X): # Forward pass through the network self.hidden_output = self.relu(np.dot(X, self.weights1) + self.bias1) self.output = self.sigmoid(np.dot(self.hidden_output, self.weights2) + self.bias2) # change to softmax (good for classification) return self.output ...
This code trains a machine learning model using mini-batch gradient descent. It shuffles training data each epoch, processes data in batches, performs forward and backward passes, and evaluates model performance on both training and test sets. Metrics like loss and accuracy are calculated and stored for each epoch, wit...
def train(self, X_train, y_train, X_test, y_test): num_samples_train = X_train.shape[0] for epoch in range(self.num_epochs): # Shuffle the indices of the training dataset indices_train = np.random.permutation(num_samples_train) print(len(indices_train)) ...
def getValue(variable): if getValueA(variable) is not None: return getValueA(variable) else: writeErr(56, 'Missing value of variable') def writeErr(code, message=''): sys.stderr.write(message + '\n') exit(code) def getType(variable): checkVar(variable) frame = re.split('@', varia...
The function `getSymb` validates an operand's type and value. It checks if the input `arg` (a variable or constant) has a type in the specified list (`types`). If `empty` is True, it ensures the value isn't `None`. For variables, it retrieves the value and checks its type; for constants, it validates directly. If inval...
def getSymb(arg, types=['int', 'string', 'bool', 'nil', 'float'], empty=False): if arg.type == 'var': val = getValue(arg.value) if empty and val is None: writeErr(56, 'Wrong value of operands') else: if getType(arg.value) in types: return val ...
def findEqX(p, e): a = ((int)(math.sqrt((p-1)))) b = a + 1 return (a,b) def computeAValues(a, l, p): i = 0 a_values = [] while(i <= a): num = (l ** (a*i))%p a_values.append(num) i+=1 return a_values def computeBValues(b,l,p,e): i = 0 b_values={} while(i <=...
The code solves a modular exponentiation equation $ l^x \equiv e \mod p $ using a divide-and-conquer approach. It finds coefficients $ a $ and $ b $, computes their corresponding values $ a_i $ and $ b_i $, and combines them to derive $ x = a \cdot a_i + b_i $. If a valid pair is found, it prints $ x $; otherwise, it r...
def divideAndConquer(p,l,e): coef = findEqX(p, e) a_values = computeAValues(coef[0],l,p) print("a = "+str(coef[0])) print(a_values) print("") b_values = computeBValues(coef[1],l,p, e) print("b = "+str(coef[1])) print(b_values) ab_pair = findPair(a_values, b_values) if(ab_pair): ...
def orderFactors(num): factors = factor(num) if not factors: return [] current = NotImplemented n = 0 pairs = [] for e in factors: if(e == current): n += 1 else: if(n > 0): pairs.append((current, n)) n = 1 cu...
The code solves the discrete logarithm problem using the Pohlig-Hellman algorithm. It computes $ x $ such that $ l^x \equiv e \mod p $ by decomposing $ p-1 $ into factors, solving congruences for each factor via `getXModP`, and combining results using the Chinese Remainder Theorem (CRT). The final value of $ x $ satisf...
def pohlig(p,l,e): xCongruences = [] print("Congruences for x:") for (fac, pwr) in orderFactors(p-1): congruence = getXModP(e,l,p,fac,pwr) print(" x mod "+str(congruence[1])+" = "+str(congruence[0])) xCongruences.append(congruence) x = crt(xCongruences) print("For "+str(l)+...
def generateChromosome(NQueen): List = [] for _ in range(NQueen): List.append(random.randint(1, NQueen)) return List def fitness(chromosome, maxFitness): # calculate fitness for chromosome. # Global variables n = len(chromosome) left_diagonal = 0 right_diagonal = 0 horizonta...
The code solves the N-Queens problem using a differential evolution algorithm. It initializes a population of random chromosome configurations, iteratively evolves them to maximize fitness (representing non-attacking queen arrangements), and returns the first valid solution along with the number of generations required...
def run(NQueen): maxFitness = (NQueen * (NQueen - 1)) / 2 # 1 1 1 1 population = [generateChromosome(NQueen) for _ in range(100)] generation = 1 # while maxFitness not found in population // 6 - (H + R + L) while not maxFitness in [fitness(chrom, maxFitness) for chrom in population]: popu...
def kill_github() -> None: """ Kill github process if running """ github_running = github_process() if github_running: print("\nStopping Github Process...") kill_status = run_command(f"taskkill /f /im {github_executable}") if kill_status.returncode != 0 and "ERROR: The proce...
This function sets up GitHub accounts by terminating existing processes, validating user uniqueness, backing up data, launching GitHub for login, renaming configuration folders, and updating a JSON config file. It handles 'init' setup or adding/removing users, ensuring no duplicate accounts and proper GitSwitch initial...
def setup(setup_accounts, setup_type='add-user', current_user=None): """ Initial accounts setup / method to setup more accounts """ kill_github() while github_process(): print("\t waiting for GitHub Desktop to terminate...", end="\r") time.sleep(2) # add a init setup type method...
def kill_github() -> None: """ Kill github process if running """ github_running = github_process() if github_running: print("\nStopping Github Process...") kill_status = run_command(f"taskkill /f /im {github_executable}") if kill_status.returncode != 0 and "ERROR: The proce...
The main task of the code is to delete specified users from a system (gitswitch) along with their data. It checks if users exist in the account list, terminates GitHub processes if the user being deleted is the current user, removes the user from accounts, updates configurations, and restarts gitswitch if no user remai...
def delete_user(users: list): """ delete user from gitswitch along with their data """ accounts = get_accounts() current_user = get_current_user() for user in users: if user in accounts: if user == current_user: kill_github() while github_proce...
def macdTrader(self): self.current_price = indicators.get_current_price(indicators, self.ticker) self.macdData.append(self.current_price) if len(self.macdData) == 26: twenty_six_ema = self.calculateEMA(self.macdData, 26, 25) twelve_ema = self.calculateEMA(self.macdData, ...
The code's main task is to execute a "triple threat" trading strategy by combining MACD, RSI, and Stochastic indicators. It increments a counter, runs three trading methods, and triggers buy/sell actions via Alpaca when specific conditions (counter >35, indicator thresholds) are met, aiming to automate trades based on ...
def tripleThreatTrader(self): self.tripleThreatCounter += 1 self.macdTrader() self.rsiTrader() self.stoTrader() print(self.tripleThreatCounter) if(self.tripleThreatCounter > 35 and self.stochasticK < 20 and self.rsi > 50 and self.macd > self.macdSignalLine): ...
def calculate_detailed_isolated_rankings_direct(town_names, town_wind, town_pressure, town_density, town_altitude, town_woodburner): """ Calculate scores for each town compared to every other, isolating each feature, without using a combined town_features dictionary. :param town_names: List of all town nam...
The main task of the code is to evaluate and rank towns based on environmental and demographic factors (wind speed, pressure, population density, altitude, woodburners) by comparing calculated rankings with a predefined ground truth. It normalizes data, computes weighted rankings, and outputs scores for each town's sim...
def main_function(): ground_truth = { 'Invercargill': ['Cromwell', 'Reefton', 'Masterton'], 'Cromwell': ['Invercargill', 'Reefton', 'Masterton'], 'Masterton': ['Invercargill', 'Cromwell', 'Reefton'], 'Reefton': ['Invercargill', 'Cromwell', 'Masterton'] } town_names = ['Inve...
def sport_key_to_game(game_to_find): requested_game = None games = get_all_sports() for game in games: if game["keyTG"] == game_to_find: requested_game = game return requested_game def get_all_matches(sport_key): url = f"http://{BACKEND_URL}/sports/{sport_key}" response = r...
The function processes user input to identify a game, retrieves its completed matches, and formats a response listing available bets. It handles group chat context, validates the game, filters completed matches, and generates a betting command list for the user.
def send_available_bet_matches(message): print( f"User interacted with, 'send_available_bet_matches'\nWith id: {message.from_user.id}\nfirstname: {message.from_user.first_name}\nfullname: {message.from_user.full_name}\ntext: {message.text}") # resolve here the short to the right key by fethcing all game...
def sign_message_with_encrypted_credentials(encrypted_account_json, message): encrypted_account = json.loads(encrypted_account_json) account_key = Account.decrypt(encrypted_account, password="password") account = Account.from_key(account_key) msg_hash = encode_defunct(text=message) signed_message = ...
The function processes a user's bet confirmation by validating their input, retrieving user data, generating a signed payload, and sending a POST request to a backend API to create a bet. It updates the user's balance and resets their betting state upon successful bet creation, or returns an error message otherwise.
def bet_confirmation(message): print( f"User interacted with, 'bet_confirmation'\nWith id: {message.from_user.id}\nfirstname: {message.from_user.first_name}\nfullname: {message.from_user.full_name}\ntext: {message.text}") confirm_response = message.text.lower() chat_response = "" if confirm_re...
def find_match_by_key(game, match_to_find): game = sport_key_to_game(game) requested_match = None matches = get_all_matches(game["key"]) for match in matches: if match["idTG"] == match_to_find: requested_match = match return game, requested_match def timestamp_converter(date_s...
The function handles user interaction to create a bet by extracting match details from the message, validating user state, and prompting for a wager amount. It checks if the user exists, ensures they complete previous steps, resolves sport/match keys, retrieves match data, and updates the user's progress in the databas...
def send_create_bet_interaction(message): print( f"User interacted with, 'send_create_bet_interaction'\nWith id: {message.from_user.id}\nfirstname: {message.from_user.first_name}\nfullname: {message.from_user.full_name}\ntext: {message.text}") user = users.find_one({"user_id": message.from_user.id}) ...
def get_all_bets(): url = f"http://{BACKEND_URL}/bets" response = requests.get(url) bets = response.json() return bets def team_bool_to_string(team_bool: bool): if team_bool: return "home" else: return "away" def find_match_by_string(game, match_to_find): game = sport_string...
The main task of the code is to retrieve and display open bets to a user, filtering by group context and bet status. It formats each bet with match details, the bet type, and an accept command, then sends the list via a bot reply.
def send_open_bets(message): print( f"User interacted with, 'send_open_bets'\nWith id: {message.from_user.id}\nfirstname: {message.from_user.first_name}\nfullname: {message.from_user.full_name}\ntext: {message.text}") bets = get_all_bets() response = "Here are the available games:\n\n" if bets ...
def gameButton(x, y, w, h, active, inactive, curstate, row, col): global turn_number, turn mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x <= mouse[0] <= x+w and y <= mouse[1] <= y+h: pygame.draw.rect(screen, active, (x, y, w, h)) if click[0] == 1 and turn == 0 and curstate[row][col] == '...
This code implements a game loop for a Tic-Tac-Toe game using Pygame. It alternates between player and computer turns, renders a 3x3 grid, handles quit events, checks win conditions, and updates the display. The loop runs until the game ends, then calls a game-end function.
def game_loop(): global end, turn, turn_number running = True curstate = [['', '', ''], ['', '', ''], ['', '', '']] while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if turn == 0 and end == 0: screen.fill((233, 237, 161)) cell_width = 120 cell_height =...
def is_royal(h): nh = convert_to_nums(h) if is_seq(h): if is_flush(h): nn = [int(x[1:]) for x in nh] if min(nn) == 10: return True else: return False def is_seq(h): ace = False r = h[:] h = [x[1:] for x in convert_to_nums(h)] h = [int(...
This function evaluates a poker hand to determine its type and rank, returning the hand's classification (e.g., "ROYAL FLUSH", "STRAIGHT", etc.), the hand itself, and a numerical rank from 1 to 10, where higher values indicate stronger hands. It checks for standard poker hand types in descending order of strength, usin...
def evaluate_hand(h): if is_royal(h): return "ROYAL FLUSH", h, 10 elif is_seq(h) and is_flush(h): return "STRAIGHT FLUSH", h, 9 elif is_four_of_a_kind(h): _, fourofakind = is_four_of_a_kind(h) return "FOUR OF A KIND", fourofakind, 8 elif is_full_house(h): return "...
def evaluate_hand(h): if is_royal(h): return "ROYAL FLUSH", h, 10 elif is_seq(h) and is_flush(h): return "STRAIGHT FLUSH", h, 9 elif is_four_of_a_kind(h): _, fourofakind = is_four_of_a_kind(h) return "FOUR OF A KIND", fourofakind, 8 elif is_full_house(h): return "...
The main task of the code is to determine the winner of a poker hand comparison by evaluating each hand's strength according to poker rules, handling cases like straight flushes, pairs, flushes, straights, full houses, and three of a kind. It compares hand ranks, identifies the highest card or combination, and returns ...
def compare_hands(hands): list_of_combs = [evaluate_hand(hand) for hand in hands.values()] if list_of_combs[0][0] == "STRAIGHT FLUSH": st_dict = { ps: is_seq(hand) for ps, hand in hands.items() } wp = [ pos for pos in st_dict if max( [max(v[1]) ...
def make_all_training_data(folder_path): """ This function collects all the labeled NER training data from a folder holding any number of ner_sheet folders from different journals. Parameters: folder_path (str, required): The path to a folder containing other folders. Those "other f...
This code initializes a Named Entity Recognition (NER) model by processing labeled data from specified directories, building vocabulary and label mappings using a pre-trained word2vec model, and preparing structured training data for machine learning. It constructs word, character, and label index mappings to convert t...
def __init__(self, path, w2v_model): """ Parameters: path (str, required): path to a directory of sub-directories containig labeled NER data for different journals in .xlsx files w2v_model (gensim w2v model, required): trained word2vec model containing ...
def recieve_message(self, connection, address= None) -> dict: """ recieve message on connection from another peer Args: connection (socket): socket connection address ((ip, port), optional): address of this connection host. Defaults to None. Returns: ...
The code handles a new peer connection by welcoming the client, receiving and processing their message, executing a response action, then closing the connection. It manages communication steps: reception, processing, response, and cleanup.
def handle_peer(self, connection, address): print(f"[NEW CONNECTION] {address} connected") message = self.recieve_message(connection, address) response = self.process_message(message) self.response_action(connection,address, response) connection.close()
def add_peer(self, peer: tuple)-> None: with self.peer_list_semaphore: try: print(f"[PEER] Add peer {peer} to list tracking") self.peer_list.add(peer) except Exception as e: print(e) def recieve_message(self, connection, address= None) -> d...
The main task of the code is to handle incoming connections from peers or trackers by receiving, processing, and responding to messages. It adds the peer to the list, receives the message, processes it, executes the appropriate action, closes the connection, and removes the peer from the list to manage interactions eff...
def handle_peer(self, connection, address): """ to handle request of another host(tracker or peer) recieve -> process message -> action """ print(f"[NEW CONNECTION] {address} connected") self.add_peer(peer = address) message = self.recieve_message(connection,addr...