dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def random_json():
data = {"secret": fake.text()}
return json.dumps(data, separators=(',', ':'))
def tokenize_via_reverse_proxy(original_data):
script = read_script('./post_token.js', url='https://{}/post'.format(reverse_proxy), data=original_data)
data = chrome_post(script=script)
return json.loads... | The code tests a tokenization and revelation process using proxies. It generates a random JSON, tokenizes it via a reverse proxy (verifying transformation), then reveals it via a forward proxy (ensuring data restoration). Assertions confirm original ≠ tokenized and original == revealed, validating proxy functionality. ... | def main():
original_value = random_json()
print(original_value)
tokenized_value = tokenize_via_reverse_proxy(original_value)
print(tokenized_value)
assert original_value != tokenized_value
revealed_value = reveal_via_forward_proxy(tokenized_value)
print(revealed_value)
assert origina... |
def points_to_poly(points):
return Polygon(shell=[(p[0], p[1]) for p in points])
def get_included_businesses(boundaries, business_census_csv_file):
# list(boundaries.boundary.array_interface()['data'])
discarded_empty = 0
businesses_within = []
addresses_seen = dd(int)
for biz, cnt in load_tsv(... | This function generates a 3D KML map visualizing business population density by census blocks. It processes boundary data, extracts businesses within those boundaries, associates them with census blocks, and creates a 3D representation with adjustable height and styling. Output is saved as a KML file with specified par... | def gen_3d_map_from_business_pop_and_blocks(
boundary_file_or_points,
business_census_csv_file,
census_shapefile_pathname,
pathname_prefix, project_title, styleset,
max_height=250, reset=False, kml_suffix=".kml"):
global object_maker_fn
object_maker_fn = make_kml_poly_3d
... |
def scale_ivs(df: pd.DataFrame) -> tuple:
"""z-scale/standardize the independent variables of df
Args:
df (pd.DataFrame): data frame with Xs
Returns:
tuple
pd.DataFrame: data frame with standardized Xs
list: names of scaled ivs
"""
cols = df.columns
cols... | The code simulates iterative trials where participants perceive pairs of stimuli, using a Gaussian Process (GP) model to predict outcomes and logistic regression to determine acceptance probabilities of the second stimulus. It alternates between fixed and sampled reward scenarios, updating the GP model and test data ba... | def run_perception_pairs(
dict_info: dict,
df_xy: pd.DataFrame,
refit_gp: bool = False,
readjust_representations: bool = False,
) -> tuple:
"""iterate over trials noisily perceiving pairs of stimuli from test dataset
feed GP predicted y values into logistic regression predicting probability of a... |
def menu_gui(self):
'''
Function to add menubar items to gui
All code related to menubar items and binding should be placed here.
'''
#add menu bar
self.menubar = tk.Menu(self.root)
self.root.config(menu=self.menubar)
#add 'file' heading
self.fil... | The main task of the code is to create and configure a main GUI window using Tkinter. It initializes the root window, sets its title, size, and resizability, loads UI components via helper methods (menus, frames, input fields), populates a well list, sets an icon, and starts the main event loop to display the applicati... | def main_gui(self):
'''
Function to create main gui window
All code related to root object should be placed here.
'''
#instantiate main window
self.root = tk.Tk()
self.root.title(self.window_title)
#define window size and make it fixed
se... |
def create_results_df(self,density_algs,ra_percentile=30,ra_range=[1,1.1,0.9]):
ra_base=[(norma, np.percentile(self.D_XToX[norma_i], ra_percentile)) for norma_i, norma in enumerate(self.normas)]
ra_values=dict([(i, [ra_*x for x in ra_range]) for i, ra_ in ra_base])
indexes=((norma,density_alg,r... | The code executes a clustering pipeline for multiple density-based algorithms (e.g., 'substractive', 'mountain') and range parameters (ra_range). It iterates over norms, computes clustering results (k_n, c_n) for each algorithm-RA combination, handles errors, and stores outcomes in a structured DataFrame. Finally, it c... | def do_ClusterPipeline(self, density_algs=['substractive','mountain'], ra_range=[0.3,0.5,1,2,3,4,6,10]):
ra_values=self.create_results_df(density_algs,ra_percentile=40,ra_range=ra_range)
for norma_i, norma in enumerate(self.normas):
print('calculating for norm %s'%norma)
k_histor... |
def create_currencies_dict(ccy_list, date_range_dictionary):
if type(ccy_list) == str:
ccy_list = [ccy_list]
ccy_dict = {}
for ccy in ccy_list:
ccy_dict[ccy] = {"Open": None, "High": None, "Low": None, "Close": None}
ccy_dict[ccy]["Open"] = get_prices(ccy, date_range_dictionary)["Ope... | The code's main task is to generate and print currency data ranges for each currency in the provided list over a specified time period. It creates a currency dictionary, iterates through each currency, constructs a DataFrame, and prints the data range. The function uses helper functions to fetch data, structure it, and... | def print_ccy_levels(ccy_list, time_period=30):
currencies = create_currencies_dict(ccy_list, date_range(time_period=time_period))
for ccy in ccy_list:
df = create_df(ccy, currencies)
print_range(df)
pass
pass |
def read_json(json_path):
with open(json_path) as json_data_file:
data = json.load(json_data_file)
return data
def create_go(
name,
json_obj=None,
json_path=None,
transform_override=None,
go_script_module=None,
):
if not json_obj and not json_path:
raise ValueError("Must ... | The function `create_scene` loads a scene definition from a JSON file, processes wall/ground definitions if present, creates game objects with optional overrides and scripts, disables objects if specified, generates tilemaps for walls/ground, and returns a list of all created game objects. | def create_scene(scene_def_json_path):
with open(scene_def_json_path) as scene_def_json_file:
scene_def_json_object = json.load(scene_def_json_file)
wall_def_json_object, ground_def_json_object = None, None
if "wall_definition" in scene_def_json_object.keys():
wall_def_path = scene_def_json... |
def heuristique(k):
items_copy = items.copy()
items_copy.sort(reverse=True, key=k)
result = 0
n = len(items_copy)
i = int(0)
solution = [0]*n #les valeurs de x
W = capacity
while i < n:
x = 0
while W-items_copy[i][1] > 0:
result += items_copy[i][0]
... | The code reads input data from "testcases.txt" to configure a problem (capacity, benefits, items). It applies a heuristic (`tri_a`) to generate an initial solution (S0), then uses a genetic algorithm (AG) to find an optimized solution (S*). The code measures execution time, prints both solutions and their objective val... | def worker():
global items
global capacity
file = open("testcases.txt", 'r')
benefices = []
for line in file:
values = line.split()
if len(values) == 0:
continue
else:
if values[0] == "$1":
capacity = int(values[-1])
elif va... |
def debug(msg):
pass
eprint(msg)
def target_directory_from_kwargs(**kwargs) -> str:
return kwargs["target_directory"] if "target_directory" in kwargs else "."
def repourl_from_kwargs(**kwargs) -> str:
return kwargs["repourl"] if "repourl" in kwargs else DEFAULT_CONAN_URL
def conan_fully_qualify_latest_v... | The main task of the code is to download a Conan package from a specified repository to a target directory, using fully qualified version details (name, version, revisions, package ID) to construct the download URL. It validates required parameters, handles URL encoding, and saves the downloaded `.tgz` file with a name... | def conan_download_package(cv: ConanVersion, **kwargs) -> str :
"""
returns path to downloaded file
Parameters:
package_name
package_version
recipe_revision
package_id
kwargs:
target_directory: directory to save the downloaded file into. Optional, Default current d... |
def _check_fleet_edges(self):
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
#Reaction to an alien hitting the ship
if self.stats.ships_left > 0:
self.stats.shi... | This function updates the positions of all aliens in the fleet, checks for collisions between the player's ship and aliens, and verifies if any alien has reached the bottom of the screen, triggering appropriate responses like collision handling or game state changes. | def _update_aliens(self):
#updating the position of all the aliens in the fleet
self._check_fleet_edges()
self.aliens.update()
#Checking collision between the ship and the aliens
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
... |
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
#move the ship to the right
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
#move the ship to the left
self.ship.moving_left = True
elif event.key == pygame.K_DO... | The main task of the code is to monitor and respond to user inputs (keyboard, mouse) in a Pygame application. It checks for events like window closure, key presses, key releases, and mouse clicks, delegating specific actions to helper methods for quitting the game, handling key inputs, and detecting mouse button presse... | def _check_events(self):
#waiting for keyboard or mouse input
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP... |
def _check_events(self):
#waiting for keyboard or mouse input
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP... | The main task of the code is to run the game loop by continuously checking for events, updating game elements (ship, bullets, aliens) when the game is active, and rendering the screen to create an interactive gaming experience. | def run_game(self):
# starting the main loop of 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 callback(event):
"""
this callback displays message to the screen
:param event:
:return:
"""
window = Tk()
window.wm_withdraw()
window.geometry("1x1+200+200")
tkinter.messagebox.showinfo(title="Greetings", message=event)
def update_world():
wf.world = world_graph.GraphRange(c... | The function `show` either loads a graph from a JSON file or initializes a new directed graph based on the `new_graph` parameter. It then updates the world state and renders the graph, handling errors if the file is not found. | def show(new_graph: bool = False):
if not new_graph:
if not controller.graph_algo.load_from_json(f'../../data/{filename}.json'):
callback('Error file was not found')
return
else:
controller.graph_algo.graph = DiGraph()
update_world()
show_graph() |
def _check_validatation_data(self, data):
detail_key = "detail"
if detail_key in data:
return False
return True
def _json_format_response(self, response_data):
return json.dumps(response_data)
def get_attribute(get_from, prop_name, default=None):
"""
Get attribute fro... | This code renders input data into an XLSX workbook with customizable headers, column styles, and body formatting. It validates data, creates a spreadsheet, applies header titles/images/styles, sets column widths, and populates rows with data from 'results', handling different data types (dict/list). The output is a byt... | def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Render `data` into XLSX workbook, returning a workbook.
"""
if not self._check_validatation_data(data):
return self._json_format_response(data)
if data is None:
return bytes()
... |
def find_longest_substring(original: str, target: str) -> str:
current_longest = ""
for i, original_char in enumerate(original):
for j, target_char in enumerate(target):
if original[i] == target[j]:
testing = test_next_chr(original, target, i, j, original[i])
... | This function calculates the distance between two strings by recursively finding the longest common substring, splitting the strings around it, and summing the distances of the left and right segments. If no common substring exists, it returns the maximum length of the two strings. | def distance(original, target, start_dist=0):
longest_substring = find_longest_substring(original, target)
if longest_substring == "":
return start_dist + max(len(original), len(target))
else:
new_orig_left = get_left(original, longest_substring)
new_targ_left = get_left(target, long... |
def test_1(math_function: string, plain_text, key, base):
print()
print(math_function.__name__)
print(f"Base:{base} plaintext:{to_base(plain_text, base)} key:{to_base(key, base)}")
temp = math_xor(plain_text, key, base, math_function)
print(f"1 time {to_base(temp, base): >8}")
for i in range(... | The code's main task is to test various mathematical functions (difference, analytical, no-carry addition, square of difference) using predefined values (plain_text=139, key=127, base=16). It iterates through these functions, executing `test_1` for each, then separately tests `analytical` and `no_carry_addition` with t... | def main():
plain_text = 139
key = 127
base = 16
math_functions = [difference, analytical, no_carry_addition, square_of_difference]
for func in math_functions:
test_1(func, plain_text, key, base)
test_analytical(base)
test_no_carry_addition(base) |
def lock(self):
print("GPS locking...")
while True:
try:
self.get_data()
# print(self.__NMEA_buff)
self.__locked = int(self.__NMEA_buff[5])
# print(type(self.__locked),self.__locked)
if self.locked():
... | The code continuously acquires a lock, retrieves data, updates internal state, and processes GPS information in an infinite loop to ensure thread safety and real-time data handling. | def run(self):
self.lock()
while True:
self.get_data()
self.__update_data()
self.__gps_info() |
def read_id_mapping(self, path):
"""
Used for reading the app_id.txt and users.txt, both of which contain a list of IDs in single-data format.
Sample return value: {'273813': 0, '2312515': 1}
:return: Dictionary, key = ID, value = mapped ID
"""
mapping = {}
... | The code initializes a data loader for a graph-based model, setting up paths for Steam dataset files (user IDs, app info, friends, etc.). It reads ID mappings, builds validation/test data, and loads or preprocesses a graph (via DGL). If a preprocessed graph exists, it loads it; otherwise, it processes data (via `self.p... | def __init__(self, args, root_path, user_id_path, app_id_path, app_info_path, friends_path, developer_path, publisher_path, genres_path, device = 'cpu', name = 'steam'):
logging.info("steam dataloader init")
self.args = args
self.root_path = root_path
self.user_id_path = user_id_path
... |
def normalize_text(text: str) -> str:
text = ' ' + text.lower().strip() ###adding the ' ' is important to make the consist encoder, for roberta tokenizer
return text
def normalize_question(question: str) -> str:
question = question
if question[-1] == '?':
question = question[:-1]
return ques... | This function processes a row of data by filtering valid supporting facts, normalizing the question and answer, and checking if the answer exists in the selected contexts. It structures the context paragraphs with flags indicating support status, answer presence, and spans, returning normalized inputs and flags for dow... | def selected_context_processing(row, tokenizer, selected_para_titles, is_roberta):
question, supporting_facts, contexts, answer = row['question'], row['supporting_facts'], row['context'], row['answer']
doc_title2doc_len = dict([(title, len(text)) for title, text in contexts])
supporting_facts_filtered = [(s... |
def json_loader(json_file_name: str):
with open(json_file_name, 'r', encoding='utf-8') as reader:
json_data = json.load(reader)
return json_data
def selected_context_processing(row, tokenizer, selected_para_titles, is_roberta):
question, supporting_facts, contexts, answer = row['question'], row['sup... | The function tokenizes and prepares data for a question-answering model by processing JSON files containing paragraphs, full questions, and named entities. It tokenizes questions and context sentences, identifies answer positions, constructs graph edges based on entity relations, and generates structured examples with ... | def hotpot_sent_edge_tokenizer(para_file: str,
full_file: str,
ner_file: str,
tokenizer,
cls_token='[CLS]',
sep_token='[SEP]',
is_roberta=False,
... |
def _render_subsector(subsector_index:int, player:Player):
render_list : List[ScreenColumn] = []
subsector = ssectors[subsector_index]
for i in range(subsector.n_segs):
seg_index = subsector.start_seg + i
seg = segs[seg_index]
linedef = linedefs[seg.linedef]
if linedef.back... | This function recursively renders BSP (Binary Space Partitioning) nodes by checking the player's position relative to node planes. It traverses the tree, appending visible subsectors or child nodes to a render list based on frustum culling and bounding box intersections, optimizing rendering by only processing visible ... | def _render_bsp_node(player:Player, node_index:Optional[int]=None):
if node_index is None:
node_index = len(nodes) - 1
if node_index >> 15:
return _render_subsector(node_index ^ (1 << 15), player)
node = nodes[node_index]
render_list : List[ScreenColumn] = []
if _on_right_side(pla... |
def create_workflow(
self,
job: DescribeJob,
parameters: Dict[str, str],
staging_paths: Dict,
db_url: str,
use_conda_store_env: bool = True,
):
input_path = staging_paths["input"]
log_path = gen_log_path(input_path)
papermill_status_path = gen_... | This code executes workflow or cron-workflow actions based on `self.job_id` or `self.job_definition_id`. For workflows, it creates, deletes, or stops jobs using methods like `create_workflow`/`delete_workflow`. For cron-workflows, it creates, updates, or deletes scheduled jobs via `create_cron_workflow`/`update_cron_wo... | def execute(self):
model = self.model
if self.job_id:
if self.action == WorkflowActionsEnum.create:
self.create_workflow(
job=model,
parameters=self.parameters,
staging_paths=self.staging_paths,
... |
def check_email_exsistence(self):
"""
This function ensures that no duplicate data/email is stored in the database
It gets the input and checks if it exists in the database, if True meaning it already exist
else if false meaning it doesnt exist
"""
self.email_exists = Fa... | The code validates an email address, checks for duplicates, and subscribes the user by storing the email in a SQLite database. If invalid or duplicate, it displays an error; otherwise, it inserts the email, logs the current date, deletes older entries, and clears the input field. | def subscribe(self):
# Create an object from the Class validator to
# check for the email validity
self.validator = Validator(self.user_email.get())
self.valid = self.validator.check_for_symbol()
if (
self.user_email.get() == ""
or self.valid is False
... |
def create_button(x, y, width, height, hovercolor, defaultcolor, msg, player1='', player2='', player3=''):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed(3)
if x + width > mouse[0] > x and y + height > mouse[1] > y:
pygame.draw.rect(screen, hovercolor, (x, y, width, height), bo... | The code implements a game menu allowing users to input names for three players (Black, Gray, White), navigate to rules, start the game, or return to the main menu. It handles real-time name editing via keyboard input, visual feedback for active fields, and button interactions to trigger game functions or exit the menu... | def menu():
running = True
player1, player2, player3 = "", "", ""
player1_NameActive, player2_NameActive, player3_NameActive = False, False, False
while running:
back = False
screen.fill(ceramic)
screen.blit(king_b, (600-(king_w.get_width()//2), 65))
screen.blit(king_g, ... |
def create_button(x, y, width, height, hovercolor, defaultcolor, msg, player1='', player2='', player3=''):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed(3)
if x + width > mouse[0] > x and y + height > mouse[1] > y:
pygame.draw.rect(screen, hovercolor, (x, y, width, height), bo... | The code defines a menu function for a game, allowing players to input their names (Black, Gray, White) and navigate to the game or rules. It handles button interactions, name editing, and displays prompts, transitioning to the game when "Enter" is clicked. | def menu():
running = True
player1, player2, player3 = "", "", ""
player1_NameActive, player2_NameActive, player3_NameActive = False, False, False
while running:
back = False
screen.fill(ceramic)
screen.blit(king_b, (600-(king_w.get_width()//2), 65))
screen.blit(king_g, ... |
def _OptWhitespace(self) -> str:
"""Consumes whitespace if any.
Returns:
str: Consumed whitespace.
"""
value = ""
while self._lookahead.type in ["WS", "LINE_CONTINUATION"]:
token = self._consume(self._lookahead.type)
value += token.value
... | This function parses an optional end-of-line construct in the input, returning an AST node for either a newline or a comment, or None if neither is found. It first consumes optional whitespace, then checks for a newline token or a comment, constructing and returning the appropriate AST dictionary if either is present. | def OptEndOfLine(self) -> dict | None:
"""EndOfLine
: whiteSpace? NEW_LINE
| whiteSpace? Comment
Returns:
dict or None: Optional AST Production.
"""
self._OptWhitespace()
token = self._opt_consume("NEW_LINE")
if token:
retur... |
def OptEndOfLine(self) -> dict | None:
"""EndOfLine
: whiteSpace? NEW_LINE
| whiteSpace? Comment
Returns:
dict or None: Optional AST Production.
"""
self._OptWhitespace()
token = self._opt_consume("NEW_LINE")
if token:
retur... | This function parses an optional end-of-line or a colon with surrounding whitespace, returning an AST node for either if found, otherwise None. It handles statement termination elements in a parser, checking for EOL or COLON with optional whitespace, and constructs a dictionary representing the parsed token if present. | def OptIndividualNonEOFEndOfStatement(self) -> dict | None:
"""OptIndividualNonEOFEndOfStatement
: EndOfLine Whitespace?
| Whitespace? COLON Whitespace?
Returns:
dict or None: Optional AST Production
"""
eol = self.OptEndOfLine()
if eol:
... |
def separate_majoranas(hami, eigenvectors):
phi_min_num = optimize.minimize_scalar(
lambda phi, hami, eigenvectors: -majoranas_avoiding_same_site(
phi, hami, eigenvectors),
args=(hami, eigenvectors),
bounds=(0, np.pi / 2))
return phi_min_num.x
def overlap_majoranas(hami, eige... | This function plots wavefunctions and their relative phases for a given Hamiltonian, either using precomputed data or calculating eigenvalues/eigenvectors if data is absent. It generates a 2x2 grid of plots showing wavefunctions and relative phases under different phi values, which are numerically optimized to minimize... | def plot_wavefunctions(hami,
majorana_basis=False,
majorana_phi=0.0,
minimize_overlap=False,
maximize_overlap=False):
if not hami.check_if_data_exists():
print('Data does not exist, calculating...')
hami.buil... |
def separate_majoranas(hami, eigenvectors):
phi_min_num = optimize.minimize_scalar(
lambda phi, hami, eigenvectors: -majoranas_avoiding_same_site(
phi, hami, eigenvectors),
args=(hami, eigenvectors),
bounds=(0, np.pi / 2))
return phi_min_num.x
def overlap_majoranas(hami, eige... | This code performs a phase sweep analysis on a Hamiltonian by varying Zeeman field and chemical potential parameters across a 2D grid. It calculates energy differences between eigenstates, analyzes Majorana wavefunctions, and computes tunneling elements. Results are visualized in plots showing energy gaps and phase tra... | def phase_sweep(hami,
zeeman_max=4.0,
chem_min=-3.0,
chem_max=5.0,
phase_grid=10,
log_scale=False,
mark_transition=False):
zeeman_min = 1e-3
chem_pot_sweep = np.linspace(chem_min, chem_max, phase_grid)
zeeman_swe... |
def words_have_diff_lengths(word1: str, word2: str) -> bool:
"""check that both string arguments passed matches in length"""
return len(word1) != len(word2)
def is_viable_duplicate(guess: str, letter_i: int, answer: str) -> bool:
"""According to the colour, check to see if the duplicate letter is viable"""
... | The function checks if a guessed letter at a specific index is misplaced (yellow) in a word game. It verifies the letter exists in the answer, handles duplicates in the guess, and ensures the letter isn't in the correct position (green). | def char_is_yellow(guess: str, letter_i: int, answer: str) -> bool:
"""check that the guess letter at that index was misplaced"""
if words_have_diff_lengths(guess, answer):
raise ValueError(SAME_LEN_REQ_OUTPUT)
# check that the letter is actually in answer
if not guess[letter_i] in answer:
... |
def __update_solver(self, use_solver: bool = False) -> None:
if self.is_automated or use_solver:
self.solver.__update_solver_info(answer_words=self.answer_words,
allowed_words=self.allowed_words,
guess_n=self.g... | This method handles the next guess in a Wordle-like game by incrementing the guess count, updating the solver, and determining the next guess (automated or player input). It processes the guess, provides optional hints from a sample of possible answers, and checks if the game should end when maximum guesses are reached... | def play_next_guess(self) -> None:
"""play the next row's guess"""
if self.guess_n < Wordle.MAX_GUESS_N and self.current_guess != self.answer:
self.guess_n += 1
self.__update_solver()
self.current_guess: str = self.solver.get_optimal_guess(
) if self.is_au... |
def __setup_solver(self, use_solver: bool = False) -> None:
if self.is_automated or use_solver:
self.solver: WordleSolver = WordleSolver(answer_words=self.answer_words.copy(),
allowed_words=self.allowed_words.copy(),
... | The main task of the code is to initiate and manage a Wordle game session. It sets up a solver, starts the game loop to process guesses until completion, outputs the game outcome, saves solver data, and resets the game state. The method handles game initialization, execution, result display, and post-game cleanup in a ... | def play(self):
"""play a fresh game of Wordle"""
self.__setup_solver()
self.__game_in_session = True
while not self.game_over:
self.play_next_guess()
self.__game_output(self.__get_game_outcome_output())
self.__save_solver_info()
self.reset() |
def __setup_solver(self, use_solver: bool = False) -> None:
if self.is_automated or use_solver:
self.solver: WordleSolver = WordleSolver(answer_words=self.answer_words.copy(),
allowed_words=self.allowed_words.copy(),
... | The function plays a Wordle game, removes the answer from future possible answers, sets up the solver, runs the game loop, outputs the result, and saves solver data. | def play_and_drop_answer(self):
"""play a game of Wordle but remove the
answer from the pool of possible answers for
subsequent games"""
self.__setup_solver()
self.__game_in_session = True
while not self.game_over:
self.play_next_guess()
self._... |
def get_parent(
globals: Mapping[str, object] | None, level: int
) -> tuple[Optional[ModuleType], str]:
"""
parent, name = get_parent(globals, level)
Return the package that an import is being performed in. If globals comes
from the module foo.bar.bat (not itself a package), this returns the
s... | This function customizes module import behavior by decomposing the module name, handling parent modules, and processing 'fromlist' to import submodules. It mimics built-in __import__ with parameters for dynamic imports, validates non-empty module names, and returns the appropriate module (head or tail) based on 'fromli... | def custom_import(
name: str,
globals: Mapping[str, object] | None = None,
locals: Mapping[str, object] | None = None,
fromlist: Sequence[str] = (),
level: int = 0,
) -> ModuleType:
"""Import a module. The signature of this function is the same as builtins.__import__
for overriding purposes.... |
def conf2unicode(B: Board) -> str:
'''converts board cofiguration B to unicode format string (see section Unicode board configurations)
Parameters:
B (Board): board configuration
Returns:
str: a string of the board configuration in unicode format
'''
size = B[0]
matrix = [[... | The code simulates a chess game between white and black, alternating turns. It checks for checkmate or stalemate after each move, ending the game if detected. White inputs moves, while Black uses an automated function. Invalid moves prompt retries. The game can be quit, saving the board state to a file. | def run_play(B: Board) -> None:
'''Function to run the play between white and black pieces based on counter
stops play if checkmate or stalemate
Parameters:
B (Board): Initial board configuration
Returns:
None
'''
cont_play = True
counter = 2
print('The initial confi... |
def play_move(self, point, color):
"""
Play a move of color on point
Returns boolean: whether move was legal
"""
assert is_black_white(color)
# Special cases
if point == PASS:
self.ko_recapture = None
self.current_player = GoBoardUtil.oppon... | This function simulates a move for the current player, evaluates the resulting game state's score (negated to represent opponent's perspective), reverts the move, and returns the calculated score. It temporarily applies a move to assess its impact without altering the game state, commonly used in game AI for move evalu... | def _move_score(self, m):
self.play_move(m, self.current_player)
score = -self.evaluate()
self.undo_move(m)
return score |
def drawFrame():
glBegin(GL_LINES)
glColor3ub(255, 0, 0)
glVertex3fv(np.array([0.,0.,0.]))
glVertex3fv(np.array([3.,0.,0.]))
glColor3ub(0, 255, 0)
glVertex3fv(np.array([0.,0.,0.]))
glVertex3fv(np.array([0.,3.,0.]))
glColor3ub(0, 0, 255)
glVertex3fv(np.array([0.,0.,0]))
glVertex3f... | The code renders multiple 3D cubes with dynamic rotations and lighting in OpenGL. It sets up a camera, applies transformations (rotation, translation), configures lighting parameters, and animates cube rotations using spherical linear interpolation (slerp) based on the input angle 'ang'. Each cube is positioned with di... | def render(ang):
global gCamAng, gCamHeight
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glEnable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, 1, 1,10)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
gluLookAt(5*np.sin(gCamAng),gCamHeight,5*np.cos(... |
def addPizza(self, transactionDialog, menus):
self.pizzaCheckBoxes = []
self.jumlahPizzas = []
self.hargaPizzas = []
self.totalHargaPizzas = []
for menu in menus:
self.pizzaCheckBox = QtWidgets.QCheckBox(transactionDialog)
self.pizzaCheckBox.setObjectName... | The code categorizes menu items into pizzas, toppings, and drinks, then adds each category to a transaction dialog. It loads all menus, separates them by type into lists, and passes these lists along with the transaction dialog to respective methods for processing. | def getMenu(self,transactionDialog):
menus = Menu.loadMenu()
self.listPizza = []
self.listTopping = []
self.listDrink = []
for menu in menus:
if menu.category == 'Pizza':
self.listPizza.append(menu)
# self.addPizza(menu)
eli... |
def addItemStoreComboBox(self):
stores = self.getStore()
for store in stores:
self.storeComboBox_4.addItem(store.name,store.id)
def setTime(self):
self.time = datetime.now().strftime("%x")
return self.time
def getOrderNo(self):
with open('./csv/transactions.csv','r') ... | The main task of the code is to set up a transaction dialog UI using Qt, organizing elements like store selection, order details, pizza/topping/drink item layouts, and total calculations through grid and vertical layouts, while connecting buttons to handle order creation and cancellation. | def setupUi(self, transactionDialog):
self.transactionDialog = transactionDialog
transactionDialog.setObjectName("transactionDialog")
transactionDialog.resize(465, 478)
self.gridLayout = QtWidgets.QGridLayout(transactionDialog)
self.gridLayout.setObjectName("gridLayout")
... |
def load_and_validate_color_sets_file(filename):
try:
with open(filename, 'r') as f:
color_sets = json.loads(f.read())
try:
validate(color_sets, COLORS_SETS_SCHEMA)
except Exception as e:
print("Not valid color sets file. Error: ", e)
... | The code generates a customized panel configuration by loading color sets and config files, processing them to create overrides, transformations, and fields, then updating an initial panel JSON with these elements and saving the modified panel to a new file. | def panel():
color_sets = load_and_validate_color_sets_file("src/color_sets.json")
config_schema = generate_config_schema(list(color_sets.keys()))
config_data = load_and_validate_config_file("config.yaml", config_schema)
parsed_config = parse_config(config_data, color_sets)
overrides = generate_ov... |
def _validate_inputs(self):
if self.image.shape[:2] != self.mask.shape:
raise AttributeError('mask and image must be of the same size')
def _initialize_attributes(self):
""" Initialize the non initialized attributes
The confidence is initially the inverse of the mask, that is, the
... | The main task of the code is to perform image inpainting by iteratively identifying high-priority pixels, finding suitable source patches to replace them, and updating the image until completion. It validates inputs, manages processing steps, tracks progress, and returns the reconstructed image after filling all target... | def inpaint(self):
""" Compute the new image and return it """
self._validate_inputs()
self._initialize_attributes()
start_time = time.time()
keep_going = True
while keep_going:
self._find_front()
if self.plot_progress:
self._plot... |
def __rank_population(self):
scores = self.__parallel_score_processing()
sorted_pop = [individual for _, individual in sorted(zip(scores, self.pop), reverse=True)]
return sorted_pop, scores
def get_individual_score(individual, estimators, X, y, classes):
selected_estimators = [estimator for ... | The main task of the code is to analyze the current population's performance in an optimization algorithm, compare it to previous scores, update the best individual if improvement is detected, and print statistics including average score, diversity, and progress tracking. It evaluates population quality, tracks improve... | def __calculate_population_stats(self, initial_score, prev_score):
sorted_pop, scores = self.__rank_population()
best_individual = sorted_pop[0]
best_score = get_individual_score(best_individual, self.estimators, self.X, self.y, self.classes)
improvement = False
if best_score > s... |
def __parallel_score_processing(self):
starts = self.__compute_starts()
scores = Parallel(
n_jobs=self.n_jobs, verbose=0)(
delayed(_get_population_scores)(self.pop[starts[i]:starts[i + 1]],
self.estimators,
... | This function performs genetic algorithm optimization to improve a model's performance by evolving a population of solutions over generations. It initializes with a majority voting score, iteratively reproduces and mutates individuals, tracks statistical metrics, and retains the best-performing model (individual) from ... | def run_genetic_evolution(self):
# self.weights = get_weights(self.X, self.y, self.estimators, self.classes)
initial_score = majority_voting_score(self.X, self.y, self.estimators, self.classes)
print("\nInitial score = %f%%" % (initial_score * 100))
self.best_so_far = (initial_score, [])... |
def reach(self):
if round(self.pos_x,1) == self.dest_x and round(self.pos_y,1) == self.dest_y:
return True
else:
return False
def stop(self):
self.twist.linear.x = 0
self.twist.angular.z = 0
self.cmd_vel_pub.publish(self.twist)
def final_pose(self):
... | The code processes laser scan data to detect the closest obstacle, calculates the angular difference to the target direction, checks if the goal is reached, and triggers navigation actions like stopping or setting new goals. It handles obstacle avoidance by tracking proximity and adjusting movement based on detected di... | def _callback2(self, msg):
#If the CV algorithm detects a trash
if self.pause:
pass
else:
inf = math.inf
laser = msg.ranges
self.laser = laser
#Detect the distance and the orientation of the cloest obstacle
cloest_angle_left... |
def check_piece_legal(self):
piece_offsets = self.active_piece.get_locations()
for offset in piece_offsets:
filled_loc_row = self.active_piece_location[0] + offset[0]
filled_loc_col = self.active_piece_location[1] + offset[1]
if not 0 <= filled_loc_col < self.col_coun... | This code handles keyboard events for a Tetris-like game, rotating and moving the active piece based on arrow keys (K_UP, K_z for rotation; K_LEFT/K_RIGHT for lateral movement) and spacebar for hard drop. It checks if rotations are legal, reverting if invalid, and manages movement state flags for smooth lateral movemen... | def on_event(self, event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.active_piece.rotate_right()
if not self.check_piece_legal():
self.active_piece.rotate_left()
elif event.key == pygame.K_z:
sel... |
def text2matrix(text):
matrix = []
for i in range(16):
byte = (text >> (8 * (15 - i))) & 0xFF
if i % 4 == 0:
matrix.append([byte])
else:
matrix[i // 4].append(byte)
return matrix
def __add_round_key(self, s, k):
for i in range(4):
for j in ... | This code implements an encryption function that converts plaintext into a matrix, applies a series of AES-like rounds (substitution, row shifts, and key addition), and returns the encrypted result as text. It uses a key schedule with multiple rounds, each involving substitution, permutation, and key addition, to secur... | def encrypt(self, plaintext):
self.plain_state = text2matrix(plaintext)
self.__add_round_key(self.plain_state, self.round_keys[:4])
for i in range(1, 10):
self.__round_encrypt(self.plain_state, self.round_keys[4 * i : 4 * (i + 1)])
self.__sub_bytes(self.plain_state)
... |
def __add_round_key(self, s, k):
for i in range(4):
for j in range(4):
s[i][j] ^= k[i][j]
def __inv_mix_columns(self, s):
# see Sec 4.1.3 in The Design of Rijndael
for i in range(4):
u = xtime(xtime(s[i][0] ^ s[i][2]))
v = xtime(xtime(s[i][1] ^... | This function performs one round of AES decryption by applying inverse operations: adding the round key, inverse mix columns, inverse shift rows, and inverse substitution bytes to the state matrix. | def __round_decrypt(self, state_matrix, key_matrix):
self.__add_round_key(state_matrix, key_matrix)
self.__inv_mix_columns(state_matrix)
self.__inv_shift_rows(state_matrix)
self.__inv_sub_bytes(state_matrix) |
def text2matrix(text):
matrix = []
for i in range(16):
byte = (text >> (8 * (15 - i))) & 0xFF
if i % 4 == 0:
matrix.append([byte])
else:
matrix[i // 4].append(byte)
return matrix
def __add_round_key(self, s, k):
for i in range(4):
for j in ... | This code decrypts AES-encrypted ciphertext by converting it into a matrix, applying inverse AES operations (inv_sub_bytes, inv_shift_rows), and iteratively using round keys in reverse order. It performs 10 rounds of decryption, starting with the last round key, then the first four keys, finally returning the decrypted... | def decrypt(self, ciphertext):
self.cipher_state = text2matrix(ciphertext)
self.__add_round_key(self.cipher_state, self.round_keys[40:])
self.__inv_shift_rows(self.cipher_state)
self.__inv_sub_bytes(self.cipher_state)
for i in range(9, 0, -1):
self.__round_decrypt(s... |
def draw_window():
global screen
global circle_radius
global clock
# Set up the display
width, height = 1200, 900
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Worming Window")
# Set up the circle
circle_radius = 10
clock = pygame.time.Clock()
... | The code runs a simulation where a neural network predicts movement directions, measures processing times for input retrieval, prediction, and execution, and returns the distance traveled after a set number of predictions. | def run_simulation(self, network, show_simulation=False):
"""
runs the simulation for a set amount of frames
:param network: NeuralNetwork
:param show_simulation: Boolean - decides weather to show the simulation
:return: float - distance traveled
"""
if show_simul... |
def initialize_population(network_size, num_of_inputs):
"""
creates a new population with a population of NeuralNetworks with random weights and biases
:param num_of_inputs int
:param network_size: array [], with sizes of each layer
:return:
"""
population = []
if constants.USE_EXISTING... | The code trains multiple populations of neural networks, selects the top-performing networks from each, merges them, and trains the best-performing network among them. It returns the final optimized neural network after iterative evaluation and selection based on fitness scores. | def train(agent, network_size, num_of_inputs):
"""
Trains "constants.NUM_OF_POPULATIONS" populations and then merges them and trained the best of each together
:param agent: agent.py - the agent we use
:param network_size: [x, y] - size of neural network
:param num_of_inputs: int - number of inputs ... |
def table_of_nodal_DsOF(v, fixed):
dof_per_node = 1
dof_table = zero_m((v, dof_per_node), dtype=int)
for s in fixed:
dof_table[support_node_index(s)] = -1
ndof = 0
j = 0
for i in xrange(v):
if dof_table[i, j] != -1:
dof_table[i, j] = ndof
ndof += 1
ret... | The function `FDM` solves a linear system arising from a finite difference method (FDM) discretization. It computes nodal degrees of freedom, selects a solver (direct via `splu` or iterative with tolerance), and delegates to internal methods (`_FDM_d` or `_FDM_it`) to compute solutions for given vertices, edges, fixed ... | def FDM(vertices, edges, fixed, q, lin_solver=splu, i_tol=1e-5, callbacks=no_callbacks):
v = len(vertices)
ndof, tdof = table_of_nodal_DsOF(v, fixed)
if lin_solver == splu:
return _FDM_d(ndof, tdof, vertices, edges, q)
else:
return _FDM_it(ndof, tdof, vertices, edges, q, lin_solver, i_to... |
def table_of_nodal_DsOF(v, fixed):
dof_per_node = 1
dof_table = zero_m((v, dof_per_node), dtype=int)
for s in fixed:
dof_table[support_node_index(s)] = -1
ndof = 0
j = 0
for i in xrange(v):
if dof_table[i, j] != -1:
dof_table[i, j] = ndof
ndof += 1
ret... | This function iteratively computes nodal displacements (xyz) and element forces (f) using a finite difference method (FDM) over multiple steps. It adjusts displacements (q0) based on constraints (fcs, lcs, l0cs) that relate forces and lengths, updating geometry and forces at each step to converge toward a stable soluti... | def _multistepFDM_d(vertices, edges, fixed, q, fcs=[], lcs=[], l0cs=[], steps=250):
v = len(vertices)
q0 = copy(q)
ndof, tdof = table_of_nodal_DsOF(v, fixed)
xyz = _FDM_d(ndof, tdof, vertices, edges, q0)
l = list_of_element_lengths(edges, xyz)
f = list_of_element_forces(l, q0)
for i in xra... |
def table_of_nodal_DsOF(v, fixed):
dof_per_node = 1
dof_table = zero_m((v, dof_per_node), dtype=int)
for s in fixed:
dof_table[support_node_index(s)] = -1
ndof = 0
j = 0
for i in xrange(v):
if dof_table[i, j] != -1:
dof_table[i, j] = ndof
ndof += 1
ret... | This function performs iterative multistep finite difference method (FDM) computations to solve a linear system for structural or mechanical simulations. It updates nodal coordinates (xyz) and forces (f) over multiple steps by solving linear equations with constraints (fcs, lcs, l0cs), adjusting the stiffness matrix (m... | def _multistepFDM_it(vertices, edges, fixed, q, fcs=[], lcs=[], l0cs=[], steps=250,
lin_solver=cg, i_tol=1e-5, callbacks=no_callbacks, cond_num=False):
v = len(vertices)
q0 = copy(q)
ndof, tdof = table_of_nodal_DsOF(v, fixed)
mD, mDf = mDmDf(ndof, tdof, vertices, edges, q0)
if c... |
def table_of_nodal_DsOF(v, fixed):
dof_per_node = 1
dof_table = zero_m((v, dof_per_node), dtype=int)
for s in fixed:
dof_table[support_node_index(s)] = -1
ndof = 0
j = 0
for i in xrange(v):
if dof_table[i, j] != -1:
dof_table[i, j] = ndof
ndof += 1
ret... | The main task of the code is to perform a multistep finite difference analysis using a linear solver (default: conjugate gradient) to iteratively compute nodal displacements (xyz), element forces (f), and updated force parameters (q0) for a structural system. It applies constraints, updates system matrices (mD, mDf), s... | def multistepFDM_cg (vertices, edges, fixed, q, fcs=[], lcs=[], l0cs=[], steps=250,
lin_solver=cg, i_tol=1e-5, callbacks=no_callbacks, cond_num=False):
v = len(vertices)
q0 = copy(q)
ndof, tdof = table_of_nodal_DsOF(v, fixed)
mD, mDf = mDmDf(ndof, tdof, vertices, edges, q0)
if c... |
def _return_static(path: str, start_response: Callable) -> List[bytes]:
"""Returns static file"""
with open(get_path_to_file(path), "rb") as file:
content = file.read()
if path.endswith(".css"):
content_type = "text/css"
elif path.endswith(".js"):
con... | This method processes HTTP requests by routing based on the URL path, handling static files, parsing request data, applying middleware, and returning responses. It checks the path for static content, normalizes it, retrieves the corresponding view function or 404 handler, prepares request data (GET/POST), executes midd... | def __call__(
self, environ: Dict[Any, Any], start_response: Callable
) -> List[bytes]:
path = environ["PATH_INFO"]
if path.startswith("/static/"):
return self._return_static(path, start_response=start_response)
if not path.endswith("/"):
path = f"{path}/"
... |
def convert_ticker_to_symbol(ticker, exchange_id):
"""Converts a ticker to a symbol for url insertion.
:arg: ticker: str
:arg: exchange_id: str
:returns: str
"""
url_symbol = ''
if exchange_id in [BINANCE_US_ID, KRAKEN_ID]:
url_symbol = '{}USD'.format(ticker.upper())
elif exchan... | Your returnThe function retrieves an asset's order book data from a specified exchange. It converts the ticker to the exchange-specific symbol, then calls the corresponding exchange's order book function (e.g., Binance US, Coinbase, Gemini, OKCoin) based on the `exchange_id`. For Kraken, it returns a placeholder with `... | def get_asset_order_book_at_exchange(ticker, exchange_id, size=5):
"""Finds the order book of an asset at an exchange.
:arg: ticker: str
:arg: exchange_id: str
:arg: size: int
:returns: dict with min_ask/max_bid/dollar_value_min_asks/dollar_value_of_max_bids
"""
symbol = convert_ticker_to_s... |
def _is_ofc_controlled_network(self, context, network_id):
# NOTE(yokose): Whether send request to OFC or not depends on
# the name of network.
net = self._get_network(context, network_id)
return net['name'] not in CONF.OFC.ofc_uncontrolled_network_names
def _uuid_to_region... | This code creates a network port and, if the port is for a compute instance, updates the OpenFlow controller (OFC) with the port's details. It checks if the network is OFC-controlled, retrieves necessary parameters like region, tenant ID, and MAC address, and calls `ofc.update_for_run_instance`. If this fails, it delet... | def create_port(self, context, port):
LOG.debug("#DodaiPlugin.create_port() called.")
LOG.debug("#port=%s" % port)
device_owner = port['port']['device_owner']
# create ports
db_port = super(DodaiL2EPlugin, self).create_port(context, port)
# NOTE(yokose): If this method i... |
def _is_ofc_controlled_network(self, context, network_id):
# NOTE(yokose): Whether send request to OFC or not depends on
# the name of network.
net = self._get_network(context, network_id)
return net['name'] not in CONF.OFC.ofc_uncontrolled_network_names
def _uuid_to_region... | (This function deletes a network port by first checking if it belongs to a compute instance. If so, it updates the OpenFlow Controller to terminate the instance's network connection, then clears associated floating IP references in the database. Finally, it delegates actual port deletion to the parent class, ensuring n... | def delete_port(self, context, id):
LOG.debug("#DodaiPlugin.delete_port() called.")
LOG.debug("#id=%s" % id)
db_port = self._get_port(context, id)
device_owner = db_port['device_owner']
session = context.session
# NOTE(yokose): If this method is called from run_instance,
... |
def _create_metadata_object(self, context, floatingip_id, fixed_port_id):
fixed_port = self._get_port(context, fixed_port_id)
LOG.debug("#fixed_port=%s" % fixed_port)
tenant_id = fixed_port['tenant_id']
device_id = fixed_port['device_id']
LOG.debug("#tenant_id=%s" % tenant_id)
... | This code updates a floating IP address by either associating it with an instance (if a port ID exists) or disassociating it (if no port ID is provided). It handles metadata updates, retrieves fixed IP addresses, and modifies the database record for the floating IP, logging actions and ensuring proper tenant/device ID ... | def update_floatingip(self, context, id, floatingip):
LOG.debug("#DodaiPlugin.update_floatingip() called.")
LOG.debug("#id=%s" % id)
LOG.debug("#floatingip=%s" % floatingip)
fixed_port_id = floatingip['floatingip']['port_id']
session = context.session
# NOTE(yokose): Asso... |
def preprocess_joint_data(
self, train_validate_date: str, end_date: str, verbose: bool
) -> None:
"""
import data if unimported, split to before and after a given datem and fit scalers based on the data before the given date
:param train_validate_date: str, date to split the data i... | The main task of the code is to execute an end-to-end machine learning workflow: preprocess data (or load cached data), create training windows, compile and fit a model, compute error metrics, and save results. It supports caching to skip preprocessing, verbose logging for progress tracking, and cross-validation handli... | def do_it_all(
self,
train_validate_date="2020-09-27",
end_date=None,
cv=False,
verbose=True,
cached=False,
):
"Note that CV should start at 1 so that the first iteration, evaluates as 1 or True"
if not cached:
if verbose:
p... |
def clark_sso_succeeded(state):
if "sso.clark" in state.state['accumulated_user_information']:
if "serviceResponse" in state.state['accumulated_user_information']['sso.clark']:
if "authenticationSuccess" in state.state['accumulated_user_information']['sso.clark']['serviceResponse']:
... | The function initiates Clark SSO by checking if authentication has already succeeded. If not, it generates a CAS login URL with a signed context and redirects the user, enabling single sign-on authentication without re-authenticating if previously successful. | def clark_sso_initiate(request, context, path_remaining, state):
# don't bother reauthenticating if we've already succeeded
if clark_sso_succeeded(state):
return True
ctx = str(state.uuid)
redir_url = generate_cas_login_url(THIS_HOST, ctx, None, sign(ctx))
return redirect(redir_url... |
def service_url(host, ctx, ticket, sig):
injectedHTML = percent_encode(
injected_html_for_js(
get_redirect_javascript(host, ctx, ticket, sig)
)
)
query_string = f"ctx={percent_encode(ctx)}&sig={percent_encode(sig)}"
return f"https://cppm.clarku.edu/guest/clarkpass_o... | The function validates a ticket via a CAS server, constructs a validation URL with encoded parameters, fetches the result, stores it in the state, and initiates SSO if validation fails. It returns True upon successful validation and state persistence. | def validate_and_store_ticket(request, context, path_remaining, state):
ticket = request.GET.get("ticket", None)
sig = request.GET.get("sig", '')
cas_validation_url = urljoin(CAS_BASE_URL, "p3/serviceValidate")
cas_validation_url += "?service=" + percent_encode(service_url(THIS_HOST, str(state.uuid), t... |
def remove_duplicates_in_one_df_by_title(self, df, column_names_to_merge=[]):
year_dict = self.get_articles_dict_by_title(df)
tfidf_matrix = self.get_tf_idf_matrix(list(df[self.title_column].values))
tfidf_matrix_abstract = self.get_tf_idf_matrix(list(df[self.abstract_column].values))
du... | The function deduplicates two datasets individually by removing duplicates within each using specified columns. It then identifies and merges duplicate articles between the datasets, removes cross-dataset duplicates, and concatenates the cleaned datasets. The process ensures data consistency by eliminating redundant en... | def deduplicate_and_process_dataset_with_merge(
self, first_dataset, second_dataset, column_names_to_merge = []):
start_time = time()
first_dataset = self.remove_duplicates_in_one_df_by_title(
first_dataset, column_names_to_merge)
print("Time spent for one df: %.2f s" % (... |
def add_new_patient(self, num_patients):
# Function to add new patients to the system
new_patients = generate_patients(num_patients) # Generating a list of new patient objects
for patient in new_patients:
self.patients[patient.patient_id] = patient
def update_patient_record(self):
... | The code simulates a hospital management system, allowing users to add patients, list/update/remove records, schedule appointments, process consultations, search patients, and exit. It uses a menu-driven interface to handle user choices, interacting with methods to manage patient data and consultation queues, ensuring ... | def test(self):
print("\n--- Welcome to the hospital system ---")
num_patients = int(input("Please enter the number of patients to add: "))
self.add_new_patient(num_patients)
print(f"{num_patients} New patients are added")
# Main loop to display the menu and handle user choices
... |
def __find_work_usb(self):
block_devices = pyudev.Context().list_devices(subsystem=self.__TARGET_SUBSYSTEM,
DEVTYPE=self.__TARGET_DEVICE_TYPE,
tag=self.__TARGET_TAG)
suitable_usbs = [
... | The code monitors USB devices for addition events, creates USB device objects upon detection, and processes them by clearing and sending data, while handling exceptions during these operations. | def run(self):
self.__find_work_usb()
monitor = self.__init_monitor()
for device in iter(monitor.poll, None):
if (device.action == self.__ADD_ACTION
and (usb_device := self.__create_usb(device.device_path))):
try:
self.__clear_u... |
def get_and_delete_all_emails_from(folder, server, port=993, delete=False, user=None, pwd=None):
if ' ' in folder:
folder = f'"{folder}"'
with imaplib.IMAP4_SSL(server, port) as mail:
user = input("Username: ") if user is None else user
pwd = getpass("Password: ") if pwd is None else pw... | The main task of the code is to retrieve and delete all emails from a specified server, extract unique papers from the emails, and save them as a CSV file. The function processes email data by filtering out duplicates, then writes the results to a specified output file. | def main(args):
emails = get_and_delete_all_emails_from(
args.folder, args.server, args.port, args.delete, args.username, args.password
)
unique_papers = filter_unique_papers_from_emails(emails)
write_papers_to_csv(unique_papers, fname=args.output) |
def is_market_open():
now = datetime.datetime.now(tz)
open_time = datetime.time(hour=9, minute=30, second=0)
close_time = datetime.time(hour=16, minute=0, second=0)
# If a holiday
if now.strftime('%Y-%m-%d') in us_holidays:
return False
# If it's before 0930 or after 1600
elif (now.t... | The main task of the code is to manage daily stock trading activities by checking if the market is open, fetching stock data, analyzing returns, identifying missing stocks, calculating optimal investment weights, generating trade decisions, and executing buy/sell orders. It updates current positions and tracks executio... | def daily_steps(): # we will cycle through this one every day
global market_open
start_time = time.time()
market_open = is_market_open() # changes value to True if the stock market is open that day
if market_open:
print('\n' * 100)
establish_current_positions()
temp_stock_dat... |
def _print_header():
print('-' * 80)
def _compute_custom_threshold_stats(self) -> None:
if not self.custom_thresholds:
return
print('\nComputing custom threshold stats...')
for label, data in enumerate(self.labels, self.all_data):
print(f'\n--> Using predictions ... | The code's main task is to execute an analysis workflow by printing a header, computing custom threshold statistics, generating ROC curves, calculating true positive rates (TPRs), and printing a footer. This method orchestrates model evaluation metrics, likely for classification tasks, by aggregating statistical data a... | def run(self):
"""run analyzer"""
self._print_header()
self._compute_custom_threshold_stats()
self._compute_roc_curves()
self._compute_tprs()
self._print_tail() |
def case_insensitive(string):
"""
:param string: str, a character.
:return: lst, a lower character lst.
"""
new_string = ''
for ch in string:
if ch.islower():
new_string += ch
else:
new_string += ch.lower()
return new_string
def read_dictionary(target)... | The main task of the code is to generate and display anagrams for user-input words using a dictionary, with performance timing. It repeatedly prompts users for input, processes the request using `find_anagrams` and `read_dictionary`, outputs results, and exits when the user specifies an exit command. The code also meas... | def main():
print(f'Welcome to stanCode "Anagram Generator" (or {EXIT} to quit)')
count = 0
while True:
searching = case_insensitive(input('Find anagrams for: '))
# Timer
t1 = time.time()
# read_dictionary
read_dictionary(searching)
# If -1, quit
if... |
def get_swap_sentences(sentences, alpha=0.1):
return [get_swap_sentence(sentence, alpha) for sentence in sentences]
def get_backtrans_sentences(sentences, cfg):
pkl_path = Path(cfg.train_path).parent.joinpath(f"train_aug_backtrans_data.pkl")
sentence_to_aug_sentence = get_backtrans_data_dict(pkl_path, cfg... | The function `get_augmented_sentences` applies text augmentation to input sentences based on the specified `augmentation_type`, returning transformed sentences using methods like token swapping, backtranslation, or synonym replacement. For "all_augmentation", it returns a tuple of results from all three methods. | def get_augmented_sentences(sentences, cfg, augmentation_type):
if augmentation_type == "token_swaps":
return get_swap_sentences(sentences)
elif augmentation_type == "backtranslation":
return get_backtrans_sentences(sentences, cfg)
elif augmentation_type == "synonym_replacement":
re... |
def check_device( self , X ):
a = X.is_cuda
b = self.cuda
if a and ( not b ):
X = X.to( 'cpu')
if b and ( not a ):
X = X.to( 'cuda')
return X
def sample_noise( self , size = 1 ):
if size < 1:
raise ValueError
data = self.spi... | This code trains a neural network model using batched data and Adam optimizer, iteratively updating parameters via the iter_step method, while tracking training costs at specified intervals. It handles device placement, batch generation, noise sampling, and maintains a record of costs for monitoring progress during tra... | def fit( self , X , y , iters = 100 , batch_size = 20 , lr = 1e-3 , verbose = True , ticks = 10 ):
X = self.check_device( X )
y = self.check_device( y )
h = X.shape[ 0 ]
idx = idx_generator( h , batch_size )
self.mod.train()
opm = torch.optim.Adam( self.mod.pa... |
def resource_exists(resource):
return run(f"kubectl get {resource}", output=DEVNULL, check=False, quiet=True).exit_code == 0
def get_resource_json(resource, jsonpath=""):
return call(f"kubectl get {resource} -o jsonpath='{{{jsonpath}}}'", quiet=True)
def await_ingress(service, timeout=300):
assert service.s... | The function pauses a demo process, extracts URLs and credentials from a model's sites (primarily Kubernetes/Podman platforms), and prints them for user access. It identifies frontend/console endpoints, decodes admin passwords from secrets, and waits for user confirmation before proceeding. | def pause_for_demo(model):
notice("Pausing for demo time")
first_site = [x for _, x in model.sites][0]
console_url = None
password = None
frontend_url = None
if first_site.platform == "kubernetes":
with first_site:
if resource_exists("service/frontend"):
if ... |
def await_resource(resource, timeout=300):
assert "/" in resource, resource
start_time = get_time()
while True:
notice(f"Waiting for {resource} to become available")
if resource_exists(resource):
break
if get_time() - start_time > timeout:
fail(f"Timed out... | The function `await_console_ok` waits for a Kubernetes secret containing admin credentials, decodes the password, and verifies accessibility of the Skupper console service at `https://service/skupper:8010` using basic authentication with the extracted credentials. | def await_console_ok():
await_resource("secret/skupper-console-users")
password = get_resource_json("secret/skupper-console-users", ".data.admin")
password = base64_decode(password)
await_http_ok("service/skupper", "https://{}:8010/", user="admin", password=password) |
def await_resource(resource, timeout=300):
assert "/" in resource, resource
start_time = get_time()
while True:
notice(f"Waiting for {resource} to become available")
if resource_exists(resource):
break
if get_time() - start_time > timeout:
fail(f"Timed out... | The function `run_step` executes commands in a given step, handling Kubernetes context setup, resource waiting, and command validation. It processes each site's commands, skips 'readme' actions, awaits specified resources/ingresses/ports, runs shell commands, checks for expected failures, and raises errors on unexpecte... | def run_step(model, step, work_dir, check=True):
if not step.commands:
return
notice(f"Running {step}")
for site_name, commands in step.commands:
with dict(model.sites)[site_name] as site:
if site.platform == "kubernetes":
run(f"kubectl config set-context --curr... |
def check_environment():
check_program("base64")
check_program("curl")
check_program("kubectl")
check_program("skupper")
def run_step(model, step, work_dir, check=True):
if not step.commands:
return
notice(f"Running {step}")
for site_name, commands in step.commands:
with di... | The function `run_steps` executes a sequence of predefined steps from a model, handling setup, execution, debugging, and cleanup. It initializes a model, processes each step (skipping "cleaning_up" during main execution), runs them in a specified directory, and ensures cleanup is performed regardless of errors. Debuggi... | def run_steps(skewer_file, kubeconfigs=[], work_dir=None, debug=False):
notice(f"Running steps (skewer_file='{skewer_file}')")
check_environment()
model = Model(skewer_file, kubeconfigs)
model.check()
if work_dir is None:
work_dir = join(get_user_temp_dir(), "skewer")
remove(work_... |
def establish_nodes(self):
self.node_dictionary={}
index = 0
x=0
y=0
for j in numpy.arange(self.y_limit[0],self.y_limit[1]+self.step_size,self.step_size):
for i in numpy.arange(self.x_limit[0],self.x_limit[1]+self.step_size,self.step_size):
... | The code implements the Rapidly-exploring Random Tree (RRT) algorithm to find a collision-free path from a start point to a goal. It iteratively samples random nodes, connects them to the nearest existing node, checks for obstacles, and builds a tree. Upon reaching the goal, it traces back from the goal to the start th... | def execute(self):
#Sets the each coords to the Node class
self.node_dictionary = self.establish_nodes()
#Gets starting node
new_node=self.get_node(self.start_x,self.start_y)
self.node_dictionary[new_node.i].pc = 0
self.node_dictionary[new_node.i].i = 0
#Gets goal... |
def establish_nodes(self):
self.node_dictionary={}
index = 0
x=0
y=0
for j in numpy.arange(self.y_limit[0],self.y_limit[1]+self.step_size,self.step_size):
for i in numpy.arange(self.x_limit[0],self.x_limit[1]+self.step_size,self.step_size):
self.node_d... | The code implements the A* algorithm for pathfinding. It initializes nodes, sets start/goal nodes, and iteratively selects the next node with the least cost until the goal is reached. After reaching the goal, it backtracks from the goal to the start to reconstruct the path, plotting the nodes and the found path on a gr... | def execute(self):
#Sets the each coords to the Node class
self.node_dictionary = self.establish_nodes()
#Gets starting node
start_node=self.get_node(self.start_x,self.start_y)
start_node.pc = 0
current_node=start_node
self.original_cost[current_node.i] = 0
... |
def establish_nodes(self):
self.node_dictionary={}
index = 0
x=0
y=0
for j in numpy.arange(self.y_limit[0],self.y_limit[1]+self.step_size,self.step_size):
for i in numpy.arange(self.x_limit[0],self.x_limit[1]+self.step_size,self.step_size):
self.node_d... | This code implements a ROS-based navigation system using Dijkstra's algorithm for pathfinding between Turtlebot1 (pursuer) and Turtlebot2 (evader). It subscribes to odometry data, calculates optimal paths, handles evasion logic, and publishes velocity commands to navigate waypoints. The system visualizes path planning,... | def main(self):
rate = rospy.Rate(50) #hz
#scan_sub=rospy.Subscriber('/turtlebot2/scan',LaserScan,self.scan_callback)
odom_evader_sub = rospy.Subscriber("/turtlebot1/odom",Odometry,self.odom_evader_callback)
odom_pursuer_sub=rospy.Subscriber('/turtlebot2/odom',Odometry,self.odom_pursuer_... |
def reset(self):
"""
Empty all cells
"""
self.delete("all")
self._draw_grid()
def _draw_grid(self):
"""
Draw sudoku lines
"""
end_x, end_y = self.first_x + 9 * self.cell_size, self.first_y + 9 * self.cell_size
# Draw horizontal lines
... | This method updates the canvas's grid and visual elements when resized or initially placed. It checks for minimum size, adjusts cell dimensions, recalculates positions, updates font size, and redraws the grid, resetting the canvas state for proper scaling and layout. | def update(self, event):
"""
Update draw and variables when Canvas is resized or placed for the first time
"""
# We don't want a too small grid
if event.width < 100 or event.height < 100:
return
# Make tkinter.Canvas update
Canvas.update(self)
... |
def __create_menu_bar(self):
menu_bar = Menu(self, tearoff=0)
menu_file = Menu(menu_bar, tearoff=0)
menu_file.add_command(label="Load", command=self.load)
menu_file.add_separator()
menu_file.add_command(label="Quit", command=self.quit)
menu_bar.add_cascade(label="File", ... | This code initializes a Sudoku game's main window using Tkinter, setting up a grid for the puzzle, navigation buttons (left/right arrows) to switch between puzzles, a number pad, erase functionality, and a menu bar. It loads Sudoku puzzles from a specified file, tracks the current puzzle line, and binds events for user... | def __init__(self, book, *args, **kwargs):
"""
Main Window of the Sudoku game
:param args: args to pass to tkinter.Tk
:param kwargs: kwargs to pass to tkinter.Tk
"""
Tk.__init__(self, *args, **kwargs)
self.numpad = None
self.book = book
file = ope... |
def getDBUsed(myConfig):
checkConfigDBUsed(myConfig=myConfig)
dbDefineInConfig = myConfig.get('DBUSED')
return dbDefineInConfig.split(',')
def createEngines(myConfig, dbPossible):
engines = {}
for item in dbPossible:
engines[item] = engine_from_config(
configuration=myConfig,
... | The main task of the code is to configure a Pyramid application's database session management. It retrieves application settings, initializes database engines, creates a session factory, registers it in the registry, and subscribes to new requests to attach a database session. This ensures each request has a properly c... | def includeme(config):
myConfig = config.get_settings()
dbPossible = getDBUsed(myConfig=myConfig)
engines = createEngines(myConfig=myConfig, dbPossible=dbPossible)
session_factory = get_session_factory(engines)
config.registry['dbsession_factory'] = session_factory
# for each new request we g... |
def M_star(self):
R_s = self.data_.index.to_series().apply(lambda x: self.R_s(x))
return self.data_[R_s >= np.median(R_s)]
def R_s(self, song):
return self.theta_s(song) @ self.phi_s_
def R_t(self, song_from, song_to):
return self.theta_t(song_from, song_to) @ self.phi_t_ | The code implements an algorithm to find the trajectory with the highest expected payoff over a given horizon. It samples trajectories from a precomputed model (`M_star`), calculates their expected payoff using reward functions `R_s` and `R_t`, and iteratively updates the best trajectory if a higher payoff is found. Af... | def algorithm_4(self, horizon, T=1000):
best_trajectory = []
highest_expected_payoff = -float("inf")
start_time = time.time()
M_star = self.M_star()
print("--- %s seconds ---" % (time.time() - start_time))
for _ in range(T):
trajectory = M_star.index.to_series... |
def algorithm_4_with_human(self, horizon, T=300):
best_trajectory = []
highest_expected_payoff = -float("inf")
for _ in range(T):
trajectory = self.data_.index.to_series().sample(horizon)
expected_payoff = self.R_s(trajectory[0]) + sum(self.R_t(x[0], x[1]) + self.R_s(x[1]... | The code implements a reinforcement learning algorithm that iteratively recommends songs using human feedback. It calculates song and transition rewards, updates model parameters (phi_s_, phi_t_) based on user preferences and reward increments, and normalizes feature weights. The algorithm adjusts recommendations by in... | def algorithm_3_with_human(self):
rewards = []
songs = []
for k in range(self.K_):
start_time = time.time()
curr_song = self.algorithm_4_with_human(self.K_ - k)
while True:
enjoyed_song = input(f"Do you like the song {self.song_info_.loc[curr_... |
def algorithm_4(self, horizon, T=1000):
best_trajectory = []
highest_expected_payoff = -float("inf")
start_time = time.time()
M_star = self.M_star()
print("--- %s seconds ---" % (time.time() - start_time))
for _ in range(T):
trajectory = M_star.index.to_series... | The main task of the code is to iteratively select songs using Algorithm 4, compute combined rewards (song + transition), update model parameters (phi_s_, phi_t_) via weighted averaging based on reward increments, and normalize feature vectors. The process dynamically adjusts parameters over K_ iterations, tracking per... | def algorithm_3(self):
print("Alg 3")
rewards = []
songs = []
for k in range(self.K_):
start_time = time.time()
curr_song = self.algorithm_4(self.K_ - k)
song_reward = self.R_s(curr_song)
trans_reward = self.R_t(songs[-1], curr_song) if k e... |
def algorithm_1(self):
for song in self.song_pref_:
self.phi_s_ += self.theta_s(song) * (1 / (self.ks_ + 1))
def algorithm_2(self):
song_prev = self.song_pref_[0]
for song_curr in self.song_pref_[1:]:
self.phi_t_ += self.theta_t(song_prev, song_curr) * (1 / (self.kt_ + 1)... | This code executes three algorithms sequentially: first algorithm_1, then algorithm_2, and finally algorithm_3_with_human, which likely involves human interaction or decision-making. The main task is to orchestrate these steps in a specific order, possibly integrating human input during the third phase to achieve a com... | def algorithm_5_with_human(self):
self.algorithm_1()
self.algorithm_2()
self.algorithm_3_with_human() |
def algorithm_1(self):
for song in self.song_pref_:
self.phi_s_ += self.theta_s(song) * (1 / (self.ks_ + 1))
def algorithm_2(self):
song_prev = self.song_pref_[0]
for song_curr in self.song_pref_[1:]:
self.phi_t_ += self.theta_t(song_prev, song_curr) * (1 / (self.kt_ + 1)... | The main task of the code is to execute algorithm_1, algorithm_2, and algorithm_3 sequentially by calling them within the algorithm_5 method. | def algorithm_5(self):
self.algorithm_1()
self.algorithm_2()
self.algorithm_3() |
def getTimeNow():
return timer
def createGraph(name, mssg):
filename = "links/" + name + ".json"
savedrecords = []
with open(filename, "r") as file:
savedrecords = json.load(file)
graph = []
for record in savedrecords:
graph.extend(record["links"])
graph.extend(mssg["links"])... | The main task of the code is to update a graph structure with a message, compute shortest paths using Dijkstra's algorithm, optimize the graph by removing redundant edges, and save the optimized links. It returns whether changes were made and the optimized graph. | def handleUpdate(name, mssg):
mssg = {
"id": mssg["id"],
"savetime": getTimeNow(),
"ttl": mssg["ttl"],
"links": mssg["links"]
}
graph = createGraph(name, mssg)
# print("\n\n", name, graph, "\n\n")
shortest_paths = dijkstra(graph, name)
graph.extend(shortest_paths... |
def getLinksFromGraph(name):
data = {}
with open("routerMapping.json", "r") as file:
data = json.load(file)
links = [[min(row[0], row[1]), max(row[0], row[1]), row[2]] for row in data["graph"] if name in row]
return links
def saveLinks(name, router_records):
update = {
"id": name,
... | This code handles a router's initialization and update processing in a distributed network. It retrieves and saves initial links, waits for system readiness, broadcasts initial data, and continuously listens for updates. Upon receiving messages, it processes topology changes, optimizes the network graph, and propagates... | def handlerouter(name, address, router_socket):
# print(f"router Active {name}: {address}")
# get initial links of this router
router_records = getLinksFromGraph(name)
saveLinks(name, router_records)
# print(router_records)
# wait till all routers/threads are active
time.sleep(10)
... |
def switch_to_position_control(self):
self._switch_controllers(self.FZI_MOTION_CONTROLLER_NAME)
def _create_stamped_pose_message_from_pose(self, pose: HomogeneousMatrixType) -> Message:
"""helper function to publish target poses to the FZI controllers over the webbridge."""
quaternion = SE3Conta... | The main task of the code is to move a robot to a specified TCP (Tool Center Point) pose synchronously. It switches to position control if necessary, publishes the target pose via a topic to the FZI motion controller, and waits until the robot reaches the target pose (within 0.005 meters of the target position) or time... | def move_to_pose(self, tcp_pose: HomogeneousMatrixType) -> None:
"""Moves the robot to the given TCP pose. The method is synchronous and will block until the robot has reached the target pose.
under the hood, the method activates the FZI motion controller and publishes the target pose to the correspondi... |
def _is_cabinet_open(self) -> bool:
# TODO: how to measure? buildup in force could indicate this but that is maybe not a perfect heuristic?
# set a q_max? but this highly depends on the twist ofc. should the twist be normalized then?
return False
def _is_grasped_heuristic(self) -> bool:
... | This function opens a grasped cabinet by iteratively adjusting the robot's joint configuration. It estimates the required twist for motion, updates gripper poses in steps, monitors force and contact status, and visualizes progress. The loop continues until the cabinet opens or conditions trigger an abort, using twist e... | def open_grasped_cabinet(self):
self.gripper_poses = []
self.joint_configuration_step_delta = self.default_delta_step
self.initial_gripper_pose = self.robot.get_tcp_pose()
self.gripper_poses.append(self.initial_gripper_pose)
# TODO: this is a hack, should be determined from the ... |
def make_a_path(): #makes the avaible options at that start of a conflict to say weather it is what reward
randchoice = random.randint(1,100)
reward = ""
if randchoice <= 30:
reward = "nothing" #WHITE
elif randchoice <= 60:
reward = "gold" #YELLOW
elif randchoice <= 80:
rewa... | The code presents three reward paths to the player, validates their choice, randomly determines if a combat encounter occurs, and grants the selected reward if the player survives. It handles input validation, displays options with color formatting, and ensures rewards are only given upon successful conflict resolution... | def conflict(player, level, enemies, scrolls):
rewardchoice1 = make_a_path()
rewardchoice2 = make_a_path()
rewardchoice3 = make_a_path()
check = 0
while check == 0:
print(colorama.Fore.BLUE+"Choose a reward for this next conflict (by number)")
print(colorama.Fore.WHITE)
displ... |
def make_a_path(): #makes the avaible options at that start of a conflict to say weather it is what reward
randchoice = random.randint(1,100)
reward = ""
if randchoice <= 30:
reward = "nothing" #WHITE
elif randchoice <= 60:
reward = "gold" #YELLOW
elif randchoice <= 80:
rewa... | The function `boss_conflict` manages a game scenario where a player selects a path (1-3) to engage in combat with a boss. It validates input, initiates combat, and grants rewards based on the chosen path if the player survives. If the player dies, it displays a death message. The function uses helper functions for path... | def boss_conflict(player, boss, scrolls):#the start of a conflict made it a fuction becasue it means it can be used multiple times
rewardchoice1 = make_a_path()
rewardchoice2 = make_a_path()
rewardchoice3 = make_a_path()
check = 0
while check == 0:#makes sure that the player chooses a correct path b... |
def _to_list(x):
# type: (Optional[Any]) -> List[Any]
"""Convert object to a list if it is not a list,
None converted to empty list
"""
if x is None:
x = []
elif not isinstance(x, list):
x = [x]
return x
def slot_mappings(self):
... | The function retrieves and validates slot mappings for a given slot. If no direct mapping exists, it maps the slot to an entity with the same name. It ensures each mapping is a dictionary containing a "type" key, raising a TypeError if invalid. Finally, it returns the validated list of mappings. | def get_mappings_for_slot(self, slot_to_fill):
# type: (Text) -> List[Dict[Text: Any]]
"""Get mappings for requested slot,
else map requested slot to an entity with the same name
"""
requested_slot_mappings = self._to_list(
self.slot_mappings().get(slot_to_fil... |
def required_slots(tracker):
# type: (Tracker) -> List[Text]
"""A list of required slots that the form has to fill
Use `tracker` to request different list of slots
depending on the state of the dialogue
"""
raise NotImplementedError("A form must implement requir... | The function extracts values for slots not currently being requested by checking if they are set by corresponding entities in the user input. It iterates through required slots, verifies mappings, and collects values if entities match the slot names and intents. The result is a dictionary of extracted slot values or No... | def extract_other_slots(self,
dispatcher, # type: CollectingDispatcher
tracker, # type: Tracker
domain # type: Dict[Text, Any]
):
# type: (...) -> Dict[Text: Any]
"""Extract the values of t... |
def extract_other_slots(self,
dispatcher, # type: CollectingDispatcher
tracker, # type: Tracker
domain # type: Dict[Text, Any]
):
# type: (...) -> Dict[Text: Any]
"""Extract the values of t... | This code validates extracted slot values during form execution. It extracts other slots, checks for a requested slot, applies custom validation methods (e.g., validate_<slot, and rejects the action if validation fails. If successful, it returns validated slot values as SlotSet objects to update the tracker. | def validate(self, dispatcher, tracker, domain):
# type: (CollectingDispatcher, Tracker, Dict[Text, Any]) -> List[Dict]
"""Validate extracted value of requested slot
else reject execution of the form action
Subclass this method to add custom validation and rejection logic
... |
def map_single(self, dataset_dict, crop_or_pad):
image = utils.read_image(dataset_dict["file_name"], format="BGR")
dataset_dict["image"] = image
annotations = dataset_dict["annotations"]
# convert all bbox8 to np.array[4, 2]
for annotation in annotations:
annotation[... | This code processes a dataset dictionary by padding the input image, optionally pasting randomly selected cropped images, converting the image to a PyTorch tensor, and mapping annotations to rotated instance objects. It handles image augmentation, random cropping, and instance filtering for object detection tasks. | def __call__(self, dataset_dict):
self.map_single(dataset_dict, crop_or_pad='pad')
# self.augment(dataset_dict)
main_dict = dataset_dict
if main_dict.get("self_crop_bbox8", None) is not None:
main_dict["pasted_crop_bboxes8"] = [main_dict["self_crop_bbox8"]]
for ... |
def param_init_gru(options, params, prefix='gru', nin=None, dim=None):
if nin is None:
nin = options['dim_proj']
if dim is None:
dim = options['dim_proj']
# embedding to gates transformation weights, biases
W = numpy.concatenate([norm_weight(nin, dim),
norm_w... | The function `param_init_gru_cond_simple` initializes parameters for a conditional GRU (Gated Recurrent Unit) model. It sets default dimensions using `options`, initializes GRU parameters via `param_init_gru`, and adds context-to-GRU gate weights (`Wc`) and context-to-hidden proposal weights (`Wcx`). These weights are ... | def param_init_gru_cond_simple(options, params, prefix='gru_cond', nin=None,
dim=None, dimctx=None):
if nin is None:
nin = options['dim']
if dim is None:
dim = options['dim']
if dimctx is None:
dimctx = options['dim']
params = param_init_gru(option... |
def make_type(name, module_class_names):
if name == "void":
link = "#"
elif name in module_class_names:
link = name + ".md"
else:
link = godot_classes_url + "/class_" + name.lower() + ".html"
return make_link(name, link)
def make_text(text, module_class_names):
text = dedent(... | This code parses a Godot class XML file, extracts structural and documentation data, and generates a formatted markdown output containing class hierarchy, properties, methods, signals, enums, constants, and descriptions. It creates tables, links, and structured sections for API documentation, writing results to a file ... | def process_xml(f_xml, f_out, module_class_names):
#print("Parsing", f_xml)
# Parse XML
tree = ET.parse(f_xml)
root = tree.getroot()
if root.tag != "class":
print("Error: No class found. Not a valid Godot class XML file!\n")
sys.exit(1)
# Header
out = "# " + root.attrib['na... |
def is_cves_file_updated():
if os.path.isfile(CVES_PATH):
month_ago = datetime.datetime.now() - datetime.timedelta(30)
modification_date = datetime.datetime.fromtimestamp(os.path.getmtime(CVES_PATH))
need_update = month_ago > modification_date
if need_update:
print("** Th... | The main task of the code is to connect to a Mikrotik device via SSH using provided credentials, execute a series of predefined commands (e.g., retrieving version, scheduler, firewall rules, users, etc.), collect the results into a structured dictionary, and output the data as JSON or formatted text based on user argum... | def main(args):
all_data = {}
commands = [Version(), Scheduler(), Files(), FWNat(), Proxy(), Socks(), DNS(), Users(), Ports(), FW()]
if args.update or is_cves_file_updated():
update_cves()
print(f'** Mikrotik ip address: {args.ip}\n')
with paramiko.SSHClient() as ssh_client:
ssh_c... |
def get_chart_indicators(self):
self.display_checkboxes_moving_averages(self.exponential_moving_averages)
self.display_checkboxes_quant_figure_indicators()
def get_start_end(self):
default_start_date, default_end_date = self.get_default_start_end()
self.start_date = st.sidebar.date_input... | The function `handle_option_overview` processes financial data for multiple stock options by retrieving chart indicators and date ranges, then generates time-based figures (minutes/days) for each symbol in `overview_tickers`. It iterates through each ticker, sets the symbol name, and triggers data visualization or anal... | def handle_option_overview(self):
self.get_chart_indicators()
self.get_start_end()
for ticker in self.overview_tickers:
self.symbol = ticker
self.symbol_name = ticker
self.quant_figure_minutes()
self.quant_figure_days() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.