dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def find_order(self):
"""
Returns a contraction order as a list of pairs of tensors.
You should use:
- nx.algorithms.approximation.treewidth_min_degree to compute a decent tree decomposition of the graph
- you should then implement the algorithm seen during the lecture that pops... | This method contracts the network using optimized tensor contractions via `opt_einsum`, leveraging the contraction order determined by `find_order` to efficiently compute the result using Einstein summation notation on the network's tensors. | def contract(self):
"""Contracts the network via opt_einsum and find_order"""
order = self.find_order()
return oe.contract(self.get_einsum_expression(), *self.get_tensors(), optimize=order) |
def get_unique_values(column):
list_of_unique_values = []
arrayOfColumn = get_array_of_column(column)
for x in arrayOfColumn:
if x not in list_of_unique_values:
list_of_unique_values.append(x)
return list_of_unique_values
def get_percentage(column, value_number):
return 100 * num... | The main task of the code is to generate a textual bar chart string from a given column of data. It retrieves unique values from the column, calculates their percentage representation, and constructs a formatted string with each value, its percentage, and a corresponding bar. The result is a multi-line string displayin... | def make_chart_string(column):
listofcolumn = get_unique_values(column)
bar_graph = ""
for i in range(len(listofcolumn)):
bar_graph += listofcolumn[i] + " " + str(round(get_percentage(column, i), 2)) + "% \t\t" + get_percentage_bar(
column, i) + "\n"
return bar_graph |
def _cache_output_metric_attributes_multi(self, metrics, weighted_metrics):
"""Caches metric name and function attributes for every model output."""
output_shapes = []
for output in self.outputs:
if output is None:
output_shapes.append(None)
else:
... | This method compiles a multi-output neural network model for training, configuring multiple loss functions (loss1, loss2, and specialized regularization losses like L1/L2), metric functions, and sample weighting. It prepares loss weights, target tensors, and computes total losses for each output, enabling the model to ... | def mcompile(self, optimizer,
loss1=None,
loss2=None,
metrics=None,
loss1_weights=None,
loss2_weights=None,
sample_weight_mode=None,
weighted_metrics=None,
target_tensors=None,
... |
def _standardize_user_data_multi(self, x,
y=None,
sample_weight=None,
class_weight=None,
check_array_lengths=True,
batch_size=None):
... | This method trains a machine learning model on provided input data (x) and target labels (y) for a specified number of epochs, supporting various data formats (arrays, generators, sequences) and validation configurations. It handles batch processing, shuffling, class/sample weighting, and callback functions, returning ... | def mfit(self,
x=None,
y=None,
batch_size=None,
epochs=1,
verbose=1,
callbacks=None,
validation_split=0.,
validation_data=None,
shuffle=True,
class_weight=None,
sample_weight=No... |
def read_file(file_path):
bytes_data = file_path.getvalue()
content = bytes_data.decode("utf-8")
return content
def parse_whatsapp(text):
message_splits = re.split(DATE_PATTERN, text)
dates = re.findall(datepattern, text)
parsed_messages = []
for i in range(2, len(message_splits)):
... | The main task of the code is to process WhatsApp chat exports by parsing messages, filtering them within specified date ranges, chunking the content, and generating a summary using a language model. If enabled, it prepends a newsletter-style introduction. The summary is printed and saved to a file for output. | def main( chat_export_file, summary_file, start_day_s, end_day_s, is_newsletter, model):
start_day = datetime.datetime.strptime(start_day_s, '%m/%d/%Y').date()
end_day = datetime.datetime.strptime(end_day_s, '%m/%d/%Y').date()
content = read_file(chat_export_file)
parsed_messages = parse_whatsapp(conte... |
def transformpoint(point, d):
res = (
d.width * (0.5 + (point[0] - DRAW_CENTRE_X) / DRAW_SIZE),
d.height * (0.5 + (point[1] - DRAW_CENTRE_Y) / DRAW_SIZE),
)
return res
def drawground(draw, poly, ground_type):
if poly and len(poly) >= 3:
col = '#969696'
if ground_type == '... | The code renders a district's geographical data by loading JSON files, transforming coordinates, and drawing boundaries, subdistricts, buildings, and streets with labeled names. It uses SVG elements to visualize spatial data, including polygons for landmasses, streets, and structures, while dynamically adjusting text o... | def drawdistrict(code, draw):
try:
with open(f"{settings.DATA_DIR}/{code}.json", "rb") as f:
# print("Drawing district" + code)
district = json.load(f)
junctions = { x['code']: x for x in district['junctions'] }
bounding_poly = district['district']['bounding... |
def __check_signal(self, signal):
""" check type and dimensionality of an input signal.
If signal is the first input signal, set the dimension of it as self.dim.
So, this method have to be called before calling functions that use self.dim.
:param signal: an input signal
"""
... | The code processes a new input signal in a SOINN (Self-Organizing Incremental Neural Network) by checking its validity, incrementing signal count, and either adding a new node (if fewer than 3 nodes exist) or evaluating similarity thresholds with the nearest nodes. If learning is enabled, it dynamically adds nodes/edge... | def input_signal(self, signal, learning=True):
""" Input a new signal to SOINN
:param signal: A new input signal
:return:
"""
self.__check_signal(signal)
self.num_signal += 1
if self.nodes.shape[0] < 3:
self.__add_node(signal)
return
... |
def count_figures_and_time(input_frames):
# Determine the maximum number of figures in a single frame of a series,
# the total number of figures (not used), and the last timecode
total_figures=0
max_figures=0
total_time=0.0
for i, frame_info in enumerate(input_frames):
total_figures += l... | The main task of the code is to interpolate missing coordinates in pose data across frames by averaging last and next known positions, handling low-confidence points, and using bounding box overlaps to ensure coordinate validity. It processes each figure's coordinates, fills gaps using adjacent frames, and adjusts for ... | def interpolate_missing_coords(input_frames, threshold=.5, flip_figures=False, check_bbox=False, all_visible=True, overlap_threshold=.7, video_file=None):
# Most matrix comparison methods do not allow for empty rows/colums.
# Given a series of poses, fill in each missing point by taking the average of
# its... |
def keys_cols(self, table):
df:pd.DataFrame = self.describe(table)
keys = (df[df['Key']=='PRI'].loc[:,'Field'].tolist())
cols = (df[df['Key']!='PRI'].loc[:,'Field'].tolist())
return keys, cols
def _get_conn(self):
try:
return mysql.connector.connect(host=self._host, p... | (This function inserts or updates records in a database table using a DataFrame. It constructs an SQL query with placeholders for values, handles NaN values by converting them to None, executes batch operations, and returns the number of affected rows. Errors are logged and re-raised, ensuring proper connection managem... | def _update_each_batch(self, table, df:pd.DataFrame):
if df.empty: return 0
UPDATE_SQL = 'INSERT INTO {0}({1}) VALUES({2}) ON DUPLICATE KEY UPDATE {3}'
idx_cols, upd_cols= self.keys_cols(table)
upd_cols = np.intersect1d(upd_cols, df.columns.values).tolist()
if len(upd_cols) <= 0:... |
def _get_available_networks(self, context, project_id,
net_ids=None):
"""Return a network list available for the tenant.
The list contains networks owned by the tenant and public networks.
If net_ids specified, it searches networks with requested IDs only.
... | The function allocates network resources for a compute instance by creating/updating Neutron ports, handling requested networks, and ensuring proper cleanup on failure. It validates the project ID, processes fixed IPs and ports, creates ports for available networks, and triggers security group updates. Exceptions trigg... | def allocate_for_instance(self, context, instance, **kwargs):
"""Allocate all network resources for the instance."""
quantum = quantumv2.get_client(context)
LOG.debug(_('allocate_for_instance() for %s'),
instance['display_name'])
if not instance['project_id']:
... |
def normalize_counts(counts):
"""Normalizes expression counts using DESeq's median-of-ratios approach."""
with np.errstate(divide="ignore"):
size_factors = estimate_size_factors(counts)
return counts / size_factors
def tmm_normalization(matrix, index_ref=None, trim_fold_change=0.3, trim_abs_exp... | This code normalizes RNA-seq data using specified methods (Median_of_ratios, TMM, CPM, TPM, RPKM, Total_count) or quartile normalization. It reads count data and gene lengths from "merged.txt", applies chosen normalization, formats results with sample IDs, and writes normalized values and original counts to "normalized... | def normalize(norm_type, column):
f = open("merged.txt", "r")
counts = pd.read_csv(f , sep="\t", index_col=list(range(column)))
f.close()
f = open("merged.txt", "r")
gene_length = pd.read_csv(f , sep="\t")
f.close()
f = open("normalized.txt", "w")
if norm_type == "Median_of_ratios":... |
def merge(input_file, columns):
frames = (pd.read_csv(fp, sep="\t", index_col=list(range(columns-1)))
for fp in input_file)
merged = pd.concat(frames, axis=1)
# Extract sample names.
f = open("merged.txt", "w")
merged.to_csv(f , sep="\t", index=True)
f.close()
def normalize_all():
... | The main task of the code is to process input files by merging them and applying normalization based on a specified type. It reads a CSV file, determines column count, deletes the DataFrame, merges input files, and applies either all normalization methods or a specific type using `normalize_all()` or `normalize()` func... | def main():
norm_type=argv[1]
files = argv[2:]
df = pd.read_csv(files[0], sep="\t")
cols=len(df.axes[1])
del df
merge(files, cols)
if norm_type == 'ALL':
normalize_all()
else:
normalize(norm_type, cols) |
def add_to_queue_with_id(self, subject_id, person_id, room_id, desk, exercises, message=None, help=False):
payload = {
"subjectID": subject_id,
"roomID": room_id,
"desk": desk,
"message": message,
"help": help,
"exercises": exercises
... | This function adds a person to a queue with specified details (subject, person, room, desk, exercises), optionally boosts their priority, re-adds them to the queue, and then removes them. It handles queue management, including prioritization via 'boost' and dynamic adjustments with parameters like exercises and message... | def add_person_id(self, subject_id, person_id, room_id=6, desk=1, exercises=[3.141592653589793], help=False,
message=None, boost=False):
self.add_to_queue_with_id(subject_id=subject_id, person_id=person_id, room_id=room_id, desk=desk, exercises=exercises,
... |
def popup(self, message):
popup = Tk()
popup.wm_title("!")
label = Label(popup, text=message)
label.pack(side="top", fill="x", pady=10)
B1 = Button(popup, text="Okay", command=popup.destroy)
B1.pack()
popup.mainloop()
def get_selected_exercises(self):
retu... | This function adds selected exercises to a queue by validating inputs (desk, exercises, students), preparing data (converting to integers, formatting names), and starting a thread to process the addition. It ensures mandatory fields are filled, handles student data, and triggers background processing via a thread. | def add_to_queue(self):
room = self.rooms[self.room_list.current()]
room_id = room["roomID"]
desk = self.desk_list.get()
if desk.strip() == "":
self.popup("You must enter a desk!")
return
exercises = self.get_selected_exercises()
if len(exercises... |
def update_queue(self, reload=False):
if self.current_subject != None:
status_code, reason, content = self.qs.get_queue(subject_id=subjects_to_id[self.current_subject])
if status_code != 200:
self.popup("We could not update the queue!")
return
... | This method updates the current subject, retrieves the corresponding queue, initializes variables for managing student additions/removals, and triggers UI updates for the queue, student list, and exercises. | def on_subject_change(self, subject):
self.current_subject = subject
self.queue = self.qs.get_queue(subject_id=subjects_to_id[subject])
self.students_to_add = []
self.current_student_to_add = None
self.current_student_to_remove = None
self.update_queue()
self.upd... |
def get_empty_spaces(board):
"""return a list of empty positions on the game board"""
return [key for key in board if board[key] == ' ']
def set_coordinate_ai(self, coord, game_board, turn):
""" return game board update for minimax algorithm, after setting a coordinate"""
if turn:
... | This function implements a "hard" AI bot for a game (likely tic-tac-toe) using the minimax algorithm. It evaluates all possible moves by recursively simulating game outcomes, selects the move with the highest score, and applies it to the game grid. If the grid is empty, it starts with the center position. The bot uses ... | def hard_bot(self, turn):
print('Making move level "hard"')
empty_spaces = self.get_empty_spaces(self.game_grid)
if self.grid_fill == 0:
self.set_coordinate('2', '2', turn)
else:
self.ai_game_board = self.game_grid.copy()
self.ai_grid_fill = self.grid_... |
def get_user_input(self, turn):
try:
x, y = input("Enter the coordinates:").split()
self.set_coordinate(x, y, turn)
except UnboundLocalError:
print("You should enter numbers!")
except ValueError:
print("You should enter numbers!")
def check_state(s... | The main task of the code is to manage a turn-based game loop, alternating between 'X' and 'O' players, capturing user input, checking the game state after each move, and resetting the game board upon completion. The loop continues until the game ends, determined by the check_state method, after which the board is rese... | def play(self):
while True:
if self.grid_fill % 2 == 0 or self.grid_fill == 0:
turn = 'X'
else:
turn = 'O'
self.get_user_input(turn)
if not self.check_state(turn):
break
self.reset_game_board() |
def easy_bot(self, turn):
print('Making move level "easy"')
empty_spaces = self.get_empty_spaces(self.game_grid)
choice = random.choice(empty_spaces)
self.set_coordinate(choice[0], choice[1], turn)
def medium_bot(self, turn):
print('Making move level "medium"')
if turn !=... | The function `player_move` handles a player's turn by selecting the appropriate input method based on the player's type. If the player is 'user', it retrieves user input; for 'easy', 'medium', or 'hard', it delegates the move to corresponding bot strategies. The main task is to route the turn logic to the correct input... | def player_move(self, player, turn):
if player == 'user':
self.get_user_input(turn)
elif player == 'easy':
self.easy_bot(turn)
elif player == 'medium':
self.medium_bot(turn)
elif player == 'hard':
self.hard_bot(turn) |
def compute_sacrebleu(self, outputs, references) -> float:
""""
Computes Sacre-BLEU score for the corpus
:param outputs: Outputs of the model
:param references: References of the model
:return: Corpus Sacre-BLEU score
"""
assert len(np.shape(outputs)) == 1
... | The function computes evaluation metrics for model outputs against references, including BLEU, SacreBLEU, GLEU, ROUGE, and others. It optionally calculates BERTScore and BLEURT, handling computational limits via sample caps. Metrics assess similarity, diversity, and overlap between outputs, inputs, and references, retu... | def compute_metrics(self, input_batch, output_batch, reference_batch, use_bertscore=True, use_bleurt=True,
verbose=True, max_samples_bertscore=None,
max_samples_bleurt=None, bleurt_batch_size=16):
"""
Computes all evaluation metrics
:param input_b... |
def create_pairs (a):
# Create local stores for use
split_array = [];
temp_array = [];
for num, value in enumerate(a, start=1):
temp_length = len(temp_array)
if temp_length == 1:
temp_array.append(value)
split_array.append(temp_array)
temp_array = []
elif len(split_array) * 2 == ... | The code implements a hybrid sorting algorithm combining merge sort and insertion sort principles. It sorts an array by first splitting it into pairs, sorting each pair, recursively sorting pairs by their larger elements, and merging them into a final sorted array. It handles odd-length arrays by isolating a "straggler... | def merge_insertion_sort (A):
# Print out Given Array, for clarity
print("Starting Array:")
print(A)
# Determine if it's odd numbered... if so, take off a straggler
hasStraggler = len(A) % 2 != 0
if hasStraggler:
straggler = a.pop(len(A) -1)
else:
straggler = False
# T... |
def unpack_pars(self, p):
par_dict = dict()
p_i = 0
for par in ['sun_z', 'sun_vz', 'lnsigma', 'lnhz']:
par_dict[par] = self.frozen_pars.get(par, p[p_i])
if par not in self.frozen_pars:
p_i += 1
if self.marginalize_alpha:
par_dict['ln... | This function computes the log posterior probability by summing the log prior and log likelihood of given parameters. It unpacks input parameters, checks if the log prior or likelihood is finite, and returns -∞ if invalid. Otherwise, it returns their sum as the log posterior. | def ln_posterior(self, p):
par_dict = self.unpack_pars(p)
lnp = self.ln_prior(par_dict)
if not np.isfinite(lnp):
return -np.inf
lnl = self.ln_likelihood(par_dict)
if not np.isfinite(lnl):
return -np.inf
return lnp + lnl |
def scrape_header():
header_elements = []
time.sleep(2)
meet_name = scrape_meet_name()
header_elements.append(meet_name)
time.sleep(2)
meet_date = scrape_meet_date()
header_elements.append(meet_date)
time.sleep(2)
meet_location = scrape_meet_location()
header_elements.append(meet_location)
time.sl... | The code scrapes webpage headers and table data, cleans the raw data, combines it with headers, and returns structured final data. It includes delays between steps and prints intermediate results for tracking. | def perform_program():
header_results = []
raw_results = []
header_results = scrape_header()
print('header results:', header_results)
time.sleep(2)
raw_results.append(scrape_td_elements())
print('raw results:', raw_results)
time.sleep(2)
print('RACE SCRAPED')
time.sleep(2)
cleaned_results = clean(... |
def load_race_url(race):
time.sleep(.5)
race = race[0]
driver.get(race)
def fork(race):
race = race
pre_element = locator()
final_data = []
if pre_element == "no pre":
print('go to formatted scraper')
final_data = perform_program()
else:
print('go to pre scraper')
final_data = pre_scrape... | The main task of the code is to iterate through a list of race URLs, load each URL using a web driver, extract data with the 'fork' function, process the data with 'main_csv_function', and remove the race URL from a CSV file if specified. The function includes delays between actions and logs progress, completing one cy... | def cycle_races(race_urls):
time.sleep(4)
race_urls = race_urls
for race in race_urls:
driver.implicitly_wait(3)
load_race_url(race)
print(race)
time.sleep(8)
final_data = fork(race)
time.sleep(8)
can_remove = main_csv_function(final_data)
time.sleep(1)
remove_race_url_from_csv... |
def _fetch_persisted_data(self):
filepath = self.get_excluded_persistence_datapath()
if os.path.exists(filepath):
try:
with io.open(filepath, "r", encoding="utf-8") as f:
persistence_file = f.read()
persistence_json = json.loads(persist... | The main task of the code is to announce device status to an OctoFarm server by sending a POST request with device and server configuration data (host, port, UUID, Docker status, CORS settings). It validates input parameters, fetches persisted data, constructs a payload, and handles errors (invalid state, missing URL/t... | def _query_announcement(self, base_url, access_token):
if self._state != State.SUCCESS and self._state != State.SLEEP:
self._logger.error("State error: tried to announce when state was not 'success'")
if base_url is None:
self._state = State.CRASHED
raise Exception(E... |
def __read_json_config(self, json_file_dir):
"""
loads the json configuration into the object
:param json_file_dir: the directory for the json file
"""
actual_dir = os.path.abspath(json_file_dir)
Logger.log.info("Reading the json configuration from : '{}'".format(actual_d... | The code's main task is to configure an Oracle DB connection, read JSON settings, retrieve table names from a database config, and subscribe to those tables. It includes a commented-out placeholder for RabbitMQ connection, suggesting potential future integration. | def subscribe(self):
self.__read_json_config(self.json_dir)
self.__oracle_db_connect()
#TODO:Comment connection
#self.__connect_rabbitmq()
tables = self.__get_oracle_db_config("table_on_change_sql_function")
self.__subscribe_to_tables(tables_name=tables.keys()) |
def manufacturing_upper_bounds(factories,resources):
days = get_n_days()
return {"manufacturing_{}_{}_{}".format(material,factory,day): 0 for material in resources for factory in factories.keys() if factory != "DUMMY_RESERVE" for day in range(1,days)}
def demand_upper_bounds(hospitals,ppe,respirators):
days... | This function generates a combined dictionary of upper bounds by aggregating constraints from manufacturing, demand, resource availability, and shipping capacities. It merges results from four helper functions into a unified set of limits for optimization or resource allocation tasks. | def gen_upper_bounds(factories,resources,hospitals,materials,shipping):
return {**manufacturing_upper_bounds(factories,resources),
**demand_upper_bounds(hospitals,materials,resources),
**availability_upper_bounds(resources),
**shipping_cap_upper_bounds(shipping)} |
def shipping_cap_recipes(shipping):
days = get_n_days()
return {("s_{}->{}_{}".format(start,end,day),"capacities_{}->{}_{}".format(start,end,day)): 1 for day in range(1,days) for start,end,cap,cost in shipping}
def total_shipped_recipes(shipping):
days = get_n_days()
materials = get_all_materials()
... | The function `gen_recipes` aggregates and returns a combined dictionary by merging multiple recipe-generating functions. These include shipping capacity, total shipped items, hospital demand, availability, on-hand resources, and manufacturing recipes. Each component contributes key-value pairs to form a comprehensive d... | def gen_recipes(shipping,hospitals,resources,factories,respirators,ppe):
return {**shipping_cap_recipes(shipping),
**total_shipped_recipes(shipping),
**demand_recipes(hospitals,ppe),
**availability_recipes(shipping),
**onhand_recipes(factories,resources,shipping,respirators,ppe),
**manufacturing... |
def g(self):
"""
Function that provides the measurements of the environment.
Give a more readable output of the state variables.
Returns
y -- measurements of the environment
"""
y = np.array([1e3 * self.state[0],
1e-3 * co2dens2ppm(se... | The code's main task is to simulate one timestep of a reinforcement learning environment by executing an action, updating the state, calculating a reward, and determining if the episode has terminated. It denormalizes the input action, transitions the environment state using `f` and `g` functions, computes the reward v... | def step(self, action):
"""
Step function that simulates one timestep into the future given input action.
Args:
actions [array] -- normalised action
Return:
observation [array] -- array consisting of four variables
reward [float] -- immediate re... |
def findBoard(self):
"""
Finds the chess board element on the webpage.
"""
svg_element = self.find_element(By.CLASS_NAME,"coordinates")
self.location = svg_element.location
self.size = svg_element.size
def getBoardAsFen(self):
"""
Returns the current posit... | The main task of the code is to determine the best move for the current game state, time the computation of that move, execute the move on the board, and return the move string. It retrieves the board position, calculates the optimal move using the game engine, prints timing metrics, converts the move to a visual forma... | def play(self) -> str | None:
self.findBoard()
fen = self.getBoardAsFen()
self.game.set_fen_position(fen)
print(self.game.get_board_visual())
black_time, white_time = self.get_current_player_time()
t1 = time.perf_counter()
movestring: str = self.game.get_best_move... |
def hook_calc_cond_uncond_batch():
from comfy.samplers import calc_cond_uncond_batch
# this function should only be run by us
orig_key = f"calc_cond_uncond_batch_original_tiled_diffusion_{gen_id()}"
payload = [{
"mode": "replace",
"target_line": 'control.get_control',
"code_to_in... | This function applies or restores specified hooks to modules in the Python environment. It iterates through all loaded modules, checks if they match hook targets, and either replaces or restores original functions based on the 'restore' flag. Hooks are predefined functions that modify module behavior, with optional res... | def hook_all(restore=False, hooks=None):
if hooks is None:
hooks: List[Hook] = [
hook_calc_cond_uncond_batch(),
hook_sag_create_blur_map(),
hook_samplers_pre_run_control(),
hook_gligen__set_position(),
]
for key, module in sys.modules.items():
... |
def scenario_player_loses_out(resmat, player, ngames=6):
unf = find_player_unfinished(resmat, player, ngames)
return add_record(resmat, player, unf.index, 0, unf)
def demoting(resmat, ngames=6, nplayers=1):
# if a player could win all of their games and still demote, they've guaranteed demotion
return [... | The function determines possible player demotions in a tournament matrix by iteratively resolving matches, handling unfinished games through recursive exploration of outcomes, and returning unique demoted players after processing all scenarios. | def could_demote(resmat, ngames=6, nplayers=1):
# Resolve one match at a time, iteratively
players = []
for p in resmat.index:
spec_resmat = scenario_player_loses_out(resmat, p, ngames)
demo = demoting(spec_resmat, ngames, nplayers)
players.extend(demo)
if len(demo) < nplay... |
def scenario_player_wins_out(resmat, player, ngames=6):
unf = find_player_unfinished(resmat, player, ngames)
return add_record(resmat, player, unf.index, unf, 0)
def promoting(resmat, ngames=6, nplayers=1):
# If a player could lose all of their games and still promote, they've guaranteed promotion
retur... | This function determines potential player promotions by simulating match outcomes iteratively. It evaluates each player's promotion status under scenarios where they win matches, recursively resolving unfinished matches with all possible outcomes. The result is a list of uniquely identified players who could be promote... | def could_promote(resmat, ngames=6, nplayers=1):
# Resolve one match at a time, iteratively
players = []
for p in resmat.index:
spec_resmat = scenario_player_wins_out(resmat, p, ngames)
promo = promoting(spec_resmat, ngames, nplayers)
players.extend(promo)
if len(promo) < n... |
def find_player_unfinished(resmat, player, ngames=6):
unf = find_unfinished(resmat, ngames)
unfA = unf.loc[player] if player in unf.index else pd.Series(dtype=int)
unf = unf.swaplevel()
unfB = unf.loc[player] if player in unf.index else pd.Series(dtype=int)
return pd.concat((unfA, unfB))
def add_rec... | This function evaluates potential match outcomes between two players by simulating varying win distributions across remaining games. It calculates possible win counts, checks demotion implications, and returns scenarios with win totals and demotion status for all plausible results. | def match_impl(resmat, playerA, playerB, ngames=6, nplayers=1):
unf = find_player_unfinished(resmat, playerA)
remaining = unf[playerB] if playerB in unf.index else 0
# Gather data about the implications of scenarios
resultrows = []
for halfwins in range(int(2*remaining+1)):
spec_resmat = ad... |
def _fit(self, data):
"""
Run K-Means on data once.
Parameters
----------
data: numpy array
Returns
-------
No value is returned.
Function sets the following two object params:
self.labels_
self.cluster_centers_
""... | The `fit` method executes K-Means clustering on input data multiple times (`n_init`), storing results for each run. It initializes cluster centers, runs the algorithm, and collects cluster labels, centers, inertia, and log-likelihood values. After all iterations, it selects the best clustering (lowest inertia) and upda... | def fit(self, data):
"""
Run K-Means on data n_init times.
Parameters
----------
data: numpy array
Returns
-------
No value is returned.
Function sets the following two object params:
self.labels_
self.cluster_centers_
... |
def free_parameters(self, data):
"""
Compute free parameters for the model fit using K-Means
"""
K = np.unique(self.labels_).shape[0] # number of clusters
n, d = data.shape
r = (K - 1) + (K * d)
if self.metric == 'euclidean':
r += 1 # one parameter f... | The function computes the Bayesian Information Criterion (BIC) score for a K-Means model. It calculates the BIC using either the residual sum of squares (RSS) or log-likelihood, depending on the `use_rss` flag. The penalty term is derived from free parameters and dataset size. The BIC formula balances model fit (via RS... | def bic(self, data):
"""
Computes the BIC score for a model fit using K-Means.
BIC = (max log likelihood) - (free parameters * log (size of dataset) / 2)
Parameters
----------
data: input data
Returns
-------
BIC score
"""
data ... |
def free_parameters(self, data):
"""
Compute free parameters for the model fit using K-Means
"""
K = np.unique(self.labels_).shape[0] # number of clusters
n, d = data.shape
r = (K - 1) + (K * d)
if self.metric == 'euclidean':
r += 1 # one parameter f... | This function computes the Akaike Information Criterion (AIC) score for a K-Means model. It calculates AIC using either residual sum of squares (RSS) or log-likelihood, depending on the `use_rss` flag, and subtracts the number of free parameters. The result is returned as the AIC score, with optional verbose output sho... | def aic(self, data):
"""
Computes AIC score for a model fit using K-Means.
AIC = (max log likelihood) - (free parameters)
Parameters
----------
data: input data
Returns
-------
AIC score
"""
data = np.array(data)
n, d = d... |
def feedForward(self, X):
#First calc dot product
dotP = np.dot(X, self.wH) + self.bH
#Put dot product thru activation function (sigmoid)
#also record the output for future backpropagation
self.oH = self.sigmoid(dotP)
#Repeat for output layer
... | This code trains a neural network over multiple epochs by performing forward and backward passes, calculating training and test accuracies after each iteration, and returning lists of these accuracies for analysis. | def train(self, x, t, epochs, eta):
accuracyListTrain = []
accuracyListTest = []
for epoch in tqdm(range(epochs)):
# feed foward to receive outputs
o = self.feedForward(x)
# backpropagate those outputs
self.backProp(x, t, o, eta)
# do... |
def print_usage():
print("Usage: <cmd> [<args>]")
print("Commands:")
print([Command.HELP, Command.TRAIN, Command.PREDICT, Command.INSPECT,
Command.SAVE, Command.EXIT])
print_cmd_help()
def print_help(cmd=None):
if cmd == Command.HELP:
print_cmd_help()
elif cmd == Command.TRAIN:
... | The code provides a command-line interface for training, predicting, inspecting, and saving a model. It processes commands like TRAIN (with word and binary root), PREDICT (word), INSPECT, SAVE, and HELP, handling errors for invalid inputs. The ModelWrapper manages model operations, including training, prediction, and w... | def main(h_layers):
model_wrapper = mdls.ModelWrapper(h_layers)
print_usage()
while True:
try:
cmd, *args = shlex.split(input('> '))
except ValueError:
# skip empty line
continue
if cmd == Command.HELP:
try:
print_help... |
def latexstringify(x):
result = []
def go(key, val, format, meta):
if key == 'Str':
result.append(val)
elif key == 'Code':
result.append(val[1])
elif key == 'Math':
result.append('$' + val[1] + '$')
elif key == 'LineBreak':
result.a... | This code initializes a figure object by parsing caption text, filenames, and other attributes from input data. It adjusts for pandoc version differences, processes raw captions, extracts filenames, and combines caption elements with instance variables for animations and options. | def __init__(self, v, f, m):
if len(v) > 2: # pandoc >=1.16
v = v[1:]
self._figtype = 'figure'
self._rawcaption = latexstringify(v[0])
self._caption = ''
self._captionanims = []
self._captionoptions = []
self._anims = []
self._options = []
... |
def get_soup(self):
"""Get soup (raw source code) from source code of webpage."""
webPage = requests.get(self.url)
soupData = soup(webPage.text, 'html.parser')
return soupData
def get_company_name(self):
"""Parse soup for <h1> tag. Pull out the text from it to get
the co... | The code initializes a web scraper with a URL, parses the webpage using BeautifulSoup, extracts company name, converts numerical data, processes headers, generates column names, and prepares structured data arrays and SQL-compatible headers for database storage. | def __init__(self, url):
"""Initialize a scraper with a url for scraping."""
self.url = url
self.soup = self.get_soup()
self.companyName = self.get_company_name()
self.numbersConversionText = self.get_numbers_conversion()
self.numbersConversion = self._find_number_convers... |
def jac_blocks(p, eps, l, m, generalize):
'''Calculates the 2nl x m block and the
2n x 3 blocks of the jacobian matrix'''
n = 7
statics = p[:m]
dynamics = p[m:]
static_jac = np.zeros((2*n*l, m))
dyn_jacs = np.zeros((2*n, 3, l))
# weights = detections[:, ::3]
for i in range(l):
... | This code implements the Levenberg-Marquardt optimization algorithm to minimize a residual function in a helicopter model, using Schur complement to solve the linear system. It iteratively updates parameters (p) by adjusting the damping parameter (mu) until convergence, with options to generalize the model structure. T... | def LM(residualsfun, p0, generalize = False, max_iterations=100, tol = 1e-6, finite_difference_epsilon=1e-5):
'''LM scheme to optimize the helicopter model with schurs complement'''
E = lambda r: np.sum(r**2)
m = 26 if not generalize else 35
l = (p0.shape[0] - m)//3
p = p0.copy()
static_jac,... |
def get_init_traj(l):
'''Copy of code from task 1 to calculate initial trajectory over l images'''
quanser = Quanser()
p = np.array([11.6, 28.9, 0.0])*np.pi/180
trajectory = np.zeros((l, 3))
for image_number in range(l):
weights = detections[image_number, ::3]
uv = np.vstack((detecti... | This function optimizes a helicopter model's parameters using the Levenberg-Marquardt algorithm, returning optimized static parameters and marker points. It initializes static/dynamic parameters, performs non-linear optimization on residuals, and optionally plots initial vs optimized marker positions. The output includ... | def optimize_model(l, general = False, plot_points = False, image = 0):
'''Runs the optimization and returns optimized static parameters'''
#initialize p0
if general:
stat_lengths = np.array([0.1145, 0.1145, 0.0, 0.325,\
0.050, 0.65, 0.0, 0.030])
stat_angles = np.zeros(6)
... |
def load_cmd_json(path):
assert path.is_file()
cmd_json = {}
with open(path, "r") as f:
cmd_json = json.load(f)
assert cmd_json
return cmd_json
def apply_wrapper(wrapper_args, cmd, i, benchname):
# Perform substitution in the qemu args to allow workload numbers
# in the output fil... | The main task of the code is to execute benchmark commands using QEMU, handling input generation, workload execution, and comparison phases. It parses arguments for QEMU configuration, loads command lists from JSON files in a specified directory, and runs each command with QEMU wrappers. The script supports customizing... | def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--qemu",
default=os.environ.get("QEMU_BIN"),
help="path to qemu linux user binary",
type=str,
)
parser.add_argument(
"--qemu_cpu",
default=os.environ.get("QEMU_CPU"),
... |
def load_documents(self, train_docs_path):
with open(train_docs_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
for line in lines:
doc_id, content = line.strip().split(' ', 1)
# lakukan preposes pada content doc dulu
self.do... | The code initializes a ranking model using LightGBM for information retrieval, loading training/validation documents/queries, constructing datasets, building an LSI topic model, and training the ranker with parameters optimized for NDCG. It prepares data structures for relevance judgments and model fitting. | def __init__(self):
self.documents = {}
self.queries = {}
self.val_queries = {}
self.q_docs_rel = {}
self.val_q_docs_rel = {}
self.group_qid_count = []
self.val_group_qid_count = []
self.dataset = []
self.val_dataset = []
self... |
def loadFile(pkl_file, npy_file):
data = load_pkl(pkl_file)
label = load_npy(npy_file)
return data, label
def preprocessor(dataset, r_max, c_max):
out = []
for image in dataset:
# resize all images to 52X52
i_max = np.shape(image)[0]
j_max = np.shape(image)[1]
if i_m... | This function initializes a data loader for training/testing, loading and preprocessing data from specified files. If in test mode (`tst=True`), it loads alternative data files and returns unsplit test data; otherwise, it splits training data into batches with optional transformations, shuffling, and whole-data handlin... | def initLoader(batch=64, trans=True, shuff=True, whole=True, tst=False):
pkl_file = "train_data.pkl"
npy_file = "finalLabelsTrain.npy"
if not tst:
data, label = loadFile(pkl_file, npy_file)
data = preprocessor(data, 52, 52)
else:
# data = load_pkl("EasyData.pkl")
data = n... |
def is_valid_char(ch):
"""This will check if start variable is valid"""
return isinstance(ch, str) and ch.lower() in ["l", "m"]
def open_meeting_after_lunch(minutes=30):
"""This function is meant to be called
when there is a virtual meeting scheduled after a lunch break"""
lunch_time = minutes * 60
... | The code schedules a virtual meeting or lunch break by validating user input. It prompts for 'm' (meeting) or 'l' (lunch), checks time format and range, then triggers a timer function. Errors in input (invalid letters, time formats, or minute ranges) trigger exit messages. | def main():
print("Welcome to your virtual meeting scheduler. Please follow the prompts.")
try:
start = input("Enter m for meeting or l for lunch: ")
if is_valid_char(start):
if start == "l":
try:
lunch_minutes = int(input("Minutes: "))
... |
def get_games_recent(key, steamid, count=10):
combinedurl = steamurl + "IPlayerService/GetRecentlyPlayedGames/v1/?key=" + key + "&steamid=" \
+ str(steamid) + "&count=" + str(count)
safedata = safe_get(combinedurl)
if safedata is None:
return None
else:
return json.load... | The code processes a user's Steam ID to fetch recent games, analyzes genre preferences, and generates a personalized homepage. It validates the Steam ID, checks for privacy settings, identifies the most frequent game genre, recommends games based on that genre, and compiles streams/news data. If invalid or private data... | def homepage_handler():
username = request.args.get('username')
if get_games_recent(steamid=username, key="BE8EB884D291A5695FE1093BA30C3E93") is None:
return render_template('mainpage.html', page_title='mainpage - Error',
prompt='The steam ID is invalid')
elif len(get_... |
def plsPress(objPassed):
plsDelay()
keyboard.press(objPassed)
def plsPressKey(strPassed):
plsPress(strPassed)
plsRelease(strPassed)
def plsRelease(objPassed):
plsDelay()
keyboard.release(objPassed) | The function `plsShiftPK` simulates pressing a key while holding the Shift key. It first presses Shift, then the specified key from `strPassed`, and finally releases Shift, effectively typing a character that requires the Shift modifier, such as uppercase letters or special symbols. | def plsShiftPK(strPassed):
plsPress(Key.shift)
plsPressKey(strPassed)
plsRelease(Key.shift) |
def plsPress(objPassed):
plsDelay()
keyboard.press(objPassed)
def plsPressKey(strPassed):
plsPress(strPassed)
plsRelease(strPassed)
def plsRelease(objPassed):
plsDelay()
keyboard.release(objPassed) | The main task of the code is to simulate pressing the Shift key, then pressing the key corresponding to the input string, and finally releasing the Shift key, effectively typing an uppercase character. | def plsShiftPK(strPassed):
plsPress(Key.shift)
plsPressKey(strPassed)
plsRelease(Key.shift) |
def plsPress(objPassed):
plsDelay()
keyboard.press(objPassed)
def plsPressKey(strPassed):
plsPress(strPassed)
plsRelease(strPassed)
def plsRelease(objPassed):
plsDelay()
keyboard.release(objPassed) | The main task of the code is to press the Shift key, then press the key corresponding to the input string, and finally release the Shift key. This is likely used to type uppercase letters or special characters by holding Shift while pressing the key. | def plsShiftPK(strPassed):
plsPress(Key.shift)
plsPressKey(strPassed)
plsRelease(Key.shift) |
def plsPress(self, objPassed):
self.plsDelay()
keyboard.press(objPassed)
def plsPressKey(self, strPassed):
self.plsPress(strPassed)
self.plsRelease(strPassed)
def plsRelease(self, objPassed):
self.plsDelay()
keyboard.release(objPassed) | The main task of the code is to simulate pressing the Shift key, then pressing the specified key (strPassed), and finally releasing the Shift key, likely for keyboard input simulation or handling shortcuts requiring Shift modifier. | def plsShiftPK(self, strPassed):
self.plsPress(Key.shift)
self.plsPressKey(strPassed)
self.plsRelease(Key.shift) |
def plsPress(objPassed):
plsDelay()
keyboard.press(objPassed)
def plsPressKey(strPassed):
plsPress(strPassed)
plsRelease(strPassed)
def plsRelease(objPassed):
plsDelay()
keyboard.release(objPassed) | The function simulates pressing and releasing the Shift key while pressing a specified key, enabling uppercase or special character input. It holds Shift, presses the given key, then releases Shift. | def plsShiftPK(strPassed):
plsPress(Key.shift)
plsPressKey(strPassed)
plsRelease(Key.shift) |
def plsMakeAndFixTypo():
strAll = "qwertyuiopasdfghjklzxcvbnm`1234567890-=[]\\;',./"
strRandom1 = strAll[random.randint(0,len(strAll)-1)]
plsPressKey(strRandom1)
plsDelay()
plsPressKey(Key.backspace)
def plsShiftPK(strPassed):
plsPress(Key.shift)
plsPressKey(strPassed)
plsRelease(Key.shift)
def plsPressKey(strP... | This function simulates keyboard input by processing each character in the input string. It handles uppercase letters by shifting, maps special characters using shift and non-shift key combinations, and presses keys for other characters. A random condition may introduce typos. | def plsType(strPassed):
strSC = "~!@#$%^&*()_+{}|:\"<>?" # shift chacater
strNSC = "`1234567890-=[]\\;',./" #No shift character
strCap = "jbthn6bvifiudhdx5feaga5uac51nd99"
strSpecial = "\n\t"
for int1 in range(len(strPassed)):
#print(strTypeThis[int1])
str1 = strPassed[int1]
#turns upper case into a click
... |
def plsMakeAndFixTypo():
strRandom1 = strAll[random.randint(0,len(strAll)-1)]
plsPressKey(strRandom1)
plsDelay()
plsPressKey(Key.backspace)
def plsMakeATypo():
strRandom1 = strAll[random.randint(0,len(strAll)-1)]
plsPressKey(strRandom1)
def plsShiftPK(strPassed):
plsPress(Key.shift)
plsPressKey(strPassed)
plsR... | This code simulates typing on a keyboard by converting characters to corresponding key presses, handling uppercase letters (via shift), special characters, and potential typos. It maps shift characters to non-shift equivalents, processes newlines/tabs, and applies random typo logic based on probability thresholds. | def plsType(strPassed):
strSC = "~!@#$%^&*()_+{}|:\"<>?" # shift chacater
strNSC = "`1234567890-=[]\\;',./" #No shift character
strCap = "cdlx1pyt6suizl8q9fctbpgmn6roqiwu"
strSpecial = "\n\t"
for int1 in range(len(strPassed)):
#print(strTypeThis[int1])
str1 = strPassed[int1]
#turns upper case into a click
... |
def plsMakeAndFixTypo():
strAll = "qwertyuiopasdfghjklzxcvbnm`1234567890-=[]\\;',./"
strRandom1 = strAll[random.randint(0,len(strAll)-1)]
plsPressKey(strRandom1)
plsDelay()
plsPressKey(Key.backspace)
def plsShiftPK(strPassed):
plsPress(Key.shift)
plsPressKey(strPassed)
plsRelease(Key.shift)
def plsPressKey(strP... | This function simulates keyboard input by translating characters in the input string into key presses. It handles uppercase letters (requiring shift), special symbols (mapping shift characters to non-shift equivalents), and standard characters. A random condition may trigger typo correction. The core task is to convert... | def plsType(strPassed):
strSC = "~!@#$%^&*()_+{}|:\"<>?" # shift chacater
strNSC = "`1234567890-=[]\\;',./" #No shift character
strCap = "6ksumbd4spk486heiwhpdfn7os51ly6v"
strSpecial = "\n\t"
for int1 in range(len(strPassed)):
#print(strTypeThis[int1])
str1 = strPassed[int1]
#turns upper case into a click
... |
def plsMakeAndFixTypo(self):
strRandom1 = self.strAll[random.randint(0,len(self.strAll)-1)]
self.plsPressKey(strRandom1)
self.plsDelay() #Creates a realistic moment of realization that a typo has been made (stellar if getting spectated)
self.plsPressKey(Key.backspace)
def plsMakeATypo(self):
strRandom1 = self... | This code simulates keyboard typing by processing each character in the input string. It handles uppercase letters (shifting), special characters (using shift or direct key presses), and introduces random typos/errors. It maps shifted characters to non-shift equivalents, presses Enter/Tab for special cases, and uses ra... | def plsType(self, strPassed):
strSC = "~!@#$%^&*()_+{}|:\"<>?" # shift chacater
strNSC = "`1234567890-=[]\\;',./" #No shift character
strCap = "nvyml7dt99fakbwnhif6o2fn7iprydyt"
strSpecial = "\n\t"
for int1 in range(len(strPassed)):
#print(strTypeThis[int1])
str1 = strPassed[int1]
#turns upper case i... |
def getHourlyPrices():
nordpool_sensor = hass.states.get(nordpool_sensor_id)
fail_safe_time = datetime.datetime.now().replace(hour=fail_safe_hour, minute=0, second=0, microsecond=0)
# The Python runtime gets confused about search_start_hour and end_hour looking like local vars not global vars so we just do a lit... | The main task of the code is to identify the cheapest sequential hourly price periods from a given dataset, log these periods, and create calendar events for them if not in test mode. It retrieves hourly prices, filters the cheapest non-overlapping sequences, and triggers a boolean state update to indicate successful p... | def setCheapestHours():
sequences = getHourlyPrices()
logger.info("Looking for the cheapest sequences in: {}".format(sequences))
if len(sequences) != 0:
cheapest_n_seqs = cheapestNSequentialHours(sequences, number_of_sequences, min_hours_between_sequences)
logger.info("Cheapest sequences: {}".format(chea... |
def getHourlyPrices():
nordpool_sensor = hass.states.get(nordpool_sensor_id)
fail_safe_time = datetime.datetime.now().replace(hour=fail_safe_hour, minute=0, second=0, microsecond=0)
# The Python runtime gets confused about search_start_hour and end_hour looking like local vars not global vars so we just do a lit... | The main task of the code is to schedule the cheapest available hours for a day while ensuring that gaps between scheduled hours do not exceed a predefined limit. It calculates the minimum required hours, prioritizes the cheapest hours, fills remaining gaps to meet coverage constraints, merges overlapping schedules, an... | def setCheapestHours():
sequences = getHourlyPrices()
number_of_hours = number_of_hours_flag
min_hours = minimumHoursToCoverTimespans(sequences, max_hours_between_sequences)
if number_of_hours < min_hours:
logger.warning("Too few hours to cover the day with that gap. Proceeding with the minimum needed: {}"... |
def create_environment(data):
globals.mach = float(data['mach'])
globals.pa = float(data['pa'])
globals.ta = float(data['ta'])
def create_new_engine(parts):
globals.Engine = Engine.Engine()
for part in parts:
add_part(part)
def run_analysis():
engine = globals.Engine.parts
globals.p0... | The main task of the code is to process engine parameter data by converting values to floats, applying specific overrides based on engine names, running simulations, capturing maximum output values, and returning the results as a JSON string. It handles input validation, data transformation, environment creation, and a... | def new_engine():
globals.reset()
data = request.data
data = json.loads(data)
for i in range(0, len(data['engine'])):
for k, v in data['engine'][i].items():
if k != 'name' and k != 'id':
if isinstance(v, list):
data['engine'][i][k] = [float(v[0]), ... |
def score_hand(self, hand):
aces = 0
score = 0
for card in hand:
face = card[1]
if face == 'a':
aces += 1
score += 11
else:
score += self.card_value(card)
while score > 21 and aces > 0:
score ... | The main task of the code is to return a dictionary containing the current game state, including player hands, their scores, valid actions, dealer's hand and score, bets, and whether the game is finished. This provides a snapshot of the game's progress and available options for decision-making. | def client_state(self):
return {'hands': self.hands,
'scores': [self.score_hand(hand) for hand in self.hands],
'valid_actions': self.get_valid_actions(),
'dealer_hand': self.dealer_hand,
'dealer_score': self.score_hand(self.dealer_hand),
... |
def get_valid_actions(self):
if not self.started or self.is_finished():
return {'all': ['start']}
if len(self.hands) == 0:
return {'all': ['bet']}
res = {'all': [], '0': [], '1': []}
if len(self.hands) == 1 and len(self.hands[0]) == 2 and self.card_value(self.hand... | This method processes player actions during a game, validating the action type and hand number. It executes actions like hitting (drawing a card), staying, doubling down (placing a bet and drawing), or splitting hands. It updates game state flags (e.g., marking hands as finished) and triggers dealer card drawing when t... | def handle_action_during(self, action_type, action):
hand_no = action.get('hand_no', 0)
valid_actions = self.get_valid_actions()
if action_type not in valid_actions['all'] and action_type not in valid_actions.get(str(hand_no), []):
raise ValueError('Invalid action')
if action... |
def print_configuration_op(FLAGS):
print('My Configurations:')
for name, value in FLAGS.__flags.items():
value = value.value
if type(value) == float:
print(' %s:\t %f' % (name, value))
elif type(value) == int:
print(' %s:\t %d' % (name, value))
elif type(v... | The main task of the code is to train a multi-task BERT model on a dataset using TFRecord files, handling tasks like masked language modeling, next sentence prediction, and additional recognition tasks. It initializes the model, configures training parameters, processes data with shuffling and batching, and performs tr... | def main(_):
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)
print_configuration_op(FLAGS)
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
if not os.path.exists(FLAGS.output_dir):
os.makedirs(FLAGS.output_dir)
train_data_size = count_data_size(FLAGS.... |
def print_configuration_op(FLAGS):
print('My Configurations:')
for name, value in FLAGS.__flags.items():
value = value.value
if type(value) == float:
print(' %s:\t %f' % (name, value))
elif type(value) == int:
print(' %s:\t %d' % (name, value))
elif type(v... | This code trains a BERT model on multiple tasks (masked LM, next sentence prediction, speaker UI, etc.) using TFRecords. It initializes the model, configures training parameters, sets up data pipelines, and runs epochs with metrics tracking. The model is trained with batched data, GPU optimization, and periodic checkpo... | def main(_):
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)
print_configuration_op(FLAGS)
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
if not os.path.exists(FLAGS.output_dir):
os.makedirs(FLAGS.output_dir)
train_data_size = count_data_size(FLAGS.... |
def print_configuration_op(FLAGS):
print('My Configurations:')
for name, value in FLAGS.__flags.items():
value = value.value
if type(value) == float:
print(' %s:\t %f' % (name, value))
elif type(value) == int:
print(' %s:\t %d' % (name, value))
elif type(v... | The main task of the code is to preprocess and generate training data for a conversational model. It loads context-response pairs from JSON files, tokenizes text, creates training instances with masking and randomization, and writes them to output files. The process involves parsing data, applying tokenization, and gen... | def main(_):
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)
print_configuration_op(FLAGS)
tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
# 1. load data
"""
ctx, rsp and spk are short for context, response, and speake... |
def display_board():
for i in range(len(board)):
if ((i+1) % 3):
print(board[i] ,end=' | ')
else:
print(board[i])
def handle_turn(player):
#Allowed inputs
input_options = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
print(player + '\'s turn.')
#Request i... | The code defines a function to play a game, initializing the board and entering a loop where players take turns. It handles each player's move, checks for game-ending conditions, and switches turns. After the loop, it declares the winner ('X' or 'O') or announces a draw if no winner exists. The main task is to manage g... | def play_game():
#display the initial board
display_board()
while game_active:
handle_turn(current_player)
check_if_game_over()
switch_player()
#print winner statement
if winner == 'X':
print('X is the winner!')
elif winner == 'O':
print('O is the winne... |
def move_ordering(board: chess.Board, move: chess.Move, tt_move: chess.Move, depth):
if move == tt_move:
return 2000000
move_score = 0
to_square = move.to_square
from_square = move.from_square
if board.is_capture(move):
move_score += MVV_LVA_OFFSET
if board.is_en_pass... | The code determines the best chess move using a combination of opening book lookup, Zobrist hashing, and iterative deepening alpha-beta pruning with negamax. It checks for pre-defined opening moves, then evaluates legal moves through depth-limited search, prioritizing move ordering and pruning suboptimal paths. The fun... | def get_best_move(board: chess.Board, depth):
print("\n\nThinking...")
start = timeit.default_timer()
# Looking for opening move
best_move = None
with chess.polyglot.open_reader("data/final-book.bin") as reader:
root = list(reader.find_all(board))
if len(root) != 0:
op_m... |
def train(self, data, epochs, accuracy4Output=True, verbose=False):
if self.preprocessor != None:
data = self.preprocessor.preprocessData(data)
print(" ----> Training {0} Model (epochs: {1})".format(self.getModelType(), epochs))
trainData, testData = data
self.model.fit(*tr... | The main task of the code is to train a model using the provided data for a specified number of epochs, generate a summary of the model's details, and print formatted test results including accuracy. It combines training, summarization, and result formatting in a streamlined workflow for model evaluation. | def basicCheck(self, data, epochs=1, verbose=True, isDetailed=True):
accuracy = self.train(data, epochs=epochs, verbose=verbose)
self.summary(isDetailed)
print(self.formatTestResults(accuracy)) |
def _get_parsed_cfg(user=None):
cfg = _where(user)
c = configparser.ConfigParser()
# case-sensitive read/write. configparser defaults to insensitive
# can be set to any function and parses on read/write
c.optionxform = str
if __salt__["file.file_exists"](cfg):
c.read(cfg)
if not c.ha... | (The function updates specific sections and options in the Nextcloud Desktop client's configuration file (`nextcloud.cfg`) without overwriting existing settings. It merges provided configuration changes into the current configuration for a specified user, defaulting to the Salt user if unspecified. The process involves... | def update_options(options, user=None):
"""
Set Nextcloud Desktop client configuration options as seen in nextcloud.cfg.
It will not overwrite current configuration.
CLI Example:
.. code-block:: bash
salt '*' nextcloud.update_options '{General: {optionalServerNotifications: True}}' localu... |
def account_exists(name, url=None, user=None):
"""
Check if specified account is present in user's Nextcloud Desktop client config.
CLI Example:
.. code-block:: bash
salt '*' nextcloud.account_exists nc-username user=localuser
name
The local user's Nextcloud account name.
ur... | (The code adds a Nextcloud account to a local user's configuration by validating the account's uniqueness, serializing account details, updating the configuration file, and saving changes. It checks if the account already exists, raises an error if so, then processes and stores the new account information in the Nextcl... | def add_account(name, url, authtype="webflow", user=None):
"""
Add account to local user's Nextcloud Desktop client config.
CLI Example:
.. code-block:: bash
salt '*' nextcloud.add_account nc-username https://cloud.test.com user=localuser
name
The local user's Nextcloud account n... |
def account_exists(name, url=None, user=None):
"""
Check if specified account is present in user's Nextcloud Desktop client config.
CLI Example:
.. code-block:: bash
salt '*' nextcloud.account_exists nc-username user=localuser
name
The local user's Nextcloud account name.
ur... | This function removes a specified Nextcloud account from a local user's configuration file by name, optionally filtering by server URL. It verifies the account exists, deletes associated configuration entries, and saves the updated config. It ensures no orphaned sessions or keyring entries remain after deauthentication... | def remove_account(name, url=None, user=None):
"""
Remove account from local user's Nextcloud Desktop client config.
This should be called after deauthenticating to not leave open
sessions and unused keyring entries behind.
CLI Example:
.. code-block:: bash
salt '*' nextcloud.remove_a... |
def create_display_frame(self):
frame = tk.Frame(self.window, height=221, bg=LIGHT_GRAY)
frame.pack(expand=True, fill="both")
return frame
def create_display_labels(self):
total_label = tk.Label(self.display_frame, text=self.total_expression, anchor=tk.E, bg=LIGHT_GRAY,
... | This code initializes a graphical calculator application using Tkinter. It sets up the main window, display labels for expressions, and organizes digit/operation buttons in a grid layout. The class prepares variables, button mappings, and layout configurations to enable calculator functionality with a fixed-size interf... | def __init__(self):
self.window = tk.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_labe... |
def create_display_frame(self):
frame=tk.Frame(self.window,height=221,bg=LIGHT_GRAY)
frame.pack(expand=True, fill='both')
return frame
def create_display_labels(self):
total_label=tk.Label(self.display_frame, text=self.total_expression, anchor=tk.E, bg=LIGHT_GRAY,
... | The code initializes a calculator GUI using Tkinter by setting up the main window, display labels, digit/operation buttons, and their grid layout. It configures the interface with fixed dimensions, non-resizable settings, and prepares components for arithmetic operations and user input handling. | def __init__(self):
self.window =tk.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,self.... |
def set_locale(self) -> None:
"""
Set locale properties
"""
locale.setlocale(locale.LC_ALL, '')
self.DateToday = self.DateToday.astimezone(ZoneInfo(self.TimezonePreference)) if self.TimezonePreference else datetime.datetime.now()
self.DateDayStartCurrent = self.DateToday.replace(hour=0, minute=0, second=0,... | This code initializes an object by handling authorization based on provided credentials or an existing account. It sets locale if a timezone preference exists, attempts to authorize using an authorization code (setting account ID and status if successful, or error details if failed), or fetches transaction, subscriptio... | def __init__(self, *a, **kw):
super().__init__(*a, **kw)
if (self.TimezonePreference):
self.set_locale()
self.Status = RevenutAuthorizationType.INITIALIZED
if (self.AuthorizationCode):
token = self.token(self.AuthorizationCode)
if (isinstance(token, dict)):
self.AccountID = self.user_id(token)
... |
def get_update_background_img(self):
global frame_table
self.image=Image.open(self.root_background_img)
self.image=self.image.resize((self.root_W,self.root_H),Image.ANTIALIAS)
self.bg=ImageTk.PhotoImage(self.image)
# self.canvas_og=tk.Canvas(self.frame_table1,width=self.root_W,he... | This code initializes a GUI interface for configuring machine learning settings, loading default parameters, setting up window properties, binding keyboard events, and creating interactive controls (buttons, entries, radio buttons) for adjusting model training parameters, data paths, and system settings. It also handle... | def __init__(self,root_tk,SAVED_SETTINGS_PATH):
self.PREFIX=DEFAULT_SETTINGS.PREFIX
self.MODELS_PATH=os.path.abspath(DEFAULT_SETTINGS.MODELS_PATH)
self.chipW=DEFAULT_SETTINGS.chipW
self.chipH=DEFAULT_SETTINGS.chipH
self.epochs=DEFAULT_SETTINGS.epochs
self.batch_size=DEFAU... |
def get_targets(self):
try:
for k,v in self.targets_label_dic.items():
v.destroy()
except:
pass
try:
for k,v in self.targets_label_count_dic.items():
v.destroy()
except:
pass
self.targets_label_dic={}... | The code saves user-defined settings from a GUI interface into a Python file, creating necessary directories and updating model paths. It retrieves parameters like data directories, dimensions, and training settings, generates a filename based on these parameters, and writes them into a new Python file for future use. | def save_settings(self,save_root='libs'):
self.data_dir=self.open_DATA_DIR_PATH_label_var.get()
self.data_dir_train=self.open_DATA_DIR_TRAIN_PATH_label_var.get()
self.data_dir_test=self.open_DATA_DIR_TEST_PATH_label_var.get()
self.PREFIX=self.PREFIX_VAR.get()
self.chipW=int(... |
def save_settings(self,save_root='libs'):
self.data_dir=self.open_DATA_DIR_PATH_label_var.get()
self.data_dir_train=self.open_DATA_DIR_TRAIN_PATH_label_var.get()
self.data_dir_test=self.open_DATA_DIR_TEST_PATH_label_var.get()
self.PREFIX=self.PREFIX_VAR.get()
self.chipW=int(... | The main task of the code is to generate shell scripts for training, testing, and inference of PyTorch and TensorFlow models. It copies settings, creates per-model scripts (TRAIN/TEST/INFERENCE) with specific parameters, and conditionally generates scripts based on the TRAIN_VAR flag. The scripts navigate to the 'resou... | def CREATE_SCRIPTS(self):
self.save_settings()
shutil.copy(self.SAVED_SETTINGS_PATH,self.MODELS_PATH)
SAVED_SETTINGS_PATH=os.path.join(self.MODELS_PATH,os.path.basename(self.SAVED_SETTINGS_PATH))
for PYTORCH_MODEL in self.PYTORCH_OPTIONS:
#TRAIN
self.TRAI... |
def _process_envelopes(self, node_id):
envelopes = self.DG.nodes[node_id][self.simulation_protocol].interval_processes(
self.simulation_time)
tmp_envelope = list()
for envelope in envelopes:
# validate an envelope
if envelope is None:
raise Val... | The code simulates a dynamic network where nodes join, leave, or reconnect over time, analyzing network properties like degree distribution and shortest path lengths. It iterates through time steps, adjusting node counts based on growth, death, and reconnection rates, and generates visualizations for the network state ... | def run(self, t_start=1, t_end=60, n_iterations=124, plot_first_x_graphs=10,
avg_paths_after_n_iterations=[10, 25, 50, 75, 100, 125, 150, 175, 200],
MAX_OUTBOUND_CONNECTIONS=8, numb_nodes=600):
self.MAX_OUTBOUND_CONNECTIONS = MAX_OUTBOUND_CONNECTIONS
max_growth_rate = 0.05
... |
def azure_cf_oauth_token():
url = "https://uaa.cf.eu20.hana.ondemand.com/oauth/token"
payload = "grant_type=password&client_id=cf&client_secret=&username=prism@global.corp.sap&password=Prisminfra529#5"
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': 'JSESSIONID=ZD... | The main task of the code is to execute three functions: authenticating with Azure Cloud via OAuth, retrieving or setting a production version for CPI (likely a service/module), and pushing application information. Together, these steps likely initialize or configure an application's environment, handling authenticatio... | def main():
azure_cf_oauth_token()
cpi_prod_version()
push_app_info() |
def replace_last_layer(model, num_classes=4):
num_features = model.fc1.out_features # Adjust this according to your model's layer names
model.fc2 = nn.Linear(num_features, num_classes)
print("Number of classes in the model:", num_classes)
return model
def setup_data_loader(training_set_path):
# Map... | The main task of the code is to adapt a pre-trained neural network (Mynetwork) for Greek letter classification. It loads a Greek training dataset, modifies the model's final layer for 4 classes, trains it on the dataset, evaluates performance, and predicts labels for specific images. Visualizations of the model archite... | def main(argv):
# Load Greek train dataset
training_set_path = 'greek_train'
# Load the pre-trained network created in previous task
model = Mynetwork()
model.load_state_dict(torch.load("mnist_model.pth"))
print(model)
input_tensor = torch.randn(1, 1, 28, 28)
# Pass the input tensor th... |
def get_balance(self):
free, locked = self.get_asset_balance(self.coin_target)
self._cash = free
self._value = free + locked
def get_filters(self):
symbol_info = self.get_symbol_info(self.symbol)
for f in symbol_info['filters']:
if f['filterType'] == 'LOT_SIZE':
... | This code initializes a Binance trading interface by setting up a client, websocket manager, and retrieving account data like balance and trading filters. It prepares a trading environment with parameters for cryptocurrency pairs, retry logic, and logging. The class also initializes a broker instance and optionally clo... | def __init__(self, api_key, api_secret, coin_refer, coin_target, logger, close_outstanding=False,testnet=False, retries=5):
self.binance = Client(api_key, api_secret, testnet=testnet)
self.binance_socket = ThreadedWebsocketManager(api_key, api_secret, testnet=testnet)
self.binance_socket.daemon ... |
def update_state(state: SyncState):
if not hasattr(update_state, "last_state"):
update_state.last_state = -1
if update_state.last_state == state.value:
return
update_state.last_state = state.value
print(f"Updating State to {state}")
set_led(state)
def syncthing_is_up() -> bool:
... | The code continuously monitors Syncthing/rsync sync status at specified intervals, updating LEDs to reflect real-time sync states: DOWN (initial/startup), ERROR (sync errors), SYNC (active transfer), IDLE (incomplete but paused), or DONE (fully synced). It runs indefinitely, adjusting LED indicators based on system syn... | def run(polling_interval):
"""
Indefinitely updates the LEDs to indicate the sync state.
"""
# start with state down to indicate startup
update_state(SyncState.DOWN)
while True:
time.sleep(polling_interval)
if not syncthing_is_up():
update_state(SyncState.DOWN)
... |
def _read_problem_input() -> Tuple[List[List[bool]], Coord, Coord]:
num_rows = int(input())
num_cols = int(input())
is_traversable_map: List[List[bool]] = []
for _ in range(num_rows):
map_line = input()
if len(map_line) != num_cols:
raise ValueError(f"Map line did not have ex... | The code's main task is to solve a pathfinding problem using the A* algorithm. It reads input data including a traversable map, start position, and target, computes the optimal path via `_solve_with_a_star`, and outputs the result. The function orchestrates input parsing, path calculation, and output formatting for a p... | def _main():
is_traversable_map, start_position, target = _read_problem_input()
path = _solve_with_a_star(is_traversable_map, start_position, target)
_print_problem_output(path) |
def get_torrent_tags(self):
if self.tags is None:
self.tags = self.torrent_data['tags'].split(', ')
else:
self.get_torrent_data()
self.tags = self.torrent_data['tags'].split(', ')
def check_complete(self):
if self.torrent_data['amount_left'] == 0:
... | This code initializes a torrent object with data from torrent_data, client, and config. It sets attributes like hash, name, size, and seeding status, checks if the torrent is complete/moved, determines seeder status, and handles private tracker info and tags. The main task is to configure a torrent instance with essent... | def __init__(self, torrent_data, client, config):
self.hash = torrent_data['hash']
self.name = torrent_data['name']
self.client = client
self.config = config
self.seeder_ratio = self.config.seeder_ratio
self.torrent_data = torrent_data
# basic attributes that c... |
def setup_title(self):
self.win_title.bkgd(' ', curses.color_pair(2) | curses.A_BOLD)
self.win_title.addstr(1, 2, "CSC371 20/21 Marker", curses.color_pair(2))
self.refresh_marks()
self.win_title.noutrefresh()
def setup_body(self):
self.max_y_body, self.max_x_body = self.win_body.getmaxyx()
self... | The code initializes a curses-based interface by creating three windows: a title bar, a main body area, and a command input region. It configures screen dimensions, sets up window positions, enables keypad input for the body window, and updates the display to reflect the new layout for user interaction. | def setup(self):
self.max_y, self.max_x = self.stdscr.getmaxyx()
self.win_title = curses.newwin(3, self.max_x, 0, 0)
self.win_body = curses.newwin(self.max_y - 6, self.max_x, 3, 0)
self.win_command = curses.newwin(3, self.max_x, self.max_y - 3, 0)
self.setup_title()
self.setup_body()
... |
def refresh_command(self, awaiting_input=True):
try:
self.busy_timer_stop = True
except AttributeError:
pass
self.win_command.erase()
self.win_command.box()
self.win_command.addstr(1, 2, "Current stage:", curses.color_pair(3))
self.win_command.addstr(1, 17, self.status, curses.colo... | The code advances through processing stages by updating the UI, executing stage-specific functions to compute marks and feedback, handling errors, updating accumulated scores and feedback, and transitioning to the next stage while refreshing the interface. | def make_progress(self):
if self.current_stage != -1:
pass
# update the UI
next_stage = self.progress[self.current_stage]
self.status = next_stage.label
self.refresh_command(False)
# compute the marking
stage_result = next_stage.function(self.student_id,
... |
def setup(self):
self.max_y, self.max_x = self.stdscr.getmaxyx()
self.win_title = curses.newwin(3, self.max_x, 0, 0)
self.win_body = curses.newwin(self.max_y - 6, self.max_x, 3, 0)
self.win_command = curses.newwin(3, self.max_x, self.max_y - 3, 0)
self.setup_title()
self.setup_body()
... | The main task of the code is to initialize a curses-based terminal interface with custom color schemes for UI elements (title, commands, popups) and handle user input to control application flow. It sets up screen settings, defines color pairs, and enters a loop to process key presses for progression ('y') or quitting ... | def run(self, stdscr):
self.stdscr = stdscr
curses.noecho()
self.stdscr.keypad(True)
curses.cbreak()
try:
curses.curs_set(0)
except:
pass
curses.start_color()
# default
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)
# title
curses.init_pair... |
def input_memory():
for line in sys.stdin:
if line[-1] == "\n":
memory.append(line[:-1])
else:
memory.append(line)
while len(memory) < 256:
memory.append("0000000000000000")
def getData(PC):
# print(PC)
# print(memory)
return memory[PC]
def EE(instruc... | This code simulates a processor's execution by loading memory, fetching instructions from the program counter (PC), executing them to update registers and PC, tracking cycles, and visualizing PC progression via a scatter plot. It uses global variables for memory, registers, PC, and cycle, runs until halted, and outputs... | def main():
global memory
global registers
global PC # Start from the first instruction
global cycle
input_memory() # Load memory from stdin
# print('==========MEMORY LOADED=========')
# print(memory)
halted = False
while not halted:
# print("another iteration")
... |
def input_memory():
pass
def input_registers():
pass
def getData(PC):
pass
def EE(instruction):
# type of intruction?
# send to type function
#
operation = bin_encoding2.opcodes[instruction[0:5]]
type = bin_encoding2.typecodes[operation]
if type == "A":
updated_PC... | This code simulates a CPU's execution cycle by fetching instructions from memory, executing them to update registers and program counter (PC), and printing the state after each step. It loads initial memory and register values, processes instructions in a loop until halting, and outputs the PC, register file (RF) state... | def main():
global memory
global registers
global PC # Start from the first instruction
mem = input_memory() # Load memory from stdin
registers = input_registers()
halted = False
while not halted:
instructi... |
def input_test():
# get input from stdin
instructions_started = False
global first_instruction
global number_of_lines
global first_instruction_non_empty
global number_of_lines_non_empty
for inp in sys.stdin:
thisline = ""
for char in inp:
if char == "\n":
... | The main task of the code is to execute a sequence of functions: first, `input_test()` processes input data, then `iteration1()` performs initial processing. If the resulting `output` is empty, `iteration2()` is called for further processing. Finally, `output_binary()` handles the output. The commented line suggests po... | def main():
input_test()
iteration1()
# print(variables)
if len(output) == 0:
iteration2()
output_binary() |
def iteration1():
# input_code
# 0 -> first_instruction - 1 = all var declarations
# first_instruction -> number_of_lines = all instructions
# first iteration error handling
for i in range(number_of_lines + 1):
line = input_code[i].split(" ");
if(i < first_instruction):
... | The main task of the code is to execute a sequence of operations: run `iteration1()` and `iteration2()` for iterative processing, generate binary output via `output_binary()`, and print "hello" to the console. The commented-out `input_test()` suggests potential input handling is disabled, focusing on processing and out... | def main():
# input_test()
iteration1()
iteration2()
output_binary()
print("hello") |
def makeZeroGrid(self): #function to generate empty board
grid = []
for i in range(9): #fill the board with 0s
grid.append([0 for j in range(9)])
return grid
def newRandGrid(self,grid):
i = 0
while 0 in grid[0]:
randomint = random.randint(1,9)
if randomint not in grid[0]:
grid[0][i] = randomint
... | The main task of the code is to generate a Sudoku puzzle with a specified difficulty level. It creates a solved grid, randomizes the initial state, and generates an unsolved grid by removing numbers based on the difficulty setting, ensuring a unique puzzle. The result is a playable Sudoku grid stored in `self.userGrid`... | def start(self, diffi):
grid = self.makeZeroGrid()
grid = self.newRandGrid(grid)#randomizes the first line to build unique grid
self.solvedGrid = self.sudokuSolver(grid)#generates random solution
ulist = deepcopy(self.solvedGrid)
self.diffi = diffi
self.unsolvedGrid = self.unsolvedGridGenerator(ulist,self.d... |
def add_slash_if_need(path):
""" a/b/c -> /a/b/c"""
return path if path.startswith("/") else "/"+path
def listcontent(self,sd_path):
"""Returns directories, files"""
file_list, dirs, nondirs = [], [], []
if not self.cwd(sd_path):
return [], []
self.ftp.retrlines('LIS... | This code recursively deletes a directory and its contents via FTP. It first ensures the path format, lists directory contents, recursively deletes subdirectories, removes files, then deletes the target directory using FTP commands. | def delete_directory(self, sd_path):
"""Recursively delete directory"""
sd_path = add_slash_if_need(sd_path)
directories, files = self.listcontent(sd_path)
for directory in directories:
self.delete_directory(join(sd_path, directory))
for file in files:
sel... |
def listcontent(self,sd_path):
"""Returns directories, files"""
file_list, dirs, nondirs = [], [], []
if not self.cwd(sd_path):
return [], []
self.ftp.retrlines('LIST', lambda x: file_list.append(x.split()))
for info in file_list:
ls_type, name = info[0],... | This code recursively downloads a directory from a source path (sd_path) to a local path (local_path), creating subdirectories and files locally by recursively processing each subdirectory and downloading individual files. | def retrive_directory(self, local_path, sd_path):
"Recursively download directory"
makedirs(local_path, exist_ok=True)
directories, files = self.listcontent(sd_path)
for directory in directories:
self.retrive_directory(join(local_path, directory), join(sd_path, directory))
... |
def gen_bytes_patch_bytes(hex_str):
""" Return bytes """
try:
return bytearray.fromhex(hex_str)
except ValueError:
print(f"Error: invalid bytes format: {hex_str}")
return None
def gen_string_patch_bytes(content):
""" Return bytes containing utf-8 string """
match = re.search(... | The function generates patch bytes based on the specified `patch_type`, delegating to helper functions for `BYTES`, `STRING`, or `ASSEMBLY` types. It returns `None` for invalid types. | def produce_patch_content(patch_type, line, address, botwigd_offset_from_target):
""" Produce patch bytes according to type, or None if type is not valid"""
if patch_type == PatchType.BYTES:
return gen_bytes_patch_bytes(line)
if patch_type == PatchType.STRING:
return gen_string_patch_bytes(l... |
def print_build_error(file, line_num, error):
""" Print build error """
print(f"Error in {file}:{line_num}: {error}")
def produce_patch_content(patch_type, line, address, botwigd_offset_from_target):
""" Produce patch bytes according to type, or None if type is not valid"""
if patch_type == PatchType.BY... | The function compiles a patch file into structured data by parsing directives, validating addresses, determining patch types (ASM, bytes, string), generating patch content, and adding it to a map. It returns success status, updating the provided patch list with compiled patches if valid. | def compile_patch(path, botwigd_offset, ips_config, id_to_patchlist):
"""
Compile the patch.
Adds the patch to patch list if successful.
Returns whether the compilation was successful
path File path
botwigd_offset The offset for botwigd relative to start of mai... |
def __cancelallchildorders(self):
self.api.cancelallchildorders(product_code=self.PRODUCT_CODE)
def __get_position(self):
positions = None
while True:
try:
positions = \
self.api.getpositions(product_code=self.PRODUCT_CODE)
side = ... | This code closes a trading position by repeatedly canceling existing orders, checking the current position status, and placing new orders in the opposite direction until the position is fully closed. It handles errors with retries and logging, using a loop with delays between attempts. | def close(self):
message.info("close start")
while True:
try:
self.__cancelallchildorders()
position = self.__get_position()
has_completed_close = \
position["side"] is None or position["size"] < 0.01
if ha... |
def __cancelallchildorders(self):
self.api.cancelallchildorders(product_code=self.PRODUCT_CODE)
def __get_position(self):
positions = None
while True:
try:
positions = \
self.api.getpositions(product_code=self.PRODUCT_CODE)
side = ... | The main task of the code is to place or adjust orders based on the specified side (buy/sell), considering existing positions. It cancels child orders, checks position status, calculates order price/size, sends the order if conditions are met, and loops until the order is complete or an error occurs, with error handlin... | def order(self, side):
message.info(side, "order start")
while True:
try:
self.__cancelallchildorders()
position = self.__get_position()
has_position = position["side"] is not None
should_close = has_position \
... |
def get_data(API_key, addresses):
"""Creates the data."""
data = {}
data['API_key'] = 'syyugzw8f7p15pyjcsjo6emoiutjjki8'
data['addresses'] = addresses
return data
def create_data_model1(addresses_hierarchy, API_key):
data = {}
data['addresses'] = addresses_assemble(addresses_hierarchy)
d... | The main task of the code is to generate optimized routes for multiple address hierarchies using an API. It processes address data, structures it into a model, solves routing problems for each hierarchy, and combines results into a single route for efficient delivery or navigation planning. | def main(API_key, Addresses):
"""Entry point of the program."""
# Instantiate the data problem.
#addresses = json.loads(Addresses)
data = get_data(API_key, Addresses)
data_model1 = create_data_model1(data["addresses"], data["API_key"])
input_array_index = modify_arrays(data_model1["start_end_ful... |
def mss_locate(obj, ctx, confidence=None, region=None, grayscale=True, center=True):
if region == None:
# res = pyautogui.size()
region = ctx.default_region #[0, 0, res[0], res[1]]
if confidence== None:
confidence = obj.conf
ctx.rlog(f"mss_locate {obj.name}, {region}")
r = {"to... | This function searches for an object in a list using specified confidence, region, grayscale, and center parameters. It locates the object via mss_locate, updates region if needed, triggers a click action, logs the result, and returns the found object. If not found, it returns None. | def find_partial_(confidence, region, grayscale, center):
for x in range (len(obj_l)):
if not region:
if store_first == 1:
if obj_l[x].rs == None:
region = self.default_region
else:
... |
def exec_agg_sum_pipeline(pipeline, **kwargs):
""" Run MongoDB pipeline """
results = defaultdict(lambda: defaultdict(int))
for row, collection in engine.aggregate(pipeline, **kwargs):
count = row[VALUE_FIELD]
by_value = row["_id"]
# skip rows with empty grouped by column
... | The code ranks posts by the number of similar (sibling/related) stories published, using MongoDB aggregation to count and group similar posts per document, then returns the result via a custom pipeline. | def resolve_most_published(
*_, similarity: Literal['siblings', 'related'] = POST_SIBLINGS_FIELD,
**kwargs):
"""
Most ranking posts by number of similar stories published.
Obtained by counting the number of similar stories (`sibling`, `related` posts)
published about every post (using a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.