dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def valids_for_slot_in_conatiner(self, container_type, index):
# returns a dictionary with 9 key-value pairs (tuple- slot coordinate, set - valid digits for the slot)
temp = {}
container_funs = {"row": self.get_row_coordinates(index), "column": self.get_column_coordinates(index),
... | The main task of the code is to solve a container puzzle by filling empty slots with valid digits based on constraints. It iterates through valid options for each slot, assigns single-value options directly, and uses frequency counting to determine unique placements. It tracks solution steps, updates a bad container co... | def container_solver(self, container_type, index):
counter = 0
valid_options = self.valids_for_slot_in_conatiner(
container_type, index)
for slot in valid_options:
if len(valid_options[slot]) == 1:
self[slot] = next(iter(valid_options[slot]))
... |
def doStepping(local_rng,
benefarray,
gfcoords,
cellarray
):
"""
Routine performing GF stepping: combined diffusion by random walk (RW)
and possible binding at each RW step.
Stepping performed until 1) all bind OR 2) all diffuse past lattice OR... | The function `cellCycleLoop` simulates cell cycle dynamics involving growth factor (GF) diffusion, binding, and cell proliferation. It iterates over a specified number of cell cycles, performing GF diffusion-binding ("stepping"), secretion, and benefit calculation using a Hill function. It applies costs if enabled, the... | def cellCycleLoop(local_rng,boundbenefarray,gfcoords,cellarray):
"""
06/07/22 Main worker sub called after all initializations
takes initial bound benefit lattice-style array (benefarray)
and initial matrix of free GF coords (gfcoords), as well as
lattice of cells (cellarr... |
def iniSquareLattice():
"""
Initializing square lattice of size LxL: empty nodes (if L>L_filled)
are 0, non-producers are 1, the seeded producer is 2.
L_filled x L_filled in the middle filled with non-producers
Center of filled - single producer
"""
global L,L_filled
#
if L==L_fi... | The function `one_run` simulates a cellular process involving growth factors and cell cycles. It initializes a lattice of cells (producers/non-producers/empty), sets up bound benefits, and secretes growth factors. Using a random seed, it executes a cell cycle loop to track invasions (`inv_ctr`) and perishing events (`p... | def one_run(local_seed):
print("Process: ", mp.current_process(), "AAA")
local_rng = np.random.default_rng(local_seed)
# initialize/setup lattice of producers/non-producers/empty nodes
cellArray = iniSquareLattice()
# initialize bound benefit lattice (how much benefit is bound in each no... |
def request_qanary_endpoint_for_question(logger, conf_qanary, question):
"""
request to Qanary endpoint that is defined within the configuration with a given question
Args:
conf_qanary ([type]): [description]
question ([type]): [description]
Returns:
[type]: [description]
"... | The main task of the code is to evaluate multiple test cases by querying a Qanary system, validating results against predefined SPARQL templates, and executing a custom validation function. It logs detailed outcomes, including success/failure indicators and execution times, for each test and its validation steps, retur... | def evaluate_tests(logger, conf_qanary, configuration_directory, validation_sparql_templates, custom_module, tests):
"""
evalute all tests defined in the configuration file, here only the request to the Qanary system is executed
Args:
logger ([type]): [description]
conf_qanary ([type]): [de... |
def create_printable_string(str):
return pprint.pformat(str, indent=20)
def determine_if_custom_module_is_callable(logger, custom_module):
"""
checks if the custom module contains a methode 'validate' with the demanded number of parameters
Args:
logger ([type]): [description]
custom_mod... | The main task of the code is to load and execute a test configuration for Qanary validation. It reads a JSON configuration file, imports a custom validation module (or uses a dummy one), runs tests using SPARQL templates, logs results, calculates runtime, and exports outcomes to JSON and Excel files. The process includ... | def main(logger, sheet_name, configuration_directory, outdir, filename_prefix):
start = datetime.datetime.now()
test_configuration_file = configuration_directory + "/qanary-test-definition.json"
test_configuration = {}
with open(test_configuration_file) as json_file:
test_configuration = json.l... |
def scrape_hot(self):
limit = self.config.get("limit")
for submission in self.praw.subreddit(self.config.get("subreddit")).hot(
limit=limit
):
self.scrape_submission(submission)
def scrape_new(self):
limit = self.config.get("limit")
for submission in self.... | The main task of the code is to determine which scraping method to execute based on the "sorting" configuration parameter. It checks the value of "sorting" and calls corresponding methods like scrape_hot(), scrape_new(), or others to handle different content sorting criteria, acting as a dispatcher for various scraping... | def scrape(self):
sorting = self.config.get("sorting")
if sorting == "hot":
self.scrape_hot()
if sorting == "new":
self.scrape_new()
if sorting == "top":
self.scrape_top()
if sorting == "rising":
self.scrape_rising()
if sort... |
def _print_title(self, title):
self._append(title)
self._append('=' * len(title))
self._append('\n')
def _append(self, line):
_line = '%s%s' % (self.ctx.get_indent(), line)
self.lines.append(_line)
def _print_toctree(self, elements, is_package=False):
if not is_package:
... | This code generates a table of contents for a software bundle's API documentation. It constructs a title and description using the bundle name and version, then prints these followed by a sorted list of package entries (toctree) for navigation. The output is stored in `self.lines`, written to the context, and the list ... | def print_table_of_contents(self, packages, bundle_name, bundle_version):
self.lines = []
title = '{0} bundle API'.format(bundle_name)
description = '\nModel API documentation for the {0} bundle.\n Version: **{1}**.\n'.format(bundle_name, bundle_version)
self._print_title(title)
... |
def _print_title(self, title):
self._append(title)
self._append('=' * len(title))
self._append('\n')
def _print_toctree(self, elements, is_package=False):
if not is_package:
# Data Classes
elements = sorted(elements, key=attrgetter('name'))
data_class... | This method prints a header for a named element by formatting its title, generating a table of contents (TOC) tree for non-Enum elements, and appending language-specific tags for non-Package elements. It adjusts the title to include "module" if applicable, constructs a TOC hierarchy from owned elements, and collects ta... | def _print_header(self, named_element):
# Title
title = named_element.name
if isinstance(named_element, Package) and named_element.stmt.keyword == 'module':
title = '%s module' % title
self._print_title(title)
# TOC Tree
if not isinstance(named_element, Enum)... |
def _print_namespace(self, clazz):
if self.lang == 'cpp':
self._append('\n.. cpp:namespace:: ydk::{0}\n'.format(clazz.get_package().name))
def _print_header(self, named_element):
# Title
title = named_element.name
if isinstance(named_element, Package) and named_element.stmt.k... | This function generates reStructuredText documentation for a class by printing its namespace, header, hierarchy, metadata (e.g., presence status, config/state type, RPC parameters), and docstring, while managing indentation levels for proper formatting. | def _print_class_rst(self, clazz):
self._print_namespace(clazz)
self._print_header(clazz)
# Body
self.ctx.lvl_inc()
self._print_bases(clazz)
self._print_class_hierarchy(clazz)
if clazz.stmt.search_one('presence') is not None:
self._append('This class i... |
def _print_namespace(self, clazz):
if self.lang == 'cpp':
self._append('\n.. cpp:namespace:: ydk::{0}\n'.format(clazz.get_package().name))
def _print_header(self, named_element):
# Title
title = named_element.name
if isinstance(named_element, Package) and named_element.stmt.k... | This method generates reStructuredText (RST) documentation for an enum by printing its namespace, header, base classes, and docstring, managing indentation levels to structure the output properly. | def _print_enum_rst(self, enumz):
self._print_namespace(enumz)
self._print_header(enumz)
# Body
self.ctx.lvl_inc()
self._print_bases(enumz)
self._print_docstring(enumz, get_enum_class_docstring(enumz))
self.ctx.lvl_dec() |
def _print_bits_rst(self, bitz):
if self.lang != 'py':
return
self._print_header(bitz)
self.ctx.lvl_inc()
self._print_docstring(bitz, get_bits_class_docstring(bitz))
self.ctx.lvl_dec()
def _print_enum_rst(self, enumz):
self._print_namespace(enumz)
self... | This method generates RST documentation for a module element based on its type. It initializes storage, checks the input element's type (Bits/Enum/Class/Package), calls corresponding private methods to generate content, writes the collected lines to the context, then cleans up the temporary storage. | def print_module_documentation(self, named_element, identity_subclasses):
self.identity_subclasses = identity_subclasses
self.lines = []
if isinstance(named_element, Bits):
self._print_bits_rst(named_element)
elif isinstance(named_element, Enum):
self._print_enum... |
def send_query(ip_address, domain_name, record_type):
query = build_query(domain_name, record_type)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(query, (ip_address, 53))
data, _ = sock.recvfrom(1024)
return parse_dns_packet(data)
def get_answer(packet):
# return the first... | This function performs DNS resolution for a given domain and record type by iteratively querying nameservers. It retrieves the IP address from the response, or follows referrals to other nameservers until the answer is found. If no valid response is obtained, it raises an exception. | def resolve(domain_name, record_type):
nameserver = "172.16.58.3"
while True:
print(f"Querying {nameserver} for {domain_name}")
response = send_query(nameserver, domain_name, record_type)
if ip := get_answer(response):
return ip
elif nsIP := get_nameserver_ip(response... |
def get_metadata_concat(obsfiles, outpath):
filename = obsfiles[0].split('/')[-1]
sensor = filename.split('_')[0]
satellite = filename.split('_')[1]
# Get first and last file cycle
s_cycle = filename.split('_')[3]
end_file = obsfiles[-1]
e_filename = end_file.split('/')[-1]
e_cycl... | The main task of the code is to process input data by either concatenating files or using individual files to generate metadata, create dataframes, and produce visualizations (figures). It uses conditional logic based on the 'concatenate' flag to determine metadata retrieval and figure generation workflows, then return... | def main(input_data):
file = input_data['file']
outpath = input_data['outpath']
concatenate = input_data['concatenate']
if concatenate:
metadata = get_metadata_concat(file, outpath)
datadf, metadatadf = create_dataframes(file, concatenate)
generate_figs(datadf, metadata... |
def empty_cells(state):
"""
Each empty cell will be added into cells' list
:param state: the state of the current board
:return: a list of empty cells
"""
cells = []
for x, row in enumerate(state):
for y, cell in enumerate(row):
if cell == 0:
cells.append... | The main task of the code is to determine the AI's move in a tic-tac-toe variant. It uses **alpha-beta pruning** for optimal decision-making when the game isn't at maximum depth, otherwise selecting a random move. The function checks if the game is over or the board is full, then either returns or selects a move based ... | def ai_turn(c_choice, h_choice, board_size=BOARD_SIZE):
"""
It calls the alpha_beta_pruning function if the depth < (board_size ** 2),
else it chooses a random coordinate.
:param c_choice: computer's choice X or O
:param h_choice: human's choice X or O
:param board_size: size of the board (defau... |
def empty_cells(state):
"""
Each empty cell will be added into cells' list
:param state: the state of the current board
:return: a list of empty cells
"""
cells = []
for x, row in enumerate(state):
for y, cell in enumerate(row):
if cell == 0:
cells.append... | The function `human_turn` allows a human player to select a valid move on a Tic-Tac-Toe board. It checks if the game can proceed (by verifying empty cells and game status), displays the board, and prompts the user for coordinates. The input is validated, and the move is applied if valid. Errors like invalid input or in... | def human_turn(c_choice, h_choice):
"""
The Human plays choosing a valid move.
:param c_choice: computer's choice X or O
:param h_choice: human's choice X or O
:return:
"""
depth = len(empty_cells(board))
if depth == 0 or game_over(board):
return
clean()
print(f'Human tu... |
def clean():
"""
Clears the console
"""
os_name = platform.system().lower()
if 'windows' in os_name:
system('cls')
else:
system('clear')
def convert_board(board, h_choice, c_choice):
rows = len(board)
cols = len(board[0])
for i in range(rows):
for j in range(... | The main task of the code is to run a Tic-Tac-Toe game where the human player selects their symbol (X/O) and starting turn, then alternates with the computer's moves. The game checks for wins/draws, renders the board, and displays outcomes like "YOU WIN!", "YOU LOSE!", or "DRAW!" based on the game state. | def main():
"""
Main function that calls all functions
"""
clean()
h_choice = '' # X or O
c_choice = '' # X or O
first = '' # if human is the first
# Human chooses X or O to play
while h_choice != 'O' and h_choice != 'X':
try:
print('')
h_choice = ... |
def _create_file_menu(self):
"""creates filemenu, and cascade. """
filemenu = tk.Menu(self.menubar, tearoff=False)
self.menubar.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="StartIMSAdmin", command=lambda: self.startimsadmin()) # DUMB referenced!
filemenu.... | This method creates a menubar object and attaches menu buttons to it by configuring the menu and calling private methods to create file, edit, view, and help menus. | def create_menubar(self):
"""
creates menubar object, which all menu buttons are attatched to.
Calls: _create_file_menu, _create_edit_menu, _create_help_menu
to create their respective menus.
"""
self.configure(menu=self.menubar)
self._create_file_menu()
s... |
def switchColors(self, board):
for i in range(len(board)):
if type(board[i]) == list:
for j in range(len(board[i])):
if board[i][j] == 'W':
board[i][j] = 'B'
elif board[i][j] == 'B':
board[i][j] = 'W'
else:
if board[i] == 'W':
board[i] = 'B'
elif board[i] == 'B':
boa... | The function generates valid moves for a checkers game in midgame/endgame phases. It switches board colors if required, selects between hopping moves (when exactly 3 white pieces exist) or regular moves, then reverses color adjustments on both board and move list if switchColor was True, returning the processed move li... | def GenerateMovesMidgameEndgame(self, board, switchColor=False):
if switchColor:
board = self.switchColors(board)
numWhitePieces = 0
for b in board:
if b=='W':
numWhitePieces += 1
if numWhitePieces == 3:
L = self.GenerateHopping(board)
else:
L = self.GenerateMove(board)
if switchColor:
... |
def GenerateMovesMidgameEndgame(self, board, switchColor=False):
if switchColor:
board = self.switchColors(board)
numWhitePieces = 0
for b in board:
if b=='W':
numWhitePieces += 1
if numWhitePieces == 3:
L = self.GenerateHopping(board)
else:
L = self.GenerateMove(board)
if switchColor:
... | The function `staticMidGame` evaluates a board state in a midgame/endgame scenario, calculating a heuristic score. It counts white/black pieces, checks for potential moves, and assesses close/potential mills. It returns high scores for imminent wins (e.g., opponent having ≤2 pieces or no moves) and a weighted combinati... | def staticMidGame(self, board):
numWhitePieces = 0
numBlackPieces = 0
for b in board:
if b=='W':
numWhitePieces += 1
if b=='B':
numBlackPieces += 1
numBlackMoves = len(self.GenerateMovesMidgameEndgame(board, True))
numWhiteCloseMills, numBlackCloseMills, \
numPotWhiteCloseMills, numPotBlackC... |
def check_game_over(attempts, guess, target_word):
"""
Prints results if either game over condition is satisfied (out of attempts or word has been found)
Inputs: Number of attempts, player guess, and target word
Outputs: None
"""
if attempts > 7:
print('Sorry you lose. The Word is ' + ta... | The main task of the code is to run a Wordle175 game where the player guesses a 5-letter target word from a dictionary, receiving color-coded feedback (red/orange/green) for letter correctness. The game tracks attempts, validates inputs, and displays results until the player solves the word or exhausts attempts. | def main():
"""
Runs the Wordle175 game.
Inputs: None
Outputs: None
"""
# initializing game elements
attempts = 1
dictionary = ScrabbleDict(5, 'scrabble5.txt')
target_word = random.choice(dictionary.getWordList())
guess = ''
guessed_words = []
previous_results = []
... |
def get_match_ratio_cycle( seq_1 = "1ST_TEST_SEQ",
seq_2 = "2ND_TEST_SEQUENCE",
# length_comparision = None,
index_seq_1 = 1,
index_seq_2 = 2,
... | This function reduces a dataset of sequences by removing pairs with high match ratios. It compares each sequence against a specified number of subsequent sequences, calculates match ratios, and filters out pairs exceeding a threshold. The result is a reduced dataset with removed sequences, their match details, and comp... | def reduce_dataset_based_on_match_ratio( df = GPCR_DF,
sequences = (),
threshold_len_min = "default",
thresh... |
def return_tune_and_chromaticity(self, beam=1):
"""Returns the tune and chromaticity for the requested beam."""
if beam == 1:
return self.tw_b1["qx"], self.tw_b1["dqx"], self.tw_b1["qy"], self.tw_b1["dqy"]
elif beam == 2:
return self.tw_b2["qx"], self.tw_b2["dqx"], self.t... | The main task of the code is to compile and summarize key collider observables—such as tune, chromaticity, linear coupling, momentum compaction factors, twiss parameters at specific interaction points (IPs), and luminosity—into a formatted string. It optionally writes this summary to a specified file, providing a struc... | def output_check_as_str(self, path_output=None):
"""Summarizes the collider observables in a string, and optionally to a file."""
# Check tune and chromaticity
qx_b1, dqx_b1, qy_b1, dqy_b1 = self.return_tune_and_chromaticity(beam=1)
qx_b2, dqx_b2, qy_b2, dqy_b2 = self.return_tune_and_chr... |
def insert_channel_details(channel_id):
channel_details = get_channel_details(channel_id)
channel_details = (channel_details['channel_id'],channel_details['channel_name'],channel_details['sub_count'],channel_details['view_count'],channel_details['channel_description'],channel_details['channel_status'],)
in... | The main task of the code is to insert data related to a YouTube channel into three database tables: channel details, video details, and comment details. It achieves this by calling three sub-functions—`insert_channel_details`, `insert_video_details`, and `insert_comment_details`—each using the provided `channel_id` to... | def insert_all_table(channel_id):
insert_channel_details(channel_id)
insert_video_details(channel_id)
insert_comment_details(channel_id) |
def store(a, v):
if 0 <= a < MAXINT:
memory[a] = v
elif MAXINT <= a < MAXINT+8:
set_register(a, v)
else:
error('store ' + str(a))
def read_value():
v = value_or_register(read_next())
return v
def set_register(i, v):
if 0 <= i < 8:
register[i] = v
elif MAXINT <= i < MAXINT+8:
register[i... | The code defines a virtual machine interpreter that executes a sequence of instructions from the input `data`. It processes each opcode (0–21) to perform operations like arithmetic, memory management, control flow (jumps, calls, returns), and I/O handling. The interpreter runs in a loop, halting on opcode 0 (`halt`), a... | def run(data):
for i in range(len(data)):
store(i, data[i])
while True:
if STOP:
break
code = read_value()
#codes.append((code, address-1))
# if code == 19 and codes[-2][0] != 19:
# print(codes[-10:])
# if 2200 < address and not 2740 < address < 3335 and not 5800 < address < 5950... |
def batch_norm_relu(inputs, is_training, data_format):
"""
performs a batch normalization followed by a relu
"""
inputs = tf.layers.batch_normalization(
inputs = inputs, axis = 1 if data_format == 'channels_first' else 3,
momentum = _BATCH_NORM_DECAY, epsilon = _BATCH_NORM_EPSILON, cent... | This function implements a residual building block for residual networks, applying batch normalization and ReLU before two 3x3 convolutions. It includes a projection shortcut (1x1 conv) for downsampling when needed, adds dropout regularization, and returns the sum of the processed inputs and shortcut, enabling residual... | def building_block(inputs, filters, is_training, projection_shortcut, strides, data_format):
"""standard building block for residual networks with batch normalization before convolutions
Args:
inputs: A tensor of size [batch, channels, height_in, width_in] or
[batch, height_in, width_in, channels... |
def batch_norm_relu(inputs, is_training, data_format):
"""
performs a batch normalization followed by a relu
"""
inputs = tf.layers.batch_normalization(
inputs = inputs, axis = 1 if data_format == 'channels_first' else 3,
momentum = _BATCH_NORM_DECAY, epsilon = _BATCH_NORM_EPSILON, cent... | This code implements a residual bottleneck block for deep neural networks, applying batch normalization, ReLU activation, and dropout to three convolutional layers (1x1, 3x3, and 1x1). It uses a projection shortcut (1x1 convolution) for downsampling when needed, combines features via residual connections, and returns t... | def bottleneck_block(inputs, filters, is_training, projection_shortcut,
strides, data_format):
"""Bottleneck block variant for residual networks with BN before convolutions.
Args:
inputs: A tensor of size [batch, channels, height_in, width_in] or
[batch, height_in, width_in, chann... |
def initialize_word_entries(self):
for word_entry in self.board.state_space["word_entries"]:
self.unused_entries.append(word_entry)
self.state_space["unused"].append(word_entry["id"])
def get_entry_by_id(self, id):
used_ids = [entry["id"] for entry in self.used_entries]
i... | The `reset_game` function resets the game state by reinitializing the board grid, clearing cumulative rewards and entry lists, and inserting a randomly selected valid word into the "2D" entry. It prepares the game for a new round by resetting all variables and placing a new word in a specific position. | def reset_game(self):
self.board.grid = self.board.initialize_grid()
self.cumulative_reward = 0
self.used_entries = []
self.unused_entries = []
self.initialize_word_entries()
word_entry = self.get_entry_by_id("2D")
valid_word_list = self.get_valid_words_f... |
def get_random_unused_entry(self):
return np.random.choice(self.unused_entries)
def get_entry_by_id(self, id):
used_ids = [entry["id"] for entry in self.used_entries]
if id in used_ids:
return self.get_entry_from_list(self.used_entries, id)
else:
return self.get_e... | This code simulates a reinforcement learning step in a word-based environment. It processes actions (add/remove) to transition between states, validating word entries and managing rewards. If adding a word fails, it recursively attempts valid moves. Removing words involves handling failures and selecting new entries, r... | def step(self, state, action_tuple, must_remove=False):
action = int(must_remove==True)
next_state = action_tuple[1]
if next_state not in [entry["id"] for entry in self.unused_entries]:
return self.step(state, (state,self.get_random_unused_entry()["id"]))
word_entry = self.ge... |
def handle_win(context: GameContext, event: pygame.event.Event) -> None:
"""Handles the win event, showing the winner and restarting the game.
Args:
context: GameContext object with the context variables of the game.
event: An EventType object with the current event to handle.
"""
if e... | The code defines a game event handler function that processes Pygame events using three specialized sub-functions: handling win conditions, bullet collisions, and bullet firing events, all while updating the game context accordingly. | def handle_event(context: GameContext, event: pygame.event.Event) -> None:
"""Event handler of the game.
Args:
context: GameContext object with the context variables of the game.
event: An EventType object with the current event to handle.
"""
handle_win(context, event)
handle_bulle... |
def merge_strategy_data(historic_block_list, strategy_list=const.STRATEGY_LIST, oracle_list=const.ORACLE_ADDRESS_LIST,
pool_address_list=const.CURVE_POOL_LIST,
strategy_names=const.STRATEGY_NAME):
data_list = []
for i in range(len(strategy_list)):
strateg... | The main task of the code is to merge new strategy and PPS data from a historic block list into existing dataframes, sort them by 'block', save the updated data, and return the modified dataframes. It combines historical data with existing datasets, ensuring sorted order and data persistence. | def get_data_for_blocks(historic_block_list, save_strategy_data, save_pps_data):
new_strategy_data = merge_strategy_data(historic_block_list=historic_block_list)
save_strategy_data = save_strategy_data.copy()
save_strategy_data = pd.concat([save_strategy_data, new_strategy_data], ignore_index=True)
save... |
def get_candidates(self, chroma, max_tick, intervals=[1, 2, 3, 4]):
candidates = {}
for interval in intervals:
for start_beat in range(max_tick):
# set target pianoroll
end_beat = start_beat + interval
if end_beat > max_tick:
end_beat = max_tick
_chroma = chroma[:... | This code extracts chord sequences from audio data by analyzing chroma features and beat timings. It generates candidate chords, applies a greedy algorithm to select optimal sequences, removes duplicates, and adjusts chord timings to align with beat boundaries. The result is a list of chords with start/end times mapped... | def extract(self):
# read
beats = self.pm.get_beats()
chroma = self.pm.get_chroma(times=beats)
# get lots of candidates
candidates = self.get_candidates(chroma, max_tick=len(beats))
# greedy
chords = self.dynamic(candidates=candidates,
max_tick=len(beats),
... |
def _get_split(files, worker_info):
if worker_info:
n_workers = worker_info.num_workers
worker_id = worker_info.id
per_worker = math.ceil(len(files) / n_workers)
start_idx = per_worker*worker_id
end_idx = start_idx + per_worker
split = files[start_idx:end_idx]
else:
split = files
ret... | This code processes musical event sequences into tokenized contexts with bar/position IDs, splitting data across workers, filtering sequences by max bars/positions, masking bar tokens, and yielding batches with optional descriptions/latents for ML training. | def __iter__(self):
worker_info = torch.utils.data.get_worker_info()
self.split = _get_split(self.files, worker_info)
split_len = len(self.split)
for i in range(split_len):
try:
current_file = self.load_file(self.split[i])
except ValueError as err:
if self.print_errors:... |
def Words_to_IDs(self, wtoidx, caption_batch):
for i, caption in enumerate(caption_batch):
cap = []
for word in caption.split():
try:
cap.append(wtoidx[word])
except KeyError:
cap.append(wtoidx["<UNK>"])
... | This code initializes a model's configuration parameters, loads training/test data, sets up vocabulary mappings, and prepares model components based on the specified mode (train/test). It handles data preprocessing, checkpoint resuming, and model structure initialization, with conditional logic for training vs. inferen... | def __init__(self, config, data=None):
self.dim_imgft = np.int(config.dim_imgft)
self.embedding_size = np.int(config.embedding_size)
self.num_hidden = np.int(config.num_hidden)
self.batch_size = np.int(config.batch_size)
self.num_timesteps = np.int(config.num_timesteps)
s... |
def _f_response(x_data, delta_t, gamma, ksq):
fx_data = lambda: fftn(x_data, axes=_axes(x_data))
fx3_data = lambda: fftn(x_data ** 3, axes=_axes(x_data))
implicit = lambda: (1 - gamma * ksq) - _explicit(gamma, ksq)
delta_t_ksq = lambda: delta_t * ksq
numerator = lambda: fx_data() * \
(1 + de... | The code advances a microstructure's evolution in time by one step using the Cahn-Hilliard equation, a mathematical model for phase separation in materials. It employs spectral methods (via FFT) to compute the updated microstructure based on the initial data, grid spacing (`delta_x`), time step (`delta_t`), and paramet... | def solve_cahn_hilliard(x_data, delta_x=0.25, delta_t=0.001, gamma=1.):
"""Solve the Cahn-Hilliard equation for one step.
Advance multiple microstuctures in time with the Cahn-Hilliard
equation.
Args:
x_data: the initial microstucture
delta_x: the grid spacing
delta_t: the time step ... |
def test00_get(self):
self.print_test_content("/", "00")
def test01_get(self):
self.print_test_content("/a", "01")
def test02_get(self):
self.print_test_content("/a/", "02")
def test03_get(self):
self.print_test_content("/doesntexist", "03")
def test05_get(self):
self.print_test_content("/fake_dir/", "05")
de... | The main task of the code is to execute a series of test methods (test00_get to test08_get) within a test suite and return the collected test cases stored in `self.tests`. This function likely aggregates results from individual GET-related tests and prepares them for execution or validation in a testing framework. | def test_simple_get(self):
self.test00_get()
self.test01_get()
self.test02_get()
self.test03_get()
self.test05_get()
self.test06_get()
self.test08_get()
return self.tests |
def padding(data,blockSize):
padSize=blockSize-len(data)
padding=([padSize])*padSize
return data+padding
def aesBlockEncrypt(plaintext,keys):
ciphertext=plaintext
ciphertext=XOR(ciphertext,keys[0])
for i in range(1,rounds):
ciphertext=ByteSub(ciphertext)
ciphertext=ShiftRow(cip... | This code implements AES encryption using a counter-based mode (CTR). It processes the plaintext in blocks, pads each block to the block size, encrypts the counter with AES using provided keys, XORs the encrypted counter with the padded plaintext block, increments the counter for each block, and accumulates the resulti... | def aesEncrypt(plaintext,keys,counter):
length=len(plaintext)
ciphertext=[]
plaintext=[ord(c) for c in plaintext]
for i in range(0,length,blockSize):
string=plaintext[i:i+blockSize]
string=padding(string,blockSize)
plaintemptext=aesBlockEncrypt(counter,keys)
ciphert... |
def aesBlockEncrypt(plaintext,keys):
ciphertext=plaintext
ciphertext=XOR(ciphertext,keys[0])
for i in range(1,rounds):
ciphertext=ByteSub(ciphertext)
ciphertext=ShiftRow(ciphertext)
ciphertext=MixColumn(ciphertext)
ciphertext=XOR(ciphertext,keys[i])
ciphertext=ByteSub(... | This code decrypts ciphertext using AES in Counter (CTR) mode. It processes the ciphertext in blocks, encrypts a counter value with AES keys, XORs the result with each ciphertext block to retrieve plaintext, and increments the counter for each block. The input ciphertext is converted to ASCII values, and the decrypted ... | def aesDecrypt(ciphertext,keys,counter):
length=len(ciphertext)
plaintext=[]
ciphertext=[ord(c) for c in ciphertext]
for i in range(0,length,blockSize):
string=ciphertext[i:i+blockSize]
ciphertemptext=aesBlockEncrypt(counter,keys)
plaintemptext=XOR(ciphertemptext,string)
... |
def expandedKeysGenerate(masterKey):
expandedKeys=[]
numWords=44
words=[None]*numWords
for i in range(4):
temp=[]
for j in range(4):
temp.append(masterKey[4*i+j])
words[i]=temp
for i in range(4,numWords):
temp=[]
if i%4==0:
for j in ran... | This code reads input data from a file, performs AES encryption using a master key and counter, then decrypts the result to verify correctness. It converts text to ASCII values, generates encryption keys, encrypts plaintext, decrypts ciphertext, removes padding, and prints both encrypted and decrypted outputs. | def main():
with open("AES-Input.txt","r") as file:
masterKey=file.readline()
counter=file.readline()
plaintext=file.read()
print("Plain data : ",plaintext)
#counter=Generate(blockSize)
counterArray=[ord(i) for i in counter]
print('Counter : ',counter)
#... |
def similarity_search(self, user_context, threshold = 0.15):
question_embedding = get_ada_embedding(user_context)
self.logger.log(self.DEV_LEVEL, "################# Similarity Search #################")
relevant_definitions = get_closest_nodes(self.df_definitions_all, embedding_c... | The function processes user input through a Retrieval-Augmented Generation (RAG) system, managing state transitions (e.g., "stuck," "rag"). It validates input, appends messages to a history, performs similarity searches, and generates responses. If no data is found or errors occur, it logs issues, updates system states... | def user_provides_input(self, user_context, threshold, model_to_use, temperature, max_tokens,
testing = False, manual_responses_for_testing = []):
if user_context is None:
self.logger.error("The user passed an empty string. This should not have happened and is an... |
def absTree(self,tree):
if tree != None:
self.absTree(tree.getLeftChild())
self.absTree(tree.getRightChild())
global listOfOperators
rootVal = tree.getRootVal()
for index,listOp in enumerate(self.listOfOperators):
if rootVal in listOp:
... | The main task of the code is to parse a formula string into an abstract syntax tree, generate logical formulas using models, format them, and combine with parenthetical variations. It processes the formula through parsing, abstraction, concretization, and outputs formatted results including all possible parenthetical c... | def mainResultOne(self): #,strFormula, operators):
#click.echo('Enter the formula as a string and a list of lists of operators')
#global listOfOperators
#listOfOperators = operators
parser = ParseTree()
pt = parser.parse(self.strFormula)
#print(pt)
self.absTree(pt... |
def conc(self, z3_exp, solver):
if z3_exp != None:
self.conc(self.getLeftChild(z3_exp), solver)
#global listOfOperators
rootVal = z3_exp.decl()
for l in self.listOfOperators:
if str(rootVal) in l:
x = self.freshVariable()
... | The main task of the code is to generate and return a list of formulas similar to the given input formula by replacing operators with equivalent ones from the provided list. It uses Z3 to parse the formula, derive models, and create variations through replacement, then formats and prints the resulting formulas. | def mainResult(self): #, strFormula, operators):
"""
Return a list of formulas similar to the given formula
:param strFormula: The base formula used to generate similar formulas.
:type strFormula: String
:param operators: The list of lists of operators to replace. If tw... |
def game_setup(self):
blank_dict = {}
self.current_window = "options_window"
self.roomDict = blank_dict
self.current_room = Room()
self.current_room.id = 0
self.current_room.type = "easy"
self.current_room.has_enemy = False
self.current_room.has_item = Fal... | This code initializes a curses-based game interface, creating multiple windows for the map, status, options, and main display. It sets up color pairs, handles user input for navigation and actions (e.g., fleeing or fighting), and updates the screen dynamically. The main task is to manage a text-based game UI with inter... | def Main(self, stdscr):
k = 0
cursor_x = 0
cursor_y = 0
temp_options= ["Flee the room the way you came", "Stand and Fight"]
# Box size
box_width = 6
box_height = 4
self.main_screen = stdscr
height, width = self.main_screen.getmaxyx()
sepera... |
def print_str(self, stdscr, str, y=0, x=0):
stdscr.addstr(y+2,x+2,str)
return
def clear_scr(self):
self.map_window.clear()
self.status_window.clear()
self.options_window.clear()
self.main_window.clear()
#self.main_screen.clear()
return
def refresh_scr(sel... | This code implements a turn-based combat system where the player can attack or flee from an enemy. It handles weapon damage, enemy health reduction, durability depletion, and player death. If the enemy is defeated, the player gains gold. The system uses curses for input/output and updates game state dynamically. | def combat(self):
# combat system
k=0
self.current_option = 0
self.selected_option = -1
self.print_str(self.main_window, "You decide to fight the enemy in front of you!")
while self.current_room.has_enemy is True:
self.clear_scr()
self.re... |
def clear_scr(self):
self.map_window.clear()
self.status_window.clear()
self.options_window.clear()
self.main_window.clear()
#self.main_screen.clear()
return
def window_boarders(self):
#height, width = stdscr.getmaxyx()
#center_x = int(width//2.3)
... | This code implements an NPC shop interface in a text-based game using the curses library. It allows players to navigate options (Buy/Sell/Leave), view item details, purchase items with gold, sell inventory items for gold, and update player/NPC inventories accordingly. The loop handles user input for navigation, validat... | def npc_shop(self):
option_int = 0
k=0
buy = False
while(k != ord('q')):
self.clear_scr()
self.window_boarders()
self.refresh_scr()
self.map_window.addstr(self.current_room.position[1],self.current_room.position[0], ... |
def pretty_subplots(
nplots: int = 1,
dict_kwargs={},
sorted_kwargs = False,
):
fig_kw = dict_kwargs.pop("fig", {})
# Set default values:
nrows = fig_kw.pop("nrows", None)
ncols = fig_kw.pop("ncols", None)
sharex = fig_kw.pop("sharex", True)
sharey = fig_kw.pop("sharey", True)
s... | The function `plot_mean_and_std` generates a plot visualizing the mean and standard deviation of input data. It accepts either raw data (`yvalues`) to compute statistics or precomputed `mean_values` and `std_values`. The plot includes a mean line and standard deviation representation (as lines or shaded areas) with cus... | def plot_mean_and_std(
yvalues = None,
mean_values = None,
std_values = None,
xvalues = None,
fig = None,
ax = None,
dict_kwargs={},
sorted_kwargs = False,
):
"""
Plot mean and std
You can either give directly the mean line in 'mean_line' or
give raw data in 'yvalues' (n... |
def sort_kwargs(
kwargs
):
dict_keys = show_kwargs(verbose=False)
dict_kwargs = {
"font" : {},
"fig" : {},
"text" : {},
"dflt" : {},
"kde" : {},
"fit" : {},
"hist" : {},
"plot" : {},
"line" : {},
}
for key in kwargs:
if... | This function converts lists of y-values (and optional x-values) into subplots with specified plot types (e.g., line, scatter, distribution). It initializes figures/axes, handles data formatting, applies default/override parameters, plots data across subplots, adds text, and returns the figure/axes. It supports multipl... | def from_list_to_subplots(
list_yvalues, # List[ndarray([n_lines, ] n_values )]
list_xvalues=None, # List[ndarray([1, ] n_values )]
plt_type: str = "plot",
fig = None,
axs = None,
show: bool = True,
dict_kwargs = {},
**kwargs,
):
# Sort key_words because matplotlib doesn't support... |
def get_initial_index(input_name: str, input_structure: list) -> int:
for index, i in enumerate(input_structure):
if i.file_name == input_name:
return index
return -1
def get_last_index(input_name: str, input_structure: list) -> int:
for index, i in enumerate(input_structure):
if... | The function `write_at` inserts `input_data` at a specified index in a file's structure, checking if the file exists, ensuring sufficient memory, and handling errors via `connection_pointer`. It modifies the file's data, updates the structure, and returns the adjusted structure or error messages if conditions fail. | def write_at(input_name: str, write_at_index: int, input_data: str, input_structure: list, connection_pointer) -> list:
starting_index = get_initial_index(input_name, input_structure)
last_index = get_last_index(input_name, input_structure)
is_file_exists = file_existence_checker(input_name, input_structure... |
def get_initial_index(input_name: str, input_structure: list) -> int:
for index, i in enumerate(input_structure):
if i.file_name == input_name:
return index
return -1
def get_last_index(input_name: str, input_structure: list) -> int:
for index, i in enumerate(input_structure):
if... | This function truncates a file's data structure by checking its existence, validating the truncate index against file size, and rewriting the structure if valid. It communicates via a connection pointer, sending errors for invalid indices or missing files, and returns the modified structure upon successful truncation. | def truncate(input_name: str, truncate_index: int, input_structure: list, connection_pointer) -> list:
starting_index = get_initial_index(input_name, input_structure)
last_index = get_last_index(input_name, input_structure)
is_file_exists = file_existence_checker(input_name, input_structure)
read_data =... |
def get_initial_index(input_name: str, input_structure: list) -> int:
for index, i in enumerate(input_structure):
if i.file_name == input_name:
return index
return -1
def get_last_index(input_name: str, input_structure: list) -> int:
for index, i in enumerate(input_structure):
if... | This function moves a specified block of data within a file's structure by rearranging its contents based on given indices. It checks file existence, validates parameters, and adjusts data positions either forward or backward. If valid, it updates the file structure; otherwise, it sends error messages through a connect... | def move_within_file(input_name: str, initial_index: int, ending_index: int, data_size: int,
input_structure: list, connection_pointer) -> list:
starting_index = get_initial_index(input_name, input_structure)
last_index = get_last_index(input_name, input_structure)
file_exists = file_ex... |
def update_label(self):
self.get_text()
def get_text(self):
self.get_dates()
req_tuple = self.process_dates()
self.display_labels(req_tuple)
def update_clock(self):
ist = timezone('Asia/Kolkata')
raw_tz = dt.now(ist)
time_now = raw_tz.strftime("%H:%M:%S %p")
... | This code initializes a GUI for an "Age Finder" application by setting up the window dimensions, title, and layout. It creates multiple frames to organize elements like a calendar widget, date/month/year input/output fields, age calculation displays, and a clock. The interface is structured with precise positioning of ... | def initialize_ui(self):
self.root.geometry('800x500+200+50')
self.root.title('Age Finder | Developed by Prathmesh')
self.root.resizable(False, False)
cal_frame = Frame(self.root, bd=4, relief=RIDGE, bg='white')
cal_frame.place(x=0, y=0, relwidth=0.625, relheight=1)
da... |
def read_comments(comments_filename):
trajectory = []
clear_events = []
with open(comments_filename, 'r') as f:
comments = json.load(f)
if isinstance(comments, dict):
trajectory = comments["trajectory"]
clear_events = comments["clear"]
comments = comments["comments"]
return comments, trajectory, clear_... | The code processes a video file along with associated comments, adjusting playback speed and generating a final video with text overlays and audio. It handles command-line arguments to either preview the output, combine video with audio comments, or generate a finalized video file with synchronized comments and adjuste... | def main():
video_filename = sys.argv[1]
comments_filename = video_filename + ".comments.json"
comments, trajectory, clear_events = read_comments(comments_filename)
# comments = comments[0:3]
audioSpeedScale = float(sys.argv[3]) if len(sys.argv) > 3 and float(sys.argv[3]) else 1.0
if len(sys.argv) > 2 and sys.... |
def get_dropbox_accesstoken_from_refreshtoken(REFRESH_TOKEN, APP_KEY, APP_SECRET):
'''
### Get the auth token from a valid refresh token, Key and Secret
returns an authorization token for dropbox, error otherwise
https://www.dropboxforum.com/t5/Dropbox-API-Support-Feedback/Get-refresh-token-from-acces... | The main task of the code is to automatically extract tables from files in a specified directory (or Dropbox) and save them into a database. It identifies unique table headings, processes PDF and Excel files, cleans data, guesses headers, and logs progress. The function handles Dropbox authentication, checks for existi... | def save_all_file_tables_in_dir(dirpath:str, use_dropbox = False):
'''
Top level function to create tables and save to db
Automatically identifies unique table headings
'''
try:
load_dotenv()
# NOTE: do NOT deploy with your key hardcoded
tmp = os.getenv('OPENAI_API_KEY')
... |
def get_spreadsheet_id(self, spreadsheet_name):
success = False
while not success:
# Define the search query to find the workbook
query = f"name='{spreadsheet_name}' and mimeType='application/vnd.google-apps.spreadsheet' and trashed=false"
# Call the Drive API to sea... | The main task of the code is to insert a specified number of empty columns at the beginning of a Google Sheet using the Sheets API, with retry logic for handling API errors, quota limits, and connection issues. It retrieves the spreadsheet and sheet IDs, constructs an API request to insert columns and update cells, and... | def insert_cells_at_start(self, spreadsheet_name, sheet_name, num_columns):
success = False
while not success:
try:
# Get the spreadsheet ID
spreadsheet_id = self.get_spreadsheet_id(spreadsheet_name)
# Get the sheet ID
sheet_id... |
def get_spreadsheet_id(self, spreadsheet_name):
success = False
while not success:
# Define the search query to find the workbook
query = f"name='{spreadsheet_name}' and mimeType='application/vnd.google-apps.spreadsheet' and trashed=false"
# Call the Drive API to sea... | This function updates specified rows and columns in a Google Sheet to set custom pixel sizes for height and width. It retrieves spreadsheet and sheet IDs, constructs API requests to adjust dimensions based on the provided cell range, and executes batch updates. Error handling includes retries for API limits and connect... | def update_cell_size(self, spreadsheet_name, sheet_name, cell_range, row_height, col_width):
# Get the spreadsheet ID
spreadsheet_id = self.get_spreadsheet_id(spreadsheet_name)
# Get the sheet ID
sheet_id = self.get_or_create_sheet_id(sheet_name)
# create a request body that sp... |
def get_spreadsheet_id(self, spreadsheet_name):
success = False
while not success:
# Define the search query to find the workbook
query = f"name='{spreadsheet_name}' and mimeType='application/vnd.google-apps.spreadsheet' and trashed=false"
# Call the Drive API to sea... | This function updates a specific cell's background color in a Google Sheet by converting coordinates to indices, translating a color name to RGB values, and sending a batch update request via the Google Sheets API, with retry logic for handling API errors, connection issues, or timeouts. | def update_cell_color(self, spreadsheet_name, sheet_name, cell_coordinates, color_name):
# Get the ID of the "Ranking" spreadsheet and the ID of the "Sheet10" sheet
spreadsheet_id = self.get_spreadsheet_id(spreadsheet_name)
sheet_id = self.get_or_create_sheet_id(spreadsheet_name, sheet_name)
... |
def get_or_create_sheet_id(self, spreadsheet_name, sheet_name):
success = False
while not success:
try:
spreadsheet_id = self.get_spreadsheet_id(spreadsheet_name)
sheet_metadata = self.sheets_service.spreadsheets().get(
spreadsheetId=spread... | This function updates row heights and column widths in a Google Sheet using batch API requests, handling retries for quota limits and connection errors. It processes specified ranges with their pixel dimensions, applying changes via the Sheets API with error resilience. | def update_cell_sizes_avg_price(self, spreadsheat_name, sheet_name, ranges_and_sizes):
sheet_id = self.get_or_create_sheet_id(spreadsheat_name, sheet_name)
batch_requests = []
for range_str, row_height, column_width in ranges_and_sizes:
start_col = column_index_from_string(range... |
def insert_cells_at_start(self, spreadsheet_name, sheet_name, num_columns):
success = False
while not success:
try:
# Get the spreadsheet ID
spreadsheet_id = self.get_spreadsheet_id(spreadsheet_name)
# Get the sheet ID
sheet_id... | This method modifies a spreadsheet by inserting cells, adjusting cell sizes, merging cells with specific labels (e.g., "12 Guests"), setting cell colors to white, and updating average price-related cells. It structures the sheet for displaying averaged price data with formatted layouts and labels. | def inserting_structure_avg_prices(self, spreadsheet_name, sheet_name):
self.insert_cells_at_start(spreadsheet_name, sheet_name, 8)
# updating cell size
ranges_and_sizes = [('B2:D2', 30, 60), ('F2:H2', 30, 60), ('C3:C3', 30, 100), ('G3:G3', 30, 100),
('E3:E3', 30, 30... |
def insert_cells_at_start(self, spreadsheet_name, sheet_name, num_columns):
success = False
while not success:
try:
# Get the spreadsheet ID
spreadsheet_id = self.get_spreadsheet_id(spreadsheet_name)
# Get the sheet ID
sheet_id... | This function prepares a spreadsheet for ranking data by inserting cells, adjusting column sizes, merging cells for headers (date and "Number of Guests"), and updating ranking information. It formats the sheet structure, sets dynamic content like today's date, and ensures proper layout for displaying rankings. | def insert_cells_for_ranking(self, spreadsheet_name, sheet_name):
self.insert_cells_at_start(spreadsheet_name, sheet_name, 12)
ranges_and_sizes = [('C1:K1', 50, 70), ('A1:A1', 50, 280), ('B1:B1', 30, 130), ('L1:L1', 50, 40)]
self.update_cell_sizes_avg_price(spreadsheet_name, sheet_name, ranges_... |
def insert_cells_at_start(self, spreadsheet_name, sheet_name, num_columns):
success = False
while not success:
try:
# Get the spreadsheet ID
spreadsheet_id = self.get_spreadsheet_id(spreadsheet_name)
# Get the sheet ID
sheet_id... | This function modifies a spreadsheet to prepare it for a price log by inserting cells at the start, adjusting specified cell ranges' sizes, and setting the background color of cells H1 and H2 to white. It ensures proper formatting for displaying average price data. | def insert_cells_for_price_log(self, spreadsheet_name, sheet_name):
self.insert_cells_at_start(spreadsheet_name, sheet_name, 8)
ranges_and_sizes = [('A2:A2', 60, 250), ('B2:G2', 60, 150), ('H2:H2', 60, 30)]
self.update_cell_sizes_avg_price(spreadsheet_name, sheet_name, ranges_and_sizes)
... |
def inserting_structure_avg_prices(self, spreadsheet_name, sheet_name):
self.insert_cells_at_start(spreadsheet_name, sheet_name, 8)
# updating cell size
ranges_and_sizes = [('B2:D2', 30, 60), ('F2:H2', 30, 60), ('C3:C3', 30, 100), ('G3:G3', 30, 100),
('E3:E3', 30, 30... | The main task of the code is to insert hotel data (bedrooms, prices, URLs) and calculate average prices into a spreadsheet for different guest numbers (12 and 14) based on filters. It processes check-in/check-out dates, updates spreadsheet ranges, computes averages, and adds property prices for "Villa in Hollywood" usi... | def insert_data_avg_price(self, spreadsheet_name, sheet_name, df_filters,description):
for a in range(len(df_filters)):
first_row = df_filters.iloc[a]
location = first_row[0]
checkin = str(first_row[1].date())
checkout = str(first_row[2].date())
# in... |
def insert_cells_for_price_log(self, spreadsheet_name, sheet_name):
self.insert_cells_at_start(spreadsheet_name, sheet_name, 8)
ranges_and_sizes = [('A2:A2', 60, 250), ('B2:G2', 60, 150), ('H2:H2', 60, 30)]
self.update_cell_sizes_avg_price(spreadsheet_name, sheet_name, ranges_and_sizes)
... | The main task of the code is to log and analyze hotel price and ranking changes over time by comparing historical data with current values. It reads filtered input data, retrieves historical prices and ranks from a spreadsheet, calculates percentage price changes, checks rank variations, and inserts structured results ... | def price_change_log(self,spreadsheet_name,hotel_ranking_sheet,worksheet_name,hotel_name):
self.insert_cells_for_price_log(spreadsheet_name,worksheet_name)
today = date.today()
self.combine_and_update_col(spreadsheet_name, worksheet_name, 'A1:G1', str(today))
self.inserting_colu... |
def insert_cells_for_ranking(self, spreadsheet_name, sheet_name):
self.insert_cells_at_start(spreadsheet_name, sheet_name, 12)
ranges_and_sizes = [('C1:K1', 50, 70), ('A1:A1', 50, 280), ('B1:B1', 30, 130), ('L1:L1', 50, 40)]
self.update_cell_sizes_avg_price(spreadsheet_name, sheet_name, ranges_... | The main task of the code is to insert ranking data and log price changes into a spreadsheet. It first adds cells for ranking, inserts data using description and location, then logs price changes to a specified price log sheet. | def main(self,spreadsheet_name,sheet_name,description,location,price_log_sheet):
# Ranking
self.insert_cells_for_ranking(spreadsheet_name, sheet_name)
self.insert_data_of_ranking(spreadsheet_name, sheet_name,sheet_name,description,location)
self.print("Inserting Values ... |
def make_group_features(self):
for groupIdx in self.groupIdxs[self.prevGroupCount:]:
groupXs = []
groupYs = []
groupSLefts = []
groupSRights = []
groupSTops = []
groupSBottoms = []
for visPoint... | This function iteratively groups objects into metagroups by calculating features, determining radii, and merging groups until only one group remains. It increments iteration counters, updates group features, and checks if the group count decreases by one to finalize the metagroup, setting `metaGrouped` to True when com... | def group_groups(self):
while not self.metaGrouped:
self.groupGroupingIters += 1
self.make_group_features()
self.determine_radius()
self.prevGroupCount = self.groupCount
... |
def build_from_visicon(self):
visPointList = []
for feat in self.visFeats:
visPointList.append(visPoint(feat))
self.visPoints = visPointList
def determine_radius(self):
distances = []
for pair in itertools.combinations(self.visPoints,2):
argDi... | This code initializes an object with visual features, grouping parameters, and collision weights. It populates visualization points from the input data, calculates a grouping radius, and creates groups of points based on this radius if non-zero. The main tasks are: 1) initializing attributes, 2) building visualization ... | def __init__(self, currentVisicon, glomType, collisionWeights):
self.visFeats = currentVisicon
self.glomRadius = 0
self.glomType = glomType
self.weights = collisionWeights
self.visPoints = None
# using the maintained currentVisicon, create a set of visPoint objec... |
def build_from_visicon(self):
for feat in self.visFeats:
self.visPoints.append(visPoint(feat))
self.visPoints[-1].groupGroupingIter = self.groupGroupingIters
def glom_groups(self,radius):
for pt in self.visPoints:
if not pt.checked and pt.groupId... | This code initializes a grouping module by setting up visual features, creating visPoint objects from currVisicon, grouping them based on glomType and radius, labeling groups, and performing hierarchical grouping. It prepares the structure for spatial clustering and metadata grouping operations. | def __init__(self, currVisicon, glomType):
self.visFeats = currVisicon
self.glomRadius = 0
self.glomType = glomType
self.visPoints = []
self.groupCount = 0
self.prevGroupCount = 0
self.groupNames = []
self.groupIdxs = []
self.metaGrouped = False
... |
def get_font():
fonts = [x for x in pygame.font.get_fonts()]
default_font = 'ubuntumono'
font = default_font if default_font in fonts else fonts[0]
font = pygame.font.match_font(font)
return pygame.font.Font(font, 14)
def should_quit():
for event in pygame.event.get():
if event.type == p... | The main task of the code is to simulate an autonomous vehicle in the CARLA environment, spawn a Tesla Model 3, attach an RGB camera, and capture real-time sensor data. It synchronizes with CARLA's simulation, measures distances to vehicles, displays camera feeds, and shows FPS metrics in a Pygame window. The script al... | def main():
actor_list = []
pygame.init()
display = pygame.display.set_mode(
(800, 600),
pygame.HWSURFACE | pygame.DOUBLEBUF)
font = get_font()
clock = pygame.time.Clock()
client = carla.Client('localhost', 2000)
client.set_timeout(2.0)
world = client.get_world()
... |
def next_action(self, first=0, last=None):
if last is None:
last = len(self.actions) - 1
self.cur_action += 1
if self.cur_action > last:
self.cur_action = first
action = self.actions[self.cur_action]
if self.pause_timer is not None:
self.disp.d... | The function handles button events by triggering actions based on the button press state. If the button is 'B', it initiates a transition to the next action (first=2). For other buttons, it sends input commands via JSON, waits briefly (0.2s) for screen updates, then captures a screenshot without clearing the display, e... | def button_event_screen_keys(self, button, state, data):
if state != 1:
return
if button == 'B':
self.next_action(first=2)
else:
self.json_call('Input.' + data[button])
# Need to wait a bit for the skin to have a chance to update the
# ... |
def update_ipt_with_local_window(self, model, train_step_index):
for n,p in model.named_parameters():
if self.whether_prune_param(n):
if n not in self.exp_avg_ipt:
self.exp_avg_ipt[n] = torch.zeros_like(p)
self.ipt[n] = torch.zeros_like(p)
... | This function performs dynamic pruning during training by adjusting model sparsity based on a schedule. It updates input pruning thresholds, generates masks using either a threshold or a fixed mask post-pruning phase, and returns sparsity level, threshold, and mask. The process transitions from gradual threshold-based ... | def update_and_pruning(self, model, train_step_index):
if train_step_index <= self.pruning_end:
self.update_ipt_with_local_window(model, train_step_index)
sparsity, pruning_ind = self.sparsity_scheduler(train_step_index)
if pruning_ind and sparsity > 0.0:
if train_step_in... |
def sparsity_scheduler(self, train_step_index):
pruning_ind = False
if train_step_index < self.pruning_start:
sparsity = 0.0
pruning_ind = False
elif train_step_index == self.pruning_start:
sparsity = self.initial_sparsity
pruning_ind = True
... | This function performs magnitude-based pruning on a neural network model during training. It determines pruning sparsity and applies either threshold-based pruning (during gradual stages) or a fixed mask (after pruning completes). The method returns sparsity level, pruning threshold, and the resulting weight mask, enab... | def magnitude_pruning(self, model, train_step_index):
sparsity, pruning_ind = self.sparsity_scheduler(train_step_index)
if pruning_ind and sparsity > 0.0:
if train_step_index == self.pruning_end:
print ("Gradual pruning stage is over. Generate the final fixed mask...")
... |
def print_pruning_modules(self, model):
print ("List of model modules to be pruned:")
for n, p in model.named_parameters():
if self.whether_prune_param(n):
print (n)
self.n_total_param_for_pruning += p.numel()
print ("Total number of candidate paramete... | This code handles pruning during training. It generates a final fixed mask if training resumes after pruning, updates pruning parameters at each batch end, and logs sparsity/mask threshold metrics. The core task is managing dynamic pruning masks and tracking their impact on model training. | def apply(self, event, state, logger):
if event == Event.FIT_START:
self.print_pruning_modules(state.model)
# in case we resume training from a checkpoint after the gradual pruning stage, we need to generate the final fixed mask first
if (state.timestamp.batch.value > self.pr... |
def print_pruning_modules(self, model):
print ("List of model modules to be pruned:")
for n, p in model.named_parameters():
if self.whether_prune_param(n):
print (n)
self.n_total_param_for_pruning += p.numel()
print ("Total number of candidate paramete... | The code implements pruning during training by logging pruning metrics, applying prior gradients, generating masks, and tracking sparsity and parameter magnitudes. It handles events like FIT_START (initializing pruning, logging model statistics, and creating masks), AFTER_TRAIN_BATCH (applying prior gradients during pr... | def apply(self, event, state, logger):
if event == Event.FIT_START:
train_step_index = state.timestamp.batch.value
# print the list of model modules to be pruned
self.print_pruning_modules(state.model)
# log the parameter's magnitude statistics of the pre-trained ... |
def dog_detector(img_path):
prediction = ResNet50_predict_labels(img_path)
return ((prediction <= 268) & (prediction >= 151))
def breed_predictor(img_path):
'''Function that takes the file path of an image and returns the dog breed as predicted by a model.
Input: Filepath to ima... | The function `dog_predictor` classifies an image as a dog or human face using detection algorithms. If a dog is detected, it predicts the breed; if a human face is detected, it speculatively predicts a dog breed. If neither is detected, it responds with a neutral message. The output combines a descriptive response with... | def dog_predictor (img_path):
''' Function to take an image path and run it through the algorithm developed
INPUT: File path to image
OUTPUT: Classify Using Algorithm
'''
if dog_detector(img_path) == True:
response = "This looks like a dog! I think it might be a"
... |
def passnextgen(self):
self.calc_fitness()
#hyper params
numelit = 1
prob_motation = 0.6
prob_crossover = 0.4
prob_new = 0.2
nextpool = []
elit_indx = np.argpartition(self.fitnessmap, numelit)[:numelit]
for i in elit_indx: #pass the elites w/o... | This code performs iterative optimization by evolving a population over a specified number of generations. It tracks the minimum fitness value in each iteration, stopping early if the fitness falls below a threshold (0.00001). The function returns the best gene (chromosome) and its corresponding fitness value, either u... | def iterate(self, numiter):
history = []
for i in range(numiter):
self.passnextgen() #TODO no roulete well selection, currently uses uniform selection of chromosomes and operations to pass it on next gen
history.append(min(self.fitnessmap))
if (min(self.fitnessmap)) ... |
def custum():
global starting_number_cluster, starting_number_robot, total_robot
numb_aree = int(input('Inserisci il numero di Aree: '))
for a in range(numb_aree):
number_of_cluster = int(input('Inserisci il numero di cluster per Area numero ' + str(a) + ': '))
Aree.append(System.Area(a))
... | The main task of the code is to present a menu-driven system construction interface. It allows users to choose between custom, semi-random, or fully random system generation modes, or request help. Based on the selected option, it calls corresponding functions to build the system and then enters an infinite loop to sta... | def main():
uscita = 1
while uscita:
opzione_numero = input(
'inserisci 1 per opzione custom, 2 per opzione tipico semirandomico, 3 per opzione tipico randomico e 4 per aiuto: ')
if opzione_numero == '1':
print('Costruiamo il sistema, rispondi alle seguenti domande')
... |
def parse_pose(self, record, *args, **kwargs):
return get_pose(record['rotation'], record['translation'], *args, **kwargs)
def sample_augmentation(self):
H, W = self.data_aug_conf['H'], self.data_aug_conf['W']
fH, fW = self.data_aug_conf['final_dim']
resize = max(fH / H, fW / W)
... | The code processes camera data from a dataset by loading images, applying transformations (resize, crop, flip, rotate), and extracting calibration/pose information. It returns tensors for images, rotations, translations, intrinsics, extrinsics, and post-transformation parameters, essential for multi-camera sensor fusio... | def get_image_data(self, rec, cams):
imgs = []
rots = []
trans = []
intrins = []
extrins = []
post_rots = []
post_trans = []
oods = []
lidar_record = self.nusc.get('sample_data', rec['data']['LIDAR_TOP'])
egolidar = self.nusc.get('ego_pose... |
def choose_cams(self):
return self.data_aug_conf['cams']
def get_image_data(self, rec, cams):
imgs = []
rots = []
trans = []
intrins = []
extrins = []
post_rots = []
post_trans = []
oods = []
lidar_record = self.nusc.get('sample_data', rec... | The code retrieves data elements for a given index by selecting cameras, fetching image data with transformations, intrinsic/extrinsic parameters, and labels. It returns images, rotations, translations, camera matrices, post-processing transformations, and OOD status for training models. | def __getitem__(self, index):
rec = self.ixes[index]
cams = self.choose_cams()
imgs, rots, trans, intrins, extrins, post_rots, post_trans = self.get_image_data(rec, cams)
label, ood = self.get_label(rec)
return imgs, rots, trans, intrins, extrins, post_rots, post_trans, label, o... |
def fftshift(img):
'''
This function should shift the spectrum image to the center.
You should not use any kind of built in shift function. Please implement your own.
'''
row, col = img.shape
res = img.copy()
res[0:row//2, 0:col//2] = img[row//2:row, col//2:col]
res[row//2:row, col//2:c... | This code applies a low-pass filter to an image by transforming it into the frequency domain using FFT, zeroing out high-frequency components (above radius r) around the center, then converting it back to the spatial domain with inverse FFT. The result is a smoothed image with reduced high-frequency noise or edges. | def low_pass_filter(img, r=30):
'''
This function should return an image that goes through low-pass filter.
'''
row, col = img.shape
center_row, center_col = row//2, col//2
fft = fftshift(np.fft.fft2(img))
for i in range(row):
for j in range(col):
if(distance(i, j, cente... |
def fftshift(img):
'''
This function should shift the spectrum image to the center.
You should not use any kind of built in shift function. Please implement your own.
'''
row, col = img.shape
res = img.copy()
res[0:row//2, 0:col//2] = img[row//2:row, col//2:col]
res[row//2:row, col//2:c... | This code applies a high-pass filter to an image by zeroing out low-frequency components in the frequency domain. It computes the 2D Fourier transform, sets pixels within a circular radius `r` from the center to zero, and reconstructs the image using the inverse Fourier transform, preserving sharp edges and high-freque... | def high_pass_filter(img, r=20):
'''
This function should return an image that goes through high-pass filter.
'''
row, col = img.shape
center_row, center_col = row//2, col//2
fft = fftshift(np.fft.fft2(img))
for i in range(row):
for j in range(col):
if(distance(i, j, ce... |
def fftshift(img):
'''
This function should shift the spectrum image to the center.
You should not use any kind of built in shift function. Please implement your own.
'''
row, col = img.shape
res = img.copy()
res[0:row//2, 0:col//2] = img[row//2:row, col//2:col]
res[row//2:row, col//2:c... | The function denoises an image by applying a Fourier transform, zeroing out specific high-frequency regions around predefined coordinates to remove noise, then reconstructing the image using the inverse Fourier transform. | def denoise1(img):
'''
Use adequate technique(s) to denoise the image.
Hint: Use fourier transform
'''
row, col = img.shape
center_row, center_col = row//2, col//2
fft = fftshift(np.fft.fft2(img))
point_width = 3
point_center_1 = 53
point_center_2 = 81
point_rows = [center_... |
def fftshift(img):
'''
This function should shift the spectrum image to the center.
You should not use any kind of built in shift function. Please implement your own.
'''
row, col = img.shape
res = img.copy()
res[0:row//2, 0:col//2] = img[row//2:row, col//2:col]
res[row//2:row, col//2:c... | The code denoises an image using a Butterworth low-pass filter in the frequency domain. It applies the 2D Fourier transform, multiplies the frequency components by a Butterworth filter (with parameters: cutoff=28, order=2, gain=10) centered at the image's midpoint, and reconstructs the image via inverse Fourier transfo... | def denoise2(img):
'''
Use adequate technique(s) to denoise the image.
Hint: Use fourier transform
'''
row, col = img.shape
center_row, center_col = row//2, col//2
fft = fftshift(np.fft.fft2(img))
for i in range(row):
for j in range(col):
fft[i][j] = fft[i][j] * \
... |
def apply_median_filter(img, kernel_size):
"""
You should implement median filter using convolution in this function.
It takes 2 arguments,
'img' is source image, and you should perform convolution with median filter.
'kernel_size' is an int value, which determines kernel size of median filter.
... | The main task of the code is to denoise a source image by comparing the effectiveness of three filters (median, bilateral, and a custom method) using RMS error against a clean image. It selects the optimal filter, adjusts parameters (e.g., kernel size) to minimize noise, and saves the resulting denoised image to the sp... | def task1_2(src_path, clean_path, dst_path):
"""
This is main function for task 1.
It takes 3 arguments,
'src_path' is path for source image.
'clean_path' is path for clean image.
'dst_path' is path for output image, where your result image should be saved.
You should load image in 'src_pat... |
def load_data(filepath, time_range=[], coin='BTC', next_day=True, model_type='nb'):
data = pickle.load(open(filepath, 'rb'))
data.rename({'text_polarity_len': 'len'}, axis='columns', inplace=True)
if coin != '':
print('Filter by cryptocurrency coin:', coin)
data = data[data.coin == coin]
... | The code trains and evaluates machine learning models (SVM, Random Forest, XGBoost, etc.) for classification using text features from financial data. It selects specific text features (polarity, subjectivity, topics) from the dataset, preprocesses the data, tunes hyperparameters via grid/random search, and evaluates mo... | def run(model_type, tuning_mode, standardize, train_test_prop, text_features, time_range,
score_metric, save, model_name, basetable_filename, max_lag, coin_name, use_smote, next_day):
print('Training an sklearn model with sacred support.')
data = load_data(basetable_filename, time_range, coin_name, next... |
def handle_site_file(input_file):
"""
Site files are formatted as CSVs instead of plaintext, so they
warrant special treatment. Each line in a SiteFile seems to cover
a single site, so we want to restrict searching for terms to just
that line. SiteFiles often have newlines embedded in them, which
throws off the s... | The code processes an input file, extracts relevant data (trinomials, dates), parses content into records, writes results to "out.csv", and optionally displays human-readable output. It handles CSV site files, sets parameters globally, and uses command-line arguments for input and formatting. | def main():
global human_readable
global relevant_trinomials
global periodo
global input_file
global date
global SEARCH_SIZE
global site_file
input_file = str(sys.argv[1])
human_readable_input = str(sys.argv[2]).lower()
if human_readable_input == 'y' or human_readable_input == 'yes':
human_readable = True... |
def parse_hex(pattern):
resulting_pattern = ''
hex_pattern = ''
in_hex = False
for character in pattern:
if character == '|' and in_hex:
resulting_pattern += to_hex(hex_pattern)
hex_pattern = ''
in_hex = False
elif character == '|':
in_hex... | The code reads a file containing hex patterns, extracts specific substrings based on an offset and length, and analyzes their uniqueness and frequency by plotting character counts and hash frequencies. | def main():
if len(sys.argv) != 2:
executable_name = sys.argv[0]
print(f"Usage: {executable_name} FILE")
sys.exit(1)
filename = sys.argv[1]
offset = CT_LARGE_OFFSET
length = CT_LARGE_LENGTH
subpatterns = []
with open(filename) as f:
for pattern in f:
... |
def GC_DFS(d,x,max_coord,bits,gc,visited,power,q,beckett):
#if we visited all the nodes we stop recursion
if d==power:
all_codes.extend(gc)
return
#for every bit of that code
for i in range (0,min(bits-1,max_coord)+1):
#if we want to find beckett gray codes
if becket... | The code generates binary codes of specified bit-length using DFS, distinguishing cycles/paths based on node differences. It computes delta values for codes, categorizes them, and outputs results (with prefixes like 'C', 'P', 'U') based on command-line flags (-a, -c, -u, etc.). It also handles isomorphism for the -r fl... | def main(argv):
bits=0
choose=[]
#read arguments and save them in a list
for i in range(1,len(sys.argv)):
temp=sys.argv[i]
#read bits
if temp.isdigit():
bits=int(temp)
else:
choose.append(str(temp))
#if we don't have any argument -a is impl... |
def findAllLines(mydict,comb,flag):
lines={}
paralines={}
current={}
alllines={}
#unitialize all points as not used
usedpoints=[False for x in range (len(mydict))]
#calculate slop for all lines that generate from the combinations
for c in comb:
point1=c[0]
point2=c[1]... | The code processes input points from a file, generates line combinations, and applies a set cover or greedy algorithm based on command-line flags to determine optimal lines covering all points, then outputs the selected lines with their coordinates in a formatted manner. | def main(argv):
mydict={}
comb=[]
par1,par2=None,None
#read arguments
if len(sys.argv)==2:
file=sys.argv[1]
elif len(sys.argv)==3:
par1=sys.argv[1]
file=sys.argv[2]
elif len(sys.argv)==4:
file=sys.argv[3]
par1=sys.argv[1]
par2=sys.arg... |
def where_vec_array(arr, vec):
return np.where(np.isclose(arr, vec).all(axis=1))[0]
def neighbor_r(self, ind):
return self.neighbor_ind_to_ind(ind)[2]
def neighbor_ur(self, ind):
return self.neighbor_ind_to_ind(ind)[3]
def neighbor_ul(self, ind):
return self.neighbor_ind_to_ind(ind)[4] | The code initializes a lattice structure with parameters `n` (number of sites) and `id` (lattice ID), defining 2D lattice vectors, transformation matrices (utlf), and simulation torus geometry. It computes site coordinates, adjacency matrices, and node IDs, using a predefined dictionary to map lattice IDs to specific v... | def __init__(self, n, id, order="paper"):
"""
:param n: Number of sites
:param id: Lattice ID
"""
# number of sites
self.n = n
# lattice constant
self.a = 1.
# lattice vectors
self.a1 = np.array([self.a, 0]).transpose()
self.a2 ... |
def calc_adjacency_matrix(self):
"""
Calculates the adjacency matrix of the honeycomb graph
:return:
"""
for i in range(self.n):
for j in range(self.n):
if j in self.neighbor_ind_to_ind(i):
self.adjacencymatrix[i][j] = 1
... | This code plots a graph on a torus by embedding nodes and edges in 3D space, using NetworkX and Matplotlib. It calculates adjacency matrices, maps nodes to toroidal coordinates, and draws edges with styles indicating periodic connections. A torus surface is rendered, nodes are labeled, and edges are plotted as solid/da... | def plot_on_torus(self, save_fig=False, lowlight_triangles=None):
"""
Creates and draws networkx graph
:return:
"""
# if not calculated so far, calc adjacency matrix
if self.adjacencymatrix[0][0] == -1:
self.calc_adjacency_matrix()
# creat... |
def calc_adjacency_matrix(self):
"""
Calculates the adjacency matrix of the honeycomb graph
:return:
"""
for i in range(self.n):
for j in range(self.n):
if j in self.neighbor_ind_to_ind(i):
self.adjacencymatrix[i][j] = 1
... | The main task of the code is to generate and visualize a networkx graph representing a honeycomb lattice. It constructs nodes with sublattice-specific colors, adds edges with differentiated styles based on neighbor relationships, and renders the graph with labels, lattice vectors, and a legend. The plot can be saved as... | def plot(self, save_fig=False):
"""
Creates and draws networkx graph
:return:
"""
# if not calculated so far, calc adjacency matrix
if self.adjacencymatrix[0][0] == -1:
self.calc_adjacency_matrix()
# create graph
G = nx.Graph()
fig = ... |
def where_vec_array(arr, vec):
return np.where(np.isclose(arr, vec).all(axis=1))[0]
def neighbor_r(self, ind):
return self.neighbor_ind_to_ind(ind)[2]
def neighbor_ur(self, ind):
return self.neighbor_ind_to_ind(ind)[3]
def neighbor_ul(self, ind):
return self.neighbor_ind_to_ind(ind)[4] | The main task of the code is to initialize a lattice structure for a physical system, defining its geometry, coordinates, adjacency matrix, and directional connectivity. It processes lattice parameters, computes simulation torus vectors, assigns site coordinates with unique identifiers, and generates horizontal and dia... | def __init__(self, n, id, order="paper"):
"""
:param n: Number of sites
:param id: Lattice ID
"""
# number of sites
self.n = n
# lattice constant
self.a = 1.
# lattice vectors
self.a1 = np.array([self.a, 0]).transpose()
self.a2 ... |
def calc_adjacency_matrix(self):
"""
Calculates the adjacency matrix of the honeycomb graph
:return:
"""
for i in range(self.n):
for j in range(self.n):
if j in self.neighbor_ind_to_ind(i):
self.adjacencymatrix[i][j] = 1
... | The main task of the code is to visualize a graph on a torus surface by plotting nodes and edges with specific styles, considering toroidal geometry. It creates a 3D networkx graph, maps nodes to toroidal coordinates, draws edges as solid or dashed lines based on adjacency, and renders the torus with nodes and edges, s... | def plot_on_torus(self, save_fig=False, lowlight_triangles=None):
"""
Creates and draws networkx graph
:return:
"""
# if not calculated so far, calc adjacency matrix
if self.adjacencymatrix[0][0] == -1:
self.calc_adjacency_matrix()
# creat... |
def get_daft_listings(property_type, offset):
daft = Daft()
daft.set_county('Dublin')
daft.set_listing_type(property_type)
daft.set_min_price(200)
daft.set_offset(offset)
return daft.search()
def validate_listings(listings, property_information, property_type):
for listing in listings:
... | The code fetches property listings from Daft, validates them, collects data across multiple pages by incrementing an offset, removes duplicates, and writes the final data to a file specific to the input property type. | def get_property_information(property_type):
property_information = []
pages = True
offset = 0
while pages:
listings = get_daft_listings(property_type, offset)
if not listings:
pages = False
property_information = validate_listings(listings, property_information, pro... |
def get_pieces_for_player(self, color):
'''Method to get the pieces for provided player'''
if color == 'Red':
return self._red_pieces_on_board
return self._black_pieces_on_board
def get_piece_from_coordinates(self, coordinate):
'''Get the proper coordinate on board.'''
... | The main task of the code is to determine if the game is over by checking for checkmate. It simulates each possible move of the opposing player's pieces, temporarily moves them on the board, and checks if the current player's king is in check. If all moves result in check, the function returns True (game over/checkmate... | def _game_over(self):
'''Determine if game is over'''
# get opposing players pieces on the board
if self._player_turn == "Red":
pieces = self.get_pieces_for_player('Black')
player_to_check = 'black'
else:
pieces = self.get_pieces_for_player('Red')
... |
def get_game_state(self):
'''Public method will return the state of the game which will be either:
UNFINISHED, RED_WON or BLACK_WON
'''
return self._game_state
def get_piece_from_coordinates(self, coordinate):
'''Get the proper coordinate on board.'''
# variable for r... | This function attempts to move a piece on a Xiangqi board if valid, checking game state, position bounds, player ownership, and move legality. It updates the board, removes captured pieces, checks for game over conditions, and toggles turns if the move is successful, returning True for valid moves and False otherwise. | def make_move(self, current_position, new_position):
'''Move the piece on the board if possible.'''
# game already won, return False
if self.get_game_state() != 'UNFINISHED':
print('Game over', self._game_state)
return False
# if current or new position is out o... |
def isVertical(pos):
if maze(pos) == "|":
return True
return False
def isSW(pos):
if maze(pos) == '7':
return True
return False
def isSE(pos):
if maze(pos) == 'F':
return True
return False
def isHorizontal(pos):
if maze(pos) == '-':
return True
... | The function `possibleNext(m)` generates valid next positions in a maze by checking up, left, right, and down movements from the current position. It ensures moves stay within bounds and applies directional validity checks (e.g., `isVertical`, `isHorizontal`) to determine if a new position is allowed. Valid moves are a... | def possibleNext(m):
pos = m.pos
dist = m.distance
# try possible next positions
nextList = []
# try up (so long as we're not in the 0 row)
if pos.y != 0:
newpos = posClass(pos.x, pos.y - 1)
if (isVertical(newpos) or isSW(newpos) or isSE(newpos)):
m = mazeClass(newpos, dist + 1)
nextLi... |
def propDensity(self):
"""
Returns
-------
A vector proposition for the MH update
"""
if self.dicMixt is None:
return stats.norm.rvs(size=self.chain.dim, scale=0.1) # for the first proposals
else:
return self.mixtureRandom(self.dicMixt)
d... | This code performs adaptive MCMC sampling with two phases: 1) Initial random-walk phase generating proposals using varying covariance matrices, and 2) Independence phase using a proposal mixture. It updates the chain state based on log-posterior comparisons, tracks covariance for adaptation, and accumulates evidence. T... | def step(self, n):
d = self.chain.dim
if n <= self.m1: # first phase of the adaptation: Random-walk
if self.nacc < 2 * self.chain.dim:
z = self.propDensity()
self.prop.arr[0] = self.chain.arr[n-1]+z
else:
z = stats.norm.rvs(size=d)... |
def optimal_weights(n_points, er, cov, max_weight = 1.0):
"""
Return a list of weights to run the optimizier on to minimize the volatility
:param n_points: int the number of points desired to simulate
:param er: np.array expected returns of each asset
:param cov: pd.DataFrame covariance matrix of ... | The function `plot_efficient_frontier` generates and visualizes the efficient frontier for multi-asset portfolios. It calculates optimal portfolio weights, computes corresponding returns and volatilities, and plots them as a line graph (volatility vs. returns). If enabled, it adds the Capital Market Line (CML), represe... | def plot_efficient_frontier(n_points, er, cov, rf = 0.03, max_weight = 1.0, style = ".-", show_cml = True):
"""
Plots the multi-asset efficient frontier
:param n_points: int the number of points desired to simulate
:param er: np.array expected returns of each asset
:param cov: pd.DataFrame covaria... |
def sse(actual, predicted):
return (residuals(actual, predicted) **2).sum()
def ess(actual, predicted):
return ((predicted - actual.mean()) ** 2).sum()
def tss(actual):
return ((actual - actual.mean()) ** 2).sum()
def mse(actual, predicted):
n = actual.shape[0]
return sse(actual, predicted) / n
def ... | This function calculates and returns key regression error metrics—SSE, ESS, TSS, MSE, and RMSE—using actual and predicted values. It aggregates these metrics into a pandas Series for easy analysis, providing insights into model performance by quantifying prediction accuracy and variance explanation. | def regression_errors(actual, predicted):
return pd.Series({
'sse': sse(actual, predicted),
'ess': ess(actual, predicted),
'tss': tss(actual),
'mse': mse(actual, predicted),
'rmse': rmse(actual, predicted),
}) |
def sse(actual, predicted):
return (residuals(actual, predicted) **2).sum()
def mse(actual, predicted):
n = actual.shape[0]
return sse(actual, predicted) / n
def rmse(actual, predicted):
return math.sqrt(mse(actual, predicted)) | The code calculates the sum of squared errors (SSE), mean squared error (MSE), and root mean squared error (RMSE) between the input `actual` values and their mean, serving as a baseline model evaluation metric. It returns these three error measures in a dictionary to assess prediction accuracy when using the mean as a ... | def baseline_mean_errors(actual):
predicted = actual.mean()
return {
'sse': sse(actual, predicted),
'mse': mse(actual, predicted),
'rmse': rmse(actual, predicted),
} |
def __get_soup(url):
res = requests.get(url)
soup = BeautifulSoup(res.content,'html.parser')
return soup
def __get_hrefs(soup):
href_links = []
for link in soup.find_all('a'):
if ("simpsonit" in link.get('href')):
href_links.append(__TELKKU_URL + link.get('href'))
return href... | The code scrapes a webpage to extract links, gathers associated information, and returns a structured matrix containing time and description data for each set. | def get_info():
'''returns a matrix of matrix[set][time = 0, description = 1]'''
soup = __get_soup(__TELKKU_URL)
href_links = __get_hrefs(soup)
info = __get_info_all(href_links)
return __formatted_info(info) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.