dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def isGoal(board,goal):
"""
Checks if the goal is met
Args:
board (dict): Dictionary representing the game board.
goal: Coordinates representing the 'B' node on the board
Returns:
Boolean True if the goal is met on the board and False if it isnt
"""
goal_coordinates_row... | The main task of the code is to use the A* search algorithm to find the optimal path of tetrimino-shaped blocks to clear the target 'B' node on a game board. It explores possible block placements, evaluates states with a heuristic, and returns a valid path as a list of coordinates if achievable, otherwise returns None. | def a_star_search(board,goal):
"""
Uses A* Search algorithm to determine the best path of tetrimino shaped blocks to clear the 'B' node on board
Args:
board (dict): Dictionary representing the game board.
goal: Coordinates representing the 'B' node on the board
Returns:
'curren... |
def make_encoding_table(huffman_tree):
"""
Given a Huffman tree, will make the encoding table mapping each
byte (leaf node) to its corresponding bit sequence in the tree.
"""
encoding_table = {}
preorder(huffman_tree, encoding_table, ())
return encoding_table
def make_freq_table(stream):
... | The code tests a Huffman tree implementation by creating tree nodes (leaves and branches), verifying their string representations, and constructing encoding tables. It also generates a frequency table from a sample string, builds a Huffman tree, and checks the resulting encoding. The main task is to validate the correc... | def testmain():
leafA = TreeLeaf('A')
leafB = TreeLeaf('B')
leafC = TreeLeaf('C')
print(leafA)
print(leafA.getValue())
print(leafB)
branch = TreeBranch(leafA, leafB)
print(branch)
print(branch.getLeft()) # leafA
print(branch.getRight()) # leafB
mytree = TreeBranch(bra... |
def _check_inputs(self, initialCheck=False):
'''
Perform some checks on the input data and inform the user
of data requirements
'''
if not isinstance(self.ds, xr.Dataset):
print(f'The elevation map should be given in xarray format')
varlist = self.ds.keys()
... | This function calculates orographic updraft using specified models ('evve' or 'bo04') based on wind direction, height, and wind speed inputs. It processes parameters like wind direction (wdir), height (h), reference wind speed (wspdAtRef), and target height wind speed (wspdAtHeightH), then applies the chosen model to c... | def calcOrographicUpdraft (self, wdir, h, wspdAtRef=None, wspdAtHeightH=None, model=None):
'''
Calculates the orographic updraft according to the the model requested.
The options are:
'evve': Orographic estimation according to Thedin et al. (2023)
'bo04': Orographic estimation ac... |
def fidelity_test(self):
"""Make a decision based on the local phermone count and the fidelity.
Note: The probability of returning True is bound by self.fidelity_min and self.fidelity_max.
The probability is the local phermone level divided by self.phermone_max.
Args:
self
... | The main task of the code is to update an ant's movement and behavior in a simulation by deciding whether to follow pheromone trails or explore based on a fidelity test, handling boundary checks, and depositing pheromones. It returns the ant's updated location after these actions. | def step(self):
"""Perform the overall logic for this ant's step.
See original paper for details.
Args:
self
Returns:
A 2-length array, self.location
"""
# If we are currently following, do a fidelity test for whether we continue following or dec... |
def get_config(config_filename):
cwd = pathlib.Path(__file__).parent.absolute()
conf_path = cwd.joinpath(config_filename)
config = configparser.ConfigParser()
config.read(conf_path)
return config
def generate_users(number_of_users):
url = base_url()
auth_list = []
for _ in range(number... | The main task of the code is to generate randomized user, post, and like data based on configuration parameters. It reads settings from a config file, creates specified numbers of users, generates posts per user, and assigns likes to posts, using functions to handle each data creation step. | def random_activity():
config = get_config(CONFIG_FILE)
num_users = config['USER']['number_of_users']
num_posts = config['POST']['max_posts_per_user']
num_likes = config['LIKE']['max_likes_per_user']
users_data = generate_users(int(num_users))
posts_data = generate_posts(users_data, int(num_pos... |
def shorten(s, w):
"""shortens a string by starting at index s instead of starting at index 0
Args:
s (int): the starting index of the shortened word
w (str): the string to be shortened
Returns:
str: the shortened string
"""
temp = []
for i in range(s, len(w)):
... | The function computes the longest common prefix (LCP) between suffixes of two strings (s1 and s2) for each pair of indices in l_pairs. For each pair, it shortens the strings, generates suffixes using Ukkonen's algorithm, compares corresponding suffixes character-by-character, and records the maximum matching length. Th... | def lcp(s1, s2, l_pairs):
"""finds the longest prefix common to the suffix of two different strings
Args:
s1 (str): first string which is the prefix string
s2 ([type]): second string which is the suffix string
l_pairs (List(tuple(int, int))): List of L pair values
"""
output =... |
def read_file(fileN):
"""reads file and creates list representing the L pairs
Args:
fileN (str): name of file to be opened
Returns:
List[str]: list of L pairs
"""
f = open(fileN, "r")
r = []
for line in f:
r.append(line)
return r
def process_l(l_pairs):
"""c... | The main task of the code is to read three input files via command-line arguments, process their contents to generate variables s1, s2, and l_pairs, and then execute the lcp function with these variables. The code prepares operatable inputs for the lcp algorithm, likely for sequence comparison or alignment, by parsing ... | def main():
"""generate operatable input variables and run lcp
"""
s1 = read_file(sys.argv[1])[0]
s2 = read_file(sys.argv[2])[0]
l_pairs = process_l( read_file(sys.argv[3]) )
lcp(s1,s2,l_pairs) |
def clocky():
today_last_time = "Unknown"
while True:
now = datetime.datetime.now()
today_date = now.strftime("%d %b %y")
today_time = now.strftime("%H:%M:%S")
if today_time != today_last_time:
today_last_time = today_time
with canvas(device) as draw:
... | The main task of the code is to control a smart glass interface by cycling through various functionalities (translation, weather, recording, camera, location) in a loop. It displays images/GIFs, checks a global flag (`opener`) to trigger specific actions (e.g., `trans_initiate`, `weather_req`), and transitions between ... | def main():
global opener
opener = False
try:
while True:
# button_next = GPIO.input(cn1)
# button_ok = GPIO.input(cn2)
# button_back = GPIO.input(cn3)
clocky()
show_image('/home/pi/smart_glass-master/Images/transl.png')
if ope... |
def draw_mids(hold_data):
last_data = hold_data[0]
mids = []
for data in hold_data[1:]:
if "hold_visible" in data[2][-1]:
mids.append(data)
if "hold_ignore" in data[2][-1]:
continue
if "critical" in last_data[2][-1]:
mid_texture = textures["notes_l... | The function `draw_notes` processes musical note data to render notes (hold and tap) on a visual interface. It iterates through sorted elements, extracts note parameters, and uses pattern matching to handle different note types. For hold notes, it draws midpoints, start/end positions, and the hold line; for tap notes, ... | def draw_notes():
for e in sorted(t[:]):
begin = e.begin
end = e.end
real_y, data = e.data
match data[0]:
case "note":
match len(data[1]):
case 1:
# hold
hold_data = data[1][0]
... |
def draw_bg():
if not sprite_lists["bg_sprites"]:
sx, sy = aspect(textures["bg_default"], (1280, 720))
sprite = pyglet.sprite.Sprite(textures["bg_default"], 640 - sx // 2, 360 - sy // 2, batch=batch, group=bg_group)
sprite.scale_x = sx / textures["bg_default"].width
sprite.scale_y = ... | This function updates game visuals and timing, handling OpenGL blending, time-based offset adjustments for video/music synchronization, dynamic note activation, judge line rendering, and foreground/background drawing. It manages pausing, user input for offset control, music playback triggers, and sprite list updates to... | def update(dt):
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
window.clear()
global previous_offset_time
global offset_time
global previous_time
global current_time
global flick_offset
previous_time = current_time
current_time = current_tim... |
def get_cf_status(stack_name):
response = ddb_client.get_item(TableName=os.environ.get('CF_MGMT_TABLE'), Key={
'StackName': {
'S': stack_name
},
})
item = response['Item']
return ast.literal_eval(item['Info']['S'])
def get_output(stack_name):
response = client.describe_st... | This function handles CloudFormation stack status events. It checks if the resource ID matches the stack name, then performs actions based on the status: creating/updating stacks by retrieving info/outputs and triggering network/server-specific handlers, deleting stacks with type-specific handlers, or force-deleting on... | def handle_status(resource_id, stack_name, status):
if resource_id == stack_name:
if status == "'CREATE_COMPLETE'" or status == "'UPDATE_COMPLETE'":
stack_info = get_cf_status(stack_name.replace("'", ''))
output_map = get_output(stack_name.replace("'", ''))
if stack_info[... |
def annotation_is_typing_optional(annotation) -> bool:
return get_origin(annotation) == Union and type(None) in get_args(annotation)
def annotation_for_storage_metadata(annotation) -> bool:
# first unwrap the Optional type
if annotation_is_typing_optional(annotation):
annotation = get_args(annotatio... | This function persists data (Polars DataFrame) to a specified path, handling optional types and metadata. It checks if the output is None based on type annotations, logs warnings if so, and otherwise saves the DataFrame to the path, either directly or along with associated metadata if required by the type annotation. | def dump_to_path(
self,
context: OutputContext,
obj: Union[pl.DataFrame, Optional[pl.DataFrame], Tuple[pl.DataFrame, Dict[str, Any]]],
path: "UPath",
partition_key: Optional[str] = None,
):
if annotation_is_typing_optional(context.dagster_type.typing_type) and (
... |
def annotation_is_typing_optional(annotation) -> bool:
return get_origin(annotation) == Union and type(None) in get_args(annotation)
def get_missing_optional_input_log_message(self, context: InputContext, path: "UPath") -> str:
return f"Optional input {context.name} at {path} doesn't exist in the filesystem... | The code's main task is to load data from a specified file path into a Polars DataFrame or LazyFrame, handling optional metadata and partitioning. It checks if the file exists, retrieves metadata if needed, filters data based on partition keys, and returns the result in the format specified by the context's type annota... | def load_from_path(
self, context: InputContext, path: "UPath", partition_key: Optional[str] = None
) -> Union[
pl.DataFrame,
pl.LazyFrame,
Tuple[pl.DataFrame, Dict[str, Any]],
Tuple[pl.LazyFrame, Dict[str, Any]],
None,
]:
if annotation_is_typing_optional(... |
def get_thread_parent(channel_id, thread_ts):
print("get_thread_parent function called!")
replies_url = 'https://slack.com/api/conversations.replies'
headers = {'Authorization': f'Bearer {slack_bot_token}'}
payload = {
'channel': channel_id,
'ts': thread_ts,
'limit': '1' }
... | This function handles Slack interactivity by processing incoming requests to verify URLs, detect button actions, and interact with Jira. It checks request types (JSON/form), decodes payloads, creates Jira tickets for "need_further_assistance" actions, and updates tickets with "bump_" actions. It sends Slack confirmatio... | def slack_interactivity():
# Check the request's content type
if request.headers.get('Content-Type') == 'application/json':
# Get the request data
request_data = request.get_json()
# Check if the request is a Slack event URL verification challenge
if "challenge" in re... |
def l(z,w):
return np.concatenate(((z.copy()+w.copy())/2.0, (z.copy()-w.copy())/2.0))
def R_phi(phi, z, w):
w = to_polar(w)
w[1] = w[1]+phi
w = to_cartesian(w)
return np.concatenate((z, w))
def get_rectangle_pts(phi, pts):
z = pts[0:2]
w = pts[2:]
pts = []
pts.append(z+w)
pts.app... | This function updates visual elements in a plot by recalculating and setting data for lines and rectangles based on transformed points. It computes current line segments, applies rotation transformations, updates term lines connecting original and transformed points, generates rectangle coordinates, and redraws the plo... | def update():
cur_L = l(point1, point2)
L1.set_data(cur_L[0], cur_L[1])
L2.set_data(cur_L[2], cur_L[3])
cur_L_phi = l(point1, point2)
cur_L_phi = R_phi(phi, cur_L_phi[0:2], cur_L_phi[2:])
L_phi1.set_data(cur_L_phi[0], cur_L_phi[1])
L_phi2.set_data(cur_L_phi[2], cur_L_phi[3])
term1_line.s... |
def get_phi(w):
raw_angle = np.arctan2(w[1], w[0])
raw_angle = (raw_angle)%(2.0*np.pi)
return raw_angle
def divide_rad(data, divisor):
data = to_polar(data)
data[0] = data[0]/divisor
data = to_cartesian(data)
return data
def add_phi(data, phi):
data = to_polar(data)
data[1] += p... | The function `g(z, w)` concatenates the input array `z` with a transformed version of `w`. The transformation involves retrieving the angle of `w` using `get_phi`, adding this angle to `w` via `add_phi`, scaling the result by `1/√2` using `divide_rad`, and then concatenating the modified `w` with `z` to produce a combi... | def g(z,w):
w_angle = get_phi(w)
return np.concatenate((z.copy(), divide_rad(add_phi(w.copy(), w_angle), np.sqrt(2.0)))) |
def __get_contained_ranges(self, node, start, end):
l = []
if node is None:
return l
if start <= node.start and end >= node.end:
t = (node.start, node.end)
l.append(t)
l = l + self.__get_contained_ranges(node.left, start, end)
l = l + self.__ge... | This code inserts a range into an AVL tree, handling four cases: inserting as a left/right child, adding to contained ranges, replacing a node's range while managing contained ranges, and raising an error for intersections. It maintains tree balance via rotations and updates node heights and balances. | def __insert(self, start, end, node):
# lesser range
if end < node.start:
if node.left is None:
nn = Node(start, end)
node.left = nn
nn.parent = node
else:
node.left = self.__insert(start, end, node.left)
... |
def read_ecg(index,folder_number=5 , denoise=False):
ecg_mat_file,ecg_annotation_file=get_ecg(index,folder_number)
mat = scipy.io.loadmat(ecg_mat_file)
np.seterr(invalid='ignore')
mat=mat['val']
if denoise == True:
mat = denoising_data(mat)
ecg=data()
ecg.index=index
ecg.mat=ma... | This function plots ECG data by reading the specified ECG file, handling time range and channel selection parameters, and using either a subplot or a formatted plot method based on inputs, finally displaying the plot. | def plot_ecg (index,time=None,channels=None,folder_number=5 , form='better'):
ecg= read_ecg(index , folder_number)
mat=ecg.mat
if time != None:
assert type(time)==tuple
else:
if ecg.samples != None :
time=(0,ecg.samples/ecg.sample_rate)
if channels != None:
... |
def get_location(folder_number):
folders=['1-Training_WFDB','2-Training_2','3-PhysioNetChallenge2020_Training_StPetersburg'
,'4-PhysioNetChallenge2020_Training_PTB','5- PhysioNetChallenge2020_Training_PTB-XL','6-PhysioNetChallenge2020_Training_E']
location= 'dataset\\'+folders[folder_number] +'\\'
... | This function identifies ECG records with coronary-related diagnoses by scanning files in a specified folder. It extracts ECG indices and their corresponding diagnoses from files containing specific label IDs (e.g., '164861001', '426434006'). It processes each file, checks for matching diagnoses, and compiles lists of ... | def find_coronaries(folder_number):
location=get_location(folder_number)[0]
number_of_files=int (len([name for name in os.listdir(location) if os.path.isfile(os.path.join(location, name))])/2)
coroneries=[]
coronery_ids=[]
label_of_coronaries=['164861001', '426434006' , '425419005' , '425623009','4... |
def get_location(folder_number):
folders=['1-Training_WFDB','2-Training_2','3-PhysioNetChallenge2020_Training_StPetersburg'
,'4-PhysioNetChallenge2020_Training_PTB','5- PhysioNetChallenge2020_Training_PTB-XL','6-PhysioNetChallenge2020_Training_E']
location= 'dataset\\'+folders[folder_number] +'\\'
... | This function filters ECG records by selecting those with diagnoses intersecting 'yekish_bashe' and excluding those intersecting 'minus'. It returns lists of filtered ECG IDs, their transformed diagnoses, and the count of matching records. | def find_plus_minus(yekish_bashe , minus=[], hamash_bashe=None ,folder_number=5):
location=get_location(folder_number)[0]
number_of_files=int (len([name for name in os.listdir(location) if os.path.isfile(os.path.join(location, name))])/2)
count=0
list_of_ids=[]
list_of_dxs=[]
for i in range (... |
def score_vals(vals:list):
'''
Takes in a 5 element list representing a row, column or diagonal and
returns its score.
'''
return score_straight(vals)+score_mults(vals)
def all_straights(vals:list) -> list:
'''
Takes in a list of 5 or less values and returns a list of tuples with all
t... | This function calculates the average score of a dice-hand evaluation by considering all possible dice combinations, weighting each scenario's score by its probability, and returning the expected value over all potential dice outcomes. | def avg_tot(vals:list):
vals = [i for i in vals if i!=0]
poss_worlds = pow(36, 5-len(vals))
#print(poss_worlds, len(vals))
if not vals:
return AVG_POINTS
if len(vals) == 5:
return score_vals(vals)
score_opps = all_straights(vals)+all_mults(vals)
#print(score_opps)
... |
def all_mults(vals:list) -> list:
'''
Takes in a list of 5 or less values and returns a list of tuples with all
the possible pairs (2 or more) and full houses that can be made using the
passed values and their corresponding scores.
'''
out =[]
u_vals = set(vals)
empties = 0
if not ... | The function `all_scores` generates all possible scoreable states from a 5-element list (`vals`), excluding states with the same score as the initial configuration. It recursively processes inputs, creating new states by appending values (2–12) when `vals` is empty or all zeros. For valid 5-element inputs, it combines ... | def all_scores(vals:list):
'''
Returns all possible additionally scoreable states from a 5 element
list (vals)with their corresponding scores. This excludes all states with
the same score as the initial state.
'''
if vals == [0]*5 or not vals:
out = []
for i in range(2,13):
... |
def set_strategies(self):
self.strategies.update({"38": MainFrame.strategy_wheel})
self.strategies.update({"2": MainFrame.strategy_key})
def register_hotkey(self, hotkey_list):
for hotkey_name in hotkey_list:
d = {
hotkey_name: {
"keytype": None,
... | The code initializes a GUI component by setting up a main frame, registering hotkeys, initializing strategies, and configuring event handling. It prepares the user interface and event callbacks for a larger application, likely involving keyboard shortcuts and dynamic behavior management. | def __init__(self, master):
self.master = master
self.frame = Frame(master, name="main")
self.frame.pack()
self.callbacks = {}
self.set_strategies()
self.register_hotkey(['hotkey_1', 'hotkey_2'])
self.init_ui()
self.register_event() |
def extract_columns_name_from_sql(cls, sql: str):
str_ = re.search(r"(?<=SELECT).*?(?=FROM)", sql, re.IGNORECASE)
if str_:
str_ = str_.group(0)
cols = str_.split(',')
cols = list(map(str.strip, cols))
return cols
return []
def extract_table_name_fr... | This function executes an SQL query and returns the results as a pandas DataFrame. It extracts column names from the SQL, resolves '*' to actual column names if specified, cleans column names, and constructs the DataFrame using the query results and column metadata. | def query_dataframe_by_sql(self,
sql: str,
with_column: bool = True) -> pd.DataFrame:
cols = self.extract_columns_name_from_sql(sql)
if '*' in cols and with_column:
table = self.extract_table_name_from_sql(sql)
cols = ... |
def read_shape_by_id(shape_id: int):
return exec_sql_read("select * from shape where id = ?", shape_id)
def insert_shapes(shapes: list[dict]):
exec_sql_write(
"insert into shape(name, no_sides, id) values(:name, :no_sides, :id)", shapes
)
def update_shapes(shapes: list[dict]):
exec_sql_write(
... | The main task of the code is to either insert a new shape or update an existing one based on its ID. If no shape with the given ID exists, it inserts the provided shape data. If a shape with the ID already exists, it updates the existing entry with the new data. The operation is idempotent, ensuring repeated calls prod... | def upsert_shape(shape: Shape):
"""Update or insert a shape object. Idempotent"""
res = read_shape_by_id(shape.id)
if len(res) == 0:
insert_shapes([shape.model_dump()])
else:
update_shapes([shape.model_dump()]) |
def index(self, node):
return (node[0], node[1], node[2])
def child_generator(self, node, cost):
# List to store all valid children
valid_children = []
# Generating the children
n1 = self.move1(node, cost)
n2 = self.move2(node, cost)
n3 = self.move3(node, cost)
... | The code implements the A* algorithm to find the shortest path from a start node to a goal node. It explores nodes by generating child nodes, sorting them by cumulative cost, and checking proximity to the goal. Upon reaching the goal, it backtracks to construct the final path, returning both the path and explored nodes... | def astar(self):
print('Started Searching... ')
explored_nodes = [(0, self.start_node, self.index(self.start_node), self.parent_node)]
explored.append(self.start_node)
valid_childs_dict[self.index(self.start_node)] = [self.start_node, self.parent_node]
cum_cost = 0
itr = ... |
def key_scheduler(self, key):
# expansion key size with n+1 round size
key_expanded_size = (self.round_num+1)*self.key_size
key_size_loop = self.key_size
# fill the init round with the key itself
expanded_key = bytearray(key_expanded_size)
expanded_key[:len(key)] = key
... | This code implements AES encryption by processing data in 16-byte blocks. It expands the key, applies initial round-key addition, executes 9 rounds of substitution, shifting, mixing columns, and round-key addition, then a final round with substitution and shifting. The encrypted data is formatted into bytes and returne... | def encrypt(self, data, key):
# Init block data
datablock = bytearray(16)
resultblock = bytearray(16)
# get the expanded key key scheduler
expanded_key = self.key_scheduler(key)
# turn original data into datablock with 16 length
for i in range(self.column_num):
... |
def key_scheduler(self, key):
# expansion key size with n+1 round size
key_expanded_size = (self.round_num+1)*self.key_size
key_size_loop = self.key_size
# fill the init round with the key itself
expanded_key = bytearray(key_expanded_size)
expanded_key[:len(key)] = key
... | This code decrypts data using AES decryption by applying inverse transformations (ShiftRow, SubBytes, MixColumn) across multiple rounds, incorporating an expanded key schedule. It processes data in 16-byte blocks, performs round-specific operations, and reconstructs the decrypted bytes. | def decrypt(self, data, key):
# Init block data
datablock = bytearray(16)
resultblock = bytearray(16)
# get the expanded key key scheduler
expanded_key = self.key_scheduler(key)
# turn original data into datablock with 16 length
for i in range(self.column_num):
... |
def get_whitelist_keywords(self):
"""
Get all whitelist keywords. If this word is used in the channel
purpose or topic, this will make the channel exempt from archiving.
"""
keywords = []
if os.path.isfile('whitelist.txt'):
with open('whitelist.txt') as fileco... | The main task of the code is to identify and archive inactive, non-whitelisted channels by checking their status against specified criteria. It logs a dry-run notice if enabled, writes archived channels to an audit CSV file with timestamps, and sends an admin report. The process involves iterating through all channels,... | def main(self):
"""
This is the main method that checks all inactive channels and archives them.
"""
if self.settings.get('dry_run'):
self.logger.info(
'THIS IS A DRY RUN. NO CHANNELS ARE ACTUALLY ARCHIVED.')
whitelist_keywords = self.get_whitelist_ke... |
def generate_sequence(self) -> None:
random.seed(time())
self.sequence.append(random.randint(0, constants.NUM_SENSORS - 1))
def flash_style(self, id: int, state: GameStates) -> None:
difficulty = int(self.difficulty.get())
sleep_time = (
constants.SLEEP_TIME * (6 - difficulty... | The code manages a game loop where the computer generates a sequence of actions (flashing lights) and waits for player input. It alternates between the computer's turn (generating and displaying a sequence) and the player's turn (inputting guesses). If the player has remaining lives, the game proceeds to the next level... | def game_logic(self):
while self.is_running:
if self.is_player_turn:
continue
self.generate_sequence()
for id in self.sequence:
if not self.is_running:
break
self.flash_style(id=id, state=GameStates.Guess)
... |
def act_on_proposal_modal(self):
modal = helper.ensure_find_element(self.driver, By.CSS_SELECTOR, "div.up-modal-dialog")
if modal:
helper.ensure_click(modal, By.CSS_SELECTOR, '.checkbox input[name="checkbox"]')
helper.ensure_click(modal, By.CSS_SELECTOR, 'button.up-btn.up-btn-pri... | The code automates interactions on a proposal page by repeatedly invoking modal actions, submitting proposal details (terms, duration, boosting), clicking specific buttons, closing windows, and navigating to predefined URLs (BEST_MATCH, SIGNUP) while handling potential exceptions. | def act_on_proposal_page(self):
# helper.ensure_find_element(self.driver, By.CSS_SELECTOR, 'button[aria-describedby="popper_125"]').click()
# time.sleep(5)
self.act_on_proposal_modal()
time.sleep(3)
self.act_on_proposal_modal()
try:
self.act_on_bid_additional_... |
def recognize_page(self):
try:
current_url = self.driver.current_url.split('?')[0]
print(current_url)
except:
curren_url = ""
if current_url == constant.UPWORK_URL_2 or current_url == constant.UPWORK_URL:
if helper.ensure_wait_for_element(self.driv... | The main task of the code is to recognize a page, handle recognition errors by labeling it as "unrecognized page," execute a "stun action" using the page ID, attempt to perform actions on the page, and then pause for 1 second. The function prioritizes error resilience by catching exceptions during page recognition and ... | def main_func(self):
try:
page_id = self.recognize_page()
except:
page_id = "unrecognized page"
print('page_id:', page_id)
self.stun_action(page_id)
try:
self.act_on_page(page_id)
except:
pass
time.sleep(1) |
def set_setting(self):
if self.Set_Popup:
self.set_popup()
if self.Set_Notification:
self.set_notification()
if self.Save_Pass:
self.save_pass_no()
def accept_cookies(self):
helper.ensure_click(self.driver, By.ID, 'onetrust-accept-btn-handler')
def mai... | The code initializes settings, navigates to a signup page, accepts cookies, and repeatedly executes a main function with a 2-second delay to perform automated tasks on a website. | def start(self):
self.set_setting()
time.sleep(1)
self.driver.get(constant.SIGNUP_URL)
time.sleep(1)
self.accept_cookies()
while True:
self.main_func()
time.sleep(2) |
def solveMarket(self, utilities = "linear", printResults = True, rho = 1):
"""
Parameters:
utilities(string): Denotes the utilities used to solve market
Currently options are 'quasi-linear' and 'linear'
Returns:
A tuple (X, p) that corresponds to the optimal matrix o... | The function `getDS` computes and validates the total demand (D) and supply (S) for all goods in an economy using a specified utility structure (e.g., quasi-linear or linear). It derives optimal allocations and prices via `solveMarket`, calculates D as the sum of goods' value (X*p), and computes S as the product of goo... | def getDS(self, utilities = "quasi-linear"):
"""
Takes as input the utility structure and returns the demand and supply
(in dollars) of all goods in the economy.
Parameters:
utilities(string): Denotes the utilities used to solve market
Currently options are 'quasi-li... |
def run_and_process_csv_detail_extraction():
# I had to add this retry because the AI occasionally gives me non-standard returns. I'll finetune it as part of v2, but for now, I just take
# five shots at it and it almost always gets one of them right.
max_retries = 5
retry_count = 0
while retry_co... | The function `aggregate_and_export_letter_and_CSV` consolidates data from multiple AI-generated processes (CSV extraction, qualification analysis), sanitizes it, and exports results to formats like TXT, Excel, and JSON. It captures filenames and URLs for hyperlinks, handles errors, and displays success/failure messages... | def aggregate_and_export_letter_and_CSV():
# This is the 'put-it-all-together' function that sends a bunch of ai calls, sanitizes the data,
# and then goes out and exports the files. It's mostly just the logic around a chain of other functions, although
# there's some cleverness about the getting the filep... |
def display_final_draft():
global results, everything_output_text_widget
everything_output_text_widget.delete("1.0", tk.END)
if results:
cover_letter_generation = results.get('cover_letter_generation', 'No generated cover letter available.')
everything_output_text_widget.insert(tk.END, ... | This function initializes a GUI frame with interactive elements for a cover letter application. It creates labels, a text widget for output, and buttons to read/export cover letters, regenerate content, or navigate between frames (e.g., ResumeUpload, JobDescUpload). The global text widget is set up to display results, ... | def initialize_loop_frame(frame, raise_frame_func):
# I called this loop, because this is where it 'loops' back - if it wouldn't be super confusing, I've have called it output
upload_label = ttk.Label(frame, text="Loop Frame")
upload_label.grid(row=0, column=0, columnspan=2)
global everything_output_... |
def model_predictions(self, backbone_feats, images_whwh, x, t, x_self_cond=None, clip_x_start=False):
x_boxes = torch.clamp(x, min=-1 * self.scale, max=self.scale)
x_boxes = ((x_boxes / self.scale) + 1) / 2
x_boxes = box_cxcywh_to_xyxy(x_boxes)
x_boxes = x_boxes * images_whwh[:, None, :]... | The main task of the code is to perform DDIM (Denoising Diffusion Implicit Models) sampling for object detection, generating predicted bounding boxes, class labels, and masks by iteratively denoising random noise through a diffusion model. It includes filtering low-confidence boxes, ensemble prediction aggregation, non... | def ddim_sample(self, batched_inputs, backbone_feats, images_whwh, images, clip_denoised=True, do_postprocess=True):
batch = images_whwh.shape[0]
shape = (batch, self.num_proposals, 4)
total_timesteps, sampling_timesteps, eta, objective = self.num_timesteps, self.sampling_timesteps, self.ddim_sa... |
def preprocess_image(self, batched_inputs):
"""
Normalize, pad and batch the input images.
"""
images = [self.normalizer(x["image"].to(self.device)) for x in batched_inputs]
images = ImageList.from_tensors(images, self.size_divisibility)
images_whwh = list()
for ... | This code processes input data through a neural network for object detection or segmentation. It extracts features from images, prepares proposals, and handles both training (computing losses) and inference (generating predictions) modes. During training, it calculates losses using predicted logits, boxes, and kernels ... | def forward(self, batched_inputs, do_postprocess=True):
"""
Args:
batched_inputs: a list, batched outputs of :class:`DatasetMapper` .
Each item in the list contains the inputs for one image.
For now, each item in the list is a dict that contains:
... |
def fightMenu():
fight = input("What do You do??\n1: Upper Cut\n2: Attack With Pirougue Paddle\n3: Throw a Delicous Yet Dangerous Seasoning Blend at Her\n")
if fight == "1":
print("\n(Marie Takes an Uppercut)")
villain1.takeDamage4()
sleep(1)
print("\n Marie's Health is now", villain1.health... | The main task of the code is to manage a text-based game loop where a player controls "Boudreaux" (hero) interacting with "Marie Laveau" (villain). The loop allows the player to harvest crawfish for health, view stats, or engage in combat. During combat, the player chooses to fight or flee, with branching outcomes incl... | def mainMenu():
while hero1.health > 0 and villain1.health > 0:
menuChoice = input("What Would You Like to Do?\n1: Harvest Crawfish for Health\n2: View Boudreaux's Stats:\n3: View Marie Laveau's Stats\n4: Take on Marie Laveau!")
if menuChoice == "1":
print("\nThibodeau: Welcome to da Annual Crawfish Ha... |
def get_all_processed_data():
files = glob.glob(r'C:\Users\trist\OneDrive\Documents\game_data\valorant_raw/*.json')
all_records = list()
agent_records = list()
for file in files:
with open(file, 'r') as f:
json_data = json.load(f)
json_data = json.loads(json_data)
... | The code trains a machine learning model using cross-validation on agent game records, splits data into training and validation sets, trains multiple models with KFold, aggregates predictions, averages results, evaluates accuracy against validation labels, logs the accuracy, and saves the trained models. | def train_model():
all_records, all_agent_records = get_all_processed_data()
all_agent_records_df = pd.DataFrame.from_dict(all_agent_records)
train_df, val_df = train_test_split(all_agent_records_df, random_state = 1, test_size=.1)
models = list()
preds_list = list()
kf = KFold(n_splits=k, ra... |
def doesExitsElement(driver, how, what):
i = 1
while not isExitsElement(driver, how, what):
sleep(1)
i = i+1
if i >= 10:
return False
else:
return True
def myClick(driver,how,what):
try:
el = getElement(driver, how, what)
el.click()
except ... | This function automates app opening by skipping guides, navigating through a welcome screen via swipes, clicking "Go to Shop" when available, waiting for loading, and dismissing updates/pop-ups by clicking "Cancel" if present. | def openApp(driver):
# skip
if doesExitsElement(driver, By.ID, "guideLayout"):
myClick(driver, By.ID, "skipBtn")
# welcom
if doesExitsElement(driver, By.ID, "ag_ll_dotlayout"):
while not isExitsElement(driver, By.ID, "agi_bn_goshop"):
# swip right
mySwipeToRig... |
def isRoman(val):
## check if tuple.count vs str.count vs iterate str time complexity
## check regex vs brute force pattern match
# check if these make difference in time complexity:
#thousand.. 'M{0,3}'
#hundred.. '(C[MD]|D?C{0,3})' = (CM|CD|D?C{0,3})
#ten.. '(X[CL]|L?X{0,3})' = (XC|XL|L?X... | The code processes input lines to build dictionaries for converting intergalactic units to Roman numerals (`galaxyRoman`) and metals to credits (`metalConvert`). It validates entries, extracts conversion rules, and collects evaluation queries. Finally, it uses these dictionaries to convert specified values via `convert... | def translateGalactic(rlines,mlines):
# readS lines from input file as tuple
galaxyRoman = {} # intergalatic to Roman dict
metalConvert = {} # metal to credits
originalVals = []
# --- CHECK TYPE OF ENTRY and validate --------
for i in range(len(rlines)):
entry = tuple(str(rlines[i... |
def isRoman_Helper(val:str) -> bool:
## check if tuple.count vs str.count vs iterate str time complexity
## check regex vs brute force pattern match
# check if these make difference in time complexity:
#thousand.. 'M{0,3}'
#hundred.. '(C[MD]|D?C{0,3})' = (CM|CD|D?C{0,3})
#ten.. '(X[CL]|L?X{... | The function `translateGalactic` processes input lines to build dictionaries for Roman numeral-to-credits and metal-to-credits conversions. It validates entries, constructs `galaxyRoman` (unit mappings) and `metalConvert` (metal value mappings), then evaluates queries using these dictionaries. It returns converted valu... | def translateGalactic(rlines,mlines):
# readS lines from input file as tuple
galaxyRoman = {} # intergalatic to Roman dict
metalConvert = {} # metal to credits
originalVals = []
# --- CHECK TYPE OF ENTRY and validate --------
for i in range(len(rlines)):
entry = tuple(str(rlines[i]... |
def pack_menu() -> None:
tk.Label(f1, text='Main Menu', ).pack()
tk.Button(f1, text='view rundown', command=lambda:raise_frame(f5)).pack()
tk.Button(f1, text='query a team', command=lambda:raise_frame(f2)).pack()
tk.Button(f1, text='query an upcoming match', command=lambda:raise_frame(f3)).pack()
tk... | The main task of the code is to initialize a Tkinter GUI by configuring grid layouts for multiple frames, setting their sizes, arranging them in the window, packing various UI components, and starting the main event loop to display the application. | def initialize_tkinter() -> None:
f2.grid_columnconfigure((0, 1, 2, 3, 4, 5), weight=1)
f3.grid_columnconfigure((0, 1, 2, 3, 4, 5), weight=1)
f5.grid_columnconfigure((0, 1, 2, 3, 4, 5), weight=1)
for frame in (f1, f2, f3, f4, f5):
frame.config(width=300, height=300)
frame.grid(row=0, co... |
def fill_rows(self,df):
df.fillna(method='ffill')
df.fillna(method='bfill')
return(df)
def select_column(self,df):
return(df.loc[ : , df.columns != 'TIMESTAMP'])
def read_file(self,address):
df = pd.read_csv(address)
if(df.empty):
print ('CSV file %s is empty'... | This code initializes a data ingestion system by reading and processing multiple files (calendar, headset, labels, settings) based on the specified mode (DEVELOPMENT or EXECUTION). It merges data, sends processed records to a preparation URL, and optionally labels to a monitoring URL. In DEVELOPMENT mode, it generates ... | def __init__(self,files,num_of_row,PREP_URL,MONITORING_URL,mode,save_file=False,show_plot=False):
if mode == 1: # DEVELOPMENT
print("Running Ingestion system - DEVELOPMENT MODE")
self.data_calendar = self.fill_rows(self.select_column(self.read_file(files[0])))
self.data_head... |
def add_stop_symbol(sentences):
""" adding STOP_SYMBOL at the end of every sentence, and removing '.' """
for sent in sentences:
if sent[-1] == '.':
sent[-1] = STOP_SYMBOL
else:
sent.append(STOP_SYMBOL)
def remove_punctuations(list_sentences):
"""
:param list_sen... | The code generates a 10-word sentence using an n-gram language model (default n=4) from a specified dataset (Brown or Gutenberg). It preprocesses the data by adding stop symbols, removing punctuations, and then employs a helper function to create a random sentence based on n-gram probabilities. The main task involves t... | def main(data_set, n=4):
"""
predicts a sentence of 10 words using n-gram model, according to n
:param data_set:
:param n:
:return:
"""
if data_set == BROWN_DATA_SET:
sentences = list(brown.sents(brown.fileids()))
elif data_set == GUTENBERG_DATA_SET:
sentences = list(gute... |
def get_position_mlb(self, player):
try:
if self.is_position_attribute_corect(player.position):
if player.position in MLB_OUTFIELD_POSITIONS:
return 'OF'
else:
return player.position
else:
position = ... | This method determines a player's position based on their league by delegating to league-specific functions. It checks the `self.league` attribute and calls `get_position_mlb`, `get_position_nfl`, or `get_position_nba` accordingly. If the league is unrecognized, it returns an empty string. The core task is to retrieve ... | def get_position(self, player):
if self.league == 'MLB':
return self.get_position_mlb(player)
elif self.league == 'NFL':
return self.get_position_nfl(player)
elif self.league == 'NBA':
return self.get_position_nba(player)
else:
return '' |
def get_list_of_team_details(self) -> list:
team_details = []
for team in self.league_teams:
if team.name == "Oakland Raiders":
team_details.append({"team_abbreviation": team.abbreviation, "team_name": "Las Vegas Raiders"})
else: team_details.append({"team_abbrevi... | The main task of the code is to aggregate all team rosters into a single league roster dictionary. It iterates through each team, retrieves its roster and name, generates a team-specific player dictionary, and merges it into a cumulative league-wide dictionary using dictionary unpacking. The function returns the consol... | def create_league_player_dict(self):
print("Start of Create League Player")
for team_details in self.get_list_of_team_details():
print("Starting:", team_details)
team_roster = self.get_team_roster(team_abbreviation=team_details["team_abbreviation"])
team_name = self.g... |
def _set_league_teams_and_roster_package(self, league : str):
if league == 'MLB':
league_teams = MLBTeams("2020")
Roster_Package = MLBRoster
# NO 2020 Team List as of 8/11, manuallly add Las Vegas Raiders
elif league == 'NFL':
league_teams = NFLTeams("2019... | The code initializes a league object, sets up team and roster data structures, and optionally builds and manually fixes a roster dictionary if `get_rosters` is True, ensuring valid team names and handling duplicate player entries. | def __init__(self, league: str, get_rosters: bool = False):
super().__init__(league)
self.league = league.upper()
self.valid_team_names = set()
self.league_teams, self.Roster_Package = self._set_league_teams_and_roster_package(league)
self.league_roster_dict: dict = {}
se... |
def isfull(sudoku):
for i in range(0,len(sudoku)):
if sudoku[i] == 0:
return False
return True
def check_availNum_1(sudoku):
'''check if the length of the available number list is 1, and if so, update sudoku'''
pointList = initPoint(sudoku)
for i in range(0,len(pointList)):
... | The main task of the code is to update a Sudoku grid by filling cells with the only available number that can fit in them. It repeatedly checks for such cells, updates the grid, and stops when no more changes occur. The function ensures the Sudoku is filled with valid single-number placements until it reaches a state w... | def update_1_availNum_sudoku(sudoku):
'''update the sudoku with the only available number'''
if isfull(sudoku):
#print('success')
#showSudoku(sudoku)
return
else:
while True:
sudoku_old = sudoku[::]
check_availNum_1(sudoku)
... |
def isfull(sudoku):
for i in range(0,len(sudoku)):
if sudoku[i] == 0:
return False
return True
def check_unique_avialNum(sudoku):
'''compare the available number lists within the same row, column and block, update sudoku with the unique candidate'''
pointList = initPoint(sudoku)
... | The main task of the code is to solve a Sudoku puzzle by iteratively checking and updating cells with available numbers until no further changes occur. It compares available number lists to identify unique placements, updates the Sudoku grid, and repeats this process until the grid is either fully solved or no more upd... | def solve_part(sudoku):
'''solve the sudoku by comparing the available number lists'''
if isfull(sudoku):
#print('success')
#showSudoku(sudoku)
return
else:
while True:
sudoku_old = sudoku[::]
check_unique_avialNum(sudoku)
update_1_ava... |
def solve_part(sudoku):
'''solve the sudoku by comparing the available number lists'''
if isfull(sudoku):
#print('success')
#showSudoku(sudoku)
return
else:
while True:
sudoku_old = sudoku[::]
check_unique_avialNum(sudoku)
update_1_ava... | The function `count_solve` checks if a Sudoku puzzle has **at most one unique solution**. It first solves the Sudoku partially, then removes the value of the first empty cell (0) from its available candidates. If solving the modified Sudoku again results in a complete solution, it indicates **a second valid solution ex... | def count_solve(sudoku,pointList):
'''control the solution of a sudoku is nomore than 1'''
sudoku_try = sudoku[::]
pointList_old = pointList[::]
#solve_sudoku(sudoku_try,pointList) #first solution
solve_part(sudoku_try) #faster
if isfull(sudoku_try): #remove the first0 can... |
def build_max_heap(a):
heap_size = len(a)
for i in range(heap_size//2, 0, -1):
max_heapify(a, heap_size, i)
def build_min_heap(a):
heap_size = len(a)
for i in range(heap_size//2, 0, -1):
min_heapify(a, heap_size, i)
def delete_max(a):
heap_size = len(a)
if heap_size == 0:
... | The code demonstrates building and manipulating max/min heaps from an array. It initializes two heaps, constructs a max heap and a min heap, then performs deletion of the maximum and minimum elements, respectively, showcasing heap operations like heapify and removal. | def main():
# print heap starting with the root at index 1
# https://stackoverflow.com/questions/22900388/why-in-a-heap-implemented-by-array-the-index-0-is-left-unused
# having the root at 0 rather than at 1 costs you an extra add to find the left child, and an extra subtraction to find the parent.
pri... |
def findAtom(self, point):
if not point:
return None
items = self.items(self.mapFromScene(*point))
if items:
for item in items:
if item.itemType == 'atom':
return item
return None
def deleteAtom(self, atom):
bounds = ato... | This code handles mouse press events in a graphics scene, enabling interactive creation/deletion of atoms, bonds, and polygons based on mouse button and mode. It supports right-click deletion, left-click creation (atoms/bonds/polygons) in different modes, and drag-based region selection/movement, with logic for item de... | def mousePressEvent(self, event):
self.xStart = self.mapToScene(event.pos()).x()
self.yStart = self.mapToScene(event.pos()).y()
item = self.itemAt(event.pos())
if event.button() == Qt.RightButton:
if self.region:
self.scene().removeItem(self.region)
... |
def loadFiles(label, start, size):
for i in range(start, start+size):
if (i > 0 and i <= 9):
files.append(label + "_000" + str(i) + ".jpg")
if (i >= 10 and i <= 99):
files.append(label + "_00" + str(i) + ".jpg")
if (i >= 100 and i <= 999):
files.append(label + "_0" + str(i) + ".jpg")
labels.append(la... | The main task of the code is to evaluate a classification model's accuracy by stratified dataset splitting, comparing pairwise class predictions against test sets. It loads labeled data, splits into training/test sets, summarizes training data, and iterates through class pairs to generate predictions. It tracks correct... | def main():
classList = ["069", "053", "113", "202", "096", "145"]
# classList = ["069", "113", "202"]
sizePerClass = 80
splitRatio = .8
numClassList = []
sizeList = []
for x in classList:
loadFiles(x, 1, sizePerClass)
numClassList.append(int(x))
sizeList.append(sizePerClass)
load_images(files, labels)
... |
def get_active_player(self):
"""Returns the active player whose turn it is"""
return self._active_player
def show_moves_on_board(self, targetLocation, indexNotation=False):
"""
Displays current Xiangqi board arrangement and possible moves for piece at targetLocation,
defaulted to... | The main task of the code is to facilitate one round of a turn-based game, allowing a player to input move locations, view possible moves, and check game status. It operates in a loop if continual_play is True, handling user commands like 'HELP' to display moves or 'EXIT' to quit. The function processes 'from' and 'to'... | def play_game(self, continual_play=False):
"""
Displays one round played by player, displaying baord, taking in location for making a move,
and input options to see possible moves and exit method if continual play is set to True
continual_play: By default, only plays one round, but set t... |
def initialization(A,B,distance_function,patch_size):
h,w = A.shape[0:2]
h_nnf = h-patch_size//2*2
w_nnf = w-patch_size//2*2
nnf = np.zeros((h_nnf,w_nnf,3))
for i in range(h_nnf):
for j in range(w_nnf):
# initialize with random values and calculate distance
nnf_i = np... | This function approximates a nearest neighbor field (NNF) between two images A and B using iterative refinement. It initializes the NNF, performs multiple iterations to update correspondences based on distance and patch size, and optionally reconstructs the image. The result is an NNF matrix representing pixel correspo... | def nnf_approx(A,B,nnf=None,distance_function=ssd,patch_size=5,iterations=5,reconstruct=False):
print("initilaization")
nnf = initialization(A,B,distance_function,patch_size) if nnf is None else nnf
for i in range(iterations):
print("==========iteration {}/{} ==========".format(i+1,iterations))
... |
def solve_captcha_challenge(self, tracking_number):
print('=> Solving Captcha Challenge...')
while True:
# Get the captcha challenge and capcode
slidingImage, backImage, capcode = self.get_captcha_challenge()
# getting captcha image solution
xspot = self.... | The main task of the code is to retrieve EMS tracking results for a given tracking number by solving a CAPTCHA challenge, generating a security ticket, and making a POST request to the EMS tracking API with language-specific parameters. It handles errors, returns JSON results on success, or error messages on failure, i... | def get_tracking_result(self, tracking_number):
print('=> Get Tracking Result:', tracking_number)
try:
# Solve captcha challenge
xspot, capcode = self.solve_captcha_challenge(tracking_number)
# Get the timestamp to generate the ticket
timestamp = self.ge... |
def calc_speed_profile(cx, cy, cyaw, target_speed):
speed_profile = [target_speed] * len(cx)
direction = 1.0 # forward
# Set stop point
for i in range(len(cx) - 1):
dx = cx[i + 1] - cx[i]
dy = cy[i + 1] - cy[i]
move_direction = math.atan2(dy, dx)
if dx != 0.0 and dy !... | This code implements a linear Model Predictive Control (MPC) system for trajectory tracking. It generates a reference path using cubic splines, calculates a speed profile, and iteratively updates a vehicle's position, velocity, and control inputs (steering, acceleration) to follow the path. Real-time plotting visualize... | def main():
ax = [0.0, 20.0, 40.0, 55.0, 70.0, 85.0]
ay = [0.0, 50.0, 20.0, 35.0, 0.0, 10.0]
cx, cy, cyaw, ck, s = \
cs.calc_spline_course(ax, ay, ds=P.d_dist)
sp = calc_speed_profile(cx, cy, cyaw, P.target_speed)
ref_path = PATH(cx, cy, cyaw, ck)
node = Node(x=cx[0], y=cy[0], yaw=cya... |
def calc_speed_profile(cx, cy, cyaw, target_speed):
"""
design appropriate speed strategy
:param cx: x of reference path [m]
:param cy: y of reference path [m]
:param cyaw: yaw of reference path [m]
:param target_speed: target speed [m/s]
:return: speed profile
"""
speed_profile = [... | The code implements a Linear Model Predictive Control (MPC) system for path following. It generates a reference trajectory using cubic splines, then iteratively computes optimal steering and acceleration commands to guide a vehicle along the path. The simulation updates the vehicle's state, visualizes its trajectory in... | def main():
ax = [0.0, 15.0, 30.0, 50.0, 60.0]
ay = [0.0, 40.0, 15.0, 30.0, 0.0]
cx, cy, cyaw, ck, s = cs.calc_spline_course(
ax, ay, ds=P.d_dist)
sp = calc_speed_profile(cx, cy, cyaw, P.target_speed)
ref_path = PATH(cx, cy, cyaw, ck)
node = Node(x=cx[0], y=cy[0], yaw=cyaw[0], v=0.0)
... |
def check_play_button(state,play_button,mouse_x,mouse_y,ship,aliens,ai_Settings,screen,bullets,sb):
button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
if button_clicked and not state.game_active:
ai_Settings.init_dynamic()
p.mouse.set_visible(False)
state.rest_game()
... | This function processes Pygame events to handle user inputs, including quitting the game, clicking the play button, and keyboard actions. It checks for mouse clicks, key presses, and key releases, triggering corresponding game responses like starting the game, moving the ship, or firing bullets. | def check_event(state,play_button,ship,aliens,ai_Settings,screen,bullets,lose_button,sb):
for event in p.event.get():
if event.type==p.QUIT:
sys.exit()
elif event.type==p.MOUSEBUTTONDOWN:
mouse_x,mouse_y=p.mouse.get_pos()
check_play_button(state,play_button,mouse_... |
def check_fleet_edges(ai_Settings,aliens):
for alien in aliens.sprites():
if alien.check_edge():
change_fleet_direction(ai_Settings,aliens)
break
def check_ship_alien_collisions(ship,aliens,ai_Settings,screen,bullets,state,sb):
if spritecollideany(ship,aliens):
ship_hit(s... | The function updates alien movement, checks for edge collisions, updates their positions, detects ship-alien collisions, and verifies if aliens have reached the screen's bottom, triggering game state changes or actions like resetting the game. | def update_aliens(aliens,ai_Settings,ship,screen,bullets,state,sb):
check_fleet_edges(ai_Settings,aliens)
aliens.update()
check_ship_alien_collisions(ship,aliens,ai_Settings,screen,bullets,state,sb)
aliens_reach_bottom(ship,aliens,ai_Settings,screen,bullets,state,sb) |
def num_class(df, predict_attr):
print("num_class was called!")
p_df = df[df[predict_attr] == 1]
n_df = df[df[predict_attr] == 0]
return p_df.shape[0], n_df.shape[0]
def choose_attr(df, attributes, predict_attr):
print("choose_attr was called!")
max_info_gain = -100000
... | The code recursively constructs a decision tree by selecting the attribute with the highest information gain as the splitting criterion. It splits the dataset into subsets based on the chosen attribute's threshold, creates internal nodes for splits, and terminates with leaf nodes when all instances in a subset are of t... | def build_tree(df, cols, predict_attr):
print("build_tree was called!")
# Get the number of positive and negative examples in the training data
p, n = num_class(df, predict_attr)
# If train data has all positive or all negative values
# then we have reached the end of our tree
... |
def majority(self, D):
elem, counts = np.unique(D["y"], return_counts=True)
return elem[list(counts).index(max(counts))]
def get_attribute(df, attributes, outColName):
max_info_gain = -100000
threshold = 0
# Test each attribute
for att in attributes[:(len(attributes)-1)]:
print(a... | This code recursively constructs a decision tree with a maximum depth of 20 to prevent overfitting. It splits data using attributes that maximize information gain, creates leaf nodes for homogeneous subsets or when stopping conditions are met (e.g., small dataset size or max depth reached), and returns the constructed ... | def GrowTree(self, height, D, attributes):
#max height is 20 to avoid overfitting
max1 = 20
#if homogenous, create Leaf
elem = np.unique(D["y"])
if (len(elem) == 1):
return Node(data=self.majority(D),name="Leaf")
#choose column and value to s... |
def make_prediction(self, token: int, activities: deque, durations: deque, resources: list, n_branches: int):
# Get sequence encoding
x_activities, x_durations, x_tokens, x_resources = self.encode_to_predict(
token, activities, durations, resources
)
# Get predictions
... | The code generates predictions for future activities in a session by exploring multiple branches constrained by time limits and probabilities. It processes session traces, extracts features like activities and timestamps, filters viable branches, combines them, and returns top candidates sorted by probability, adhering... | def predict(self, session: dict, time_limit: float, t_eps: float, min_prob: float = 0., n_branches: int = 3):
"""
Alternative prediction where ONLY the time limit is looked at
:param min_prob: Minimum probability to be reached to take a branch into account
:param n_branches: Maximum numb... |
def get_modules_info(path, depth=1):
""" Return a digest of each installable module's manifest in path repo"""
# Avoid empty basename when path ends with slash
if not os.path.basename(path):
path = os.path.dirname(path)
modules = {}
if os.path.isdir(path) and depth > 0:
for module i... | The code processes command-line arguments to either list modules (with optional filters for applications/localization) or collect addons from specified paths, excluding specified modules, then outputs the result as a comma-separated list. | def main(argv=None):
if argv is None:
argv = sys.argv
params = argv[1:]
if not params:
print(__doc__)
return 1
list_modules = False
application = None
localization = None
exclude_modules = []
while params and params[0].startswith('-'):
param = params.pop... |
def on_leftclick(self, i, j, event):
val = self.get_value(self.master.get_cell(self.generation, i, j))
if (val < 5):
if val == 4:
val = 0
else:
val += 1
val = val % 4
else:
return
self.field[i][j].set('... | This method creates a Tkinter label widget for a grid cell at position (i,j), configures its appearance, binds left/middle/right click events to handle user interactions, and returns the label for display in a GUI application. | def tile(self, i, j):
L = tk.Label(self, textvariable=self.field[i][j], relief=tk.RAISED, fg=fgfield[4], bg=bgfield[4], width=3, height=1)
L.grid(row=i, column=j, ipadx=4, ipady=5)
L.bind('<Button-1>',lambda e,i=i,j=j: self.on_leftclick(i, j, e))
L.bind('<Button-2>',lambda e,i=i,j=j: sel... |
def on_keyhandler(self, event):
if (self.i_saved < 0):
return
i = self.i_saved
j = self.j_saved
var = self.master.get_cell(self.generation, i, j)
val = self.get_value(var)
if (val == 5):
if (event.keysym == 'Escape'):
self.check_em... | This code initializes a grid-based interface by retrieving row/column dimensions, validating non-zero values, creating a 2D field of StringVars for cell data, setting up labels for each cell, binding keyboard/focus events, and organizing tiles in a grid structure for interactive board manipulation. | def create(self):
row = self.master.row.get()
column = self.master.column.get()
if (row == 0) or (column == 0):
raise "Board.new called with zero dimension(s)"
self.generation = self.master.generation.get()
self.field = [ [tk.StringVar(self,' ') for _ in range(colum... |
def get_message(email_id, mail):
typ, data = mail.fetch(email_id, '(RFC822)')
return data
def get_email_message(message):
raw_email = message[0][1]
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
return email_message
def get_recipients(ema... | The code processes an email by extracting its subject, sender, and text content. It handles both multipart and non-multipart emails, identifies the sender's email, and saves attached files. The text is extracted from the first non-attachment text/plain part, and the user associated with the sender's email is retrieved.... | def process_message(email_id, mail):
message = get_message(email_id, mail)
email_message = get_email_message(message)
subject = str(make_header(decode_header(email_message.get('Subject', ''))))
text = ''
recipients = get_recipients(email_message)
user = User.find_one({"notify_email": recipients... |
def population(guild, quest, count):
party_pool = []
while len(party_pool) != count:
party_pool.append(individual(guild, quest))
return party_pool
def grade(population, quest):
total_fitness = 0
for party in population:
# print("The party fitness is: {}" .format(fitness(party, quest)))
total_fitn... | The code implements a genetic algorithm to evolve a population of "parties" (teams) based on a quest and guild context. It generates an initial population, selects parent parties via fitness-based selection, performs crossover to create offspring, and returns the best-performing party. The process aims to iteratively i... | def evolve(pop_count, guild, quest):
new_population = []
party_pool = population(guild, quest, pop_count)
avg_fitness = grade(party_pool, quest)
parent_parties = selection(party_pool, quest, avg_fitness)
while(parent_parties):
parent_1 = choice(parent_parties)
parent_parties.remove(parent_1) #en... |
def pickBestQueue(self) -> np.array:
self._queue = self._queue.reshape(self.arrayShape)
f = self.f()
index = [e for e in range(0, len(f)) if f[e] == f[np.argmin(f)]]
i = random.choice(index)
top = np.copy(self._queue[i])
for n in range(0, len(self._queue), 1):
... | The function `visitTopQueue` performs a breadth-first search (BFS) by dequeuing the best node, checking if it solves the problem, marking it as visited, and enqueuing its children. If the queue is empty, it raises an error. It handles exceptions by returning an empty array. The core task is to explore nodes in BFS orde... | def visitTopQueue(self, tree: dict, graph: dict, settings: Settings) -> None:
try:
if len(self._queue) == 0: self._err.BFSQueueEmpty()
top = self.pickBestQueue()
if self.checkSolved(top): return top
self._visitedNode = np.append(self._visitedNode, top).reshape(sel... |
def build_conv_layer(self, inputData, num):
# Passes each filter across the input data to create the respective channels. Then
# passes more filters over these channels to create the hidden maxout layer
for c in range(len(self.convLayers[num])):
n = c + (num... | This code processes input data through multiple convolutional and max-pooling layers in a neural network. It iteratively builds convolutional layers, applies max-pooling, and accumulates intermediate outputs. After constructing all layers, it creates a final pooling layer and passes the processed data to a deeper netwo... | def feed_forward(self, inputData):
self.inputData = [inputData]
for num in range(self.numMaxOut):
self.build_conv_layer(inputData, num)
self.create_max_pooling(num)
if num < self.numMaxOut - 1:
self.inputData.append(self.maxOut[nu... |
def import_cards(self):
with open(self.args.import_from, 'r') as file:
counter = 0
for line in file:
k, v = line.split(',')
self.cards_dict[k] = str(v).replace('\n', '')
counter += 1
self.logger.print_and_log(f"{counter} cards h... | This code runs a loop to process user actions for a flashcard application, handling tasks like adding/removing cards, importing/exporting data, logging, tracking hardest cards, and resetting stats. It continues until the user inputs "exit," then saves logs and exports cards if specified. | def start(self):
while self.action != "exit":
if self.args.import_from:
self.import_cards()
self.logger.print_and_log(
'Input the action (add, remove, import, export, ask, exit, log, hardest card, reset stats):')
action = self.logger.logged_i... |
def _check_force_weights(self):
if self.force_weights is None:
return
if len(self.force_weights) != self.n_clusters:
raise ValueError(
(
"len(force_weights)={} but must equal "
"n_clusters={}".format(len(self.force_weights)... | This code performs mixture of von Mises Fisher clustering on input data X by normalizing data if required, validating parameters, and calling the movMF function to compute cluster centers, labels, and model parameters. It returns the fitted model with updated attributes like cluster centroids, posterior probabilities, ... | def fit(self, X, y=None):
"""Compute mixture of von Mises Fisher clustering.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
"""
if self.normalize:
X = normalize(X)
self._check_force_weights()
random_state... |
def getEmpowerBuildOptions(self) -> List[Tile]:
buildLocationOptions = []
islandTilesSet = set(self.lockdownState.islandTiles)
for tile in self.gameState.myTiles:
minCol = self.lockdownState.lockdownCol + 1 if self.gameState.startedOnLeftSide else self.lockdownState.lockdownCol - 1
... | The function uses remaining materials to build recyclers and spawn bots in enemy territory to empower an invasion. It calculates available spawn actions, selects optimal build/spawn locations, prioritizes building recyclers near spawn points, then spawns bots with leftover materials, adjusting for lockdown status and r... | def useRemainingMatsToEmpowerInvade(self):
LOG.debug("== Starting empower")
numSpawns = Lockdown.getNumberOfSpawnActionsAvailable(self.lockdownState.matsRemaining,
self.lockdownState.numRecyclersLeftToBuild)
LOG.debug(f"can build/spa... |
def tryToPlaceRecyclers(self):
# First step, go build recyclers to block them out on part of the map
orderedRecyclerBuildLocations = self.calculateRecyclerPlacementOrder()
LOG.debug("== Ordered recycler tiles: " + str(orderedRecyclerBuildLocations))
for buildLocation in orderedRecyclerBu... | The main task of the code is to execute a sequence of strategic actions in a game turn, including placing recyclers, building a defensive bot wall, capturing islands, invading, moving bots, reclaiming territory, and empowering invasion using remaining resources. It logs timing and material (mats) usage for each step to... | def takeActions(self, turnNumber: int):
LOG.debug(f"{self.lockdownState.matsRemaining} mats remaining at start")
tic = time.perf_counter()
self.tryToPlaceRecyclers()
toc = time.perf_counter()
LOG.debug(f"{toc - tic:0.5f} seconds")
LOG.debug(f"{self.lockdownState.matsRemai... |
def get_class_name(self, frame):
class_obj = self.get_class_obj(frame)
# print(dir(class_obj))
if class_obj:
class_name = class_obj.__name__
else:
class_name = "None"
return class_name
def handle_call(self, frame, key_name, class_name):
code = fram... | This code tracks function calls and returns for profiling/logging, identifying function/class names, filtering out system/internal functions, and handling events via handle_call/handle_return methods. | def __call__(self, frame, event, arg):
code = frame.f_code
func_name = code.co_name
func_filename = code.co_filename
# # Ignore write() calls from printing
if func_name in ("write", "_shutdown"):
return
# # Ignore calls not in this module
if (
... |
def cls():
'''
Clears console
'''
os.system('cls' if os.name=='nt' else 'clear')
def pick_card() -> int:
'''
Pick card randomly from deck and return its value
'''
return random.choice(cards)
def game_status(player_cards : list, dealer_cards : list, player_sum : int, dealer_sum : int) -> None:
'''
displays ... | The main task of the code is to run a Blackjack game by initializing player and dealer cards, handling card draws and sum calculations, adjusting for aces, checking for busts/blackjacks, displaying game status, and determining the outcome based on player choices or automatic dealer actions. | def run_game() -> None:
'''
Runs the whole game
'''
cls()
print(logo)
player_cards = []
dealer_cards = []
# pick two cards for player and dealer
player_cards.append(pick_card())
player_cards.append(pick_card())
dealer_cards.append(pick_card())
dealer_cards.append(pick_card())
while(True):
player_su... |
def convert_opponents_board_to_display(opponents_board):
for i in range(len(opponents_board)):
for j in range(len(opponents_board)):
if opponents_board[i][j] == "\U0001F6A2":
opponents_board[i][j] = "\U0001F30A"
return opponents_board
def display_board(board, board2):
pri... | The main task of the code is to handle a player's turn in a game by allowing them to shoot at the enemy's board. It ensures valid input (avoiding repeated shots), updates the enemy board after a successful shot, checks for a win condition, and returns the updated board and winner status. | def player_move(player, enemy_board, player_board):
coordinates = None
print(f"Now shooting player: {player}!\n")
foe_board = deepcopy(enemy_board)
foe_board = convert_opponents_board_to_display(foe_board)
display_board(player_board, foe_board)
cell_occupied = True
while cell_occupied:
... |
def player_move(player, enemy_board, player_board):
coordinates = None
print(f"Now shooting player: {player}!\n")
foe_board = deepcopy(enemy_board)
foe_board = convert_opponents_board_to_display(foe_board)
display_board(player_board, foe_board)
cell_occupied = True
while cell_occupied:
... | This function simulates a turn-based game between a human and AI player. It alternates moves: the human updates the AI's board, then the AI updates the human's board. After each move, it checks for a win condition. If achieved, it displays the winner and exits the loop. The game continues until one side wins, with the ... | def human_vs_ai(human, ai_player, human_board, ai_board):
winner = False
while not winner:
clear_screen()
ai_board, winner = player_move(human, ai_board, human_board)
if winner:
display_win(human, ai_board)
break
human_board, winner = ai_move(human_board, ... |
def get_dimensions(lines):
maxx=max([p[0] for l in lines for p in l])
maxy=max([p[1] for l in lines for p in l])
return (maxx,maxy)
def pen_up():
GPIO.output(pen_up_pin,GPIO.LOW)
print("pen up")
def pltmove1(c):
pltmove(c[0],c[1])
def scale_point(p,dim):
return [p[0]/dim[0],p[1]/dim[1]]
def pen_down():
GPIO.out... | The main task of the code is to draw lines on a plot by scaling input points to a specified dimension. It lifts the pen, moves to the first point of each line, lowers the pen, and then sequentially moves to subsequent points in the line with timed intervals between actions, repeating this for all lines. The function us... | def draw_image(lines):
dim=get_dimensions(lines)
pen_up()
for line in lines:
pltmove1(scale_point(line[0],dim))
time.sleep(pen_interval)
pen_down()
time.sleep(pen_interval)
for point in line[1:]:
pltmove1(scale_point(point,dim))
time.sleep(move_interval)
pen_up()
time.sleep(pen_interval) |
def parse_arguments() -> argparse.Namespace:
parser = configure_parser()
args = parser.parse_args()
validate_arguments(parser, args)
return args
def get_matching_files(args: argparse.Namespace) -> List[FileMetadata]:
"""Create a list of metadata objects for data files that match conditions specified... | The main task of the code is to process command-line arguments, identify matching files, create necessary directories, and copy the files to their designated locations based on the provided parameters. | def main() -> None:
args = parse_arguments()
file_metadata = get_matching_files(args)
create_directories(args, file_metadata)
copy_files(args, file_metadata) |
def load_private_key():
try:
with open('private_key.pem', 'rb') as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(),
password=None,
backend=default_backend()
)
except FileNotFoundError:
# If the pr... | The code generates a QR code for a new student by encrypting their student code using RSA encryption. It creates a data payload with student details, encrypts the student code with a public key, prints encrypted/decrypted data for verification, saves the encrypted QR image, and stores the image path in a QRModel instan... | def generate_qr(sender, instance, created, **kwargs):
if created:
# Generate QR code for the new student
data = {
'programme': instance.programme,
'name': instance.name(),
'student_code': instance.student_code.replace('/', '_'),
'signature': instance.s... |
def cut_paste_user_mask(r_obj, c_obj):
img1, img2 = r_obj.image, c_obj.image
r_img, c_img = img1.copy(), img2.copy()
# create masks
concave_hull = get_concave_hull(np.int32(c_obj.pix_points))
mask = np.zeros(cam_obj.image.shape, dtype=cam_obj.image.dtype)
mask = cv2.fillPoly(mask, [concave_hull]... | The code processes real-time camera input to track facial landmarks, calculates rotation differences, applies user masks, and updates textures. If a match is detected, it saves the morph result, resets tracking variables, updates UI elements, and sets textures for display. When no selection is active, it restores previ... | def update(self, dt):
global selected, view, pb_rots, view_source, last_match, morph_texture, cam_obj, morph_selected
if selected != -1:
success, frame = self.capture.read()
image = cv2.flip(frame, 1)
self.texture = view.texture
if success:
... |
def get_hosts_list(api_url, api_token=None, specific_host=None):
"""Retrieves hosts list from netbox API.
Returns:
A list of all hosts from netbox API.
"""
if not api_url:
sys.exit("Please check API URL in script configuration file.")
api_url_headers = ... | The main task of the code is to generate a dynamic Ansible inventory by fetching host data from Netbox via an API, organizing hosts into groups, and compiling their associated variables into a structured dictionary. The function constructs an inventory with `_meta` and `hostvars` keys, updating host metadata and variab... | def generate_inventory(self):
"""Generate Ansible dynamic inventory.
Returns:
A dict has inventory with hosts and their vars.
"""
inventory_dict = dict()
netbox_hosts_list = self.get_hosts_list(self.api_url, self.api_token, self.host)
if netbox_hosts_list:
... |
def score_update(highscore: int, score: int):
global score_display
score_display.set_text("Highscore: " + str(highscore) + "\nScore: " + str(score))
def focus(input_field) -> None:
ui.run_javascript(f'getElement({input_field.id}).$refs.qRef.focus()')
def reset_gui():
global pointer
global checkboxes... | The code's main task is to submit a user's input word to a game, process the result, update the UI based on outcomes (e.g., disabling checkboxes, updating scores), and reset input fields for the next round. It checks if all fields are filled, handles game results like "GOOD" (enabling next inputs), "REPEAT" (game over)... | def enter(): # submit word to game, process results, reset text boxes to initial state for next round
global pointer
global checkboxes
full = True
for i in input_fields:
full = full and i.value != ""
if full:
temp = [i for i in game.get_letters()]
game.set_user_word([i.... |
def backspace(): # clear current input and move to previous input
global pointer
if pointer > 0:
if pointer <= 4:
input_fields[pointer].set_value("")
input_fields[pointer].disable()
pointer -= 1
while pointer >= 0 and game.get_req_letters()[pointer] != "":
... | This function handles keyboard events by triggering specific actions based on the key pressed. It checks if the key is Backspace or Enter during a keydown event and calls corresponding functions (backspace() or enter()). For other keys, it adds the pressed character using add_letter(). The main task is to process key i... | def handle_key(e: KeyEventArguments):
if e.key == "Backspace" and e.action.keydown:
backspace()
elif e.key == "Enter" and e.action.keydown:
enter()
elif e.action.keydown:
add_letter(str(e.key)) |
def load_mask_model(model_name, device, cache_dir):
model_name = get_model_fullname(model_name)
# mask filling t5 model
print(f'Loading mask filling model {model_name}...')
mask_model = from_pretrained(AutoModelForSeq2SeqLM, model_name, {}, cache_dir)
mask_model = mask_model.to(device)
return ma... | The code generates multiple perturbed versions of original and sampled texts using a mask-filling model. It loads a pre-trained model and tokenizer, applies perturbations to each sample by masking and regenerating text, and saves the results along with original data. The process ensures reproducibility via seeding and ... | def generate_perturbs(args):
n_perturbations = args.n_perturbations
name = f'perturbation_{n_perturbations}'
# load model
mask_model = load_mask_model(args.mask_filling_model_name, args.device, args.cache_dir)
mask_model.eval()
try:
n_positions = mask_model.config.n_positions
except ... |
def generate_perturbs(args):
n_perturbations = args.n_perturbations
name = f'perturbation_{n_perturbations}'
# load model
mask_model = load_mask_model(args.mask_filling_model_name, args.device, args.cache_dir)
mask_model.eval()
try:
n_positions = mask_model.config.n_positions
except ... | The code conducts an experiment to evaluate the performance of a language model by comparing original and perturbed text log-likelihoods. It loads precomputed perturbations, calculates log probabilities using a scoring model, computes normalized differences between original and perturbed texts, and derives metrics like... | def experiment(args):
n_perturbations = args.n_perturbations
name = f'perturbation_{n_perturbations}'
perturb_file = f'{args.dataset_file}.{args.mask_filling_model_name}.{name}.raw_data.json'
if os.path.exists(perturb_file):
print(f'Use existing perturbation file: {perturb_file}')
else:
... |
def _encode(A: np.array, b: np.array) -> list:
'''
A = np.array([[1, 1, 1, 1, 1],
[1, 1, 0, 0, 0],
[0, 0, 1, 1, 0],
[1, 1, 1, 1, 0],
[1, 0, 1, 0, 1]], dtype=np.int8)
b = np.array( [5, 2, 2, 4, 3], dtype=np.int8)
:return:
[(31, ... | (The code performs Gaussian elimination on a system of linear equations represented by matrix A and vector b. It encodes the inputs into a structured format, applies elimination steps to transform the system into row-echelon form, then decodes the result to return the solution as a tuple.) | def elim(A: np.array, b: np.array) -> tuple:
hd = _encode(A, b)
_elim(hd)
return _decode(hd) |
def getAvailable(self):
already_sent = []
with open("already_sent_times.txt", 'r') as infile:
for line in infile:
already_sent.append(line)
send = False
self.driver.get('https://fcymca.org/swim-reservations/')
self.driver.execute_script("window.scrollT... | The main task of the code is to continuously monitor and manage available time slots for scheduling. It checks for new "good_day_times" against previously sent times, sends updates if discrepancies exist, and periodically checks for user-selected email values to trigger registration actions. The loop ensures real-time ... | def main_function(self):
while True:
send = False
good_day_times, already_sent = self.getAvailable()
with open("already_sent_times.txt", 'r') as infile:
already_sent = infile.read().splitlines()
if len(good_day_times) != len(already_sent):
... |
def check_area(self, col = 0, row = 0) :
if col == 0 and row == 0 :
col = self.cols
row = self.rows
remove_area = 0
area_candidate = []
for x in range(col) :
for y in range(row) :
area_candidate.append((x, y))
while len(area_c... | The code performs a combo action by repeatedly removing and moving down elements as long as `check_area()` returns True, counting each successful operation in `combo_count`. If debugging is enabled, it prints the combo count. | def do_combo(self) :
combo_count = 0
while self.check_area() :
self.remove()
self.move_down()
combo_count += 1
if debug_ctrl['do_combo'] == True :
print('do_combo : ', combo_count) |
def __init__(self):
# basic info
self.file_path = ""
self.main_tid = 0
self.sub_tids = []
# graph construct info
self.last_func = {}
self.last_timeline = {}
self.last_task = {}
self.func_dict = {}
self.task_arrs = {}
self.timeline_a... | The code processes trace events from a JSON file, filters relevant events (FunctionCall, timeline, tasks), constructs a graph by adding nodes/edges, and identifies key functions based on execution frequency/duration thresholds. It returns the graph, a websocket flag, and a mining result indicating potential critical fu... | def construct(self, trace_path):
self.__init__()
self.file_path = trace_path
with open(trace_path, 'r') as f:
trace_json = json.load(f)
trace_events = trace_json['traceEvents']
# select some trace events
tes = []
func_te_temp = None
for te ... |
def start_avail_script():
volumes = {
'/Projects/avail_gpi_0.8_docker/avail_gpi': {'bind': '/app', 'mode': 'rw'},
'/var/log/': {'bind': '/app/logs', 'mode': 'rw'}
}
if is_container_running(AVAIL_CONTAINER_NAME) is False:
control_log.info("{} not running - starting in Deployment ... | The code defines a function `ss_menu()` that presents a command-line menu for selecting actions like starting, stopping, or restarting scripts. It uses PyInquirer to prompt the user, processes their choice, and executes corresponding functions (`start_avail_script()`, `stop_avail_script()`, `restart_avail_script()`) or... | def ss_menu():
ss_menu_promt = {
'type': 'list',
'name': 'start_stop',
'message': '\nChoose an option\n',
'choices': [v for k,v in ss_options.items()]
}
while (True):
print('\n')
ss_answers = pyq.prompt(ss_menu_promt)
if ss_answers['start_stop'] is s... |
def ss_menu():
ss_menu_promt = {
'type': 'list',
'name': 'start_stop',
'message': '\nChoose an option\n',
'choices': [v for k,v in ss_options.items()]
}
while (True):
print('\n')
ss_answers = pyq.prompt(ss_menu_promt)
if ss_answers['start_stop'] is s... | The main task of the code is to display a menu with selectable options and handle user choices by invoking corresponding functions, looping until the user selects 'back'. It uses a dictionary to define menu choices, processes user input via pyq.prompt, and executes functions like ss_menu(), autostart_menu(), or config_... | def main_menu():
main_menu_promt = {
'type': 'list',
'name': 'main_choice',
'message': 'Choose an option\n',
'choices': [v for k,v in mm_choices.items()]
}
while(True):
print('\n')
mm_answers = pyq.prompt(main_menu_promt)
if mm_answers['main_choice'... |
def reset_weight(self):
self.w = np.array(self.original_w)
def backward_propagation(self, X: list[float] | list[list], y: int | list[int], l2: float) -> list[float]:
"""
Parameters
----------
X: list | list[list]
A single input vector | Multiple input vectors
... | This function trains a neural network using gradient descent with L2 regularization, updating weights after each input vector. It iterates over epochs, performs backward propagation, evaluates training and test data accuracy/log loss per epoch, and returns final test log loss along with epoch-wise performance metrics. | def quick_train(
self,
X: list[list],
y: list[int],
epochs: int = 100,
learning_rate: float = 1,
l2: float = 0,
) -> tuple[float, list[float]]:
"""
Train the neural network and update weights after the forward pass of each input vector.
Parame... |
def reset_weight(self):
self.w = np.array(self.original_w)
def backward_propagation(self, X: list[float] | list[list], y: int | list[int], l2: float) -> list[float]:
"""
Parameters
----------
X: list | list[list]
A single input vector | Multiple input vectors
... | This function trains a neural network using gradient descent by updating weights after each full epoch. It computes weight updates via backpropagation, tracks training and test accuracy/loss, prints progress, and returns the final test loss along with a list of epoch-wise metrics. | def slow_train(
self,
X: list[list],
y: list[int],
epochs: int = 100,
learning_rate: float = 1,
l2: float = 0,
) -> tuple[float, list[float]]:
"""
Train the neural network and update weights after each entire epoch forward pass.
Parameters & R... |
def xml_string_to_dict(xml: str):
root = ET.fromstring(xml)
return xml_to_dict(root)
def on_available(self, message, site_url):
"""Called when tickets are available.
Useful to override for custom notifications"""
print(message)
print(site_url)
def on_unavailable(self, message):
... | The code checks a URL for available tickets by fetching the webpage, parsing XML data to find remaining ticket counts, and notifying via `on_available` if tickets exist. It tracks URLs to avoid redundant notifications and calls `on_unavailable` if tickets are exhausted. Errors in connection are logged with status codes... | def check(self, url):
"""Checks url for tickets
Prints message if tickets are available"""
# make request to url
response = requests.get(url)
# check if response is good
if response.status_code == 200:
# check if there are tickets available
# find ... |
def occurence(array):
temp_dict = {}
for ind, task in enumerate(array):
if task in temp_dict.keys():
temp_dict[task].append(index2name(ind))
else:
temp_dict[task] = [index2name(ind)]
return temp_dict
def best_vm_for_char(char):
# for a given charecteristic it give... | The code allocates tasks to VMs based on dependencies by processing sorted task names in reverse order. It iterates through task indices, identifies tasks with single occurrences, assigns them to VMs using best_vm_for_char, and handles multi-occurrence tasks via independent_Task2Vm. Unallocated tasks are tracked and re... | def dependent_Task2Vm(task_scores, sorted_task_names):
# Input is task scores a dict, sorted task names a 2d list.
index = len(sorted_task_names[0])-1
unallocated_vms = {k: 0 for k in task_scores}
while index >= 0 and len(unallocated_vms) > 0:
temp_array = [a[index] for a in sorted_task_names]
... |
def get_file_tokens(directory):
file_names = [os.path.join(directory, f) for f in listdir(
directory) if isfile(join(directory, f))]
file_tokens = {file_name: generate_token(
file_name) for file_name in file_names}
return file_tokens
def sprint(string, output=False):
print(string)
if... | The function analyzes files (single or directory) to compute memory, compute, and network scores for each file. It then sorts and displays files by these scores in priority order. Results are printed or written to an output file if specified, providing token counts and scores for each category. | def analyze(directory=False, directory_name=None, output=False, output_file_name=None, file_name=None):
global output_file
if output:
output_file = open(output_file_name, 'w')
if directory:
file_tokens = get_file_tokens(directory_name)
total_mem_token = 0
total_com_token = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.