dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def format_name_for_url(name):
return name.replace(" ", "-").lower()
def format_name_for_storing(name):
return name.replace("'", "-").replace("Jr.", "Jr").replace("Sr.", "Sr").replace(". ", " ").replace(".", "-")
def extract_player_data(name, different_names_df, team, web_roster, team_rookies=[]):
f_name, i... | This code collects and stores NFL team player data from a website into an Excel file, formatting names, merging with existing data, and logging invalid names for a specified team. | def do_full_team_collection(team):
full_team_name = full_team_names[team]
web_roster = pd.read_html("https://www.nfl.com/teams/" + format_name_for_url(full_team_name) + "/roster")[0]
web_roster_names = list(web_roster["Player"])
for i in range(0, len(web_roster_names)):
web_roster_names[i] = for... |
def check_if_collection_exists(collection_id):
collections = list_collections()
for collection in collections:
if collection["id"] == collection_id:
collection_id = collection["id"]
break
else:
print("Collection with id '{}' not found.".format(collection_id))
... | This function exports a collection's items and related databases into a JSON file, including retrieving data for each item based on its model type (card/dashboard) and saving the structured data to the specified file path. | def export_collection(collection_id, file_path):
check_if_collection_exists(collection_id)
collection_items = get_collection_items(collection_id)
for item in collection_items:
model = item["model"]
id = item["id"]
if model == "card":
data = get_card(id)
elif mod... |
def check_if_collection_exists(collection_id):
collections = list_collections()
for collection in collections:
if collection["id"] == collection_id:
collection_id = collection["id"]
break
else:
print("Collection with id '{}' not found.".format(collection_id))
... | The main task of the code is to import and process a JSON export file into a collection by verifying its existence, loading database mappings, and creating cards/dashboards within the specified collection using the exported data. | def import_collection(export_file, collection_id):
check_if_collection_exists(collection_id)
with open(export_file) as export_file:
export_data = json.load(export_file)
load_database_mapping(export_data["databases"])
for item in export_data["collection_items"]:
if item["model"] == "ca... |
def sample(
params,
num_samples=10**3,
thermalization_steps=200,
skip_count=50,
variation_size=1.0,
key=jax.random.PRNGKey(np.random.randint(0, 10000)),
skipping=True,
):
outputs = []
all_data = []
coords_t = np.random.uniform(-variation_size, variation_size, num_particles)
... | The code computes the autocorrelation of energy values by sampling parameters, binning energy data across varying bin sizes, and plotting bin size against uncertainty to analyze how energy estimates' variability changes with binning. | def autocorrelation(params):
samples = sample(
params,
num_samples=10**3,
thermalization_steps=200,
skip_count=40,
variation_size=1,
key=jax.random.PRNGKey(np.random.randint(0, 100)),
skipping=False,
)
energies = [Hpsi(s, params) for s in samples]
... |
def remove_piece(self, position):
#get piece number at given board position
piece = self.board.get_square_status(position=position)
#pickup the piece
self.pick_piece(piece)
#throw the piece in the graveyard
self.trash_piece()
def move_piece(self, current_pos, final_pos):... | The function executes a chess move by validating the move, removing the target piece if it's a kill move, moving the piece from the current position to the final position, updating the board state, and triggering a robotic joint state and pose retrieval for mechanical execution. | def execute_chess_move(self, current_pos, final_pos, kill_move):
#Check move validity and type
if kill_move:
#remove the victim
self.remove_piece(final_pos)
self.move_piece(current_pos, final_pos)
self.board.update_board(current_pos, final_pos)
self.rea... |
def wave_height_printer():
wave_height = surf_info_finder().find('td', string='Wave Height (WVHT):').find_next_sibling().get_text().strip()
# print("Current Wave Height:", wave_height)
# print(wave_height)
return wave_height
def wave_interval_printer():
wave_interval = surf_info_finder().find('td', string='Dominan... | The code evaluates current weather and wave conditions in Boston by checking if wave height and interval are not in predefined lists, wind direction is valid, and wind speed is below 17. If met, it prints "Good Waves Right Now in Boston! Go out & Surf!" Otherwise, it advises against surfing due to poor conditions. | def forecast_logic():
wave_height_ = wave_height_printer()
wave_interval_ = wave_interval_printer()
wind_direction_ = wind_direction_printer()
air_temp_ = air_temp_printer()
water_temp_ = water_temp_printer()
wind_speed_spliced_ = wind_speed_splicer()
# if wave_height_ not in wave_height_list:
if wave_height_ ... |
def wave_height_printer():
wave_height = surf_info_finder().find('td', string='Wave Height (WVHT):').find_next_sibling().get_text().strip()
# print("Current Wave Height:", wave_height)
# print(wave_height)
return wave_height
def wave_interval_printer():
wave_interval = surf_info_finder().find('td', string='Dominan... | The function `forecast_summary_printer` prints a formatted summary of current weather and tide data for Boston Harbor. It displays wave height, interval, wind direction, air and water temperatures, and wind speed by calling respective helper functions. It also includes a section for tide information retrieved via `tide... | def forecast_summary_printer():
print("-----Wave Info: Boston Harbor-----")
print("\n")
print("Current Wave Height:", wave_height_printer())
print("Current Wave Interval:", wave_interval_printer())
print("Current Wind Direction:", wind_direction_printer())
print("Current Air Temperature:", air_temp_printer())
pr... |
def square_under_attack(self,r,c):
self.whiteToMove = not self.whiteToMove #swap turn to make the opponent's moves
opponentMove = self.getAllPossibleMove()
self.whiteToMove = not self.whiteToMove #swap back
for move in opponentMove:
if move.endRow == r and move.endCol == c: #... | This function generates valid castling moves for the king if the current player has the right to castle. It checks if the king is not under attack, then verifies king-side or queen-side castling permissions. If valid, it calls respective methods to add castling moves to the provided list. | def getCastleMove(self,r,c,moves):
if self.square_under_attack(r,c):
return
if (self.whiteToMove and self.Castle.wks) or (not self.whiteToMove and self.Castle.bks):
self.getKingSideCastleMove(r,c,moves)
if (self.whiteToMove and self.Castle.wqs) or (not self.whiteToMove an... |
def getGreedyMove(gs,ValidMoves):
global nextmove
muliplier = 1 if gs.whiteToMove else -1
bestopponentMINMAXscore = checkmate
nextmove = None
random.shuffle(ValidMoves)
for AImove in ValidMoves:
gs.makeMove(AImove)
if gs.isPawnPromotion:
gs.undoMove()
... | This function determines the best move for a game AI by evaluating valid moves using either a greedy algorithm or the negamax algorithm with alpha-beta pruning. It adapts the search depth, tracks game state metrics, and returns the optimal move (nextmove) based on the selected strategy, aiming to maximize the player's ... | def getBestMove(gs, ValidMove):
global nextmove,count,maxdepth,endGame,piece_count,k,last_move,last_move_count,count_store,whiteScore,blackScore
nextmove = None
print('-----------------------------------')
if greedy:
getGreedyMove(gs,ValidMove)
elif negamax:
getNegaMaxM... |
def getAllPossibleMove(self):
self.piece_count = 0
moves = []
for r in range(len(self.board)):
for c in range(len(self.board[r])):
if self.board[r][c] != '--':
self.piece_count += 1
turn = self.board[r][c][0] #check if the piece at ... | The function generates all valid chess moves by checking each possible move for legality, ensuring the king isn't in check after the move. It iterates through generated moves, simulates each, checks for check status, removes invalid moves, and determines checkmate/stalemate conditions. The original game state is restor... | def getValidMove(self):
#generate all possible move
tempEnpassantPossible = self.enPassantPossible
tempCastleRight = CastleRights(self.currentCastlingRight.wks,self.currentCastlingRight.bks,
self.currentCastlingRight.wqs,self.currentCastlingR... |
def all_summer_product_price():
"""
all_summer_product_price function will gonna collect all sunscreens product
price and return it.
"""
product_list = driver.find_elements_by_xpath("//*[contains(text(),'SPF-50')\
or contains(text(),'SPF-30')... | The function `adding_to_cart` adds the most expensive product to a shopping cart based on the given season. It retrieves price lists for summer or winter products, identifies the highest-priced item, clicks its "Add" button using XPath, waits, and then navigates to the cart by clicking the "Cart" button. The task invol... | def adding_to_cart(season):
"""
adding_to_cart function is gonna take season as the argument and based upon
that it adds the product.
"""
if season == "summer":
price_list = all_summer_product_price()
elif season == "winter":
price_list = all_winter_product_price()
... |
def getAllPossibleMoves(self):
moves = []
for r in range(len(self.board)):
for c in range(len(self.board[r])):
turn = self.board[r][c][0]
if (turn == 'w' and self.whiteMove) or (turn == 'b' and not self.whiteMove):
piece = self.board[r][c][1]
self.getMoves(piece,r, c, moves)
return moves
def... | The main task of the code is to generate all possible moves, filter out invalid ones that leave the king in check, and handle checkmate/stalemate scenarios by updating the game state and notation log. It returns the list of valid moves after processing. | def getValidMoves(self):
#1. generate all possible moves
moves = self.getAllPossibleMoves()
#2. for each move,
for i in range(len(moves)-1, -1, -1): #transverse list backwards so we can delete if need be safely
#3. generate all opponents moves
self.makeMove(moves[i], moves)
#4. for each of opponents m... |
def makeMove(self, move, validMoves):
notation = "Null"
#EN PASSANT
if move.flag == 1: #flag 1 = white en passant left
self.board[move.startRow][move.startCol] = "-"
self.board[move.startRow][move.startCol-1] = "-"
self.board[move.endRow][move.endCol] = move.pieceMoved
startCol = self.colNotation[... | The code implements a Minimax algorithm for a board game, evaluating all possible move sequences for the current player (White) by recursively assessing subsequent moves and their outcomes. It calculates scores for each potential first move, considers opponent responses, and selects the move with the highest score. Ana... | def miniMax(self, moves): #FOR WHITE TURN
#ANALYTICS
startTime = time.perf_counter()
totalCalcs = 0
firstSetScores = []
bestMoveIndex = []
finalIndex = -1
if len(moves) == 1:
self.makeMove(moves[0], moves)
else:
priorEval = self.boardScore
originalNotationLog = self.notationLog[:]
or... |
def makeMove(self, move, validMoves):
notation = "Null"
#EN PASSANT
if move.flag == 1: #flag 1 = white en passant left
self.board[move.startRow][move.startCol] = "-"
self.board[move.startRow][move.startCol-1] = "-"
self.board[move.endRow][move.endCol] = move.pieceMoved
startCol = self.colNotation[... | This function implements the Minimax algorithm with Alpha-Beta pruning to select the optimal move for the current player (White) in a board game. It evaluates all possible moves and their outcomes, considering opponent responses, while pruning suboptimal branches to reduce computation. Analytics track calculation count... | def miniMaxAB(self, moves): #FOR WHITE TURN
#ANALYTICS
startTime = time.perf_counter()
totalCalcs = 0
if len(moves) == 1:
self.makeMove(moves[0], moves)
else:
priorEval = self.boardScore
v = -INFINITY #score of best move
vi = -1 # index of best move
alpha = -INFINITY
beta = INFINITY
... |
def makeMove(self, move, validMoves):
notation = "Null"
#EN PASSANT
if move.flag == 1: #flag 1 = white en passant left
self.board[move.startRow][move.startCol] = "-"
self.board[move.startRow][move.startCol-1] = "-"
self.board[move.endRow][move.endCol] = move.pieceMoved
startCol = self.colNotation[... | The code implements a minimax algorithm for a board game, evaluating all possible first moves for Black and their subsequent White responses. It calculates scores for each move path, selects the optimal move by minimizing the maximum potential loss, and applies the chosen move. Analytics track computation time, move ev... | def maxMini(self, moves): #FOR BLACK TURN
#ANALYTICS
startTime = time.perf_counter()
totalCalcs = 0
firstSetScores = []
bestMoveIndex = []
finalIndex = -1
if len(moves) == 1:
self.makeMove(moves[0], moves)
else:
priorEval = self.boardScore
originalNotationLog = self.notationLog[:]
... |
def makeMove(self, move, validMoves):
notation = "Null"
#EN PASSANT
if move.flag == 1: #flag 1 = white en passant left
self.board[move.startRow][move.startCol] = "-"
self.board[move.startRow][move.startCol-1] = "-"
self.board[move.endRow][move.endCol] = move.pieceMoved
startCol = self.colNotation[... | This code implements the minimax algorithm with alpha-beta pruning to determine the optimal move for White in a board game (likely chess). It evaluates all possible moves and their subsequent opponent responses, prioritizing the move with the highest score while pruning suboptimal branches to improve efficiency. The fu... | def maxMiniAB(self, moves): #FOR WHITE TURN
#ANALYTICS
startTime = time.perf_counter()
totalCalcs = 0
if len(moves) == 1:
self.makeMove(moves[0], moves)
else:
priorEval = self.boardScore
v = INFINITY #score of best move
vi = -1 # index of best move
alpha = -INFINITY
beta = INFINITY
... |
def _profile_helper(self, func, name):
if not self.mem:
tt.tic(name)
func()
tt.toc(name)
else:
with profile(
activities=
[
ProfilerActivity.CPU
] if not usingcuda else
... | This code simulates and profiles a Faster R-CNN model by measuring execution time and details of key components: image transformation, backbone/FPN feature extraction, RPN (region proposal network) operations, and ROI heads for object detection. It uses helper functions to track performance metrics and reveal implement... | def faster_rcnn_simulation(self):
self._profile_helper(self.get_original_images_sizes, "get_original_images_sizes")
self._profile_helper(self.transform, "transform")
self.backbonefpn_details()
self.backbonefpn_fpn_details() # uncomment to reveal details
self.rpn_head()
... |
def generate_state(self, environment):
hx, hy, body, fx, fy = environment
fdx = 0
if hx > fx:
fdx = 1 # food on snake head left
elif hx < fx:
fdx = 2 # food on snake head right
fdy = 0
if hy > fy:
fdy = 1 # food on sna... | The code's main task is to select an optimal action (UP, DOWN, LEFT, RIGHT) for a snake game agent based on the current environment state, using Q-learning. It converts the environment into a discretized state, updates Q-values during training with rewards, and chooses actions by balancing exploration/exploitation. If ... | def act(self, environment, points, dead):
'''
:param environment: a list of [snake_head_x, snake_head_y, snake_body, food_x, food_y] to be converted to a state.
All of these are just numbers, except for snake_body, which is a list of (x,y) positions
:param points: float, the current poi... |
def calculate_bleu_sent(self, ref_sents, sys_sents):
"""
Calculate BLEU by SacreBLEU sentence level by the guideline: https://github.com/mjpost/sacreBLEU.
final score is 0 to 100.
*Please note that sentence-level BLEU score is not a good way to report compared to document/corpus level BL... | The function creates a structured DataFrame combining linguistic features, evaluation scores (z-score, BLEU, METEOR), and metadata from translation system outputs. It uses cue_info_dict and obj_list to extract sentence-level data, handling English-source and non-English-source cases differently by including source/refe... | def prepare_info_dataframe(self, tr_src, cue_info_dict, obj_list):
"""
Create a datafram using cue_info_dict and the score file for each system under a particular translation.
params:
@tr_src: (string), source language
@cue_info_dict: (dictionary), contains cue info of a ... |
def InitIcons(self):
self.AddButton.setIcon(QIcon(pd.__PyDist__._WorkDir+"assets/edit_add.png"))
self.AddAction.setIcon(QIcon(pd.__PyDist__._WorkDir+"assets/edit_add.png"))
self.RemoveButton.setIcon(QIcon(pd.__PyDist__._WorkDir+"assets/edit_remove.png"))
self.RemoveAction.setIcon(QIcon(... | This code initializes a PyQt5 GUI component with features like item management (add/remove/mark/clear), context menus, and UI interactions. It sets up event connections for buttons, actions, and signals, integrates an AI dialog, and handles application quit events. The class manages a list of items, updates the UI dyna... | def __init__(self,window:QMainWindow,app:QApplication):
self.window = window
self.app = app
self.app.setStyle("Fusion")
self.about = aboutUi(
pd.__PyDist__.GetAppVersion(),
windowIcon=self.window.windowIcon()
)
super().__init__()
super().... |
def get_basic_component(filename):
# before, the runner would use the directory given _in_ the component description
# which may be inaccurate
comp_desc = ComponentDescription.parse_file(filename)
comp_desc.directory = os.path.dirname(filename)
return basic_component(comp_desc, bad_type_checker)
def... | The code defines a `build` function that constructs a simulation system by loading component definitions and a wiring diagram, then generating Docker/Kubernetes configurations or a runner setup based on the `multi_container` flag. It processes input files, validates components, and creates deployment structures for sim... | def build(
target_directory,
system,
component_dict,
multi_container,
broker_port,
):
"""Build to the simulation folder
Examples::
oedisi build
oedisi build --component-dict components.json --system scenario.json
\f
Parameters
----------
target_directory ... |
def _format_target(self, song):
return os.path.join(self.target, self._format_tail(song))
def _ensure_dirname(path):
os.makedirs(os.path.dirname(path), exist_ok=True)
def _tag_file_get_length(path, song):
mp4tags = {
'title': '\xa9nam',
'artist': '\xa9ART',
'a... | The code downloads a song's low-quality audio file to a specified path, creating directories if needed. It checks if the file already exists, and if not, streams the file from the URL, saves it, tags it with the song's length, and returns the duration. If directories can't be created or the file exists, it returns Fals... | def download(self, song):
target = self._format_target(song)
log.debug('Saving {}\\{}\\{} as {}'.format(song.album_name, song.artist_name, song.name, target))
url = song.audios['low'].url
try:
self._ensure_dirname(target)
except FileNotFoundError:
return ... |
def _unigrams(words):
"""
Input: a list of words, e.g., ["I", "am", "Denny"]
Output: a list of unigram
"""
assert type(words) == list
return words
def _bigrams(words, join_string, skip=0):
"""
Input: a list of words, e.g., ["I", "am", "Denny"]
Output: a list of bigram, e.g., ... | This function generates n-grams from a list of words based on the specified `ngram` value. It dispatches to helper functions for unigrams (1), bigrams (2), trigrams (3), and fourgrams (4). Special cases like `12` combine unigrams and filtered bigrams, while `123` combines unigrams, bigrams, and trigrams. The `join_stri... | def _ngrams(words, ngram, join_string=" "):
"""wrapper for ngram"""
if ngram == 1:
return _unigrams(words)
elif ngram == 2:
return _bigrams(words, join_string)
elif ngram == 3:
return _trigrams(words, join_string)
elif ngram == 4:
return _fourgrams(words, join_string)
elif ng... |
def find_straights(cards):
enriched_cards = _ace_enrich_for_straight_search(cards)
straight_rank_ordering = [Rank.Ace] + [rank for rank in Rank]
sequential_card_count = 0
current_rank_index = 0
for card in enriched_cards:
if card.rank != straight_rank_ordering[current_rank_index]:
... | This function evaluates a set of poker cards to determine the highest-ranking hand, following standard poker hierarchy: it checks for straight flush, four of a kind, full house, flush, straight, three of a kind, two pair, pair, and finally high card, returning the corresponding hand type with the highest value. | def evaluate_card_set(cards):
sorted_cards = sorted(cards, key=lambda card: card.rank.value)
straights = list(find_straights(sorted_cards))
straight_flush = find_straight_flush(straights)
if straight_flush:
return straight_flush
cards_by_rank = build_rank_histogram(sorted_cards)
... |
def generate_deck():
for rank in Rank:
for suit in Suit:
yield Card(rank, suit)
def deal_hand(deck):
return list(deal_x_cards(deck, HAND_SIZE))
def deal_board(deck):
return list(deal_x_cards(deck, BOARD_SIZE))
def determine_winner(cards_by_player_index, board):
evaluated_hands_by_pla... | The code simulates a card game by generating and shuffling a deck, dealing hands to four players, and setting a board. It determines the winning player based on their hand and the board, then prints the winner and their hand. The main task is to execute a card game simulation, including deck management, player dealing,... | def main():
deck = list(generate_deck())
random.shuffle(deck)
player_count = 4
cards_by_player_index = { i: deal_hand(deck) for i in range(player_count) }
board = deal_board(deck)
(winning_player_index, winning_hand) = determine_winner(cards_by_player_index, board)
print(f'Player {win... |
def detectNight(img):
GRID_DENSITY_X = 20
GRID_DENSITY_Y = 20
w, h = img.shape[::-1]
whites = 0
blacks = 0
for x in np.linspace(0, w - 1, GRID_DENSITY_X):
for y in np.linspace(0, h - 1, GRID_DENSITY_Y):
if img[int(y), int(x)] < 127:
blacks += 1
els... | The main task of the code is to process a camera feed by cropping, resizing, and detecting game elements (dino, cactuses, birds) using template matching. It highlights detected objects with colored rectangles, adjusts for night mode by inverting the image, and measures processing time. The output is a visualized frame ... | def loop(picam2, crop):
(maxX, maxY, minX, minY) = crop
start = datetime.now()
frame = cv.cvtColor(picam2.capture_array(), cv.COLOR_YUV2GRAY_I420)
playFiledNormalized = cv.resize(frame[minY : maxY, minX: maxX], (258,64))
if detectNight(playFiledNormalized):
playFiledNormalized = np.invert(pl... |
def initialize_parameters_deep(layer_dims):
parameters = {}
L = len(layer_dims) # number of layers in the network
for l in range(1, L):
parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) * 0.01
parameters['b' + str(l)] = np.zeros(shape=(layer_dims[l], 1))
... | The code implements a deep neural network with multiple layers using gradient descent. It initializes parameters, performs forward and backward propagation, updates weights via computed gradients, and tracks/trains the model over iterations. The learning process visualizes cost reduction over time, optimizing model par... | def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):#lr was 0.009
np.random.seed(1)
costs = [] # keep track of cost
parameters = initialize_parameters_deep(layers_dims)
for i in range(0, num_iterations):
# Forward propagation: [LI... |
def get_host(self):
'''
This method used to get host details.
Arguments : None
Return: None
'''
uri = 'hosts'
res = ILDC().do_ssy_details(uri, header=None)
msg = 'Get host details'
if str(res) == '<Response [200]>':
LogCreate().logger_i... | The main task of the code is to execute a test process after a 3-minute delay. It initializes configuration data, retrieves host/server information, runs a preliminary check, and conditionally triggers the test execution if the check returns a success flag (0). | def start(self):
'''
This method execute the test.
Arguments : None
Return: None
'''
time.sleep(180)
self.config_dict = {}
self.get_host()
self.get_server()
flag = self.run()
if flag == 0:
self.execute_test() |
def fire_task(self, curr_workers):
dir_name = os.path.join(self.task_dir, str(self.active_task.get_id()))
files = self.create_chunks(dir_name, len(curr_workers))
# map protocol : task map <file_chunk_path> <file_chunk_ptr> <application_name>
for ind, val in enumerate(curr_workers):
... | The code's main task is to orchestrate task execution by checking worker statuses, triggering tasks when conditions are met, managing mapping/reducing phases, handling errors, synchronizing via barriers, and writing output files, ensuring tasks complete before proceeding. | def task_handler(self):
"""
check the worker handlers status if all workers are free and if a new task can be picked up
:return:
"""
while True:
curr_workers = [k for k, v in self.worker_servers.items() if v.marker and v.role == variables.mapper]
check_cur... |
def get_start_position(mat2d):
for i in range(len(mat2d)):
for j in range(len(mat2d[0])):
if mat2d[i][j] == 1:
return Node(x = j, y = i, direction = "E")
return None
def go_dir(curr: Node, steps: int, mat2d):
dir = get_direction(curr.direction)
# eligible to go
#... | The code simulates a robot's movement on a 2D grid based on a sequence of instructions. It processes each instruction (movement steps, left/right turns) to update the robot's position and direction. The final result encodes the robot's ending coordinates and direction into a numeric value using a predefined formula. Th... | def get_result(instructions, mat2d):
instrs = copy.deepcopy(instructions)
curr: Node = get_start_position(mat2d=mat2d)
while instrs:
instr = instrs.pop()
# number
# print('start')
# print(f"{curr.x = } {curr.y = } {curr.direction = }")
if isinstance(instr, int):
... |
def _unpack_str16(self, index):
str_length = self._in_packet.packet[index+1]
str_length += self._in_packet.packet[index]
string = str(self._in_packet.packet[index+2:index+2+str_length])
return (string, index+2+str_length)
def _unpack16(b_array, index):
t = b_array[index+1] + (b_array... | This function processes an incoming MQTT PUBLISH message by parsing its header, topic, and payload. It handles QoS levels (0-2), validates the topic, and manages message state. For QoS 1/2, it sends appropriate acknowledgments (PUBACK/PUBREC) and stores messages for tracking. It sets return codes and prepares data for ... | def _handle_publish(self):
header = self._in_packet.command
message = MQTTMessage()
message.dup = (header & 0x08)>>3
message.qos = (header & 0x06)>>1
message.retain = (header & 0x01)
message.topic, c_pos = self._unpack_str16(0)
if len(message.topic) == 0:
... |
def _unpack16(b_array, index):
t = b_array[index+1] + (b_array[index]<<8)
return (t, index+2)
def print_d(*args):
if debug:
print(*args)
def _send_pubcomp(self, mid):
self._send_command_with_mid(PUBCOMP, mid, False) | This function handles an MQTT PUBREL packet by validating its structure, identifying the corresponding message using the message ID (mid), removing it from the message list, and sending a PUBCOMP response to confirm receipt, ensuring thread safety with a lock and returning a success status. | def _handle_pubrel(self):
if self._in_packet.remaining_length != 2:
raise MQTTProtocolError
if len(self._in_packet.packet) != 2:
raise MQTTProtocolError
mid,z = _unpack16(self._in_packet.packet,0)
print_d("rec PUBREL (mid: "+str(mid)+")")
self._in_messa... |
def _pack_remaining_length(self, packet, remaining_length):
while True:
byte = remaining_length % 128
remaining_length = remaining_length // 128
# If there are more digits to encode, set the top bit of this digit
if remaining_length > 0:
byte = byt... | The main task of the code is to establish a connection to an MQTT broker by creating a socket, configuring network parameters (timeout, keepalive), constructing and sending an MQTT CONNECT packet with client credentials, and resubmitting pending messages upon reconnection. It handles protocol-specific flags, authentica... | def _connect(self, host, keepalive, port=PORT, ssl_ctx=None, breconnect_cb=None, aconnect_cb=None, sock_keepalive=None):
self._before_reconnect = breconnect_cb
self._after_connect = aconnect_cb
self._host = host
self._port = port
ip = __default_net["sock"][0].gethostbyname(host... |
def _unpack16(b_array, index):
t = b_array[index+1] + (b_array[index]<<8)
return (t, index+2)
def print_d(*args):
if debug:
print(*args)
def _send_pubrel(self, mid, dup=False):
self._send_command_with_mid(PUBREL|2, mid, dup) | This function processes a PUBREC MQTT packet by validating its structure, identifying the corresponding outgoing message using its message ID (mid), updating the message state to await a PUBCOMP, and sending a PUBREL response. It ensures thread safety with a lock and returns success if the operation completes without e... | def _handle_pubrec(self):
if self._in_packet.remaining_length != 2:
raise MQTTProtocolError
mid, z = _unpack16(self._in_packet.packet,0)
print_d("Rec PUBREC mid:",mid)
self._out_message_lock.acquire()
for m in self._out_messages:
if m.mid == mid:
... |
def _send_publish(self, mid, topic, payload=None, qos=0, retain=False, dup=False):
command = PUBLISH | ((dup&0x1)<<3) | (qos<<1) | retain
packet = bytearray()
packet.append(command)
if payload is None:
remaining_length = 2+len(topic)
else:
remaining_lengt... | This function checks messages for retry deadlines, updates their timestamps and duplication flags, and resends unacknowledged MQTT messages using appropriate control packets, ensuring thread safety with a lock. | def _message_retry_check_actual(self, messages, lock):
lock.acquire()
now = timers.now()
for m in messages:
if m.timestamp + self._message_retry < now:
if m.state == mqtt_ms_wait_for_puback or m.state == mqtt_ms_wait_for_pubrec:
m.timestamp = now
... |
def _handle_pingresp(self):
print_d("reading response...")
if self._in_packet.remaining_length != 0:
raise MQTTProtocolError
self._in_packet.data['return_code'] = MQTT_ERR_SUCCESS
def _handle_pubackcomp(self):
if self._in_packet.remaining_length != 2:
raise MQTTPr... | This function processes incoming MQTT packets by identifying the command type (e.g., PINGREQ, PUBLISH) and dispatching execution to the corresponding handler method, ensuring proper protocol response handling. If an unrecognized command is detected, it raises an MQTTProtocolError to signal invalid packet format. | def _handle_packet(self):
cmd = self._in_packet.command & 0xF0
if cmd == PINGREQ:
self._handle_pingreq()
elif cmd == PINGRESP:
self._handle_pingresp()
elif cmd == PUBACK:
self._handle_pubackcomp()
elif cmd == PUBCOMP:
self._handle_p... |
def perror(self, s: Union[str, Path], err: Union[OSError, None] = None):
if self.force:
return 0
msg = f"trash: {s}"
if err is not None:
msg += f": {err.strerror}"
print(msg, file=sys.stderr)
return 1
def relative_files(self, files, fillEmpty=False):
... | This function restores files from a trash directory, handling errors for missing files, directories, metadata, and existing destinations. It checks file existence, validates metadata, resolves destination paths, and moves files while managing overwrite prompts and cleanup of trash metadata. | def restore_trash(self, files):
if not files:
return self.perror("No files to restore")
files = self.relative_files(files)
err = 0
for file in files:
if not file.exists():
err += self.perror(f"{file} does not exist in trash")
conti... |
def perror(self, s: Union[str, Path], err: Union[OSError, None] = None):
if self.force:
return 0
msg = f"trash: {s}"
if err is not None:
msg += f": {err.strerror}"
print(msg, file=sys.stderr)
return 1
def relative_files(self, files, fillEmpty=False):
... | This function processes multiple files or directories by reading their contents recursively if enabled, handling errors during file operations, and returning the total number of errors encountered during the process. | def cat_trash(self, files):
if not files:
return self.perror("No files to cat")
files = self.relative_files(files)
err = 0
for file in files:
try:
if file.is_dir() and self.recursive:
self.cat_dir(file)
else:
... |
def draw_no_connection():
draw_all()
fonts = pygame.font.SysFont("comicsans", connectButton.font)
display_text = fonts.render(str("No Connection to Server..."), 1, (0, 0, 0))
run = True
start_time = time.perf_counter()
while run:
current_time = time.perf_counter()
if current_time... | The function `run_game_stage_play` manages a connected game session by initializing player data, handling server communication, processing player inputs, updating game state (movement, collisions, health), managing hit mechanics, potion interactions, sound effects, and rendering the game stage. It maintains the game lo... | def run_game_stage_play():
topScorer = True
server_communicate = True
client_player_info =[]
hitLoadButton = HitLoadButton(playerLog[5], playerLog[6])
# Ready to connect to server
net = Network()
print("receiving: ", net.init_info)
# if no connection to ... |
def wall_is_valid(wall, walls):
#check if wall places is already occupide
if wall in walls or (wall[0], wall[1], wall[2]-1, wall[2])in walls or (wall[0], wall[1], wall[3], wall[3]+1)in walls:
return False
#check if it has collision with other wall
if wall[0] == 'V':
return ('H', wall[2],... | The function handles a player's turn in a game, allowing them to place horizontal/vertical walls (if available) or move in a direction. It validates wall placements and movements, updates the wall count, and adjusts the player's position, ensuring all actions comply with game rules. | def player_turn(player, walls, player_walls, other_players, n):
#declare whose turn it is
print(n, " player's turn")
#check if player has walls left
if player_walls != 0:
#a loop to run until a valid move is made
while True:
#let player decide to put a wall or make a move
... |
def print_game(players_place, walls):
#print 100 enter to clear screen
print('\n'*100)
#line iterator
for i in range(2*rows_and_columns-1):
#chracter iterator
for j in range(2*rows_and_columns-1):
#check if line includes game board space
if i % 2 == 0:
... | The code simulates a two-player game where players take turns moving and placing walls on a grid. The goal is to reach the opponent's side of the board (player 1 to column 7, player 2 to column 0) while ensuring walls do not block both players' paths. The game checks for win conditions, validates wall placements, and a... | def two_player_game():
#declaring players starting places and walls
player_1_place = [3, 0]
player_2_place = [4, 7]
player_1_walls = 5
player_2_walls = 5
#declaring game variables
game_is_over = False
wall_places = []
turn = 1
#main game loop
while not game_is_over:
p... |
def print_game(players_place, walls):
#print 100 enter to clear screen
print('\n'*100)
#line iterator
for i in range(2*rows_and_columns-1):
#chracter iterator
for j in range(2*rows_and_columns-1):
#check if line includes game board space
if i % 2 == 0:
... | This code simulates a four-player turn-based game where players move on a grid, place walls to block opponents, and aim to reach their designated goal edges. The game checks for valid wall placements, player wins when reaching their goal, and ends if walls block all paths. | def four_player_game():
#declaring players starting places and walls
player_1_place = [3, 0]
player_2_place = [4, 7]
player_3_place = [0, 3]
player_4_place = [7, 4]
player_1_walls = 5
player_2_walls = 5
player_3_walls = 5
player_4_walls = 5
#declaring game variables
game_is_o... |
def print_legend(self):
output = f"""\
# {self.method} for Ising model on the square lattice
# chi= {self.chi}
# T= {self.temp}
# f_exact= {self.f_exact:.12e}
# 1: step
# 2: N_spin
# 3: free energy
# 4: Relative erro... | The code's main task is to execute a loop that updates and prints results repeatedly for a specified number of steps, starting with displaying a legend and initial results. It calls `print_legend()`, `print_results()`, and iterates `step` times, updating the state and printing results each iteration to track progress o... | def run(self, step):
self.print_legend()
self.print_results()
for i in range(step):
self.update()
self.print_results() |
def cnt_freq(filename):
'''Opens a text file with a given file name (passed as a string) and counts the
frequency of occurrences of all the characters within that file'''
f = open(filename, "r")
running_cnt = [0] * 256
for line in f:
for character in line:
running_cnt[ord(charac... | The function `huffman_encode` encodes text from an input file using Huffman coding, writing the encoded result to an output file. It also generates a compressed binary file with `_compressed.txt` suffix, storing encoded bits via `HuffmanBitWriter`. The process includes creating a header for frequency data, handling emp... | def huffman_encode(in_file, out_file):
'''Takes inout file name and output file name as parameters - both files will have .txt extensions
Uses the Huffman coding process on the text from the input file and writes encoded text to output file
Also creates a second output file which adds _compressed before the... |
def initialize_partition(self,init_method = 'regular',seed = 1,figsize = (10,10),
plot_init = False,save_plot = False, plotpath = None,
plotname = 'init_partition.png'):
if init_method == 'regular':
self._initialize_regular()
... | This function implements the Cross-Entropy Method (CEM) to estimate optimal partition parameters for a multinomial distribution. It iteratively generates samples, evaluates their KL divergence scores, selects top-performing samples, updates probability distributions using a weighted average, and converges when KL diver... | def estimate_partition_CEM_multinom(self,n_sim = 100, maxiter_CE = 100,tol_ce = 0.001,
N_grid_omega = 100, N_grid_t = 100, tol_omega = 1, tol_t = 1,
beta = 0.6, rho = 0.2, seed = 1, seed_init = 1,init_method = None,bandwidth_kde = 0.1,
... |
def eval_norm_freq(orig_df, resample): # evaluate and apply ML to the data normalized by frequency
report = "Data normalized by frequency:\n"
# first way: true for cutters and false for everyone else
report += "\nFirst way: making it true for cutters and false for everyone else:\n"
df = orig_df.copy()... | The code generates a report by evaluating three normalized datasets (frequency, presence, median) using machine learning. It reads each CSV, removes irrelevant columns, applies corresponding evaluation functions, and combines results into a report. | def get_report(resample):
report = ""
df1 = pd.read_csv(f"../results/lemmas_normalized/norm_by_freq.csv", keep_default_na=False, index_col=0)
df1 = df1.drop(columns=["~~n_posts~~", "~~n_words~~"]) # remove these columns cuz we dont need them for ML
report += eval_norm_freq(df1, resample) # evaluate a... |
def _load_pack_config_placeholders(self):
#Load placeholders from the pack.config template.
#Returns a list of keys (placeholders).
with open(self.template_pack_config, 'r') as file:
template_config = yaml.safe_load(file)
return list(template_config.keys())
def _load_version_... | This function imports resources from a specified pack directory to a target directory by processing texture mappings and UID-based files. It handles texture atlases by deconstructing them, extracts variables from files, replaces placeholders, and updates the pack configuration. Missing textures are logged, and files ar... | def _import_resource_pack(self, pack_import_path, source_dir, mappings, uid_mappings):
print(f"Starting import from {pack_import_path} to {source_dir}")
missing_textures = [] # List to store missing textures
pack_config_updates = {} # Dictionary to store extracted variables
# Load pla... |
def _extract_zip_to_temp(self, zip_path):
temp_dir = tempfile.mkdtemp()
print(f"Extracting {zip_path} to temporary directory {temp_dir}")
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(temp_dir)
# Check if the contents are in a nested dire... | This code imports a Minecraft resource pack by extracting ZIP files, determining the pack's version and platform, loading mappings, and generating configuration files. It handles version detection from metadata, applies source mappings, and imports resources if a valid version is identified, otherwise reporting an erro... | def import_pack(self):
pack_import_path = self.pack_import_path
if zipfile.is_zipfile(pack_import_path):
pack_import_path = self._extract_zip_to_temp(pack_import_path)
pack_format_to_version = self._load_pack_format_to_version(self.pack_format_to_version_file)
platf... |
def load_yml_config(file_path):
with open(file_path, 'r') as file:
config = yaml.safe_load(file)
return config
def setup_logging(log_directory):
backup_directory = os.path.join(log_directory, 'backup')
# Create log directory if it doesn't exist
if not os.path.exists(log_directory):
... | The main task of the code is to generate resource packs for different platforms and versions by loading configuration files, processing mappings, adjusting resolutions, creating zip archives, and cleaning up temporary files. It reads input directories, applies transformations, and outputs versioned resource packs with ... | def main(config_path):
build_config = load_yml_config(config_path)
source_dir = build_config['source_dir']
mappings_dir = build_config['mappings_dir']
output_dir = build_config['output_dir']
tempfile_dir = build_config['tempfile_dir']
log_output_dir = build_config['log_output_dir']
source_m... |
def render_text_page(self) -> None:
"""
Render the html in the ui.
"""
# getting data
url = self.get_content_search_bar()
datetime_current = ut.get_date_current()
# saving search in the history
ut.save_in_history(Search(datetime_current, url))
ht... | The code creates a top menu bar for a UI with two main sections: 'Actions' and 'Help'. The 'Actions' menu includes options for search, history, configuration, and exiting the application, while the 'Help' menu provides access to about and contact information. Each menu item is linked to specific methods that trigger co... | def create_menu(self) -> None:
"""
Create a bar menu in the
top of the ui.
"""
# creating principal menu
self.bar_menu = Menu(
self.wind,
bg = '#222',
fg = '#CCC',
activebackground = '#333',
activeforeground = '... |
def create_node(state, parent):
return Node(state, parent)
def swap(t_node, a, b):
t_node.state[a], t_node.state[b] = t_node.state[b], t_node.state[a]
def get_manhattan_sorted_states(to_expand):
return sorted(to_expand, key=lambda s: manhattan(s.state)) | The code generates valid child nodes from a given puzzle state by exploring left, up, right, and down moves. It avoids revisiting states using a 'visited' set and prioritizes nodes using Manhattan distance sorting. The sorted valid moves are inserted into a 'to_visit' list for heuristic-based search, ensuring efficient... | def move(node):
to_expand = list()
#left
t_node = create_node(node.state[:], node)
z_index = t_node.z_index()
if(z_index not in [0,3,6]):
swap(t_node, z_index, z_index-1)
if(tuple(t_node.state) not in visited):
to_expand.insert(0, t_node)
else:
visite... |
def is_current_the_goal(node):
return node.state == goal_node.state
def show_path(node):
if(node.parent != 0):
show_path(node.parent)
node.reveal()
def move(node):
hamming_value = 9
to_expand = list()
#left
t_node = create_node(node.state[:], node)
z_index = t_node.z_index()
... | This code implements the A* algorithm to find the shortest path from an initial state to a goal state. It uses a priority queue (to_visit) to explore nodes, checks if the current node is the goal, and tracks visited states to avoid cycles. The 'move' function generates next states, and 'show_path' displays the solution... | def a_star(initial_state):
global iterations, p_size, goal_node
initial_node = Node(initial_state, 0)
#initialize the list of nodes to visit
to_visit.insert(0, initial_node)
while to_visit:
current_node = to_visit.pop(0)
if(is_current_the_goal(current_node)):
show_path(... |
def is_current_the_goal(node):
return node.state == goal_node.state
def show_path(node):
if(node.parent != 0):
show_path(node.parent)
node.reveal()
def move(node):
to_expand = list()
#left
t_node = create_node(node.state[:], node)
z_index = t_node.z_index()
if(z_index not in [0,... | The code implements the A* algorithm to find a path from an initial state to a goal state. It initializes a priority queue with the start node, iteratively explores nodes by expanding the current node, checks if it matches the goal, and tracks visited states to avoid cycles. If the goal is reached, it displays the path... | def a_star(initial_state):
global iterations, p_size, goal_node
initial_node = Node(initial_state, 0)
#initialize the list of nodes to visit
to_visit.insert(0, initial_node)
while to_visit:
current_node = to_visit.pop(0)
if(is_current_the_goal(current_node)):
show_path(... |
def log(message):
if DEBUG:
if WIN:
logging.debug(message)
if MAC:
from AppKit import NSLog
NSLog("Type.World Agent: %s" % message)
def getClient():
global prefDir
if WIN:
prefFile = os.path.join(prefDir, "preferences.json")
... | The main task of the code is to automatically reload subscriptions based on a configured interval or forced trigger, check for app updates when the application isn't running, and synchronize with a server if the last sync was too long ago. It logs progress, manages preferences for timing, and initiates updates or syncs... | def autoReloadSubscriptions(force=True):
log("started autoReloadSubscriptions()")
client = getClient()
log(client)
# Preference is set to check automatically
if (
client.preferences.get("reloadSubscriptionsInterval")
and int... |
def log(message):
if DEBUG:
if WIN:
logging.debug(message)
if MAC:
from AppKit import NSLog
NSLog("Type.World Agent: %s" % message)
def setStatus(amountOutdatedFonts, notification=False):
if amountOutdatedFonts > 0:
icon.icon = image_... | The main task of the code is to run a background daemon that periodically checks for outdated fonts, reloads subscriptions, and manages Windows-specific tasks like removing shortcuts and processing messages. It operates in an infinite loop, resetting a counter every `LOOPDURATION` seconds to trigger `autoReloadSubscrip... | def run(self):
log("beginning of run()")
# First run
# autoReloadSubscriptions(force = False)
setStatus(getAmountOutdatedFonts(), notification=False)
replyFromMothership("daemonStart")
log("about to start inner loop"... |
def outer_layer():
'''
Pre: Karel at initial position
Post: Karel colors the perimeter
'''
color = get_color()
while front_is_clear() and corner_color_is(""):
paint_corner(color)
move()
if front_is_blocked():
turn_left()
def move_inward():
'''
pre: Karel at initial position (facing Eas... | The code defines a function `rainbow_layers()` that sequentially executes three operations: initializing an outer layer, moving inward, and processing inner layers. Its main task is to structure or generate layered components, likely for visual or hierarchical data representation, by orchestrating the creation and arra... | def rainbow_layers():
outer_layer()
move_inward()
inner_layers() |
def generatePadFile(filename,size):
pad = generatePad(size)
file = open(filename,"w")
file.write(pad)
file.close()
def encipher(message,padfile):
f = open(padfile)
pad = f.read()
return addPad(message,pad)
def decipher(message,padfile):
f = open(padfile)
pad = f.read()
return subPad(mess... | The main task of the code is to handle command-line operations for generating one-time pads and using them to encrypt/decrypt files. It parses flags like -p (generate pad), -e (encrypt), -d (decrypt), and -w (specify pad file), performing corresponding actions such as creating a 10,000-character one-time pad, encryptin... | def main(argv):
#save input name from arg
One_time_pad = ''
unencryptedfile = ''
encryptedfile = ''
try:
opts, args = getopt.getopt(argv,"mp:e:d:w:")
except getopt.GetoptError:
print('please check manual')
sys.exit(2)
if not opts or len(opts) >2:
print("too many argument.")
sys.exit(2)... |
def update_endgame(self):
random.shuffle(self.black_deck)
def update_turn(self):
# game indivual turn update
if self.turn_state == TurnState.Submission:
if not self.card_czar:
self.card_czar = self.get_czar()
self.current_black_card = self.cards.draw_blac... | The `update_game` method manages the game's state transitions by executing specific updates based on the current `game_state`. If the game is ending, it handles endgame logic; if playing, it advances the turn; if waiting for players, it updates the waiting state. It also checks for a quit condition to exit early, ensur... | def update_game(self):
# game macro level update
if self.game_state == GameState.End:
# wait / ask players if they want to restart
self.update_endgame()
if self.game_state == GameState.Playing:
# Game Starts
self.update_turn()
if self.ga... |
def load_model(mpath, lexsize, bit_size, h_size):
model = NbrReg(lexsize, bit_size=bit_size, h_size=h_size)
model.double()
model.load_state_dict(torch.load(mpath))
return model
def train(train_docs, train_cats, train_knn, cv_docs, cv_cats, bitsize=32,
epoch=30, bsize=100, lr=1e-3, latent_size=... | The code defines a command-line interface for training and testing a machine learning model. It parses arguments for data paths, model parameters, training settings (epochs, batch size, learning rate), and resuming training. The 'train' task loads training data, trains a model with optional resumption, and saves it. Th... | def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(
help="Subcommand help", dest="task")
train_parser = subparsers.add_parser("train",
help="Train a model and save")
subparsers.add_parser("test", help="Load and test a model"... |
def compute_recall_at_k(top_preds, labels, k=20):
assert(len(top_preds) == len(labels))
r_k = (top_preds[:, :k] == labels.reshape(-1, 1)).sum(-1).mean(-1)
return float(r_k)
def compute_mrr_at_k(top_preds, labels, k=20):
assert(len(top_preds) == len(labels))
top_preds, labels = top_preds[:, :k].tolis... | The code computes evaluation metrics (Recall@20, MRR@20, NDCG@20) for a batch of predicted rankings against ground-truth labels, returning them as a dictionary with a specified prefix. It leverages helper functions to calculate each metric at k=20, then formats results for reporting or logging. | def compute_metrics(top_preds, labels, prefix):
# top_preds: (B x N), labels: (B)
r_20 = compute_recall_at_k(top_preds, labels, k=20)
mrr_20 = compute_mrr_at_k(top_preds, labels, k=20)
ndcg_20 = compute_ndcg_at_k(top_preds, labels, k=20)
return {f'{prefix}/r@20': r_20, f'{prefix}/mrr@20': mrr_20, f'... |
def compute_mrr_at_k(top_preds, labels, k=20):
assert(len(top_preds) == len(labels))
top_preds, labels = top_preds[:, :k].tolist(), labels.tolist()
mrr_k = np.mean([1 / (top_pred.index(label) + 1) if label in top_pred else 0. for top_pred, label in zip(top_preds, labels)])
return float(mrr_k)
def assert... | This code tests the correctness of four evaluation metrics (MRR, Recall, Precision, NDCG) at different k-values (1,2,3) by comparing computed results with expected values using assertions. It uses predefined top predictions and labels to verify metric calculations for ranking tasks, ensuring functions like compute_mrr_... | def metric_unit_tests():
top_preds = np.array([[1,2,3], [4,5,6], [7,8,9]])
labels = np.array([3,5,7])
mrr_at_1 = compute_mrr_at_k(top_preds, labels, k=1)
assert_equal(mrr_at_1, (0+0+1/1)/3)
mrr_at_2 = compute_mrr_at_k(top_preds, labels, k=2)
assert_equal(mrr_at_1, (0+1/2+1/1)/3)
mrr_at_3 = ... |
def batchify_data(self, data, batch_size):
num_batches = len(data) // batch_size
batches = []
for data_group in range(num_batches):
start = data_group * batch_size
end = start + batch_size
batch_data = data[start:end]
if (len(batch_data) != batc... | The code trains a neural network by iterating over epochs and batches of training data, performing forward and backward propagation to compute gradients, updating model parameters using the Adam optimizer, and clearing intermediate caches after each step to manage memory efficiently. | def train(self):
# Create batches from training data
batch_data = self.batchify_data(self.train_data, self.batch_size)
for step in range(self.epochs):
for batches in batch_data:
# Forward propagation
self.forward_prop([batches], self.b... |
def batchify_data(self, data, batch_size):
num_batches = len(data) // batch_size
batches = []
for data_group in range(num_batches):
start = data_group * batch_size
end = start + batch_size
batch_data = data[start:end]
if (len(batch_data) != batc... | The code performs LSTM-based prediction on test data by iterating through batches, updating hidden/cell states via the LSTM cell, and collecting outputs from the output cell. It initializes states using primed training data, processes each test batch sequentially, and returns the accumulated predictions as a NumPy arra... | def predict(self, batch_size):
predictions = [] # Stores the predicted values
prev_activation = np.zeros((batch_size, self.hidden_size)) # Initialize previous activation
prev_cell_activation = np.zeros((batch_size, self.hidden_size)) # Initialize previous cell activation
#... |
def playMCTSMove(self, mcts):
mcts = mcts.observeBoard(self)
best_child_ind = mcts.findNextMove()
if best_child_ind is not None:
checker_pos, next_pos = mcts.nextMoves[best_child_ind]
my_checker = self.getSquare(*checker_pos).checker
if self.visual is not... | This function simulates a game between an MCTS player and a random player, alternating turns. It tracks game state, checks for wins/draws, and returns the outcome, turn count, winner ID, and final score. The MCTS player uses its own move logic, while the random player makes random moves. The game ends if either player ... | def playMCTSAgainstRandom(self, mcts_player, draw_after=None):
i_turn=0
i_play=0
isMCTSTurn = mcts_player.playerId == 1
while True:
if isMCTSTurn:
isAlive, mcts_player = self.playMCTSMove(mcts_player)
isMCTSTurn = False
i_pl... |
def generateDateRange(dateBands):
dateRanges = []
for dateBand, key in dateBands:
if(len(dateRanges) == 0):
dateRanges.append(dateBand)
else:
dateRanges = splitDateRange(dateRanges, dateBand)
return dateRanges
def populateKeys(dateBands, dateRanges):
dateRangeKe... | The code generates pairs of date ranges from sales and booking data by expanding date bands into ranges, creating key-value mappings, and combining them into pairs. It prints intermediate results for debugging, including date ranges, key-populated ranges, and final pairs. | def findPairs(salesDateBands, bookingDateBands):
salesDateRanges = set(generateDateRange(salesDateBands))
bookingDateRanges = set(generateDateRange(bookingDateBands))
print('Sales Date Range: {!r}'.format(salesDateRanges))
print('Booking Date Range: {!r}'.format(bookingDateRanges))
salesDateRangeW... |
def parse_args(args=None):
Description = (
"Create custom spreadsheet for pertinent MultiQC metrics generated by the nf-core/viralrecon pipeline."
)
Epilog = "Example usage: python multiqc_to_custom_tsv.py"
parser = argparse.ArgumentParser(description=Description, epilog=Epilog)
parser.add_a... | The code processes MultiQC YAML files to extract specific metrics based on the sequencing platform (Illumina or Nanopore). It defines configurations for variant calling, assembly, and coverage metrics, mapping YAML fields to CSV outputs. For Illumina, it identifies paired-end samples and generates variant and assembly ... | def main(args=None):
args = parse_args(args)
## File names for MultiQC YAML along with fields to fetch from each file
illumina_variant_files = [
(
"multiqc_fastp.yaml",
[
("# Input reads", ["before_filtering", "total_reads"]),
("# Trimmed read... |
def get_basic_data_sizes():
'''
# Define the number / length of the various quantities
# - See Google-Doc, "Background: Observations and Tracklets"
'''
N_obs = 10 # => Fixed maximum number of observations per tracklet:
# Get basic field names
basic_data_fields = get_basic_d... | The function `annotate_and_reformat_tracklet_A` reformats MPC tracklet data into a standardized array for machine learning. It processes each observation by converting RA/Dec to unit vectors, handling magnitudes, and adding supplementary data (e.g., solar elongation). It calculates derived quantities (e.g., angular vel... | def annotate_and_reformat_tracklet_A( tracklet ):
''' Version (A) of a function to reformat MPC tracklet data into
a standardized format approopriate for machine learning.
Contains information from the original constituent observations,
along with with "derived" and "supplementary" ... |
def get_header():
''' Make a header string of length == N_tot
It contains all of the field names
The header is populated in the same order as the data
'''
# Get basic field names
basic_data_fields = get_basic_data_fields()
# Get basic data sizes ...
N_obs, N_ppo, N_spo, N_dp... | The main task of the code is to convert observational data from a filestream into standardized tracklet records with derived/supplementary data, saving them in a fixed-width format to a specified output file. It processes tracklets in chunks, writes them with headers, generates a mapping between designations and number... | def create_standardized_file( filestream , out_filepath, orbit_type='ALL', out_option = 'w', i_break = None):
""" Convenience function to convert obs80 observations into a set of
tracklets, where the data for each tracklet is in a fixed-width
format.
The original observational data ... |
def is_left_turn(p, q, r):
return cross_product(p, q, r) > 0
def is_colinear(p,q,r):
return cross_product(p,q,r) == 0
def is_rigth_turn(p, q, r):
return cross_product(p, q, r) < 0
def rm_colin(points):
include = [True for _ in range(len(points))]
for i in range(1, len(points)-1):
if is_colin... | The code merges two convex hulls (`left_hull` and `right_hull`) into a single convex hull by identifying **upper and lower tangents** between them. It locates key points (e.g., rightmost on the left, leftmost on the right) and iteratively adjusts indices to find valid tangents. For cases where a hull has only one point... | def merge_hulls(left_hull, right_hull):
n_left = len(left_hull)
n_right = len(right_hull)
lh_rightmost_top = left_hull.index(max(left_hull, key=lambda p: p[0]))
lh_righmost_bot = lh_rightmost_top
rh_leftmost_top = right_hull.index(min(right_hull, key=lambda p: p[0]))
rh_leftmost_bot = rh_leftm... |
def convex_hull_base_case(points):
if len(points) < 2:
return points
elif len(points) == 2:
return points if points[0][0] <= points[1][0] else [points[1], points[0]]
elif len(points) == 3:
if cross_product(points[0], points[1], points[2]) == 0:
tmp = sorted(points, key=la... | This function computes the convex hull of a set of points using a divide-and-conquer algorithm. It recursively splits points into left and right halves, computes their convex hulls, and merges them. The base case handles small point sets directly, while the merge step combines two hulls into a single convex hull. The a... | def preparata_hong(points):
if len(points) <= 3:
#print(points)
return convex_hull_base_case(points)
lh, rh = split_points(points)
# print(lh)
# print(rh)
left_hull = preparata_hong(lh)
right_hull = preparata_hong(rh)
#print(left_hull)
#print(right_hull)
re... |
def init_args():
save_path = "/raid/workspace/cvml_user/rhg/AI502-DL/FinalProject/weights"
device = 'cuda:0'
print_freq = 100
Exp_N = 0
parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('--save_path', default=save_path, type=str, help='path to save ch... | The main task of the code is to initialize training parameters (save path, device, print frequency, experiment number) from command-line arguments and execute two classification tasks: fine-tuning a pre-trained classifier and training a classifier from scratch. The global variables are set based on parsed arguments, th... | def main():
global save_path, device, print_freq, Exp_N
args = init_args()
save_path = args.save_path
device = args.device
print_freq = args.print_freq
Exp_N = args.Exp_N
finetune_classifier()
train_classifier_from_scratch() |
def get_dataset_name(nb_per_genre, slice_size):
"""Creates name of dataset from parameters"""
name = "{}".format(nb_per_genre)
name += "_{}".format(slice_size)
return name
def create_dataset_from_slices(nb_per_genre, genres, slice_size, validation_ratio, test_ratio):
"""Creates and save dataset from... | The function `get_dataset` creates or loads a dataset based on specified parameters. It checks if dataset files exist; if not, it generates new data using `create_dataset_from_slices` with parameters like number of slices per genre, slice size, and ratios for validation/test splits. If files exist, it reuses them. Fina... | def get_dataset(nb_per_genre, genres, slice_size, validation_ratio, test_ratio, mode):
"""Creates or loads dataset if it exists, note: Mode is train or test"""
print("[+] Dataset name: {}".format(get_dataset_name(nb_per_genre, slice_size)))
if not os.path.isfile(dataset_path + "train_X_" + get_dataset_name(... |
def train_one_step(self, step, batch, total_steps):
images, labels, _, age_id = self.process_batch(batch)
with autocast(enabled=self.fp16):
outputs = self.model(images, age_id)
batch_loss = self.criterion(outputs, labels) / self.grad_accum_steps
... | This function trains a model for one epoch using a dataloader, accumulating gradients over specified steps, tracking training loss with a progress bar, logging metrics to W&B if enabled, and performing validation after a specified epoch. It returns the average training loss for the epoch while managing CUDA memory. | def train_one_epoch(self, epoch, train_dataloader, valid_dataloader, fold_i=None):
self.model.train()
total_steps = len(train_dataloader) * (epoch)
start_step = (epoch - 1) * len(train_dataloader) + 1
total_train_loss = 0
with tqdm(enumerate(train_dataloader, start_step), unit=... |
def black_scholes(v:float, S:float, K:float, r:float, T:float, optiontype) -> float:
# This function returns the price of a put
# requires import numpy as np
# S is the current stock price
# T is the maturity in years
# r is the risk-free rate
# d is the continuous time dividend rate
# v i... | This function numerically computes the implied volatility (sigma) using Newton-Raphson iterations to match a target option price via the Black-Scholes model. It iterates up to 4000 times, adjusting sigma by the ratio of the squared pricing error and vega (price sensitivity to volatility), ensuring non-negative sigma an... | def find_vol(target_value, S, K, r, T, option_type):
MAX_ITERATIONS = 4000
PRECISION = 1.0e-7
nevernegativesigma = .10
for i in range(0, MAX_ITERATIONS):
price = black_scholes(nevernegativesigma, S, K, r, T, option_type)
vega = vegav(nevernegativesigma, S, K, r, T)
objective = ob... |
def total_interest(self, monthly_payment: float) -> float:
return self.total_payment(monthly_payment) - self._loan
def total_payment(self, monthly_payment: float) -> float:
return monthly_payment * self.term_m(monthly_payment)
def interest_to_principal(self, monthly_payment: float) -> float:
ret... | The function `_get_simulation_data` generates a list of formatted strings containing key financial metrics for a mortgage simulation, including property value, loan details, payment breakdowns, tax deductions, interest rates, and ratios. It compiles data for display or analysis, using input parameters to calculate and ... | def _get_simulation_data(
self, monthly_payment: float, amortization: float, amortization_rate: float, term: float, title: str
) -> List[str]:
""""""
data = [
title,
f"{int(self.property_value):,} sek",
f"{int(self.downpayment):,} sek",
f"{int(... |
def amortization(self, monthly_payment: float) -> float:
return monthly_payment - self.monthly_interest
def amort_rate(self, monthly_payment: float) -> float:
return self.amortization(monthly_payment) / self._loan * 12.0
def term_y(self, monthly_payment: float) -> float:
return self.term_m(month... | The function simulates loan/mortgage scenarios using a specified monthly payment, calculating amortization, amortization rate, and loan term. If no payment is provided, it defaults to the minimum required. It logs warnings if the input payment is below the minimum. The results, along with the provided title, are format... | def simulate_by_payment(self, monthly_payment: float = None, title: str = "") -> List[str]:
"""
Simulation based on monthly payment
:param monthly_payment:
:param title:
:return:
"""
if monthly_payment is None:
monthly_payment = self.minimum_monthly_pa... |
def token_in_pools(trade: TradeOpertunity) -> bool:
for pool in trade.pools:
if trade.token_in not in pool.tokens or trade.token_out not in pool.tokens:
return False
return True
def opertunity(trade: TradeOpertunity) -> bool:
prices = []
for pool in trade.pools:
prices.append... | The function identifies and calculates the optimal arbitrage opportunity between two token pools. It validates input by checking that exactly two pools are provided, that tokens exist in those pools, and that an arbitrage opportunity exists. If valid, it returns the computed optimal arbitrage value using the `calculate... | def find_arbitrage(trade: TradeOpertunity) -> float:
if len(trade.pools) != 2:
raise ValueError('Can only found arbitrage opertunity between two pools')
if not token_in_pools(trade):
raise ValueError('Tokens does not exist in pools')
if not opertunity(trade):
raise ValueError('No a... |
def check_direction(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if not self.is_exit: # -----------------------prevent keys if level complete
... | The code's main task is to update the game state by checking the snake's direction, transforming its position, moving it, rendering visuals, detecting collisions with fruits, obstacles, walls, and its own body, and verifying level completion in a snake game. | def update(self):
self.check_direction()
self.transform()
self.move()
self.draw()
self.check_over_time_eat_fruit()
self.check_snake_and_fruit_collide()
self.check_snake_and_figure_collide()
self.check_crash_in_body()
self.check_crash_in_wall()
... |
def __manage_telnet_connection(self, hostname):
self.__auth_list[0] = 'telnet ' + hostname
response = self.__run_command_and_get_response(self.__auth_list[0].encode('ascii') + b'\n')
if not response.endswith('username: '):
return False
for command in self.__auth_list[1:]:
... | The code manages telnet and SSH connections for a given hostname, runs commands if connected, records connection statuses, and logs results into a CSV file. It first checks telnet, runs commands if successful, then checks SSH. If telnet fails, it attempts SSH first. Statuses are converted to text and added to a structu... | def manage(self, hostname):
fieldnames = self.__csv_writer.get_fieldnames()
values_dict = AttributeOrderedDict(AttributeOrderedDict.create_dict(fieldnames))
values_dict.HOSTNAME = hostname
telnet_status = self.__manage_telnet_connection(hostname)
if telnet_status:
sel... |
def loadColors(self, file):
''' load the color data from a file '''
colors = []
with open(file) as f:
for line in f:
rowdata = line.replace('\n', '')
colordata = rowdata.split(', ')
for color in colordata:
c = color.... | This code initializes a GUI window with custom settings, including title, icon, geometry, and grid layout. It loads tile maps, colors, and creates UI components like menubar, canvas, and binds interactions. The window is positioned relative to the mouse cursor, configured for resizing, and sets up a tile-based interfac... | def __init__(self, master, **kw):
Frame.__init__(self, master, **kw)
self.style = Style()
self.configure()
# window title and icon
loadIcon(self.master, self.master, IIVLXICO)
self.master.title(self.WINDOW_TITLE)
# window geometry
self.master.resizable(*s... |
def increaseTileHT(self, tile, amount=32):
''' Increase the top corner of one tile and surrounding tiles '''
max = tile.ht - amount
top = self.getTileTop(tile)
topright = self.getTileTopRight(tile)
topleft = self.getTileTopLeft(tile)
# slope direction
if amount > ... | This code handles keyboard events to manipulate selected tiles (W/A/S/D increase properties), adjust canvas view (arrow keys), toggle coordinates (C), rotate tiles (E/Q), print tile data (V/Space), and debug unhandled keys. It updates the display after each action. | def handleKeyPress(self, event):
''' Handle a keyboard event '''
if event.keycode == 87: # w
if self.selected:
self.increaseTileHT(self.selected)
elif event.keycode == 65: # a
if self.selected:
self.increaseTileHL(self.selected)
eli... |
def increaseTileHB(self, tile, amount=32):
''' Increase the bottom corner of one tile and surrounding tiles '''
max = tile.hb - amount
bottomright = self.getTileBottomRight(tile)
bottomleft = self.getTileBottomLeft(tile)
bottom = self.getTileBottom(tile)
# check tiles
... | This method increases the height of a specified tile's corners and adjacent tiles' affected corners by a given amount, then triggers a redraw to update the display. | def increaseTileHeight(self, tile, amount=32):
''' Increase the height of all the corners of a tile and the surrounding tiles affected corners '''
self.increaseTileHB(self.tiles[tile.r][tile.c], amount)
self.increaseTileHR(self.tiles[tile.r][tile.c], amount)
self.increaseTileHL(self.tile... |
def increaseTileHB(self, tile, amount=32):
''' Increase the bottom corner of one tile and surrounding tiles '''
max = tile.hb - amount
bottomright = self.getTileBottomRight(tile)
bottomleft = self.getTileBottomLeft(tile)
bottom = self.getTileBottom(tile)
# check tiles
... | This function decreases the height of a specified tile's corners and surrounding affected tiles by calling four increasing methods with a negative value, then triggers a redraw to update the display. | def decreaseTileHeight(self, tile, amount=-32):
''' Decrease the height of all the corners of a tile and the surrounding tiles affected corners '''
self.increaseTileHB(self.tiles[tile.r][tile.c], amount)
self.increaseTileHR(self.tiles[tile.r][tile.c], amount)
self.increaseTileHL(self.til... |
def getTileFromEvent(self, event):
''' Get a tile from a click event '''
# Find the tile clicked
clicked = event.widget.find_withtag('current')[0]
tags = self.canvas.gettags(clicked)
gridtag = tags[0]
# r,c of tile clicked
r,c = gridtag[1:].split('x')
tile... | This method handles a right-click event on a tile by determining the current canvas action and modifying the tile accordingly: decreasing its height if the action is 'lower', increasing it if 'raise', or changing its color if 'color'. | def tileRightClick(self, event):
''' right click on a tile '''
tile = self.getTileFromEvent(event)
#print(self.canvas.action)
if self.canvas.action == 'lower':
self.decreaseTileHeight(tile)
elif self.canvas.action == 'raise':
self.increaseTileHeight(tile)
... |
def read_datafile(filename):
"""
Reads csv file with python span list and text.
@param filename: path of csv file
return List[tuple(fixed_span(List[int]), text(str))]
"""
data = []
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
... | The main task of the code is to process a CSV file into a Named Entity Recognition (NER) dataset. It reads data, tokenizes text with spaCy, extracts entities labeled 'TOXIC', structures input-output pairs, and returns a `NERDataset` object with specified sequence length and optional flair embeddings for training/testin... | def get_dataset(file_path, max_seq_len=96, split="train", flair_model_path=None):
"""
return NERDataset
@param file_path: path of the csv file
@param max_seq_len: max sequence length for bert input tokens
@param split: train, trial or test
@param flair_model_path: None if not adding flair embedd... |
def __init__(self):
self.buffer_offset = 0
self.byte_count = 0
self.buffer = _buffer()
self.state = _state()
self.state.b = sha1InitState.copy() * HASH_LENGTH
def write(self, data):
self.byte_count += 1
self.addUncounted(data)
return 1
def result(self):
... | The code initializes an HMAC key by processing the input key, truncating or padding it to match the block length, and applying XOR with HMAC_IPAD to prepare the key buffer for cryptographic hashing operations. | def initHmac(self, key, keyLength):
self.keyBuffer = [0] * BLOCK_LENGTH
if keyLength > BLOCK_LENGTH:
self.__init__()
for i in range(keyLength):
self.write(key[i])
self.keyBuffer = self.result() * HASH_LENGTH
else:
self.keyBuffer = k... |
def result(self):
# Pad to complete the last block
self.pad()
# Swap byte order back
for i in range(5):
a = self.state.w[i]
b = (a << 24) | ((a << 8) & 0x00ff0000) | ((a >> 8) & 0x0000ff00) | (a >> 24)
w = list(self.state.w)
w[i] = b
... | This code computes an HMAC by first obtaining an inner hash, reinitializing the object, then processing the key with HMAC_OPAD via XOR, followed by writing the inner hash bytes. Finally, it returns the computed HMAC result. | def resultHmac(self):
innerHash = self.result()
self.__init__()
for i in range(BLOCK_LENGTH):
self.write(self.keyBuffer[i] ^ HMAC_OPAD)
for i in range(HASH_LENGTH):
self.write(innerHash[i])
return self.result() |
def create_mesh(mu, mumesh, name):
mesh = bpy.data.meshes.new(name)
faces = []
for sm in mumesh.submeshes:
faces.extend(sm)
mesh.from_pydata(mumesh.verts, [], faces)
if mumesh.uvs:
create_uvs(mu, mumesh.uvs, mesh, name + ".UV")
if mumesh.uv2s:
create_uvs(mu, mumesh.uv2s, ... | The main task of the code is to create a 3D object (mesh, light, or placeholder) from a Unity-like scene object, applying materials, handling skinned meshes, setting up colliders, tags, layers, and recursively processing children. It constructs the object hierarchy, stores it in a scene graph, and associates animations... | def create_object(mu, muobj, parent, create_colliders, parents):
obj = None
mesh = None
if hasattr(muobj, "shared_mesh"):
mesh = create_mesh(mu, muobj.shared_mesh, muobj.transform.name)
for poly in mesh.polygons:
poly.use_smooth = True
obj = create_mesh_object(muobj.trans... |
def dump_textures(mu):
print("Textures")
for i, tex in enumerate(mu.textures):
print (i, tex.name, tex.type)
def dump_materials(mu):
print("Materials")
for i, mat in enumerate(mu.materials):
print(i, mat.name)
dump_thing(mat, mu, 1, [], mat_dump_funcs);
def dump_object(mu, obj, l... | The code reads a file using the Mu class, checks for successful reading, prints the version, and processes textures, materials, and the object from the Mu instance. | def dump(fname):
mu = Mu()
if not mu.read(fname):
print("could not read: " + fname)
raise
print(mu.version)
dump_textures(mu)
dump_materials(mu)
dump_object(mu, mu.obj) |
def create_textures(mu, path):
extensions = [".dds", ".mbm", ".tga", ".png"]
#texture info is in the top level object
for tex in mu.textures:
base, ext = os.path.splitext(tex.name)
ind = 0
if ext in extensions:
ind = extensions.index(ext)
lst = extensions[ind:] + ... | This code imports a 3D model from a file, disables global undo, processes textures/materials, creates the model object, selects it in the scene, and restores undo settings. It handles error reporting for invalid file formats and ensures proper scene setup. | def import_mu(self, context, filepath, create_colliders):
operator = self
undo = bpy.context.user_preferences.edit.use_global_undo
bpy.context.user_preferences.edit.use_global_undo = False
for obj in bpy.context.scene.objects:
obj.select = False
mu = Mu()
if not mu.read(filepath):
... |
def _load_data(self, index):
raise NotImplementedError
def _resize(self, image, label, bigger_side_to_base_size=True):
# return image, label
if isinstance(self.base_size, int):
d, h, w = image.shape
if self.augment and self.scale:
longside = random.randint... | This code loads and preprocesses image and label data for a dataset. It resizes, crops, normalizes, and transforms images/labels based on mode (train/val) and augmentation settings. It returns processed data for training, validation, or weak/strong augmentations, using specified transformation functions. | def __getitem__(self, index):
image, label, image_id = self._load_data(index)
# print("image_id:{},mean:{},std:{}".format(image_id, np.mean(image), np.std(image)))
if self.base_size is not None:
image, label = self._resize(image, label)
if self.crop_size is not None:
... |
def washBrush(ditch_excess=False):
washDirty()
# dabSponge()
washClean()
if ditch_excess:
ad.moveto(3,22)
ad.moveto(3,20)
def pickUpColor(coords):
x,y = coords
color_height = 0.2
color_width = color_height
ad.penup()
ad.moveto(x, y)
ad.pendown()
ad.line(0,-col... | The code generates a flower pattern by repeatedly calling the `sunflower` function with specific parameters, using a brush and colors. It draws 200 dots in groups of 7, adjusting positions and visual properties like size, offset, and stroke magnitude to create a layered flower design. The loop increments dot count and ... | def flower():
flower_x = 14.5
flower_y = 8
tot_dots = 200
dot_count = 0
dots_per = 7
while dot_count < tot_dots:
# for color in [DARK_GREEN]: #, BLUE, BLUE, GREEN, ORANGE, RED, GREEN, GREEN]:
washBrush()
pickUpColor(DARK_GREEN)
# pickUpColor(YELLOW)
# pi... |
def gaussian_kernel(size, sigma):
kernel = np.zeros((size, size))
a=int((size-1)/2)
for i in range (size):
for j in range (size):
kernel[i][j]=np.exp(-((i-a)**2+(j-a)**2)/(2*(sigma**2)))/(2*(np.pi)*(sigma**2))
return kernel
def conv(image, kernel):
Hi, Wi = image.shape
Hk, Wk... | This function performs Canny edge detection on an input image by applying Gaussian smoothing, calculating gradient magnitude and direction, non-maximum suppression, double thresholding, and edge linking to detect and refine edges. | def canny(img, kernel_size=5, sigma=1.4, high=20, low=15):
Hi, Wi = img.shape
edge = np.zeros((Hi, Wi))
kernel = gaussian_kernel(kernel_size,sigma)
smoothed = conv(img, kernel)
G, theta = gradient(smoothed)
nms = non_maximum_suppression(G, theta)
strong_edges, weak_edges = double_thresholdin... |
def get_info(patient_id):
db = get_db()
health_info = mock_patient_health()
health_info["patient_id"] = patient_id
health_info["timestamp"] = get_timestamp()
patient_info = health_info | db.get_patient_info(patient_id)
patient_info["activity_log"] = db.get_activity_log(patient_id)
return pa... | The main task of the code is to record a patient's vital information snapshot by logging details, capturing request data, and storing an activity log entry in a database with a timestamp. It retrieves patient info, formats it, and persists the data along with metadata like the name and timestamp for tracking purposes. | def snapshot_vitals(patient_id):
info = get_info(patient_id)
logger = get_logger()
logger.info(str(info))
json = request.get_json()
db = get_db()
db.add_activity_log(patient_id, json['name'], get_timestamp(), format_snapshot(info))
return Ok() |
def GetF2(f, theta, kappa1, mu1, kappa2, mu2):
from numpy import square
a = GetA(mu1, mu2)
b = GetB(kappa1, mu1, kappa2, mu2)
r = GetR(kappa1, mu1)
bf2 = 1+a*(1+3/2*(f+theta)-r/2*(3*f+5*theta))+b*(3-4*r)+a/2*(a+3*b)*(3-4*r)*(f+theta-r*(f-theta+2*square(theta)))
return bf2
def GetF3(f, theta, k... | The function `GetT2` computes a value `bt2` by combining results from multiple helper functions (`GetF2` to `GetF9`) that depend on input parameters `f`, `theta`, `kappa1`, `mu1`, `kappa2`, and `mu2`. It uses a formula involving divisions, multiplications, and algebraic combinations of these intermediate results to der... | def GetT2(f, theta, kappa1, mu1, kappa2, mu2):
bf2 = GetF2(f, theta, kappa1, mu1, kappa2, mu2)
bf3 = GetF3(f, theta, kappa1, mu1, mu2)
bf4 = GetF4(f, theta, kappa1, mu1, mu2)
bf5 = GetF5(f, theta, kappa1, mu1, kappa2, mu2)
bf6 = GetF6(f, theta, kappa1, mu1, kappa2, mu2)
bf7 = GetF7(f, theta, kap... |
def is_filled(self):
'''
return True if all positions are set
Warning: do not check if it is correct
'''
progress = 0
for col in range(9):
for row in range(9):
if self._grid[col][row] != 0:
progress += 1
re... | This function recursively solves a grid puzzle using backtracking, prioritizing cells with the fewest possible values ("safest" positions) to minimize dead ends. It fills the grid by testing valid values in these positions, backtracking when a dead end is reached, and tracking failed attempts. The goal is to efficientl... | def safest_first_solver(self):
'''
recursive function
fill positions with minimal solutions number first
'''
if self.is_filled():
return True
pos = self.find_safest_position_to_solve()
for try_solution in pos[1] :
col, row = pos... |
def im_detect_bbox(model, im, query, query_type, target_scale, target_max_size, boxes=None):
"""Prepare the bbox for testing"""
inputs, im_scale = _get_blobs(im, boxes, target_scale, target_max_size)
if cfg.DEDUP_BOXES > 0 and not cfg.MODEL.FASTER_RCNN:
v = np.array([1, 1e3, 1e6, 1e9, 1e12])
... | The function processes model outputs for object detection tasks, performing bounding box detection, non-max suppression, and optional mask/keypoint processing. It returns class-specific boxes, masks, and keypoints after timing each step, using config flags to conditionally enable mask/keypoint detection. | def im_detect_all(model, im, query, query_type, catgory, num_classes, box_proposals=None, timers=None):
"""Process the outputs of model for testing
Args:
model: the network module
im_data: Pytorch variable. Input batch to the model.
im_info: Pytorch variable. Input batch to the model.
gt... |
def transformation_to_str(val: Union[str, None]) -> int:
if not val:
return "0"
else:
return val
def get_inputs(
self, obj: dict, cycle_id: str, transformation_id: Optional[str]
) -> list:
counter = defaultdict(int)
exchange_list = []
for inpt in obj["inputs... | This function processes transformation data from an input object, constructs structured datasets with transformation details, exchanges, and emissions, and returns a list of these datasets. It iterates over each transformation, extracts relevant attributes, retrieves associated inputs, products, and emissions, and comp... | def get_transformations(self, obj: dict, cycle_id: str) -> list:
new_datasets = []
for source in obj.get("transformations", []):
target = {
"name": source["term"]["name"],
"term_type": source["term"]["termType"],
"term_id": source["term"]["@id... |
def get_basic_metadata(self, obj: dict, cycle_id: str) -> dict:
"""
Return a minimum subset of the object data, partly
renamed to fit the BW format.
"""
EXTRAS = {
"createdAt",
"updatedAt",
"endDate",
"cycleDuration",
"f... | The code converts a source dictionary into a structured list of data by extracting metadata, exchanges, products, emissions, and transformations. It builds a target dictionary with core metadata, adds practices, animals, and exchanges, then aggregates new datasets from products, emissions, and transformations into retu... | def convert(self, source: dict) -> list:
return_data = []
cycle_id = source["@id"]
target = self.get_basic_metadata(source, cycle_id)
self.add_practices(source=source, target=target)
if "animals" in source:
target["animals"] = source["animals"]
target["exch... |
def safeGet(self, url, jsonObj=False):
session = requests.Session()
headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36"}
try:
r = requests.get(url, headers=headers)
except HTTPError as e:
print("HTTP error "+st... | This function scrapes game data from a URL, extracts game ID, date, contestant details, and player information, then stores the structured data in a database. It handles URL validation, skips duplicate games, parses HTML content, and saves game results and questions. | def scrapeGame(self, url):
if "game_id=" not in url:
print("Invalid URL "+url)
return
if(url.startswith("showgame")):
url = "http://www.j-archive.com/"+url
gameId = url.split("game_id=")[1]
if int(gameId) == self.waitingOnGame:
self.waitingOnGame = False
if self.waitingOnGame:
print("SKIPPING ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.