dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def free_for_transit(self, square):
if square.square_coordinates == square.SERVER_PORTS[self.game_player_index][0] or square.square_coordinates == \
square.SERVER_PORTS[self.game_player_index][1]:
return False
if square.player_card is None:
return True
r... | This function handles a card's movement on a board game, validating directions, checking for blocked paths, and executing moves or escapes. It raises errors for invalid operations like double-moving non-line-boosted cards, checks direction validity, updates the board state, and returns status codes indicating move succ... | def card_move(self, card_name, direction1, direction2=None):
if direction2 is not None and self.line_boosted != self.my_cards[card_name]:
raise RuntimeError("You can't move twice a non line boosted card")
parity = pow(-1, self.game_player_index)
moving_card = self.my_cards[card_name]... |
def _create_cells(self) -> None:
self._cells = [
[Cell(self._window) for _ in range(self._num_rows)]
for _ in range(self._num_cols)
]
for column_index, column in enumerate(self._cells):
for row_index, cell in enumerate(column):
self._draw_cell(... | This code initializes a maze structure by setting up grid parameters, creating cells, breaking walls to form paths, and establishing entrance/exit points for maze navigation. | def __init__(
self,
x1: int,
y1: int,
num_rows: int,
num_cols: int,
cell_size_x: int,
cell_size_y: int,
window: Window,
) -> None:
self._cells = []
self._x1 = x1
self._y1 = y1
self._num_rows = num_rows
self._num_... |
def _flatten_list(self, messages: list) -> list:
"""
Recursively flattens a list down to a list of strings
:param messages: list
:return: list
"""
flat_messages = []
for message in messages:
if isinstance(message, list):
self._flatten_l... | The main task of the code is to handle message processing by validating, filtering, and sending payloads. It converts input messages into a list, flattens nested structures, applies filters, sets color defaults, constructs payloads, sends requests, and handles errors/warnings. It returns the response or an error messag... | def message(self, title: str, messages: list | str, color=None) -> requests.models.Response | str:
"""
Main handling function that is responsible for building, validating, and sending the payloads.
:param title: str
:param messages: str | list
:param color: None
:return: ... |
def _local_only(path_info: types_.PathInfo) -> types_.CreateAction:
"""Return a create action based on information about a local documentation file.
Args:
path_info: Information about the local documentation file.
Returns:
A page create action.
"""
return types_.CreateAction(
... | The function determines the appropriate action for a documentation page by checking the presence of `path_info` (local file) and `table_row` (navigation table entry). If both are absent, it raises an error. If only one exists, it returns a local-only or server-only action. If both exist, it computes a combined action. ... | def _calculate_action(
path_info: types_.PathInfo | None,
table_row: types_.TableRow | None,
clients: Clients,
base_path: Path,
) -> tuple[types_.AnyAction, ...]:
"""Calculate the required action for a page.
Args:
path_info: Information about the local documentation file.
table_... |
def encoder(inputs):
"""
This function defines the encoder or downsampling path.
Args:
inputs (tensor) -- batch of input images
Returns:
p4 - the output maxpooled features of the last encoder block
(f1, f2, f3, f4) - the output features of all the encoder blocks
"""
f1, p1 = encoder_block(inpu... | The code defines a UNet model by integrating an encoder, bottleneck, and decoder. It processes input images through the encoder to extract features, passes them through a bottleneck for deeper abstraction, then decodes them with skip connections using encoder outputs. The model is compiled with specified output channel... | def unet():
"""
Defines the UNet by connecting the encoder, bottleneck and decoder.
"""
# specify the input shape
inputs = tf.keras.layers.Input(shape=(H, W, 3))
# feed the inputs to the encoder
encoder_output, convs = encoder(inputs)
# feed the encoder output to the bottleneck
bottle_neck = bottle... |
def encoder(inputs):
"""
This function defines the encoder or downsampling path.
Args:
inputs (tensor) -- batch of input images
Returns:
p4 - the output maxpooled features of the last encoder block
(f1, f2, f3, f4) - the output features of all the encoder blocks
"""
f1, p1 = encoder_block(inpu... | The code defines a UNet model by integrating an encoder, bottleneck, and decoder. It initializes input layers, processes features through the encoder to obtain intermediate convolutions, passes the encoder's output to a bottleneck for deeper feature extraction, then combines the bottleneck output with encoder features ... | def unet():
"""
Defines the UNet by connecting the encoder, bottleneck and decoder.
"""
# specify the input shape
inputs = tf.keras.layers.Input(shape=(H, W, 3))
# feed the inputs to the encoder
encoder_output, convs = encoder(inputs)
# feed the encoder output to the bottleneck
bottle_neck = bottle... |
def move_to_pose_def(self, target_position, interpolation_duration=2, extra_duration=1, interpolation_method="linear"):
"""Move the whole trajectory to intend poses
Args:
target_position (numpy.ndarray): a (12,) or (12,1) ndarray represent that target pose of the 12 joints.
int... | The code replays a trajectory by moving a robot through a sequence of joint poses. It validates input shape (n×12), moves to the initial pose, iterates through subsequent poses with interpolation (adjustable speed/frequency), and maintains the final pose via UDP commands. If `maintain_last_pose` is False, it ends with ... | def trajectory_replay(self, trajectories, speed = None, replay_frequency = 100, maintain_last_pose = True):
"""Replay the trajectory
Args:
trajectories (numpy.ndarray): The trajectory to replay.
speed (numpy.ndarray, optional): The speed of the joint, must have the same shape as... |
def initialize(self):
''' Creates `self.number_of_initial_trees` trees and chooses best of them to be `self.current_best`.
return: None
'''
potential_trees = [self.create_initial_tree() for _ in range(self.number_of_initial_trees)]
temp_tree = potential_trees[0]
temp_fi... | The code implements a simulated annealing algorithm to optimize a tree structure. It iteratively generates similar solutions, evaluates their fitness, and updates the best solution if the new one is better or accepted probabilistically based on iteration count. The process continues until a termination condition is met... | def simulated_annealing(self):
''' Main function.
return: tuple (int, int, int) containing best tree and its fitness
'''
self.initialize()
while not self.condition():
current_similar = self.find_new_similar()
fitness_similar = self.fitness(current_simila... |
def log(self, message, verbose=True):
if verbose:
print(message)
def findJVM(self, jdkLocation='', verbose=False):
jdk = jdkLocation
if jdk == '':
jdk = self.findJDK(verbose=verbose)
if jdk == '':
return ''
self.log('JDK found at ' + jdk, verbo... | The main task of the code is to initialize a Java Virtual Machine (JVM) using the JPype library by determining the correct JVM path based on provided settings or automatic detection. It checks for a specified JDK path, verifies Java environment variables, and starts the JVM with the given classpath. The function logs d... | def startJVM(self, path, jdk='', verbose=False):
if jdk != '':
self.log('Provided path to jdk: ' + jdk, verbose)
jvmPath = self.findJVM(jdkLocation=jdk, verbose=verbose)
elif self.isJavaSet() and self.isJavaHomeSet(verbose=verbose):
jvmPath = ''
else:
... |
def transcribe(model, title):
file = input_path + model + title
print("tarnscribing: " + file)
type = model.split("_")[0]
command = 'python /home/meong/saber-project/saber/skripsi/transcribe/' + type + '_transcribe.py --model_dir="' + \
model_path + model + '" ' + file
os.system(com... | The main task of the code is to process audio files by transcribing them, zipping the results, sending email notifications, and cleaning up temporary files. It iterates through directories in `input_path`, handles each file with `transcribe`, `zip_file`, `send_email`, and `cleanup` functions, logging timestamps and sta... | def main():
models = os.listdir(input_path)
for model in models:
inputs = os.listdir(input_path + model)
model = model + "/"
for file in inputs:
print(datetime.datetime.utcnow().strftime("%c"))
print("Start transcribing....")
print("WE ARE ON DIR: " + ... |
def __selection(self):
print(f"\t▶ Generating Parents Population using {self.selection_method} Method\n")
population_after_selection = []
# ==========================================================================
# ROULETTE WHEEL
if self.parents <= self.genes_population_after_fitness.shape[0]: # ... | This code executes a genetic algorithm over multiple generations to optimize a population of chromosomes. It evaluates fitness, tracks valid solutions, applies selection, crossover, mutation, and replacement operators, and stores results for analysis, aiming to find optimal solutions with minimal colors in a constraine... | def run(self):
for g in range(self.generations):
print("\n≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣≣\n")
print(f"🧬 Generation --- {g+1}")
fitness_scores, self.genes_population_after_fitness = self.population.fitness_scores()
self.best_fitness_scor... |
def command(self, wblk, rdlen = None):
w = self.write(crc_blk(wblk))
if w != len(wblk)+2:
self.err = 100
return None
if rdlen == None:
rdlen = self.MAX_RESPONSE_SIZE
chklen = self.MIN_RESPONSE_SIZE
else:
chklen = rdlen
self.wcnt = 0
rblk = self.read(rdlen)
if rblk == None or len(rblk) < chk... | This function retrieves and parses version/config data from a PGM board via a command, extracts chip ID and version info, identifies the chip type (e.g., TLSR8266), calculates SWire bit rate, and prints diagnostic details like chip ID, version, power status, and communication parameters. It returns True on success or F... | def GetVersion(self):
data = self.command(struct.pack('<BBH', self.CMD_FUNCS, self.CMDF_GET_VERSION, 0), 19)
if data == None:
print('\rError[%d] Read PGM Version and Config!' % self.err)
return False
self.pgm_version = [data[5], data[4]]
(self.pgm_cid, self.pgm_pwr, self.pgm_swdiv, self.pgm_swaddrlen) = s... |
def EnableClkALGM(self):
rdsize = 4
offset = 0x61
data = self.command(struct.pack('<BBHH', self.CMD_SWIRE_READ, offset & 0xff, (offset>>8) & 0xffff, rdsize), rdsize+6)
if data == None or self.wcnt != rdsize:
print('Error Read SWire data! (%d)' % self.err)
return False
x = bytearray(data[4:8])
# TLSR8... | This function reads and dumps analog registers from a chip via SWIRE interface. It configures read size, sends a read command, verifies data integrity, then prints the register data in hexadecimal format. The task involves enabling clock, handling size parameters, executing read operations, and outputting results for d... | def DumpChipARegs(self, offset = 0x0, rdsize = None):
if not self.EnableClkALGM():
return False
if rdsize == None:
if self.pgm_swaddrlen == 3:
rdsize = 0x100
else:
rdsize = 0x80
data = self.command(struct.pack('<BBHH', self.CMD_SWIRE_AREAD, offset & 0xff, (offset>>8) & 0xffff, rdsize), rdsize+6)
... |
def get_opts(argv):
args = get_args(argv)
places_file = None
if args.places_file:
places_file = Path(args.places_file)
else:
if args.profile:
p = Path(args.profile)
else:
windows_appdata = os.getenv("APPDATA")
if windows_appdata:
... | The code processes bookmarks from a database or SQLite file, converting them into HTML format or a new database. It reads input from `in_db` or `places_file`, extracts bookmarks, and writes output to specified files. Conditional logic handles database operations, HTML generation, and date-based sorting, returning 0 on ... | def main(argv):
print(f"\n{app_title}\n")
opts = get_opts(argv)
ok = True
if opts.in_db:
print(f"Reading {opts.in_db}")
con = sqlite3.connect(str(opts.in_db))
n_hosts, bookmarks = get_bookmarks_from_db(con)
write_bookmarks_html(str(opts.output_file), bookmarks)
... |
def _get_max_estimation(estimations: List[Union[list, np.ndarray]],
max_: (int, float) = None,
min_: (int, float) = None) -> np.ndarray:
estimations = deepcopy(estimations)
estimations = list(map(lambda est_: np.array(est_) if isinstance(est_, list) else est_, est... | This function stabilizes timestamps by merging maximum and minimum estimates derived from input timestamps. It calculates max (mx) and min (mn) estimates using helper functions, then combines them with the original timestamps via either an averaging method (_avg_merge_min_max) or a direct merge (_merge_max_min_estimati... | def _stabilize_more_timestamps(timestamps: List[Union[list, np.ndarray]],
max_: (int, float) = None, min_: (int, float) = None, average=True) -> np.ndarray:
mx = _get_max_estimation(timestamps, max_=max_, min_=min_)
mn = _get_min_estimation(timestamps, max_=max_, min_=min_)
if... |
def add_items():
amount = int(scoops_litres_amount.get()) # Amount of scoops / litres
role = user_role.get() # Users role
items[role][scoop_litre.get()]['amount'] += amount # Add the amount to the scoops / litres
# If the user could buy a cone or cup
if cone_cup.get() and user_role.get() == "... | The function navigates through a dictionary of questions based on user role and current index. It retrieves question data, checks if the user is a business to process a receipt, or advances to the next question. If reaching the end of a question set, it locates the next role-specific key or resets indices, ensuring the... | def make_dictionary_route():
global function_importance_num
global question_num
# Get the key of all the questions
function_importance_names = list(function_information)
function_importance_name = function_importance_names[function_importance_num]
# Get the key with all the information for the... |
def add_items():
amount = int(scoops_litres_amount.get()) # Amount of scoops / litres
role = user_role.get() # Users role
items[role][scoop_litre.get()]['amount'] += amount # Add the amount to the scoops / litres
# If the user could buy a cone or cup
if cone_cup.get() and user_role.get() == "... | The main task of the code is to validate whether the user wants to add more items to the receipt. If 'yes', it resets values and re-asks questions; if 'no', it displays the receipt. The function orchestrates adding items, conditional logic for further input, and receipt generation. | def validate_ask_receipt():
add_items() # Add the items to the receipt
if buy_more.get() == "yes":
item_values() # Reset the values
make_dictionary_route() # Ask the same questions again
else:
show_receipt() |
def end_game(self, winner: str):
print(f" Thank you for the game! \n {winner} won!")
f = open("ReadMe.txt", "a")
f.write("\nEND OF GAME\n")
f.close()
exit()
def analyze_game(self):
if self.search_method == "MM":
return self.mm_output(False)
elif self.s... | The main task of the code is to handle a player's turn in a turn-based game by validating input coordinates, updating the game board with the player's mark, checking for terminal states (win/draw), and recursively prompting for valid moves if necessary. It also triggers the AI's move, updates the game state, and repeat... | def next_turn(self):
# The player's turn
player_move = input("Your turn, enter the coordinates in the format row/column").split("/")
# Prevent attempting to input illegal argument from outside of the appropriate limit numbers
if len(player_move) != 2:
print("Not a valid move.... |
def is_valid(self, q):
for key in q:
if key not in self.VALID_KEYS:
return False
return True
def process_filters(self, q):
filters = q.get('filter', {})
queryset = None
for k, v in filters.items():
if not queryset:
queryset ... | The code processes a query by applying filters and grouping to a dataset, returning total item counts and grouped statistics. It validates the input, filters the queryset, counts total items, and if a 'groupedBy' parameter is provided, generates grouped results. The output is a dictionary with total counts and group-sp... | def query(self, q):
"""
1. Apply filters to queryset
2. Apply groupby to queryset
:param q: query as a dict
:return: {totolCounts: <int>, groups: {<str>: <int>}}
"""
if not self.is_valid(q):
raise Exception('Invalid Query')
result = {'totalCoun... |
def search_for_sets():
"""
Helps users query sets.
Presents several options for searching for sets.
"""
print("\n-----------------------------------------------------\n")
print("Which of the following questions can I help you with?\n")
print(" [a] - I have a maximum price in mind. What can... | The code defines a function `show_options()` that presents a menu for LEGO store customers, offering options to search products, make purchases, request out-of-stock items, or write reviews. It loops until the user selects 'q' to exit, directing inputs to corresponding functions like `search_for_sets()` or `quit_ui()`.... | def show_options():
"""
Helps customers navigate the store. They can:
1. Search for sets
2. Purchase an item
3. Make a request
4. Write a review.
"""
print("\n-----------------------------------------------------\n")
print("HELLO AND WELCOME TO THE LEGO STORE! :)")
... |
def prior_sde(self,dimensions):
return tf.random.normal(dimensions,dtype=tf.float32)
def get_logsnr_alpha_sigma(self,time):
logsnr = self.logsnr_schedule_cosine(time)
alpha = tf.sqrt(tf.math.sigmoid(logsnr))
sigma = tf.sqrt(tf.math.sigmoid(-logsnr))
return tf.re... | The code implements a **Predictor-Corrector sampling method** for generating samples from score-based models. It iteratively refines samples by computing the score (gradient of the log-density) using a neural network model, applying second-order corrections to improve stability, and updating the sample distribution ove... | def DDPMSampler(self,
cond,
model,
data_shape=None,
const_shape=None,
jet=None,mask=None,
clip=False,second_order=True):
"""Generate samples from score-based models with Predictor-Corrector me... |
def _window_style(self):
self._window.title("Bank of OOP")
self._window.geometry('700x500')
window_style = ttk.Style(self._window)
window_style.theme_use('aqua')
self._window.grid_rowconfigure(2, weight=1)
self._window.grid_columnconfigure(0, uniform="half", weight=... | This code initializes a GUI application for managing a bank system. It loads or creates a Bank object from a database, sets up a Tkinter window with themed frames for account management, transaction listing, and summaries, and initializes components like TransactionGrid. The GUI includes exception handling, layout conf... | def __init__(self):
self._session = Session()
#get bank from db
self._bank = self._session.query(Bank).first()
#if bank does not exist then initialize and save a new bank
if self._bank:
logging.debug("Loaded from bank.db")
else:
self... |
def togglePlayer(self):
if self.whoseTurn == 2:
self.whoseTurn = 1
else:
self.whoseTurn = 2
def makeMove(self, m1, m2):
p1 = self.board[m1[0]][m1[1]]
p2 = self.board[m2[0]][m2[1]]
# Check for players existence
if not self.isPlayer(p1):
... | The code generates all valid successor game states for the current player's turn by iterating through the board, identifying movable pieces (pawns for player 1, Dragon/Queen for others), calculating possible moves, filtering out invalid states, and appending deepcopies of valid states to the successor list. | def successors(self):
successor = []
player = self.whoseTurn
self.togglePlayer()
if player == 1:
for i in range(self.y):
for j in range(self.x):
if isinstance(self.board[j][i], token):
if self.board[j][i].isPawn():... |
def nextAvailableMoves(self, m):
x1 = m[0]
y1 = m[1]
# 1 Free Movement
if 0 < x1 < 4 and 0 < y1 < 4:
return {(x1, y1 - 1), (x1 - 1, y1), (x1 + 1, y1), (x1, y1 + 1),
(x1 - 1, y1 - 1), (x1 - 1, y1 + 1), (x1 + 1, y1 - 1), (x1 + 1, y1 + 1)}
# 2 Can't G... | The code determines legal moves for a chess piece based on its type (Queen/Dragon/Pawn). It filters available moves to ensure they stay within the 5x5 board bounds, checks if target squares are empty or contain enemy tokens, and applies specific movement rules (e.g., diagonal captures for Pawns, Queen/Dragon's range). ... | def nextLegalMoves(self, m1):
moves = self.nextAvailableMoves(m1)
thing = self.board[m1[0]][m1[1]]
nextMove = []
if isQueen(thing) or isDragon(thing):
for i in moves:
if 5 > i[0] >= 0 and 5 > i[1] >= 0:
gs = self.board[i[0]][i[1]]
... |
def isToken(thing):
return isinstance(thing, token)
def isEnemy(thing, foe):
if isPawn(thing) and (isDragon(foe) or isQueen(foe)):
return True
elif isPawn(foe) and (isDragon(thing) or isQueen(thing)):
return True
else:
return False
def isPawn(thing):
if isToken(thing):
... | The code handles piece movement on a board, validating pawn, queen, and dragon moves. It checks if moves are straight/diagonal, verifies target status (enemy, friendly, blank), updates the board state, and captures enemies while adjusting scores for queen captures. | def makeMove(self, m1, m2):
x1 = m1[0]
y1 = m1[1]
x2 = m2[0]
y2 = m2[1]
p1 = self.board[x1][y1]
p2 = self.board[x2][y2]
enemy = -1
# Check for players existence
if not isToken(p1):
return False
else:
if isEnemy(p1... |
def H1(self):
numAlive = 0
positions = list()
for i in range(len(self.game.getBoard())):
for j in range(len(self.game.getBoard())):
if isPawn(self.game.getBoard()[i][j]):
if self.game.getBoard()[i][j].alive:
numAlive += 1
... | The main task of the code is to calculate the total Manhattan distance between all alive entities' positions and the queen's position. It retrieves alive entities' positions via `H1()` and the queen's position via `H3()`, then sums the Manhattan distances between each entity and the queen, returning the aggregated resu... | def H4(self):
totalDistance = 0
numAlive,positions = self.H1()
qAlive,queenPosition = self.H3()
for i in range(len(positions)):
totalDistance = totalDistance + self.manhattan_distance(positions[i],queenPosition)
return totalDistance |
def isPawn(thing):
if isToken(thing):
return thing.type == 'pawn'
else:
return False
def nextLegalMoves(self, m1):
moves = self.nextAvailableMoves(m1)
thing = self.board[m1[0]][m1[1]]
nextMove = []
if isQueen(thing) or isDragon(thing):
for i in moves:... | The main task of the code is to generate all valid successor game states by iterating through each piece on the board, applying legal moves for the current player (pawns for player 1, dragons/queens for others), creating new game instances for each move, and filtering out invalid moves (False or empty lists) with error... | def successors(self):
successor = []
player = self.whoseTurn
# self.togglePlayer()
if player == 1:
for i in range(self.y):
for j in range(self.x):
if isPawn(self.board[j][i]):
m1 = (j, i)
for... |
def H1(self):
numAlive = 0
positions = list()
for i in range(len(self.game.getBoard())):
for j in range(len(self.game.getBoard())):
if isPawn(self.game.getBoard()[i][j]):
if self.game.getBoard()[i][j].alive:
numAlive += 1
... | This code calculates a heuristic evaluation for a game state by combining weighted values from four helper functions (H1-H4). It multiplies each factor's weight by its corresponding status (e.g., pawn count, dragon count, queen presence, pawn-queen distance), sums them, then triples the result to produce a strategic sc... | def heuristic(self):
pawnsAlive, pawnPositions = self.H1()
dragonsAlive, dragonPositions = self.H2()
qAlive, qPosition = self.H3()
distanceP2Q = self.H4()
eval_functions = [(-10, pawnsAlive), (15, dragonsAlive), (20, qAlive), (-1, distanceP2Q)]
return sum(x[0] * x[1] fo... |
def cluster_to_target(samples):
clusters = [[], [], []]
for pt in samples:
dists = [dist2(pt, m) for m in MEANS]
clusters[np.argmin(dists)].append(pt)
return clusters
def plot_set(samples, rows, cols, iteration, clusters=True):
plt.subplot(rows, cols, iteration + 3)
plt.xlim(-1, 9)
... | The function `test_one` evaluates a sampling algorithm's performance by iteratively applying a sampling function to initial points, visualizing intermediate results, and computing metrics. It initializes points, runs the sampler for `num_steps`, plots ground truth and sampled points, measures execution time, and return... | def test_one(init_pts, gt_pts, sampling_fn, num_steps=18, name="", clusters=True, plot=True):
cols = 5
rows = int(np.ceil(float(num_steps + 2)) / cols)
samples = init_pts[:]
if plot:
plt.figure()
plt.suptitle(name)
# Ground truth.
plt.subplot(rows, cols, 1)
plt... |
def get_compilation_cmd(src_file):
"""
Returns an object with the compilation database object for the given
source file. See the compilation database spec for more information.
"""
paths = glob.glob(build_dir + "/**/compile_commands.json", recursive=True)
for db in paths:
print("Searchin... | The main task of the code is to instrument a source file by inserting faults through macro replacements. It compiles the file, parses its AST, identifies nodes to replace, reverses their order, and injects faults using a TextReplacer, logging progress and replacement status. The process ensures fault injection for test... | def instrument_file(src_file):
"""
Instruments the given file with faults.
"""
src_file = os.path.realpath(src_file)
print(" * Finding compilation args...")
info = get_compilation_cmd(src_file)
print(" * Parsing AST...")
ast = get_ast(info)
if verbose:
print(json.dumps(ast, ... |
def loadData():
list_box.delete(0, END)
for booking in BookingController.get()['booking']:
list_box.insert(int(booking['id']), booking['id']
+ '.field: ' + str(FieldController.read(booking['field_id'])['name'])
+ '.schedule: ' + str(Sch... | The code creates a GUI for a payment system allowing users to select members, view their bookings, and process payments. It loads member data, filters active bookings, calculates payment totals, and updates booking statuses to 'done' upon confirmation. Global variables track selections, and controllers handle data retr... | def paymentView():
global selectedMemberItem
global selectedItem
loadedBooking = []
if isLogin:
view = Toplevel()
view.title('System')
member_list_box = Listbox(view, width=80)
member_list_box.grid(row=1, columnspan=2)
for data in MemberController.get()['member']:... |
def checkAvailableSession():
if selectedScheduleItem == 0 and selectedFieldItem == 0:
toast('Please select item first')
else:
taken_session = []
session_list_box.delete(0, END)
for b in BookingController.get()['booking']:
if b['schedule_id'... | The code creates a UI for booking sessions by allowing users to select a schedule, field, session, and member. It checks for available sessions based on selections, books the chosen session with the selected member, and updates the booking system. Global variables track selections, and functions handle session availabi... | def bookingView():
global selectedScheduleItem
global selectedFieldItem
global selectedSessionItem
global selectedMemberItem
if isLogin:
view = Toplevel()
view.title('System')
schedule_list_box = Listbox(view)
schedule_list_box.grid(row=1, column=1)
for data i... |
def getExplodingIndex(s):
numberOfLeftBrackets = 0
for i, char in enumerate(s):
if char == '[':
numberOfLeftBrackets += 1
if numberOfLeftBrackets == 5:
# due to previous explotions we now its here a digit
if not isdigit(s[i+1]):
... | The main task of the code is to add two numbers in a specific format by concatenating them with brackets and commas, then repeatedly reduce the result by performing explosions and splits in priority order until no further reductions are possible. The function returns the fully reduced number after processing all requir... | def fishAdd(lNumber, rNumber):
lNumber.insert(0, "[")
lNumber.append(",")
for char in rNumber:
lNumber.append(char)
lNumber.append("]")
# Prio list is
# 1. Do explotion (can generate splits)
# 2. Do splits (can generate explotions, so do explotion first before a possible second ... |
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)
def check_winner(board, player):
for row in board:
if all(cell == player for cell in row):
return True
for col in range(3):
if all(board[row][col] == player for row in range(3)):
... | The code simulates a Tic Tac Toe game where a player ('O') and an AI ('X') take turns. It randomly selects player moves, checks for wins/draws, and resets the board upon game endings. The AI's moves are recorded in a dictionary (`good`) and saved to a file for training purposes. The loop runs up to 10,000 iterations, t... | def play_game():
count = 10000
board = [[" " for _ in range(3)] for _ in range(3)]
print("Let's play Tic Tac Toe! You are 'O'.")
print_board(board)
while count:
count-=1
player_row, player_col = random.randint(0,2),random.randint(0,2)
while(board[playe... |
def get_initial_centroids(first_point, k, dataset):
"""
Given the index of the first centroid, return a set of
k indices of the initial centroids.
Parameters:
first_point: int, index of the first centroid
k: int, number of centroids
dataset: list[ndarray], a list of vectors
... | This function performs k-means clustering on a dataset using Spark, calculates the diameter of each cluster, and returns the average diameter across all clusters. It initializes centroids, assigns data points to clusters, computes cluster diameters in parallel, sums them, and divides by the number of clusters to obtain... | def get_average_diameter(k_value, dataset):
"""
Perform clustering on dataset using given k_value
and return the average diameter of the clusters.
Parameters:
k_value: int, number of clusters
dataset: list[ndarray], a list of vectors
Returns:
average_diameter: float, t... |
def cv2tk(image):
img = cvtColor(image, COLOR_BGR2RGB)
img = Image.fromarray(img)
return ImageTk.PhotoImage(img)
def Edge(image):
edges = Canny(image, 50, 150, apertureSize=3)
return medianBlur(edges,3)
def line_detection(image,alternative=140):
return HoughLines(image, 1, np.pi/180, line_thresh... | The code uploads an image, performs edge detection, detects lines, displays the original and processed images with detected lines, and provides interactive buttons to adjust line detection parameters. It also creates a dataframe and table for further processing. | def upload_image(self):
file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.png;*.jpg;*.jpeg;*.gif")])
if file_path:
self.image = imread(file_path)
img = cv2tk(self.image)
self.image_label.config(image=img)
self.image_label.image = img
... |
def get_len_index_tensor(self, ind_x):
"""Calculate the lengths ((B, 32), torch.LongTensor) of pgrid."""
with torch.no_grad():
lengths = self.max_simu_note - \
(ind_x[:, :, :, 0] - self.pitch_pad == 0).sum(dim=-1)
return lengths
def index_tensor_to_multihot_tens... | This function performs a forward pass through a neural network, encoding input data into latent variables and decoding them into pitch and duration outputs. It uses teacher forcing during training, sampling latent variables for stochasticity, and handles both training and inference modes. The encoder processes input te... | def forward(self, x, inference=False, sample=True,
teacher_forcing_ratio1=0.5, teacher_forcing_ratio2=0.5):
lengths = self.get_len_index_tensor(x)
x = self.index_tensor_to_multihot_tensor(x)
dist, embedded_x = self.encoder(x, lengths)
if sample:
z = dist.rsamp... |
def game_explanation():
print("The following is the structure of board:")
print_numpad()
def choose_user():
global player1, player2, current_player
player1 = input("Choose user. X or O ?").upper()
while(player1 not in ["X","O"]):
print("Selected user is invalid. Should be X or O")
pl... | The code initializes a game by explaining rules and selecting a user, then enters a loop that continues while the game is active. It repeatedly displays the current player's turn. Once the game ends, it declares the current player as the winner. | def start_game():
game_explanation()
choose_user()
while game_on():
print(f"Current player is {current_player}")
print(f"Winner is {current_player}") |
def fspecial(fltr, ws, **kwargs):
if fltr == Filter.UNIFORM:
return np.ones((ws, ws)) / ws**2
elif fltr == Filter.GAUSSIAN:
x, y = np.mgrid[-ws // 2 + 1:ws // 2 + 1, -ws // 2 + 1:ws // 2 + 1]
g = np.exp(-((x**2 + y**2) / (2.0 * kwargs['sigma']**2)))
g[g < np.finfo(g.dtype).eps * ... | The function calculates the **average Structural Similarity Index (SSIM)** between two images (`gt` and `im`) to assess their structural similarity. It computes local statistics (means, variances, and covariances) using a sliding window, applies the SSIM formula with constants `C1` and `C2` to stabilize division, and r... | def SSIM(gt, im, ws=11, C1=0.01, C2=0.03, MAX=None,
fltr_specs=None, mode='valid'):
gt = np.array(gt, dtype=np.uint8)
im = np.array(im, dtype=np.uint8)
if MAX is None:
MAX = np.iinfo(gt.dtype).max
if fltr_specs is None:
fltr_specs = dict(fltr=Filter.UNIFORM, ws=ws)
win = f... |
def fspecial(fltr, ws, **kwargs):
if fltr == Filter.UNIFORM:
return np.ones((ws, ws)) / ws**2
elif fltr == Filter.GAUSSIAN:
x, y = np.mgrid[-ws // 2 + 1:ws // 2 + 1, -ws // 2 + 1:ws // 2 + 1]
g = np.exp(-((x**2 + y**2) / (2.0 * kwargs['sigma']**2)))
g[g < np.finfo(g.dtype).eps * ... | The main task of the code is to compute a perceptual blur index (PBVIF) by comparing an input image to a ground-truth image across multiple scales. It calculates a quality metric using Gaussian filters, variance, and covariance terms, handling noise and avoiding division-by-zero errors. The result is a ratio of summed ... | def PBVIF(gt, im, sigma_nsq=2):
EPS = 1e-10
num = 0.0
den = 0.0
for scale in range(1, 5):
N = 2.0**(4 - scale + 1) + 1
win = fspecial(Filter.GAUSSIAN, ws=N, sigma=N / 5)
if scale > 1:
gt = filter2(gt, win, 'valid')[::2, ::2]
im = filter2(im, win, 'valid')... |
def cahn_hilliard_loss(self):
"""
* loss residual derived from the phase field transport equation
"""
c = self.output[:,3:4]
u = self.output[:,0:1]
v = self.output[:,1:2]
phi = self.phi()
c_g = gradients(c,self.input)[0]
phi_g = gradients(phi,s... | The main task of the code is to compute the total PDE loss residual by summing individual physics-informed loss components—Cahn-Hilliard, continuity, and momentum losses (x and y directions)—during each batch iteration. This aggregated loss guides the neural network's training to satisfy governing equations for multiph... | def loss(self):
"""
* constructs the total PDE loss residual
* called every batch iteration
"""
# print(self.x_momentum_loss())
return self.cahn_hilliard_loss() + \
self.continuity_loss() + self.x_momentum_loss() + \
self.y_momentum_loss() |
def compute_outputs(net, loader):
print("retrieving outputs")
"""Auxiliary function to compute the logits for all datapoints.
Does not shuffle the data, regardless of the loader.
"""
# Make sure loader does not shuffle the data
if isinstance(loader.sampler, torch.utils.data.sampler.RandomSa... | The function evaluates an unlearning algorithm by comparing the performance of an unlearned model against a retrained model. It computes accuracy metrics (retain, test, forget) and calculates a forgetting quality score using outputs from both models. The score combines these metrics with attack-based evaluations to qua... | def score_unlearning_algorithm(
data_loaders: dict,
models: dict,
n: int = 1,
delta: float = 0.01,
f: Callable = cross_entropy_f,
attacks: list[Callable] = [best_threshold_attack, logistic_regression_attack]
) -> dict:
# n=512 in the case of unlearn and... |
def get_embeds(data_dir,
class_dict,
embed_dim,
embed_batch_size,
num_classes,
num_workers,
weights_path,
embeds_path,
embeds_labels_path,
idx_conv_dict_path,
folder_to_c... | The code conducts a comprehensive experiment to evaluate and compare multiple machine learning algorithms (DMGT_UNIF, DMGT_DYN, RAND, SIEVE) under varying initial conditions, data imbalances, and selection rounds. It trains models on streaming data, tracks accuracy for rare and all classes, records sample sizes, and co... | def experiment(init_pts,
imbals,
unif_taus,
dyn_taus,
trials,
num_sel_rounds,
num_algs,
stream_size,
num_test_pts,
num_epochs,
batch_size,
num_workers,
... |
def get_data(data_dir):
data = {}
data['img'] = glob.glob(data_dir+'/*.jpg')
data['label'] = data_dir
n_data = len(data['img'])
return data, n_data
def unet(X, training, flags=None):
net = X / 127.5 - 1
conv1, down1 = conv_block(net, [8, 8], training, flags, name='down1')
conv2, down2 =... | The code trains a UNet model for image segmentation using TensorFlow, applying data augmentation, computing IoU and box loss, and optimizing via a custom training op. It loads data, initializes variables, trains over epochs with batched data, saves checkpoints, and validates periodically on test data to evaluate perfor... | def train(flags):
train_data, n_train = get_data(train_data_dir)
test_data, n_test = get_data(test_data_dir)
tf.reset_default_graph()
X = tf.placeholder(tf.float32, shape=[None, None, None, 3], name="X")
y = tf.placeholder(tf.float32, shape=[None, None, None, 1], name="y")
box_true = tf.placeho... |
def get_data(data_dir):
data = {}
data['img'] = glob.glob(data_dir+'/*.jpg')
data['label'] = data_dir
n_data = len(data['img'])
return data, n_data
def unet(X, training, flags=None):
net = X / 127.5 - 1
conv1, down1 = conv_block(net, [8, 8], training, flags, name='down1')
conv2, down2 =... | The main task of the code is to evaluate a UNet model on test data by either validating its performance (calculating IoU and box loss) or generating predictions for individual images. It loads test data, initializes the model, restores checkpoints, and runs inference. In validation mode, it computes average IoU and box... | def test(flags):
test_data, n_test = get_data(test_data_dir)
batch_size = flags.batch_size if train_mode == 'val' else 1
tf.reset_default_graph()
X = tf.placeholder(tf.float32, shape=[batch_size, None, None, 3], name="X")
y = tf.placeholder(tf.float32, shape=[batch_size, None, None, 1], name="y")
... |
def enterGrades():
name = input("enter student name: ")
if name in students:
grade = floatGradeInput()
print("adding grade ...")
students[name].append(grade)
# print name, new numbers list
print(name, students[name])
else:
print(name, "not found in system")
de... | The code defines a menu-driven system for managing student grades, allowing users to enter grades, remove students, view averages, or logout. It recursively calls itself to repeat the menu until logout is chosen, handling user input with conditional logic to trigger corresponding functions. | def action():
# for printing string in multiple lines, use """
print("""
Welcome to Central Student Grades System:
[1] - enter grades
[2] - remove a student
[3] - student average grades
[4] - logout
""")
# the variable here cannot be "input",
# looks like method names are also... |
def __transofrm(self, x):
result = x.copy()
result[self.negative] = -result[self.negative]
for k in self.not_monotonic:
result[k + "-"] = -result[k]
return result
def __getMappingVector(self, mapping, x, k):
l = list(sorted([i for i in mapping]))
first, size =... | The main task of the code is to solve an optimization problem using linear programming and probabilistic methods to evaluate or rank solutions. It constructs constraints based on data transformations, handles skewness and additional points, sets up linear equations for optimization, and computes results using `linprog`... | def __model(self, mode="F", ):
used = []
for x in self.better:
used.append(x[0])
used.append(x[1])
used = self.__transofrm(pd.DataFrame(used, columns=self.df.columns))
mappings = []
mappingsNames = []
i = 0
for c in used.columns:
... |
def __domination(self, x, y):
used = [x, y]
used = self.__transofrm(pd.DataFrame(used, columns=self.df.columns))
return all(used.iloc[0] >= used.iloc[1]) or all(used.iloc[1] >= used.iloc[0])
def __model(self, mode="F", ):
used = []
for x in self.better:
used.append(x[... | (The code evaluates a pair of elements (x, y) using a scoring method and model to compute their interaction score. It checks if x dominates y, returning -9 if true. Otherwise, it appends the pair to a list, queries a model twice (with reversed order), and aggregates results via min, mean, or weighted average based on t... | def scorePair(self, x, y, scoring='pesimistic', method='correlation'):
assert scoring in ['pesimistic', 'mean', 'expected']
assert method in ['correlation', 'entropy']
if self.__domination(x, y):
print("domination")
return -9
result = []
self.better.appen... |
def _getWinnableCards(self):
'''
looks for cards which when changed to the card's rule,
will make the player win
caches the colors in a set to avoid duplicate computation
returns a Hand object
'''
winnableCards = Hand([])
computedColors = set()
for card in self.hand:
if card.c... | The code handles a player's turn by letting them choose an action (play cards to palette/canvas or pass). For bots, it selects actions based on winnable cards and weighted probabilities; humans input their choice. The selected action is executed, and the turn ends with a status update. | def onTurn(self):
'''
on the player's turn the player can choose a action to perform
'''
choice = 0
if self.isBot:
# if it a bot, check if it has winnable cards
# ie. can choose option 2 or 3
winnableCards = self._getWinnableCards()
if len(winnableCards) == 0: # can't
... |
def remove_agent(self):
"""Remove the agent and its safe location from the grid"""
self.goal.remove()
self.model.grid._remove_agent(self.pos, self)
self.model.schedule.remove(self)
def surrounding_danger(self):
"""Return a list of reputation, location, distance tuples where:
... | (The code's main task is to guide a victim agent to its safe location by deciding movement based on surrounding danger and fear levels. If danger is detected, the agent adjusts fear using environmental influence or familiarity, then either moves away from threats if fear is high or continues toward the goal. The agent ... | def step(self):
"""
This is the action the victim agent makes with every tick.
The victim's ultimate goal is to make it back to their safe location.
The agents will either chose to move in the direction of the safe location,
or if they feel scared enough, they will try to move aw... |
def get_surr_crime(self):
"""Get the visible surrounding criminal area positions
:return List of AttractorLoc and GeneratorLoc agents. """
surr_pos = self.get_surr_pos(self.pos, self.VISIBILITY)
cell_contents = self.model.grid.get_cell_list_contents(surr_pos)
criminal_area_c... | The code defines an agent's decision-making process in a simulation. Based on criminal motive intensity, surrounding crime data, and random probabilities, the agent either chases a victim to commit a crime, moves toward a criminal area, commits an opportunistic crime, or moves randomly. High motive intensity with a tar... | def step(self):
""" With every tick of the simulation, depending on the different internal levels
of the agent, it will either :
- find a victim, chase the victim, and attempt commit a crime against the victim.
- move towards a criminal area
- commit an oportunistic ... |
def handleCookieJar(self) -> (tuple[SimpleCookie, list[str]] | NoneType):
## Reads cookies and looks for authToken and username
cookies = SimpleCookie(self.headers.get('Cookie'))
uName = ''
authT = ''
for cookie in cookies.values():
cookie = cookie.OutputString().spli... | The code handles HTTP PUT requests to write or delete files on a server. It uses cookies for authentication, processes incoming data, checks file existence, and performs write/delete operations via a filesystem module. It returns HTML-formatted success/failure messages with HTTP status codes (200/404) based on operatio... | def do_PUT(self):
"""
Handles the following requests:
- writefile
- deletefile
"""
CookieJar = self.handleCookieJar()
if CookieJar == None:
return
cookies:SimpleCookie = CookieJar[0]
authRe... |
def handleCookieJar(self) -> (tuple[SimpleCookie, list[str]] | NoneType):
## Reads cookies and looks for authToken and username
cookies = SimpleCookie(self.headers.get('Cookie'))
uName = ''
authT = ''
for cookie in cookies.values():
cookie = cookie.OutputString().spli... | (The code handles HTTP POST requests to manage user creation, file operations, and folder listings. It processes actions like newUser (validating and creating users), makefile (creating files if they don't exist), listfolder (listing directory contents), and renamefile (renaming files). It checks authentication, valida... | def do_POST(self):
"""
Handles the following requests:
- newUser
- makefile
- listfolder
- renamefile
"""
CookieJar = self.handleCookieJar()
if CookieJar == None:
return
... |
def feed_crf_params(grid_search_params=None):
"""
This function provides all the combinations of a greedy search parameters.
:param grid_search_params:
:return: dict. A dictionary of parameters for the crf model.
"""
if grid_search_params is None:
grid_search... | This method performs grid search cross-validation for a CRF model by evaluating all parameter combinations across k-folds, selecting the best parameters based on average accuracy, retraining the model on the full training data, and returning the best model's performance metrics on the test set. | def grid_search_cross_validation(self,
X_train,
X_test,
filepath='grid_crf_model_en.crfsuite',
grid_params=None,
verbose=0,
... |
def prepare_input(self, image):
self.img_height, self.img_width = image.shape[:2]
input_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Resize input image
input_img = cv2.resize(input_img, (self.input_width, self.input_height))
# Scale input pixel values to 0 to 1
input... | The main task of the code is to perform object segmentation on an input image. It processes the image into a tensor, runs inference to detect objects, and extracts bounding boxes, confidence scores, class IDs, and segmentation masks. The function returns these results for further analysis or visualization. | def segment_objects(self, image):
input_tensor = self.prepare_input(image)
outputs = self.inference(input_tensor)
self.boxes, self.scores, self.class_ids, mask_pred = self.process_box_output(outputs[0])
self.mask_maps = self.process_mask_output(mask_pred, outputs[1])
return self... |
def change_led_state_from_file(self, led_state_file):
state = open(led_state_file, mode="r", encoding="utf-8").readline()
self.is_on = distutils.util.strtobool(state)
self.change_led_state()
def change_color_from_file(self, color_state_file):
color = open(color_state_file, mode="r", enco... | This code continuously updates LED state and color from files, toggles to random color on button press, and switches LED state via a micro input. It runs in an infinite loop, handling GPIO inputs and cleaning up resources on interruption. | def exec(self):
try:
while True:
self.change_led_state_from_file(PathConsts.state_filename)
self.change_color_from_file(PathConsts.color_filename)
if not GPIO.input(self.button_channel):
print('color')
self.chan... |
def get_grid():
nums = []
for i in range(9):
nums.append([cube[i][j].val for j in range(9)])
return nums
def draw_game_grid(grid):
for i in range(9):
for j in range(9):
cube[i][j].val = grid[i][j]
draw_game_window()
def clear_screen():
for i in range(9):
for j... | The main task of the code is to handle user interactions in a Pygame-based grid application. It processes mouse clicks to select grid cells, updates cell values via number keys, and triggers actions like solving or clearing the grid. The loop continuously checks for events, updates the selected cell's state, and redraw... | def main():
run = True
i = 0
j = 0
while run:
pygame.time.delay(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
cube[i][j].selected = False
pos... |
def cleanInput(self,txt):
if txt[0] == '\n':
txt = txt[1:]
n = 0
for i in range(len(txt)):
if txt[i] != '\n':
n+=1
else:
n = 0
if n > 50 and txt[i] == ' ': #arbriaty number
n = 0
... | This code processes and displays user input text in a GUI, cleaning it of unnecessary characters, incrementally updating the interface, and triggering a response from an NPC. It trims whitespace/punctuation, cleans input/output, and dynamically updates the text display before passing the processed text to a reply funct... | def TalkEnter(self,inpt,txt,npc):
txt = txt.replace('\n','')
if txt[-1] in ('?','.',' ','\n'):
txt = txt[:-1]
if txt[0] == ' ':
txt = txt[1:]
txt = self.cleanInput(txt)
self.cleanOutput()
txt = txt+'\n'
for i in txt:
se... |
def cleanInput(self,txt):
if txt[0] == '\n':
txt = txt[1:]
n = 0
for i in range(len(txt)):
if txt[i] != '\n':
n+=1
else:
n = 0
if n > 80 and txt[i] == ' ': #arbriaty number
n = 0
... | The code processes input text by cleaning it, displaying characters with a typing effect in a GUI textbox, and triggering an interpretation function. It handles special cases like 't' to initiate a dialogue, updates the interface dynamically, and resets input fields after processing. | def enter(self,inpt,txt):
if txt != None:
txt = txt.replace('\n','')
if txt == 't':
ui.talkWindow(jeremy,C1)
txt = self.cleanInput(txt)
self.cleanOutput()
txt = txt+'\n'
for i in txt:
#Types to ... |
def setAttr(self,dictionary):
for k,v in dictionary.items():
setattr(self,str(k),v)
def make_sec_dict(self,dendTypeList):
d = {}
for dendType in dendTypeList:
d[dendType] = {}
dend = dendTypeList[dendType]
for ii in range(len(dend)):
dend[ii].push()
idx = h.n3d()-1
dist = np.sum((np.array(... | This code initializes a neuron cell model by setting up parameters like ID, location, and synapse properties. It loads morphology data, organizes sections into layers, and configures synapses based on cell type. The modeltype flag determines whether to create a multicompartmental (Multi) or single-compartment (Single) ... | def __init__(self,cellID,locn,synvars,celltype,morphFileName,modeltype='Multi'):
# Sets the synapse properties
self.synvars = synvars
# Sets ID of cell
self.ID = cellID
# Sets location of cell
self.location = locn
# Create random number generator for cell
self.ranGen = random.Random()
self.ra... |
def getjunk(r):
line = b''
while fire not in line:
line = r.recvline()
if b'HTB' in line:
print(f'flag : {line.decode()}')
sys.exit()
def getboard(board):
# read until bottom border
while True:
l = r.recvline()
line = l.split(b' ')
# cleanup
line = [x for x in line if ((x != ... | The main task of the code is to repeatedly solve a board puzzle by generating step sequences, sending them to a remote server via `r.sendline()`, and looping indefinitely. It initializes a board, retrieves puzzle parameters, renders the board state, computes solution steps using the `solve()` function, formats the step... | def exp():
i = 1
while True:
board, steps = [], []
getjunk(r)
board, src, dest = getboard(board)
render(board)
s = solve(board, src, dest, steps)
s = ''.join(s)
print(f'steps : {s}')
r.sendline(s.encode())
print('*************************')
print(f'iter: {i} ==> DONE')
... |
def STinit(c, D):
# calling above function
P = DCTpower(c)
Kmax,_ = D.shape
ST = np.empty(0)
# calculating ST according to the given formula
for k in np.arange(3,Kmax-26):
if P[k] > P[k+1] and P[k] > P[k-1]:
Dk = np.where(D[k,:])
if P[k] > np.max(np.r_[P[k-Dk],P[k+Dk]... | The function `psycho` computes global masking thresholds (Tg) by sequentially initializing signal structures (ST), calculating masking power (PM), reducing signal complexity (STr, PMr), determining local masking thresholds (Ti), and aggregating them into global thresholds (Tg) using predefined parameters and auxiliary ... | def psycho(c,D):
# defining Kmax and calling the previous functions one after another
Kmax = len(c) - 1
Tq = np.load("Tq.npy", allow_pickle=True).squeeze()
ST = STinit(c,D)
PM = MaskPower(c,ST)
STr,PMr = STreduction(ST,c,Tq)
Ti = Masking_Thresholds(STr,PMr,Kmax)
Tg = Global_Masking_Thresholds(Ti,Tq)
... |
def create_layer_conv(params, index, index_out):
node = Layer_node()
node.name = params['layer_type']
node.op_type = params['operation_type'] # TODO might be redundant
node.pads = params['padding']
node.group = params['group']
node.strides = params['stride']
node.kernel_shape = params['kern... | The code constructs a computational graph for a neural network by iterating through nodes, creating convolutional/fully connected layers or addition operations, managing branch paths, and appending nodes to a list. It handles input propagation, branch switching, and output tracking using PyTorch operations, returning t... | def create_graph(params, network_dir,number_of_nodes):
layers = []
index_layer = 0
for index in np.arange(number_of_nodes):
if params[index]['layer_type'] in ["Convolution", "FullyConnected"]:
increment = index_layer + 1
if index > 0:
if params[index-1]['branc... |
def get_headers(file: Path, delimiter: str = ","):
return exec(["xsv", "headers", "-j", "-d", delimiter, file]).split("\n")
def select_meta_ids(metadata: list[MetaPath], intersect: bool) -> list[int]:
"""This function selects the IDs from the metadata files following the MetaPath instructions
Args:
... | The main task of the code is to select specific columns from an input CSV file based on metadata paths, filter out missing IDs if instructed, and export the selected columns to an output file using xsv commands. It processes headers, validates selections, handles optional parameters like intersection and always-inclusi... | def metasplit(
metadata: list[MetaPath],
input_file: Path,
output_file: Path,
intersect: bool = False,
ignore_missing: bool = False,
input_delimiter: str = ",",
always_include: Optional[list[str]] = None,
) -> None:
if not input_file.exists():
raise ValueError(f"Input csv {input_... |
def get_legal_moves(self, actual_piece, r, c, **kwargs):
#region black KING get legal moves
if actual_piece.notation == "Kb":
add_legal_moves = []
add_defends = []
add_border = []
# CASTLE queen side
if (actual_piece.moved == False):
... | The code handles moving a chess piece on a board, validating the move's legality (e.g., check constraints), updating the board state, capturing pieces, executing special moves (castling, en passant), promoting pawns, and resetting legal moves for all pieces. It also manages UI highlights, user interactions, and game ru... | def move_piece(self, event, from_square_r, from_square_c, from_square_id, actual_piece):
# finding the row and col of the next selected square
r = 0
c = 0
for col in range(1,9):
if (event.x <= col*100 and event.x >= (col-1)*100):
c = col-1
for ... |
def load_csv(filename):
dataset = list()
with open(filename, 'r') as file:
csv_reader = reader(file)
for row in csv_reader:
if not row:
continue
dataset.append(row)
return dataset
def data_prep(dataset):
for col in range(len(dataset[0])):
i... | This function evaluates k-NN classifier performance using cross-validation on a dataset, testing varying numbers of neighbors (1 to num_neighbors_max) and distance metrics (Jaccard, Minkowski with p=1 to p_norm_max). It supports sequential, multithreaded, or multiprocessing execution to compute average accuracy across ... | def runner(filename, n_folds, num_neighbors_max, p_norm_max, parallel='seq'):
p_norm_range = range(1, p_norm_max + 1)
dataset = load_csv(filename)
dataset = data_prep(dataset)
# Split dataset into n_folds folds
folds_list = cross_validation_split(dataset, n_folds)
# Evaluate
if parallel ==... |
def SentenceWords(text):
return [Words(sentence) for sentence in Sentences(text)]
def FilterSentenceWords(sentenceWords, stopWords=StopWords()):
return [FilterWords(words, stopWords) for words in sentenceWords]
def StemSentenceWords(sentenceWords, stemmer=Stemmer()):
return [StemWords(words, stemmer) for words in se... | The main task of the code is to process input text by splitting it into words, filtering irrelevant terms, applying stemming to reduce words to their root forms, and printing the resulting processed words. | def Main(text):
words = SentenceWords(text)
words = FilterSentenceWords(words)
words = StemSentenceWords(words)
print(words) |
def fitness_function(self, pos):
x, y = pos.swapaxes(0, 1)
return self.f0(x, y)
def update_bests(self):
fits = self.fitness_function(self.particles)
for i in range(len(self.particles)):
# update best personnal value (cognitive)
if fits[i] < self.p_bests_values[i]... | This code initializes a Particle Swarm Optimization (PSO) algorithm for optimization tasks, setting up particles, velocities, targets, and parameters like inertia (w), cognitive (c_1), and social (c_2) coefficients. It defines decay rules based on proximity to targets, initializes personal and global best positions, an... | def __init__(self, particles, velocities, targets,
w=0.8, c_1=1, c_2=1, max_iter=100, prox_dist=.1, carry=0.01, auto_coef=True):
self.particles = particles
self.carry_cap = carry # how much a particle can "carry" from target
self.velocities = velocities
# self.fitness_f... |
def move_particles(self):
# add inertia
new_velocities = self.w * self.velocities
# add cognitive component
r_1 = np.random.random(self.N)
r_1 = np.tile(r_1[:, None], (1, 2))
new_velocities += self.c_1 * r_1 * (self.p_bests - self.particles)
# add social compone... | The code advances a Particle Swarm Optimization (PSO) algorithm iteration by moving particles, updating targets, best positions, and coefficients. It increments the iteration count and checks if the algorithm should continue based on remaining targets and maximum iterations, returning whether the algorithm is still act... | def next(self):
if self.iter > 0:
self.move_particles()
self.update_target()
self.update_bests()
self.update_coef()
self.iter += 1
self.is_running = self.is_running and self.has_targets and self.iter < self.max_iter
return self.is_running |
def mask_logits(logits: Tensor, mask: Tensor) -> Tensor:
return torch.where(
mask, # condition (mask in this case)
logits,
torch.tensor(-100.0, dtype=logits.dtype), # set to really small number
)
def dither(cat: Categorical, temp=1.0, eps=0.0) -> Categorical:
# Temper the probs
p... | The code trains a neural network model (TrajBalMLP) for reinforcement learning by generating episodes, optimizing model parameters and logZ with Adam, and updating the model based on batch losses. It processes batches of trajectories, computes policy gradients, clips gradients, and logs metrics like loss, Z-values, and... | def train(
self,
n_episodes=5000,
batch_size=16,
lr_model=3e-4,
lr_Z=1e-1,
temp=1.0,
eps=0.0,
grad_clip=1e6,
):
# Settings
device = torch.device("cpu")
n_batches = n_episodes // batch_size
# Model
self.model = T... |
def advance(self):
if self.isAtEnd(): return '\x00'
c = self.source[self.current]
self.current += 1
return c
def addToken(self, t_type, literal=None):
lexeme = self.source[self.start:self.current]
self.tokens.append(Token(t_type, lexeme, literal, self.line))
def readNumbe... | The main task of the code is to scan and classify the current character into tokens. It handles operators, whitespace, numbers, identifiers, and unexpected characters by either adding tokens, updating line numbers, or raising errors, functioning as part of a lexical analyzer for parsing input. | def scanToken(self):
c = self.advance()
if c in "+-*/^()=,[]":
self.addToken(c)
elif c == '\n':
self.line += 1
elif c in '\r\t ':
pass
elif c.isdigit():
self.readNumber()
elif c.isalpha():
self.readIdentifier()
... |
def isAtEnd(self):
return self.current >= len(self.source)
def scanToken(self):
c = self.advance()
if c in "+-*/^()=,[]":
self.addToken(c)
elif c == '\n':
self.line += 1
elif c in '\r\t ':
pass
elif c.isdigit():
self.readNu... | The code scans the input text to tokenize it, tracking position and line numbers, and returns a list of tokens including an EOF marker. | def scan(self, txt):
self.source = txt
self.current = 0
self.line = 1
self.tokens.clear()
while not self.isAtEnd():
self.start = self.current
self.scanToken()
self.addToken('EOF')
return self.tokens.copy() |
def get_cwd():
#cwd = '/Users/mahrokh/DECODE/Simulations/London'
return os.getcwd()
def get_data_of_a_person(block=5, house_id="MAC004504", crop_years=True, verbose=False):
path = get_cwd()+"/input/halfhourly_dataset/block_"+str(block)+".csv"
data = pd.read_csv(path)
if house_id==[]:
ho... | The main task of the code is to aggregate and average half-hourly energy consumption data from multiple households belonging to a specified ACORN group (e.g., "ACORN-L"). It selects a base household with complete yearly data, then iteratively adds data from other households in the same group, ensuring data consistency,... | def get_data_of_acorn_group(group="ACORN-L", num_houses=10, crop_years=True, verbose=False):
path = get_cwd()+"/input/informations_households.csv.xls"
data = pd.read_csv(path)
candidates = data.loc[data.Acorn==group]
# get 1 p
ind_1p=0
while True:
block_name = candidates.file.iloc[ind_1p... |
def get_cwd():
#cwd = '/Users/mahrokh/DECODE/Simulations/London'
return os.getcwd()
def get_data_of_a_person(block=5, house_id="MAC004504", crop_years=True, verbose=False):
path = get_cwd()+"/input/halfhourly_dataset/block_"+str(block)+".csv"
data = pd.read_csv(path)
if house_id==[]:
ho... | The function aggregates and averages energy consumption data from multiple households across different blocks. It reads CSV data, processes each household's energy usage by converting units, checking for data quality issues, and combining their energy values. It ensures consistent data length and integrity before avera... | def get_data_of_mixed_group(block=20, num_houses=10, crop_years=True, verbose=False):
path = get_cwd()+"/input/halfhourly_dataset/block_"+str(block)+".csv"
data = pd.read_csv(path)
ids = data.LCLid.unique()
# get 1 p
df = get_data_of_a_person(block=block, house_id=ids[0], verbose=verbose)
df[... |
def get_cwd():
#cwd = '/Users/mahrokh/DECODE/Simulations/London'
return os.getcwd()
def get_data_of_a_person(block=5, house_id="MAC004504", crop_years=True, verbose=False):
path = get_cwd()+"/input/halfhourly_dataset/block_"+str(block)+".csv"
data = pd.read_csv(path)
if house_id==[]:
ho... | This function aggregates and averages energy consumption data from multiple households belonging to a specified ACORN socioeconomic group (e.g., "ACORN-L") for the year 2013. It filters input data, processes individual household datasets, ensures temporal consistency, cleans data, and combines energy readings across th... | def get_data_of_acorn_group_2013(group="ACORN-L", num_houses=10, crop_years=True, verbose=False):
path = get_cwd()+"/input/informations_households.csv.xls"
data = pd.read_csv(path)
candidates = data.loc[data.Acorn==group]
ys=[]
# get 1 p
ind_1p=0
while True:
block_name = candidates.f... |
def _generate_home_view(self, wait: bool) -> Image.Image:
"""Generate the home view as an image.
Args:
wait (bool): Indicates if wait message is printed
Returns:
Image: The home image
"""
# Add logo
img = Image.open(f"{Path(__file__).parent}/../i... | The function retrieves the current buffered image based on the device's active view mode (HOME, SYSTEM, STATUS, SETUP, or CUSTOM). It delegates image generation to private methods specific to each view type and returns the buffered image using the EPD (e-paper display) object. The 'wait' parameter controls whether a wa... | def get_current_buffered_image(self, wait: bool = False) -> Any:
"""Get current image as buffered.
Args:
wait (bool, optional): Indicates if wait message is printed. Defaults to False.
Returns:
Any: The buffered image
"""
if self.current_view == "HOME":
... |
def send_command(self, command: Any) -> None:
"""Send a command on EPD.
Args:
command (Any): Send a command on EPD (see EPD datasheet for more details)
"""
self.dc_gpio.set_value(0)
self.spi_transfer([command])
def send_data2(self, data: Any) -> None:
"""Send... | The main task of the code is to send image data to a display module by sending a specific command (0x24), transmitting the pixel data via `send_data2`, and activating the display with `turn_on_display()` to render the image on the screen. | def display(self, image: bytearray) -> None:
"""Send and display the data on the screen.
Args:
image (bytearray): Data to send to screen
"""
self.send_command(0x24)
self.send_data2(image)
self.turn_on_display() |
def send_command(self, command: Any) -> None:
"""Send a command on EPD.
Args:
command (Any): Send a command on EPD (see EPD datasheet for more details)
"""
self.dc_gpio.set_value(0)
self.spi_transfer([command])
def send_data2(self, data: Any) -> None:
"""Send... | This function refreshes a base image on a display by sending specific commands (0x24 and 0x26) followed by image data twice using send_data2, then activating the display with turn_on_display. It prepares the display for partial image updates and ensures the new image is rendered properly. | def displayPartBaseImage(self, image: Image.Image) -> None:
"""Refresh a base image.
Args:
image (Image): the raw image to send
"""
self.send_command(0x24)
self.send_data2(image)
self.send_command(0x26)
self.send_data2(image)
self.turn_on_dis... |
def send_command(self, command: Any) -> None:
"""Send a command on EPD.
Args:
command (Any): Send a command on EPD (see EPD datasheet for more details)
"""
self.dc_gpio.set_value(0)
self.spi_transfer([command])
def send_data2(self, data: Any) -> None:
"""Send... | The main task of the code is to clear the screen with a specified color by calculating the required data size based on the display's width and height, sending a command (0x24), transmitting the color data repeated to fill the screen, and then enabling the display. | def clear(self, color: int) -> None:
"""Clear all the screen with specific color.
Args:
color (int): Data to send to screen
"""
if self.width % 8 == 0:
linewidth = int(self.width / 8)
else:
linewidth = int(self.width / 8) + 1
self.sen... |
def reset(self) -> None:
"""Reset EPD."""
self.reset_gpio.set_value(1)
epd_delay_ms(20)
self.reset_gpio.set_value(0)
epd_delay_ms(2)
self.reset_gpio.set_value(1)
epd_delay_ms(20)
def wait_busy(self) -> None:
"""Wait EPD ready state."""
self.logger.... | This code initializes an e-Paper display's hardware registers by sending specific commands and data to configure display settings, reset the device, set data entry mode, define display windows, and control update parameters, ensuring the display is ready for operation. | def init(self) -> None:
"""Initialize the e-Paper register."""
# EPD hardware init start
self.reset()
self.wait_busy()
self.send_command(0x12) # SWRESET
self.wait_busy()
self.send_command(0x01) # Driver output control
self.send_data(0xF9)
self.... |
def epd_delay_ms(delaytime: int) -> None:
"""Utility function to create a delay in ms.
Args:
delaytime (int): Wait delay in ms
"""
time.sleep(delaytime / 1000.0)
def send_command(self, command: Any) -> None:
"""Send a command on EPD.
Args:
command (Any): Send a comm... | The code sends image data to an e-paper display for a partial refresh by configuring display settings, setting the window/cursor, writing data to the display RAM, and enabling partial refresh. It handles GPIO reset, command/data transmission, and display activation. | def display_partial(self, image: bytearray) -> None:
"""Send the data on the screen and execute a partial refresh.
Args:
image (bytearray): Data to send to screen
"""
self.reset_gpio.set_value(0)
epd_delay_ms(1)
self.reset_gpio.set_value(1)
self.send... |
def get_neighbors(x, y, color, board):
neighbors = []
# Above
if y > 0:
if is_color(x, y - 1, color, board):
neighbors.append((x, y - 1))
# Below
if y < rows - 1:
if is_color(x, y + 1, color, board):
neighbors.append((x, y + 1))
# Left
if x > 0:
... | This function checks if placing a stone of a given color at position (x,y) on a board is valid. It verifies if the spot is empty, has liberties, joins a chain with liberties, or captures enemy stones. Validity depends on ensuring the move doesn’t violate rules like filling already occupied spots or leaving no liberties... | def is_valid_move(x,y,color, board):
#if it is already filled with stone, return False
if board[y][x] != 0:
print("Already Filled")
return False
#if is a location with liberties
liberties = get_neighbors(x,y,0, board)
if len(liberties) > 0:
print('Valid because it has a at l... |
def pass_turn():
newCapture1 = capture_history[-1][0]
newCapture2 = capture_history[-1][1]
newBoard = deep_copy_array(board_history[-1])
board_history.append(newBoard)
capture_history.append((newCapture1, newCapture2))
update_display('Player passed...')
paint_stones()
def update_disp... | The function `execute_menu_action` processes a selected menu option in a game, triggering actions like passing a turn, resuming play, entering review mode (if move history exists), or resetting the game. It uses global state variables and updates the display based on the chosen action, cycling through menu options usin... | def execute_menu_action():
global menu_mode
global review_mode
global review_offset
global board_history
menu_mode = False
option_len = len(menu_options)
action = menu_options[current_position % option_len][0]
if action == 'PASS':
pass_turn()
elif action == 'RESUME':
... |
def update_display(line2):
text_lines = macropad.display_text(title="GO!")
i = len(board_history)
if i % 2:
text_lines[1].text = "Red's Turn"
else:
text_lines[1].text = "Blue's Turn"
text_lines[2].text = line2
capture1, capture2 = capture_history[-1]
text_lines[3].tex... | The main task of the code is to validate a move in a board game (likely Go) by checking if the target position is empty, has liberties, belongs to a chain with liberties, or captures enemy stones. It ensures the move is legal by verifying no existing stones occupy the position, the placement provides liberties, or the ... | def is_valid_move(x,y,color, board):
#if it is already filled with stone, return False
if board[y][x] != 0:
update_display('Filled Already')
return False
#if is a location with liberties
liberties = get_neighbors(x,y,0, board)
if len(liberties) > 0:
# print('Valid because it... |
def is_valid_move(x,y,color, board):
#if it is already filled with stone, return False
if board[y][x] != 0:
print("Already Filled")
return False
#if is a location with liberties
liberties = get_neighbors(x,y,0, board)
if len(liberties) > 0:
print('Valid because it has a at l... | This function attempts to make a move on a Go board at position (x,y) with the given color. It validates the move, updates the board state, captures opposing stones if applicable, checks for the Ko rule (repeating board states), and appends the new board state to history if valid. It handles game state transitions and ... | def attempt_move(x, y, color):
board = board_history[-1]
if is_valid_move(x, y, color, board):
newBoard = deep_copy_array(board_history[-1])
update_board(x, y, color, newBoard) # Place the new stone on the board
captured_stones = get_captured_stones(x,y,color,board)
if len(capt... |
def is_valid_move(x,y,color, board):
#if it is already filled with stone, return False
if board[y][x] != 0:
update_display('Filled Already')
return False
#if is a location with liberties
liberties = get_neighbors(x,y,0, board)
if len(liberties) > 0:
# print('Valid because it... | This function attempts to make a move on a board game by validating the position (x,y) for the given color, updating the board with the new stone, capturing opposing stones if any, updating capture history, checking for invalid Ko moves (repetition), and appending the new board state to history while updating the displ... | def attempt_move(x, y, color):
global capture_history
board = board_history[-1]
if is_valid_move(x, y, color, board):
newBoard = deep_copy_array(board_history[-1])
update_board(x, y, color, newBoard) # Place the new stone on the board
captured_stones = get_captured_stones(x,y,color... |
def read_from_txt(name):
txt_file = open(name, "r", encoding="utf-8")
content_list = txt_file.readlines()
_list = list()
for element in content_list:
_list.append(element.strip())
return _list
def extract_data(directory_path):
data = []
print('Extracting data...')
filenames = os.... | The main task of the code is to initialize feature data (X) and target labels (y) by either loading them from text files if they exist, or generating them by extracting and processing text data from a directory. If file loading fails, it extracts training data, lemmatizes it, splits content/ratings, and saves the proce... | def initialize_data(directory_name, file_name_X, file_name_y, X, y):
try:
X = read_from_txt(file_name_X)
y = read_from_txt(file_name_y)
except:
# extract the training data
training_data = extract_data(directory_name)
# lemmatize the data
format_data(training_data)... |
def select_mutual_info_vocab(X_train, y_train, stops, vectorizer_type, max_features, tfidf_filename):
selected_vocab = {}
try:
with open(tfidf_filename, 'r') as f:
s = f.read()
selected_vocab = eval(s)
except:
print(tfidf_filename, 'is not found. Creating vocab file:'... | This function tests mutual information-based feature selection by iterating over specified max_features values. For each value, it retrieves or generates vocabulary for count and TF-IDF representations, vectorizes training and validation data, and applies models to evaluate performance using these feature sets. The pro... | def test_feature_params_with_model_mutual_info(X_train, X_val, y_train, y_val, stops, max_features_list):
for max_features in max_features_list:
# get mutual info vocab from file if the file is created for COUNT.
# else, create the vocab and save it for future use.
count_filename = 'mi_vocab... |
def extract_data(directory_path):
data = []
# print('Extracting data...')
sorted_filenames = os.listdir(directory_path)
sorted_filenames.sort(key=lambda x: int(x[:-6]))
for filename in sorted_filenames:
with io.open(directory_path + '\\' + filename, "r", encoding="utf8") as f:
re... | The main task of the code is to load a pre-trained model and vocabulary from a pickle file, process test data from a specified folder by lemmatizing and vectorizing it, use the model to predict ratings, and evaluate performance metrics like accuracy, precision, and recall. The code also prints results and statistical a... | def main():
X_test = []
y_test = []
MODEL = {}
args = sys.argv
# test folder path
if len(args) <= 1:
print('Missing arguments.')
exit()
PKL_FILENAME = args[1] # TODO(): decide on file extension
FOLDER_NAME = args[2]
# obtain data from the test folder
t... |
def invert_image_in_W(self, image_path=None):
ref_im = Image.open(image_path).convert('RGB')
ref_im_L = self.image_transform(ref_im.resize((256, 256), PIL.Image.LANCZOS)).unsqueeze(0)
ref_im_H = self.image_transform(ref_im.resize((1024, 1024), PIL.Image.LANCZOS)).unsqueeze(0)
optimizer_... | This code inverts an input image into a latent representation by optimizing latent variables in a Feature Space (FS) using a generator network. It resizes the image, initializes latent codes, and iteratively refines them via optimization steps. The process compares generated images against reference images (high/low re... | def invert_image_in_FS(self, image_path=None):
ref_im = Image.open(image_path).convert('RGB')
ref_im_L = self.image_transform(ref_im.resize((256, 256), PIL.Image.LANCZOS)).unsqueeze(0)
ref_im_H = self.image_transform(ref_im.resize((1024, 1024), PIL.Image.LANCZOS)).unsqueeze(0)
latent_W ... |
def generateKey(string, key):
key = list(key)
if len(string) == len(key):
return(key)
else:
for i in range(len(string) -
len(key)):
key.append(key[i % len(key)])
return("" . join(key))
def affine_encrypt(text, key):
'''
C = (a*P + b) % 26
'... | The main task of the code is to encrypt or decrypt a string using a combination of affine cipher and a keyword-based key. It separates the input key into alphanumeric characters and special characters, generates a key from numeric parts, and applies encryption/decryption based on user choice. The process involves affin... | def main():
string = input("Enter String: ")
strings = input("Enter Key: ")
alpha = ""
num = ""
special = ""
for i in range(len(strings)):
if (strings[i].isdigit()):
num = num+ strings[i]
elif((strings[i] >= 'A' and strings[i] <= 'Z') or
(strings[i] >= 'a... |
def affine_encrypt(text, key):
'''
C = (a*P + b) % 26
'''
return ''.join([ chr((( key[0]*(ord(t) - ord('A')) + key[1] ) % 26)
+ ord('A')) for t in text.upper().replace(' ', '') ])
def encryptMessage (messages, keys):
return cipherMessage(messages, keys, 'encrypt')
def generateKe... | The code implements a hybrid encryption/decryption system using affine cipher and another method. It takes user input for a message, two integer keys (key1, key2), a string key (key3), and mode (encrypt/decrypt). In encryption mode, it applies affine transformation, then encrypts with key3, generates a new key, and pro... | def main():
message = input('enter message:\n')
key1= int(input("Enter key 1: "))
key2= int(input("Enter key 2: "))
key = [key1, key2]
key3 = input('enter your key:\n')
mode = input('encrypt or decrypt\n')
if mode == 'encrypt':
message = affine_encrypt(message, key)
cipher = ... |
def isLoggedIn(self):
# check if chat is already opened
url = self.browser.current_url
if "messenger.com/t/" in url:
return True
else:
return False
def logToScreen(self, text, isBanner=False):
if isBanner:
# clear the terminal
os.sy... | The main task of the code is to ensure the user is logged in and navigate to a specific Messenger chat (via its chat ID). It checks if the correct chat is already open; if not, it repeatedly loads the chat page, waiting for a specific UI element to confirm successful loading, retrying if the page fails to load within a... | def getChat(self, chatid):
if not self.isLoggedIn():
self.logToScreen("Need to login first before getting chat")
self.login()
# check if correct chat is already opened
url = self.browser.current_url
if "messenger.com/t/{}".format(chatid) in url:
retur... |
def isLoggedIn(self):
# check if chat is already opened
url = self.browser.current_url
if "messenger.com/t/" in url:
return True
else:
return False
def logToScreen(self, text, isBanner=False):
if isBanner:
# clear the terminal
os.sy... | The main task of the code is to retrieve and return a list of chat names and their corresponding IDs from a messaging platform by logging in if necessary, extracting data from web elements, and parsing links to generate a structured list of tuples containing chat names and IDs. | def getChatIDs(self):
if not self.isLoggedIn():
self.logToScreen("need to login first before getting chat")
self.login()
# gets chats that you see on your left
while True:
self.logToScreen("Fetching your chats and IDs ...")
names = []
... |
def read_data(model_name):
"""This function reads data files that are in a directory called "SNe Data". Don't change this! """
d = np.genfromtxt('SNe Data/' + model_name+'.txt', delimiter=',')
zs = d[:, 0]
mu = d[:, 1]
muerr=d[:, 2]
return zs, mu, muerr
def mcmc(p0, nwalkers, niter, ndim, lnprob... | The code performs Bayesian parameter estimation using MCMC to fit cosmological models (Ωₘ, ΩΛ, w₀, wa) to reduced supernova dataset. It generates corner plots, histograms, and Hubble diagrams comparing model fits, calculates χ² statistics, and saves results (parameters, plots, and diagnostics) for two scenarios: fixed ... | def main():
"""This is the main program which is run."""
plt.rcParams['font.family'] = 'Serif' #sets the graph font to be in the Serif family (close to the LaTeX default font)
dataset = "Data0"
print(dataset) #print which dataset we're currently analysing
zs, mu, muerr = read_d... |
def OBDM(s):
"""
One-body density matrix of liquid 4-He at 1.09 K.
Parameters
----------
s : float
Distance in units of \AA.
Returns
-------
float
"""
return 7.357e-2 + Gaussian(s, 2.271, 0, 3.189) + \
Gaussian(s, 5.227e-1, 0, 1.921) + \
Gaussi... | The main task of the code is to compute a prediction by multiplying three components: OBDM(s), R(s, gamma_r, gamma_i), and resolution(s). The function takes input parameters s, gamma_r (real part), and gamma_i (imaginary part), and returns their product, likely representing a combined model or signal processing calcula... | def prediction(s, gamma_r, gamma_i):
return OBDM(s)*R(s, gamma_r, gamma_i)*resolution(s) |
def getEthPriceinUSDForBlocks(self, blocks):
"""Calculate ETH price in USD for all blocks between given start and end block.
Sushiswap subgraph is used to fetch WETH-USDC pool reserves.
"""
print("Collect ETH prices...")
blocks = sorted(set(blocks))
marketSnapshots = sel... | The function calculates the USD price of a specified token for each block in a given range by fetching Sushiswap subgraph data on token reserves. It uses ETH price data (either provided or fetched) to convert token-ETH exchange rates into USD values, handling edge cases like zero reserves or missing WETH pairs. The res... | def getTokenPriceinUSDForBlocks(self, token, blocks, eth_prices):
"""Calculate custom token price in USD for all blocks between given start and end block.
Sushiswap subgraph is used to fetch token reserves.
"""
blocks = sorted(set(blocks))
## collect ETH prices if empty dict is ... |
def collect_top_20_by_trading_volume():
protocols = [
'CRV_WETH',
'ALCX_WETH',
'RADAR_WETH',
'METIS_WETH',
'OHM_WETH',
'DAI_WETH',
'SUSHI_WETH',
'YGG_WETH',
'KP3R_WETH',
'YFI_WETH',
'UST_WETH',
'WBTC_WETH',
'SPEL... | The main task of the code is to collect data on top DeFi pools by trading volume and stablecoin pools, focusing on liquidity and trading activity across major token pairs like WETH. It aggregates information on decentralized finance ecosystems, highlighting high-volume trading pools and stablecoin market dynamics for a... | def main():
# collect_data_for_dai_weth()
# collect_data_for_ldo_weth()
# collect_data_for_aave_weth()
# collect_data_for_usdc_weth()
# collect_data_for_wbtc_weth()
# collect_data_for_usdt_weth()
# collect_data_for_yfi_weth()
# collect_data_for_ilv_weth()
# collect_data_for_sushi_we... |
def get_args():
parser = argparse.ArgumentParser(
description="select genfare files for processing"
)
parser.add_argument(
"-i",
"--input_file",
type=argparse.FileType("r"),
# default=sys.stdin,
help="filename with list of genfare file names to be processes",
... | The main task of the code is to process multiple files by handling command-line arguments, retrieving filenames and paths, executing batch processing on the files, and aggregating results to count Cornell riders. It initializes parameters, processes input files, generates output data, and prints the total number of row... | def main(argv):
""" handle args and get filenames to pass to class"""
# set default arg values and process args
file_list = []
value_list = []
#begin_date = ""
#end_date = ""
fail_msg = ""
dropfile = ""
args = get_args()
file_names = get_file_names(args)
file_count = len(fil... |
def find_subset(pheno, column, cases=None):
# TODO check pandas type input
subset_mask = np.array(~pheno[column].isnull())
if cases is not None and not not cases:
all_cases = pheno.loc[subset_mask][column].unique()
try:
case_available = np.array([True if case in all_cases else Fa... | This function performs permutation-based generalized linear modeling (GLM) on connectivity data to assess group differences between cases and controls. It standardizes input data, iteratively shuffles group labels using cross-validation, fits GLMs with specified regressors, and collects beta coefficients across permuta... | def permutation_glm(pheno, conn, group, case, control, regressors='', n_iter=1000, stand=False):
# Make sure pheno and conn have the same number of cases
if not conn.shape[0] == pheno.shape[0]:
print(f'Conn ({conn.shape[0]}) and pheno ({pheno.shape[0]}) must be same number of cases')
sub_mask, case_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.