dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_socket(ip, port, listen=False):
"""Create a TCP/IP socket at the specified port, and do the setup
necessary to turn it into a connecting or receiving socket. Do
not actually send or receive data here!
PARAMETERS
==========
ip: A string representing the IP address to connect/bind t... | The server_loop function establishes a server to handle client connections for user registration and key exchange. It listens on a specified IP and port, processes client requests (register 'r', generate shared secret 'p', or quit 'q'), and maintains a database of registered users. For 'r', it registers clients using s... | def server_loop(IP, port, N, g, k, verbose=False):
database = dict() # for tracking registered users
sock = create_socket(IP, port, listen=True)
if sock is None:
if verbose:
print(f"Server: Could not create socket, exiting.", flush=True)
return
if verbose:
print(f"Server: Beginning conn... |
def determine_password( input ):
"""For the given encrypted input, attempt to brute-force the password used
to encrypt it. This routine makes no attempt to check for the codeword,
but it will reject a tag that doesn't match.
PARAMETERS
==========
input: A bytes object containing the encrypted i... | The function decrypts the input bytes, checks if the decrypted text contains the specified codeword, replaces a target string with a substitute if the codeword is present, re-encrypts the modified text with the same password and a new IV, and returns the encrypted result. If decryption fails or the codeword is absent, ... | def attempt_substitute( input, codeword, target, substitute ):
"""Brute-force the password for input, and if successfully decrypted check that it
contains "codeword". If it does, swap "target" for "substitute", re-encrypt
with the same password, and return the encrypted version.
PARAMETERS
=======... |
def CreateDrive(self):
"""Create a drive client instance.
The service can only ever retrieve the credentials from the session.
"""
# For the service, the session holds the credentials
creds = self.GetSessionCredentials()
if creds:
# If the session contains credentials, use them to create ... | The code handles HTTP POST requests to create a new Google Drive file by deserializing JSON data, using the Drive API to insert a file with specified metadata and content. It retrieves an access token from storage, uploads the file via MediaInMemoryUpload, and returns the file ID upon success. If the access token is in... | def post(self):
"""Called when HTTP POST requests are received by the web application.
The POST body is JSON which is deserialized and used as values to create a
new file in Drive. The authorization access token for this action is
retreived from the data store.
"""
# Create a Drive service
... |
def CreateDrive(self):
"""Create a drive client instance.
The service can only ever retrieve the credentials from the session.
"""
# For the service, the session holds the credentials
creds = self.GetSessionCredentials()
if creds:
# If the session contains credentials, use them to create ... | The code handles HTTP GET requests by fetching file metadata and content from Google Drive using a file_id query parameter. It retrieves the file via the Drive API, downloads content if a download URL exists, and returns the data as JSON. If no URL is present, content is set to empty. It also handles access token error... | def get(self):
"""Called when HTTP GET requests are received by the web application.
Use the query parameter file_id to fetch the required file's metadata then
content and return it as a JSON object.
Since DrEdit deals with text files, it is safe to dump the content directly
into JSON, but this is... |
def CreateDrive(self):
"""Create a drive client instance.
The service can only ever retrieve the credentials from the session.
"""
# For the service, the session holds the credentials
creds = self.GetSessionCredentials()
if creds:
# If the session contains credentials, use them to create ... | This code handles HTTP PUT requests to update a Google Drive file. It deserializes JSON request data, updates file metadata (title, description, mimeType) via a two-step process, and uploads the file content using MediaInMemoryUpload. It retrieves an access token from the data store, redirects to an auth page if the to... | def put(self):
"""Called when HTTP PUT requests are received by the web application.
The PUT body is JSON which is deserialized and used as values to update
a file in Drive. The authorization access token for this action is
retreived from the data store.
"""
# Create a Drive service
service... |
def get_select_query_part(self) -> Select[Any]:
return select(self.model)
def get_filter_query_part(self, filter_query_str: str) -> List[Any]:
conditions = self._get_filter_query(filter_query_str)
if conditions == []:
return conditions
return [or_(*conditions)]
def get_group_... | The function constructs a SQL query by combining select, filter, group by, and order by clauses. It assembles these components based on input parameters, applying filters, grouping if specified, and sorting results when an order-by string is provided. | def get_complete_query(self, filter_query_str: str, order_by_query_str: str | None = None) -> Select[Any]:
select_query_part = self.get_select_query_part()
filter_query_part = self.get_filter_query_part(filter_query_str)
complete_query = select_query_part.filter(*filter_query_part)
group... |
def getQ(s):
x = encodeInput(s)
y = nn2.getQ(model,x)
return y
def isValidMove(s,a):
if(getNextState(s,a)!=s): return True
else: return False
def getRandomAction(s):
valid_actions = []
for a in actionList:
if(isValidMove(s,a)):
valid_actions.append(a)
if len(valid_actions)==0: return -1
return random.choi... | The main task of the code is to select the optimal action for a given state using an epsilon-greedy strategy. It evaluates all valid actions by comparing their Q-values, chooses the one with the highest Q-value (exploitation), and occasionally returns a random action (exploration) based on the epsilon probability to ba... | def getAction(s):
bestAction = -1
bestQ = float("-INF")
Qlist = getQ(s)
for a in range(0,4):
currentQ = Qlist[a]
if isValidMove(s,a) and currentQ>bestQ:
bestQ = currentQ
bestAction = a
action = bestAction
e = random.uniform(0,1)
if e<epsilon:
return getRandomAction(s)
else:
return bestAction |
def initializeBoard():
s = [0]*16
TempindicesList = copy.copy(indicesList)
p = random.uniform(0,1)
firstindex = random.choice(TempindicesList)
if p<0.1: s[firstindex] = 2
else: s[firstindex] = 1
del TempindicesList[firstindex]
p = random.uniform(0,1)
secondindex = random.choice(TempindicesList)
if p<0.1: s... | The code simulates a game episode by iterating through states and actions until reaching a terminal state. It tracks previous states/actions, calculates rewards, and stores experiences in a replay memory for reinforcement learning. During the first episode, it prints the board and actions. The loop updates the game sta... | def playGame():
global totalEpisodes
currentstate = initializeBoard()
previousState = -2
previousAction = -2
while(currentstate!=terminalState):
if totalEpisodes == 1:
printBoard(currentstate)
action = getAction(currentstate)
if previousAction != -2:
reward = getReward(previousState,previousAction)
... |
def check_all_bg(line, distance, name, blockgroup_df):
'''
Goes through all the blockgroups and sees which if the given line
intersects with it. If a line intersects with a blockgroup, adds the
distance to the final_df
Inputs:
line: (LineString) the line between the beginning and ending poi... | The main task of the code is to process and analyze geospatial data by reading CSV files, cleaning the data, and calculating distances traveled within or between blockgroups for each location record. It identifies errors in data processing, categorizes valid and invalid records into separate dataframes, and exports res... | def main():
'''
The main of the file
This function pulls in the necessary data, cleans it, and then iterates
through the data and sends each record to the appropriate function to
find the length a location passes through a blockgroup
Inputs: none; it reads data from previously created CSVs
... |
def _look(self, /, offset: int = 0) -> str | None:
index = self._pos + offset
if index < len(self._lex._src):
return self._lex._src[index]
return None
def _check_universal_char_name(self, *, offset: int = 0) -> int:
first = self._look(offset)
i... | This function checks if the current position in the input is the start of an identifier. It returns True if the character is either a backslash followed by a valid universal character name or a letter/underscore, which are valid identifier-start characters in many programming languages. | def _is_ident_start(self) -> bool:
if self._look() == "\\":
return self._check_universal_char_name(offset=1) != 0
return self._look_pred(0, lambda ch: ch.isalpha() or ch == "_") |
def _match_prefix(self, prefix: str, *, offset: int = 0) -> bool:
if self._has_prefix(prefix, offset=offset):
self._move(len(prefix) + offset)
return True
return False
def _move(self, /, n: int = 1) -> None:
self._pos += n
def _look_ch(self, /, offset:... | This function skips whitespace and comments in a token stream. It handles both block comments (/* ... */) and line comments (// ...), moving through the input until it reaches a non-comment, non-whitespace character. The loop continues processing until it finds a meaningful token to return, effectively cleaning the inp... | def _skip_ws(self) -> None:
# mini-lexer that also skips comments
block_comment = False
line_comment = False
while True:
assert not (block_comment and line_comment)
if block_comment:
if self._match_prefix("*/"):
... |
def _look(self, /, offset: int = 0) -> str | None:
index = self._pos + offset
if index < len(self._lex._src):
return self._lex._src[index]
return None
def _move(self, /, n: int = 1) -> None:
self._pos += n
def _match_prefix(self, prefix: str, *, offset: in... | This function identifies punctuation tokens by checking possible matches starting from the current position. It first checks single-character punctuators, then verifies multi-character sequences using a prefix match. If a match is found, it returns the corresponding token kind, resolving digraphs when necessary. If no ... | def _lex_punct(self) -> TokenKind:
start = self._look()
assert start is not None
possibilities = _PUNCTUATORS_NEXT[start]
for p in possibilities:
if len(p) == 1:
self._move()
return _PUNCTUATORS[p]
if... |
def _match_prefix(self, prefix: str, *, offset: int = 0) -> bool:
if self._has_prefix(prefix, offset=offset):
self._move(len(prefix) + offset)
return True
return False
def _look_pred(self, /, offset: int, pred: Callable[[str], bool]) -> bool:
ch = self... | This method checks if the current input position matches an escape sequence in a string, supporting single-character escapes (e.g., '\n', '\t'), octal escapes (e.g., '\123'), hexadecimal escapes (e.g., '\x12'), and universal character names (e.g., '\u1234'). It returns True if any valid escape sequence is detected, Fal... | def _match_escape_seq(self, *, code_unit_bytes: int = 1) -> bool:
if (
self._match_prefix("'")
or self._match_prefix('"')
or self._match_prefix("?")
or self._match_prefix("\\")
or self._match_prefix("a")
or self.... |
def _match_prefix(self, prefix: str, *, offset: int = 0) -> bool:
if self._has_prefix(prefix, offset=offset):
self._move(len(prefix) + offset)
return True
return False
def _lex_universal_char_name(self) -> bool:
expected_count = self._check_universal_c... | This function lexes an identifier token, checking for valid characters (alphanumeric or underscore) and handling escape sequences. If an invalid escape is encountered, it returns an error; otherwise, it returns the identifier token. | def _lex_ident(self) -> TokenKind:
while True:
if self._match_prefix("\\") and not self._lex_universal_char_name():
return TokenKind.ERROR
if self._look_pred(0, lambda ch: ch.isalnum() or ch == "_"):
self._move()
else:
... |
def _is_int_start(self) -> bool:
return self._look_pred(0, lambda ch: ch.isdigit())
def _is_char_start(self) -> bool:
return (
self._match_prefix("'")
or self._match_prefix("L'")
or self._match_prefix("u'")
or self._match_prefix("U'... | The function `_check_int_end` determines if the current position is not the start of an integer, character, string, or identifier by negating the combined result of four boolean checks. It returns `True` when none of these start conditions are met, likely aiding in parsing or tokenization logic to identify non-start po... | def _check_int_end(self) -> bool:
return not (
self._is_int_start()
or self._is_char_start()
or self._is_string_start()
or self._is_ident_start()
) |
def _token_has_prefix(self, prefix: str, *, start: int) -> bool:
return self._lex._src[start:].startswith(prefix)
def _match_prefix(self, prefix: str, *, offset: int = 0) -> bool:
if self._has_prefix(prefix, offset=offset):
self._move(len(prefix) + offset)
return ... | This function lexes a string literal, determining its type (e.g., C_STRING_LIT) based on prefixes like "U", "u8", "u", or "L". It processes escape sequences while considering code unit size (1, 2, or 4 bytes) and returns an error if invalid characters are encountered. The loop continues until a closing quote is found o... | def _lex_string(self, *, start: int) -> TokenKind:
result = TokenKind.C_STRING_LIT
code_unit_bytes = 1
if self._token_has_prefix("U", start=start):
code_unit_bytes = 4
elif self._token_has_prefix("u8", start=start):
code_unit_bytes = 1
... |
def _token_has_prefix(self, prefix: str, *, start: int) -> bool:
return self._lex._src[start:].startswith(prefix)
def _match_prefix(self, prefix: str, *, offset: int = 0) -> bool:
if self._has_prefix(prefix, offset=offset):
self._move(len(prefix) + offset)
return ... | This function lexes a character literal, determining its token type based on prefixes (U/u/L) indicating code unit size. It processes escape sequences, validates syntax, and returns TokenKind.C_CHAR_LIT for valid literals or TokenKind.ERROR for syntax issues like unmatched quotes or invalid escapes. | def _lex_char(self, *, start: int) -> TokenKind:
result = TokenKind.C_CHAR_LIT
code_unit_bytes = 1
if self._token_has_prefix("U", start=start):
code_unit_bytes = 4
elif self._token_has_prefix("u", start=start):
code_unit_bytes = 2
... |
def connecting_edges(self, partitions, graph):
cut_set = []
for a in partitions[0]:
for b in partitions[1]:
if a in graph:
if b in graph[a]:
cut_set.append((a, b))
return cut_set
def get_weights(self, graph, edges):
... | The function calculates the relative closeness between two clusters in a graph by evaluating the mean weight of connecting edges (SEC) and normalizing it with a weighted sum of internal cluster closeness (Ci, Cj) and bisection weights (SECci, SECcj). It returns a normalized measure reflecting the structural connectivit... | def relative_closeness(self, graph, cluster_i, cluster_j):
edges = self.connecting_edges((cluster_i, cluster_j), graph)
if not edges:
return 0.0
else:
SEC = np.mean(self.get_weights(graph, edges))
Ci, Cj = self.internal_closeness(
graph, cluster_i), se... |
def connecting_edges(self, partitions, graph):
cut_set = []
for a in partitions[0]:
for b in partitions[1]:
if a in graph:
if b in graph[a]:
cut_set.append((a, b))
return cut_set
def get_weights(self, graph, edges):
... | This function calculates the relative interconnectivity between two clusters in a graph. It computes the total weight of edges connecting the clusters (EC), divides it by the average internal interconnectivity of each cluster (ECci and ECcj), and returns the ratio. This measures how strongly connected the clusters are ... | def relative_interconnectivity(self, graph, cluster_i, cluster_j):
edges = self.connecting_edges((cluster_i, cluster_j), graph)
EC = np.sum(self.get_weights(graph, edges))
ECci, ECcj = self.internal_interconnectivity(
graph, cluster_i), self.internal_interconnectivity(graph, cluster_... |
def get_cluster(self, graph, clusters):
nodes = [n for n in graph.nodes if graph.nodes[n]
['cluster'] in clusters]
return nodes
def connecting_edges(self, partitions, graph):
cut_set = []
for a in partitions[0]:
for b in partitions[1]:
if a in... | This function identifies the optimal pair of clusters to merge in a graph based on a merge score. It iterates through all cluster pairs, calculates their merge score using the graph and parameter 'a', and selects the pair with the highest score. If the score exceeds zero, it merges the clusters in both the input datafr... | def merge_best(self, graph, df, a, k, verbose=False):
clusters = np.unique(df['cluster'])
max_score = 0
ci, cj = -1, -1
if len(clusters) <= k:
return False
for combination in itertools.combinations(clusters, 2):
i, j = combination
if i != j:
... |
def load_image(image_path, which_direction=0, is_gray_scale=True):
input_img = imread(image_path, is_gray_scale=is_gray_scale)
w_pair = int(input_img.shape[1])
w_single = int(w_pair / 2)
if which_direction == 0: # ct to mr
img_a = input_img[:, 0:w_single]
img_b = input_img[:, w_singl... | This function loads and preprocesses two images from a given path, applying transformations, flipping if specified, and ensuring they have the correct dimensionality for neural network input. It returns the processed image pairs as tensors. | def load_data(image_path, flip=True, is_test=False, which_direction=0, is_gray_scale=True):
img_a, img_b = load_image(image_path=image_path, which_direction=which_direction,
is_gray_scale=is_gray_scale)
img_a, img_b = preprocess_pair(img_a, img_b, flip=flip, is_test=is_test)
i... |
def surface_prufer_codes(genus):
""" We have internal nodes 2g through 4g-2 and outer nodes 0 through 2g - 1.
They are paired as 0 to 1, 2 to 3, etc """
nodes = range(2 * genus, 4 * genus - 2)
for c in trivalent_prufer_codes(nodes):
yield c
def glued_graph(tree, genus):
""" Takes a trivalent Prufer tree... | The main task of the code is to generate unique Prüfer codes for surfaces of a given genus by filtering out isomorphic graphs. It iterates through Prüfer codes, constructs corresponding graphs, checks for isomorphism with previously stored graphs, and retains only non-isomorphic ones. The function returns the list of u... | def unique_surface_prufer_codes(genus):
reps = []
iso_reps = []
for c in surface_prufer_codes(genus):
g = glued_graph(prufer_tree(c), genus)
seen = False
for h in iso_reps:
if nx.is_isomorphic(g, h):
seen = True
break
if not seen:
iso_reps.append(g)
reps.append(c)... |
def parse_data(lines: list):
"""takes a list of strings and outputs a list of lists of Beacon objects"""
scanners = [[]]
for line in lines:
if line.startswith('---'):
continue
if line == '':
scanners.append([])
else:
ints = [int(num) for num in lin... | The code builds a 3D map of beacons detected by multiple scanners, aligning them to a shared coordinate system. It starts with a reference scanner at (0,0,0), then matches and merges other scanners' beacon data. The main tasks are: (1) calculating the total number of unique beacons across all scanners, and (2) determin... | def build_beacon_map():
"""builds a 3d map of all of the beacons detected by scanners and prints the desired results."""
lines = file_reader.get_lines('2021/python/inputs/19.txt')
data = parse_data(lines)
scanners = [Scanner(data.index(group), group) for group in data]
scanner0 = scanners.pop(0)
... |
def get_bbox_mask(self,im):
mask_coordinates = []
outputs = self.predictor(im)
#print(f'outputs: {outputs}')
#Get bboxes from prediction output
bbox_raw = outputs['instances'].to('cpu')
#mask= outputs['instances'].get('pred_masks')
mask = outputs['instances'].pred... | The main task of the code is to compare detected bounding boxes (from `bbox` and `mask`) with annotated bounding boxes (from `annotations`) to verify detection accuracy, identify false positives, and debug discrepancies between model outputs and ground-truth annotations in image data. | def get_comparacion(self, image_data, image_path):
bbox, mask = self.get_bbox_mask(image_data)
#self.draw_mask(image_data, mask)
annotations = self.get_annotation(image_path)
bbox_annotation = self.get_bboxFromAnnotation(annotations)
print(f'bbox: {bbox}, annotations: {bbox_annot... |
def encrypt_caesar(plaintext, shift):
encrypted_text = ""
for char in plaintext:
if char.isalpha():
ascii_offset = ord('A') if char.isupper() else ord('a')
encrypted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
encrypted_text += encrypted_char
... | The main task of the code is to provide a menu-driven interface for encrypting and decrypting messages using Caesar Cipher, RSA Encryption, and Baconian Cipher. Users select a cipher, input text, and view encrypted/decrypted results. The loop continues until the user chooses to exit, with error handling for invalid inp... | def main():
print("WELCOME")
while True:
print("Choose the Cipher you want")
print("1. Caesar Cipher")
print("2. RSA Encryption")
print("3. Baconian Cipher")
print("4. Exit")
choice = int(input("Choose a cipher (1, 2, 3, or 4 to exit): "))
if choice == 1:... |
def encode_data(self):
data_df = self.tar_enc_data
X = data_df.drop(columns=[self.tar_name])
# normalize skewed distributions if necessary
if(self.skewed_feats):
X = self.normalize_distributions(X)
# winsorize the data if necessary
if(self.lim):
... | This class initializes data preprocessing and feature analysis by encoding raw data, handling categorical variables, detecting skewness, and applying dimensionality reduction (PCA, t-SNE, UMAP). It evaluates multicollinearity, variance inflation, target correlations, and performs feature selection via logistic regressi... | def __init__(self, data, cats, skew_feats=None, out_lims=None, pca_thresh=.95):
self.raw_data = data['raw']
self.tar_enc_data = data['tar']
self.tar_name = self.raw_data.columns[0]
self.cat_dict = cats
if out_lims:
self.lim = out_lims
else:
self.l... |
def split_by_ratio(self, ratios, group_by=None):
"""
Overloaded split_by_ratio in RecBole.
Main difference - we split RobustnessGymDataset instance (instead of
Dataloader instance) into train, valid, and test.
Args:
ratios (list):
group_by ():
Ret... | The code builds original and modified datasets for robustness testing by splitting data according to specified strategies (e.g., ratio, leave-one-out), applying ordering (shuffle or sort), and generating robustness variants. It returns original train/valid/test datasets and a dictionary of modified datasets tailored to... | def build(self, eval_setting):
"""
Overloads RecBole build. Our version builds train, valid, test
and modified versions of train, valid, test as needed according to the
robustness tests requested in the robustness_dict.
Args:
eval_setting (EvalSetting):
Retur... |
def get_subjects_of_verb(verb):
if verb.dep_ == "aux" and list(verb.ancestors):
return get_subjects_of_verb(list(verb.ancestors)[0])
"""Return all subjects of a verb according to the dependency parse."""
subjs = [tok for tok in verb.lefts
if tok.dep_ in SUBJ_DEPS]
# get additional c... | The code transforms the tense of input text (present/past/future) by parsing verbs with SpaCy, identifying subject/number/person, and conjugating verbs using linguistic rules. It handles negations, auxiliary verbs, and edge cases like "will" as a noun, while preserving capitalization and adjusting punctuation spacing. ... | def change_tense(text, to_tense, nlp=nlp):
"""Change the tense of text.
Args:
text (str): text to change.
to_tense (str): 'present','past', or 'future'
npl (SpaCy model, optional):
Returns:
str: changed text.
"""
tense_lookup = {'future': 'inf', 'present': PRESENT,... |
def clean_pheromones(self, mg):
for airport_1 in mg.nodes:
for airport_2 in mg.adj[airport_1]:
for flight in mg.adj[airport_1][airport_2]:
mg.adj[airport_1][airport_2][flight]['pheromone_level'] = 0
mg.adj[airport_1][airport_2][flight]['pheromo... | The code implements an Ant Colony Optimization (ACO) algorithm to find the optimal path between two airports. It initializes ants at the origin, iteratively simulates their movement toward the destination, updates pheromone trails, and collects results. After sufficient iterations, it identifies the best path from the ... | def run(self, origin: Airport, destination: Airport):
self.clean_pheromones(self.net.ant_graph)
self._init_ants(origin)
for _ in trange(self.config.iters_numb):
self._run_next_event(origin, destination)
results = []
while len(results) < self.config.result_samples:
... |
def stem_query(self, query):
if self.corpus.stemmer:
words = [self.corpus.stemmer.stem(w) for w in query.words]
else:
words = query.words
return words
def load_query(self, query):
corpus_fb_path = self.feedback_path / self.corpus.name
try:
retu... | This code computes cosine similarity between a query and documents in a corpus. It stems query terms, filters vocabulary, generates query weights, and calculates document similarity using TF-IDF-like weights. Documents with similarity >0.1 are ranked descendingly and returned as tuples of (Document, similarity score). | def query(self, query: Query) -> List[Tuple[Document, float]]:
words = self.stem_query(query)
words = [word for word in words if word in self.corpus.vocabulary]
query_counter = nltk.Counter(words)
ranking = []
q_vector = None
if self.feedback_path:
... |
def solve_first_linear_model(m1, n):
# m1.setParam('OutputFlag', 0)
m1.solve()
infeasible = check_infeasibility(m1)
if infeasible == True:
return ('infeasible', 'none', 'none', 'none')
else:
x_y_list = []
for i in m1.iter_variables():
x_y_list.append(i.solution_va... | The code implements a **multiplicative Feasibility Pump (FP) algorithm** for solving mixed-integer optimization problems. It iteratively solves LP relaxations, checks for integrality, applies rounding to non-integer solutions, and uses a feasibility pump to refine solutions. If non-integer, cuts are added to the models... | def multiplicative_FP(z, n, p,I,c,d, TT,TL, epsilon, multiplier, previous_y_values, m1, multiplicative_y_m1, f, multiplicative_y_f, objvar):
nIT_list = [] # number of FP iteration in each cut iteration
cut_iteration = 0
time_limit_2 = 1200
start_time = time.time()
while True and (time.... |
def solve_first_linear_model(m1, n):
# m1.setParam('OutputFlag', 0)
m1.solve()
infeasible = check_infeasibility(m1)
if infeasible == True:
return ('infeasible', 'none', 'none', 'none')
else:
x_y_list = []
for i in m1.iter_variables():
x_y_list.append(i.solution_va... | This function implements a multiplicative feasibility pump algorithm for optimization. It solves LP relaxations using Gurobi, checks for integer solutions, and applies rounding/feasibility pump techniques to generate cuts. The algorithm iteratively refines solutions by adding constraints (cuts) to models m1 and f, aimi... | def multiplicative_FP(start_time, z, n ,I, c, d, TT, TL,previous_y_values, m1, f, objvar):
nIT_list = [] # number of FP iteration in each cut iteration
cut_iteration = 0
for i in range(1):
# LP relaxation with help of gurobi
m1, z_lp, x_relaxed, y_values = solve_first_linear_model(m1, n)... |
def MILMMP_parameters():
epsilon = 100
multiplier = 10**4
return epsilon, multiplier
def get_integer_index(num_of_dec_var):
# generally in andrea lodi's paper 90% of variables are integer in average
# I = sorted(list(set(random.sample(range(num_of_dec_var), int(9 * num_of_dec_var/ 10)))))
I = [... | This function solves an optimization problem using a multiplicative algorithm, generating linear models and iteratively refining solutions. It returns decision variables, objective value, convergence delta, computation time, and iteration counts for performance analysis. | def main_function(A, b, c, m, n, d, p):
#with open("output.csv","w", newline = '') as csv:
#csv.write("decision_variables, y_values, optimal_value, delta, solution_time, FP_iterations, cut_iterations")
#read and get data
# parameters
epsilon, multiplier = MILMMP_parameters()
I, not_I = get_integer_in... |
def MILMMP_parameters():
epsilon = 100
multiplier = 10**4
return epsilon, multiplier
def get_integer_index(num_of_dec_var):
# generally in andrea lodi's paper 90% of variables are integer in average
# I = sorted(list(set(random.sample(range(num_of_dec_var), int(9 * num_of_dec_var/ 10)))))
I = [i... | The main task of the code is to execute a multiplicative Frank-Wolfe (FP) algorithm for optimization, using parameters and models initialized from input data. It computes decision variables, objective values, and algorithm performance metrics (e.g., solution time, iterations). The function returns optimized variables, ... | def main_function(A, b, c, m, n, d, p):
#with open("output.csv","w", newline = '') as csv:
#csv.write("decision_variables, y_values, optimal_value, delta, solution_time, FP_iterations, cut_iterations")
#read and get data
# parameters
epsilon, multiplier = MILMMP_parameters()
I, not_I = get_integer_in... |
def write_common_tex(args):
template_path = pathlib.Path(__file__).parent / 'common.tex'
with open(template_path) as f:
template = f.read()
with open(args.dst_root / 'common.tex', 'w') as f:
f.write(template.replace('$contest_name$', get_contest_name(args)))
def get_problems(args):
root ... | The main task of the code is to generate problem-specific configurations by first writing common text, retrieving problem lists, and then iterating through each problem to invoke `poly_problem.main` with dynamically generated arguments for processing individual problems. | def main(args):
write_common_tex(args)
problems = get_problems(args)
for pid, pname in problems:
print(pid, pname)
poly_problem.main(gene_prob_args(args, pid, pname)) |
def advect(vf: ti.template(), new_vf: ti.template()):
for i, j in vf:
p = ti.Vector([i, j]) + 0.5
p = backtrace(vf, p, dt)
new_vf[i, j] = bilerp(vf, p)
def divergence(vf: ti.template(), velo_div: ti.template()):
for i, j in vf:
vl = sample(vf, i - 1, j)
vr = sample(vf, i ... | The main task of the code is to perform a sub-step in a fluid simulation by advecting velocity, computing divergence, solving pressure via Jacobi iteration, updating velocity with pressure gradients, and printing the total divergence to ensure incompressibility. This enforces zero-divergence flow by iteratively correct... | def sub_step():
advect(velo, new_volo)
divergence(new_volo, velocity_divs)
solve_pressure_jacobi(pressures, velocity_divs, new_pressures)
sub_gradient(new_volo, pressures)
renew(velo, new_volo)
div_s = np.sum(velocity_divs.to_numpy())
print(f'divergence={div_s}') |
def new_json_2_scasp(payload,ruledoc,testname,exclude_assumptions=False):
output = ""
# I need to grab the ontology for the current test.
ontology = get_ontology_internal(ruledoc,testname)
# For Each Category
for (category_name,category_contents) in payload.items():
# Make category membership abducible?... | The function `interview` processes a user request to execute a logic-based test using Prolog. It checks user permissions, translates submitted JSON data into SCASP facts, constructs a Prolog ruleset, runs queries to derive answers, and extracts relevant categories/attributes from results. It handles Prolog execution, e... | def interview(request,ruledoc,test_name):
print("Dealing with interview request.\n")
test = BlawxTest.objects.get(ruledoc=RuleDoc.objects.get(pk=ruledoc),test_name=test_name)
if request.user.has_perm('blawx.run',test):
print("User has permissions.\n")
# translated_facts = ""
# if request.d... |
def ping(host):
print_info(f"Pinging {host}")
run_command_live_output(["ping", "-c", "4", host])
def traceroute(host):
print_info(f"Tracerouting to {host}")
run_command_live_output(["traceroute", host])
def show_ip_addr():
print_info("Showing IP addresses")
if platform.system() == "Darwin":
... | The code defines a command-line network diagnostic tool that processes user arguments to perform tasks like pinging hosts, tracing routes, displaying IP information, capturing network traffic with tcpdump, conducting DNS lookups, and running speed tests, executing the appropriate function based on the provided flags an... | def main():
parser = argparse.ArgumentParser(description="Network Diagnostic Tool")
parser.add_argument("-p", "--ping", help="Ping a host", type=str)
parser.add_argument("-t", "--traceroute", help="Perform a traceroute to a host", type=str)
parser.add_argument("--ipaddr", help="Display IP addresses", ac... |
def clear_results_file(app):
for bfm in p.rf_bfm_list:
open(get_log_name(app, p.RF_MODE, "rf", bfm)).close()
for igid in p.inst_value_igid_bfm_map:
for bfm in p.inst_value_igid_bfm_map[igid]:
open(get_log_name(app, p.INST_VALUE_MODE, igid, bfm)).close()
for igid in p.inst_address_igid_bfm_map:
for bfm in p... | The main task of the code is to execute injection experiments on sorted applications, handling parallel execution via the lockfile module when not in standalone mode. It creates log directories, cleans results if specified, and runs multiple injections per app based on command-line arguments. | def main():
if len(sys.argv) >= 2:
where_to_run = sys.argv[1]
if where_to_run != "standalone":
if pkgutil.find_loader('lockfile') is None:
print ("lockfile module not found. This python module is needed to run injection experiments in parallel." )
sys.exit(-1)
sorted_apps = [app for app, value i... |
def parse_results_apps(typ):
for app in p.parse_apps:
if typ == p.INST_VALUE_MODE:
for igid in p.parse_inst_value_igid_bfm_map:
for bfm in p.parse_inst_value_igid_bfm_map[igid]:
parse_results_file(app, typ, igid, bfm)
elif typ == p.INST_ADDRESS_MODE:
for igid in p.parse_inst_address_igid_bfm_map:
... | The main task of the code is to parse injection results, compute instruction fractions, and generate TSV reports. It initializes parameters, processes parsed data, sets output file paths, and prints detailed statistics, fractions, and results to TSV files for analysis. The function orchestrates data parsing, fraction c... | def main():
inj_type = "inst_value"
parse_results_apps(inj_type) # parse sassifi results into local data structures
# populate instruction fractions
populate_inst_fraction()
global fname_prefix
fname_prefix = p.NVBITFI_HOME + "/logs/" + "results/results_" + inj_type + "_" + str(p.NUM_INJECTIONS) + "_"
pri... |
def tokenize(self, line):
token = ''
index = 0
tokens = []
while index < len(line):
if self.isPartOfOperator(line[index]):
if token:
tokens.append(token)
token, index = self.getOperatorToken(line, index)
toke... | The code performs lexical analysis on a file named "p1err", tokenizing each line and classifying tokens into separators, operators, reserved words, identifiers, or constants. It builds a symbol table for identifiers/constants and a PIF (Parsing Intermediate File) with token types and positions. Lexical errors are recor... | def run_program(self):
readFile()
filename = "p1err"
error_message = ""
with open(filename, 'r') as file:
cnt = 0
for line in file:
cnt += 1
tokens = self.tokenize(line.strip())
for i in range(len(tokens)):
... |
def templateMatching(self,template):
img = self.test_img.copy()
w, h = template.shape[1],template.shape[0]
meth = 'cv.TM_CCOEFF_NORMED'
method = eval(meth)
res = cv.matchTemplate(img,template,method)
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
top_... | This function checks each feature template against an image, validating matches through template matching. It processes 'Image' and 'Text' features differently, performing additional color checks for text. If a feature is invalid, it stops processing, records the failure, and returns detected points. Otherwise, it logs... | def checkAllFeatures(self):
for i in range(len(self.feature_pts)):
pts = self.feature_pts[i]
ftype = self.feature_types[i]
print(ftype+" feature "+str(i))
template = self.mas_img[pts[1]:pts[3],pts[0]:pts[2]]
detected_pts = self.templateMatchin... |
def collide(self, action):
self.remove_shape()
copied_shape = self.current_shape.copy()
if action == 0:#rotate
copied_shape['shape'] = np.rot90(copied_shape['shape'],1)
elif action == 1:#left
copied_shape['x'] -= 1
elif action == 2:#down
copied... | The code processes a list of actions to move a shape, checking for collisions. If a collision occurs, it clears completed rows, generates the next shape, and updates the game state. It returns whether the game is still active, if the shape moved, and the number of cleared rows. | def move_shape(self, actions):
alive = True
cleared_rows = 0
moved = False
for action in actions:
collide, moved = self.collide(action)
if collide:
cleared_rows = self.clear_rows()
alive = self.generate_next()
return alive, ... |
def draw_grid(self, screen: pg.Surface):
color = self._config['grid']['color']
self.thickness = self._config['grid']['thickness']
lines = [
# Vertical
((self.third_width, 0), (self.third_width, self.height)),
((self.two_thirds_width, 0), (self.two_thirds_widt... | The main task of the code is to update the game's visual state by drawing the grid, placed game elements, and displaying the winner on the provided screen surface. The function orchestrates rendering the game board layout, player pieces, and victory status, ensuring the UI reflects the current game state and outcome. | def update(self, screen: pg.Surface, winner: str) -> None:
self.draw_grid(screen)
self.draw_placed(screen)
self.draw_winner(screen, winner) |
def global_alignment(v, w):
global indel_penalty
n = len(v)
m = len(w)
S = [[0 for j in range(m + 1)] for i in range(n + 1)]
backtrack = [[0 for j in range(m + 1)] for i in range(n + 1)]
for i in range(1, n + 1):
S[i][0] = -i * indel_penalty
for j in range(1, m + 1):
S[0][j]... | The function `linear_space_alignment` recursively aligns two sequences `v` and `w` within specified bounds using a divide-and-conquer approach. It splits the alignment into subproblems, finds the "middle edge" for optimal splitting, and combines results from left/right subproblems with the middle alignment. This method... | def linear_space_alignment(top, bottom, left, right):
global v, w
if left == right:
return [v[top:bottom], '-' * (bottom - top)]
if top == bottom:
return ['-' * (right - left), w[left:right]]
if bottom - top == 1 or right - left == 1:
return global_alignment(v[top:bottom], w[le... |
def _parse_json_message(self, payload):
'''
Try to Parse a message as JSON. If parses; return the object, if not return False.
'''
try:
return json.loads(payload)
except ValueError as e:
return False
def _is_sdk_formatted_message(self, me... | The main task of the code is to handle incoming PubSub messages by validating their JSON format, determining if they conform to the AWS Greengrass SDK structure, and routing them to appropriate processors. It logs received messages, parses payloads, checks format compliance, and directs messages to either the SDK messa... | def _received_message_callback(self, protocol, topic, payload):
'''
Callback for all (IPC and MQTT) PubSub Client received messages.
Provides initial message validation and passing to PubSub topic routers.
Expects message payload provided is JSON formatted.
'''
try:
... |
def log(self, activity, bookname = None):
'''Logs the activity of the users'''
username = nme.title()
logCode = rq.genCode()
time = datetime.datetime.now()
try:
with open('signupToken.txt') as file:
token = file.read()
if token =... | The main task of the code is to present a menu-driven interface for a library system, allowing users to select actions like listing books, searching, renting, returning books, viewing profiles, or exiting. It logs the login activity and processes user input to invoke corresponding methods for each selected operation. | def __init__(self):
print("Welcome to the Library!!\n")
print("What you wanna do?")
print("\n0 to list books available")
print("1 to search for a book")
print("2 to rent a book")
print("3 to return a book")
print("4 to view profile")
print("Enter to exit."... |
def gameOver(board):
return checkWin(board, "X") or checkWin(board, "O") or len(availableMoves(board)) == 0
def printBoard(board):
print(f"""
| |
{board[0]} | {board[1]} | {board[2]}
| |
---+---+---
| |
{board[3]} | {board[4]} | {board[5]}
| |
---+---+---
| ... | The main task of the code is to run a tic-tac-toe game where two players take turns selecting slots on a 3x3 board. It validates moves, updates the board, checks for a win after each move, and declares the winner or a tie if all slots are filled without a winner. | def startGame():
playBoard=[' ',' ',' ',' ',' ',' ',' ',' ',' ']
turn = 'X'
winner = False
# prints numbered slots board and playing board
while (not gameOver(playBoard)):
numbering = []
for i in range(1,10):
numbering.append(i)
print("Keep in mind the Slot Numbering")
printBo... |
def read_sampling_index(df):
sample_file_path = "../../data/example_sampling.csv"
sampled_df = pd.read_csv(sample_file_path)
sampled_indices = list(sampled_df['selected_row_number'] - 1)
sampled_df = df.loc[sampled_indices].sort_index()
return sampled_df
def read_context(ESSAY_PATH):
with open(... | This function evaluates answers against questions using predefined rules and noun phrases. It reads data from CSV files, processes anchor and answer sentences, and checks consistency between question texts and stored answers. If mismatches occur, it exits early. For each entry, it extracts context segments, applies rul... | def rule_base_criteria3(rule, strict):
data = pd.read_csv(NP_FILE_PATH)
np_list = data["Longest np"].to_list()
question_list = data["questions"].to_list()
df = pd.read_csv(ANCHOR_FILE_PATH)
df = df.reset_index()
df = df.rename(columns={df.columns[0]: "index"})
df = read_sampling_index(df... |
def xor_blocks(self, res, a, b, b_start, len):
for i in range(len):
res[i] = a[i] ^ b[b_start + i]
def swap_bytes(self, w, k):
for i in range(4):
for j in range(8):
k[i + 4*j] = w[8*i + j]
def gost_encrypt(self, key, in_block, in_pos, out_block, out_pos):
... | This function performs cryptographic hashing using XOR operations, byte swapping, and GOST encryption. It processes input blocks (xh, xm) through multiple rounds of transformations, including XORing with precomputed values, encrypting with GOST, and iterative transformations on a state array (xs). The result is stored ... | def hash_step(self, xh, xm, mstart):
xu = bytearray([0]*32)
xw = bytearray([0]*32)
xv = bytearray([0]*32)
xs = bytearray([0]*32)
key = bytearray([0]*32)
self.xor_blocks(xw, xh, xm, mstart, 32)
self.swap_bytes(xw, key)
self.gost_encrypt(key, xh, 0, xs, 0)
... |
def array_copy(self, src, src_pos, dest, dest_pos, length):
dest[dest_pos:dest_pos] = src[src_pos:src_pos+length]
def hash_step(self, xh, xm, mstart):
xu = bytearray([0]*32)
xw = bytearray([0]*32)
xv = bytearray([0]*32)
xs = bytearray([0]*32)
key = bytearray([0]*32)
... | This function finalizes a cryptographic hash computation by processing remaining data, encoding the total input length in bytes, and performing final hash steps to produce the resulting hash value (xh). It handles leftover data from the context, appends the length as a 32-bit little-endian value, and applies two final ... | def finish_hash(self, context):
buf = bytearray([0]*32)
xh = bytearray([0]*32)
xs = bytearray([0]*32)
fin_len = context.len
self.array_copy(context.h, 0, xh, 0, 32)
self.array_copy(context.s, 0, xs, 0, 32)
if context.left > 0:
self.array_copy(context.r... |
def array_copy(self, src, src_pos, dest, dest_pos, length):
dest[dest_pos:dest_pos] = src[src_pos:src_pos+length]
def hash_step(self, xh, xm, mstart):
xu = bytearray([0]*32)
xw = bytearray([0]*32)
xv = bytearray([0]*32)
xs = bytearray([0]*32)
key = bytearray([0]*32)
... | This function processes a block of data for a hash algorithm by handling remaining bytes, updating the hash state, and processing 32-byte chunks. It copies data into a remainder buffer, updates the hash step, adds blocks to the state, and manages the total length. If leftover data exists, it prepares for subsequent pro... | def hash_block(self, context, block, _pos, length):
pos = _pos
last_pos = pos + length
if context.left > 0:
add_bytes = 32 - context.left
if add_bytes > length:
add_bytes = length
self.array_copy(block, pos, context.remainder, context.left, add... |
def opcode(self):
opcode = "00000000" + str(self.memory[self.instruction_pointer])
return opcode[-2:]
def jump_if_true(self):
if self.get(1):
self.instruction_pointer = self.get(2)
else:
self.instruction_pointer += 3
def jump_if_false(self):
if not self.ge... | The code executes a program defined by opcodes stored in memory, processing each instruction in a loop until a "99" (halt) opcode is encountered. It handles arithmetic operations (add, multiply), conditional jumps, comparisons (less than, equals), input/output, and memory management. The program uses a copy of the inpu... | def run(self, memory, indata=None):
self.indata = indata
self.memory = copy(memory)
while True:
opcode = self.opcode()
if opcode == "99":
return
elif opcode == "05":
self.jump_if_true()
elif opcode == "06":
... |
def debug_print(message):
'''Prints the message if the DEBUG flag is set'''
if DEBUG:
prettyprint(message)
def prettyprint(message, width=280):
'''pretty prints the text'''
pprint.pprint(message,width = width)
def add_customers_to_dealers(customer_file,dealer_file):
"""Adds the customers in ... | The main task of the code is to parse command-line arguments for dealer/customer CSV files, handle simulation/verbose flags, validate input files, and execute the `add_customers_to_dealers` function to process data, with results pretty-printed to output. Global variables `DEBUG` and `SIMULATION` are set based on option... | def main():
global DEBUG #important, otherwise the global var DEBUG won't be set.
global SIMULATION #important, otherwise the global var SIMULATION won't be set.
usage = "usage: python3 %prog [-v|--verbose] [-s|--simulation] -d dealers.csv -c customers.csv >> out.log"
parser = OptionParser(usage)
... |
def _check_events(self):
# Respond to keypresses and mouse events
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Controls flags related to keypresses and button clicks
elif event.type == pygame.KEYDOWN:
... | The code runs a game loop that continuously checks for events, updates particles if the program is active, maintains a capped frame rate, and refreshes the screen to render visual changes in real-time. | def run_program(self):
# Start the main loop for the program
while True:
self._check_events()
if self.settings.program_active:
self._update_particles()
pygame.time.Clock().tick(self.settings.frameratecap)
self._update_screen() |
def validateConfiguration():
logging.info("Validating local environment")
goodConfig = True
if( platform.system() != 'Linux' ) :
logging.warning( "You do not appear to be running on a Linux platform. This code has not be tested on other platforms." )
goodConfig = False
if( "Ubuntu" not ... | The main task of the code is to configure logging, validate system settings, execute tests (either all tests or a specific function via threading based on the 'cmd' input), and clean up resources. It ensures proper setup verification, runs test routines, and logs results to a file and console, then terminates listeners... | def main( cmd ):
#print locals()
#print globals()
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p',
handlers= [logging.FileHandler(filename='ceFlutterTests.log'),logging.StreamHandler()],
level=logging.INFO)
... |
def get_content(in_data):
for index, _line in get_line(in_data):
_content = filter_token_dict(_line)
yield index, _content
def check_item(item, case_insensitive):
if case_insensitive is True:
item = item.casefold()
_name_list = NAME_LIST_CASEFOLDED
else:
_name_list = ... | The main task of the code is to process input data by validating items against checks for correctness (e.g., identifiers, integers), detect errors, and generate correction suggestions when invalid. It yields structured results via `TemplateItem`, including error status, line numbers, and case-sensitive mismatch flags, ... | def get_items(in_data, case_insensitive):
for index, content in get_content(in_data):
for level, items in content.items():
for item in items:
possible_correction = None
has_error = False
is_case_error = False
if check_item(item, ca... |
def parse_for_href(host: HostNode, soup):
for anchor in soup.find_all('a'):
hrefs = anchor.get('href')
if hrefs is not None:
if type(hrefs) == list:
for location in hrefs:
driver_create_href(host, location)
else:
driver_cre... | The code enumerates a website by crawling its domain, parsing HTML content to extract hyperlinks and email addresses, processing identified links, checking for new sites, and marking the host as enumerated while updating a counter. | def enumerate_site(host: HostNode):
resp = crawler.get_web_page(host.domain, "", host.name)
soup = BeautifulSoup(resp, 'html.parser', on_duplicate_attribute=accumulate)
parse_for_href(host, soup)
parse_for_emails(host, soup)
enumerate_hrefs(host)
test_host_for_new_sites(host)
host.is_enumer... |
def see_action(request, game_id, player):
game = Game.objects.get(pk=game_id)
player = request.user.player
# Implement logic for "See" action
# Example: Player matches the current bet in the pot
if player.wallet >= game.pot:
player.wallet -= game.pot
game.pot *= 2 # Double the pot a... | This function manages a turn-based game by handling player actions (see, raise, fold, showdown), ensuring only the current player can act, switching turns after each move, and rendering appropriate templates based on the player's turn status. | def play_game(request):
user = request.user
player, created = Player.objects.get_or_create(user=user)
game, created = Game.objects.get_or_create()
if game.current_player is None:
game.current_player = player
game.save()
# Check if it's the current player's turn
if game.curr... |
def create_results_directory():
if not os.path.exists('results'):
os.makedirs('results')
def create_embedding_results_directory(model_name):
embedding_results_dir = os.path.join('visualization', 'embedding', model_name)
if not os.path.exists(embedding_results_dir):
os.makedirs(embedding_resu... | The main task of the code is to evaluate multiple graph neural network models (GINModel, GraphUNetTopK, SimpleGraphUNet) on three benchmark datasets (MUTAG, ENZYMES, PROTEINS). For each model-dataset pair, it preprocesses data, loads models, evaluates performance, and visualizes/saves embeddings in structured directori... | def main():
create_results_directory()
model_names = ['GINModel', 'GraphUNetTopK', 'SimpleGraphUNet']
dataset_names = ['MUTAG', 'ENZYMES', 'PROTEINS']
for model_name in model_names:
for dataset_name in dataset_names:
embedding_results_dir = create_embedding_results_directory(model_n... |
def __makedir_exist_ok(dirpath):
"""Make directory if not already exists
"""
try:
os.makedirs(dirpath)
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
raise
def __create_info_df_csv(self):
if os.path... | This code initializes a dataset handler for training or testing, setting up directories, file paths, and parameters like image size and fold ratio. It validates the data type, constructs paths for processed data (Pickle files and CSV metadata), and triggers methods to generate these files, ensuring data is structured f... | def __init__(self, root_dir, d_type, transform=None, img_size=(168, 224), fold_ratio=2,
simplified=False):
if d_type not in ('test', 'train'):
raise ValueError("d_type can only be set to 'test' or 'train'")
print("IMAGES ARE EXPECTED TO BE 168x224 !")
self.root_dir... |
def parse_date(file='date.txt'):
with codecs.open(file, 'r', 'utf-8') as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
return lines
def get_search_result(date, cur_page=1, keyword='tesla'):
all_urls = set()
total_page, urls = get_one_page_search_result(date, cur_page, k... | The main task of the code is to iterate through a list of dates, print each date, retrieve search results for that date, and extract article content from the obtained URLs. The function `main()` orchestrates parsing dates, fetching search results, and collecting article data, likely for web scraping or data aggregation... | def main():
dates = parse_date()
for date in dates:
print('CURRENT QUERY DATE:', date)
urls = get_search_result(date)
get_all_article_content(date, urls) |
def __debug(self, message):
if self.__debugMode:
print(message)
def __predictClass(self, message=None):
# filter out predictions below a threshold
(p, matchPhrase) = self.__bow(message)
res = self.__model.predict(numpy.array([p]))[0]
results = [[i,r] for i,r in enumer... | The code processes a user message by predicting intent, detecting variables, setting context, generating a response, evaluating it, and logging interactions. It returns the evaluated response after debugging and logging. | def message(self, username=None, message=None):
if not username or not message:
return None
self.__debug("DEBUG MODE "+"^" * 59)
(intents, phrase) = self.__predictClass(message=message) # Get prediction class
variables = self.__detectUserVariables(intents=inten... |
def get32(mv: memoryview):
return ((mv[0] << 24) + (mv[1] << 16) + (mv[2] << 8) + mv[3])
def recv_ack(m: MBuf): # pylint: disable=W0613,R0912
global lastack # pylint: disable=W0603
if m.len() != 24:
logger.info("Received Bad Length ACK: len: %d", m.len())
return
start = memoryview(m.... | This function reads and processes TFS link packets from a socket, managing sequence numbers, detecting duplicates/losses, handling congestion control, and reconstructing inner packets. It uses queues for memory management, logs errors/drops, and ensures correct packet ordering before outputting processed data. | def read_tfs_packets(s, freeq: MQueue, iovfreeq: MIOVQ, outq: MIOVQ,
send_ack_cv: threading.Condition, max_rxrate: int):
del send_ack_cv # quiet the warning.
logger.info("read: start reading on TFS link")
outq.startseq = 0
outq.lastseq = 0
outq.dropcnt = 0
rxlimit = None
... |
def forgy_initialization(X, K):
"""
Add documentation.
"""
N = X.shape[0]
idx = np.random.choice(N, K)
centers_init = X[idx]
return centers_init
def fixed_length_initialization(min_init, diff_init, fixed_length, K, dim):
"""
Add documentation.
"""
s1 = min_init + diff_init *... | The main task of the code is to initialize representative points or segments for a model based on a configuration file. It loads parameters like input/latent dimensions, number of classes, and initialization strategies. Depending on the `type_rep` (points/segments), it applies strategies such as random sampling, Forgy ... | def get_rep(cfg_path, X):
"""
Add documentation.
"""
cfg_file = load_config(cfg_path)
input_dim = cfg_file["model"]["input_dim"]
latent_dim = cfg_file["model"]["latent_dim"]
K = cfg_file["data"]["num_classes"]
init_strategy = cfg_file["train"]["init_strategy"]
min_init = cfg_file["tr... |
def find_empty(board, i, j):
for x in range(i, 9):
for y in range(j, 9):
if board[x][y] == 0:
return x, y
for x in range(0, 9):
for y in range(0, 9):
if board[x][y] == 0:
return x, y
return -1, -1
def valid_check(board):
valid = che... | This function solves a Sudoku puzzle using backtracking. It recursively fills empty cells with numbers 1-9, checking validity at each step. If a valid number leads to a solution, it returns True; otherwise, it backtracks by resetting the cell and trying the next number. The process continues until the board is fully so... | def solve(board, i=0, j=0):
i, j = find_empty(board, i, j)
if i == -1:
return True
for e in range(1, 10):
board[i][j] = e
if valid_check(board):
if solve(board, i, j):
return True
board[i][j] = 0
return False |
def find_empty(board, i, j):
for x in range(i, 9):
for y in range(j, 9):
if board[x][y] == 0:
return x, y
for x in range(0, 9):
for y in range(0, 9):
if board[x][y] == 0:
return x, y
return -1, -1
def valid_check(board):
valid = che... | This code solves a Sudoku puzzle using backtracking, recursively trying numbers 1-9 in empty cells while visually updating a Pygame grid in real-time. It checks validity, updates the display for each attempt, and backtracks if a number leads to an invalid state, ultimately returning True if the board is solved. | def solve(board, i=0, j=0):
i, j = find_empty(board, i, j)
if i == -1:
return True
for e in range(1, 10):
screen.fill(WHITE)
board[i][j] = e
pygame.draw.line(screen, GREY, (0, 150), (500, 150), 1)
pygame.draw.line(screen, GREY, (0, 300), (500, 300), 1)
pygame... |
def __decide_best_trade__(self, suggested_trade_list: list[SuggestedTransaction]) \
-> tuple[SuggestedTransaction, int, int]:
"""
Best trade is decided by maximizing: unit_profit * volume
"""
best_trade = None
max_profit = 0
trade_volume = 0
for sugges... | The main task of the code is to generate a sequence of buy/sell trades based on stock history data, using a trading engine to identify optimal trades within sliding time windows. It iteratively selects the best trade (maximizing profit), executes it, updates the trade history, and adjusts the current date until all des... | def trade(self):
current_date = self.stock_history["Date"].min()
max_date = self.stock_history["Date"].max()
trades = deque()
trade_history_df = pd.DataFrame(columns=self.stock_history.columns)
desired_transactions = self.number_of_transactions
while desired_transaction... |
def aesenc(s, rk):
s = subbytes(s)
s = shiftrows(s)
s = mixcolumns(s)
s = xor(s, rk[::-1])
return s
def convRC(rc):
rcstr = hex(rc)[2:-1].zfill(32)
return [int(rcstr[i:i+2], 16) for i in range(0, 32, 2)]
def mix512(s):
return [s[0][12:16] + s[2][12:16] + s[1][12:16] + s[3][12:16],
... | This code implements a cryptographic hash function (likely a variant of the Haraka algorithm) by processing the input message through multiple rounds of AES-style encryption, mixing operations, and a feed-forward step, then truncating the final state to produce a 256-bit hash output. | def haraka512256(msg):
# obtain state from msg input and set initial rcon
s = [msg[i:i+16] for i in [0,16,32,48]]
rcon = [0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1]
#print("= input state =")
#printstate(s)
# apply round functions
for t in range(ROUNDS):
# first we do AES_ROUNDS of AES rounds... |
def aesenc(s, rk):
s = subbytes(s)
s = shiftrows(s)
s = mixcolumns(s)
s = xor(s, rk[::-1])
return s
def convRC(rc):
rcstr = hex(rc)[2:-1].zfill(32)
return [int(rcstr[i:i+2], 16) for i in range(0, 32, 2)]
def shift32(x):
# make list of 32-bit elements
w = [((x[i] << 24) ^ (x[i+1] << 1... | The code implements a cryptographic hash function (likely HAHA-256) by processing the input message through multiple rounds of AES-like encryption operations, state mixing, and a feed-forward step to produce a truncated hash output. | def haraka256256(msg):
# obtain state from msg input and set initial rcon
s = [msg[i:i+16] for i in [0,16]]
rcon = [0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1]
#print("= input state =")
#printstate(s)
# apply round functions
for t in range(ROUNDS):
# first we do AES_ROUNDS of AES rounds and u... |
def __load_similarity_scores(self):
'''
returns similarity scores of numpy array
'''
data = self.grouby_character()
cv = CountVectorizer()
count_matrix = cv.fit_transform(data['dialogue'])
self.similarity_scores = cosine_similarity(coun... | The code identifies the top three characters most similar to the input character `c` using precomputed similarity scores. It retrieves the similarity scores, sorts them in descending order, extracts the top three, and returns them in a pandas DataFrame with columns for characters and their similarity percentages. | def get_similar_character(self,c):
'''
returns the similar characters corresponding to the input character value.
'''
self.__load_similarity_scores()
index = self.__get_index_of_character(c)
if index==-1:
return
s... |
def texttospeech(text, filename):
filename = filename + '.mp3'
flag = True
while flag:
try:
tts = gTTS(text=text, lang='en', slow=False)
tts.save(filename)
flag = False
except:
print('Trying again')
playsound(filename)
os.remove(filenam... | The code handles user authentication and redirects unauthenticated/inactive users. It uses speech-to-text and text-to-speech for voice-based email interactions, processing commands like composing, reading, deleting emails, searching, or logging out, returning JSON responses for client-side actions while maintaining use... | def home_view(request):
context = {}
user = request.user
print("Printing in views")
if not user.is_authenticated:
return redirect("myapp:first")
if not user.is_active:
return redirect("myapp:auth")
print("--------------", user.email)
print("=========", user.gpass)
MailL... |
def texttospeech(text, filename):
filename = filename + '.mp3'
flag = True
while flag:
try:
tts = gTTS(text=text, lang='en', slow=False)
tts.save(filename)
flag = False
except:
print('Trying again')
playsound(filename)
os.remove(filenam... | This Django view handles user signup via voice input. It checks authentication status, processes POST data with voice prompts, validates email uniqueness, creates inactive users, and returns JSON responses for success/failure. If unauthenticated, it renders the signup form. | def signup_view(request):
if request.user.is_authenticated and request.user.is_active:
return redirect("myapp:home")
if request.user.is_authenticated and not request.user.is_active:
return redirect("myapp:auth")
if request.method == 'POST':
print(request.POST)
file = 'test'... |
def texttospeech(text, filename):
filename = filename + '.mp3'
flag = True
while flag:
try:
tts = gTTS(text=text, lang='en', slow=False)
tts.save(filename)
flag = False
except:
print('Trying again')
playsound(filename)
os.remove(filenam... | The code implements a voice-based login system that uses text-to-speech for user interaction. It checks user authentication status, collects email/password via voice input, validates credentials, and returns JSON responses for success/failure. If authenticated, it redirects to home or auth pages; otherwise, it renders ... | def login_view(request):
context = {}
if request.user.is_authenticated and request.user.is_active:
return redirect("myapp:home")
if request.user.is_authenticated and not request.user.is_active:
return redirect("myapp:auth")
if request.method == 'POST':
file = 'test'
i =... |
def introVoice(email, file, i):
flag = True
addr = ''
passs = ''
while (flag):
texttospeech("Enter your"+email, file + i)
i = i + str(1)
addr = speechtotext(10)
if addr != 'N':
texttospeech("You meant " + addr +
" say yes to confirm or... | The code handles email composition via voice input, processing POST requests to gather sender details, subject, and message content. It allows users to read, delete, rewrite, or send the draft based on voice commands. If 'send' is chosen, it sends the email using the user's credentials and redirects to the sent folder.... | def compose_view(request):
file = 'test'
i = '1'
user = request.user
if request.method == 'POST':
print("hit post request in compose view")
# entering sender's email address
recievers_addr = introVoice('Senders Address', file, i)
print("recievers_addr-->")
print(r... |
def texttospeech(text, filename):
filename = filename + '.mp3'
flag = True
while flag:
try:
tts = gTTS(text=text, lang='en', slow=False)
tts.save(filename)
flag = False
except:
print('Trying again')
playsound(filename)
os.remove(filenam... | The code processes a sent email by converting its content to speech and allowing user interaction via voice commands. It handles actions like replying, deleting, rewriting, or sending the email, using text-to-speech and voice recognition. The function renders a template for GET requests and returns JSON responses for P... | def read_sent_view(request,id):
id = int(id)
user = request.user
MailList = read_sentmail(user.email, user.gpass)
mail = MailList[id]
print("Reached read sent View")
i = '1'
file = "test"
if request.method == 'GET':
return render(request,'myapp/readSent.html',{'mail':mail,'mail_i... |
def texttospeech(text, filename):
filename = filename + '.mp3'
flag = True
while flag:
try:
tts = gTTS(text=text, lang='en', slow=False)
tts.save(filename)
flag = False
except:
print('Trying again')
playsound(filename)
os.remove(filenam... | The main task of the code is to handle a web request for reading an email, using voice commands to interactively reply, forward, or delete the email. It converts the email body to speech, processes user voice responses (e.g., "reply," "forward," "delete"), and performs actions like sending replies, drafting messages, o... | def read_view(request, id):
id = int(id)
user = request.user
MailList = ReadMails(user.email, user.gpass)
mail = MailList[id]
print("Reached read View")
i = '1'
file = "test"
if request.method == 'GET':
return render(request,'myapp/read.html',{'mail':mail,'mail_id':id})
... |
def fit_prediction_models():
X_train, X_test, y_train, y_test = train_test_valid()
clf = MLPClassifier(random_state=1).fit(X_train, y_train)
clf_preds = clf.predict(X_test)
f1, r_score, p_score = get_metrics(y_test, clf_preds)
return clf, f1, r_score, p_score
def train_test_valid():
RA... | The function `get_model` loads or trains a machine learning model from a specified path. If the model file doesn't exist, it creates a "model" directory, trains the model using `fit_prediction_models()`, saves it with `pickle`, and returns the model along with training metrics (F1, recall, precision). If the file exist... | def get_model(clf_path):
if not os.path.exists(clf_path):
models_fldr = os.path.join(os.getcwd(), "model")
if not os.path.exists(models_fldr):
os.mkdir(models_fldr)
clf, f1, r_score, p_score = fit_prediction_models()
with open(clf_path, 'wb') as file_f:
pickl... |
def set_recording_indicator_status(self, status_text):
rec_indicator = self.findChild(QLabel, "recordIndicator")
rec_indicator.setText(status_text)
def __process_result(self, result):
try:
result = [ch.upper() for ch in result.split()]
inters = tuple(set(self.vertex_ident... | The main task of the code is to record voice input, convert it to text, and process the result. It sets a status indicator during processing, handles errors with a generic message, and resets the indicator upon completion. The function records audio, converts it to text via a speech-to-text function, then processes the... | def record(self):
try:
self.set_recording_indicator_status("Processing your voice...")
audio_path = record()
result = convert_speech_to_text(audio_path)
self.__process_result(result)
self.set_recording_indicator_status("")
except Exception:
... |
def __level_completed__(self):
return len(self.level.balls) == 0
def __game_completed__(self):
return self.levelIndex == len(self.levels)
def restart(self):
"""Restarts current level"""
self.level = Level(self.level.number, self.level.segments, self.level.colors, self.level.max_balls,
... | This function updates the game state by checking if it's paused or finished. If a level is completed, it advances to the next level, updates the score, and checks for game completion. If the current level ends, it restarts. Otherwise, it moves balls, adds new ones, handles user interactions, and processes collisions to... | def update_game(self):
"""Updates state of the game and moves all balls"""
if self.paused or self.finished:
pass
elif self.__level_completed__():
self.levelIndex += 1
self.score += 100 * self.levelIndex
if self.__game_completed__():
... |
def calibrate_with_pedestal(self,
file_data: [ndarray],
pedestal: int,
console: Console,
session_controller: SessionController) -> [ndarray]:
result = file_data.copy()
console.... | This function calibrates image data arrays based on a pre-defined calibration type. It checks the calibration mode (none, pedestal, fixed file, or auto directory) and applies the corresponding calibration method, returning the adjusted image data. The process uses parameters like the data model, console, and session co... | def calibrate_images(self, file_data: [ndarray],
sample_file: FileDescriptor,
console: Console,
session_controller: SessionController) -> [ndarray]:
calibration_type = self._data_model.get_precalibration_type()
if calibration_typ... |
def bound_point_cloud_world(pts, poses):
"""Bound the point cloud in the world frame."""
for i, pose in zip(range(len(pts)), poses):
world_pc = transform_vec(
pts[i].unsqueeze(0), pose.unsqueeze(0)
)[0]
valid = in_bounds(world_pc, WORLD_BOUNDS)
pts[i] = pts[i][valid]
... | The function processes a queue of point cloud data to detect robotic grasp poses. It converts ROS messages to point clouds, applies bounding, downsampling, and coordinate transformations, runs a neural network to identify grasps, filters results, and publishes grasp poses and visualized point clouds as ROS messages for... | def find_grasps():
global queue, device, queue_mtx
with queue_mtx:
if len(queue) != QUEUE_LEN: return
with TimeIt("FIND_GRASPS() fn: "):
with TimeIt('Unpack pointclouds'):
# only copy the queue with the mutex. Afterward, process the copy.
with queue_mtx:
... |
def check_keys(self):
events = self.kb.getKeys()
for kbe in events:
if kbe.key in self.key_codes:
if kbe.type == 'KEYBOARD_PRESS':
self.exo_display.spoof_keydowns[int(np.where(kbe.key==np.array(self.key_codes))[0])]=True
elif kbe.type == 'K... | The code runs an infinite loop to control an experiment's main process, checking for user input, updating exoskeleton display inputs, handling experiment stages (waiting or running trials), and rendering visuals. It continuously processes stages, updates displays, and responds to key presses until the loop is externall... | def run_main_loop(self):
while True:
if not(self.exo_display.exo_active):
self.check_keys()
self.exo_display.update_inputs()
if self.exp_stage == 'wait':
self.wait_for_start()
elif self.exp_stage == 'run':
self.run_t... |
def getDistanceToCenterLine(state, currentRoadBlockIndex):
currentBlockCenter = roadBlocks[currentRoadBlockIndex]
if currentRoadBlockIndex != 0 and currentRoadBlockIndex not in cornerBlockIndices:
#Case 1: road continues in the x direction -> z stays the same
if currentBlockCenter[1] == roa... | The function `getAgentInputs` computes and returns a list of seven parameters representing a vehicle's state and environment for decision-making. These include speed magnitude (a), acceleration (b), turning rate (c), distance to the centerline (d), angle to the centerline (e), distance to the next turn (f), and the dir... | def getAgentInputs(state, currentRoadBlockIndex, prevSpeed):
a = (state.velocity[0]**2 + state.velocity[2]**2)**0.5
b = a - prevSpeed
c = state.scene_mobil.turning_rate
d = getDistanceToCenterLine(state, currentRoadBlockIndex)
e = getAngleToCenterline(state, currentRoadBlockIndex) #???
f = ... |
def readFilePoints(path) :
# Create an array of points.
points = [];
# Read points
with open(path) as file :
for line in file :
x, y = line.split()
points.append((int(x), int(y)))
return points
def getDelaunayTri(allPoints, images):
# Dimensions of output imag... | The code performs morphing between two images by blending corresponding points using Delaunay triangulation. It reads input images and their point coordinates, computes weighted averages of points based on alpha, generates a triangulated mesh, and morphs each triangle by interpolating vertices and pixels. The result is... | def morph(img1Name,img2Name, alpha):
try:
# Read images
img1 = cv2.imread(img1Name);
img2 = cv2.imread(img2Name);
# Convert Mat to float data type
img1 = np.float32(img1)
img2 = np.float32(img2)
# Read array of corresponding points
points1 = readFilePo... |
def findDistPointLine(point, line):
return findPointDistance(point, findNearestPoint(point, line));
def isInsideTriangle(A, B, C, p):
if(
(sideOfLinePointIsOn((A,B), p) > 0) and
(sideOfLinePointIsOn((B,C), p) > 0) and
(sideOfLinePointIsOn((C,A), p) > 0)):
return True
def sideOfLinePointIsOn(lin... | This code computes the convex hull of a set of points using a recursive divide-and-conquer approach. It identifies the furthest point from a line segment PQ, adds it to the hull, partitions remaining points into subsets based on their position relative to lines formed by the furthest point, and recursively processes th... | def findHull(Sk, P, Q):
if(len(Sk) == 0): return
furthestPoint = Sk[0]
maxDist = 0
for x in Sk:
dist = findDistPointLine(x, [P, Q])
if(dist > maxDist):
maxDist = dist
furthestPoint = x
Sk.remove(furthestPoint)
hull.insert(1, furthestPoint)
... |
def gen_prime(n):
if n % 2 == 0:
n += 1
while True:
while not miller_rabin(n):
n += 2
if randint(0, 10) == 0:
return n
n += 2
def bit_len(a):
n = 0
while a > 0:
a >>= 1
n += 1
return n
def carmichael(p, q):
return lcm(p -... | The code generates an RSA key pair (public and private keys) using a specified bit length. It selects two primes `p` and `q` with a randomized bit offset to ensure balanced sizes, computes the modulus `n = p * q`, calculates the Carmichael function of `n` (instead of Euler's totient), determines a public exponent `e` c... | def rsa_gen(bits):
bit_offset = randint(0, bits // 16)
p = gen_prime(randint(2 ** (bits//2 - bit_offset), 2 ** (bits//2 - bit_offset + 1)))
q = gen_prime(randint(2 ** (bits//2 + bit_offset), 2 ** (bits//2 + bit_offset + 1)))
print('p =', p)
print('q =', q)
n = p * q
print(bit_len(n), 'bits'... |
def split64(x):
return x >> 32, x & bit_mask(32)
def feistel(xL, xR, P, S):
"""
Blowfish Feistel network
:type xL: int
:type xR: int
:param xL: left 32 bit half
:param xR: right 32 bit half
:param P: P array
:param S: S box
:return: xL, xR
"""
for i in range(16):
... | The function `encrypt` performs a Feistel network encryption on a 64-bit input word `x` using permutation `P` and substitution box `S`. It splits `x` into two 32-bit halves, applies a Feistel round (likely involving substitution, permutation, and mixing operations via `P` and `S`), and recombines the halves to produce ... | def encrypt(x, P, S):
"""
Encrypt 64 bit word
:type x: int
"""
xL, xR = split64(x)
xL, xR = feistel(xL, xR, P, S)
return merge64(xL, xR) |
def split64(x):
return x >> 32, x & bit_mask(32)
def feistel(xL, xR, P, S):
"""
Blowfish Feistel network
:type xL: int
:type xR: int
:param xL: left 32 bit half
:param xR: right 32 bit half
:param P: P array
:param S: S box
:return: xL, xR
"""
for i in range(16):
... | The function `decrypt` decrypts a 64-bit ciphertext using a Feistel network structure. It splits the input `x` into left (`xL`) and right (`xR`) halves, applies the `feistel` operation with reversed permutation `P` and substitution boxes `S`, then merges the transformed halves back into a 64-bit plaintext. The reversal... | def decrypt(x, P, S):
"""
Decrypt 64 bit ciphertext
:type x: int
"""
xL, xR = split64(x)
xL, xR = feistel(xL, xR, tuple(reversed(P)), S)
return merge64(xL, xR) |
def generate(key):
"""
Generate subkeys
:param key: 32 bit word array
:return: P, S
"""
P = list(PARRAY)
S = [list(box) for box in SBOX]
for i in range(18):
P[i] ^= key[i % len(key)]
xL, xR = 0, 0
for i in range(0, 18, 2):
xL, xR = feistel(xL, xR, P, S)
... | The code verifies encryption and decryption processes by comparing actual outputs with expected values. It generates keys (P, S) from the input key `k`, encrypts plaintext `p` to produce `crypt`, then decrypts `crypt` to retrieve `plain`. If `crypt` mismatches the expected ciphertext `c` or `plain` differs from `p`, th... | def test(k, p, c):
"""
Verify encryption and decryption
:type k: int
:type p: int
:type c: int
:param k: key
:param p: plaintext
:param c: expected ciphertext
:return: False if test failed
"""
P, S = generate(key_arr(k))
crypt = encrypt(p, P, S)
plain = decrypt(crypt... |
def _check_keydown_event(self, event):
"""Check the keys that was pushed"""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame. K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
... | This method handles Pygame events by checking for quit requests, keyboard input (keydown/up), and mouse clicks. It exits the game on quit, triggers key-specific actions, and checks if the play button is clicked when the game is inactive, using mouse position data to initiate gameplay. | def _check_events(self):
"""Respond to the pushed keys and other events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_event(event)
elif event.type == ... |
def _check_army_edge(self):
"""Check if army reached the edges of screen, change direction if it's so"""
for alien in self.aliens.sprites():
if alien.edge_touching():
self._change_army_direction()
break
def _ship_destroy(self):
"""Respond when ship is ... | This method updates alien positions by checking edges, updating their movement, detecting collisions with the player's ship (triggering a ship destruction response if collided), and verifying if any aliens have reached the screen's bottom to handle game logic accordingly. | def _update_aliens(self):
"""Update aliens position"""
self._check_army_edge()
self.aliens.update()
# Find the aliens that touch the ship, start game with new live if so
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_destroy()
# Look f... |
def _check_events(self):
"""Respond to the pushed keys and other events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_event(event)
elif event.type == ... | The main task of the code is to run the game loop by continuously checking events, updating game elements (ship, bullets, aliens, upgrades) when the game is active, rendering the screen, and limiting the frame rate to maintain performance. The loop ensures real-time interaction, motion, and visual updates for an engagi... | def run_game(self):
"""All the processes run here"""
while True:
self._check_events()
if self.stats.game_active:
self.ship.move_update()
self._update_bullets()
self._update_aliens()
self._update_upgrades()
... |
def clear_grid():
for i, j, k in grid_m:
grid_v[i, j, k] = [0, 0, 0]
grid_m[i, j, k] = 0
grid_v.grad[i, j, k] = [0, 0, 0]
grid_m.grad[i, j, k] = 0
grid_v_out.grad[i, j, k] = [0, 0, 0]
def clear_SVD_grad():
zero = ti.Matrix.zero(ti.f32, dim, dim)
for i in range(0, n_pa... | The main task of the code is to perform backward computation in a neural network or optimization process, involving clearing grids/SVD gradients, computing temporary values, executing SVD, and grid-point conversions. It calculates gradients for each operation (grid operations, SVD, and temporary value computation) to p... | def backward(s):
clear_grid()
clear_SVD_grad()
compute_F_tmp(s)
svd()
p2g(s)
grid_op(s)
g2p(s)
g2p.grad(s)
grid_op.grad(s)
p2g.grad(s)
svd_grad()
compute_F_tmp.grad(s) |
def get_bat(self):
battery = psutil.sensors_battery()
try:
plugged = battery.power_plugged
except AttributeError:
logger.exception("No Battery was found.")
percent = int(battery.percent)
return (percent, plugged)
def _notify(self, percent):
if not ... | The code's main task is to monitor battery status by retrieving the current percentage and charging state. It triggers a notification if the battery falls below a specified threshold while not charging, then updates internal configurations and visually renders the battery's current state based on the retrieved data. | def update(self):
percent, charging = self.get_bat()
if self.notify and percent < self.warn_below and not charging:
self._notify(percent)
self.configure_(percent, charging)
self.draw_battery(percent, charging) |
def get_bat(self):
battery = psutil.sensors_battery()
try:
plugged = battery.power_plugged
except AttributeError:
logger.exception("No Battery was found.")
percent = int(battery.percent)
return (percent, plugged)
def configure_(self, percent, plugged):
... | The code's main task is to update and render a battery indicator by retrieving the current battery percentage and charging status, configuring the display with these values, and then drawing the battery state on the interface. | def draw(self):
percent, charging = self.get_bat()
self.configure_(percent, charging)
self.draw_battery(percent, charging) |
def UpdateTherapeuticCategoryForExistingData():
DailyMedId=''
ActiveIngredients=''
cursor = conn.cursor()
cursor.execute("select d.DailyMedId,ai.Active_Ingredient From Daily_Med_Data d left join Active_Ingredient ai on d.DailyMedId =ai.DailyMedId where d.Therapeutic_Updated_Status=0")
rows=cursor.fe... | The main task of the code is to synchronize offline data by updating therapeutic categories, sales data, USFDA data, and patent exclusivity information for existing records. It executes four specific update functions and returns a JSON response indicating successful synchronization with a status code of 200. | def updateTherapeuticCategory():
UpdateTherapeuticCategoryForExistingData()
UpdateSalesDataForExistingData()
UpdateUsfdaDataForExistingData()
UpdatePatentExclusivityForExistingData()
return jsonify({'statusCode':'200', 'message':'Offline data synced sucessfully'}) |
def get_publications_entries_to_process(db_records: List[ProcessedEntry], service_name: str, min_spec_version: str) -> List[ProcessedEntry]:
"""Return all the publications in the database that needs to be processed by a service (i.e. not just for the partition)"""
publications_entries_to_process = []
for r... | The main task of the code is to process a batch of partitioned files using specified services (GROBID, SoftCite, DataStet), download relevant files from a storage system, execute processing tasks, update a database with results, and log the total runtime. It filters files based on UUIDs from database records, coordinat... | def create_task_process(partition_files, spec_grobid_version, spec_softcite_version, spec_datastet_version):
logger_console.debug(f"Call with args: {partition_files, spec_grobid_version, spec_softcite_version, spec_datastet_version}")
_swift = Swift(config_harvester)
db_handler: DBHandler = DBHandler(engine... |
def load_detection_anno(self, img, index):
if self.training:
gt_path = self.data[index].replace('all_images', 'all_gts').replace('jpg', 'txt')
bboxes = get_anno(img, gt_path)
##################### test #####################
else:
gt_path = self.data[index].re... | The code loads an image, its ground truth, structure data, and applies augmentations during training. It converts data to tensors and returns them along with metadata for model input processing. | def load_item(self, index):
size = self.input_size
# load image
img = cv2.imread(self.data[index])
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
name = self.data[index]
gt = cv2.imread(self.data[index].replace('all_images', 'all_labels'))
gt = cv2.cvtColor(gt, cv... |
def get_title(element):
title= ''
try:
# Finding all instances of tag
e_title = element.find('titleStmt')
if e_title == None:
return ''
e2 = e_title.find('title')
if e2 == None:
return ''
title = str(e2.te... | The main task of the code is to parse a TEI XML file, extract structured data such as title, abstract, and sections, and convert it into a JSON object. The function reads the file, identifies the file ID, uses BeautifulSoup to parse XML content, and populates a dictionary with extracted information. It returns a JSON-l... | def process_tei_file(file):
# Reading the data inside the xml file to a variable under the name data
with open(file, 'r') as f:
data = f.read()
file_id = file.split('/')[-1].replace('.tei.xml','')
my_json={}
# Passing the stored data inside the beautifulsoup parser
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.