dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def _add_to_write(self, text: str):
self.assembly_command.append(text+"\n")
def write_push_pop(self, command: CommandNameEnum, segment: str, index: int) -> None:
"""
Writes to the output file the assembly code that implements the given command
:param command: C_PUSH or C_POP
:par... | This function initializes a new function by setting its local segment (LCL) to the current stack pointer (SP) and pushing `num_vars` zero values onto the stack. It labels the function with the given name and handles stack setup for variable initialization in a virtual machine environment. | def write_function(self, function_name: str, num_vars: int) -> None:
"""
Responsibilities:
1. Sets up the local segment of the called function
> push n_vars zero on to stack and set stack pointer to LCL
:param function_name:
:param num_vars:
:return:
"""... |
def _add_to_write(self, text: str):
self.assembly_command.append(text+"\n")
def write_push_pop(self, command: CommandNameEnum, segment: str, index: int) -> None:
"""
Writes to the output file the assembly code that implements the given command
:param command: C_PUSH or C_POP
:par... | This method generates assembly code to handle function returns by copying the top stack value to argument 0, restoring caller's segment pointers (THAT, THIS, ARG, LCL), setting the return address, adjusting the stack pointer, and jumping back to the return address. It systematically saves and restores state variables, ... | def write_return(self) -> None:
"""
Responsibilities:
1. Copy top most value of stack to arg 0
2. Restore segment pointers of the callers
3. Clear the stack
4. Sets SP for the caller (one above arg0)
5. Jumps to the return address within the code
:return:
... |
def overNineCheckerAm(time):
#Checks if the extra hour is it gonna make it go from 9 to 10
if int(time[1]) < 9:
time[1] = str(int(time[1]) + 1)
time[-1] = '0'
time[-2] = '0'
#Checks if time goes from 11 AM to 12 PM
hour = amToPmDetector(time)
return hour
#Defa... | The code adjusts input time strings to round to the nearest hour, handling both AM/PM formats. It ensures proper leading zeros, parses time components, and uses helper functions to round up/down based on minute values (≥30 rounds up, <30 rounds down). The function returns adjusted hour-minute pairs in a standardized fo... | def time_fixer(hour):
#hIn is the inputed time in list format
hIn = list(hour.upper())
#Check if the input has 00:00, if not add the 00
if len(hIn) <= 7:
hIn.insert(0, '0')
#Check if time is AM
if 'A' in hIn:
del hIn[-3:]
#Check if time is roundable to th... |
def check_validity_path(self) -> None:
"""
If the path is a file, create the parent directory if it doesn't exist. If the path is a directory, create the
directory and set the path to the default file name
"""
if self.json_path:
if Path(self.json_path).suffix:
... | The code processes data by validating paths, setting up a Gensim model, verifying input, determining top concepts, and iteratively expanding concepts while resolving overlaps. It refines conceptual patterns, sets a concept dictionary, cleans up resources, and converts data keys to uppercase for standardized output. | def run(self) -> None:
self.check_validity_path()
self.set_gensim_model()
self.verify_data(self.verbose)
self.determine_topn()
self.expand_concepts()
# settle words around overlapping concepts
for _ in range(5):
self.expand_concepts()
self.... |
def set_exclude_pos(self, exclude_pos: list):
if exclude_pos is None:
exclude_pos = [
"VERB",
"AUX",
"ADP",
"DET",
"CCONJ",
"PUNCT",
"ADV",
"ADJ",
"PART",
... | This code initializes an entity matching system using spaCy, configuring synonym rules, POS/exclusion filters, and entity scoring. It sets up data structures for text processing, handles model integration, and prepares pipelines for entity recognition with customizable parameters like case sensitivity, compound words, ... | def __init__(
self,
nlp: Language,
data: dict = {},
model: Union[str, FastText, KeyedVectors, Word2Vec] = None,
topn: list = None,
word_delimiter: str = "_",
ent_score: bool = False,
exclude_pos: list = None,
exclude_dep: list = None,
inclu... |
def view():
current_health = character_stats.iat[0,0]
max_health = character_stats.iat[0,1]
current_magic = character_stats.iat[1,0]
max_magic = character_stats.iat[1,1]
armor = character_stats.iat[2,0]
current_gold = character_stats.iat[3,0]
print("\n---------- | Character Stats | ---------... | This code provides a menu-driven interface for a character sheet, allowing users to view stats, rest, take damage, heal, check money, or exit. It loops until "exit" is selected, handling commands by calling respective functions and validating input. | def access():
while (using == 1):
print ("Welcome to the Character Sheet")
print ("view | rest | hurt | heal | money | exit")
command = input('-->')
if command == "view":
view()
elif command == "rest":
rest()
elif command == "hurt":
... |
def extractReferences(text):
data = text.split('\n')
refs = []
for line in data:
if re.search(r'<ref', line):
refs.append(re.sub(r'.*title[\ ]*=[\ ]*([^\|]*).*', r'\1', line))
data = tokenize(' '.join(refs))
data = removeStopWords(data)
data ... | The code processes input text by splitting it into sections, extracting components like title, body, infobox, categories, links, and references. It performs case folding, handles different reference separators, and returns structured data for further use. | def processText(text, title):
text = text.lower() #Case Folding
data = text.split('==references==')
if len(data) == 1:
data = text.split('== references == ')
if len(data) == 1:
references = []
links = []
categories = []
els... |
def next(event):
global filelabel
global filename
basename = os.path.basename(filename).split('_', 1)
basename = basename[-1]
if (filelabel != slabel.val):
_zw = os.path.join(os.path.dirname(filename), "{:.1f}".format(slabel.val) + "_" + basename)
... | This code defines a keyboard event handler that triggers specific actions based on key presses: 'right' and 'enter' navigate forward, 'left' navigates backward, 'up'/'down' adjust a label's value, and 'delete' removes an item. The function maps key inputs to operations like navigation, modification, or deletion, enabli... | def on_press(event):
# print('press', event.key)
if event.key == 'right':
next(event)
if event.key == 'left':
previous(event)
if event.key == 'up':
increase_label(event);
if event.key == 'down':
decrease_label(event)
if event... |
def improve_starting_location(location):
url = "https://transit.api.here.com/v3/stations/by_geocoord.json"
url += "?app_id=inyah45axuPunUzafruc"
url += "&app_code=dSeR84rhEUZEwBEV1NVGaA"
url += "¢er=" + location
url+="&radius=1000" # radius in meters
url+="&max=1"
contents = urllib.requ... | The function identifies optimal meeting points by processing isochrone data from multiple starting locations, aggregating and optimizing results to select the best options based on weighted criteria, and returning corresponding locations from API responses. | def optimal_meeting_points(arrival_time, starting_locations,topic=""):
starting_locations=[improve_starting_location(loc) for loc in starting_locations]
arrival_time = dateutil.parser.parse(arrival_time)
#todo #print([generate_bundle_set(arrival_time,starting_location) for starting_location in starting_loc... |
def __advance(self) -> Token:
self.__current += 1
return self.__tokens[self.__current - 1]
def __note(self, note_letter_token:Token) -> bool:
note_num = 69
divisor = 1
duration = 1
# Parse note letter.
note_letter = str(note_letter_token.value)
if note_le... | This method parses the next token in a music notation parser, handling note letters, rests, octave changes, and BPM changes. It advances the token, checks its type, and delegates processing to corresponding private methods. If any operation fails or an unexpected token is encountered, it returns False or an error messa... | def __parse_next_token(self) -> bool:
t = self.__advance()
if t.token_type == NOTE_LETTER:
if not self.__note(t):
return False
elif t.token_type == REST:
if not self.__rest(t):
return False
elif t.token_type in {OCT_UP, OCT_DN}:
... |
def __advance(self) -> str:
self.__current += 1
self.__current_col += 1
return self.__text[self.__current - 1]
def __newline(self, c:str):
self.__current_col = 0
self.__current_ln += 1
# Consume second control character if using Windows line endings.
if c == '\r'... | This function scans the next token from input, handling whitespace, line breaks, comments, symbols (like ~, _, +, -, >, <, @), numeric values, and note letters (a-g). It adds appropriate tokens to the parser or raises an error for unrecognized characters, returning True on success and False on error. | def __scan_next_token(self) -> bool:
c = self.__advance()
if c == ' ' or c == '\t':
pass
elif c in {'\r', '\n'}:
self.__newline(c)
elif c == '#':
self.__comment()
elif c == '~':
self.__tildes()
elif c == '_':
se... |
def plot_inference_time_vs_patches(tflite=False, metric="inference_time"):
patches = []
all_metrics = metrics.get_metrics()
all_metrics = list(all_metrics.values())
all_metrics = list(filter(lambda met : met["tflite"]==tflite, all_metrics))
all_metrics.sort(key = lambda met : met["number_of_patches"... | The main task of the code is to generate plots comparing inference time and memory usage across different model configurations. It evaluates TFLite-optimized and standard models by plotting inference time versus patches, with variations in metrics and TFLite flags. Additionally, it analyzes peak memory consumption for ... | def main():
# model = tf.keras.models.load_model("models/vanilla3_testloss_0.891_epochs_15.h5")
# metrics.compute_metrics_for_model(model, 0.89, 1, False)
plot_inference_time_vs_patches(tflite=True)
plot_inference_time_vs_patches(tflite=False)
plot_inference_time_vs_patches(tflite=False, metric="blo... |
def generate_design_specs(requirements_filepath, design_specs_filepath):
if os.path.exists(design_specs_filepath):
print(f"Design Specification: {design_specs_filepath} -> already exists.")
return
if not os.path.exists(requirements_filepath):
print(f"Requirements: {requirements_filepat... | The code simulates a process where design specifications are generated from a requirements file, then developer tasks are created based on those specifications. The `development()` function likely executes or models the actual development phase using the generated tasks. The main task is to automate the creation of des... | def simulator():
generate_design_specs('requirements/chess_requirements.txt', 'gen/design_specification.json')
generate_developer_tasks('gen/design_specification.json', 'gen/developer_tasks.json')
development() |
def user_input():
input_info = '1234'
user_row = []
for i in range(4):
s = input_info[i] + ' row of letters: '
row = input(s).lower()
# check if format of user input is legal
if len(row) != 7:
print('Illegal input') # check length
return False
for j in range(7):
if j % 2 == 1 and row[j] != ' ':
... | The code measures the performance of a Boggle word-finding algorithm by reading user input, loading a dictionary, executing the algorithm to find valid words, and timing its execution. It outputs the total words found and the elapsed time to assess efficiency. | def main():
"""
TODO:
"""
while True:
row = user_input()
if row is False:
break
word_set = read_dictionary(row)
start = time.time()
####################
all_word = set()
start_point(all_word, row, word_set)
print('There are ', len(all_word), ' words in total.')
####################
end = time... |
def game_over_look(self,matrix):
"""
Check if game is over by checking if the player has already won(if 2048 has been achieved) or if no moves can be made (No empty cells and no combinations possible).
Args:
matrix (2D List): Game grid
"""
if any(2048 in row for row ... | The main task of the code is to check if a gameover state is reached using `game_over_look`. If not, it generates the next possible game states by moving the game piece in all four directions: left, right, up, and down. | def checknext(self):
"""
Check if a gameover state is reached. If not, make the next 4 direction states.
"""
if self.game_over_look(self.gamegrid)==0:
return
self.moveleft()
self.moveright()
self.moveup()
self.movedown() |
def generate_amr_lines(f1, f2):
"""
Read one AMR line at a time from each file handle
:param f1: file handle (or any iterable of strings) to read AMR 1 lines from
:param f2: file handle (or any iterable of strings) to read AMR 2 lines from
:return: generator of cur_amr1, cur_amr2 pairs: one-line AMR... | The function `score_amr_pairs` scores alignment between AMR (Abstract Meaning Representation) pairs from two files by comparing triples (instances, attributes, relations). It iterates through AMR lines from `f1` and `f2`, calculates matching triples, and accumulates statistics (matches, test triples, gold triples). It ... | def score_amr_pairs(f1, f2, justinstance=False, justattribute=False, justrelation=False):
"""
Score one pair of AMR lines at a time from each file handle
:param f1: file handle (or any iterable of strings) to read AMR 1 lines from
:param f2: file handle (or any iterable of strings) to read AMR 2 lines f... |
def _check_keydown_events(self, event):
# check for right and left arrow keys to guide direction of the
# ship, space bar to fire bullets and 'q' key to quit the game
# we set the moving left and right flags so that ship continuously
# moves left or right until keyup event is detected t... | The main task of the code is to detect and handle keyboard and mouse events in a Pygame application. It processes events such as quitting the game, key presses, key releases, and mouse button clicks. When the quit event is detected, the game exits. Keydown and keyup events trigger corresponding methods for input handli... | def _check_events(self):
# detect keyboard and mouse events - cycle through events returned
# from pygame event get function - we look for quit, keydown and
# keyup events
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
... |
def _check_fleet_edges(self):
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
self.sb.prep_ships()
... | This method updates alien movement, checks for collisions between the ship and aliens, and verifies if aliens have reached the screen's bottom. It triggers collision responses and boundary checks to manage game interactions and potential game-over conditions. | def _update_aliens(self):
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
print("Ship hit")
self._ship_hit()
self._check_aliens_bottom() |
def _check_events(self):
# detect keyboard and mouse events - cycle through events returned
# from pygame event get function - we look for quit, keydown and
# keyup events
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
... | The main task of the code is to run the game loop, continuously checking for events, updating game elements (ship, bullets, aliens) when the game is active, and rendering the screen to maintain gameplay and visuals. | def run_game(self):
# main loop for the game
while True:
self._check_events()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen() |
def py__annotations__(funcdef):
dct = {}
for function_param in funcdef.get_params():
param_annotation = function_param.annotation
if param_annotation is not None:
dct[function_param.name.value] = param_annotation
return_annotation = funcdef.annotation
if return_annotation:
... | The function `infer_return_types` determines a function's return type using type annotations. It first checks Python 3-style annotations, then falls back to Python 2-style comments if absent. It resolves unknown type variables, evaluates annotations, and constructs a `ContextSet` of inferred types. The task involves pa... | def infer_return_types(function_execution_context):
"""
Infers the type of a function's return value,
according to type annotations.
"""
all_annotations = py__annotations__(function_execution_context.tree_node)
annotation = all_annotations.get("return", None)
if annotation is None:
#... |
def _get_min_clustering_cost(self, clustering: dict) -> float:
"""
Calculates the min total cost of a clustering configuration based on the lowest cost feature in each cluster.
:param clustering: A dictionary containing 'labels' which map to the cluster labels of each feature.
:return: ... | This method performs heuristic-based KMedoids clustering with a budget constraint, dynamically adjusting clusters if the clustering cost exceeds the allowed budget. It iterates over epochs, updating configurations and returning cluster labels, medoid indices, and locations if the heuristic completes successfully, or No... | def _execute_heuristic(self, k: int) -> Optional[dict]:
"""
Performs a heuristic-based KMedoids clustering on the provided dataset with a specified number of clusters (k).
This method tries to optimize the clustering process under a predefined budget constraint over several epochs.
It d... |
def _get_selected_medoids_cost(self, k: int) -> float:
"""
Computes the total cost of medoids for the specified number of clusters (k).
:param k: The number of clusters.
:return: The total cost of medoids for the given number of clusters.
"""
return sum(
list... | The main task of the code is to execute a heuristic process to find a subset of valid features within a budget. It iterates from a 'knee_value' down to 2, checking if the cost of 'k' features fits the budget. If not, it applies a heuristic to seek a viable solution. If successful, it returns the selected features; othe... | def run(self) -> Optional[dict]:
"""
Executes the heuristic process. Iterates from 'knee_value' found down to 2 to find a subset of new valid
features within the budget using a heuristic approach. For each 'k':
- If the cost of the 'k' cheapest features exceeds the budget, it continues t... |
def generate(out_dir, i, regex):
try:
pr = parenthesize(regex)
posix = to_posix(regex)
inp = generate_examples(posix)
out = grep_eval(posix, inp)
write_examples(out_dir, f"{i:04d}", pr, inp, out)
except Exception:
print(regex)
raise
def explicit_concat_o... | The code processes a source file by generating outputs in two ways: first, it applies an explicit concatenation operation to each line and saves results in a 'generated' directory. Then, it uses parallel processing with regex patterns to generate additional outputs, leveraging multi-core CPUs for efficiency. | def main():
src = Path(sys.argv[1])
out_dir = src.with_name("generated")
out_dir.mkdir(parents=True)
i = -1
with src.open() as f:
for i, line in enumerate(f):
generate(out_dir, i, explicit_concat_op(line.rstrip()))
regexes = _all_regexes()
Parallel(n_jobs=os.cpu_count()... |
def gui_container(self):
pass
def draw_window(self):
self.screen.fill((100, 100, 100))
self.draw_terrain()
boot.blit_text(
'main_titles',
[self.grid['start_x'][10], self.grid['start_y'][340]],
(255, 255, 255),
self.fonts,
'Stag... | The main task of the code is to run a loop that continuously draws the window and handles events while the application is running. The loop terminates when VARS.RUNNING becomes false, returning -1 to indicate exit. | def main_loop(self):
self.gui_container()
while VARS.RUNNING:
self.draw_window()
event_decisions = self.event_handle()
if not VARS.RUNNING: return -1 |
def get_display_grid(display_size):
whole_numbers = {}
for i in range(1, 50):
width = round(display_size[0] / i, 1)
height = round(display_size[1] / i, 1)
square_name = str(round(width, 0)) + ':' + str(round(height, 0))
if width.is_integer() and height.is_integer():
... | This code initializes a Pygame display window with a resolution from predefined settings, sets up a grid layout, scales fonts to match the display size, initializes mouse position tracking, and starts the application's menu loop as the initial state. | def __init__(self):
disp_size = VARS.APPROVED_RESOLUTIONS[VARS.CRT_REZ]
self.screen = pygame.display.set_mode(disp_size)
self.grid = get_display_grid(disp_size)['80.0:45.0']
self.fonts = scale_fonts(disp_size)
self.mouse_pos = None
self.state = self.menu_loop() |
def create_display_frame(self):
frame = Frame(self.window, height=221, bg="#F5F5F5")
frame.pack(expand=True, fill="both")
return frame
def create_display_labels(self):
total_label = Label(self.display_frame, text=self.total_expression, anchor=E, bg="#F5F5F5", fg="#000000", padx=24, f... | This code initializes a Tkinter-based calculator GUI, setting up the window, display labels for expressions, digit buttons, operation buttons, and their grid layouts. It configures the interface with proper sizing, positions buttons using a grid system, and binds keyboard inputs for interaction. | def __init__(self):
self.window = Tk()
self.window.geometry("375x667")
self.window.resizable(0,0)
self.window.title("Calculator")
self.total_expression = ""
self.current_expression = ""
self.display_frame = self.create_display_frame()
self.total_label, s... |
def getCurrentPop(self):
x = 0
for species in self.population:
x += species.size()
return x
def eliminateWorstPerforming(self, species: Species, numEliminate):
numEliminate = math.floor(min(species.size()-2, numEliminate))
if numEliminate <= 0:
return
... | This code evaluates the fitness of neural networks in a population, eliminates underperforming members based on fitness, and reproduces new individuals through crossover. It calculates total fitness, determines elimination quotas, and generates offspring proportional to species' fitness. Species with insufficient offsp... | def run(self):
for species in self.population:
numPerfect = 0
for netNum in range(species.size()):
fitness = self.environment.eval_train(species.nets[netNum])
if fitness >= PERFECT_FITNESS:
numPerfect += 1
species.fitnes... |
def mutate_add_edge(self):
validConfig = False
numNodes = len(self.nodes)
numHidden = numNodes - (self.numInputs +
self.numOutputs+2*self.numRNN)
tries = 0
while not validConfig:
# Give up if can't find
tries += 1
... | This function adds a new node to a neural network by splitting a randomly selected enabled edge. It disables the original edge, generates a new node with an innovation number, and creates two new edges connecting the original nodes through the new node. The process ensures valid configurations within a limit of attempt... | def mutate_add_node(self):
if(len(self.edges) == 0):
self.mutate_add_edge()
return
validConfig = False
tries = 0
while not validConfig:
tries += 1
if(tries > min(len(self.edges), MAX_CYCLES_ADD_NODE)):
return
# G... |
def split_df_by_day_of_week(intraday_minute_bars_df: pd.DataFrame) -> dict:
'''
Split the intraday minute bars by day of the week. Return a dict where each key is the number of the day of the week and
the value is a dataframe containing the rows of intraday_minute_bars corresponding to that particular day o... | The function analyzes intraday price changes by grouping data by day-of-week, month, and year. It calculates average price changes at each minute after the open, then computes temporal statistics using these averages and the dataset's median price change at the 59th minute. Results are returned as grouped statistics fo... | def analyze_open_type(intraday_minute_bars_df: pd.DataFrame) -> pd.DataFrame:
median_cfo_value_at_t_sixty_for_whole_dataset = intraday_minute_bars_df[intraday_minute_bars_df[
'Open Minutes Offset'] == 59]['Price Change From Intraday Open'].median()
# Split our dataframes apart in grouping the day, month... |
def contract_month_and_year_from_file_name(filename: str) -> str:
settlement_data_month_and_year = filename[-9:-4]
settlement_data_contract_month = settlement_data_month_and_year[0]
settlement_data_contract_year = settlement_data_month_and_year[1:]
return settlement_data_contract_month + settlement_data... | The main task of the code is to process settlement data from multiple CSV files, calculate volatility metrics (e.g., count of data points and price ranges over 7-day, 30-day, and 365-day periods), and compile these into a structured DataFrame. It extracts contract metadata, filters historical data for each date, comput... | def process_settlement_volatility(
settlement_csv_filenames: List[str],
):
all_dates_metadata = []
for item_index in trange(len(settlement_csv_filenames)):
filename = settlement_csv_filenames[item_index]
contract_month_and_year = contract_month_and_year_from_file_name(
filename)
... |
def gather_data(barangays, orders):
"""
Load data for barangays and orders from Google Sheets.
Args:
barangays (dict): A dictionary containing 'sheet_id' and 'tab' for barangays data.
orders (dict or None): A dictionary containing 'sheet_id' and 'tab' for orders data, or None.
Returns:... | The main task of the code is to geocode barangay data by retrieving coordinates, merge them with orders data if provided, handle missing coordinates through a review process, and return a cleaned DataFrame with geocoded results, a review log, and an error message if applicable. | def geocode_by_barangay(barangays,orders=None):
"""
Perform geocoding for barangays and orders data.
Args:
barangays (dict): A dictionary containing 'sheet_id' and 'tab' for barangays data.
orders (dict or None): A dictionary containing 'sheet_id' and 'tab' for orders data, or None.
Re... |
def gather_variables(mechanics_count_redash : str,
appointments_source : (str, pd.DataFrame) =' sample_appointments.csv') -> tuple:
"""
Gathers variables including hub data, hub mechanics, and appointments from different sources.
Args:
-----
- mechanics_count_redash : str
... | This function clusters and assigns appointments to service hubs using algorithms, returning a DataFrame of assigned appointments, a similarity score, updated mechanics counts per hub, and hub service data. It processes input data, calculates distances, applies clustering, maps labels to hubs, initializes mechanics, run... | def cluster_appointments(appointments_source, config, init_mechanics_dict):
"""
Cluster and assign appointments to service hubs based on various algorithms.
Args:
appointments_source (str): Path to the source file containing appointment data.
config (dict): Loaded dictionary of configuratio... |
def map_cui(self, ref):
cui_encode = dict()
with torch.no_grad():
for cui in ref.keys():
cui_encode[cui] = self.model(self.tokenize(ref[cui])).cpu()
if self.embbed_size == None:
... | This code trains a neural network model using cosine similarity loss between mention and label embeddings. It performs backpropagation, tracks training/validation loss and MAP@k metrics, logs results to TensorBoard, and saves checkpoints periodically. The model ranks candidates against CUI-encoded references, evaluatin... | def train(self):
# self.basenorm.train()
self.model.train()
# Train
start_time = time.time()
for epoch in range(self.config.epochs):
epoch_loss = 0
train_map = 0
idx = ... |
def getX(dataTab):
y = getY(dataTab)
xLen = xLen = y.size
x = numpy.arange(xLen)
#y = y.reshape(-1, 1)
x = x.reshape(-1, 1)
return(x)
def getY(dataTab):
data = dataTab
data = data["Close"]
y = numpy.array(data)
return(y)
def getModel(dataTab):
x = getX(dataTab)
y = g... | The main task of the code is to calculate the coefficient of determination (R²) for a given dataset. It retrieves features (x) and target variable (y) from the input data, trains a model using getModel(), and computes the R² score by comparing the model's predictions against the actual target values. The function retur... | def getR2(dataTab):
x = getX(dataTab)
y = getY(dataTab)
model = getModel(dataTab)
rSqVal = model.score(x, y)
return(rSqVal) |
def get_gene_name(gene_id):
'''Handles the extraction of gene names for various gene sources.
:param gene_id: (str) the entity id
:return: (str) the extracted name or None if a name could not be found
'''
# case: the gene's id is actually it's name
if gene_id.startswith("N"): #DOES A GENEID STARTING WITH N MEAN ... | This function retrieves the name of an entity (gene, compound, or disease) based on its ID and type by calling specific helper functions. It returns the extracted name or None if the entity type is unsupported or no name is found. | def get_entity_name(nid, ntype):
'''Extracts a name for the given entity id.
Currently handles only genes, compounds, and diseases.
:param nid: (str) the entity id
:param ntype: (str) the entity type
:return: (str) the extracted name or None if a name could not be found
'''
if ntype == "Gene":
name = get_gene_... |
def read_from_named_entities_files():
'''Reads in the list of entities that we have already named.
:return: (list) the list of ids of entity which are already named
'''
named_entities = []
for file in named_files.values():
with open(file, 'r', encoding="utf-8") as f:
for line in f:
try:
nid, name = ... | The function `get_all_entity_names` extracts names for entities (genes, compounds, diseases) from a knowledge graph (KG) based on entity IDs and sources. It skips already named or previously failed entities, processes remaining entities of target types, attempts to retrieve their names, and updates the KG or logs failu... | def get_all_entity_names(update_kg=True):
'''Names all entities in the graph (or at least attempts to). Extracts any entity names that it can based on the entity id and source database.
Currently, this only covers most compounds, diseases, and genes.
:param update_kg: (boolean) True if the extracted names should be... |
def get_save_location(sample_rate: int, extension: str, is_speech: bool = False) -> str:
"""Get relative file path to save new processed audio clip
Args:
sample_rate (int): sample rate of processed audio clip.
extension (str): file extension to save as, e.g. ".mp3".
is_speech (bool, opt... | This function preprocesses audio files by splitting them into fixed-length segments, saving each segment with type-specific paths (speech/music), and generating precomputed data for the DNNDataset used in DeGLI. It processes audio from a directory, respects file/clip limits, and returns counts of processed files and cl... | def _preprocess_audio(
src_path: str = "data/orig_audio",
src_limit: int = None,
segment_limit: int = None,
) -> tuple[int, int]:
"""Process audio to be used in a dataset.
Duplicates will not be detected if run on the same audio again.
Splits audio into segments with fixed no. samples each, an... |
def clearConsole():
# This function simply clears the console to make the menu more readable
command = 'clear'
if os.name in ('nt', 'dos'): # If Machine is running on Windows, use cls
command = 'cls'
os.system(command)
def print_menu():
# This function prints the main menu, prompts the... | The code implements a menu-driven program that repeatedly displays options for creating a login, logging in, or exiting. It uses a loop to maintain the menu interface, executes corresponding functions based on user choices, and handles login validation. The loop terminates when the user selects an exit option. | def main():
keepGoing = True
while keepGoing:
clearConsole()
choice = print_menu()
if choice == "1":
createLogin()
elif choice == "2":
username = login()
print("You are now logged in as: ", username)
input("Press enter to continue.... |
def get(self, url, method='get', parse=False, **kwargs):
logger.debug(f'{method} {url}')
func = getattr(self.session, method)
kwargs.setdefault('timeout', 60)
n_attempt = 5
while True:
try:
inline_logger(f'{method} {url}')
response = f... | The code handles user sign-in by fetching the sign-in page, prompting for credentials, submitting the form with provided username/email and password, and verifying successful authentication. It checks authorization status before and after submission, raising errors if authentication fails or form data is invalid. | def signin(self):
page = self.get('/signIn', parse=True)
if self.is_authorized(page):
return
username = input('username or email: ')
password = getpass.getpass('password (is not stored anywhere): ')
form = page.forms[-1]
form.fields['loginOrEmail'] = usernam... |
def clear_cache(self):
self.cache = {}
def suggest(self, username):
users = self.cache.get(username)
if not users:
data = self.post('/data/suggestUser', data={
'action': 'getRandomUsers',
'otherUserLogin': username,
'csrf_token': self.c... | This code creates a game by selecting participants from a list of users, handling queries to fetch users (suggest, top, random), ensuring unique usernames (or allowing duplicates), determining each user's strategy, and submitting the game creation request with participant details and strategies. | def create_game(self, users, formats, allow_duplicate_users):
game_params = {
'action': 'createGame',
'csrf_token': self.csrf_token,
'gameFormat': random.choice(formats),
}
self.clear_cache()
username_for_suggest = None
strategies = []
... |
def get_adults_table(top_dir):
"""
Function to build a dataframe of participant audio files that have had at
least one adult vocalization removed from them. Also notifies of any
unaccounted-for conditions.
Parameters
----------
top_dir : string
path to the top directory
... | The code processes audio files to remove adult speech by replacing it with ambient sounds. It generates a CSV of adult speech data, parses audio files, segments silences/sounds, applies masks, and replaces adult clips with ambient noise. The script handles directory navigation, file operations, and data organization fo... | def main():
# tasks = ["button", "vocal"]
# stranger = ["w", "no"]
top_dir = input("Top directory: ")
# top_dir = "/Volumes/Data/Research/CDB/openSMILE/audio_files/"
as_dir = os.path.join(os.path.dirname(os.path.dirname(top_dir)),
'adults_speak')
as_path = os.path.join(as_dir, 'adul... |
def initializeToken(self):
"""
Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
CREDENTIALS_FILE = './credentials.json'
creds = None
# The file token.pickle stores the user's access and refre... | The main task of the code is to retrieve Google Calendar events, identify busy time intervals, compute free time slots for each date in a specified range, and store/appended these free times in a dictionary. It adjusts date formats, initializes service access, processes event data to determine busy periods, iterates th... | def main(self):
date_1 = self.from_date
self.from_date += 'T00:00:00.000000Z'
date_2 = self.to_date
self.to_date += 'T23:59:59.599999Z'
#get the service
self.initializeToken()
if not self.service:
print('Service is not available')
retur... |
def verify_input_paramters(raid_data, module):
# Verifying input parameters
input_list = ["LogicalDriveName", "Raid", "DataDrives"]
drive_input = [
"DataDriveCount",
"DataDriveMediaType",
"DataDriveInterfaceType",
"DataDriveMinimumSizeGiB",
]
for raid in raid_data:
... | The main task of the code is to create logical drives via Redfish API by validating input parameters, checking existing drives, ensuring physical drive availability, and updating storage configuration with new RAID settings. It avoids redundant creation if drives already exist, handles errors, and returns new logical d... | def create_logical_drive(redfishClient, module):
# This function invokes the creation of logical drive.
# read raid_details from input
raid_data = module.params["raid_details"]
# verify input parameters
verify_input_paramters(raid_data, module)
# Get logical drives from server
logical_drives... |
def file_control():
out_dict = {"topology":topology(),
"pbc":pbc(),
"trajectories":trajectories()}
out_VBox = widgets.VBox([widgets.Label("File Control:"),
widgets.HBox([widgets.Label("topology: ", layout=Layout(width="100px")), out_dict["topology"... | The code creates a GUI for computing residue neighborhoods using IPython widgets. It combines file, contact, IO, and fragment controls into a layout with a "Compute residue neighborhoods" button. When clicked, it retrieves input values, validates them, and executes the residue_neighborhoods function with those paramete... | def screen():
run_button = widgets.Button(description="Compute residue neighborhoods")
ifile_control = file_control()
out_dict = ifile_control._gui_GUI_dict
icontact_control = contact_control()
out_dict.update(icontact_control._gui_GUI_dict)
iIO_control = IO_control()
out_dict.update(iIO... |
def findSet(self, x):
'''
Method of find and return the representative
node for cluster/tree containing x
'''
if x != self.metav[x]['p']:
self.metav[x]['p'] = self.findSet(
self.metav[x]['p'])
return self.metav[x]['p']
def findSetArcsWeight(self, x):
'''
Method to return sum of arc weights in
... | This method merges two clusters/trees via edge (x,y,w) using union-by-rank. It updates arc and node weight sums for the combined cluster, sets parent pointers based on rank comparison, and increments the rank of the resulting root when ranks are equal. The operation maintains metadata for connected components, ensuring... | def link(self, x, y, w):
'''
Method to update meta data for the two
clusters/trees being linked through edge (x,y,w)
depending upon rank
'''
if self.metav[x]['rank'] > self.metav[y]['rank']:
self.arcweightsum[self.findSet(x)] = \
self.findSetArcsWeight(x) \
+ self.findSetArcsWeight(y) + w
... |
def findSet(self, x):
'''
Method of find and return the representative
node for cluster/tree containing x
'''
if x != self.metav[x]['p']:
self.metav[x]['p'] = self.findSet(
self.metav[x]['p'])
return self.metav[x]['p']
def findSetArcsWeight(self, x):
'''
Method to return sum of arc weights in
... | The method `mstKruskal` implements a modified Kruskal's algorithm to construct cluster(s)/tree(s) by selecting edges while respecting constraints on total arc weight (`maxtreearcswt`) and node weight (`maxtreenodeswt`). It sorts edges by weight, checks if connecting nodes belongs to separate sets, calculates combined w... | def mstKruskal(self, maxtreearcswt, maxtreenodeswt):
'''
Method to execute modified Kruskal's
algorithm to create cluster(s)/tree(s)
'''
result = []
# sort edges based on their weight
self.graph = sorted(self.graph, key=lambda e: e[2])
for u,v,w in self.graph:
if self.findSet(u) != self.findSet(v):... |
def mstKruskal(self, maxtreearcswt, maxtreenodeswt):
'''
Method to execute modified Kruskal's
algorithm to create cluster(s)/tree(s)
'''
result = []
# sort edges based on their weight
self.graph = sorted(self.graph, key=lambda e: e[2])
for u,v,w in self.graph:
if self.findSet(u) != self.findSet(v):... | The code generates clusters using a modified Kruskal's algorithm, grouping connected components into trees. It processes edges from the minimum spanning tree, assigns arcs to clusters, identifies isolated nodes, and calculates total arc/node weights for each cluster. The result is a dictionary of clusters with arcs and... | def getClusters(self, maxtreearcswt, maxtreenodeswt):
'''
Method to call modified kruskal's and
retrive cluster(s)/tree(s) in to nice
format with additional information
on cluster/tree
'''
clusters = {}
connected = {v: False for v in self.V}
resultedges = self.mstKruskal(maxtreearcswt, maxtreenodes... |
def make_single_barplotpair(df, fname, col, ylabel, group_cols=["group", "year"]):
"""Plots bars with mean error indicators and p-values of t-tests for
comparison of the variable `col`.
"""
# Subset data
df = df[df[col] > 0]
mask = df["has_discussion"] == "With"
papers_with = df.loc[mask]
... | The main task of the code is to analyze and visualize data from academic presentations, comparing key metrics (duration, affiliation rank, and readability scores) between papers with and without discussions. It generates individual bar plots for each metric, performs statistical comparisons (t-tests), and combines four... | def main():
# Read presentations
df_cols = ["short", "has_discussion", "duration", "group", "year",
"Tilburg_Rank_weighted_auth", 'pres_flesch',
'pres_fleschkincaid', 'pres_gunningfog', 'pres_smog']
df = pd.read_csv(SAMPLE_FILE, usecols=df_cols)
df["has_discussion"] = df["h... |
def read_batch_job_config(self, content):
batch_job_config = re.search(r'configure_for_batchJob\{(.*?)\}', content, re.DOTALL)
# [ re.serach ] module will get the all content within configure_for_batchJob{ ... }
if not batch_job_config:
raise ValueError("configure_for_batchJob secti... | The code reads a configuration file, parses its content, and processes it into three specific configurations: batch job settings, output merger parameters, and batch job output scaler details. | def read_config(self, file_name):
with open(file_name, 'r') as file:
content = file.read()
self.read_batch_job_config(content)
self.read_outputMerger_config(content)
self.read_batchJobOutputScaler_config(content) |
def check_keydown_event(self, event, ship, ai_settings, bullets,screen):
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_SPACE:
self.fire_bullet(ai_settings,screen,shi... | This function handles user input events in a Pygame game. It processes keyboard presses (movement/shooting), releases, mouse clicks (play button), and exit commands. Key actions trigger methods to control the ship, manage bullets, start the game, and update game state, using parameters like ship, bullets, aliens, and s... | def check_events(self,button,stats,aliens,bullets,screen,ship,ai_settings,sb):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self.check_keydown_event(event,ship,ai_settings, bullets,screen)
... |
def check_fleet_edges(self,aliens,ai_settings):
for alien in aliens.sprites():
if alien.check_edges():
self.change_fleet_direction(aliens,ai_settings)
break
def ship_hit(self,aliens,ai_settings,screen,ship,stats,bullets,sb):
if stats.ships_left > 0:
... | The function updates alien movement, checks for collisions between the ship and aliens, and verifies if aliens have reached the screen's bottom, triggering responses like ship damage or game over conditions. | def update_aliens(self,aliens,ai_settings,screen,ship,stats,bullets,sb):
self.check_fleet_edges(aliens,ai_settings)
aliens.update()
if pygame.sprite.spritecollideany(ship,aliens):
self.ship_hit(aliens,ai_settings,screen,ship,stats,bullets,sb)
self.check_alien_bottom(aliens,a... |
def build_frame(self):
dome = cq.Workplane("XY")
solid_dome = self.__build_ring1(self.hexagon, self.pentagon)
cut_dome = self.__build_ring1(self.hexagon_cut, self.pentagon_cut)
ring_2 = self.__build_ring2(self.hexagon, self.pentagon)
ring_2_cut = self.__build_ring2(self.hexagon_... | The code constructs a dome structure by adding decorative "greebles" in two rings. It first builds a base frame, then generates ring1 (hexagons/pentagons) and ring2 (additional pentagons/hexagons) if enabled. These are translated vertically and combined with the base dome. The main task is assembling a 3D dome with lay... | def build(self):
super().build()
dome = self.build_frame()
greebled_r1 = None
greebled_r2 = None
#greebles
## center greeble
#print(self.greebles_bp)
if self.render_greebles:
if self.greebles_bp and len(self.greebles_bp) > 0:
... |
def mult_matrix(matrix1,matrix2):
answer = []
for column in range(len(matrix2[0])):
answer.append([])
for row in range(len(matrix1)):
sum=0
for subrow in range(len(matrix1[0])):
sum += matrix1[row][subrow] * matrix2[subrow][column] ... | The code computes the absorption probabilities in an absorbing Markov chain by calculating the inverse of (I - Q) multiplied by R, then converts the resulting fractions to a common denominator. It returns the numerators and the least common multiple (LCM) of denominators. The main task is to determine the probabilities... | def solution(m):
'''
print('Q is:')
printMatrix(getQ(m))
print()
print('R is:')
printMatrix(getR(m))
print()
print('I is:')
printMatrix(getI(m))
print()
print('I-Q is:')
printMatrix(sub_matrix(getI(m),getQ(m)))
print()
print('Inverse of (I-Q) is:')
pri... |
def load_ds_data(num_cv_folds=5, pos="Positive", neg="Negative",
random_state=None):
filename = data_dir + "ds_data.csv"
return construct_cv_dataset(filename, num_cv_folds, random_state)
def load_huffpost_data(num_cv_folds=5, pos="Positive", neg="Negative",
random_state=N... | The function `load_data` loads and prepares text data from specified sources (e.g., "ds", "huffpost", "reddit") for cross-validation. It delegates to source-specific loaders, applying given positive/negative labels and random state for reproducibility, returning processed data split into the specified number of cross-v... | def load_data(source, num_cv_folds=5, pos="Positive", neg="Negative",
random_state=None):
if source == "ds":
return load_ds_data(num_cv_folds, pos, neg, random_state=random_state)
elif source == "huffpost":
return load_huffpost_data(num_cv_folds, pos, neg,
... |
def __select_top_k(self, keywords, m, valid_labels,
use_all_keywords=False):
positive = valid_labels[0]
tot_sample = m * self.__sampling_ratio
sample_sz = max(30, int(tot_sample / len(keywords)))
X, y, pct_pos = [], [], []
for i, keyword in enumerate(keywo... | The code iteratively refines keyword rankings using reference documents, queries top documents based on updated keywords, labels results, and ensures a minimum number of outputs by supplementing with API queries if needed. | def liu(self, keywords, m, num_iterations=2, valid_labels=default_labels):
keyword_ranking = KeywordRanking(minimum_frequency=0.05)
X, y, _, pc_ps = self.__select_top_k(keywords, m,
valid_labels=valid_labels)
current_docs = [X[i] for i in range(len(X)... |
def __select_top_k(self, keywords, m, valid_labels,
use_all_keywords=False):
positive = valid_labels[0]
tot_sample = m * self.__sampling_ratio
sample_sz = max(30, int(tot_sample / len(keywords)))
X, y, pct_pos = [], [], []
for i, keyword in enumerate(keywo... | The main task of the code is to select and query top keywords, adjust sample counts based on parameters, and combine results from multiple API queries while handling label assignments. It processes input keywords, calculates adjusted sample sizes, queries data via an API, filters results, and returns labeled data. The ... | def tp_ksa(self, keywords, m, proportional=False, rand_neg=False,
valid_labels=default_labels):
X, y, kw, pct_pos = self.__select_top_k(keywords, m, valid_labels)
m_k = m / (1 + sum(pct_pos) / len(pct_pos)) if rand_neg else m
m_k = round(min(m_k, 0.8 * m)) if rand_neg else m
... |
def start_new_game(ai_settings, screen, stats, sb, ship, bullets, aliens):
""" Reset game and start new game. """
play_bg_music(ai_settings)
# Reset game speed metrics
ai_settings.initialize_dynamic_settings()
# Hide the mouse cursor
pygame.mouse.set_visible(False)
# Reset the game stats, s... | This function handles keyboard input events in a game. It manages actions like starting/pausing/resuming the game, controlling ship movement, firing bullets, and quitting. It checks which key is pressed and triggers corresponding game mechanics based on the current game state. | def check_keydown_events(event, ai_settings, screen, stats, sb, menu, ship, bullets, aliens):
""" Responds to keypresses. """
if event.key == pygame.K_p:
if not stats.game_active:
start_new_game(ai_settings, screen, stats,
sb, ship, bullets, aliens)
elif st... |
def check_menu(ai_settings, screen, stats, sb, menu, ship, aliens,
bullets, mouse_x, mouse_y):
"""Start a new game when the player clicks Play."""
button_clicked = menu.rect.collidepoint(mouse_x, mouse_y)
if button_clicked and not stats.game_active:
start_new_game(ai_settings, screen... | This function processes user input events in a game, handling mouse clicks, quitting, and key presses/releases. It delegates actions to other functions like check_menu, save_and_quit, check_keydown_events, and check_keyup_events to manage game state, menu interactions, and ship controls. | def check_events(ai_settings, screen, stats, sb, menu, ship, aliens, bullets):
""" Respond to key presses and mouse events. """
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = pygame.mouse.get_pos()
check_menu(ai_settings, screen, stat... |
def load_data_mnist():
"""
Load the MNIST dataset. Reads the training and testing files and create matrices.
:Expected return:
train_data:the matrix with the training data
test_data: the matrix with the data that will be used for testing
y_train: the matrix consisting of one
... | The code trains a neural network on MNIST/CIFAR-10 datasets, performing preprocessing, weight initialization, gradient checking, and iterative training with configurable hyperparameters. It evaluates model performance, tracks training/test costs/accuracies, supports convergence checks, and visualizes learning curves, s... | def run_model(dataset_choice=0, shuffle_data_first=True, hidden_size=100, batch_size=100, learning_rate=0.001,
lam_reg=0.1, activation=tanh, per_batch_print=50, weight_init_mode='normal', grad_check_enabled=False,
plot_sample_instances=False, epochs=200, per_epoch_shuffle_interval=0, plot_fa... |
def create_move(self, pos1, pos2, extra):
if extra == None: # the move is a normal move (pos1, pos2, None)
return tuple([pos1, pos2, None, 'normal'])
if isinstance(extra, Piece.Piece): # the move is a promotion move (pos1, pos2, Piece)
return tuple([pos1, pos2, extra, 'promoti... | This function determines if a king can perform regular or queenside castling by checking if the king and rooks are unmoved, the path is clear, and the resulting position isn't in check. It returns a tuple (can_castle, can_qastle) based on these conditions. | def can_castle(self, color):
#Returns (True or False, True or False) for (can_castle,can_qastle)
castle = True
qastle = True
if color == -1:
king = self.black_king
pos_y = 0
r1 = self.board[pos_y][0]
r2 = self.board[pos_y][7]
#... |
def get_possible_squares(self, piece, pos):
moves = []
init_x = pos[0]
init_y = pos[1]
piece_name = piece.get_piece()
if piece_name == 'Pawn':
if piece.get_color() == 1:
x_1 = init_x
y_1 = init_y - 1
if y_1 > -1:
... | The function generates all legal moves for a given player color by collecting possible moves from each piece, including pawn promotions, en passant, and castling. It filters out moves that leave the king in check by simulating each move and checking for check status, returning only valid, non-checking moves. | def get_legal_moves(self, color):
# Add all moves but castles
moves = []
for row in range(8):
for col in range(8):
piece = self.board[row][col]
if piece is not None and piece.get_color() == color:
# RETURNS A LIST OF POSSIBLE MOVES ... |
def get_characters(translations, n=None):
if n is None:
unfiltered_characters = translations['chinese'].to_list()
else:
unfiltered_characters = translations.head(n)['chinese'].to_list()
return get_characters_not_downloaded(unfiltered_characters)
def get_translations(filepath):
is_valid... | The main task of the code is to download MP3 files for each character from a translation file. It retrieves characters using translated data, iterates through them with a progress bar, fetches source IDs, and downloads corresponding MP3s with a delay between requests to avoid overloading the system. | def main():
time_between_character_retrievals = 0.1
characters = get_characters(
get_translations(os.path.join(translations_directory, translations_filename))
)
t = tqdm(characters)
for character in t:
t.set_description(f'Downloading mp3 for: {character}')
logging.info(f'Fe... |
def add_gaussian_noise(image, min_sigma, max_sigma):
"""
:param image:
:param min_sigma:
:param max_sigma:
:return:
"""
sigma = np.random.uniform(min_sigma, max_sigma)
noise = np.random.normal(loc=0, scale=sigma, size=image.shape)
noisy = image + noise
noisy = nearest_fraction(n... | The main task of the code is to train a denoising neural network model using residual blocks. It loads noisy image data, constructs a model with specified parameters, and trains it either in a quick mode (with reduced batch sizes and epochs) or full mode. The model learns to remove Gaussian noise from images, returning... | def learn_denoising_model(num_res_blocks=5, quick_mode=False):
"""
The following function trains denoising model
:param num_res_blocks: number of residual blocks (default is 5)
:param quick_mode: Boolean that indicates the function to do a quick training
:return: Keras trained denoising model
""... |
def random_motion_blur(image, list_of_kernel_sizes):
"""
The following function adds a random motion blur to a given
image, random in terms of - kernel and angle.
:param image:2d numpy array.
:param list_of_kernel_sizes: list of kernel sizes to choose randomly from.
:return: blurred image, clipp... | The function trains a deblurring neural network using residual blocks, applying random motion blur to images. It builds a model with specified parameters and trains it in either quick mode (smaller batches/epochs) or full mode. The trained model is returned for deblurring tasks, adapting to input size and channel confi... | def learn_deblurring_model(num_res_blocks=5, quick_mode=False):
"""
The following function trains a deblurring model.
:param num_res_blocks: number of residual blocks (default is 5)
:param quick_mode: Boolean that indicates the function to do a quick training
:return: Keras trained deblurring model
... |
def author_papers(self, author):
documents = self.lines[author].copy()
#doc_len = 10
semantic_inputs = []
semantic_labels = []
document_mask = []
if len(documents)>=self.doc_len:
documents = documents[:self.doc_len]
document_mask = [1]*s... | The main task of this code is to generate a training data sample for a model by retrieving author-related information, including BERT input/label for papers, neighbor papers with relations and hop counts, negative author samples, and converting all into tensors. It constructs a dictionary with keys like 'bert_input', '... | def __getitem__(self, item):
author = self.vocab.itoa[item]
bert_input, bert_label = self.author_papers(author)
#bert_input = item
#bert_label=1
neighbor_papers, relations, relations_type, hop_count = self.author_neighbor_papers(author, self.neighbor_size, self.hops)
n... |
def compute_mean_mles(train_data, train_labels):
'''
Compute the mean estimate for each digit class
Should return a numpy array of size (10,64)
The ith row will correspond to the mean estimate for digit class i
'''
means = np.zeros((10, 64))
# Compute means
for i in range(10):
i... | The code's main task is to compute maximum likelihood estimates (MLES) for means and covariances from training data, then evaluate the model by calculating average conditional log-likelihoods on both training and test datasets to assess performance. | def main():
train_data, train_labels, test_data, test_labels = data.load_all_data('data')
print('Finding mles')
# Fit the model
means = compute_mean_mles(train_data, train_labels)
covariances = compute_sigma_mles(train_data, train_labels)
# Evaluation
# Find avg conditional likelihood on ... |
def __goUp(self):
self.past_positions.append(self.position)
y, x = self.position
self.position = (y - 1, x)
reward = self.__calculate_move()
return reward
def __goDown(self):
self.past_positions.append(self.position)
y, x = self.position
self.position = (y... | The main task of the code is to dispatch movement actions (UP, DOWN, LEFT, RIGHT) to corresponding private methods like __goUp() or __goDown(). If an unrecognized action is provided, it raises a ValueError to indicate the invalid input. | def doAction(self, action: int):
if action == UP:
return self.__goUp()
elif action == DOWN:
return self.__goDown()
elif action == LEFT:
return self.__goLeft()
elif action == RIGHT:
return self.__goRight()
else:
raise Val... |
def _logger(_env:str):
_log_format = "%(asctime)s %(levelname)s %(message)s"
logging.basicConfig(filename=_getEnv("LOG_FILE"), filemode='w', level=logging.INFO, format=_log_format)
logging.info(_env)
def _countOnlineUsers():
QUERY = _mongoConnection("USERS").count_documents({"status": "online"}) #Count Online U... | The main task of the code is to collect system usage statistics by counting online, busy, away, and offline users, sent messages, uploaded documents, and rooms. It logs the script's execution start and finish, then writes each metric to separate output files for record-keeping or analysis. | def main(): # Main script
_msg = "Bingo! script started..."
_logger(_msg)
onlineUsers = _countOnlineUsers()
busyUsers = _countBusyUsers()
awayUsers = _countAwayUsers()
offLineUsers = _countOffLineUsers()
countSentMsg = _countSentMsgs()
countUploads = _countTotalUploads()
countRooms = _countRooms()... |
def showing_worker_list(dict):
# Show workers that are present
for keys, values in dict.items():
# Try and except for empty dict
try:
print(keys, values["First name"], values["Last name"])
except KeyError:
pass
def worker_detail_change(detail):
#Make a loop
... | The main task of the code is to add new workers to a dictionary, allowing users to input first and last names, update worker details, and manage empty slots in the dictionary. The function loops until the user exits, dynamically expanding the dictionary when necessary and offering options to modify newly added worker i... | def adding_worker():
#Make a loop
while True:
#Show workers that are present
showing_worker_list(workers)
#Enter the worker's first name
new_worker = input("Please enter new worker's First name, or enter no to exit").title().strip()
#If the user enter no then the function... |
def adding_jobs():
while True:
#Print the jobs
show_jobs(jobs)
#Ask the user the jobs they want to add
job_adding = input("Enter the job type you want to add, or enter no to exit").title().strip()
#to detect if the user wants to exit or keep.
if job_adding != "No" and... | The code defines a menu-driven interface allowing users to add/delete jobs, view/add/delete workers, or exit. It uses a loop with input validation (try/except) to handle numeric choices (0-5) and route actions to corresponding functions like adding_jobs(), deleting_jobs(), etc. | def menu():
#loop
while True:
#Used number to chose the function so we need try/except
try:
#Enter the number
choose = int(input("Enter 1 to add jobs \n"
"Enter 2 to deleting jobs \n"
"Enter 3 to view workers d... |
def get_cookie(self):
uid_cookie = request.get_cookie(self.cookie_name)
return uid_cookie
def load_session(self, cookie_value):
self.sessionid = uuid.UUID(cookie_value).hex
fileName = os.path.join(self.session_dir, 'sess-px-%s' % self.sessionid)
if os.path.exists(fileName):
... | The code initializes a session management system by setting session directory, cookie parameters, and session expiration settings. It checks for an existing cookie; if found, it loads the session data, otherwise creates a new session. The class handles cookie lifetime configuration, defaulting to a maximum TTL if unspe... | def __init__(self, session_dir="/tmp", cookie_name='px.session',
cookie_lifetime=None):
self.session_dir = session_dir
self.cookie_name = cookie_name
self.sessionid = None
if cookie_lifetime is None:
self.ttl = MAX_TTL
self.max_age = None
... |
def generateObstacles(self):
obstacleList = []
numObstacles = self.totalObstacles
i=0
tries = 0
while (tries<1000):
while(i<numObstacles):
#Randomly place the obstacle
rx = random.randint(0,self.cols-1)
ry = random.randi... | The main task of the code is to initialize a game environment by setting up grid dimensions, obstacles, walls, the player, and enemies. It calculates grid rows/columns, positions game elements like the end piece, initializes scrolling parameters, and prepares game state variables such as pause status and bullet renderi... | def appStarted(self):
#Initialize the level
self.margin = 50
self.extra = 200
self.rows = (self.height-2*self.margin)//Square.width
self.cols = (self.width+self.extra-2*self.margin)//Square.width
self.endPiece = Square(self.cols-1, self.rows//2, self)
self.obstacl... |
def lf2crlf(text):
if '\n' in text:
text = '\r\n'.join(text.split('\n'))
if len(text) > 253:
text = text[:253] + '\205'
return text
def AutoSizeDialog(dialog, center=True):
classNameBuffer = ctypes.c_buffer(1024)
children = []
editBoxes = []
for child in EnumChildWindows(dial... | This code updates a dialog box's label text using Windows API functions. It sets the text of a control (ID 1002) in a GUI window, adjusts the dialog size to fit content, and processes messages through a pump. The function converts line breaks, stores text in an instance variable, and ensures the UI reflects changes. | def label( self, *newstr ):
"""label(text) - Set text in progress box"""
if newstr:
self._label = lf2crlf(newstr[0])
user32.SetWindowTextA(user32.GetDlgItem(self.hwnd, 1002), self._label)
AutoSizeDialog(self.hwnd, center=False)
self._pump() |
def DisplayGui(board, final=False):
win.fill(black)
if not final:
pygame.event.pump()
for i in range(N):
ydraw = i * (WIN_DIMENSION/N)
for n in range(N):
xdraw = n * (WIN_DIMENSION / N)
pygame.draw.rect(win, red, (xdraw, ydraw, WIN_DIMENSION/N, WIN_DIMENSION/N), 3)
displayText(board[i][n], xdraw, yd... | The code implements a recursive backtracking algorithm to find a valid path on a board. It explores all 8 possible moves from the current position, checks validity, marks the path, and recursively continues until the target number of moves is reached. If a solution is found, it returns True; otherwise, it backtracks by... | def generateMove(board, currx, curry, totalmoves, xmoves, ymoves):
if totalmoves == TARGETMOVES:
return True
print("X: {} <> Y: {}".format(currx, curry)) # draw board here
DisplayGui(board)
for i in range(8):
nextx = currx + xmoves[i]
nexty = curry + ymoves[i]
if checkValid(board, nextx, nexty):
... |
def make_new_game(code=-1):
global game_id
if code == -1:
code = random.randint(0,999999)
# code = 123456
players = []
game = {'game_id': game_id, 'code': code, 'players': players}
games.append(game)
lmao = [game_id, code]
game_id += 1
return lmao
def get_game(code):
... | This code manages a client-server interaction for a multiplayer game. It handles host/join requests, initializes or joins games, updates player data, and broadcasts game state updates. The loop receives player inputs, updates the game, and sends the current player list. On disconnect, it removes the player and closes t... | def threaded_client(conn, id):
"""Main loop that sends and receives data for the players"""
data = pickle.loads(conn.recv(4092))
if data == 'host':
# print('host')
game_data = make_new_game()
gid = game_data[0]
code = game_data[1]
else:
# print('join')
cod... |
def horizontal_movement(self, keys):
if keys[pygame.K_LEFT]:
self.x -= self.vel
if keys[pygame.K_RIGHT]:
self.x += self.vel
self.update()
def check_collision_x(self, keys):
collisions = self.get_collisions(self.objects)
for obj in collisions:
... | The main task of the code is to handle a game object's movement and collision detection. It processes keyboard input, updates horizontal/vertical movement, checks collisions with environment elements (walls, checkpoints, coins, dots), updates the object's state, and determines if the current level is completed. | def move(self):
keys = pygame.key.get_pressed()
self.horizontal_movement(keys)
self.check_collision_x(keys)
self.vertical_movement(keys)
self.check_collision_y(keys)
self.check_collision_checkpoints()
self.check_collision_coins()
self.check_collision_dots(... |
def plugin_enabled(plugin_id):
"""
Function used to determine whether a plugin is enabled or not.
Simply looks in the ``conf['plugins']`` dict to see if the imported module is
present.
:param plugin_id: The plugin name.
:type plugin_id: string
:return: True if the plugin seems to be enabled... | The function enables a plugin by checking if it's already active, downloading it from a repository if needed, installing dependencies, adding its directory to Python's path, dynamically importing the module, and executing its `on_enable()` method. It handles missing dependencies, installs Python requirements, and confi... | def enable_plugin(plugin_id, downloadable_plugins=None):
"""
Enables a single plugin, which entails:
* If already enabled, return
* If plugin not found, search online repository
* Download if found in repository, else log and return
* Recusively enable dependencies if found, els... |
def get_plugin_directory():
"""
Helper function to get Eva's plugin directory specified in the config file.
Will automatically replace ``~`` with the user's home directory.
"""
plugin_dir = conf['eva']['plugin_directory']
if '~' in plugin_dir: plugin_dir = os.path.expanduser(plugin_dir)
ret... | The main task of the code is to initialize Eva's plugin system by loading all plugins from the plugin directory, loading user-defined configurations, enabling required plugins based on Eva's configuration, and triggering the `eva.plugins_loaded` event to signal successful plugin initialization. | def load_plugins():
"""
The function that is called during Eva's boot sequence.
Will fetch the plugin directory , load all of the plugins' info files, load
all of the plugin's configurations, and enable all the required plugins and
their dependencies specified in Eva's configuration file.
Fires... |
def choose_from_dir(path: Path):
paths = list(path.glob('**/*.so'))
has_dso = False
for index, dso in enumerate(paths):
has_dso = True
size = dso.stat().st_size / 1000
filename = str(dso)
marker = get_hint_marker(filename)
print(f"{index:3} {marker} {size:8.0f} kB {fi... | The main task of the code is to analyze an input file or directory by extracting resource data, generating size statistics, running system tools like nm and objdump, processing output into JSON structures, and generating an HTML report with embedded visualizations of symbol and section data, including resgen resources. | def main(args):
path = Path(args.input)
path.exists() or quit("No file or folder at the specified path.")
if path.is_dir():
path = choose_from_dir(path)
elif path.suffix in ['.zip', '.aar', '.apk']:
path = choose_from_zip(path)
dsopath = Path(path)
size = format_bytes(dsopath.st... |
def _check_fleet_edges(self):
"""Respond appropriately if any aliens have reached an edge."""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_feet_direction()
break
def _ship_hit(self):
"""Respond to the ship being hit by an al... | This method updates alien positions by checking fleet edges and moving aliens. It detects collisions between aliens and the player's ship, triggering a response if hit, and checks if any aliens reach the screen's bottom to handle accordingly. | def _update_aliens(self):
"""
Check if the fleet is at an edge,
then update the positions of all aliens in the fleet.
"""
self._check_fleet_edges()
self.aliens.update()
# Look for alien-ship collisions.
if pygame.sprite.spritecollideany(self.ship, self.al... |
def reset():
for pin in lightpins:
GPIO.output(int(pin),GPIO.LOW)
def mode():
#toggles mode based on time and day
now = datetime.datetime.now(EST())
wday = now.strftime('%w')
h = now.strftime('%p')
#print(wday)
#print(h)
if (wday == '1' or wday == '2' or wday == '3' or wday == '4... | The main task of the code is to monitor and display electrical parameters (voltage/current) from specific bus channels based on the selected mode. It initializes the system, retrieves data via `setbus`, updates an LCD screen with formatted values, and controls lights using these parameters. If errors occur, it displays... | def main():
reset()
if mode() == 1:
try:
points = setbus('00977', '501', '00977', '503')
lcd.clear()
lcd.message('501:' + str(round(points[0], 1)) + ' A:' + str(round(points[1], 1)) + '\n503:' + str(round(points[2], 1)) + ' A:' + str(round(points[3], 1)))
... |
def possible_moves(board: int):
for i in range(0, BOARD_SIZE):
if board & (1 << i) == 0:
yield i,
if i < BOARD_SIZE - 1 and board & (1 << i + 1) == 0:
yield i, i + 1
def apply_move(board: int, move: Union[Tuple[int], Tuple[int, int]]):
for i in move:
board... | The function identifies and returns a winning move if available by evaluating all possible moves through a depth-first search (dfs). If no winning move exists, it randomly selects a losing move. It prints counts and details of winning/losing moves before returning a choice. | def select_winning_move(board: int):
turn = 2
winning_moves = []
losing_moves = []
for move in possible_moves(board):
new_board = apply_move(board, move)
win_guaranteed = dfs(State(turn, new_board))
if win_guaranteed:
winning_moves.append(move)
else:
... |
def select(board: int, group_size: int):
mask = ((1 << NBITS) - 1)
return (board >> NBITS * (group_size - 1)) & mask
def set(board: int, group_size: int, count: int):
mask = select(board, group_size) << NBITS * (group_size - 1)
board ^= mask
board |= count << NBITS * (group_size - 1)
return boar... | The code implements a depth-first search (DFS) with memoization to determine if the current player can force a win from a given game state. It recursively evaluates all possible board configurations, checking terminal states (empty board) and using memoization to avoid redundant calculations. The function returns `True... | def dfs(state: State):
ones = select(state.board, 1)
state = State(state.turn, set(state.board, 1, ones % 2))
if state in memo:
return memo[state]
#ones = select(state.board, 1)
#print("ones", ones)
#state = State(state.turn, set(state.board, 1, ones % 2))
#if ones % 2 == 1:
... |
def computer_move(board: int):
# computer is turn 1
move = select_winning_move(board)
print(move)
board = apply_move(board, move)
return board
def print_board(board: int):
for i in range(0, BOARD_SIZE):
print(i % 10, end="")
print()
for i in range(0, BOARD_SIZE):
print(i... | The code implements a game where the computer and human take turns making moves on a board until it's full. The computer starts, and after each move, the board is updated and displayed. Once the board is complete, the winner is determined based on whose turn it was when the board filled: if the human's turn (turn=2), t... | def computer_starts():
board = 0
while board != (1 << BOARD_SIZE) - 1:
turn = 1
print(Fore.BLUE, end="")
print("COMPUTER:")
board = computer_move(board)
print_board(board)
print(Fore.RESET, end="")
turn = 2
print("HUMAN:")
board = human_mo... |
def computer_move(board: int):
# computer is turn 1
move = select_winning_move(board)
print(move)
board = apply_move(board, move)
return board
def human_move(board: int):
human_move = ()
while len(human_move) == 0 or len(human_move) > 2 or (len(human_move) == 2 and abs(human_move[0] - human_... | The code implements a turn-based game where a human and computer alternate moves on a binary board. The loop continues until the board is full (all bits set). The human starts, then the computer plays. After each move, the board is printed. The winner is determined by whose turn it was when the board filled: if the com... | def human_start():
board = 0b0000000000000
while board != (1 << BOARD_SIZE) - 1:
turn = 2
print("HUMAN:")
computer_move(board)
print()
board = human_move(board)
print_board(board)
if board == (1 << BOARD_SIZE) - 1:
break
print(Fore.B... |
def computer_move(board: int):
# computer is turn 1
move = select_winning_move(board)
print(move)
board = apply_move(board, move)
return board
def print_board(board: int):
for i in range(1, BOARD_SIZE + 1):
v = select(board, i)
if v:
print(("#"*i + " ")*v, end="")
... | This code simulates a turn-based game where the computer and human alternate moves on a board. The computer starts first, and each player's move is processed sequentially. The game continues until the board is full (all cells occupied), with the winner determined by who made the final move. The board state is printed a... | def computer_starts():
board = 0
while board != (1 << BOARD_SIZE) - 1:
turn = True
print(Fore.BLUE, end="")
print("COMPUTER:")
board = computer_move(board)
print_board(board)
print(Fore.RESET, end="")
turn = False
print("HUMAN:")
board = h... |
def computer_move(board: int):
# computer is turn 1
move = select_winning_move(board)
print(move)
board = apply_move(board, move)
return board
def human_move(board: int):
human_move = ()
while len(human_move) == 0 or len(human_move) > 2 or (len(human_move) == 2 and abs(human_move[0] - human_... | The code implements a turn-based game where a human and computer alternate moves on a board represented as a bitmask. The game continues until the board is full, with the winner determined by whose turn it was when the board reached completion. The loop alternates between human and computer moves, updates the board sta... | def human_start():
board = 0b0000000000000
while board != (1 << BOARD_SIZE) - 1:
turn = True
print("HUMAN:")
computer_move(board)
print()
board = human_move(board)
print_board(board)
if board == (1 << BOARD_SIZE) - 1:
break
print(For... |
def build_questions(self, question_stage):
"""Build questions based off of sports odds."""
if question_stage == "ingame":
num_questions = 1
else:
num_questions = 2
staged_questions = random.sample(self.question_templates[question_stage], num_questions)
sp... | This method manages a game session by initializing pregame questions, tracking game time, transitioning through stages (pregame, in-play, halftime, final), building/locking questions based on the stage, updating game status/scores, and resolving questions at the end. It uses debug mode for faster simulation and handles... | def run_game_session(self):
"""Main thread for running the game"""
self.build_questions("pregame")
LOGGER.info("Creating pregame questions")
self.game_stage = "NS"
self.game_status = "PREGAME"
if self.DEBUG == False:
while self.game_stage == "NS":
... |
def move(self,queue):
new_row = []
while queue:
while queue and queue[0] == 0:
queue.popleft()
if queue: # Check if the queue is not empty
first = queue.popleft()
else:
break # Exit the loop if the queue is empty
... | This code handles the "left" movement in a tile-based game (like 2048). It iterates through each row of the game board, slides tiles left, merges adjacent equal tiles, and updates the board if changes occur. If any row changes, it triggers an update; otherwise, it checks if the game is over. | def left(self):
change = False
for i in range(4):
queue = deque(self.board[i])
new_row = self.move(queue)
#check for change
if new_row != self.board[i]: change = True
# Update the current row with the modified new_ro... |
def move(self,queue):
new_row = []
while queue:
while queue and queue[0] == 0:
queue.popleft()
if queue: # Check if the queue is not empty
first = queue.popleft()
else:
break # Exit the loop if the queue is empty
... | The main task of the code is to handle the "right" movement of tiles in a grid-based game (e.g., 2048). It processes each row by reversing it, simulating rightward movement via the `move` function, checks for changes, updates the grid if tiles moved, and triggers game updates or end conditions accordingly. | def right(self):
change = False
for i in range(4):
queue = deque(self.board[i][::-1])
new_row = self.move(queue)
#check for change
if new_row != self.board[i][::-1]: change = True
# Update the current row with the modified new_ro... |
def optimal_weights(n_points,er,cov):
"""
-> list of weights to run the optimiser on to minimise the vol
"""
target_rs=np.linspace(er.min(),er.max(),n_points)
weights=[minimize_vol(target_return,er,cov) for target_return in target_rs]
return weights
def portfolio_return(weights,returns):
"""... | The function `plot_ef` generates and visualizes the efficient frontier for a multi-asset portfolio, plotting optimal return-volatility trade-offs across `n_points` weight configurations. It accepts expected returns (`er`), covariance matrix (`cov`), and optional flags to display the equal-weighted portfolio, global min... | def plot_ef (n_points,er,cov,style=".-",show_cml=False,riskfree_rate=0,figsize=(20,10),show_ew=False,show_gmw=False):
"""
Plots the N-aset efficient frontier and
"""
weights=optimal_weights(n_points,er,cov)
rets=[portfolio_return(w,er) for w in weights]
vols=[portfolio_vol(w,cov) for w in weigh... |
def resample(self):
# sample control noise vectors
self.noise = np.random.multivariate_normal(mean=self.noise_mu, cov=self.noise_sigma, size=(self.K, self.N))
def compute_sample_costs(self):
# calculate the total costs corresponding to sampled trajectories
for k in range(self.K):
... | This function performs a full iteration of a control process by initializing costs, resampling states, computing sample costs (either from new inputs or existing ones), determining the control vector, and returning the current control vector while preparing the next iteration by shifting the vector. | def step(self,x0,u_new=None):
# do a full iteration of this process and return control vector
self.cost_total[:] = 0
self.x0 = np.copy(x0)
self.resample()
if u_new is None:
self.compute_sample_costs()
else:
self.u_vec = np.copy(u_new)
s... |
def get_text_box(self) -> BBox:
font = self.font.font_variant(size=self.text_font_size)
text_offset = self.get_type_marker_offset()
text_height = self.get_text_height(font)
text_box_height = self.text_box_rows * text_height + self.text_padding * 2
x1 = self.get_x1()
x2... | This function calculates and returns a bounding box (BBox) for an image by adjusting the vertical positions of the title and text bounding boxes. It combines the horizontal coordinates from the text box and title box, then adds/subtracts a separation value to the vertical coordinates to create a non-overlapping image b... | def get_image_box(self) -> BBox:
text_bbox = self.get_text_box()
title_bbox = self.get_title_box()
(_, (_, y1)) = title_bbox
((_, y2), _) = text_bbox
y1 = y1 + self.box_separation
y2 = y2 - self.box_separation
x1 = self.get_x1()
x2 = self.get_x2()
... |
def populate_type_marker(self, draw: ImageDraw, card_type: str) -> None:
font = self.font.font_variant(size=self.type_font_size)
type_height = self.get_text_height(font)
type_x = self.width - self.inset
type_y = self.height - self.inset - type_height // 2 - self.type_padding
dra... | The main task of the code is to generate a card image by creating an RGBA background, drawing the card's type marker, title, description text, and embedded image based on the provided `Card` object, then returning the composed image. | def draw(self, card: Card):
img = Image.new('RGBA', (self.width, self.height),
color=self.bg_colour)
draw = ImageDraw.Draw(img)
self.populate_type_marker(draw, card.get_card_type())
text_bbox = self.get_text_box()
self.populate_text(draw, card.descriptio... |
def data(self):
xl=[0]*(self.dim-self.fix)
xh=[1]*(self.dim-self.fix)
cl=[-30]*self.fix
ch=[-3]*self.fix
low = np.array(xl+cl)# set the minimum range of random variables
high = np.array(xh+ch) # set the maximum range of random variables
... | The function `get_result` computes an aggregated result by iterating over multiple networks (`num_net`), extracting coefficients (`tf_coe` or `sk_coe` based on `method`), and applying integration functions (`sig_inte` or `re_inte` based on `inte`). It processes constraints (`self.cons`), accumulates outputs in `ANS`, a... | def get_result(self,method,inte):
X,Y,Y2=self.data()
if method == 1:
if inte == 1:
ANS={}
for k in range(self.num_net):
wi, wo, bi, bo = self.tf_coe(self.tf(X,Y2,100))
ans=[]
... |
def data(self):
intdim=self.dim-self.fix
qmcx=qmc_r1sl_sample(self.datasize, intdim)
qmcf=qmc_r1sl_sample(self.datasize, self.fix)*(-27)+np.array(-3)
qmc=np.concatenate((qmcx,qmcf),axis=1)
qmcxs= shuffle(qmcx, random_state=0)
qmcfs= shuffle(qmcf, random_state=1)
c... | The function computes an aggregated result by processing input data through different methods (tf/sk) and activation functions (sig/re), iterating over multiple networks to calculate coefficients, integrate results, and average them. It handles normalization and returns the final aggregated output. | def get_result(self,method,norm,epoch):
X,Y,Y2=self.data()
if norm == 0:
Y2=Y
if method == 1:
if self.activ == 1:
ANS={}
for k in range(self.num_net):
wi, wo, bi, bo = self.tf_coe(self.tf(X,Y2,epoch))
... |
def transform_and_validate_erasure_requests(
connection: Any, erasure_requests_data: List[Dict[str, Any]], date: str, hour: str
) -> List[Dict[str, Any]]:
"""
Transform and validate erasure requests against the schema.
Args:
connection (Any): The PostgreSQL connection.
erasure_requests_... | The function processes erasure requests for a specific date and hour by extracting data from .json.gz and .json files, transforming and validating the requests, logging processed data, and archiving/deleting original files. It tracks processing time and logs statistics, ensuring data is handled efficiently and securely... | def process_hourly_data(
connection: Any, date: str, hour: str, available_datasets: List[str]
) -> None:
"""
Process erasure requests for a given hour.
Args:
connection (Any): The PostgreSQL connection.
date (str): The date of the data.
hour (str): The hour of the data.
... |
def load_excel(self, filename):
df=pd.read_excel(filename)
return df
def convertPDF(self, filename):
pdf = wi(filename= filename, resolution = 300)
pdfImage = pdf.convert('jpeg')
blobs=[]
for img in pdfImage.sequence:
imgPage = wi(image = img)
blob... | The code initializes an object by loading Excel data into a DataFrame, converting a PDF file into image blobs, and setting up attributes for processing dental records. It prepares data structures for storing conditions, order numbers, and output files, while the `mapper()` method likely processes the data for further u... | def __init__(self, filename):
self.df=self.load_excel(outfile)
self.table=[]
self.outFile=outfile
self.cond = self.teethNo = self.drawNo = self.orderNo = ''
self.imageBlobs=self.convertPDF(filename)
self.mapper() |
def get_opereto_client():
if opereto_credentials_json.get('opereto_password'):
client = OperetoClient(opereto_host=OPERETO_HOST,
opereto_user=opereto_credentials_json['opereto_user'],
opereto_password=opereto_credentials_json['opereto_password'])... | The code reruns an Opereto process using provided parameters (old PID, title, agent), updates the global RUNNING_PROCESS variable, waits for synchronous execution, checks the process status, logs success or raises an error on failure, and outputs a dashboard link for the rerun process. | def rerun(params):
global RUNNING_PROCESS
client = get_opereto_client()
old_pid = params['<pid>']
agent = params['--agent']
title = params['--title']
pid = client.rerun_process(old_pid, title=title, agent=agent)
print('Re-running process [%s]..'%pid)
if not params['--async']:
R... |
def get_opereto_client():
if opereto_credentials_json.get('opereto_password'):
client = OperetoClient(opereto_host=OPERETO_HOST,
opereto_user=opereto_credentials_json['opereto_user'],
opereto_password=opereto_credentials_json['opereto_password'])... | The main task of the code is to create and manage a process in Opereto based on input parameters. It determines the operation mode (development/production), constructs process properties, initiates the process, and monitors its status. If not asynchronous, it waits for completion, logs success/failure, and retrieves RC... | def run(params):
global RUNNING_PROCESS
client = get_opereto_client()
operations_mode = 'development'
if params['services']:
operations_mode = 'production'
version=params['--service-version'] or 'default'
agent = params['--agent'] or 'any'
title = params['--title'] or None
proce... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.