dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def which_player_start() -> int: """ Decides which player starts :return: int """ return random.randint(1, 2) def create_board(size: int = DEFAULT_SIZE) -> list[list[str]]: """ Takes an integer and creates a board according to the size :return: ...
The main task of the code is to initialize and manage a game loop, handling player turns, board updates, and game-ending conditions. It starts by validating the board size, determining the first player, and creating the game board. The loop alternates turns, processes player moves, checks for win/tie states, and termin...
def start_game(): """ The core function that brings it all together. It starts by determining the first player and making sure the board size is valid. After that it enters a loop that ends either when a player wins or at a tie. :return: bool """ ...
def get_column_values_by_name(data, column_names: list[str], data_type: Optional[str] = FLOAT) -> np.array: """ Extracts column values by their given names :return: numpy.array """ header = data[0] col_indexes = get_column_indexes_by_names(hea...
The main task of the code is to generate a histogram visualizing the distribution of asteroids by their average diameter. It calculates the mean diameter for each asteroid, maps these values to asteroid names, and plots a histogram with 10 bins to show how many asteroids fall into each diameter range, labeling axes and...
def plt_hist_diameter(data) -> None: """ Plots a histogram of the amount of asteroids in each average diameter :return: None """ name_column = get_column_values_by_name( data=data, column_names=[NAME], data_type=INT) average_mean_column = get_mean_b...
def which_player_start() -> int: """ Decides which player starts :return: int """ return random.randint(1, 2) def generate_number() -> int: """ Generates a random number between 1000 to 9999 :return: int """ return random.randint(1000, ...
The main task of the code is to initiate and manage a number-guessing game loop where players take turns attempting to guess a secret number. It determines the starting player, generates the secret number, alternates turns, checks guesses via the play_turn function, and declares a winner when the secret number is corre...
def start_game(): """ Starts the game with a loop until a player wins :return: None """ turn = 1 first_player = which_player_start() secret = generate_number() print("Secret number =", secret) print("Player", first_player, "starts!") while True: playe...
def load_data(file_name: str) -> np.ndarray: """ Loads the data from a given file name, supports CSV :return: numpy.ndarray """ try: data = np.genfromtxt(fname=file_name, delimiter=",", dtype=str) except FileNotFoundError: print(f"{file_name=} not found") ra...
The main task of the code is to load asteroid data from "nasa.csv" and generate visualizations: histograms for diameter distribution, common orbit types, and hazard status (pie chart), along with a linear regression plot analyzing magnitude vs. motion. The function orchestrates data analysis and visualization to explor...
def main() -> None: """ The main function where all the magic happens :return: None """ data = load_data(file_name="nasa.csv") plt_hist_diameter(data=data) plt_hist_common_orbit(data=data) plt_pie_hazard(data=data) plt_linear_motion_magnitude(data=data)
def parse_arguments(): "Parse arguments from console" def open_rb(file): return open(file, "rb") p = argparse.ArgumentParser(description='Hyperparams') p.add_argument('vocab', type=open_rb, help='File of DE vocab and EN vocab as NamedFields. Suggested: "DE_EN_vocab.pkl"') ...
The main task of the code is to perform German-to-English translation using a trained sequence-to-sequence model with optional attention. It loads vocabulary mappings, initializes the model, encodes input sentences, and uses beam search decoding to generate translations. The code supports writing predictions to files, ...
def main(): "Entrance function for running from console" args = parse_arguments() device = "cuda" if args.cuda else "cpu" print("[*] Loading vocab: DE -> EN") DE_vocab = pickle.load(args.vocab) EN_vocab = pickle.load(args.vocab) print("[*] Loading models on %s" % device) mdl_weights =...
def get_cdrom_name(filename): cdrom_name = Path(filename).resolve().parents[3].name # This takes the whole filepath and returns just the name of the folder. folder_name = Path(filename).resolve().parents[2].name # The next few lines get rid of weird characters that might cause bugs if they're in the folder ...
The main task of the code is to process a list of TIFF blob files by reading their contents, extracting individual TIFF images using the `extract` function, and saving them into folders named according to the `cdrom_name` derived from each filename. This ensures organized storage of extracted TIFFs in directory structu...
def main(): for filename in list_of_TIFF_blobs: cdrom_name = get_cdrom_name(filename) # This should be identical to the folder name extract_metadata.py gets with open(filename, 'rb') as f: data = f.read() # This "data" variable is where the entire file's contents is going to be stored ...
def get_cdrom_name(filename): cdrom_name = Path(filename).resolve().parents[3].name # This takes the whole filepath and returns just the name of the folder. folder_name = Path(filename).resolve().parents[2].name # The next few lines get rid of weird characters that might cause bugs if they're in the folder ...
The main task of the code is to process metadata files by reading their contents, extracting structured records, and saving them as JSON files named after associated CD-ROMs. The function iterates through a list of filenames, retrieves each file's data, parses it into records, and stores the results in JSON format with...
def main(): for filename in list_of_metadata_files: cdrom_name = get_cdrom_name(filename) with open(filename, 'rb') as f: data = f.read() # This "data" variable is where the entire file's contents is going to be stored records = extract(data) save_json_file(records, cdro...
def _parse_query(self, table, *args, **kwargs): query = kwargs['query'] if 'query' in kwargs else {} field = kwargs['field'] if 'field' in kwargs else '*' orderby = kwargs['orderby'] if 'orderby' in kwargs else [('id',1)] limit = kwargs['limit'] if 'limit' in kwargs else None page = int(kwargs['page']) if 'pa...
This function retrieves paginated data from a database table based on query parameters, sorts results, and returns the data along with pagination metadata like total records, current page, page size, and last page number.
def getPage(self, table, input_query={},input_field='*', input_orderby=[('id',-1)], page=1, size=50,input_expect=["user"]): query = deepcopy(input_query) field = deepcopy(input_field) orderby = deepcopy(input_orderby) expect = deepcopy(input_expect) sql = self._parse_query(table=table, query=query,field=fi...
def getOne(self, table,input_query={},input_field='*',input_orderby=[('id',1)]): query = deepcopy(input_query) field = deepcopy(input_field) orderby = deepcopy(input_orderby) sql = self._parse_query(table=table, query=query, field=field, orderby=orderby, limit=1) result = self.query_one(sql) return result d...
The code updates or inserts a record in a database table. It checks if the input_key exists in input_data, retrieves existing data if present, compares fields, and applies updates only if values differ. If no existing data, it inserts the new record. It returns the updated or newly added data, decoding bytes to UTF-8 w...
def save(self, table,input_data,input_key='id'): result = {} new_id = 0 data = deepcopy(input_data) if input_key in data: new_id = data[input_key] oldData = self.getOne(table, {input_key:new_id},'*',[(input_key,1)]) if oldData: update_data = {} for key in data: if key not in [input_key]: ...
def compute_potentials(y, A, C, Q, Rs, mu_0, Lambda_0): # compute potentials hs = dict() Js = defaultdict(dict) for i in range(len(y)): J_ii = C.T @ inv(Rs[i, :, :]) @ C if i == 0: J_ii += inv(Lambda_0) if i != 0: J_ii += inv(Q) if i != (len(y) - ...
The function performs Gaussian Belief Propagation to compute posterior means and variances over time steps. It calculates potentials, executes forward and backward message passing, combines messages to derive posterior distributions, and finally inverts precision matrices (Js_hat) to obtain variances and compute means ...
def gaussian_belief_prop(y, A, C, Q, Rs, mu_0, Lambda_0): """ :param n: dimension of :param A: :param C: :param Q: :param R: :return: """ # correct hs, Js = compute_potentials(y=y, A=A, C=C, Q=Q, Rs=Rs, mu_0=mu_0, Lambda_0=Lambda_0) hs_forward, Js_forward = forward_pass(hs...
def generate_random_cipher(cipher): # random shuffle on the cipher to propose a new cipher did not yield good results and most importantly # it doesn't converge. Therefore a new method is needed. # cipher = list(cipher) # random.shuffle(cipher) # return ''.join(cipher) # cipher = ''.join(random...
This code implements a Metropolis-Hastings MCMC algorithm to decrypt text by iteratively generating random ciphers, evaluating their fitness via a score function, and accepting/rejecting new ciphers based on an exponential acceptance probability. It tracks the best cipher found and returns the final decrypted text alon...
def MCMC_cipher(iterations, text): current_cipher = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' best_state = '' trial_score = 0 for i in range(iterations): new_cipher = generate_random_cipher(current_cipher) current_cipher_score = cipher_score(text, current_cipher) next_cipher_score = cipher_sc...
def mouse_draw(self, Game, Color): mouse_pos = pygame.mouse.get_pos() x = mouse_pos[0] y = mouse_pos[1] while (x % 8) != 0: x -= 1 while (y % 8) != 0: y -= 1 Game.pen_pos_x = x Game.pen_pos_y = y self.toggle_draw = True if x...
This function detects and processes user input events in a Pygame application, handling mouse movements/drawing, mouse wheel color changes, keyboard controls for pen movement, erasing, color toggling, and mode switching. It updates the game state and continuously renders the drawing interface, returning False after pro...
def detect_movement(self, Game, Color): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEMOTION: if pygame.mouse.get_press...
def price_states(self, th: float, k=5) -> list: """ *States:* increase, decrease, soar, fall :param th: threshold for fraction relative to the spread size :param k: number of steps for price :return: list of states (iterations - 1) """ states = list() siz...
The function generates market state descriptions by combining price, volume, and liquidity metrics. It returns a list of strings, each concatenating the primary state from price, volume, and truncated liquidity data for corresponding time periods.
def market_states(self) -> list: """ *States:* dangerous, volatile, shocked, balanced :return: """ price = self.price_states(.7) volume = self.volume_states(.7) liquid = self.volatility_states(.3) states = list() for i in range(len(price)): ...
def get_data(self): sample = self.iterator.get_next() self.user, self.item_s= sample['user'], sample['item'] self.label_s = tf.cast(sample['label'], tf.float32) def init_weights(self): all_weights = dict() initializer = tf.truncated_normal_initializer(0.01) regularizer = ...
The main task of the code is to initialize a LightGCN-based recommendation model with multiple graph convolutional layers and self-supervised learning components. It initializes user-item embeddings using normalized adjacency matrices, combines embeddings from different layers with weighted aggregation, and prepares mo...
def __init__(self, args, iterator, norm_adj_mat1, norm_adj_mat2, num_users, num_items,is_training): self.args = args self.iterator = iterator self.norm_adj_mat1 = norm_adj_mat1 self.norm_adj_mat2 = norm_adj_mat2 self.num_users = num_users self.num_items = num_items ...
def load_all(rating_dir): files = glob.glob(f'{rating_dir}/*.json') return load_files(files) def get_lines(dir, doc, model, line): if model in {'PROMT_NMT', 'eTranslation'}: model = 'PROMT_NMT-eTranslation' with open(f'{dir}/{doc}/{model}.txt', 'r') as f: line_tgt = [x for x in f.readlin...
This function loads and processes a dataset by parsing arguments, mapping data, and structuring it into a DataFrame with user, document, model, and text fields. It optionally filters out bad lines and computes BLEU scores for text comparisons, returning the processed DataFrame.
def load_all_p2(clear_badlines=False, add_bleu=False): print('Loading data') parser = argparse.ArgumentParser() parser.add_argument('--rating-dir', default='../collected_data/p2/') parser.add_argument('--data-dir', default='./doc_data/') parser.add_argument('--line-mapping', default='./line_mapping....
def updateMonitored(self, item, val): assert item in self.item_to_indices insert_heap_index, delete_heap_index = self.item_to_indices[item] assert self.items[self.insert_count_heap[insert_heap_index]][0] == item assert self.items[self.delete_count_heap[delete_heap_index]][0] == item ...
This code updates a data structure maintaining a fixed-size collection of items by either updating existing entries or inserting/removing items based on their values. It manages monitored/unmonitored states, uses heaps for efficient priority-based replacement, and ensures size limits are respected by replacing least-us...
def update(self, x, val): self.total_items += val if x in self.item_to_indices: self.updateMonitored(x, val) else: if self.size < self.k: assert(val > 0) self.size += 1 self.insertUnmonitored(x, val) ...
def userExists(id, servID): #Returns True if user exists data = getServer(servID) if serverExists(servID) and str(id) in data["users"]: return True else: return False def serverExists(id): #Returns True if server exists data = getServer(id) if data is not None: return True ...
The function updates a user's data in a JSON file by replacing their entry with dictionary `d`, under the specified server ID. It first checks if the user exists; if not, it verifies server existence and initializes the user if valid. The updated data is written back to "serverdata.json", truncating excess content. Ret...
def updateUser(id, servID, d): #updates user data with dict d (use sparingly) if not userExists(id, servID): if not serverExists(servID): return False initUser(id, servID) with open("datastore/serverdata.json", "r+") as f: data = json.load(f) data[str(servID)]["users...
def userExists(id, servID): #Returns True if user exists data = getServer(servID) if serverExists(servID) and str(id) in data["users"]: return True else: return False def serverExists(id): #Returns True if server exists data = getServer(id) if data is not None: return True ...
The function `buyStock` facilitates purchasing stocks by verifying user existence, checking sufficient funds, updating stock holdings, deducting cash, logging transactions, and saving user data. It returns `True` on success or "Insufficient Funds" if the user lacks required cash.
def buyStock(id, servID, stock, amount, pps): #buys stock if not userExists(id, servID): if not serverExists(servID): return False initUser(id, servID) #with open("datastore/serverdata.json", "r+") as f: data = getUser(id, servID)#json.load(f) #userdata = data[str(servID)]["...
def userExists(id, servID): #Returns True if user exists data = getServer(servID) if serverExists(servID) and str(id) in data["users"]: return True else: return False def serverExists(id): #Returns True if server exists data = getServer(id) if data is not None: return True ...
The function `sellStock` processes a stock sale by verifying user/server existence, checking stock availability, updating holdings, adding proceeds to cash, recording the transaction, and returning success or error messages.
def sellStock(id, servID, stock, amount, pps): #sells stock if not userExists(id, servID): if not serverExists(servID): return False initUser(id, servID) data = getUser(id, servID)#json.load(f) userdata = data[str(servID)]["users"][str(id)] if stock not in data[str(servID)]...
def split1(m): r, q = [], [] absorbing = set() for row in range(len(m)): if sum(m[row]) == 0: absorbing.add(row) for row in range(len(m)): if row not in absorbing: total = float(sum(m[row])) temp_r, temp_q = [], [] for col in range(len(m[r...
The code processes input 'm' by splitting it into components 'r' and 'q', computes a function 'f' from 'q', calculates the dot product of 'f' and 'r', then converts and returns the first element of the result. The task involves transforming input data through splitting, function application, matrix operations, and conv...
def solution(m): if len(m) < 2: return [1,1] r, q = split1(m) f = find_f(q) fr = np.dot(f, r) return convert(fr[0])
def __make_website_folder(self): """ Makes a temp folder for downloaded html file and deployment preparations """ try: lock.acquire() next_available_dir_name = self.__find_available_dir_name() os.mkdir("./websites/in-progress/" + next_available_dir_nam...
The code's main task is to download files by enqueuing tasks, wait for their completion, create a temporary directory, save downloaded files, prepare for deployment, deploy the website, and return a Website object with the deployed URL. It manages task execution, file handling, and deployment流程 to generate a functional...
def make_website(self): """ Entry method to - download files, prepare files for deployment and finally deploy the files :returns: json representation of a website object with the deployed url :rtype: return """ taskIds = self.client.enqueue_tasks(self.selection) wait_tim...
def reset(self): """A full reset. Resets internal state completely (besides pRNG advancement), then sets initial values according to params.""" self.init_fields() self.expRemaining = self.params.exp_pool self.forcedAssignments = self.preplaced.copy() self.forceAssignedLoc...
The code performs reachability analysis on a game world by evaluating how different items (e.g., Glide, Stomp) affect the number of accessible locations. It iterates over items, simulates their presence/absence in the inventory, and calculates reachable areas by opening connections and counting accessible locations. Sc...
def do_reachability_analysis(self, params): self.params = params self.preplaced = {} self.playerID = 1 self.mapQueue = {} self.reservedLocations = [] self.doorQueue = {} self.random = random.Random() #items = ["WallJump", "Dash", "ChargeFlame", "DoubleJump...
def placeItems(self, depth=0): self.reset() keystoneCount = 0 mapstoneCount = 0 self.form_areas() if self.params.do_loc_analysis: self.params.locationAnalysisCopy = {} for location in self.params.locationAnalysis: self.params.locationAnal...
The main task of the code is to place items for multiple players in a cooperative or cloned game setup, handling retries if placements fail. It initializes shared data structures, processes item placements with error logging, and splits/assigns items to players' inventories or locations based on sync parameters, ensuri...
def placeItemsMulti(self, retries=5): placements = [] self.sharedMap = {} self.sharedCounts = Counter() self.split_locs = {} self.playerID = 1 placement = self.placeItems(0) if not placement: if retries > 0: retries -= 1 el...
def formatDates(line): # get potential valid lines dateRegex = r"\b(?:0?[1-9]|1[012]|January|Jan|Feburary|Feb|March|Mar|April|Apr|May|June|Jun|July|Jul|August|Aug|September|Sept|October|Oct|November|Nov|December|Dec)[-/, ]\s*(?:0?[1-9]|[12][0-9]|3[01])[-/,]\s*[\d{2}|\d{4}\b" datePattern = re.compi...
The main task of the code is to process and format a given text line by sequentially applying multiple functions that standardize date formats, file extensions, hyphens, capital letters with dots, and numeric values, ultimately returning the transformed line for further processing or analysis.
def readLines(line): wordList = [] # e.g: Jan 3, 2002 02/03/19 line = formatDates(line) # e.g: files.txt line = formatExtensions(line) # e.g: part-of-speech line = formatHyphens(line) # e.g: Ph.D line = formatCapDot(line) # e.g: 1,234,432.123 ==> 1...
def h(a: int) -> np.ndarray: '''Homographic matrix for one term of continued fraction''' return np.array([[a, 1], [1, 0]]) def euclid_matrix_(m: np.ndarray) -> Iterator[Tuple[int, np.ndarray]]: """ Symbolic Euclidean algorithm for a homographic function. :param m: The 2x2 matrix representing the fu...
The code transforms a continued fraction by iteratively applying matrix operations and Euclidean steps, exposing internal states for visualization. It processes each term of the input continued fraction, updating a homographic matrix and performing Euclidean divisions, yielding intermediate results (quotient, remainder...
def cf_transform_( cf: Iterator[int], m0: np.ndarray = np.identity(2, int), finite_term=True ) -> Iterator[Tuple[Optional[int], Optional[np.ndarray], np.ndarray, int, bool]]: """ Transform a continued fraction. Exposes the internal states of the algorithm for visualization. ...
def ABQueue( a: Iterator[int], b: Iterator[int] ) -> Callable[[np.ndarray], Tuple[Optional[int], Optional[str]]]: """ Return next term either from the first or the second continued fraction. The source is selected by the scoring function. :param a: The first continued fraction. :param b: The s...
The function `cf_arithmetic_` performs arithmetic operations on two continued fractions (`cf_a` and `cf_b`) using a 2x2x2 tensor `t0` to represent the operation. It iteratively processes terms from the continued fractions, applies them to the tensor, and yields results including quotients, remainders, and metadata (e.g...
def cf_arithmetic_(cf_a: Iterator[int], cf_b: Iterator[int], t0: np.ndarray, finite_term=True) -> Iterator: """ Perform arithmetic operation on two continued fraction. :param cf_a: The first continued fraction. :param cf_b: The second continued f...
def read_data(infiles, variable_name, dataset_name=None, input_units=None, output_units=None): """Read the input data file/s.""" if len(infiles) == 1: ds = xr.open_dataset(infiles[0]) else: ds = xr.open_mfdataset(infiles) if dataset_name: ds = fix_input_metadata(ds, dataset_nam...
The main task of the code is to perform extreme value analysis on climate/environmental datasets using Dask for parallel processing. It reads input data, subsets/chunks it, calculates extreme values based on specified statistical parameters, persists results for local clusters, and exports the analysis output to a NetC...
def main(args): """Run the program.""" if args.local_cluster: assert args.dask_dir, "Must provide --dask_dir for local cluster" dask.config.set(temporary_directory=args.dask_dir) cluster = LocalCluster(n_workers=args.nworkers) client = Client(cluster) print("Watch pr...
def _remove_tag_pair(text: Text, open_tag: str, close_tag: str) -> Text: """Remove all occurences of two tags, as an open and closing tag.""" # NOTE: There is probably a clever way to do this with recursion. initial_text = Text() final_text = Text() initial_text.append_text(_remove_tag(text, open_...
The main task of the code is to process and format text by removing specified tags and replacing them with defined styles or text. It iterates through various tag types, applying regex-based highlighting, tag removal, or substitution with styled replacements. Special handling includes formatting cross-references, date ...
def format_text(text: Text) -> Text: """Remove tags and format the replacement text accordingly.""" tag_pairs = [ "b", "it", "sc", "inf", "sup", "gloss", "parahw", "phrase", "qword", "wi", ] tag_solo = [ "bc", ...
def format_uns(uns: list[UsageNoteElement]) -> Text: """Format the usage note section.""" items_separator = Text("\n") items = [] for usage_note in uns: for element in usage_note: if element[0] == "text": # Always present items.append(Text(f"-> {eleme...
The code formats a DefiningText object by processing its items (text, uns, vis, etc.) with type-specific styling and transformations, appending results to a list, then joining them with newlines into a single Text object for display.
def format_dt(dt: DefiningText) -> Text: """Format the defining text section.""" # Set all to empty `Text`, which acts like `None` but we can use `+` item_separator = Text("\n") items = [] for item in dt: if item[0] == "text": dt_element_line = Text( item[1], sty...
def _format_sense(sense: Sense) -> DefinitionRow: sn = sense.get("sn") sen_vals = _format_sense_values(sn) dt = sense["dt"] defn = format_dt(dt) # for item in dt: # if item[0] == "text": # defn = Text(item[1]) row = DefinitionRow(sen_vals[0], sen_vals[1], sen_vals[2], defn...
The function `_format_sense_item` processes a `sense_item` (of varying types) to format its definition data and add it to a table. It checks the type of `sense_item` using its first element, delegates formatting to helper functions (`_format_sense`, `_format_pseq`, etc.), collects resulting `DefinitionRow` objects, and...
def _format_sense_item( sense_item: SenseArray | TruncatedSenseArray | BindingSubstitute | ParenthesizedSenseSequence, table: Table, ) -> None: definition_rows: list[DefinitionRow] = [] # Mypy seemed to be angry with a match...case setup for this if sense_item[0] == "sense": def...
def format_panel_title(self) -> Text: """Format the dictionary item title.""" dict_index_text = Text( f" {self.index + 1} ", style=CONFIG.style["display"]["item_index"] ) panel_title_spacing = Text(" ─── ", style=CONFIG.style["display"]["panel"]) headword_text = Text(...
This code renders a dictionary item in the terminal using the Rich library. It formats components like panel title, pronunciations, definitions, stems, date, and quotes, then combines them into a structured display. The function yields a styled rule and grouped renderables to visualize the item's data in a terminal int...
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: """Render the dictionary item to the terminal.""" # Panel title panel_title = self.format_panel_title() # Pronunciations pronunciations = self.format_pronunciations() de...
def ps_fontname(self): """Get the PS fontname""" # This Adobe restriction is classically ignored # if len(n) > 29: # print('Shortening too long PS fontname') # return n[:29] return self._make_ps_name(self.psname(), False) def fullname(self): """Get the SFN...
This code renames a FontForge font object by updating its metadata (fontname, fullname, familyname) and SFNT table entries. It addresses FontForge's limitations by manually managing SFNT names, removing default/undesired entries, and adding corrected English (US) entries for Family, SubFamily, Fullname, and PostScriptN...
def rename_font(self, font): """Rename the font to include all information we found (font is fontforge font object)""" font.fontname = self.ps_fontname() font.fullname = self.fullname() font.familyname = self.ps_familyname() # We have to work around several issues in fontforge: ...
def bASSL4CCR(x): model = torch.load("/home/fengbojing/fengbojing/CCRS/ASSL4CCR.pt") model.eval() tensorinput = torch.Tensor(x).unsqueeze(0) out = int(model("predict",x = tensorinput)) # out = int(torch.argmax(F.softmax(out,1), 1).detach().numpy()) m = ["AAA","AA", "A","BBB","BB","B","CCC","CC",...
The main task of the code is to handle POST requests by processing input data, applying one of three machine learning models (ASSL4CCR, CCRCNN, or CCRGNN) based on the specified model parameter, and returning the model's output. It normalizes input data using mean/std, executes the selected model, and returns results o...
def hello_world(): if request.method == 'POST': que = json.loads(request.get_data()) print(que) model = que['model'] tensorinput = (np.array(que['x'])-mean)/(std) asslout = bASSL4CCR(tensorinput) print(asslout) cnnout = bCCRCNN(tensorinput) print(cnnou...
def pieces(): pieces = [ (24, 16, 1), (24, 32, 1), (12, 16, 1), (24, 16, 2), (24, 32, 2), (12, 16, 2), (48, 32, 2), (32, 48, 2), (48, 48, 2), ] random.shuffle(pieces) return pieces def score(mask, remaining_board, placement, my_loc, neighbor_loc, piece): a = pow(volume(piece), 1/3) scr = 0 neig...
The code evaluates the placement of puzzle pieces on a grid, calculating a score based on individual piece placements and penalizing the use of diverse pieces. It iterates through each cell, selects appropriate pieces, updates the board state, and accumulates scores while tracking piece usage. The final score adjusts f...
def generate(wall, mask, remaining_board): placement_score = 0 placement = {} for r in range(wall.shape[0]): for c in range(wall.shape[1]): # skip any cells that have already been set if mask[r,c][0] != 0 and mask[r,c][1] != 0: continue piece_score, piece = None, None if r == 0 and c == 0: p...
def spin_cycle(pattern): for dirn in (D.NORTH, D.WEST, D.SOUTH, D.EAST): pattern = tilt(pattern, dirn) return pattern def to_string(pattern): return "\n".join("".join(l) for l in pattern) def load(pattern): load = 0 for i, l in enumerate(pattern): load_factor = len(pattern) - i ...
The code detects a repeating cycle in pattern transformations, calculates its start and length, then computes the state after 1,000,000,000 operations using cycle properties. It returns the pattern at the computed index. Your return
def day14_part2(filename): with open(filename) as f: pattern = [l.rstrip("\n") for l in f.readlines()] # remove newlines it = 0 cache = {} cycle_length = None while True: pattern = spin_cycle(pattern) if not cycle_length: pstr = to_string(pattern) ...
def readGif(filename: str, asNumpy: bool = True, split: bool = True) -> list: """ Takes a string-path of a gif-File and returns either the numpy array or the PIL Image array of all frames or half the frames. """ if not os.path.isfile(filename): raise IOError('File not found: ' + str(filename...
The function generates a GIF by either reading an existing image array or initializing a new game state. It updates the game iteratively to reach a specified frame count, then saves the GIF with a pause effect, using the defined speed parameter.
def createGif() -> None: """ Reads the -gif Parameter file to an image array, updates the last frame until -gifLength frames is reached, and saves the updated gif. """ gifSplit = os.path.splitext(gif) if (gifSplit[1].upper() == '.GIF'): images = readGif(gif, False) cells, cu...
def initRunningGame(imageFile: str, dark: int) -> tuple: """ Takes an imagePath as String and the 'dark' color-index value. Returns the cell array and the PIL Image as a tuple. """ image = Image.open(imageFile).convert("RGBA") return initConvertGame(image, dark) def updateGame(cells: np.ndar...
The main task of the code is to generate a transition GIF between two Game of Life states by creating frames for both the "from" and "to" configurations, blending them with interpolated transition frames, and concatenating all frames—including pauses and reversed sequences—into a single animated GIF with specified timi...
def createTransition() -> None: """ Reads the -from and -to parameters to images and gameoflife state arrays. updates the arrays and concatenates then. inserts transition frames between the images. saves the transition to a gif. """ gifSplit = os.path.splitext(fromTransition) images...
def createGif() -> None: """ Reads the -gif Parameter file to an image array, updates the last frame until -gifLength frames is reached, and saves the updated gif. """ gifSplit = os.path.splitext(gif) if (gifSplit[1].upper() == '.GIF'): images = readGif(gif, False) cells, cu...
The main task of the code is to process a sequence of target images by simulating a game (likely a cellular automaton) for each image. It checks if a GIF or transition is requested, otherwise iterates through target images, reads game states, updates game cycles, generates new images, and saves them. If the game reache...
def main(): if gif: createGif() return if fromTransition: createTransition() return for i, target_image in enumerate(target_images): if os.path.exists(target_image): try: tracelog("reading game state...") cells, cu...
def extract_text_from_pdf(pdf_path): text = "" with open(pdf_path, "rb") as pdf_file: pdf_reader = PyPDF2.PdfReader(pdf_file) for page_number in range(len(pdf_reader.pages)): page = pdf_reader.pages[page_number] text += page.extract_text() return te...
The code extracts text from a PDF, identifies entities (PERSON, ORG) and relationships (triples), filters unique entities, exports them to CSV files, generates a knowledge graph using NetworkX, and visualizes it with matplotlib. A Tkinter GUI lets users select entities to explore the graph interactively. The process in...
def main(): pdf_path = "NSD_EMPLOYERS_HANDBOOK.pdf" # File saved in same folder where code is text = extract_text_from_pdf(pdf_path) # function 1 entities, triples = extract_entities_and_triples(text) # function 2 unique_entities = set() # To store unique entities # Filter out entities with labe...
def io_setup(self): fetches = self.per_example_loss + self.per_example_logits + self.actions_idx + [self.loss_op] + [self.dummy] feeds = self.candidate_relation_sequence + self.candidate_entity_sequence + self.entity_sequence + \ [self.query_relations] + [self.range_arr] + [self.cum_disc...
The code trains a reinforcement learning model using episodes from a training environment, performing forward passes, reward modification based on rules, backpropagation with cumulative discounted rewards, and logging metrics like loss, rewards, and accuracy. It iterates through episodes, updates model parameters, and ...
def train(self, sess): fetches, feeds, feed_dict = self.io_setup() train_loss = 0.0 self.batch_counter = 0 for episode in self.train_environment.get_episodes(): self.batch_counter += 1 h = sess.partial_run_setup(fetches=fetches, feeds=feeds) feed_dict...
def prediction(num_speakers, net, wav_list, chunk_len_list): acti_lst = [] svec_lst = [] len_list = [] with torch.no_grad(): for wav, chunk_len in zip(wav_list, chunk_len_list): wav = wav.to('cuda') outputs = net.batch_estimate(torch.unsqueeze(wav, 0)) ys = o...
The main task of the code is to perform speaker diarization on an audio file using a pre-trained Transformer model. It loads model parameters, processes the audio into chunks, predicts speaker embeddings, clusters them, and generates an RTTM file for speaker turn segmentation.
def main(args): conf = parse_config_or_kwargs(args.config_path) num_speakers = conf['dataset']['num_speakers'] args.num_speakers = num_speakers # Prepare model model_parameter_dict = torch.load(args.model_init)['model'] model_all_n_speakers = model_parameter_dict["embed.weight"].shape[0] co...
def search_code(url): """ Search for code information: code_language, url_code and url """ response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") # content = response.text code_availability = soup.find( "div", {"id": "code-availability-content"}).text ...
The function formats code information by determining the programming language and URL, handling missing inputs, and generating code snippets with shields color codes. It checks if inputs are missing, searches for code details if needed, and constructs output by iterating over results or using defaults. The formatted co...
def format_code(code_language, url_code, url): """ Format code information: code_language, url_code and url """ if not url_code and not code_language: code_infors = search_code(url) if code_infors: if len(code_infors) == 1: co...
def parse_filed(lines): f = [] for line in lines: f.append([x for x in line.strip()]) return f def parse_agent(type, lines, n): start = str_to_pos(lines[n]) moves = lines[n+2] agent = Agent(type, start, moves) return agent, n+3 def game_loop(field, pacman, ghosts): matrix = ...
The code executes a game simulation by parsing a grid-based game configuration (e.g., Pac-Man), initializing game elements like the player and ghosts, and running a game loop to generate a sequence of moves. It ensures the move count stays below a specified maximum and returns the validated move list. The function proc...
def exec(code): global H, W lines = code.split('\n') n = int(lines[0]) H = W = n field_lines = lines[1:n+1] field = parse_filed(field_lines) n += 1 max_moves = int(lines[n+1]) pacman, n = parse_agent(PACMAN, lines, n) #n_ghosts = int(lines[n]) #n += 1 ghosts = [] #gho...
def parse_filed(lines): f = [] for line in lines: f.append([x for x in line.strip()]) return f def parse_agent(type, lines, n): start = str_to_pos(lines[n]) moves = lines[n+2] agent = Agent(type, start, moves) return agent, n+3 def game_loop(field, pacman, ghosts): agents = [pacm...
The code executes a game simulation by parsing a grid layout, player (PACMAN), and ghost agents from input lines. It initializes game parameters, processes entities, and runs a game loop to determine collected items and survival status, returning a formatted result. Your return
def exec(code): global H, W lines = code.split('\n') n = int(lines[0]) H = W = n field_lines = lines[1:n+1] field = parse_filed(field_lines) n += 1 pacman, n = parse_agent(PACMAN, lines, n) n_ghosts = int(lines[n]) n += 1 ghosts = [None for _ in range(n_ghosts)] for gid i...
def smallMatrix(matrixValues): i = 0 while i <= len(matrixValues) - 1: smallMatrixAux(matrixValues,i,[],matrixValues[i][1]) i += 1 def showFinalResultsDynamic(): print("\nMaximum amount of gold collected: ",finalGoldCollected[0]) print("Matrix coordinates leading to the result:") ...
The code's main task is to solve a matrix path optimization problem using either exhaustive search or dynamic programming based on the selected algorithm. It reads input data, applies the chosen algorithm to find optimal paths, calculates execution time, displays results, and visualizes optimal paths by coloring them i...
def main(): readInputFile() #Exhaustive Search if algorithmToUse[0] == 1: m = len(fileInformation[0]) - 1 #print(n,m) start = default_timer() if m == 1: smallMatrix(fileInformation) end = default_timer() executionTime = end - start ...
def create_if_block(elements): def_variable = False term = "if\n" for x in elements: term += ":: true ->\n" if 'sequence' in x[:x.find("[")]: atoms = [x.strip().replace('[','').replace(']','') for x in x[x.find("["):].split(':seq:')] for i, a in enumerate(atoms): ...
The `prefix_parser` function analyzes an input expression to parse it into a structured term and variables. It checks if the expression starts with "ifBlock" or "sequence" to determine its structure. If so, it splits the expression into components using specific delimiters and processes them with helper functions (`cre...
def prefix_parser(expression): operators = ['_=_', '_+_', '_._', '_<-_', '_!_', '_?_'] tags = ['@Channel', '@Recursive', '@Field'] term = "" temp = expression if 'ifBlock' in temp[:temp.find("[")]: summands = [x.strip().replace('(','').replace(')','') for x in temp[temp.find("[")+1:temp.rf...
def variable_typedef(): term = "typedef Packet {\n" for v in fields: term += "\tint {};\n".format(v) term += "}\n\n" term += "Packet {};\n\n".format(packet_var_name) return term def parse2proctype(recursive_variables): term = "" for k, i in recursive_variables.items(): ...
The main task of the code is to generate a concatenated string (`term`) by combining three components: variable type definitions, parsed process types from recursive variables, and channel definitions. It initializes an empty string, retrieves each component via helper functions, and returns their combined result as a ...
def parse2program(recursive_variables): term = "" variable_def = variable_typedef() proctypes = parse2proctype(recursive_variables) channels = channel_def() term = variable_def + channels + proctypes return term
def fill_shop(): for level in range(3): for pos in range(4): if (TABLE[level][pos] is None) and DECK[level]: TABLE[level][pos]=DECK[level].pop() def init_turtle(): turtle.screensize(1080,720) turtle.setup(1280,780,0,0) turtle.pensize(1) turtle.speed(10) turtle...
The code implements a card game where players collect tokens, buy cards, and aim to reach 15 prestige points. It initializes game settings, manages player turns, processes actions like token acquisition and card purchases, checks noble conditions, and determines the winner when a player reaches 15 points. The game uses...
def game_main(): global NOBLES print('\n---------- Game start! Setup: ----------') while k:=input('\nPlayer number ?= '): if k.isdigit() and 2<=(k:=int(k))<=4: break else: print('Wrong input !') for color in COLORS: TOKENS[color]=[0,0,4,5,7][k] for i in range(3): shuf...
def getBorderType(charIndex, line, lineIndex, content): if (charIndex == len(line)-1 and lineIndex == 0): return "northEast" if (charIndex == len(line)-1 and lineIndex == len(content)-1): return "southEast" if (charIndex == 0 and lineIndex == len(content)-1): return "southWest" i...
This function determines the adjacent numbers based on the position's border type by dispatching to specific directional helper functions. It first identifies the border type using `getBorderType`, then returns the corresponding adjacent numbers from functions like `getNorthEastAdjacentNumbers` or defaults to `getCentr...
def getAdjacentNumbers(charIndex, line, lineIndex, content): borderType = getBorderType(charIndex, line, lineIndex, content) if (borderType == "northEast"): return getNorthEastAdjacentNumbers(charIndex, line, lineIndex, content) if (borderType == "southEast"): return getSouthEastAdjacentNum...
def get_class_num(self) -> int: return 5 if 25 >= self.size else self.next_int(self.size**0.5) def get_range_num(self) -> int: return round(self.max_value-self.mim_value,DECIMAL_PLACES) def get_amplitude(self) -> int: return self.next_int(self.range_num/self.class_num) def init_table...
The code initializes a class to process input data by calculating statistical properties (size, max, min, class number, range, amplitude) and generating a table for data distribution analysis.
def __init__(self, data=[]): super().__init__() self.data = data if self.data != []: self.size = len(data) self.max_value = max(data) self.mim_value = min(data) self.class_num = self.get_class_num() self.r...
def get_separatrices(self, value_order, i=1) -> float: order = i * self.size / value_order for row in self.table: if order <= row.accumulated_frequency: row = self.table[row.id] break prev_accumulated_frequency = 0 i...
This method retrieves and prints specific statistical information based on the requested key(s). It maps keys to predefined metrics like class count, range, amplitude, size, median, quartiles, mode, variance, standard deviation, and kurtosis. If "ALL" is requested, it prints all metrics. Otherwise, it processes comma-s...
def table_info(self, requested_info) -> None: infos = {"K":f"Numero de class= {self.class_num}", "R":f"Range= {self.range_num}", "H":f"Amplitude= {self.amplitude}", "N":f"Tamanho= {self.size}", "M":f"Mediana= {self.get_separatrices(2)}", ...
def create_XY_prefix(log, mappingsize, prefixlen): X = [] Y = [] for i in range(0, len(log)): for k in range(1, len(log[i])): X.append(log[i][max(0, k-prefixlen):k]) #get the prefix of 'encoded' activities y = [0] *(mappingsize) y[int(log[i][k])-1] = 1 ...
The main task of the code is to train and evaluate a sequence prediction model (likely an LSTM-based architecture) on log data, using training, validation, and test datasets. It processes logs into input-output pairs, trains a model with specified hyperparameters (e.g., bidirectionality, layers, dropout), evaluates per...
def do_experiment(train_log, val_log, test_log, mapping, size_simulated_log, location_simulated_log, prefixlen, maximumlength, bidirec, n_layers, lstmsize, dropout, l1, l2, batch_size): if prefixlen == False: prefixlen = len(max(train_log,key=len))...
def calculate_carbon_emissions(self) -> dict: result_dict = {} power_energy_result_dict = self._calculate_power_energy_needed_data() result_dict["carbon_emissions_cpu"] = ( power_energy_result_dict["energy_needed_cpu"] * self.ga_data.constants.carbon_intensity_dict["KR"] ...
The function `carbon_calc_results` computes and returns a dictionary containing carbon emissions data, energy requirements, tree-month equivalents, and driving/flying distance metrics. It aggregates results from three methods: `calculate_carbon_emissions` (for emissions and energy), `calculate_tree_months` (for tree-mo...
def carbon_calc_results(self) -> dict: ce = self.calculate_carbon_emissions() tm = self.calculate_tree_months(ce["carbon_emissions"]) dk = self.calculate_driving_kilometers(ce["carbon_emissions"]) return { "carbon_emissions": ce["carbon_emissions"], "energy_neede...
def close_buy(self): self.balance+=(self.stoplossbuy-self.price_bought)*self.unit self.bought=False if self.verbose: print('Closed buy: price_bought =',self.price_bought,'price_sold =',self.cur_bid,'balance = ',self.balance) print(self.df1m.iloc[int(self.minute_index)+1:i...
The code simulates a trading strategy by processing tick data, evaluating bid-ask spreads, and executing buy/sell decisions based on a threshold. It tracks financial metrics like balance, transaction counts, and loss per trade, normalizing losses relative to average spreads. The simulation returns final balance, transa...
def RunSim(self, lookup, no_units_change, threshold): print('\nRunning simulation.\n') self.spread=0.00015 self.cum_spread = 0 self.steps = 0 self.verbose=False self.lookup = lookup self.no_units_change = no_units_change self.balance=0 self.balance...
def user_Entered_Hash(user_entry): # Seach database for hash databaseSearch = database.search_file(user_entry) # Hash is not in database if databaseSearch is None: # # call VT # # store into database print("\nHash not in database, calling VirusTotal and then storing in database") response = v...
The function processes user input by checking if the entry is a hash or URL. It returns corresponding detection templates (Hashdetection/URLdetection) if valid, or redirects to an invalid request page if neither is detected.
def receive_user_entry(): # Get the username, id, and score from front-end user_entry = request.form.get("uEntry") # Error message print statement: User's entry print("\n\nIn receive_user_entry function with entry:", user_entry) # Return True or False if user entered hash returnHashDetection = user_Enter...
def get_case_list(population: list): ''' Gets a list of Person objects and returns a list of infected Person objects from the given list a list of Person objects -> a list of Person objects ''' return [ person for person in population if is_infected(person) ] def get_new_case_list(case_list: list): # updat...
The function `spread_epid` simulates epidemic spread by updating case statistics. It processes a list of `Person` objects and a quarantine flag to calculate new infections, infectious individuals, quarantined cases, and recoveries. Using helper functions, it retrieves existing cases, computes new cases, updates statuse...
def spread_epid(population: list, quarantine: bool): ''' Gets a list of Person obejcts and boolean value representing the quarantine requirement By calling 'get_case_list', 'get_new_case_list', and 'update_person_status' functions, update the new cases and quarantine, and recoveries Returns the dictionary o...
def gen_feature_space(mentions, men_docs_nlp, tfidx, men_tfidx): feature_space = [] tokenizer = nlp.Defaults.create_tokenizer(nlp) for k, v in mentions.items(): nlpmen = men_docs_nlp[mentions[k]['doc_title']] span = nlpmen.char_span(mentions[k]['offset'], ment...
The main task of the code is to disambiguate entity mentions in a corpus using XGBoost. It builds inverted indexes from entity pages and SpaCy-processed documents, generates feature spaces from training data, trains an XGBoost model with pairwise ranking objective, evaluates on a development set, and returns predicted ...
def disambiguate_mentions(train_mentions, train_labels, dev_mentions, men_docs, parsed_entity_pages): # pos_set = set([v[3] for v in parsed_entity_pages]) # ent_set = set([v[4] for v in parsed_entity_pages]) # print(pos_set) # print(ent_set) print("Building inverted index.....
def create_action(self, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, signal="triggered"): """Create the actions for the interface. Parameters: text (str): the name of the action slot (func): the slot for the action shortcut (str): the shortcut ic...
The main task of the code is to initialize the QrcEditor class by setting up its user interface, including menus, toolbars, and actions for managing resource collections. It initializes a resource collection, configures options for compilation and compression, connects signals to slots for UI interactions, and prepares...
def __init__(self, file_name=None, parent=None): """Constructor for QrcEditor class. """ super(QrcEditor, self).__init__(parent) self.setAttribute(Qt.WA_DeleteOnClose) QrcEditor.instances.append(self) self.collection = qrcdata.ResourceCollection() if file_name ...
def is_open(file_name): """Check if an editor with file_name collection is open. If an editor with file_name collection is open the method shows the existing window, otherwise returns False """ for editor in QrcEditor.instances: if editor.collection.file_name() == file_name...
This method opens a dialog to select a `.qrc` file, validates its extension, and either loads it into the current collection (if clean/unnamed) or opens a new editor window. It updates the UI afterward.
def file_open(self): """Create the dialog to select and then open a qrc file. """ file_dir = os.path.dirname(self.collection.file_name())\ if self.collection.file_name() is not None else "." file_name, _ = QFileDialog.getOpenFileName(self, "QRC Editor - Load Resource Collect...
def display_boards(): print(board[0]+"|"+board[1]+"|"+board[2]) print(board[3]+"|"+board[4]+"|"+board[5]) print(board[6]+"|"+board[7]+"|"+board[8]) def handle_turn(player): global c print(player + "'s turn.") position=input("choose a position from 1-9:") valid = False while not valid: ...
This code defines a game loop for a turn-based game, displaying the initial board, handling player turns, checking game-over conditions, flipping players when applicable, and announcing the winner or a tie once the game concludes.
def Play_game(): global c #display initial board display_boards() while game_is_still_on: handle_turn(current_player) check_if_game_over() if c==True: flip_player() #game ended if winner=="X" or winner=="O": print(winner+"won") elif winner==None:...
def initialize(model, sample, params): """ Efficient Implementation of BlendedUniformNoiseAttack in Foolbox. """ if params['target_image'] is None: # Find a misclassified random noise. while True: random_noise = np.random.uniform(params['clip_min'], ...
Your return The code implements the LHS_BA algorithm to generate adversarial examples by perturbing input images to mislead model predictions. It iteratively approximates gradients, adjusts perturbations using step-size search (e.g., geometric progression), and enforces constraints (L2/LINF norms). The perturbed image,...
def lhs_ba(model, sample, clip_max=1, clip_min=0, constraint='l2', num_iterations=40, gamma=1.0, target_label=None, target_image=None, stepsize_search='geometric_progression', max_num_evals=1e4, init...
def _serial_setup_device(self) -> None: self._at_disable_echo_sim800c() def _tcp_connect(self, host: str, port: int, tls: bool = False) -> None: self._sim800c_tcp_connect(host, port, tls) def _tcp_send(self, data: bytes) -> None: self._sim800c_tcp_send(data) def _mqtt_process_connack(self, packe...
This function connects to an MQTT broker via a cellular chip using configurable parameters. It establishes a TCP connection, sends an MQTT CONNECT packet with client credentials, processes the broker's response, and schedules periodic keep-alive pings. Default values are pulled from a config dictionary, with TLS suppor...
def connect(self, client_id: str = config['MQTT_BROKER']['MQTTClientID'], host: str = config['MQTT_BROKER']['MQTTHost'], port: int = config['MQTT_BROKER']['MQTTPort'], username: str = config['MQTT_BROKER']['MQTTUsername'], password: str = config['MQTT_BROKER']['MQTTPassword'], keep_alive: ...
def generate_constraints(n_constraints, arity, previous_fresh, adaptive=True):# {{{ n_fresh = n_constraints + previous_fresh cs = [] for i in range(n_constraints): lhs = smatrix( arity, n_fresh, initialize=False ) rhs = smatrix( 1, n_fresh, initialize=False ) for j in range( arit...
The function `generate_gb` constructs a cryptographic garbling scheme with constraints on security, correctness, and invertibility. It generates garbled circuits (`gb`), basis change matrices (`bs`), and evaluation schemes (`ev`), while verifying properties like invertibility of basis matrices, security checks, correct...
def generate_gb(params, check_security=True, check_correct=True, check_inv=True):# {{{ input_bits = params['input_bits'] output_bits = params['output_bits'] h_arity = params['h_arity'] h_calls_gb = params['h_calls_gb'] h_calls_ev = params['h_calls_ev'] gate = params['gate'] siz...
def print_truth_table(gate, input_bits, output_bits):# {{{ print(gate_to_str(gate, input_bits, output_bits)) def generate_gb(params, check_security=True, check_correct=True, check_inv=True):# {{{ input_bits = params['input_bits'] output_bits = params['output_bits'] h_arity = params['h_arity'] h...
The code processes a cryptographic shortcut by generating a scheme with configurable security checks, then verifies or enumerates it using a solver based on command-line arguments. It prints truth tables, scheme details, and timing information when enabled, and outputs SAT/UNSAT results or models depending on verificat...
def run_shortcut(shortcut, args):# {{{ if args.read_gate or args.all_gates or (args.verbose and args.verbose >= 2): print_truth_table(shortcut['gate'], shortcut['input_bits'], shortcut['output_bits']) scheme = generate_gb( shortcut , check_security = not args.nosecure ...
def local_standard_time_meridian(zone): """ Calculate the local standard time meridian for a zone. Be careful with DST! Args: zone (str): the local timezone official name Returns: The longitude, in degrees, of the standard meridian for this zone. >>> print(loc...
The function `solar_to_local` converts a given solar time (datetime) to the corresponding local standard time for a specified timezone and longitude. It adjusts for three factors: (1) the longitudinal difference between the location and the local standard time meridian (LSTM), (2) the equation of time (EoT) correction,...
def solar_to_local(dt, zone, lon): """ Convert from solar time to local standard time. Args: dt (datetime): the local standard time zone (str): the local timezone official name lon (float): the longitude of the location, in decimal degrees Returns: The local standard ti...
def longitude_correction(zone, lon): """ Calculate the difference between mean solar time and local standard time based on location within time zone (longitude). Args: zone (str): the local timezone official name lon (float): the longitude of the location, in decimal degrees ...
The function `local_to_solar` converts a local standard time datetime to solar time by applying three corrections: longitude adjustment (difference between local mean time and solar time), the equation of time (accounting for Earth's orbital variations), and daylight saving time (DST) adjustments. It sums these correct...
def local_to_solar(dt, zone, lon): """ Convert a datetime object from local standard time to solar time. Args: dt (datetime): the local standard time zone (str): the local timezone official name lon (float): the longitude of the location, in decimal degrees Returns: The...
def mean_solar_time(jd, lon): """ Get the mean solar time. :param jd: Julian date :type jd: float :param lon: longitude of site, in degrees :type lon: float :return: mean solar time :rtype: float >>> mean_solar_time(jd_from_iso('2022-11-25 13:09:30'), -87.61) 8365.243361111112 ...
The function `solar_transit` calculates the **exact time of solar transit** (when the Sun reaches its highest point in the sky) for a given **Julian date** and **longitude**. It combines the **mean solar time** with corrections derived from the **solar mean anomaly** and **ecliptic longitude** to account for the Sun's ...
def solar_transit(jd, lon): """ Julian date of solar transit. :param jd: Julian date :type jd: float :param lon: longitude of site, in degrees :type lon: float :return: time of solar transit :rtype: float >>> iso_from_jd(solar_transit(jd_from_iso('2022-11-25 13:09:30'), -87.61)) ...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def put_seq_on_board(board, y, x, d_y, d_x, length, col): # Don't modify >:( for i in range(length): board[y][x] = col y += d_y x += d_x def print_board(board): # Don't modify >:(...
This test case verifies if the `detect_rows` function correctly identifies one open row of length 3 for color 'w' and no other configurations on an 8x8 board, by placing a horizontal sequence of 3 'w' pieces starting at (5,1) and checking the output against the expected result (1,0).
def test_detect_rows(): board = make_empty_board(8) x = 5; y = 1; d_x = 0; d_y = 1; length = 3; col = 'w' put_seq_on_board(board, y, x, d_y, d_x, length, "w") print_board(board) if detect_rows(board, col,length) == (1,0): print("TEST CASE for detect_rows PASSED") else: print("TES...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def put_seq_on_board(board, y, x, d_y, d_x, length, col): for i in range(length): board[y][x] = col y += d_y x += d_x def print_board(board): s = "*" for i in...
This test case checks if the detect_row function correctly identifies a row with one open end and no closed ends by placing a sequence of 'w' pieces on an 8x8 board and verifying the function's output.
def test_detect_row(): board = make_empty_board(8) x = 5; y = 1; d_x = 0; d_y = 1; length = 3 put_seq_on_board(board, y, x, d_y, d_x, length, "w") print_board(board) if detect_row(board, "w", 0,x,length,d_y,d_x) == (1,0): print("TEST CASE for detect_row PASSED") else: print("TEST...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def put_seq_on_board(board, y, x, d_y, d_x, length, col): # Don't modify >:( for i in range(length): board[y][x] = col y += d_y x += d_x def print_board(board): # Don't modify >:(...
The code's main task is to test functions for placing stones on a Gomoku board and analyzing game states. It initializes a board, places white and black stones at specific coordinates, and uses analysis to count open/semi-open rows of varying lengths for both colors, verifying expected outcomes after each move.
def some_tests(): board = make_empty_board(8) board[0][5] = "w" board[0][6] = "b" y = 5; x = 2; d_x = 0; d_y = 1; length = 3 put_seq_on_board(board, y, x, d_y, d_x, length, "w") print_board(board) analysis(board) # Expected output: # *0|1|2|3|4|5|6|7* # 0 | | | | |w...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def put_seq_on_board(board, y, x, d_y, d_x, length, col): for i in range(length): board[y][x] = col y += d_y x += d_x def print_board(board): s = "*" for i in...
This test case verifies the 'detect_rows' function by placing a horizontal sequence of 3 'w' pieces on an 8x8 board and checking if it correctly identifies 1 open row with no other patterns, ensuring the function accurately counts valid rows for a given player's piece.
def test_detect_rows(): board = make_empty_board(8) x = 5; y = 1; d_x = 0; d_y = 1; length = 3; col = 'w' put_seq_on_board(board, y, x, d_y, d_x, length, "w") print_board(board) if detect_rows(board, col,length) == (1,0): print("TEST CASE for detect_rows PASSED") else: print("TES...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def put_seq_on_board(board, y, x, d_y, d_x, length, col): for i in range(length): board[y][x] = col y += d_y x += d_x def print_board(board): s = "*" for i in...
The code tests if placing 5 black pieces in a horizontal line on an 8x8 board triggers a "Black won" win condition. It initializes a board, positions a white piece, then places 5 black pieces starting at (3,2) moving right. After printing the board, it checks if `is_win()` correctly identifies the black victory, output...
def testing_win_5_closed(): board = make_empty_board(8) board[2][2] = "w" y = 3; x = 2; d_x = 0; d_y = 1; length = 5 put_seq_on_board(board, y, x, d_y, d_x, length, "b") print_board(board) if is_win(board)=="Black won": print("PASSSSSSSSS") else: print("EPIC F...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def print_board(board): # Don't modify >:( s = "*" for i in range(len(board[0])-1): s += str(i%10) + "|" s += str((len(board[0])-1)%10) s += "*\n" for i in range(len(board)): ...
The code simulates a Gomoku game where the computer (playing as "b") and a human player (playing as "w") alternate turns. The computer uses the `search_max` function to determine its move, while the human inputs coordinates. After each move, the board is updated, and the game checks for a win or draw. The loop continue...
def play_gomoku(board_size): # Don't modify >:( board = make_empty_board(board_size) board_height = len(board) board_width = len(board[0]) while True: print_board(board) if is_empty(board): move_y = board_height // 2 move_x = board_width // 2 else: ...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def put_seq_on_board(board, y, x, d_y, d_x, length, col): # Don't modify >:( for i in range(length): board[y][x] = col y += d_y x += d_x def print_board(board): # Don't modify >:(...
This test case checks if the `search_max` function correctly identifies the optimal move on a 8x8 board. It places white and black sequences, then verifies if `search_max` returns `(4,6)` as the best move, indicating successful implementation of the AI's decision-making logic.
def test_search_max(): board = make_empty_board(8) x = 5; y = 0; d_x = 0; d_y = 1; length = 4; col = 'w' put_seq_on_board(board, y, x, d_y, d_x, length, col) x = 6; y = 0; d_x = 0; d_y = 1; length = 4; col = 'b' put_seq_on_board(board, y, x, d_y, d_x, length, col) print_board(board) if searc...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def put_seq_on_board(board, y, x, d_y, d_x, length, col): for i in range(length): board[y][x] = col y += d_y x += d_x def print_board(board): s = "*" for i in...
The code tests a board game's analysis function by placing pieces on an 8x8 board and verifying open/semi-open sequences. It initializes the board, adds white and black stones in specific positions, prints the board state, and runs analysis to count open/semi-open rows of various lengths for both colors. The expected o...
def some_tests(): board = make_empty_board(8) board[0][5] = "w" board[0][6] = "b" y = 5; x = 2; d_x = 0; d_y = 1; length = 3 put_seq_on_board(board, y, x, d_y, d_x, length, "w") print_board(board) analysis(board) # Expected output: # *0|1|2|3|4|5|6|7* # 0 | | | ...
def test_is_empty(): board = make_empty_board(8) if is_empty(board): print("TEST CASE for is_empty PASSED") else: print("TEST CASE for is_empty FAILED") def test_is_bounded(): board = make_empty_board(8) x = 5; y = 1; d_x = 0; d_y = 1; length = 3 put_seq_on_board(board, y, x, d_...
This code executes a series of unit tests for core functions, including checking emptiness, boundedness, row detection, and maximum value search, to validate their correctness and functionality.
def easy_testset_for_main_functions(): test_is_empty() test_is_bounded() test_detect_row() test_detect_rows() test_search_max()
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def print_board(board): s = "*" for i in range(len(board[0])-1): s += str(i%10) + "|" s += str((len(board[0])-1)%10) s += "*\n" for i in range(len(board)): s += ...
The main task of the code is to implement a Gomoku game where the computer and user alternate placing pieces ("b" for computer, "w" for user) on a board. The computer uses a search algorithm to determine its moves, while the user inputs their coordinates. After each move, the board is updated, analyzed, and checked for...
def play_gomoku(board_size): board = make_empty_board(board_size) board_height = len(board) board_width = len(board[0]) while True: print_board(board) if is_empty(board): move_y = board_height // 2 move_x = board_width // 2 else: move_y, m...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def put_seq_on_board(board, y, x, d_y, d_x, length, col): for i in range(length): board[y][x] = col y += d_y x += d_x def print_board(board): s = "*" for i in...
This test case verifies the functionality of the `search_max` function by placing white and black sequences on an 8x8 board, then checking if `search_max` correctly identifies the position (4,6) as the maximum. The test passes if the function returns the expected coordinate, ensuring it operates as intended in a game-l...
def test_search_max(): board = make_empty_board(8) x = 5; y = 0; d_x = 0; d_y = 1; length = 4; col = 'w' put_seq_on_board(board, y, x, d_y, d_x, length, col) x = 6; y = 0; d_x = 0; d_y = 1; length = 4; col = 'b' put_seq_on_board(board, y, x, d_y, d_x, length, col) print_board(board) if searc...
def get_data_from_jhu_git(value_name: str) -> pd.DataFrame: base_url = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/' path_dict = {'cases': 'time_series_covid19_confirmed_global.csv', 'deaths': 'time_series_covid19_deaths_global....
The function retrieves and processes COVID-19 data from JHU's CSSE GitHub repository, cleaning columns, renaming fields, applying a rolling window aggregation, and filtering entries based on minimum case thresholds to produce a structured DataFrame for analysis.
def get_csse_data(value_name: str, min_cases: int, rolling_window: int) -> pd.DataFrame: df = get_data_from_jhu_git(value_name) df = df.drop(['Lat', 'Long', 'Province/State'], axis=1) df = df.rename(columns={'Country/Region': 'country', '3/21/202': '3/21/20'}) df_tidy = tidy_...
def validate_emails(self, participants): """ Validates emails for `participants`. """ for participant in participants: email = participant["email"] full_name = self.full_name(participant) if self.Email.validate_email(""): msg = f"{email...
The code's main task is to generate Secret Santa gift-pairing assignments by validating participant data, calculating possible permutations, creating pairs, and sending email notifications. It prompts user confirmation before sending emails and includes debug mode handling for testing.
def run(self): year = dt.datetime.now().year title = f"[prim]Secret Santa Pair Picker[/] | [sec]{year}[/]\n" self.console.print(title) # validationms self.validate_emails(self.participants) self.validate_last_giftees(self.participants) permutations = self.get_pe...
def final(matrix): global before_overlap overlap_list = [] before_overlap = [i for i in matrix if matrix.count(i) == 1] # before_overlap --> matrix with all the inputs without overlapping # overlap_list --> inputs list to be overlapped for j in before_overlap: overlap_list.extend...
The code's main task is to merge intervals in a matrix based on user input. It prompts the user to register new intervals, then merges overlapping or adjacent intervals by extending lists and sorting them. The process continues until the user declines, at which point the final merged list is printed. However, the code ...
def merge_lists(list0, matrix, new_list): print(final(matrix)) question = '' while not ('no' or 'yes') in question.lower(): question = input('Do you want to register a new interval? Answer yes or no: ') if 'no' in question.lower(): print(f'END OF PROGRAM, your final list is: {(...
def displayBoard(board): """Display the given board on the screen.""" labels = [board[0][0], board[1][0], board[2][0], board[3][0], board[4][0], board[0][1], board[1][1], board[2][1], board[3][1], board[4][1], board[0][2], board[1][2], board[2][2], board[3][2], board[4][2], ...
The function `automatic` automates a game by repeatedly displaying a board, making random moves, and checking if the board matches a new (solved) state. If the board matches the new state, it declares a win and exits. After 40 moves, it prompts the user to continue or stop, exiting if the board is solved or based on us...
def automatic(board): for i in range(40): displayBoard(board) makeRandomMove(board) if board == getNewBoard(): displayBoard(board) print('You won!') sys.exit() stoppingcondition = input("Do you want to continue?\n") if board == getNewBoard(): ...
def evaluate(self): """Calls evaluation functions Returns: int: Evaluation of position """ if self.board.get_counter() > 10: return self.feature_evaluation() else: return self.static_evaluation() def naive_move_sort(self, moves : list) -> list...
The code implements the **minimax algorithm with alpha-beta pruning** to search a game tree and determine the optimal move for a player (AI or human). It evaluates terminal game states (win/draw), applies depth-based scoring, and recursively explores valid moves while pruning suboptimal branches. The function alternate...
def minimax(self, depth : int, alpha : int, beta : int, is_max : bool): """Minimax search of game tree Args: depth (int): Current search depth alpha (int): Pruning upper bound beta (int): Pruning lower bound is_max (bool): Maximiser or minimiser turn ...
def create_window(self): """Creates the main window used by the application """ self.window = pygame.display.set_mode((600,400)) pygame.display.set_caption("Connect 4 Application") self.window.fill(self.base_theme) pygame.display.flip() def home_menu_window_setup(self): ...
The code displays a home menu interface, processes user mouse clicks on buttons, and returns an integer representing the selected application component. It maintains an active button loop, checks for clicks, handles menu-specific actions, and exits with the user's choice.
def home_menu_window(self) -> int: """Runs the home menu window and gets the user's chocie Returns: int: Code representing application component choice """ self.create_window() self.home_menu_window_setup() ##Main loop for home window while True: ...
def update_active_buttons(self): """Update all active buttons in the window """ for button in self.active_buttons: button.update(self.window, self.base_theme) def menu_options(self): """Adds the menu option buttons once menu button clicked """ ##Text button la...
The `game_loop` function handles user interactions in a game, processing mouse clicks on active buttons. It updates the game state, checks for move inputs (0-6), triggers menu options, or returns "home" based on button actions. It runs the game loop until a terminal state is reached, returning codes to dictate the appl...
def game_loop(self, board : Board, game_surface : pygame.Surface): """Runs the game while checking all button clicks Codes being returned: home - Return to home window menu options - Run selected component None - Run game loop for next turn Args: board (Board...
def create_window(self): """Creates the main window used by the application """ self.window = pygame.display.set_mode((600,400)) pygame.display.set_caption("Connect 4 Application") self.window.fill(self.base_theme) pygame.display.flip() def game_window_setup(self) -> pyga...
This code manages a game window for player vs human/AI gameplay. It initializes the game interface, alternates turns, handles human input via game_loop(), and executes AI moves using Minimax. The loop continues until a terminal state is reached, returning the next application code.
def game_window(self, board : Board): """Runs the game window, allowing a user to play a game against a human or ai Needs players to be set before running Args: board (Board): Current board instance Returns: str: Code for next part of the application to use ...
def makeRows(self): # This function parses through ROWS and returns the names of the rows rows = [] for line in self.ROWS: if self.findOperation(line)=="has-row": rows.append(self.getArguments(line)[1]) return rows def findOperation(self, line): # This...
The main task of the code is to parse the `SLOTS` data by mapping each slot to its corresponding row. It initializes a dictionary of rows, iterates through `SLOTS` to identify "has-slot" operations, extracts row-slot pairs, and appends slots to their respective rows. Finally, it returns the populated dictionary mapping...
def getSlots(self): # This function parses through SLOTS and maps each slot to the corresponding row rows = dict([[row, []] for row in self.makeRows()]) for line in self.SLOTS: if self.findOperation(line)=="has-slot": row, slot = self.getArguments(line) ...
def getSlots(self): # This function parses through SLOTS and maps each slot to the corresponding row rows = dict([[row, []] for row in self.makeRows()]) for line in self.SLOTS: if self.findOperation(line)=="has-slot": row, slot = self.getArguments(line) ...
This function generates a table by mapping time slots to columns based on their start and end times. It iterates over each row, extracts slot data, and assigns each slot to columns within its time range. The result is a list of dictionaries, where each dictionary represents a row with columns populated by corresponding...
def makeTable(self): # This function returns a list of dicts containing the data for each column row-wise slots = self.getSlots() time = self.getTime() table = [] for row in slots.keys(): data = self.getColumns() data["Row"]=row for i in range(...
def getCommands(self, file_name): # This functions takes in the file and returns a list containg every line of the file commands = [] with open(file_name) as file: for line in file: commands.append(line.strip()) return commands def getOperation(self): ...
The code initializes a class by reading a file, extracting commands, parsing operation parameters (TITLE, ROWS, SLOTS, TIME), constructing a table from data, converting it into a pandas DataFrame, and storing relevant attributes like the name from the TITLE. The main task is to load and structure data from a file for f...
def __init__(self, file_name): self.commands = self.getCommands(file_name) self.TITLE, self.ROWS, self.SLOTS, self.TIME = self.getOperation() self.contents = self.makeTable() self.table = pandas.DataFrame(self.contents) self.name = self.getArguments(self.TITLE[0])[0]
def print(*args, **kwargs): force = kwargs.pop('force', False) if is_master or force: builtin_print(*args, **kwargs) def setup_for_distributed(is_master: int) -> None: # This function disables to console-printing when not in master process (i.e. rank=0) import builtins as __builtin__...
The function `init_distributed_mode` initializes distributed training by parsing environment variables for multi-GPU settings (e.g., `RANK`, `WORLD_SIZE`, `MASTER_ADDR`). If these variables exist, it configures PyTorch's distributed backend, sets the local GPU device, prints launch details, and initializes the process ...
def init_distributed_mode(args: Dict) -> None: # If already distributed mode is activated if args.distributed: return try: args.rank = int(os.environ["RANK"]) args.local_rank = int(os.environ['LOCAL_RANK']) args.world_size = int(os.environ['WORLD_SIZE']) args.group_rank = i...
def insert(array, k, size): array[size] = k bubbleup(array, size) def minmaxheapproperty(array, size): for i, k in enumerate(array[:size]): if level(i) % 2 == 0: # min level # check children to be larger for j in range(2 * i + 1, min(2 * i + 3, size)): if array[j] < k: print(array, j, i, array[j], ...
The code tests the correctness of a min-max heap implementation by inserting random elements, verifying the heap property after each insertion, and repeatedly removing min/max elements while ensuring the heap maintains valid properties and correctly reflects the expected min/max values.
def test(n): from random import randint a = [-1] * n l = [] size = 0 for _ in range(n): x = randint(0, 5 * n) insert(a, x, size) size += 1 l.append(x) assert minmaxheapproperty(a, size) assert size == len(l) print(a) while size > 0: assert min(l) == peekmin(a, size) assert max(l) == peekmax(a, s...
def _calculate_distribution(self): try: dataframe = pd.read_csv(self.file.path, sep="\t") except pd.errors.EmptyDataError: raise EmptyFileException() except (UnicodeDecodeError, ValueError): raise IncorrectFileException() if self.IDENTIFIER_COLUMN not ...
The main task of the code is to analyze data for compliance with Benford's Law by calculating the distribution of first-digit frequencies, generating a visual graph, performing a chi-square test to assess statistical significance, and saving the results. It processes data to determine if the distribution matches expect...
def calculate_benford_distribution(self): first_number_percentages = self._calculate_distribution() self._set_statistics(first_number_percentages) graph = self._generate_graph(first_number_percentages) self.graph.save(f"{self.id}_graph.png", ImageFile(graph)) self.distribution_ma...
def get_exp_type(self): return os.path.basename(os.path.abspath(self.get_path("../.."))) def get_path(self, path, needfile = False): jpath = os.path.join(self.exp_path, path) if needfile and not os.path.isfile(jpath): raise Exception(f"file {jpath} doesn't exist") return jpath def get_prog_path(self, path, n...
The function validates the existence and structure of required files for an experiment. It checks if "code.hash", "input1.json" (and optionally "input2.json" for "exps2" type), and "code.asm" exist, ensuring JSON files are valid dictionaries. Returns True only if all files are present and correctly formatted.
def is_valid_experiment(self): filenames = ["code.hash", "input1.json"] + (["input2.json"] if self.get_exp_type() == "exps2" else []) for filename in filenames: if not os.path.isfile(self.get_path(filename)): return False if filename.endswith(".json"): with open(self.get_path(filename, True), "r") as ...
def get_exp_gens(self): prefix = "gen." gens = [] for f in os.listdir(self.get_path(".")): if os.path.isfile(self.get_path(f)) and f.startswith(prefix): gens.append(f) return gens def get_run_ids(self): prefix = "run." ids = [] for d in os.listdir(self.get_path(".")): if os.path.isdir(self.get_p...
The code prints detailed experimental information including generation details, run IDs, program configurations, assembly code, and input files. It checks the experiment type ("exps1" or "exps2"), retrieves data like program ID and code, formats input files using `gen_readable`, and structures output with separators fo...
def print(self): print("generation info:") print("-"*40) for g in self.get_exp_gens(): print(f"- {g}") print() print("runs:") print("-"*40) for g in self.get_run_ids(): print(f"- {g}") print() print("configuration:") print("-"*40) assert self.get_exp_type() == "exps2" or self.get_exp_type(...
def get_embeddings(FASTA_PATH, EMB_PATH, EMB_LAYER): global headers headers = [] ys = [] Xs = [] for header, _seq in esm.data.read_fasta(FASTA_PATH): headers.append(header) fn = f'{EMB_PATH}/{header}.pt' embs = torch.load(fn) Xs.append(embs['mean_representations'][EMB...
The main task of the code is to predict KSB (Kozak-like sequence binding) elements in a genome using a pre-trained PyTorch classifier. It loads embeddings from a FASTA file, applies the model to classify sequences, filters predicted positive labels (class 0), and passes these results to a downstream function for furthe...
def ksb_predict(fasta_file, embeddings, output_path, prefix): ksb = torch.load('./model/KSb_binary_Classifier.pt', map_location=device) test_X = get_embeddings(fasta_file, embeddings, 36) test_X = torch.Tensor(test_X).to(device) test_y=np.empty(len(headers)) test_y[:]=-1 # Make predictions on ...
def parseJSON(file): ret_str = "" for dictionary in file["body_text"]: ret_str = ret_str + " " + dictionary["text"] return ret_str def tokenizeText(file, sentencesFound): entry_start = 0 tokens = [] possible_date = False found_num = False space_count = 0 prev_char = "" fi...
The code processes text files by converting them into JSON, tokenizing the content, removing stopwords, and applying stemming. It iterates through a file list, handling every fourth file, and stores processed tokens in a documents dictionary with incremental IDs. Errors during JSON conversion are logged, and the functi...
def processFolder(file_list, passStartId, documents): idProcessed = passStartId for i,x in enumerate(file_list): if(i %4 == 0): file = open(x, "r") try: data = json.load(file) current_file = parseJSON(data) current_file = current_fi...
def move_nodes_fast(graph, partition): """Move nodes to its neighbors communities to maximize the modularity""" # randomize the order of the visited nodes Q = list(graph.nodes()) random.shuffle(Q) # initialize best modularity and partition best_modularity = nxq.modularity(graph, partition, wei...
The code implements the Leiden algorithm for community detection in a graph. It iteratively refines partitions using node movement, aggregates the graph based on refined communities, and merges partitions across iterations until a single node or stable community structure is achieved, returning the final community part...
def leiden_algorithm(graph): prev_best_community, prev_best_mod = None, None First = True partition = singleton_partition(graph) while 1: # Phase 1 init_partition = singleton_partition(graph) best_partition, best_mod = move_nodes_fast(graph, init_partition) # Phase 2...
def initializeCTAStatistics(self): self.statsbycta = {} print("Loading geodata list of all CTAs") with open(settings.OUTPUT_CTATOPOJSON, 'r') as jsonfh: places = json.load(jsonfh) for place in places['objects']['ctazones']['geometries']: zoneid = place['p...
The main task of the code is to process and aggregate demographic, county, city, and incidence data from standardized CSV files, generate a master shapefile, and package all processed data into downloadable ZIP files (a master ZIP and individual ZIPs) for public distribution via a website. The code ensures data consist...
def run(self): print("DownloadableZipsMaker") # self.statsbycta is our master stats storage from the CSVs, an assoc keying CTZ Zone ID => StatsDict # this is our source of truth for what zones should exist # all zones listed therein should have a presence in all CSV files, and all rows ...
def create_connection_string(credentials: dict): # print(credentials) if not credentials: return None else: # target_name = get_target() # credentials = get_outputs() con_str = [f"DRIVER={{{credentials.get('driver')}}}"] server = credentials.get('server') if ...
The function executes an SQL query on a specified database target, retrieves results, and returns them as a list of dictionaries with column names as keys. It uses credentials from a profile to create a connection, executes the query, and converts each row into a dictionary for structured output.
def run_sql_on_target(sql: str, target: str = None): con_str = create_connection_string(get_credentials_from_profile(target=target)) with open_db(connection_str=con_str, autocommit=True) as cursor: results = cursor.execute(sql).fetchall() query_results = [dict(zip([column[0] for column in cursor...
def get_wall_mask(bgr=np.zeros((1, 1, 3), dtype="uint8")): kernel_3 = np.ones((3, 3), np.uint8) kernel_5c = np.array( [ [0, 1, 1, 1, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 0], ], dtype=np.uint8, ...
The function generates and combines masks for different unit plan elements (walls, entrances, LDK, bedrooms, balconies, bathrooms) from an input image using OpenCV operations. It processes color spaces, applies dilation/erosion, identifies indoor/outdoor regions, and refines masks via connected components analysis and ...
def get_unit_mask(bgr=np.zeros((1, 1, 3), dtype="uint8")): """Returns unit plan masks of the unit plan, as a dictionary of opencv masks and also a single combined mask, including masks for walls, entrances, LDK, bedrooms, balconies, and bathrooms.""" kernel_3 = np.ones((3, 3), np.uint8) kernel_5c ...