dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def clean_data(threedata):
df = threedata
df = df.dropna()
df['arcAngleProxy'] = df.apply(lambda row: get_arcAngleProxy(row), axis=1)
df['rimDepthInches'] = df.apply(lambda row: get_rimDepthInches(row), axis=1)
df['rimLeftRightInches'] = df.apply(lambda row: get_rimLeftRightInches(row), axis=1)
... | The code processes 3D data by cleaning input CSV data, generating smooth grids, adding shot scores, and saving the updated dataset as 'threedata_shotscore.csv' | def main():
threedata = clean_data(pd.read_csv(FILENAME))
write_smooth_grids(threedata)
add_shot_score(threedata)
threedata.to_csv('threedata_shotscore.csv') |
def get_title(page):
return page.find("span", itemprop="name").text
def get_desc(page):
if page.find("span", itemprop="description") != None:
description = page.find("span", itemprop="description").text
return description.replace("[Written by MAL Rewrite]","").strip()
return "No descripti... | This function scrapes anime data from a given URL, extracting title, description, and sidebar information into a dictionary. It checks if the anime exists via HTTP status codes, returns structured data if found, or handles errors by returning None or an error message. | def scrape_anime_url(page_link, anime_id):
page_response = requests.get(page_link, headers = {'User-agent': 'your bot 0.1'})
try :
anime_data = {}
# if the anime doesn't exist, an error will be raised
page_response.raise_for_status()
# if anime exists, get the html from the page
... |
def squarePerimeter(self, outline='green'):
X, Y=extractDims(self.dots)
x0=min(X)
x1=max(X)
y0=min(Y)
y1=max(Y)
self.canvas.create_rectangle(x0, y0, x1, y1, outline=outline, fill='')
def web(self, fill='green'):
dotPairs=ngroupFinder(self.dots, 2)
for pair... | The main task of the code is to handle keyboard events within a canvas by triggering specific methods based on the pressed key. It checks the event's character and calls functions like squarePerimeter(), web(), or manualCommand(), but currently lacks a check to ensure the event originates from the canvas. The code need... | def keyEvents(self, event): #need to make it so it only happens when event is in canvas
if event.char=='p':
self.squarePerimeter()
elif event.char=='w':
self.web()
elif event.char=='z':
self.avgCircleAnimation1()
elif event.char==' ':
self... |
def _sample_hidden_units(self, vector_visible_units):
"""
Computes hidden unit activations by sampling from a binomial distribution.
:param vector_visible_units: array-like, shape = (n_features, )
:return:
"""
hidden_units = self._compute_hidden_units(vector_visible_units... | The function computes gradients for training a model using Contrastive Divergence (CD). It initializes visible units, iteratively samples hidden and visible units via Gibbs sampling, then calculates weight and bias updates by comparing initial and reconstructed states. The gradients (delta_W, delta_b, delta_c) reflect ... | def _contrastive_divergence(self, vector_visible_units):
"""
Computes gradients using Contrastive Divergence method.
:param vector_visible_units: array-like, shape = (n_features, )
:return:
"""
v_0 = vector_visible_units
v_t = np.array(v_0)
# Sampling
... |
def copy(node: Node) -> Node:
if node is None:
return None
result = Node()
result.num = node.num
result.left = copy(node.left)
result.right = copy(node.right)
if result.left is not None:
result.left.parent = result
if result.right is not None:
result.right.parent = result
return result
def add(x: Node, y:... | The code sums all Node objects in the input list by sequentially adding them, starting with the first element, and returns the magnitude of the resulting Node. It creates deep copies of the input nodes to avoid modifying the originals during operations. | def part1(lines: list[Node]):
lines = lines.copy()
for i in range(len(lines)):
lines[i] = copy(lines[i])
x = lines[0]
for y in lines[1:]:
x = add(x, y)
return magnitude(x) |
def copy(node: Node) -> Node:
if node is None:
return None
result = Node()
result.num = node.num
result.left = copy(node.left)
result.right = copy(node.right)
if result.left is not None:
result.left.parent = result
if result.right is not None:
result.right.parent = result
return result
def add(x: Node, y:... | The main task of the code is to compute the maximum magnitude achievable by adding any two nodes from the input list. It iterates through all possible pairs of nodes, creates copies of each pair, adds them, calculates the magnitude of the result, and updates the maximum magnitude found. The function returns this maximu... | def part2(lines: list[Node]):
n = len(lines)
max_magnitude = 0
for i in range(n):
for j in range(n):
x = copy(lines[i])
y = copy(lines[j])
sum = add(x, y)
mag = magnitude(sum)
if mag > max_magnitude:
max_magnitude = mag
return max_magnitude |
def segment_intersection(start0, end0, start1, end1):
r"""Determine the intersection of two line segments.
Assumes each line is parametric
.. math::
\begin{alignat*}{2}
L_0(s) &= S_0 (1 - s) + E_0 s &&= S_0 + s \Delta_0 \\
L_1(t) &= S_1 (1 - t) + E_1 t &&= S_1 + t \Delta_1.
... | The function `from_linearized` computes intersections between two curves (non-lines) using their linearized representations. It checks if their segments intersect within valid parameter ranges, falls back to Newton iteration if needed, refines the intersection points, and adds them to the `intersections` list if valid.... | def from_linearized(first, second, intersections):
"""Determine curve-curve intersection from pair of linearizations.
.. note::
This assumes that at least one of ``first`` and ``second`` is
not a line. The line-line case should be handled "early"
by :func:`check_lines`.
.. note::
... |
def bbox_intersect(nodes1, nodes2):
r"""Bounding box intersection predicate.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Determines if the bounding box of two sets of control points
intersects in :math:`\mathbf{R}^2` with non... | The function `intersect_one_round` processes pairs of curves to check if their bounding boxes intersect. If they do, it either adds the intersection to a list or subdivides the curves into linearized forms for further processing. The goal is to refine candidate pairs by discarding non-intersecting pairs and generating ... | def intersect_one_round(candidates, intersections):
"""Perform one step of the intersection process.
.. note::
This is a helper for :func:`all_intersections` and that function
has a Fortran equivalent.
Checks if the bounding boxes of each pair in ``candidates``
intersect. If the boundin... |
def check_lines(first, second):
"""Checks if two curves are lines and tries to intersect them.
.. note::
This is a helper for :func:`.all_intersections`.
If they are not lines / not linearized, immediately returns :data:`False`
with no "return value".
If they are lines, attempts to inters... | The function `all_intersections` computes the intersection points between two 2D curves defined by their control points (`nodes_first` and `nodes_second`). It identifies parameter pairs $(s, t)$ where the curves intersect ($B_1(s) = B_2(t)$) using subdivision and numerical methods. The function handles both linear and ... | def all_intersections(nodes_first, nodes_second):
r"""Find the points of intersection among a pair of curves.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
.. note::
This assumes both curves are in :math:`\mathbf{R}^2`, but... |
def _get_steam_client(self, username):
self._create_sandbox(username)
tf2_installation = self._get_tf2installation(username)
return SteamClient(tf2_installation,
shell_executer=partial(self.sbie.start,
box=username, wai... | The main task of the code is to asynchronously log out multiple accounts by invoking each account's Steam client logout method, then clean up resources for each account, returning the logout results. It uses parallel execution via `__run_async` to handle simultaneous logouts efficiently. | def logout(self, accounts):
tasks = [partial(self._get_steam_client(account.username).logout)
for account in accounts]
logout_results = self.__run_async(tasks)
for account in accounts:
self.cleanup(account.username)
return logout_results |
def _get_steam_client(self, username):
self._create_sandbox(username)
tf2_installation = self._get_tf2installation(username)
return SteamClient(tf2_installation,
shell_executer=partial(self.sbie.start,
box=username, wai... | The code's main task is to asynchronously log out multiple accounts by generating logout tasks for each account, executing them using `__run_async`, and subsequently cleaning up resources for each account. It returns the results of the logout operations. | def logout(self, accounts):
tasks = [partial(self._get_steam_client(account.username).logout)
for account in accounts]
logout_results = self.__run_async(tasks)
for account in accounts:
self.cleanup(account.username)
return logout_results |
def LocateConfig(pipe):
""""Locates the configuration range, based on meaningful string CRULOADER_STRING."""
config_range = []
for string in pipe.cmdj("izj"):
if(string["string"] == CRULOADER_STRING):
config_range.append(string['vaddr'])
if len(config_range) == 2:
bre... | The main task of the code is to decrypt a payload from a binary file. It locates configuration data, extracts decryption keys, retrieves an image from a URL in the config, and decrypts the payload using the extracted keys, saving the result to the specified output path. | def main(args):
with rzpipe.open(args.file) as rz:
rz.cmd("aaa")
config_range = LocateConfig(rz)
# For regex search:
# config_range, user_agent = LocateConfigRegEx(rz)
config = DecryptConfig(rz, config_range)
exe_flag, payload_key = LocateDecryptPayloadCfg(rz, config_... |
def _process_json_response(self, response, action_result):
""" This function is used to process json response.
:param response: response data
:param action_result: object of Action Result
:return: status phantom.APP_ERROR/phantom.APP_SUCCESS(along with appropriate message)
"""
... | The function processes HTTP responses by analyzing the Content-Type header. It logs debug data, handles JSON/JavaScript responses, parses HTML content, manages empty responses, and returns errors for unrecognized content types, ensuring proper error messaging and status codes are set in the action result. | def _process_response(self, response, action_result):
""" This function is used to process html response.
:param response: response data
:param action_result: object of Action Result
:return: status phantom.APP_ERROR/phantom.APP_SUCCESS(along with appropriate message)
"""
... |
def _dump_error_log(self, error, message="Exception occurred."):
self.error_print(message, dump_object=error)
def _get_error_message_from_exception(self, e):
""" This method is used to get appropriate error messages from the exception.
:param e: Exception object
:return: error message
... | This function makes a REST API call to a specified endpoint using the provided HTTP method. It handles request construction, error logging, and exception handling for connection issues. The function returns a processed response status and data, leveraging the ActionResult object to report success/failure. It supports c... | def _make_rest_call(self, endpoint, action_result, headers=None, params=None, data=None, method="get", verify=True):
""" Function that makes the REST call to the app.
:param endpoint: REST endpoint that needs to appended to the service address
:param action_result: object of ActionResult class
... |
def _make_rest_call(self, endpoint, action_result, headers=None, params=None, data=None, method="get", verify=True):
""" Function that makes the REST call to the app.
:param endpoint: REST endpoint that needs to appended to the service address
:param action_result: object of ActionResult class
... | The function `_generate_new_access_token` generates a new access token using an authorization code via a REST POST request. It constructs a URL with tenant-specific parameters, sends data to obtain tokens, and stores the response. If successful, it extracts and saves the access and refresh tokens in the state. Errors d... | def _generate_new_access_token(self, action_result, data):
""" This function is used to generate new access token using the code obtained on authorization.
:param action_result: object of ActionResult class
:param data: Data to send in REST call
:return: status phantom.APP_ERROR/phantom... |
def _get_phantom_base_url_defenderatp(self, action_result):
""" Get base url of phantom.
:param action_result: object of ActionResult class
:return: status phantom.APP_ERROR/phantom.APP_SUCCESS(along with appropriate message),
base url of phantom
"""
url = '{}{}'.format... | The main task of the code is to construct a REST API URL for a specific app in Phantom by combining the base URL, app directory name, app ID, and asset name. It retrieves necessary components like the Phantom base URL and asset name, validates them, and returns the constructed URL along with a success status if all ste... | def _get_app_rest_url(self, action_result):
""" Get URL for making rest calls.
:param action_result: object of ActionResult class
:return: status phantom.APP_ERROR/phantom.APP_SUCCESS(along with appropriate message),
URL to make rest calls
"""
ret_val, phantom_base_url ... |
def data_loader(filename):
filename_queue = tf.train.string_input_producer([filename])
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(serialized_example,
features={
... | This code implements a GAN training loop with encoder-decoder architecture. It loads image data, trains an encoder to map images to latent space, uses a discriminator to distinguish real/fake latent vectors, and a decoder to reconstruct images. The model minimizes discriminator loss (via cross-entropy) and reconstructi... | def main():
iter_counter = 0
real_image_data, label_data = data_loader('train.tfrecords')
img_batch, label_batch = tf.train.shuffle_batch([real_image_data, label_data],
batch_size=batch_size,
capacity=200... |
def z_translate(self):
if self.settings == 0:
self.move_gripper_up()
self.step_simulation(15)
self.move_gripper_down()
self.step_simulation(15)
self.move_gripper_up()
self.step_simulation(15)
self.move_gripper_down()
... | The main task of the code is to perform a gripper movement sequence by first translating along the z-axis, then rotating around the y-axis, and finally advancing the simulation by 50 steps to complete the motion. This likely simulates a shaking or positioning action for a robotic gripper in a controlled environment. | def gripper_shake(self):
self.z_translate()
self.y_rotate()
self.step_simulation(50) |
def step_simulation(self, num_steps=1000):
for _ in range(num_steps):
# step the physics
self.gym.simulate(self.sim)
self.gym.fetch_results(self.sim, True)
# refresh tensors
# self.gym.refresh_net_contact_force_tensor(self.sim)
... | The code simulates a robotic grasping task by moving the gripper, manipulating an object's position, capturing point cloud data, closing the gripper to grasp the object, and shaking it to confirm the grasp. Simulation steps and gripper adjustments ensure precise control and validation of the grasping process. | def execute_grasp(self):
self.step_simulation(10)
self.move_gripper_away()
self.step_simulation(20)
self.move_obj_to_pos()
self.step_simulation(20)
self.get_pointcloud()
self.move_gripper_to_grasp()
self.step_simulation(20)
self.close_gripper_effor... |
def on_click(self):
x, y = pygame.mouse.get_pos()
#get column of mouse click (1-3)
if(x < self.width/3):
col = 1
elif (x < self.width/3*2):
col = 2
elif(x < self.width):
col = 3
else:
col = None
#get row of mouse cli... | This method handles Human vs AI gameplay in a turn-based game. It processes events like quitting or mouse clicks, allowing the player to place a mark, then the AI (CPU) responds. After each move, it checks for a winner or draw, and resets the game if necessary. | def play_step(self):
'''Human vs AI'''
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.exit = True
elif event.type == pygame.MOUSEBUTTONDOWN:
# the user clicked; place an X or O
self.on_click()
ti... |
def cpu_x(self):
"""AI trained as X player"""
action = self.player_x.predict(self.board)[0]
row, col = action
self.draw_xo(row+1, col+1)
self.check_winner()
def rand_cpu(self):
'''AI that plays random moves'''
avail: list[tuple[int, int]] = get_available(self.boar... | This code runs a Pygame game loop, updating the display, handling exit events, executing CPU moves with delays, checking for game end conditions (winner/draw), and resetting the game. It maintains a 60 FPS frame rate using a clock, with the loop terminating when the exit flag is set. | def run(self):
while not self.exit:
pygame.display.update()
#self.play_step()
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.exit = True
time.sleep(0.5)
self.cpu_x()
time.sleep(0.5)
... |
def send_move(self,selection):
'''
Function to send message to peer using button click
selection indicates the selected button
'''
row,col = divmod(selection,3)
################### Fill Out #######################
# send message and check ACK
msg = 'SEN... | This function handles a player's move in a Tic-Tac-Toe game by validating the selected button, sending the move to the opponent, updating the board, and switching turns if the game remains active. It checks if the move is valid, quits if invalid, updates the UI, and starts a thread to await the opponent's move. | def my_move(self, e, user_move):
'''
Read button when the player clicks the button
e: event
user_move: button number, from 0 to 8
'''
#vvvvvvvvvvvvvvvvvvv DO NOT CHANGE vvvvvvvvvvvvvvvvvvv
# When it is not my turn or the selected location ... |
def check_msg(msg, recv_ip):
'''
Function that checks if received message is ETTTP format
'''
################### Fill Out #######################
checkmsg = msg.split('\r\n')
'''
split string (checkmsg) by '\r\n' --> list with 5 factors
ex) 'RES... | The main task of the code is to receive a move from a peer via socket, validate the message, and if valid, send an acknowledgment (ACK), update the game board, and switch the turn. If invalid, it closes the connection and exits. The function decodes the message, checks its validity, extracts coordinates, constructs an ... | def get_move(self):
'''
Function to get move from other peer
Get message using socket, and check if it is valid
If is valid, send ACK message
If is not, close socket and quit
'''
################### Fill Out #######################
msg = self.socket.recv... |
def check_msg(msg, recv_ip):
'''
Function that checks if received message is ETTTP format
'''
################### Fill Out #######################
checkmsg = msg.split('\r\n')
'''
split string (checkmsg) by '\r\n' --> list with 5 factors
ex) 'RES... | (The main task of the code is to send a player's move to a peer in a turn-based game, validate the move's coordinates, ensure the selected board position is unoccupied, and verify the peer's acknowledgment matches the sent move. If invalid, it terminates the game. If valid, it updates the board, ends the turn, and init... | def send_debug(self):
'''
Function to send message to peer using input from the textbox
Need to check if this turn is my turn or not
'''
if not self.my_turn:
self.t_debug.delete(1.0,"end")
return
# get message from the input box
d_msg = se... |
def create_board_frame(self):
'''
Tic-Tac-Toe Board UI
'''
#vvvvvvvvvvvvvvvvvvv DO NOT CHANGE vvvvvvvvvvvvvvvvvvv
self.board_frame = tk.Frame()
self.board_frame.pack(expand=True)
self.cell = [None] * self.total_cells
self.setText=[None]*self.total_cells... | This code initializes a game by setting up UI components, determining the starting player (user or computer), and configuring game state. It assigns symbols ('X'/'O') to players, updates status indicators, and starts a separate thread for the computer's move if the user doesn't begin. The function prepares the game env... | def play(self, start_user=1):
'''
Call this function to initiate the game
start_user: if its 0, start by "server" and if its 1, start by "client"
'''
#vvvvvvvvvvvvvvvvvvv DO NOT CHANGE vvvvvvvvvvvvvvvvvvv
self.last_click = 0
self.create_board_frame()
... |
def up_energy_levels(self):
for line in self.grid:
for octopus in line:
octopus.up_energy_level()
def flash_step(self):
while self.flash_all():
self.flash_all()
def prepare_for_next_step(self):
for line in self.grid:
for octopus in line:
... | The main task of the code is to increment energy levels, execute a flash step (checking for energy thresholds), prepare for the next iteration, and return the total number of flashes recorded during the process. | def take_step(self):
self.up_energy_levels()
self.flash_step()
self.prepare_for_next_step()
return self.total_flashes |
def download_from_ya_disk(public_key, dst):
api_call_url = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?' + \
urlencode(dict(public_key=public_key))
response = requests.get(api_call_url)
download_url = response.json()['href']
download_response = requests.get(downloa... | The function processes video conversion tasks by downloading videos from YaDisk, converting them to GIFs using ffmpeg, uploading the result to object storage with a presigned URL, and updating the task status in DocAPI. It iterates through event messages, handles each task individually, and returns "OK" upon completion... | def handle_process_event(event, context):
for message in event['messages']:
task_json = json.loads(message['details']['message']['body'])
task_id = task_json['task_id']
# Download video
download_from_ya_disk(task_json['src'], '/tmp/video.mp4')
# Convert with ffmpeg
su... |
def download_video_from_gdrive(cfg):
# create video input path
video_input_path = os.path.join(current_path, "input")
output = os.path.join(video_input_path, cfg['video_name'])
if not os.path.exists(video_input_path):
os.makedirs(video_input_path)
# get video absolute path
gdown.... | The code downloads a video, creates an output directory, and extracts 2D or 3D pose data based on the configuration, writing results to the output path. | def run(cfg):
# download test video
SOURCE_VIDEO_PATH = download_video_from_gdrive(cfg)
# create output directory
output_path = os.path.join(current_path, "output")
if not os.path.exists(output_path):
os.makedirs(output_path)
if cfg['2D']:
pose_data_extraction_2d(cfg, SOURCE_VI... |
def clear_db(self):
statement = SQLStatements()
statement.execute("DELETE FROM book_loans;")
statement.execute("DELETE FROM book_reservations;")
statement.execute("DELETE FROM book_transaction_logs;")
statement.execute("DELETE FROM books;")
def load_books(self, file_name=book_pat... | The main task of the code is to initialize a database by first clearing existing data, then loading book information, and finally populating loan and reservation history records. This ensures the database starts with a clean slate and is populated with essential data for book management and transaction tracking. | def initialize_db(self):
self.clear_db()
self.load_books()
self.load_loan_reservation_history() |
def __SearchBookFrame(self, frame):
"""
Tab frame for book search
:param frame:
:return:
"""
wrapper1 = LabelFrame(frame, text="Find a book", labelanchor='w', relief=RIDGE)
wrapper2 = LabelFrame(frame, text="Book List")
wrapper1.pack(expand="no", padx=20, ... | The main task of the code is to create a GUI interface with multiple tabs for managing book-related operations. It initializes a notebook with four tabs (All Books, Loan/Checkout, Return, Purchase), sets up corresponding frames for each tab, and integrates UI components like tables, labels, and input fields to handle b... | def __CreateBookResultPlace(self):
"""
Create container for the tab frame components
:return: None
"""
member_id = StringVar()
email = StringVar()
############ Tabs and frames #################
tabControl = Notebook(self.__mainWin)
tabControl.grid(... |
def createGame(self, ownerId):
"""
:param ownerId: person creating game
:return: game id of new game
"""
gameId = choice(words) + choice(words)
self.players[ownerId] = gameId
self.games[gameId.lower()] = Game()
self.joinGame(gameId.lower(), ownerId, isOwn... | This code processes user messages by parsing keywords to trigger game-related actions like creating, joining, leaving, modifying roles, clearing roles, starting, or checking game status, while validating input format and delegating tasks to corresponding methods with member IDs and parameters. | def handleMsg(self, msg):
text = msg['message'].get('text').lower().split(' ')
memberId = msg['sender']['id']
keyword = text[0]
if keyword == "create":
return self.createGame(memberId)
elif keyword == "join":
if len(text) != 2:
return err... |
def decode_list_tuple(l, target_field):
output = l
for i in range(len(l)):
output[i] = decode_tuple(l[i], target_field)
return output
def decode_list(l):
output = l
for i in range(len(l)):
if isinstance(l[i], (bytes, bytearray)):
output[i] = to_hex(l[i])
else:
... | This function converts byte/bytearray values in a dictionary to hexadecimal strings, and decodes lists/tuples using a target schema to produce human-readable, JSON-serializable data structures. It handles nested data types by mapping them to specified schema components, ensuring compatibility with serialization formats... | def convert_to_hex(arg, target_schema):
"""
utility function to convert byte codes into human readable and json serializable data structures
"""
output = dict()
for k in arg:
if isinstance(arg[k], (bytes, bytearray)):
output[k] = to_hex(arg[k])
elif isinstance(arg[k], (li... |
def zero_or_more(p: Parser) -> Parser:
"""Use parser to consume zero or more chars"""
def parser(input_: Stream) -> Result:
ret = []
inp: Stream | None = input_
while curr := p(inp):
inp = curr.stream
ret.append(curr)
return OutputValue(inp, flatten([i.va... | The code tests a parser that matches zero or more occurrences of the identifier "ha" in input strings. It applies this parser to two streams: "hahaha" (which contains three "ha" pairs) and "wocao" (which contains none). The main task is to verify how the parser handles repeated matches and absence of the target pattern... | def test_zero_or_more():
p = zero_or_more(identifier("ha"))
print(p(Stream("hahaha", 0)))
print(p(Stream("wocao", 0))) |
def one_or_more(p: Parser) -> Parser:
"""Use parser to consume one or more chars"""
def parser(input_: Stream) -> Result:
ret = []
inp: Stream | None = None
if curr := p(input_):
inp = curr.stream
ret.append(curr)
else:
return None
whi... | The code tests the `one_or_more` function by applying it to two streams. It checks how many times the pattern "ha" (defined by `identifier("ha")`) appears consecutively in the strings "hahaha" and "wocao", printing the results. The main task is to validate the behavior of the `one_or_more` parser on different input seq... | def test_one_or_more():
p = one_or_more(identifier("ha"))
print(p(Stream("hahaha", 0)))
print(p(Stream("wocao", 0))) |
def and_then(*args: Parser) -> Parser:
"""Consume chars with parser in args"""
return reduce(and_, args)
def or_(p1: Parser, p2: Parser) -> Parser:
def parser(input_: Stream) -> Result:
return p1(input_) or p2(input_)
return parser
def icao_expr() -> Parser:
upper_alphabet = any_char("".joi... | This code tests the limitation of LL(k) parsing by comparing two parser configurations. The first parser (using `or_` with `icao_expr()` and `identifier("CAVOK")`) fails to parse "CAVOK " (expecting `None`), while the second parser (swapped order) successfully parses it (expecting a non-None result). The test highlight... | def test_failed_llk():
"""Because of the limit of LL(k), this case will failed."""
p = and_then(or_(icao_expr(), identifier("CAVOK")), char(" "))
assert p(Stream("CAVOK ", 0)) == None
p = and_then(or_(identifier("CAVOK"), icao_expr()), char(" "))
assert p(Stream("CAVOK ", 0)) != None |
def getconnection( filepath ):
"""open sqlite db at filepath.
returns either:
connection to database OR
0: parent folder does not exists. Something is wrong.
"""
filepath = os.path.abspath( filepath )
folder, filename = os.path.split( filepath )
if not os.path.exists( folder ):... | The function retrieves a concept and its related edges from an SQLite database, normalizing input parameters (lowercasing, replacing underscores), caching results, and returning concepts, edges (with language codes, relations, weights), and the loaded cache. It handles edge relationships by fetching and caching connect... | def query_concept( concept, relation=None, context=None, maxedges=None, lang="en", weight=0.0 ):
"""Retrieve a concept from the sqlite database.
relation & context are ignored in getedges.
"""
conn = getconnection( databasefile)
concept = concept.lower()
concept = concept.replace("_", " "... |
def grad(f, x):
'''
CENTRAL FINITE DIFFERENCE CALCULATION
'''
h = np.cbrt(np.finfo(float).eps)
d = len(x)
nabla = np.zeros(d)
for i in range(d):
x_for = np.copy(x)
x_back = np.copy(x)
x_for[i] += h
x_back[i] -= h
nabla[i] = (f(x_for) - f(x_back)) / (2 ... | The code implements the BFGS Quasi-Newton optimization method to find the optimal solution of a function $ f $ starting from an initial guess $ x_0 $. It iteratively updates the search direction using the Hessian approximation, performs line search for step size, and adjusts the Hessian via the BFGS update rule. The al... | def BFGS(f, x0, max_it, plot=False):
'''
DESCRIPTION
BFGS Quasi-Newton Method, implemented as described in Nocedal:
Numerical Optimisation.
INPUTS:
f: function to be optimised
x0: intial guess
max_it: maximum iterations
plot: if the problem is 2 dimensional, returns
... |
def checkDataType(dataFromClient):
data = dataFromClient.decode('latin-1')
parseData = data.split(' ')[0]
if(parseData == '{"RFWDID":'):
return 1
else:
return 2
def parseJsonDataFromClient(clientReq):
decodedData = clientReq.decode('latin-1')
reqDict = json.loads(decodedData)
... | The code creates a TCP server socket that listens for client connections on a specified port. It processes incoming data by determining its type (JSON or proto), parses and processes the request, generates a response, and sends it back to the client. The server continuously accepts connections, handles each request, an... | def serverSocketCreation():
# declaring the host for the socket
host = ''
# declaring the port for the socket
port = 666
# Making a TCP connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(f"Socket Successfuly created!")
# bind the socket to the port... |
def load_pdf(pdfFileName, index=0, dpi=300):
pdf = pdfium.PdfDocument(str(pdfFileName))
width, height = pdf.get_page_size(index)
img = pdf.render_to(
pdfium.BitmapConv.pil_image,
page_indices = index,
scale = dpi/72
)
return (safe_pil(next(img)), width, height)
def create_thu... | This function processes an input file (e.g., PDF/image) by converting it to a Collada (.dae) 3D model format, generating optional thumbnails, and compressing outputs into ZIP archives. It handles file sizing conversions, saves results to a specified directory, and returns output paths while logging progress. | def process(inputFile, outputDir, thumbs=False, thumb_size=THUMB_MAX_SIZE, compress=False, keep_generated=False):
filename = os.path.split(inputFile)[1]
inputfile = os.path.abspath(inputFile)
outputFile = os.path.abspath(os.path.join(modelDir, "{}.dae".format(os.path.splitext(filename)[0])))
cprint("P... |
def __find_good_route(self,A,B):
start_house, end_house = self.__binary_search(A, 0, len(self.port_bridge)-1)
indexes = [start_house,end_house]
start_shop, end_shop = self.__binary_search(B, 0, len(self.port_bridge)-1)
indexes +=[start_shop, end_shop]
indexes = sorted(indexes)
... | The code calculates distances between houses and shops by pairing each house with each shop. It uses different methods based on the presence of port bridges, adjusting multipliers accordingly. The function returns computed distances (`home_to_shop`) and associated paths (`path`). | def calculate_distance(self):
if len(self.port_bridge) != 0:
mul = (2, 1, 1) if self.port else (1, 1, 1)
else:
mul = (2, 1) if self.port else (1, 1)
for i in range(len(self.house_array)):
for j in range(len(self.shop_array)):
if len(self.port_b... |
def channel_info_save(self):
print('\033[1mStart to crawl Channel Information of '+self.search_term+'.\033[0m')
#channelsSearch = ChannelsSearch(self.search_term, limit = 2, region = 'US')
#channel_result = channelsSearch.result()['result']
#channel = self.channels_show(channel_... | The main task of the code is to execute a single data crawling session by saving channel, video, and comment information, handling potential errors during the process, and logging the start and end timestamps of the crawl. It includes error detection for video and comment data, generating error reports when issues occu... | def run_once(self):
print('Start crawling time:' + datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'\n')
# channel information
try:
self.channel_info_save()
except:
self.issue_raise('channel',pd.DataFrame())
# video information
sel... |
def _close_file(self):
if self.data_file:
filename = self.data_file.name
self.data_file.close()
self.data_file = None
self._new_message("File closed: " + filename)
def get_sensor_data(self, col: int) -> list:
return [row[col] for row in csv.reader(self.tag... | The code opens a timestamped CSV file, writes a header row containing sensor data fields and debug information if enabled, and notifies the user of the new file. It closes any existing file first, ensuring proper file management for data logging. | def _open_file(self, current_time: datetime):
self._close_file()
filename = self.folder + "/" + current_time.strftime("%Y-%m-%d_%H-%M-%S.csv")
self.data_file = open(filename, "w", newline="")
writer = csv.writer(self.data_file, delimiter=COLUMN_DELIMITER)
debug_header = self.get_... |
def _now(self):
return datetime.now(timezone.utc)
def _new_message(self, message: str, timestamp: Optional[datetime] = None):
if timestamp is None:
timestamp = self._now()
message = f"{timestamp.replace(microsecond=0).isoformat()}: {message}"
self._messages.append(message)
... | This code initializes a custom time-tagging measurement system, configuring channels, reference signals, and data storage. It sets up internal data structures for tracking timestamps, manages channel names and debug logging, and prepares file output based on specified parameters. The class registers input channels, ini... | def __init__(self,
tagger: TimeTagger.TimeTaggerBase,
channels: List[int],
reference: int,
period: int = 1000000000000,
folder: str = None,
channel_names: Optional[List[str]] = None,
reference_name: st... |
def _select_tags_within_range(self):
"""Add the timetags for the last reference tag. Called when a new reference tag arrives."""
reference_time = self._reference_tag.reference_tag
lower_limit = reference_time - self.period
self._determine_channel_tag_offset()
remaining = list()
... | This method processes a reference tag by selecting relevant tags within a range, checking for missing input channels, logging any missing ones, storing the reference tag in a list, and ensuring the list doesn't exceed a specified maximum size by trimming older entries. | def _process_reference_tag(self):
if self._reference_tag is not None:
self._select_tags_within_range()
if missing := self._reference_tag.get_missing_channels(self.channels):
self._new_message("Tags missing: " +
", ".join([f"input {ch}" fo... |
def _now(self):
return datetime.now(timezone.utc)
def _process_reference_tag(self):
if self._reference_tag is not None:
self._select_tags_within_range()
if missing := self._reference_tag.get_missing_channels(self.channels):
self._new_message("Tags missing: " +
... | The code processes incoming time tags by filtering valid tags, handling reference and data tags, tracking missed events, and monitoring for signal absence. It updates reference timestamps, groups tags, and logs warnings if no signals are received beyond a threshold, ensuring proper timing and event tracking in a measur... | def process(self, incoming_tags, begin_time, end_time):
"""Method called by TimeTagger.CustomMeasurement for processing of incoming time tags."""
current_time = self._now()
incoming_tags = incoming_tags[numpy.logical_or(numpy.isin(incoming_tags["channel"], self.__all_channels), incoming_tags["ty... |
def find_good(parent, goods, wiki_mode):
if parent is not None:
if not parent.__class__.__name__ == "NavigableString" and not parent.__class__.__name__ == "Comment":
if hasattr(parent, "name"):
if parent.name in accepted_tags:
add_item(goods, parent)
... | The code extracts text from HTML content using BeautifulSoup, identifies Wikipedia pages, collects relevant elements via `find_good`, processes them with `extract`, and cleans the output with `check_spaces` and `check` functions, returning the final cleaned text. | def get_text(soup):
soup = soup.html
wiki_mode = False
if ("wikipedia.org" in str(soup)):
wiki_mode = True
goods = list()
find_good(soup, goods, wiki_mode)
text = ""
for item in goods:
if item is None:
break
extraction = extract(item)
if extraction... |
def kill_animals(self):
# Filter to animals
animals_to_kill: List[Animal] = filter(
lambda a: isinstance(a, Animal), self.schedule.agents
)
# Filter this animals with 0 energy
animals_to_kill = filter(lambda a: a.energy == 0, animals_to_kill)
# Kill those an... | The code's main task is to advance a simulation step by executing scheduled actions, managing animal lifecycle processes (killing, feeding, reproducing), and collecting data. It first progresses the simulation schedule, then sequentially handles animal mortality, nourishment, and reproduction, finally gathering data fo... | def step(self):
self.schedule.step()
self.kill_animals()
self.feed_animals()
self.reproduce_animals()
# Collect data
self.datacollector.collect(self) |
def initialize():
if "user_id" not in st.session_state:
st.session_state["user_id"] = None
if "user_email" not in st.session_state:
st.session_state["user_email"] = None
if "oobCode" not in st.query_params:
st.query_params["oobCode"] = None
if "mode" not in st.query_params:
... | The code handles user authentication by checking login status, redirecting authenticated users to the recommendation page, and displaying an email login form or anonymous login option. It manages session state, sends sign-in emails, and processes anonymous login requests, ensuring personalized recommendations while cla... | def main():
initialize()
# Check if the user is already logged in or is anonymous
if (st.session_state["user_id"]) or (st.query_params["anonymous"] == "True"):
st.switch_page("pages/recommendation_page.py")
# Display email input form
with st.form(key="login_form"):
st.markdown("###... |
def _get_df(self):
if self.df.empty:
self.clean_up_datasets()
return self.df
def get_pivot_table(df, index, columns):
"""
Create a pivot table from the input DataFrame based on specified index and columns.
Parameters:
-----------
df : pandas.DataFrame
The input D... | The main task of the code is to identify users similar to a given user by analyzing their ratings. It combines the input user's ratings with existing data, creates a pivot table of user-item interactions, and uses a user similarity model to find similar users. The result is a list of user IDs representing those most si... | def get_similar_users(self, user_ratings):
"""
Retrieve a list of users similar to the given user based on their ratings
"""
user_id = user_ratings["userId"].unique()[0]
df_concat = pd.concat([self._get_df(), user_ratings])
df_pivot = get_pivot_table(df_concat, ["userId"]... |
def generate_similar_items(self, model, item, df_pivot, n_neighbors=5, seek="both"):
"""
Generate items similar to a given item using the trained model.
Parameters:
- model: The trained model for generating similar items.
- item (str): The item to find similar items for... | The code generates a flattened list of original items and their similar items by iterating through each item in the input list, using a helper method to find similar items, and appending both the original item and its similar counterparts to a container, which is then flattened for return. | def get_similar_items(self, item_list):
"""
Generate similar items for each item in the input item list.
Returns:
-------
list
A flattened list containing each item from the input item list along with their similar items
"""
similar_items_cont... |
def retrieve_user_ratings(self):
"""
Retrieve the ratings for the current user.
"""
return self.retrieve_ratings_in_file().query(f"userId == '{self.user_id}'")
def get_samples(self, num_samples=5):
"""Get a list of random samples from the dataset"""
return self._... | The code generates personalized item recommendations using collaborative filtering by aggregating ratings from similar users. If the user has no ratings, it uses random samples. It collects top-rated items from similar users, sorts them, removes duplicates, and enhances recommendations by finding items similar to the i... | def get_positive_recommendations(self):
"""
Generates personalized item recommendations for the user based on
their ratings and the ratings of similar users(collaborative filtering). If the user has not rated any items,
random samples are used for recommendations.
Returns:... |
def get_user_edge_rated_items(self, user_id, edge="top"):
"""
Retrieve the user's highest or lowest rated items.
Parameters:
----------
user_id : str
The user ID for which the rated items are to be retrieved.
edge : str, optional
Specifies wh... | The function generates negative recommendations by identifying items similar to those the user has down-rated. It retrieves down-rated items, samples them, and finds similar items to suggest potential negative ratings. Returns a list of such items. | def get_negative_recommendations(self):
"""
Generate a list of recommendations based on items the user has rated negatively (down-rated).
This function retrieves items that the user has rated poorly and uses them to generate a list
of items similar to the poorly rated ones.
... |
def get_positive_recommendations(self):
"""
Generates personalized item recommendations for the user based on
their ratings and the ratings of similar users(collaborative filtering). If the user has not rated any items,
random samples are used for recommendations.
Returns:... | The function generates personalized item recommendations using collaborative filtering by leveraging user positive ratings and penalizing items similar to negatively rated ones, returning the top eligible items based on a specified maximum number. | def generate_user_recommendations(self, max_recommendations=10):
"""
Generate personalized item recommendations for the user based on collaborative filtering.
This function generates recommendations tailored to the user's preferences by leveraging collaborative filtering
techniq... |
def L_prime_func(y, Cl_func):
return Cl_func * q * C_y_func(y)
def find_Cl_alpha(y, alpha):
Cl_d = find_cl_d(alpha)
Cl_func_0 = interpolate(load_file(file_names[0])[0], load_file(file_names[0])[1], load_file(file_names[0])[2],
load_file(file_names[0])[3])[0]
Cl_func_10 = inte... | The function `animate(i)` updates three plot lines (`line1`, `line2`, `line3`) with recalculated y-data values derived from aerodynamic coefficients (lift, drag, moment) for varying angles of attack (`alpha + i/10`). It dynamically adjusts the plot title to reflect the current angle of attack, enabling an animated visu... | def animate(i):
line1.set_ydata(L_prime_func(length, find_Cl_alpha(length, alpha + i / 10)))
line2.set_ydata(D_prime_func(length, find_Cd_alpha(length, alpha + i / 10)))
line3.set_ydata(M_prime_func(length, find_Cm_alpha(length, alpha + i / 10)))
ax.set_title('Alpha ' + str(round(alpha + i / 10, 2)))
... |
def calc_mass_sens_terms(self, vehicle_name:str):
vehicle_data = self.vehicles[vehicle_name]
engine_data = self.engines[vehicle_data["engine"]]
propellant_data = self.propellants[engine_data['propellant']]
prop_sens = (engine_data['MXR'] * (propellant_data['f_oxtank'] / propellant_data... | The function calculates and assigns mass fraction parameters (Minit_Mpay, Mprop_Mpay, Mdry_Mpay) to each edge in the graph, using vehicle/engine attributes, directionality, dV, and Isp values. It computes mass_frac via an exponential formula and applies it to determine mass ratios for propulsion and dry mass, updating ... | def assign_mass_fractions(self, graph):
for edge in graph.edges.items():
attrs = edge[1]
edge_item = edge[0]
vehicle = self.vehicles[attrs['vehicle']]
engine = self.engines[vehicle["engine"]]
gross_sens, prop_sens = self.calc_mass_sens_te... |
def adiabatic_expansion(temp, ltemp):
initP, initv, _, inits, fins = isothermal_addition(temp)
liquid_entropy = entliq_extrap(ltemp)
vapour_entropy = entvap_extrap(ltemp)
x = (fins - liquid_entropy)/(vapour_entropy-liquid_entropy)
new_spvolume = (x*(satvap_extrap(ltemp)-satliq_extrap(ltemp)))+satliq... | The function calculates the vapor fraction (new_x) and specific volume (final_spvolume) after an isothermal rejection process using entropy values from an adiabatic expansion and extrapolated saturation properties. It returns new_x, final_spvolume, initial entropy (inits), and pressure (press) for thermodynamic analysi... | def isothermal_rejection(temp,ltemp):
liquid_entropy, vapour_entropy, _, _, press, inits = adiabatic_expansion(temp, ltemp)
new_x = (inits - liquid_entropy)/(vapour_entropy-liquid_entropy)
final_spvolume = (new_x*(satvap_extrap(ltemp)-satliq_extrap(ltemp)))+satliq_extrap(ltemp)
return new_x, final_spvol... |
def grayscale(img):
"""Applies the Grayscale transform"""
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
def gaussian_blur(img, kernel_size):
"""Applies a Gaussian Noise kernel"""
return cv2.GaussianBlur(img, (kernel_size, kernel_size), 3)
def canny(img, low_threshold, high_threshold):
"""Applies the ... | The main task of the code is to detect and highlight lane lines in an image through a pipeline: converting the image to grayscale, applying Gaussian blur, detecting edges with Canny, masking the region of interest, using the Hough transform to identify lines, and overlaying the detected lines on the original image. | def process_image_pipeline(image):
# 1 grayscale the image
gray = grayscale(image)
# 2 Apply Gaussian smoothing
blur_gray = gaussian_blur(gray, kernel_size = 5)
# 3 Apply Canny in order to perform the edge detection
edges = canny(blur_gray, low_threshold = 50, high_threshold = 250)
# 4 T... |
def compute_reward_closeness(self, state_1, state_2):
if state_2.type == StateType.END:
return self.MAX_REWARD
elif state_2.type == StateType.MINE:
return self.MIN_REWARD
else:
return self.euclidean_dist(state_1, self.end_state) - self.euclidean_dist(state_2, ... | The function computes a reward value based on the specified policy. It selects between three methods: 'CLOSENESS' calculates reward from state proximity, 'MAXPOWER' evaluates state_2 against visited power states, and 'COMBINATION' integrates both factors. If an undefined policy is provided, it prints an error and retur... | def compute_reward(self, state_1, state_2, policy, visited_power_states):
if policy == Policy.CLOSENESS:
return self.compute_reward_closeness(state_1, state_2)
elif policy == Policy.MAXPOWER:
return self.compute_reward_maxpower(state_2, visited_power_states)
eli... |
def select_random_action(self, agent_state):
possible_actions = self.environment.actions.copy()
if (agent_state.x == 0):
possible_actions.remove(self.environment.actions[0])
if (agent_state.x == self.environment.x_size - 1):
possible_actions.remove(self.environment.action... | This code trains a reinforcement learning agent using Q-learning by iterating over episodes, exploring/exploiting actions, updating Q-values with rewards, tracking visited states, and decaying learning/exploration rates. It records episode rewards and returns the optimal policy after training. | def train(self):
for i in range(self.episode_count):
total_episode_reward = 0
# keep track of visited states
visited_power_states = []
# reset agent to some random location
self.environment.agent_state = self.environment.grid[random.randint(0, self.env... |
def parse_message(msg: ET.Element) -> dict:
"""Parses a message for data in specific columns/keys.
Args:
msg: Element of the message.
Returns:
Dict mapping column name (string) to column value (ElementTree Element).
"""
msg_cols = msg.findall("td")
return dict(zip(MESSAGE_KEYS,... | The function formats HTML generated by json2html to enhance readability using Bootstrap. It structures the HTML with Bootstrap styles, separates message types (COMMAND/LOG) into tabbed sections, sorts data alphabetically, and integrates enum data into modals. The output is a styled ElementTree with responsive layout, t... | def format_html(html: str, enum_data: Enums) -> ET.ElementTree:
"""Formats the HTML output from json2html to look better by removing data and using Bootstrap.
Args:
html: String of HTML tables.
enum_data: List of enums where each enum is a dictionary.
Returns:
ElementTree of the fo... |
def parse_args() -> argparse.Namespace:
"""Parses program arguments.
Returns:
Results from argument parsing.
"""
parser = argparse.ArgumentParser()
parser.add_argument('json_db', help='Path to the NovAtel JSON database.')
parser.add_argument('-o', '--out_file',
h... | The main task of the code is to generate HTML documentation from a JSON database by parsing command-line arguments, validating the input file, loading JSON data, converting it into formatted HTML tables, applying enum-based formatting, and saving the resulting HTML file with a specified or derived filename, then printi... | def main():
"""Main function to generate HTML documentation from the JSON database.
"""
args = parse_args()
json_database_path = Path(args.json_db)
if not json_database_path.exists():
raise FileNotFoundError(f"Database file doesn't exist: {json_database_path}")
json_database = json.load... |
def get_new_population(theta_center, theta_list, sigma, mirror_sampling):
## in place operation to generate new population in theta_list
pop_size = len(theta_list)
if not mirror_sampling:
for i in range(pop_size):
theta_i = theta_list[i]
theta_i.load_state_dict(theta_center.s... | The code trains an Evolution Strategies (ES) algorithm to optimize a neural network policy in a reinforcement learning environment. It initializes a population of models, evaluates their fitness through environment interaction, and updates a central model using weighted gradients derived from the population's performan... | def train_ES(envname,
num_train_epoch,
random_seed,
learning_rate,
episode_length,
sigma,
pop_size,
n_hidden,
mirror_sampling,
fitness_shaping,
weight_decay_rate,
action_sigma
... |
def get_new_population(theta_center, theta_list, sigma, mirror_sampling):
## in place operation to generate new population in theta_list
pop_size = len(theta_list)
if not mirror_sampling:
for i in range(pop_size):
theta_i = theta_list[i]
theta_i.load_state_dict(theta_center.s... | The main task of the code is to train a neural network using Evolution Strategies (ES) for reinforcement learning on a specified Gym environment. It initializes a population of models, evaluates their fitness through environment interaction, applies weight decay, normalizes fitness scores, and updates a central model's... | def train_ES(envname,
num_train_epoch,
random_seed,
learning_rate,
episode_length,
sigma,
pop_size,
n_hidden,
mirror_sampling,
fitness_shaping,
weight_decay_rate,
network):
... |
def build_network(
input_size,
output_size,
discrete=True,
network='policy',
n_layers=1,
size=32,
activation=nn.Tanh,
output_activation=None,
tanh_mean=False,
tanh_std=False
):
if network == 'policy':
return PGES_model(i... | The code implements a policy gradient reinforcement learning algorithm to train a neural network policy for a given environment. It collects trajectories, computes advantages using reward-to-go or discounted returns, normalizes advantages, and updates the policy via gradient ascent. An optional neural network baseline ... | def train_PG(exp_name='',
env_name='CartPole-v0',
n_iter=100,
gamma=1.0,
min_timesteps_per_batch=1000,
max_path_length=None,
learning_rate=5e-3,
reward_to_go=True,
animate=True,
logdir=None,
... |
def check_events(self):
""" Check keyboard events. """
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
self.playing = False
self.curr_menu.run_display = False
sys.exit()
if event.t... | The code defines a game loop that runs while `self.playing` is True. It processes events, checks for a start key, and renders the game screen. Depending on the selected menu option ("Human vs. Human," "EasyAI vs. Human," or "HardAI vs. Human"), it draws game lines, displays turn messages, executes the corresponding gam... | def game_loop(self):
while self.playing:
self.check_events()
if self.START_KEY:
self.playing = False
self.screen.fill(self.BG_COLOR)
if self.main_menu.state == "Human vs. Human":
self.draw_lines()
self.draw_help_msg(... |
def _reshape_einsum_inputs(
input_tensor: tf.Tensor,
equation: str,
) -> tf.Tensor:
"""Converts an input tensor of arbitrary rank to a batched matrix tensor.
Args:
input_tensor: A `tf.Tensor` corresponding to the first input of the einsum
equation.
equation: The einsum equation `string`.
R... | The function computes the squared gradient norms of an Einsum gradient decomposition, generalizing the approach for `tf.keras.layers.Dense`. It calculates the Frobenius norm squared of the gradient matrix, combining input-output interactions (`X'G`) and bias terms (`Q'G`), while handling microbatches and bias axes. The... | def compute_fast_einsum_squared_gradient_norm(
equation: str,
input_tensor: tf.Tensor,
grad_tensor: tf.Tensor,
bias_axes: Optional[str],
num_microbatches: Optional[int] = None,
) -> tf.Tensor:
"""Computes the batch gradient norms of an Einsum gradient decompostion.
This logic generalizes the on... |
def part1primitives():
# Primitives work very similar to c++, except that the data can be accessed as properties instead of functions
p = Point3d(getId(), 0, 0, 0)
assert p.x == 0
p.id = getId()
p.attributes["key"] = "value"
assert "key" in p.attributes
assert p.attributes["key"] == "value"
... | The code defines a `tutorial()` function that sequentially executes six parts of a Python tutorial, aligning with C++ functionality while highlighting Python-specific implementations. It focuses on key differences and essential features like primitives, regulatory elements, lanelet maps, file handling, traffic rules, a... | def tutorial():
# We do our best to keep the python interface in sync with the c++ implementation. As a rule of thumb: Everything
# you can do in c++ works pretty similar in python, we just "pythonized" some things. Therefore this tutorial only
# shows you just the most important things and the things that ... |
def format_table_name(table_name: str) -> str:
"""
Formats the table name by adding the prefix 'num_' if the table name starts with a number.
This is because table names in SQL cannot start with a number.
:param table_name: str, name of the table to be formatted
:return: str, formatted table name
... | (This function inserts or updates a k-line (candlestick) record into a PostgreSQL table using data from a dictionary. It dynamically creates the table if it doesn't exist, constructs an SQL INSERT statement with values from the dictionary, and adds an ON CONFLICT clause to either update existing records (if `update=Tru... | def add_kline(k: dict, update: bool = True) -> None:
"""
This function adds a k-line (candlestick) to a PostgreSQL database table.
The k-line data is passed in as a dictionary, and the update parameter
determines whether the function updates existing data or not.
:Example Inputs:
k = {
... |
def format_table_name(table_name: str) -> str:
"""
Formats the table name by adding the prefix 'num_' if the table name starts with a number.
This is because table names in SQL cannot start with a number.
:param table_name: str, name of the table to be formatted
:return: str, formatted table name
... | (The function `add_trade` inserts a trade record into a database table corresponding to the trade's symbol. It constructs the table name, creates it if missing, and prepares an SQL `INSERT` statement with values from the input dictionary. The `update` parameter determines whether to update existing records on conflict ... | def add_trade(t: dict, update: bool = True) -> None:
"""
Add a trade to the trades table in the database.
:param t: A dictionary containing the trade information in the following format:
t = {
"e": "trade", // Event type
"E": 123456789, // Event time
"s": "BNBBTC... |
def format_table_name(table_name: str) -> str:
"""
Formats the table name by adding the prefix 'num_' if the table name starts with a number.
This is because table names in SQL cannot start with a number.
:param table_name: str, name of the table to be formatted
:return: str, formatted table name
... | The main task of the code is to insert multiple trade records into a database table named "{symbol}_trade", handling conflicts by either updating existing entries (if update=True) or ignoring them. It processes trades in batches of 1000 for efficiency, dynamically creating the table if it doesn't exist, and uses SQL IN... | def add_multiple_trades(symbol: str, trades: List[dict], update: bool = False) -> None:
"""
Add multiple trades to a table with the name format "{symbol}_trade".
:param symbol: The trading pair symbol.
:param trades: A list of dictionaries containing trade information.
:param update: Whether to upd... |
def _get_all_next_states(self, matris):
posY, posX = matris.tetromino_position
valid_observations = []
valid_actions = []
for i in range(COLOR_TO_ROTATION[matris.current_tetromino.color]):
shape = matris.rotated(i)
maxPosX = posX
while matris.blend(sha... | The code resets the environment, retrieves initial observations and next states, processes them with handcrafted features or dimension expansion, and returns the observation, next states, reward, done status, and info for the environment reset. | def reset(self):
obs, reward, done, info = self.env.reset()
all_next_states = self._get_all_next_states(self.matris)
if self.handcrafted_features:
all_next_states_ = []
for action, observation in all_next_states:
all_next_states_.append(
... |
def _get_observation(self, observation):
if self.handcrafted_features:
return self._get_handcrafted_observation(observation)
return np.expand_dims(observation, axis=2)
def _get_all_next_states(self, matris):
posY, posX = matris.tetromino_position
valid_observations = []
... | The main task of the code is to execute a Tetris action (rotation and movement) by processing the given action parameters, updating the game state through environment steps, checking for game completion, and returning the resulting observation, reward, and possible next states. It handles rotation, horizontal movement,... | def step(self, action):
"""
action Tuple(int, int, int): 1st entry is the number of rotation needed.
The 2nd and 3rd entries are valid target position (y, x) for the falling piece
"""
rotation, y, x = action
cur_position = self.matris.tetromino_position
for _ in r... |
def init_weights(nn_structure):
W = {}
b = {}
for l in range(1, len(nn_structure)):
W[l] = r.random_sample((nn_structure[l], nn_structure[l-1]))
b[l] = r.random_sample((nn_structure[l], ))
return W, b
def init_tri_values(nn_structure):
tri_W = {}
tri_b = {}
for l in range(1, ... | This function trains a neural network using gradient descent by iteratively updating weights and biases to minimize the cost function. It initializes parameters, performs forward propagation, computes layer deltas, accumulates gradients, and updates parameters using the learning rate. The average cost per iteration is ... | def train_nn(nn_structure, X, y, iter_num=3000, alpha=0.25):
W, b = init_weights(nn_structure)
cnt = 0
m = len(y)
avg_cost_func = []
print('Starting gradient descent for {} iterations'.format(iter_num))
while cnt < iter_num:
if cnt % 1000 == 0:
print('Iteration {} of {}'.form... |
def fix_skew_angle(self):
# edge detection
edges = self.edges_detection(
self.base_image,
config.getint(config.default_section, 'canny_threshold_1'),
config.getint(config.default_section, 'canny_threshold_2')
)
self.show_image(edges, "4. Edges")
... | The code processes an image by correcting skew, detecting edges using Canny thresholds, identifying and sorting digit bounding boxes, extracting regions of interest (ROIs), and optionally displaying intermediate results for debugging. The main task is to prepare and segment digit regions from an image for further analy... | def process(self):
self.fix_skew_angle()
# edge detection
edges = self.edges_detection(
self.base_image,
config.getint(config.default_section, 'canny_threshold_1'),
config.getint(config.default_section, 'canny_threshold_2')
)
self.show_image(e... |
def process_min(self, value):
self.min = value
self.process()
def process_max(self, value):
self.max = value
self.process()
def process(self):
detected_edges = ImageProcessor.edges_detection(self.processor.base_image, self.t1, self.t2)
contours = ImageProcessor.contours_d... | This code initializes an OpenCV window with trackbars for adjusting "Low" and "High" thresholds, linking them to update methods. It processes image data using these parameters, displays the result, and waits for user input to proceed. | def run(self):
cv2.namedWindow(self.window_name, cv2.WINDOW_AUTOSIZE)
cv2.createTrackbar("Low:", self.window_name, self.min, DigitHeight.MAX, lambda x: self.process_min(x))
cv2.createTrackbar("High:", self.window_name, self.max, DigitHeight.MAX, lambda x: self.process_max(x))
self.proces... |
def get_logits(model, dataloader, device):
# compute logits, i.e., pre-sigmoid outputs, of model
logits, lbls, metas = torch.tensor([], device=device),\
torch.tensor([], device=device), torch.tensor([], device=device)
for _, (_, inp, lbl, meta) in enumerate(dataloader):
inp, lbl, me... | The code performs inference using a model on a dataset, computes prediction metrics, and optionally determines an optimal classification threshold. It returns the threshold (either provided or optimized) along with evaluation metrics calculated from model logits, true labels, and metadata. | def infer(model, dataloader, device, threshold=0.5, predict_meta=False):
logits, lbls, metas = get_logits(model, dataloader, device)
if predict_meta:
lbls = metas
if threshold is None:
opt_threshold = find_opt_threshold(logits, lbls)
return opt_threshold, get_metrics(logits, lbls, me... |
def get_formsets(self):
return {formset_prefix: getattr(self, f"get_{formset_prefix}")() for formset_prefix in self.formsets_prefixes}
def forms_valid(self, form, **kwargs):
self.object = form.save(commit=False)
self.object.specifications_en = kwargs['specification_en_formset'].needed_data
... | This code handles POST requests by validating a main form and multiple formsets. If all are valid, it calls `forms_valid` with them; otherwise, it invokes `forms_invalid` to manage errors. | def post(self, request, *args, **kwargs):
form = self.get_form()
formsets = self.get_formsets()
if form.is_valid() and all((formset.is_valid() for formset in formsets.values())):
return self.forms_valid(form, **formsets)
else:
return self.forms_invalid(form, **for... |
def has_similar_face_in(face, faces_to_map_like_for_radius, err = 10**-10): #the function checks if exists a face with the same radius as face in order for map_all_faces_in_radius to map them with the same orientation
if len(faces_to_map_like_for_radius) == 0:
return False
for face_to_map_like in faces_... | This function processes faces within a specified radius by checking for similar (rotated) duplicates. If a duplicate exists, it aligns the new face's orientation with the existing one and adds vertices to the graph. If no duplicate is found, it directly adds the face to the graph, optionally printing debug messages in ... | def map_all_faces_in_radius(oriented_G, faces_in_radius, err = 10**-10, test = False): #the function get all faces in a specific radius and add orientation to them. if a face has a rotated duplicate they will be oriented in the same way
faces_to_map_like_for_radius = []
for face in faces_in_radius:
map_... |
def create_model_optimization_records_gpu(standard_model: nn.Module) -> List[ModelInfo]:
# This function is only for GPU testing
assert(device.type == 'cuda')
result: List[ModelInfo] = []
model_name: str = type(standard_model).__name__
standard_model.to(device)
standard_model.eval()
... | This function benchmarks the inference speed of neural network models on specified hardware (CPU/GPU) using varying batch sizes. It validates device compatibility, configures appropriate batch sizes, runs speed tests for each model, and saves results as CSV files with corresponding bar graphs comparing performance acro... | def run_speed_benchmark_tests_by_type(models: List[nn.Module], testing_mode: str) -> None:
assert ((testing_mode == 'gpu' and device.type == 'cuda') or \
(testing_mode == 'cpu' and device.type == 'cpu'))
batch_size_subset = BATCH_SIZES
if testing_mode == 'cpu':
batch_size_subset = BATCH... |
def create_model_optimization_records_gpu(standard_model: nn.Module) -> List[ModelInfo]:
# This function is only for GPU testing
assert(device.type == 'cuda')
result: List[ModelInfo] = []
model_name: str = type(standard_model).__name__
standard_model.to(device)
standard_model.eval()
... | The function runs accuracy benchmark tests on multiple neural network models for either GPU or CPU, validating device compatibility. It generates optimization records, evaluates model accuracy, stores results in CSV files, and creates bar graphs to visualize performance differences across models and testing modes. | def run_accuracy_benchmark_tests_by_type(models: List[nn.Module], testing_mode: str) -> None:
assert ((testing_mode == 'gpu' and device.type == 'cuda') or \
(testing_mode == 'cpu' and device.type == 'cpu'))
for model in models:
model_name = type(model).__name__
model_list = create_m... |
def valid(self, i=0, best_valid_acc=0):
data_iter = iter(self.validloader)
total = 0
correct = 0
mean_loss = 0
self.model.eval()
for img_seqs, label in data_iter:
# with torch.no_grad():
img_seqs = img_seqs.to(self.device)
label = label... | The code trains a neural network model by iterating over epochs and batches, performing forward and backward passes, computing loss, and optimizing parameters. It tracks training accuracy and loss, validates periodically, and updates learning rates. The best model is saved based on validation accuracy, and results are ... | def train(self):
data_iter = iter(self.trainloader)
iters = len(data_iter)
total = 0
correct = 0
best_acc = 0
best_valid_acc = 0
mean_loss = 0
for i in range(self.max_epoch):
for j in range(iters):
try:
img... |
def start(self):
self.draw()
time.sleep(0.25)
self.revealAll()
self.draw()
time.sleep(3)
self.hideAll()
self.draw()
def handleEvents(self):
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
s... | The code defines a `play` method that initializes a game loop by starting the game, then continuously handles events, updates game state, and renders graphics in a loop until terminated. | def play(self):
self.start()
while True:
self.handleEvents()
self.update()
self.draw() |
def fitness(self, sample, fullrange):
"""Given a sample match, determine fitness as a float (0,1)"""
# sample,reference are the
# comparing [(index0, index1)]
# reference:{---------[++++++]-----------}
matchpoint = 0.0001 # base value for having a match (also provides room to el... | The code evolves a population using fitness-based selection, simulated annealing for parent-child comparison, and diversity maintenance. It calculates adjusted fitness, generates new individuals, tracks metrics like average fitness and diversity, and updates telemetry data for monitoring. The process iteratively improv... | def run_population(self, pop, modifier=1.0001):
"""Given a population, runs parameters to produce new population"""
if not self.target or not self.sourcetext:
print(
'Invalid start status, target = "{}" len(source) = {}'.format(
self.target, len(self.sourc... |
def Mn(n, u):
if n < 2:
print("Order of B-spline is less than 2\n")
exit()
if n == 2:
if u < 0.0 or u > 2.0:
return 0.0
if u < 1.0:
return u
else:
return 2.0 - u
return u/(n-1)*Mn(n-1, u) + (n-u)/(n-1)*Mn(n-1, u-1)
de... | The function `bspline_1d` evaluates a 1D B-spline at a specified point `x1` using input data points, with optional computation of first and second derivatives. It scales `x1` to a grid index range, computes the B-spline basis function values (`Mn`) and their derivatives (`dMn`, `dMn2`), and aggregates weighted contribu... | def bspline_1d(data, min_x1, max_x1, \
num_x1, x1, order, f_d1 = True, f_d2 = True):
# num_x1: number of data points
# min_x1: x-coordinate of the first data point
# max_x1: x-coordinate of the last data point
# order: B-spline order
# f_d1: flag for calculating first-derivative value
# f_d2: flag for c... |
def word_embedding_training(dataset):
"""
Function: Training the Word2Vec model.
:param dataset: Dataset.
:return: Trained model
"""
sentences = []
for new in dataset:
word_list = get_word_list_in_sentence(new[0])
sentences.append(word_list)
word2Vec_model = Word2Vec(sent... | The code performs k-fold cross-validation on a training and development dataset to train and evaluate a logistic regression model. It iteratively splits the data into training and validation sets, trains the model using frequency dictionaries and word embeddings, computes macro-averaged F1-score, accuracy, precision, a... | def kfold_training(training_and_dev_set, k):
"""
Function: k-fold cross-validation, and tuning parameter by grid search.
:param training_and_dev_set: The training and development sets of data.
:param k: The k value of k-fold.
:return: The best classifier with the best parameters is selected after gr... |
def _on_request(self, request_msg):
"""Handle REQUEST type message
a. Cache the request if the node is in the critical section currently.
b. Otherwise, check if the node has voted for a request or not.
i. If it has, either send an INQUIRE message to the previous
... | This function processes incoming messages by logging them conditionally, updating the node's Lamport timestamp, and routing the message to appropriate handlers based on its type (e.g., request, grant, release). It ensures proper message-type-specific actions are triggered while maintaining synchronization through times... | def _process_message(self, msg):
"""Process message received from the socket.
Args:
msg (Message): message received by server socket
"""
if self._node.OPTION == 1:
logging.log_receive_message(msg)
#logging.log_receive_message_debug(msg, self._node.lamport_... |
def strToExpr(self, s: str) -> str:
"""
Description
-----------
Parses an expression from simple format or LaTeX, quick to type in the command line to a python expression.
Useful for copy-pasting stuff from Desmos Graphing Calculator or some documents and for typing simply by han... | The function `compileCartesianEquation` converts a given text or LaTeX equation into two representations: a string matrix visualizing the equation's Cartesian plane and a boolean mask indicating where the equation holds true. It processes the input equation by parsing it, calculating the corresponding Cartesian plane, ... | def compileCartesianEquation(self, eq: str) -> str:
"""
Parameters
----------
eq: str
A text or LaTeX equation
Returns
-------
A tuple (See cartesianEqsToStrMatrix above, See planeToBool above)
"""
eq, mode = self.strToExpr(eq)
... |
def X(self):
"""
Description
-----------
Automatically create a 2D space with left-to-right gradient from minimum x-axis bound[0][0]
to maximum x-axis bound[0][1] (using np.linspace). The length of the array is the
horizontal canvasSize[0] by the vertical canvasSize[1] (s... | This code initializes a plotting system by setting up a coordinate grid (canvasSize and bounds), defining mathematical functions/constants for calculations, and configuring visualization parameters like marching squares masks, character sets for text rendering, and color codes for console output. It prepares the enviro... | def __init__(
self,
canvasSize: Tuple[int, int] = (45, 21),
bounds: Tuple[Tuple[float, float], Tuple[float, float]] = (
(-12, 12),
(-12, 12),
),
):
"""
Parameters
----------
canvasSize: Tuple[int,int]
The number of (... |
def compileCartesianEquation(self, eq: str) -> str:
"""
Parameters
----------
eq: str
A text or LaTeX equation
Returns
-------
A tuple (See cartesianEqsToStrMatrix above, See planeToBool above)
"""
eq, mode = self.strToExpr(eq)
... | The function generates a Cartesian coordinate system matrix with X and Y axes, adding arrowheads at the ends, overlaying them, and applying a specified color (defaulting to grey). It constructs axes from equations, positions arrows using bounds, combines elements via matrix overlays, and returns the final colored matri... | def cartesianAxes(self, color=None): # defaults to grey
if color == None:
color = self.colors.GREY
xAxis = self.compileCartesianEquation("y=0")[0]
yAxis = self.compileCartesianEquation("x=0")[0]
arrows = {
"<": (np.real(self.X()[0][0]), 0),
">": (self... |
def newCanvasMatrix(
self, canvasSize: Tuple[int, int] = (-1, -1), character: str = " "
) -> np.string_:
"""
Description
-----------
Used to create a blank canvas full of spaces with swappable characters
to be populated by other functions
Parameters
-... | This function converts a list of mathematical equations into a visual matrix representation, overlaying or intersecting their graphs based on parameters. It allows custom coloring, coordinate axes drawing, and handles system intersections where all equations overlap. The output is a numpy array matrix for display. | def cartesianEqsToStrMatrix(
self,
eqs: List[str],
drawAxes: bool = True,
system: bool = False,
intersect: str = "x",
contourOnTop=True,
colors: List[str] = [None],
) -> np.ndarray:
"""
Description
-----------
Magic
Par... |
def cartesianPointsToStrMatrix(
self,
positions: List[Tuple[int, int]],
characters: List[str] = ["o"],
colors: List[str] = [None],
):
"""
Description
-----------
Generates a strMatrix with a characters corresponding to the given position on the coordin... | This function generates an ASCII Cartesian plot by converting point coordinates into a string matrix using specified characters and colors, then optionally overlaying grid axes. It returns the resulting ASCII art as a string for display or further processing. | def plotCartesianAsciiPoints(
self,
positions: List[Tuple[int, int]],
character: str = "o",
drawAxes: bool = True,
colors: List[str] = [None],
):
"""
Description
-----------
See cartesianPointsToStrMatrix above
Returns
-------
... |
def _reset_thread(self):
self.thread_ts = None
def _dict2str(info: dict) -> str:
return "\n".join([f"{key}:\t{value}" for key, value in info.items()])
def _list2str(info: list) -> str:
return ", ".join([str(elem) for elem in info])
def _start_function(self, send_message: str):
self.start... | The wrapper_function executes a target function, logs start/end messages with arguments/return values, handles exceptions by notifying errors, and resets threads. It constructs messages from inputs, triggers the function, and notifies completion or errors with detailed logs. | def wrapper_function(*args, **kargs):
self._reset_thread()
send_message = f"{self._dict2str(info)}\n{self._list2str(args)}\n{self._dict2str(kargs)}"
self._start_function(f"{start_message}\n{send_message}") ###
try:
end_message = functi... |
def read(name: str) -> list:
""" read a txt file and put the lines in a list
Args:
name(str): the input txt file
Return:
raw_data(list): all the lines of the input txt file
Exceptions:
the execption raise when the file doesn't exist in the input_file folder
the expecti... | The main task of the code is to process raw data from a text file by reading, cleaning, and comparing worker-hour pairs. It converts the data into a structured dictionary, prints the results, and saves them to a "results" folder without returning any values. | def run(read_name):
"""principal function with the main procces
Args:
read_name (str): the name of the raw data file
Return:
The function doesn't return any variables
"""
# read the txt file and put in a list
raw_data: list = read(read_name)
# put the initial list in a mo... |
def optimize_query(ws):
i = 0
for w in ws:
if w is not_found:
i += 1
else:
break
return ws[i:]
def lo_hi_of(entries, i2s, x):
"""
- `lo`: inclusive
- `hi`: exclusive
Use as `e[lo:hi]`.
"""
# todo: use interpolation search
i = bisect.bisect... | The function generates candidate tuples from a tree structure and symbols, optimizes the symbols, calculates bounds, recursively processes sub-trees, counts candidates, and returns them sorted by count in descending order. | def candidates(tree, syms):
assert syms
assert len(tree) > len(syms)
assert isinstance(tree[0], tuple)
syms = optimize_query(syms)
if not syms:
return ()
lo, hi = lo_hi_of(tree[0][0], tree[0][1], syms[0])
return sorted(
count_candidates(_candidates(tree[1:], syms[1:], lo, h... |
def fuzzy_queries(ws):
for q in itertools.product(
*[_query_entry(w)
for w
in reversed(ws)]
):
yield tuple(reversed(q))
def encode(ws, sym_of_w):
return tuple(_encode(w, sym_of_w) for w in ws)
def candidates(tree, syms):
assert syms
assert len(tree) > ... | The main task of the code is to search for related words and their counts using fuzzy queries on a database, leveraging caching to avoid redundant computations. It processes encoded symbol queries, retrieves candidate word-symbol pairs from a tree structure, and yields unique results while logging cache hits or new ent... | def _search(
db,
ws,
cache,
):
seen = set()
sym_of_w = db['sym_of_w']
w_of_sym = db['w_of_sym']
tree = db['tree']
for syms in fuzzy_queries(encode(ws, sym_of_w)):
if all(sym == not_found for sym in syms):
continue
if syms in cache:
logg... |
def load_cache(f, path, mtime):
try:
mtime_cache = os.path.getmtime(path)
except Exception:
mtime_cache = -(2**60)
if mtime_cache > mtime:
try:
with open(path, 'rb') as fh:
f(pickle.load(fh))
return True
except Exception:
pa... | The function `load_db` loads or updates a database from text files. It first checks a cache (using `load_cache`) to avoid reprocessing; if unsuccessful, it processes text files, splits them into chunks, updates the database, and asynchronously saves the updated database to a file using `pickle`. Returns `True` if cache... | def load_db(
db,
txt_files,
n,
mtime,
db_file,
):
if load_cache(lambda c: db.update(c), db_file, mtime):
return True
db.update(make_db(read_and_split_all_txt(txt_files), n))
def save_db():
try:
os.makedirs(os.path.dirname(db_file), exist_... |
def plot_beam_driven(self, out_num, **kwargs):
h_fig = plt.figure(**kwargs)
self.outfile.out_num=out_num
h_ax = h_fig.add_subplot(111)
self.plot_background(h_fig, h_ax)
if self.driver_spec_name is not None:
self.outfile.field_name=self.density_type
self.o... | The main task of the code is to generate and save plots based on the specified `plot_type` (beam_driven, laser_driven, or phasespace_raw) for a given `out_num`. It checks if the output file already exists, skips saving if not overwritten, and saves the generated figure in the specified format (`self.save_type`) while h... | def plot_save(self, out_num, overwrite = False, **kwargs):
'''if 'out_num' in kwargs:
out_num = kwargs['out_num']
else:
out_num = args[0]
if 'overwrite' in kwargs:
overwrite = kwargs['overwrite']
kwargs.pop('overwrite')
else:
ov... |
def forward_supervised_loss(self, x, y, c, f, l):
# Compute supervised losses of forward model
y_out, c_out, f_out, z_out = self.eval_forward(x, y)
y_loss = tf.reduce_mean((y_out - y)**2, axis=1)
c_loss = tf.reduce_mean((c_out - c)**2, axis=1)
# For f losses, we include implied ... | This function computes multiple loss components for a dataset, including supervised losses (yf, c, f), MMD losses on latent (z) and output (x) spaces, and reconstruction error (yi). It processes batches, repeats inputs N_reps times, generates random noise, evaluates model outputs, and aggregates normalized losses acros... | def compute_dataset_loss(self, ds, N_reps=1):
yf_loss, c_loss, f_loss, z_loss = 0., 0., 0., 0.
x_loss, yi_loss = 0., 0.
N_loss = 0.
for xx, yy, cc, ff, ll in ds:
N_batch = xx.shape[0]
yf_l, c_l, f_l = self.forward_supervised_loss(xx, yy, cc, ff, ll)
_... |
def eval(self, test_loader, dataset_idx, biases=None, copy_train=False, cv=None, replay=False):
"""Performs evaluation."""
if not self.args.disable_pruning_mask:
self.pruner.apply_mask(dataset_idx)
if biases is not None:
self.pruner.restore_biases(biases)
... | The code performs pruning on a neural network by evaluating the model pre-pruning, applying the pruning process, and evaluating post-pruning. It saves the pruned model and optionally conducts fine-tuning to enhance performance. The task includes checking model integrity, calculating accuracy, and summarizing pruning re... | def prune(self):
"""Perform pruning."""
print('Pre-prune eval:')
self.eval(self.pruner.current_dataset_idx)
self.pruner.prune()
self.check(True)
print('\nPost-prune eval:')
errors = self.eval(self.pruner.current_dataset_idx)
accuracy = 10... |
def exe_query(conn,cursor):
conn=db_connection()
cursor=conn.cursor()
return conn,cursor
def blood_loc(new_bloodgroup,new_location):
a,b=exe_query('con','cursor')
new_bloodgroup=request.form['bloodgroup']
new_location=request.form['location']
b.execute("""SELECT * FROM blood WHERE location... | The code handles POST requests to search for blood donors based on parameters like blood group, location, gender, or email. It checks combinations of these inputs, calls helper functions to query donor data, and returns JSON responses indicating availability or errors. If a donor is found, it returns the result; otherw... | def searchdonnar():
a,b=exe_query('con','cursor')
new_bloodgroup=request.form.get('bloodgroup')
new_location=request.form.get('location')
new_gender=request.form.get('gender')
new_email=request.form.get('email')
if request.method=="POST" and new_location and new_bloodgroup and not n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.