dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def free_energy_XB_T(T0,
omega,
X_B,
T):
"""
This function calculates the free energy of a binary alloy in the "quasi-chemical" atomistic model.
The assumptions taken in the model are :
- Only nearest-neighbours interactions are tak... | This function calculates the Gibbs free energy of a binary alloy in the (eta, T) space using the quasi-chemical model, considering nearest-neighbor interactions and configurational entropy. It generates grids for structural order parameter (eta) and temperature (T), computes enthalpy and entropy terms, then returns the... | def free_energy_eta_T(T0,
omega,
X_B,
eta,
T):
"""
This function calculates the free energy of a binary alloy in the "quasi-chemical" atomistic model.
The assumptions taken in the model are :
- Only nearest-... |
def display_board():
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])
def handle_turn(player):
position = input(player + "'s turn.Choose a position from 1-9: ")
valid = False
while n... | The code defines a function to play a tic-tac-toe game. It displays the board, alternates turns between players, checks for a win or tie after each move, and announces the result once the game ends. | def play_game():
display_board() # display the initial board first
while game_still_going:
handle_turn(current_player)
check_if_game_over()
flip_player()
if winner == "Player X" or winner == "Player O":
print("Winner: " + winner)
elif winner == None:
print("This... |
def on_delete_locus(self, entry_num):
# do nothing if there is one (or less) loci
if len(self.entry_vars) <= 1:
return
# if there are 5 loci currently then enable the new locus button
if len(self.entry_vars) == 5:
self.new_entry_button.configure(state="enabled")
... | This code creates a GUI interface with two frames: the first allows users to input loci equations via an entry field and add new loci, while the second lets them configure selected loci using a delete button, color selection, and dynamic updates. Widgets are organized with Tkinter, and components are stored in a dictio... | def widget_setup(self):
# First frame
self.entry_frame = tk.Frame(self, bg=self.frame_bg, bd=5)
self.entry_frame.pack(side="left", fill="both")
title_one = tk.Label(self.entry_frame, justify="center", text="Enter Loci Equations Below:", bg=self.frame_bg)
title_one.pack(side="top... |
def on_delete_locus(self, entry_num):
# do nothing if there is one (or less) loci
if len(self.entry_vars) <= 1:
return
# if there are 5 loci currently then enable the new locus button
if len(self.entry_vars) == 5:
self.new_entry_button.configure(state="enabled")
... | This function creates a new locus entry with input fields and color selection, updates UI components, and manages dynamic locus creation with deletion and color change handling, limiting to a maximum of 5 loci. | def on_new_locus(self):
# Check which is the lowest locus number which can be created
entry_num = max(self.plotsdict.keys()) + 1
# Add new entry to entry_vars and new colour select to colour_select_vars
entry_text = tk.StringVar()
self.entry_vars[entry_num] = entry_text
... |
def extract_decimal(id) -> Expr:
maybe = AssetParam.decimals(id)
return Seq(maybe, If(maybe.hasValue(), Extract(Itob(maybe.value()), Int(7), Int(1)), Bytes("base16", "00")))
def auth_addr(id) -> Expr:
maybe = AccountParam.authAddr(id)
return Seq(maybe, If(maybe.hasValue(), maybe.value(),... | The code handles a cross-chain asset transfer by validating transaction inputs, extracting and adjusting amounts/fees, determining asset details (Wormhole wrapped or native), constructing a payload with metadata, and submitting an inner transaction to a core application for further processing. It ensures correct format... | def sendTransfer():
aid = ScratchVar()
amount = ScratchVar()
d = ScratchVar()
p = ScratchVar()
asset = ScratchVar()
aaddr = ScratchVar()
Address = ScratchVar()
FromChain = ScratchVar()
zb = ScratchVar()
factor = ScratchVar()
fee = S... |
def auth_addr(id) -> Expr:
maybe = AccountParam.authAddr(id)
return Seq(maybe, If(maybe.hasValue(), maybe.value(), Bytes("")))
def extract_creator(id) -> Expr:
maybe = AssetParam.creator(id)
return Seq(maybe, If(maybe.hasValue(), maybe.value(), Bytes("")))
def get_sig_address(acct_seq_st... | The code verifies and prepares a token's metadata for cross-chain bridging via Wormhole. It checks if the token is Wormhole-wrapped (validating creator address, asset data, and chain details) or non-wrapped (extracting decimals, name, symbol). It constructs a standardized payload (p) with token info, ensuring correct f... | def attestToken():
asset = ScratchVar()
p = ScratchVar()
zb = ScratchVar()
d = ScratchVar()
uname = ScratchVar()
name = ScratchVar()
aid = ScratchVar()
Address = ScratchVar()
FromChain = ScratchVar()
return Seq([
aid.store(Bto... |
def checkForDuplicate():
off = ScratchVar()
emitter = ScratchVar()
sequence = ScratchVar()
b = ScratchVar()
byte_offset = ScratchVar()
return Seq(
# VM only is version 1
Assert(Btoi(Extract(Txn.application_args[1], Int(0), Int(1))) == Int(1)),
... | This function processes an attestation transaction to create or update a cross-chain asset on Algorand. It validates transaction group structure, verifies the VAA (Verification Agreement) from a core contract, parses asset metadata (name, symbol, decimals, chain), trims data to limits, and creates/upgrades an Algorand ... | def receiveAttest():
me = Global.current_application_address()
off = ScratchVar()
Address = ScratchVar()
Chain = ScratchVar()
FromChain = ScratchVar()
Decimals = ScratchVar()
Symbol = ScratchVar()
Name = ScratchVar()
asset = ScratchVar()
... |
def checkForDuplicate():
off = ScratchVar()
emitter = ScratchVar()
sequence = ScratchVar()
b = ScratchVar()
byte_offset = ScratchVar()
return Seq(
# VM only is version 1
Assert(Btoi(Extract(Txn.application_args[1], Int(0), Int(1))) == Int(1)),
... | This code processes a cross-chain token transfer by validating the incoming transaction against a verified core application, parsing the VAA (Verified Action Aggregate) data to extract source/destination details, asset information, and amount. It ensures the transfer originates from the correct chain/emitter, handles n... | def receiveTransfer():
me = Global.current_application_address()
off = ScratchVar()
Chain = ScratchVar()
Emitter = ScratchVar()
Amount = ScratchVar()
Origin = ScratchVar()
OriginChain = ScratchVar()
Destination = ScratchVar()
DestChain = ... |
def getAlgodClient(self) -> AlgodClient:
return AlgodClient(self.ALGOD_TOKEN, self.ALGOD_ADDRESS)
def getTemporaryAccount(self, client: AlgodClient) -> Account:
if len(self.accountList) == 0:
sks = [account.generate_account()[0] for i in range(3)]
self.accountList = [Account(sk) ... | The main task of the code is to create and test a token application on the Algorand blockchain. It initializes accounts, deploys a token app, stores data, and performs operations like adding buffers, setting values, and redeeming wrapped coins. The code also prints account states and application data to verify function... | def simple_token(self):
client = self.getAlgodClient()
print("Generating the foundation account...")
foundation = self.getTemporaryAccount(client)
print("Creating the Token app")
appID = self.createTokenApp(client=client, sender=foundation)
print("appID = " + str(appID)... |
def list_raw_docs(data_dir):
"""List all raw docs/papers found in data dir.
:data_dir: TODO
:returns: TODO
"""
in_dir = [os.path.join(data_dir, f) for f in os.listdir(data_dir)]
files = [f for f in in_dir if os.path.isfile(f)]
docs = [f for f in files if f.endswith('.doc') or f.endswith('.... | The main task of the code is to process raw documents from an input directory into an interim dataset by converting them using pypandoc and unoconv. It combines raw documents with metadata into a structured DataFrame, which is then saved as a pickle file in the specified output directory. This serves as a preprocessing... | def main(input_dir, output_dir):
""" Runs data processing scripts to turn raw data from (../raw) into
a single interim dataset (../interim), for which later features
will be engineered. The main process here is *conversion* via pypandoc
and external calls to unoconv.
"""
logger = log... |
def get_songslist():
f = open("playInfo.json", "r")
data = json.loads(f.read())
song_arr=[]
for i in data['items']:
song_arr.append(i['snippet']['title'])
f.close()
return song_arr
def searchSong(songname):
headers = get_resource_header()
endpoint = "https://api.spotify.com/v1/s... | The code adds songs to a Spotify playlist by processing a list of song names, constructing search queries, retrieving track URIs via Spotify's API, and posting them to the specified playlist. It handles song formatting, searches for matches, and returns the API response. | def add_songs(playlistID):
songslist = get_songslist()
urilist = []
for i in songslist:
arr = i.split(" ")
s=""
if(len(arr)>=4):
for j in range(4):
s+=str(arr[j])
else:
s=i
current = searchSong(s)
if current!="":
... |
def insert_filer_information(self) -> None:
self.cik = self.filing.filer["cik"]
business = self.filing.filer["business_address"]
mail = self.filing.filer["mail_address"]
lei = self.filing.general_information["filer_lei"]
if self.filing.filer["former_names"] is None:
... | The main task of the code is to sequentially insert multiple data types into a database or system. It calls methods to insert filer information, series class information, fund information, portfolio data, and explanatory notes. If `series_id` is None, the method exits early, skipping subsequent insertions. This ensures... | def insert_all(self) -> None:
self.insert_filer_information()
self.insert_series_class_information()
if self.series_id is None:
return
self.insert_fund_information()
self.insert_portfolio_data()
self.insert_explanatory_notes() |
def conn_sql(self):
#connect to db
try:
cnxn = pymssql.connect(self.server, self.user_login, self.password, self.database)
cursor = cnxn.cursor()
return cnxn,cursor
except Exception as e:
self.alert_line("Danger! cannot connect sql server")
... | The function logs execution results into a SQL Server database table, inserting status, process, message, and error details from the input dictionary. It connects to the database, executes an INSERT statement with formatted values, and handles exceptions by alerting the user, logging the error, and terminating the prog... | def log_to_db(self,result):
#connect to db
cnxn,cursor=self.conn_sql()
try:
cursor.execute(f"""
INSERT INTO [{self.database}].[dbo].[{self.table_log}]
values(
getdate(),
'{result["status"]}',
... |
def read_path(self):
path_list = []
file_extension = '.txt'
for root,dirs,files in os.walk(self.path):
for name in files:
if name.endswith(file_extension):
file_path = os.path.join(root,name)
path_list.append(file_path)
... | This code processes multiple files by reading their data, checking for duplicates, and inserting non-duplicate records into a database. It timestamps execution, iterates through file paths, validates data uniqueness, and logs success after database insertion. | def run(self):
self.stamp_time()
self.read_path()
for i in range(len(self.path_list)):
self.path_now = self.path_list[i]
self.read_data()
if self.check_duplicate() == constant.STATUS_OK:
self.df_to_db()
self.ok_msg(self.df_to_db._... |
def conn_sql(self):
#connect to db
try:
cnxn = pymssql.connect(self.server, self.user_login, self.password, self.database)
cursor = cnxn.cursor()
return cnxn,cursor
except Exception as e:
self.alert_line("Danger! cannot connect sql server")
... | The main task of the code is to insert log data into a SQL Server database table. It connects to the database, executes an INSERT statement with timestamp, status, process, message, and error details from the input `result` dictionary, then commits the transaction. If an error occurs during insertion, it triggers an al... | def log_to_db(self,result):
#connect to db
cnxn,cursor=self.conn_sql()
try:
cursor.execute(f"""
INSERT INTO [{self.database}].[dbo].[{self.table_log}]
values(
getdate(),
'{result["status"]}',
... |
def alert_error_msg(self,result):
if self.line_notify_token != None:
return f'\nproject: {self.table}\nprocess: {result["process"]}\nmessage: {result["message"]}\nerror: {result["error"]}\n'
def alert_line(self,msg):
value = alert.line_notify(self.line_notify_token,msg)
value = json.... | The main task of the code is to handle errors by generating an error message, sending alerts via Line if enabled, logging the error to a database, and exiting the program. It also includes a fallback to log any exceptions during execution and exit. | def error_msg(self,process,msg,e):
result = {"status":constant.STATUS_ERROR,"process":process,"message":msg,"error":e}
try:
print("Error: "+self.alert_error_msg(result))
if self.line_notify_flag == "True":
self.alert_line(self.alert_error_msg(result))
... |
def alert_error_msg(self,result):
if self.line_notify_token != None:
return f'\nproject: {self.table}\nprocess: {result["process"]}\nmessage: {result["message"]}\nerror: {result["error"]}\n'
def alert_line(self,msg):
value = alert.line_notify(self.line_notify_token,msg)
value = json.... | The code handles errors by generating an error message, sending notifications via Line if enabled, logging the error to a database, and exiting the program. It also catches exceptions during this process, logs them, and exits. | def error_msg(self,process,msg,e):
result = {"status":constant.STATUS_ERROR,"process":process,"message":msg,"error":e}
try:
print("Error: "+self.alert_error_msg(result))
if self.line_notify_flag == "True":
self.alert_line(self.alert_error_msg(result))
... |
def build_all_locations():
# img = numpy.array(sct.grab(dimensions))
# scr_remove = img[:,:,:3]
all_locations = {}
# scr = scr_remove.copy()
# delivery_box_loc = get_delivery_box_location(scr_remove, 'cv2.TM_CCOEFF_NORMED', cv2.TM_CCOEFF_NORMED)
# print(delivery_box_loc)
#
# delivery_box_... | The main task of the code is to manage a trading process by refreshing item data, then executing flows to buy specified items and remove others across all locations. It handles errors during execution, ensuring operations like purchasing and disposal are processed systematically. The function initializes locations, upd... | def start_gw_trade():
all_locations = build_all_locations()
remove_items, what_to_buy_items, item_lookups = autotrader.refresh_all_items()
# remove_items, what_to_buy_items, item_lookups = load_data()
try:
buy_item_flow(all_locations, what_to_buy_items, item_lookups)
remove_item_flow(all_... |
def start_gw_trade():
all_locations = build_all_locations()
remove_items, what_to_buy_items, item_lookups = autotrader.refresh_all_items()
# remove_items, what_to_buy_items, item_lookups = load_data()
try:
buy_item_flow(all_locations, what_to_buy_items, item_lookups)
remove_item_flow(all_... | The code repeatedly launches the Guild Wars 2 program, attempts to initiate trade functions up to five times with error handling, and terminates the program in a loop. Its main task is to automate launching, trading, and restarting Guild Wars 2, likely for testing or script-based interactions. | def start():
start_gw_trade()
kill_gw2()
while True:
start_guild_wars2_program()
for i in range(5):
try:
start_gw_trade()
except:
continue
kill_gw2() |
def start():
start_gw_trade()
kill_gw2()
while True:
start_guild_wars2_program()
for i in range(5):
try:
start_gw_trade()
except:
continue
kill_gw2()
def run_trade_forever():
while True:
start_gw... | This code defines a keyboard event handler that triggers specific functions when F1-F4 keys are pressed. On F1, it runs 'start()'; on F2, it executes 'run_trade_forever()'; on F3, it prints the mouse position and a message; on F4, it calls 'refresh_take_all_location()'. Each action includes error handling for attribute... | def on_press(key):
if key == keyboard.Key.f1:
try:
start()
except AttributeError:
print('special key {0} pressed'.format(
key))
if key == keyboard.Key.f2:
try:
run_trade_forever()
except AttributeError:
print('specia... |
def response(message):
response = MessagingResponse()
response.message(message)
return str(response)
def signup_flow(request):
message = request.form.get('Body').lower()
phone = request.form.get('WaId')
if message in welcome:
return response(f"Welcome to Bima, we believe that maternal ca... | This code handles user interactions via a messaging system, processing commands like "exit," "signup," "welcome," "make_payment," and "view_balance." It retrieves user data, manages session states, and returns appropriate responses based on user input. | def reply():
message = request.form.get('Body').lower()
phone = request.form.get('WaId')
user = User.query.filter_by(phone=phone).first()
if message == "exit":
if session.get(phone):
session.pop(phone)
return response("User deleted successfuly")
if not user... |
def get_letter_count(f):
"""
Takes a read text file and returns an ordered list of tuples containing each alphabetic letter and its count in the text
"""
# Make sure all letters are lowercase and that there aren't any newlines or tabs
f = prep_text(f)
# Count per alphabetic letter
letter_co... | The function `text_summary` generates text analysis statistics from a file, including letter counts, total/unique word counts, and frequent words with their top following words. Results are printed or appended to an optional output file. It uses helper functions to compute counts, formats data, and ensures proper file ... | def text_summary(f, dict_f, output_file=None):
"""
Takes a read text file and prints all the summary stats
"""
if output_file is not None:
output_file = open(output_file, "a")
letter_count = get_letter_count(f) # Count per alphabetic letter
for letter, count in letter_count:
pr... |
def read_model(project, fold):
if not torch.cuda.is_available():
model = torch.load(os.path.join('..', 'weights', project, 'fold{}_best.pth'.format(fold)), map_location={'cuda:0': 'cpu'})
else:
model = torch.load(os.path.join('..', 'weights', project, 'fold{}_best.pth'.format(fold)))
for i, ... | This code performs inference on a validation dataset using a pre-trained model. It loads the dataset, initializes a model, iterates through batches, generates predictions, processes results, and executes post-prediction actions. The task involves model evaluation with TTA (test-time augmentation) options, batch process... | def predict(self, fold, val_indexes):
prefix = ('fold' + str(fold) + "_") if self.test else ""
val_dataset = SequentialDataset(self.ds, val_indexes, stage='test', config=self.config, transforms=self.val_transforms)
val_dl = PytorchDataLoader(val_dataset, batch_size=self.config.predict_batch_size... |
def disableButtons(self):
for i in range(3):
for j in range(3):
display.root.grid_slaves(row=i+2, column=j)[0].config(state="disabled")
return
def computerEasy(self):
# this ai will just pick a random spot
# note: should be relatively easy to win, as long as y... | The code handles the computer's turn in a game by disabling buttons, updating the UI to "Calculating...", selecting a move based on difficulty level, placing "X" or "O" on the board, resetting the UI to "Your turn", and re-enabling buttons if the game continues. It ensures smooth transition between turns and maintains ... | def computerTurn(self):
# disable all buttons
self.disableButtons()
# set top text to "Calculating..."
self.topText.set("Calculating...")
# show
self.display.root.update()
# wait for 1 second
time.sleep(1)
# get computer move
row, col = 0... |
def disableButton(self, row, column):
display.root.grid_slaves(row=row)[column].config(state="disabled")
return
def winCheck(self):
winner = checkWinner(self.board)
if winner != 'none': # if there is a winner
if winner == self.computer:
self.winner = "computer... | This method handles a player's move on a game board by disabling the clicked button, updating the board state with the player's symbol, and modifying the button's text. It then checks if the player has won; if not, it triggers the computer's turn to continue the game. | def boardClick(self, row, column):
# disable button at row, column
self.disableButton(row+2, column)
# update board
self.board[row][column] = self.player
# update text of the button
display.root.grid_slaves(row=row+2, column=column)[0].config(text=self.player)
... |
def selectUserNames(self):
# popup to select players
print("Select players for x and y")
self.players = (self.selectUser("X"), self.selectUser("O"))
print("Players: " + str(self.players))
return
def setupGame(self):
# determine who goes first
self.turn = self.play... | The main task of the code is to initialize and manage a game by setting up the game board, players, and display; clearing the frame; selecting user names; starting the game; updating scores; waiting for user input via `continueVar`; and quitting the GUI. It orchestrates game flow, resets state variables, and handles UI... | def main(self):
# clear all class variables
self.board = setupBoard()
self.players = ()
self.display = display()
self.forbiddenNames = [""]
self.winner = None
self.turn = None
self.topTextLabel = None
self.continueVar = tkinter.IntVar()
sel... |
def resetVars(self):
self.playerList = json.loads(requests.get(serverIP + "players").text)
self.AmHost = False
self.hostName = ""
self.username = ""
self.opponentName = ""
self.opponentPiece = ""
self.yourPiece = ""
self.game = None
self.continueVa... | The main task of the code is to manage a game session by initializing variables, clearing the GUI frame, obtaining the player's name, handling host/join logic, executing the game loop, updating scores, and exiting the application after the game concludes. It distinguishes between hosting and joining scenarios, runs cor... | def main(self):
# reset variables
self.resetVars()
# clear frame
clearFrame(display.root)
# get player name
self.getPlayerName()
# join or start
self.joinOrStart()
if self.AmHost == True:
# host game
shouldQuit = self.ho... |
def _inject_password(self, admin_password):
"""Set the root password to admin_passwd
"""
# The approach used here is to copy the password and shadow
# files from the instance filesystem to local files, make any
# necessary changes, and then copy them back.
LOG.debug(_("I... | The main task of the code is to perform post-creation configuration by injecting an admin password (if provided), uploading specified files, and attaching block device information. It handles exceptions during block device attachment and logs errors, ensuring system setup steps are executed sequentially with fault tole... | def _do_create():
if admin_password is not None:
self._inject_password(admin_password)
if inject_files:
self._inject_files(inject_files, plain=True)
if block_device_info:
try:
self._attach_bdm(block_device_info)
... |
def plug_vifs(self, network_info):
"""Plug VIFs into networks."""
instance = self.container['id']
for vif in network_info:
LOG.debug(_("Plug vif %s"), vif)
self.vif_driver.plug(vif, instance)
def _attach_vifs(self, network_info):
"""Plug VIFs into container."""
... | The code starts a container using Docker, configuring network interfaces and block devices. It logs the process, initiates the container with specific privileges and mounts, and handles network setup via plug_vifs and _attach_vifs. If network setup fails, it raises an exception. Similarly, it updates block device mappi... | def start(self, request, network_info={}, block_device_info={}):
""" Start the container. """
container_id = self.container['id']
LOG.info(_("Start container %s network_info %s block_device_info %s"),
container_id, network_info, block_device_info)
self.docker.start(con... |
def _stop(self, container_id, timeout=5):
try:
self.docker.stop(container_id, max(timeout, 5))
except dockerErrors.APIError as e:
if 'Unpause the container before stopping' not in e.explanation:
LOG.warning(_('Cannot stop container: %s'),
... | The main task of the code is to restart a container by stopping it, tearing down its network configuration, and restarting it with the same network and DNS settings. It handles network interface plugging/unplugging, cleans up namespaces, and logs errors during the process. | def restart(self, request, network_info={}, block_device_info={}):
""" Restart the container. """
# return webob.Response(status_int=204)
container_id = self.container['id']
LOG.info(_("Restart container %s"), container_id)
self._stop(container_id)
try:
networ... |
def find_groups(grid):
rows, columns = grid.shape
visited = np.zeros((rows, columns), dtype=bool)
groups = []
for row in range(rows):
for col in range(columns):
if grid[row, col] == 100 and not visited[row, col]:
new_group = []
explore_group(row, ... | The main task of the code is to process a map to identify obstacles, convert their positions to real-world coordinates, plan a navigation route to visit each obstacle, and control a robot to take pictures while navigating around obstacles until a detection threshold is met. The result includes metrics like time elapsed... | def execute_callback(self, goal_handle):
self.get_logger().info('inital pose...')
self.initial_pose_pub.publish(self.initial_pose) #this needs to be provided for when you use a map and not slam.
self.get_logger().info('Executing goal...')
self.get_logger().info('Its me, hi, Im a ID a... |
def on_session_started(session_started_request, session):
""" Called when the session starts """
print("on_session_started requestId=" + session_started_request['requestId']
+ ", sessionId=" + session['sessionId'])
def on_launch(launch_request, session):
""" Called when the user launches the skil... | The code defines an AWS Lambda handler for an Alexa skill, routing incoming requests (LaunchRequest, IntentRequest, SessionEndedRequest) to appropriate functions. It prints the application ID, includes a commented-out validation check, and triggers session-start, launch, intent, or session-end handlers based on the req... | def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
print("event.session.application.applicationId=" + event['session']['application']['applicationId'])
"""
Unc... |
def is_game_over(self):
"""Returns True if game is over"""
message = self.driver.find_element('xpath',
'/html/body/div[3]/div[4]/div[1]')
if message.get_attribute('class') == 'game-message game-over':
return True
def is_win(self):
""... | This function plays a game where the player moves tiles with priority order (right, down, up, left) when the 'block' flag is off, and (right, up, down, left) when on. It tracks moves until the game ends, returning the score, highest tile, and total moves made. | def r_a_d_t_with_block_flag_game(self):
"""Play a game.
Moves strategy: Try to move based on the following
priority: right, down, up, left, but if 'block' flag
is on, switch between down and up.
Returns: (Score, Highest tile, Number of moves)
"""
moves_flag_off =... |
def get_if_moved_grids(curr_grid):
"""Returns possible next step grids in a dict."""
directions = ['right', 'left', 'up', 'down']
if_moved = dict()
for direction in directions:
if_moved[direction] = get_board_if_move_with_score(
curr_grid, direction)
return if_moved
def is_higher... | The function `greedy_random_game` plays a game by prioritizing moves that increase the highest tile value, using a greedy strategy. If no such move exists, it randomly selects a valid move. It returns the final score, highest tile value, and total moves made. The algorithm repeatedly checks possible moves, attempts to ... | def greedy_random_game(session):
"""Play a game.
Strategy: First check if can increase highest tile.
Else, choose a random move.
:param session: Session object.
:return: (Score, Highest tile, Number of moves)
"""
moves = {'right': session.right, 'left': session.left,
'up': ses... |
def get_if_moved_grids(curr_grid):
"""Returns possible next step grids in a dict."""
directions = ['right', 'left', 'up', 'down']
if_moved = dict()
for direction in directions:
if_moved[direction] = get_board_if_move_with_score(
curr_grid, direction)
return if_moved
def is_higher... | The function `greedy_rtnl_game` plays a tile-based game using a greedy strategy: prioritize moves that increase the highest tile (right/up/down), then move right, and randomly choose up/down if no higher tile is possible. It avoids left moves unless forced. The game returns the final score, highest tile value, and tota... | def greedy_rtnl_game(session):
"""Play a game.
Moves strategy: If possible get higher top tile
(right before up or down), else move right, else,
randomly pick between up or down.
Move left only if can't move any other way.
Returns: (Score, Highest tile, Number of moves)
"""
moves = {'up... |
def is_game_over(self):
"""Returns True if game is over"""
message = self.driver.find_element('xpath',
'/html/body/div[3]/div[4]/div[1]')
if message.get_attribute('class') == 'game-message game-over':
return True
def is_win(self):
""... | The code simulates a game where moves are randomly chosen from right, up, and down, with left moves used only when no other moves are possible. It returns the final score, highest tile value, and total number of moves made during the game. | def no_left_random_game(self):
"""Play a game.
Moves strategy: every move is randomly picked from
{right, up, down}. Move left only if can't move any other way.
Returns: (Score, Highest tile, Number of moves)
"""
moves = [self.right, self.up, self.down]
moves_cou... |
def is_game_over(self):
"""Returns True if game is over"""
message = self.driver.find_element('xpath',
'/html/body/div[3]/div[4]/div[1]')
if message.get_attribute('class') == 'game-message game-over':
return True
def is_win(self):
""... | The main task of the code is to play a game by prioritizing rightward moves, randomly choosing up/down if right is blocked, and only moving left as a last resort. It returns the score, highest tile, and total moves taken until the game ends or is won. | def right_trend_no_left_game(self):
"""Play a game.
Moves strategy: If possible, move right, else, randomly pick
between up or down.
Move left only if can't move any other way.
Returns: (Score, Highest tile, Number of moves)
"""
moves = [self.up, self.down]
... |
def convex_hull(pts, clean_only=False):
"""A dummy docstring."""
lar_pb = (min((x for (x, y) in pts)), min(y for (x, y) in pts))
def angle_cmp(lar_p1, lar_p2):
if lar_p1 == lar_pb:
return -1
elif lar_p2 == lar_pb:
return +1
lar_c = -cross(lar_pb, lar_p1, lar_... | The code demonstrates convex hull computation, Pick's theorem validation, and point-in-polygon verification. It generates a grid, computes its convex hull (showing four corners), creates random points, finds closest pairs, constructs a star polygon, applies Pick's theorem to both star and convex hull, and verifies cons... | def __demo():
print("Let us compute the convex hull of a big grid.")
pts = [(x, y) for x in range(100) for y in range(100)]
random.shuffle(pts)
pts = convex_hull(pts)
print("The convex hull consists of the four corners:")
print(pts)
far_m, pts = 100, set()
print(f"Next, create {far_m} ... |
def convex_hull(pts, clean_only=False):
pb = (min((x for (x, y) in pts)), min(y for (x, y) in pts))
def angle_cmp(p1, p2):
if p1 == pb:
return -1
elif p2 == pb:
return +1
c = -cross(pb, p1, p2)
if c != 0:
return c
(dx, dy) = (p2[0] - p... | The code demonstrates convex hull computation on a grid and random points, applies Pick's theorem to star and convex polygons, and verifies point-in-polygon consistency. It generates grids, computes hulls, calculates closest points, and validates geometric algorithms through comparisons and theorem applications. | def __demo():
print("Let us compute the convex hull of a big grid.")
pts = [(x, y) for x in range(100) for y in range(100)]
random.shuffle(pts)
pts = convex_hull(pts)
print("The convex hull consists of the four corners:")
print(pts)
m, pts = 100, set()
print(f"Next, create {m} random p... |
def blink(self, times):
Pin(LED_PIN, Pin.OUT).on()
pixel = neopixel.NeoPixel(Pin(RGB_LED_PIN), 1)
pixel[0] = (0, 0, 255, 1)
pixel.write()
for i in range(times):
self.led.on()
pixel[0] = (0, 0, 255, 1)
pixel.write()
time.sleep(0.05... | The code handles device wake-up events by checking the wake reason (timer or pin interrupt). If triggered by a timer, it checks for new parameters, sends notifications, and enters deep sleep. If triggered by a pin interrupt, it blinks, logs the event, and prepares for sleep. For other wake reasons, it waits 30 seconds ... | def start(self):
print('Device woke')
self.blink(1)
reason = machine.wake_reason()
print('Got wake reason: ', reason)
if reason == machine.TIMER_WAKE:
self.blink(1)
print('Woke due to timer')
print('Checking for new params')
self... |
def describe_room(self):
print('>', self.location['name'])
print('')
print(self.location['desc'])
if 'items' not in self.location:
self.location['items'] = []
if len(self.location['items']) > 0:
print('')
print('Items: '+', '.join([x for x in... | This code defines a game loop that processes user input to control a text-based adventure game. It repeatedly prompts the player for actions, parses commands into verbs/nouns, checks validity against predefined lists, handles ambiguous inputs, and executes corresponding game actions like movement or description updates... | def play(self):
self.describe_room()
while True:
user_choice = ' '
try:
user_choice = input('What would you like to do? ').lower()
except EOFError:
print("Use 'quit' to exit.")
continue
choice_array = user_... |
def get_current_state(self):
self.startup_costs_and_emissions_if_ON()
self.shutdown_costs_and_emissions_if_OFF()
self.determine_priority_orders()
self.identify_must_ON_and_must_OFF_units()
state_dict = {
"timestep": self.timestep + 1,
"demand": self.demands_vec[self.timestep],
... | This function executes a single step in an environment by applying an action vector to the current state, validating the action, calculating rewards, and returning the next state and relevant metrics. It ensures the action's legitimacy, computes operation costs/emissions, evaluates reward based on demand and action, ch... | def step(self, action_vec: np.ndarray):
if not (isinstance(action_vec, list) or isinstance(np.array(action_vec), np.ndarray)):
raise TypeError("Action vector must be a list or NumPy array.")
action_vec = np.array(action_vec)
state_flat, state_dict = self.get_current_state()
self.demand = state_d... |
def accuracy(P, L):
"""Mean euclidean distance between two N✕2 numpy arrays"""
C = (P == L)
corr = np.sum(C)
acc = corr/len(C)
return acc
def log_confs_from_logits(logits):
logits_normalized = logits - logits.max(axis=-1, keepdims=True)
log_confidences = -logsumexp(logits_normalized, axis=-1... | The code evaluates a machine learning model's accuracy and out-of-distribution (OOD) detection capabilities using confidence thresholds, adversarial attacks (PGD), and interval bound propagation (IBP). It processes in-distribution and OOD data, computes logit bounds, confidence metrics, and AUROC scores for OOD detecti... | def evaluate_ibp_lc(model, test_loader_in, test_loader_out_list, eps, conf_th, device, short_name=None, n_pgd=0, model_path=None, n_samples=30000, do_accuracy_above=False, save_plots=False): #pass model_path to save evaluation graphs in the model directory
starttime_eval = datetime.datetime.utcnow()
torch.set_p... |
def parsehead(self):
line = self.plines[0]["content"]
i = 4
while i < len(line) and line[i] != '(':
i += 1
if i == len(line):
return 0
while i < len(line):
vname, i = self.getvname(line, i)
if vname:
self.vars[vname]... | This code parses a formula definition from a list of lines, validating structure and indentation levels. It processes 'return' statements by evaluating expressions, handles 'if' blocks recursively, and parses other expressions. Finally, it simplifies and returns the parsed return value using Z3, or 0 on errors. | def formula(self):
if len(self.plines) == 0 or self.plines[0]["type"] != "def":
print("Empty or invalid input.")
print(self.plines)
return 0
if not self.parsehead():
print("Invalid def:")
print(self.plines[0]["content"])
return 0
... |
def filterFrame(df,
colpreds,
colnames):
"""
produces filtered dataframe based on colpreds
of data from columns in colnames
df -- dataframe you want to filter
colpreds -- list of boolean filters you want
to apply using logical AND
colnames -... | The function removes outliers from specified numerical columns in a DataFrame using the 1.5×IQR method, returning a cleaned DataFrame without samples containing detected outliers. | def removeIQROutliersFromDF(df,
cols):
"""
Takes in a dataframe and numerical columns that need
to be filtered based on 1.5*IQR, returns the dataframe without
samples w/ detected outliers
"""
return filterFrame(
df,
makeFilters(df, makeIQROutlierPairs(... |
def stop(self):
"""stop containers
:return:
"""
command = f"docker-compose stop"
process = subprocess.Popen(command, cwd=self.docker_folder, shell=True, stdout=subprocess.PIPE)
process.wait()
def start(self, until_started=True):
"""start docker containers.
... | The main task of the code is to reset a container environment by removing existing containers, clearing data/metastore, and restoring to a factory state. It optionally allows table modifications, manages autostart, and handles container lifecycle operations like stopping, removing, and restarting based on parameters. | def reset(self, allow_table_modification=False, autostart=False, until_started=False):
"""remove created container. This will clear all data and metastore and restore the container to factory state.
:param allow_table_modification: reset and allow presto connector to modify hive tables
:param a... |
def getList(lst):
keywordList = []
for each in lst:
splitStr = each.split(",")
keywordList.append((splitStr[0], splitStr[1]))
return keywordList
def get5yearsOfData(lst):
dt = datetime.now()
dt = dt.replace(year=dt.year-5)
dates = getDates(str(dt.strftime('%Y%m%d')), str(dateti... | The main task of the code is to scrape news data based on user input. It accepts command-line arguments: an option (1 for 5 years of historical data, 2 for live data) and pairs of keywords and stock tickers. The code validates inputs, processes the list of keyword-ticker pairs, and calls either `get5yearsOfData` or `ge... | def main(argv):
if len(sys.argv) < 3:
inst = """
option 1 - to get 5 years of news data - "python gsScraptingEC2.py 1 <keyword>,<ticker> <keyword>,<ticker> <keyword>,<ticker> ..."
option 2 - run it for live data - "python gsScraptingEC2.py 2 <keyword>,<ticker> <keyword>,<ticker> <keyword>,<ticker> ..."
... |
def handRankWrapper(a, b, hand1, hand2):
if a ^ b == 1:
return a - b
if a & b == 1:
return highest(hand1, hand2)
return 0
def xKind(cards, x):
for card in cards:
if cards[card] == x:
return 1
return 0
def fullHouse(cards):
if (xKind(cards, 3) + xKind(cards, 2)... | The code compares two poker hands (`hand1` and `hand2`) by evaluating their ranks (e.g., five-of-a-kind, full house, etc.) in descending priority. It uses helper functions like `xKind`, `fullHouse`, `twoPair`, and `highCard` to determine hand strengths. If a rank difference is detected, it returns the result. If all ra... | def comparer(hand1, hand2):
cards1 = Counter(hand1[0])
cards2 = Counter(hand2[0])
if (ret := handRankWrapper(xKind(cards1, 5), xKind(cards2, 5), hand1, hand2)) != 0:
return ret
if (ret := handRankWrapper(xKind(cards1, 4), xKind(cards2, 4), hand1, hand2)) != 0:
return ret
if (ret := ... |
def createFuncMapping(self, AST):
logging.debug("Building the symbol table before running the program")
stack = [AST] #the stack for symbols, not to be confused with the stacks the user code operates on
while(len(stack) != 0):
node = stack.pop()
if(node.token.label ==... | (This function interprets an abstract syntax tree (AST) by traversing nodes and executing operations. It manages control flow (IF, LOOP), stack operations (STACK), math (MATH), I/O (IO), and function calls (CALLFUNC). It maintains execution context via stacks (s1, s2) and scope tracking, ignoring FUNC nodes since they'... | def run(self, ast):
self.createFuncMapping(ast) #TODO: we will only be pushing references onto the stack each time we enter a scope, so that shouldn't be
#too bad performance wise right?? May need to check this and reimplement if that isn't the case
self.sco... |
def play(self, actions):
"""
Apply the given actions to the environment.
Parameters:
actions (np.ndarray): The actions to be applied to the environment, represented as a 4-tuple of integers (from_row, from_col, to_row, to_col)
Returns:
tuple: A 4-tuple containing the fo... | This code processes a game step in a reinforcement learning environment, executing a player's move, validating it, updating the state, and letting Stockfish respond. It calculates rewards, generates observations, checks game termination, and returns these values for training or evaluation. | def step(self, actions):
white_piece_moved = self.board[actions[0]][actions[1]]
white_valid_move, white_captured_piece, white_in_check, white_promoted = self.play(actions)
if white_valid_move and not white_in_check:
self.update_stockfish_state(actions, white_promoted)
sto... |
def config_parser():
import configargparse
parser = configargparse.ArgumentParser()
parser.add_argument('--config', is_config_file=True,
help='config file path')
parser.add_argument("--basedir", type=str, default='./logs/',
help='where to store ckpts an... | The code trains a neural network for rendering and depth estimation using the KITTI360 dataset. It loads data, sets up intrinsics, initializes a NeRF model, and performs ray batching for training. The loop computes image and depth losses, applies gradient updates, and adjusts learning rates. It saves checkpoints, rende... | def train():
parser = config_parser()
args = parser.parse_args()
# Load data
K = None
if args.dataset_type == 'kitti360':
images, poses, depths_gt, test_poses, render_poses, random_poses, hwf, near, far, _ = load_kitti(
data_root = a... |
def get_orders(session):
# Define the tickers you will be trading
tickers = ["AC", "RY", "CNR"]
# Initialize the open_orders dictionary with the tickers and required structure
open_orders = {
ticker: {"BUY": [], "SELL": [], "order_data": {}}
for ticker in tickers
}
# Return all... | The main task of the code is to execute buy/sell limit orders for a given stock ticker based on market conditions, technical indicators (RSI, MACD), and predefined parameters. It checks for open orders, ensures sufficient bid-ask spread, calculates position size, adjusts order prices using RSI/MACD signals, and submits... | def open_trade(session, ticker):
# Initial trade execution function
open_orders = get_orders(session)
market_data = get_market_data(session, ticker)
ticker_volume_alotment = {"CNR": 8000, "RY":10000, "AC": 5000}
ticker_order_sizes = {"CNR": 1600, "RY":2000, "AC": 1000}
position = get_position(... |
def get_tick(session):
#Return tick of current simulaion
resp = session.get('http://localhost:9999/v1/case')
data = resp.json()
if resp.ok:
data = resp.json()
return data['tick'], data['status']
else:
return -1
def megatrade(session):
open_trade(session, ticker="AC")
... | The main task of the code is to continuously monitor and execute trading algorithms using an API session. It checks tick status conditions, runs `megatrade` and `mega_reorder` functions when valid, handles errors gracefully, and pauses execution when the system is "STOPPED," ensuring stable algorithm operation with tim... | def main():
print("Running main() function")
with requests.Session() as s:
s.headers.update(API_KEY)
tickers = ["AC", "RY", "CNR"]
while True:
if get_tick(s)[0] > 2 and get_tick(s)[0] < 296:
# Prevents random errors from affecting algos functi... |
def generate_unary_visible(self, x, evidence_mask, observed_var=1e-3):
x_ = torch.from_numpy(x).to(self.dev).type(self.dtype)
target_mask_ = torch.from_numpy(1 - evidence_mask).to(self.dev).type(self.dtype)
# Mean is the observed value for those that are observed.
means = self.mu.t() *... | This code trains a probabilistic model using stochastic gradient descent with Adam optimizer. It processes data in minibatches, applies belief propagation for inference, computes a loss based on inferred beliefs, and updates parameters via backpropagation. The model uses masks to distinguish target and evidence nodes, ... | def train(
self,
num_epochs=100,
n_bp_iter=50,
mb_size=200,
sb_size=20,
p_target=0.5,
box_mask=False,
):
n_images = self.X.shape[0]
optimizer = torch.optim.Adam((self.W, self.c, self.mu), lr=5e-3)
for epoch in range(num_epochs):
... |
def gibbs_initialize_h1_from_vh2_with_mask(v_true, mask, w1, w2, hid_b1, hid_b2, vis_b):
v = np.array([np.random.binomial(1, 0.5) for _ in range(vis_b.shape[0])])
v[mask == 0] = v_true[mask == 0]
h2 = np.array([np.random.binomial(1, 0.5) for _ in range(hid_b2.shape[0])])
# v, h2 to h1
h1 = np.array(... | This function performs Gibbs sampling on a masked RBM to generate samples of visible units. It initializes hidden units, runs a warm-up phase to stabilize the distribution, then samples n_samples times, updating hidden units and computing visible unit expectations using the learned weights and biases. The mask controls... | def gibbs_sampling_with_mask(
n_samples,
v,
mask,
w1,
w2,
hid_b1,
hid_b2,
vis_b,
n_warmup_samples=5000,
random_h1=False,
):
# Initialize h1
if random_h1:
h1 = np.array([np.random.binomial(1, 0.5) for _ in range(hid_b1.shape[0])])
else:
h1 = gibbs_initi... |
def vis2hid(v, w, hid_b):
return sigmoid(-vis2hid_potential(v, w, hid_b))
def gibbs_hvh_with_mask(h, v_true, mask, w, hid_b, vis_b):
v = gibbs_hv(h, w, hid_b, vis_b)
v[mask == 0] = v_true[mask == 0]
h = gibbs_vh(v, w, hid_b, vis_b)
return h
def hid2vis(h, w, vis_b):
return np.dot(h.astype(np.flo... | The function performs Gibbs sampling with a mask to generate latent variable samples and their corresponding visible layer means. It initializes hidden states, runs a warm-up phase to stabilize distributions, then collects samples by iteratively updating hidden states. The mask likely controls which visible units are o... | def gibbs_sampling_with_mask(
n_samples, v, mask, w, hid_b, vis_b, n_warmup_samples=100000
):
# Initialize h
h = np.array(
[
np.random.binomial(1, p)
for p in vis2hid(np.random.randn(vis_b.shape[0]) + vis_b, w, hid_b)
]
)
for ii in range(n_warmup_samples):
... |
def write_list(dirs, l):
fname = get_csv_name(dirs)
csv_writer = csv.writer(open(fname, 'w'), dialect='excel')
header = []
if "video" in dirs[0]:
header = ["A_url", "B_url"]
elif "frame" in dirs[0]:
header = ["A_url", "B_url", "image_url"]
csv_writer.writerow(header)
for p in... | The main task of the code is to generate and write comparison lists between specified directories based on given styles. If `independent` is True, it creates pairwise comparisons between all directory pairs. If False, it generates a comprehensive comparison across all directories. The function prints the directories an... | def build_list(dirs, styles, independent=False):
print("=> build %s" % ",".join(dirs))
print("=> style %s" % ",".join(styles))
if independent:
n = len(dirs)
for i in range(n):
for j in range(i + 1, n):
write_list([dirs[i], dirs[j]], get_compare_list(dirs[i], dirs[... |
def log_message(self, message, tag=''):
self.view.log_panel_frame.log_message(message, tag)
def update_file_management_model(self):
model = self.model.file_management_model
view = self.view.file_management_frame
try:
model.output_directory = view.output_directory
... | The code defines an event handler for a button click, logging the action and triggering updates to two models: file management and artwork criteria. Its main task is to handle user interaction by updating relevant data models upon a "fetch" button press. | def on_fetch_button_clicked(self, event):
self.log_message("fetch clicked")
self.update_file_management_model()
self.update_file_artwork_criteria_model() |
def _get_retries(self, retries, redirect):
if not isinstance(retries, Retry):
retries = Retry.from_int(
retries, redirect=redirect, default=self.retries)
if retries.connect or retries.read or retries.redirect:
warnings.warn(
"URLFetch only support... | This function performs an HTTP request using URLFetch, handling errors like timeouts, redirects, and size limits. It manages retries based on configured parameters, converts URLFetch responses to HTTP responses, and enforces retry logic when necessary, returning the final HTTP response or raising appropriate exceptions... | def urlopen(self, method, url, body=None, headers=None,
retries=None, redirect=True, timeout=Timeout.DEFAULT_TIMEOUT,
**response_kw):
retries = self._get_retries(retries, redirect)
try:
response = urlfetch.fetch(
url,
payload=... |
def get_params(goal, step_size, client):
params = {}
params['start_time'] = time.time()
params['goal'] = goal
params['step_size'] = step_size
params['client'] = client
params['dstar'] = 1.5
params['chi'] = 0.8
params['qstar'] = 2
params['eta'] = 0.8
params['grad'] = Point(1,1)
... | The main task of the code is to plan a collision-free path from a start point to a goal while avoiding obstacles using a potential field approach. It employs ROS actionlib for movement control, iteratively updates path parameters, checks proximity to the goal, and adjusts the path dynamically to ensure safety and accur... | def potential_planner(start, goal, obstacles_list, step_size):
rospy.init_node('test', anonymous=True)
client = actionlib.SimpleActionClient('move_xy', MoveXYAction)
client.wait_for_server()
params = get_params(goal, step_size, client)
curr_pos = start
params = update_params(params, curr_pos)
... |
def goal_termination():
return euclid_dist(params['goal'], params['my_pose'][:2]) < params['eps']
def gen_samples():
theta = params['my_pose'][2]
params['samples'] = []
for vel in np.linspace(0, VEL_MAX, params['vel_d']):
for ang in np.linspace(theta-ANG_MAX, theta+ANG_MAX, params['ang_d']):
if vel!=0:
par... | The code's main task is to navigate towards a goal while avoiding obstacles by iteratively generating path samples, filtering valid points, optimizing a trajectory, and progressing until the goal is reached. The loop continues until the termination condition for reaching the goal is satisfied. | def avoid_obs():
while not goal_termination():
gen_samples()
filter_points()
opti_point()
proceed() |
def conv_arr(arr):
arr1 = []
for i in range(len(arr)):
arr1.append(Point(arr[i][0], arr[i][1]))
return arr1
def computeDistancePointToPolygon(arr, q):
if not isinstance(arr[0], Point):
arr = conv_arr(arr)
n = len(arr)
d_min = 1e6
for i in range(n):
d, w = computeDistancePointToSegment(q, arr[i%n], arr[... | This function computes a tangent vector to a polygon at a given point q. It handles three cases: when q lies on an edge (returns a normalized edge direction scaled by the polygon's area), when q coincides with a vertex (returns an adjusted tangent based on adjacent edges), or when q is near a vertex (returns a modified... | def computeTangentVectorToPolygon(arr, q):
if not isinstance(arr[0], Point):
arr = conv_arr(arr)
n = len(arr)
d_min, w_0, idx = computeDistancePointToPolygon(arr, q)
if w_0 == 0:
b = misc_area(arr)
norm = arr[idx%n].dist(arr[(idx+1)%n])
return b*(arr[idx%n].x - arr[(idx+1)%n].x)/norm, b*(arr[idx%n].y - ar... |
def conv_arr(arr):
arr1 = []
for i in range(len(arr)):
arr1.append(Point(arr[i][0], arr[i][1]))
return arr1
def computeDistancePointToPolygon(arr, q):
if not isinstance(arr[0], Point):
arr = conv_arr(arr)
n = len(arr)
d_min = 1e6
for i in range(n):
d, w = computeDistancePointToSegment(q, arr[i%n], arr[... | This function computes the normal vector to a polygon at the closest point to a given query point q. It first checks if the input points are of type Point, converting them if necessary. Depending on whether the closest point to q is a vertex (w_0=0) or an edge (w_0=1 or else), it calculates the normal vector using eith... | def computeNormalVectorToPolygon(arr, q):
if not isinstance(arr[0], Point):
arr = conv_arr(arr)
n = len(arr)
d_min, w_0, idx = computeDistancePointToPolygon(arr, q)
if w_0 == 0:
b = misc_area(arr)
norm = arr[idx%n].dist(arr[(idx+1)%n])
return -b*(arr[idx%n].y - arr[(idx+1)%n].y)/norm, b*(arr[idx%n].x - a... |
def pixels_fill_notes(colour):
for i in range(NEO_PIXEL_NOTES_START, (NOTE_BUTTON_NUM + NEO_PIXEL_NOTES_START)):
pixels_set(i, colour)
def pixels_show():
# Create a new array and fill it with the same colours, just less bright...
dimmer_ar = array("I", [0 for _ in range(len(NEO_PIXELS))])
for i,... | The function handles an octave down button press by decrementing the global MIDI octave, clamping it to valid values, updating NeoPixel colors to reflect the new octave, re-triggering active notes, and refreshing the display with updated visual indicators for octave selection. | def octave_down(_sm):
""" IRQ handler for the octave down button """
global MIDI_OCTAVE
# Calculate the new octave
new_octave = MIDI_OCTAVE - 1
if new_octave not in MIDI_OCTAVES:
new_octave = MIDI_OCTAVES[0]
if new_octave != MIDI_OCTAVE:
# Change colour
pixels_fill_note... |
def pixels_fill_notes(colour):
for i in range(NEO_PIXEL_NOTES_START, (NOTE_BUTTON_NUM + NEO_PIXEL_NOTES_START)):
pixels_set(i, colour)
def pixels_show():
# Create a new array and fill it with the same colours, just less bright...
dimmer_ar = array("I", [0 for _ in range(len(NEO_PIXELS))])
for i,... | This function handles an octave-up button interrupt by incrementing the MIDI octave, clamping it within valid ranges, updating NeoPixel colors to reflect the new octave, re-triggering active notes, and adjusting visual indicators for octave direction. | def octave_up(_sm):
""" IRQ handler for the octave up button """
global MIDI_OCTAVE
# Calculate the new octave
new_octave = MIDI_OCTAVE + 1
if new_octave not in MIDI_OCTAVES:
new_octave = MIDI_OCTAVES[len(MIDI_OCTAVES) - 1]
if new_octave != MIDI_OCTAVE:
# Change colour
... |
def Box(noise, size, output):
ytime = arrsize[1] - size + 1
xtime = arrsize[0] - size + 1
for y in range(ytime):
for x in range(xtime):
total = 0
for box_y in range(size):
for box_x in range(size):
total += noise[y + box_y][x + box_x]
... | The code visualizes different noise filtering techniques by applying 3x3/5x5 box filters, median filters, and morphological operations (closing-opening, opening-closing) on an input noise image. It calculates and displays the Signal-to-Noise Ratio (SNR) for each method, arranging six processed images in a 3x2 grid with... | def ShowNoise(noise, n_snr, name, toptitle):
box3 = np.zeros([arrsize[0] - 1, arrsize[1] - 1], dtype = np.float)
snr_box3 = Box(noise, 3, box3)
title_box3 = 'box 3x3 SNR = ' + str(round(snr_box3, 3))
box5 = np.zeros([arrsize[0] - 2, arrsize[1] - 2], dtype = np.float)
snr_box5 = Box(noise, 5, box5)
... |
def get_parent_dir(path: str) -> str:
"""Returns the absolute path of the parent directory"""
return os.path.abspath(os.path.join(path, os.pardir))
def convert_attachments_to_pdf(agenda_items: List[AgendaItem], output_dir: str):
"""
Converts and saves AgendaItem attachments to PDF format.
Returns a ... | The main task of the code is to generate a structured agenda PDF using HTML templates, combining a title page, table of contents, and agenda items. It processes input models, converts attachments to PDFs, merges them with the TOC, and outputs a finalized document with proper formatting, bookmarks, and internal links. | def generate_agenda(template: AgendaTemplate,
agenda: Agenda,
agenda_items: List[AgendaItem],
output_path: str = os.path.join(BASE_DIR, "uploads/untitled_agenda.pdf")):
"""
Generate an agenda PDF.
:param template: the agenda template
:param ag... |
def read_csv(filename, input_cols=(0,1,2,3), input_dtype=float, output_categories={4: ("Iris-setosa", "Iris-versicolor", "Iris-virginica")}):
"""
Reads from csv file into a data file
:param filename: String name of file to use
:param input_cols: tuple with column numbers for input (starting with 0)
... | The main task of the code is to read the Iris dataset, split it into training and testing sets, train three distance-based classifiers (Euclidean, Manhattan, Chebyshev), print category centers, and evaluate their accuracy on the test set by comparing correct and incorrect predictions. | def main():
"""
Main function of script
Reads from file 'iris.csv', trains a Euclidean distance algorithm,
then prints the data point centers and tests the last 20% of data
"""
data = read_csv("iris.csv")
training_set, testing_set = split_data(data, proportions=(8,2), random=True)
... |
def Lambda_of_mass(
central_pressure_array, mass, gamma_0, gamma_1, gamma_2, gamma_3,
maximum_mass_limit=1.97):
'''
We interpolate the Lambda_array_from_central_pressure function
to obtain Lambda, given a mass, an array of central pressures
and an EoS model.
If the maximum_mass is ... | This function generates binary neutron star (BNS) tidal parameters (lambda_1, lambda_2) from posterior samples of a piecewise polytrope equation of state (EOS). It calculates tidal deformabilities for each neutron star mass in the samples, appends them to the posterior data, and optionally filters out samples violating... | def generate_bns_parameters_from_piecewise_polytrope_posteriors(
posterior_samples, maximum_speed_of_sound=1.15,
max_mass=1.90, check_eos_constraints=False,
pressure=np.logspace(np.log10(4e32), np.log10(2.5e35), 70)):
'''
Parameters
----------
posterior_samples = pandas dataframe... |
def isospin_asymmetry(xarr, S_0, L_0, K_sym, J_sym):
f_n = neutron_fraction(xarr, S_0, L_0, K_sym, J_sym)
return 2 * f_n - 1
def symmetric_energy_model(xarr, E_0, K_0, J_0):
Esnm = E_0 + K_0 * xarr**2 / 2 + J_0 * xarr**3 / 6
return Esnm / JtoMeV
def symmetry_energy_model(xarr, S_0, L_0, K_sym, J_sym):
... | This function calculates the dimensionless energy per baryon by combining symmetric energy and symmetry energy models. It uses isospin asymmetry to weight the symmetry energy, then normalizes the total energy by the average baryon mass and speed of light squared, returning a dimensionless value for nuclear energy per b... | def dimensionless_energy_per_baryon_model(xarr, E_0, K_0, J_0,
S_0, L_0, K_sym, J_sym):
delta = isospin_asymmetry(xarr, S_0, L_0, K_sym, J_sym)
epb = symmetric_energy_model(xarr, E_0, K_0, J_0) + \
symmetry_energy_model(xarr, S_0, L_0, K_sym, J_sym) * delta**2
... |
def get_seat_one():
box = (x_pad + 27, y_pad + 60, x_pad + 23 + 63, y_pad + 60 + 16)
im = ImageOps.grayscale(ImageGrab.grab(box))
a = array(im.getcolors())
a = a.sum()
print(a)
# im.save(os.getcwd() + '\\Images\\seat_one__' + str(int(time.time())) + '.png', 'PNG')
return a
def makeFood(food)... | The main task of the code is to check the occupancy status of six tables, determine the required sushi type for each occupied table using a lookup dictionary, and prepare the corresponding food if valid. It handles errors for invalid sushi types and logs table status, repeating this process for all tables before cleari... | def run_game():
s1 = get_seat_one()
if s1 != Blank.seat_1:
if sushiTypes.__contains__(s1):
print('table 1 is occupied and needs %s' % sushiTypes[s1])
makeFood(sushiTypes[s1])
else:
print('sushi not found!\n sushiType = %i' % s1)
else:
print('Table ... |
def launch_page():
driver = webdriver.Firefox()
driver.maximize_window()
driver.implicitly_wait(10)
driver.get("https://www.miniclip.com/games/sushi-go-round")
time.sleep(5)
driver.execute_script("arguments[0].scrollIntoView();",
driver.find_element_by_css_selector("sec... | The main task of the code is to automate a game loop by repeatedly running the game (500 iterations), checking for failure conditions, handling failure responses (e.g., continuing or retrying), verifying win status, and monitoring daily goals. It initializes the game, starts it, and continuously processes game logic wh... | def main():
# buyFood("rice")
# check_you_win()
# check_shrimp_level()
# screenGrabGoal()
# get_ocr_text()
launch_page()
startGame()
for i in range(500):
run_game()
check_fail()
fail_continue_watermark()
fail_try_again()
check_you_win()
ch... |
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = path.abspath(".")
return path.join(base_path, re... | This code initializes a GUI application by loading a UI from 'main.ui', setting up default header items for a table (including chemical-related parameters like charge and adducts), configuring mass precision, enabling search functionality, and initializing undo/redo mechanisms. It also disables certain UI actions initi... | def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
#load UI from main.ui
uic.loadUi(resource_path("view/main.ui"), self)
#default header items
self.header_items = [HeaderItem('name'),
HeaderItem('compound'),
HeaderItem('neutra... |
def generateprime(keylength):
primenumberlist = []
number = random.randrange(2, 2 ** keylength - 1)
for iteration in range(0,number):
prime = True
for iteration2 in range(2,iteration):
if iteration % iteration2 == 0:
prime = False
if prime:
pri... | The code generates RSA cryptographic keys by selecting two large prime numbers, computing their product (n), calculating Euler's totient function (phi), choosing a public exponent (e) coprime to phi, and determining the private exponent (d) as the modular inverse of e. It returns the public key components (e, n) and th... | def keygenerationalgo(keylength):
prime1 = generateprime(keylength)
prime2 = generateprime(keylength)
print('Prime p:'+ str(prime1))
print('Prime q:' + str(prime2))
#
n = prime1 * prime2
phiofN = (prime1 - 1) * (prime2 - 1) # totient
print("Euler Totient of n: " + str(phiofN))
# cho... |
def keygenerationalgo(keylength):
prime1 = generateprime(keylength)
prime2 = generateprime(keylength)
print('Prime p:'+ str(prime1))
print('Prime q:' + str(prime2))
#
n = prime1 * prime2
phiofN = (prime1 - 1) * (prime2 - 1) # totient
print("Euler Totient of n: " + str(phiofN))
# cho... | The main task of the code is to demonstrate RSA encryption and decryption. It generates RSA key pairs (public and private), encrypts user-input text using the public key, decrypts the ciphertext with the private key, and prints both keys along with the original and decrypted messages. The function also displays the use... | def rsa():
print("Name: Ali Aqeel Zafar")
print("Neptune ID: AAFZDE")
keylength = 10
message = input("Enter Message:")
e,d,n=keygenerationalgo(keylength)
print('Public Key Pair:' + '(' + str(e) + ',' + str(n) + ')')
print('Private Key Pair:' + '(' + str(d) + ',' + str(n) + ')')
intermlit... |
def _make_unique_classes(detection_data: Iterable[DetectionData]):
class_exists = []
for detection in detection_data:
if detection.name not in class_exists:
class_exists.append(detection.name)
return class_exists
def _make_scaler_field(config: Config, init=0) -> list[list[list[any]]]:
... | The function generates class-specific semantic fields by processing detection data with a configuration. It first identifies unique object classes, initializes scaler fields for each class, filters detection data per class, and applies a weighting algorithm to create scaled fields, returning a dictionary mapping classe... | def create_semantic_fields(
self, detection_data: Iterable[DetectionData], config: Config
) -> dict[str, list[list[list[float]]]]:
# make unique classes list
classes_unique = _make_unique_classes(detection_data)
scaler_fields = {}
for _class in classes_unique:
sc... |
def reformate_workflows(wf):
"""
Reformate history workflow into a list and a dictionary with key being the tool names
:param wf: Bioblend workflow
:return: list and dictionary
"""
ordered_wf = []
wf_by_tools = {}
for key, step in wf.items():
if is_input(step):
conti... | The code compares a user workflow (hist_wf) to a reference workflow (ref_wf) by analyzing step counts, input numbers, and tool usage. It reformats workflows, checks for similarities in inputs/steps, and generates a detailed report comparing ordered steps and tool-specific differences. The report includes counts, boolea... | def compare_workflows(hist_wf, ref_wf, report):
"""
Compare a user workflow to a reference workflow and generate a report
:param hist_wf: dictorionary with history extracted workflow
:param ref_wf: dictionary with reference workflow
:return: dictionary with report
"""
hist_wf = hist_wf['ste... |
def get_workflow_from_history(hist_url, apikey):
"""
Extract the workflow from a Galaxy history using bioblend
:param hist_url: URL to Galaxy history
:param apikey: API key to Galaxy server with history
:return: dictionary with the workflow corresponding to Galaxy history
"""
# Get Galaxy U... | (The function `ghevaluator` processes input URLs and an API key to retrieve a workflow from a Galaxy history and a standard workflow template. It compares these workflows using a dedicated comparison function and generates a report file at the specified output path, serving as the central driver for workflow evaluation... | def ghevaluator(hist_url, wf_url, apikey, output_dp):
"""
The main function
This function serves as the driver and connection between all major parts of the program:
1. Call different fundtions to process the parameters, and to generate two workflows.
2. Pass the two workflows to the compare funct... |
def display_word_table(word_commonalities):
"""
to display our top 5 word choices every time
"""
for (word, freq) in word_commonalities:
print(f"{word:<5} | {freq:<5.2}")
def sort_by_word_commonality_git(words):
"""
generate a sorted (highest-to-lowest) list of tuples,
with ea... | The code implements a word-solving algorithm for a game similar to Wordle, focusing on Git-related terms. It iteratively narrows down possible solutions by analyzing user feedback (G for correct position, Y for correct letter elsewhere, ? for incorrect). The algorithm updates constraints on each letter's validity, filt... | def solve_git():
possible_words = set(gitksan_word_list).copy()
word_vector = [set(token_list) for _ in range(GIT_WORD_LENGTH)]
for attempt in range(1, ALLOWED_ATTEMPTS + 1):
print(f"Attempt {attempt} with {len(possible_words)} possible words")
display_word_table(sort_by_word_commonality_git... |
def get_single_attr_configs(attribute:str, to_select_attrs=None):
"""
Associates each value of the attribute to all the configurations containing it. Allows to specify which
configurations to exclude through an additional dictionary mapping (other attribute names, [allowed values list]).
"""
if to_... | The function aggregates training results from multiple configurations into a single DataFrame, filtered by a specific attribute. It maps attribute values to corresponding filenames, compiles their results into separate DataFrames, adds a column indicating the attribute's value, and combines all these DataFrames into on... | def dframes_for_attribute(attribute:str, to_select_attrs=None):
"""
Returns a DataFrame containing all training results for one specific attribute, with one
additional column indicating the attribute's value.
"""
# dict attribute value --> filenames containing it
values_filenames_dict = get_sing... |
def set_stats_path(name:str):
global _statistics_path;
_statistics_path = name
try: os.mkdir(name)
except FileExistsError: pass
def get_attr_possibilities():
"""
Returns a dictionary associating each attribute to its possible values.
"""
cfgs = [attrs_from_fname(name) for name in avail... | This code generates a comparative bar chart analyzing the performance of different LSTM architectures (varying num_layers and hidden_size) using Adam and AdamW optimizers, across metrics like accuracy, F1 score, and non-'O' accuracy, to evaluate optimizer effectiveness in the given task. | def optimizer_graph():
set_stats_path('LSTM_architecture_stats')
metrics=['accuracy', 'f1', "non-'O' acc."]
attribute = "optimizer"
ps = get_attr_possibilities()
layer_possibilities = ps['num_layers']
hidden_size_possibilities = ps['hidden_size']
adam_dframes = {}
wadam_dframes = {}
... |
def check_posible_move(self, x, y):
if self._is_finish:
raise Exception("Error. Can't play a finished game.")
if not (self.in_range(x) and self.in_range(y)):
raise Exception("Error. Invalid coodinated to play.")
if self._board[y][x] != self._empty:
raise Exc... | The code executes a player's move by updating the game board at position (x, y) with the current player's symbol, switches to the next player, and checks if the game has ended, returning the result. | def make_move(self, move):
x, y = move
self.check_posible_move(x, y)
self._board[y][x] = self._turn
self._turn = self.next_player()
return self.check_if_ended() |
def get_ingredient_ids():
'''
gets list of top 1000 ingredient ids
'''
ingredient_ids = {}
with open('top-1k-ingredients.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=';')
for row in csv_reader:
ingredient_ids[row[0]] = row[1]
return ingredient_ids
def ingredient_to_id(ingredi... | The main task of the code is to process user queries for recipe recommendations by integrating ingredient inclusion/exclusion filters, dietary constraints, and condition-based logic. It retrieves and cleans recipe data from APIs, constructs a recipe-ingredient graph, applies filtering rules, and returns a list of recip... | def prep_for_flask(user_query, ingredient_in=[], ingredient_ex=[], diet='', condition=''):
'''
Combines prior functions for output to user
'''
# get ingredient ids
ingredient_ids = get_ingredient_ids()
# convert ingredient include/exclude to ids
ingredient_in = [ingredient_to_id(ingredient, ingredient_id... |
def randomize_order(self):
ordtype = 2 # limit order
leverage = 1 # spot leverage is 1
side = choice(self.order_sides) # pick random side
price = self.decim(round(self.mid_price, self.price_precision))
qty = self.decim(round(self.qty, self.qty_precision))
if len(self.... | The main task of the code is to execute three operations sequentially: randomize order data, update orders, and randomly cancel orders, with pauses (`sleep`) between each step to introduce delays. These actions are likely part of a simulation or automation process involving order management, ensuring randomized process... | def main(self):
self.randomize_order()
sleep(self.sleep)
self.update_orders()
sleep(self.sleep)
self.random_cancel()
sleep(self.sleep) |
def __scoring_function__(self,grid,node_number,number_of_parts):
list_of_number_of_branches,_ = self.__get_list_of_number_of_branches__(grid,node_number)
value, combination = self.__find_best_score__(list_of_number_of_branches,number_of_parts)
combination_of_lines = []
for bit, line_n... | The main task of the code is to split a grid into a specified number of sub-grids using either an "exponential" scoring method or an iterative approach. It evaluates nodes' scores, identifies optimal split points, generates child grids, and checks consistency. The function returns the list of child grids and a flag ind... | def __split_grid__(self,number_of_parts=2,split_method="exponential"):
list_of_child_grids = []
optimal_locations = {}
if split_method == "exponential":
#### brute-force method to compute the objective function value for all nodes and then find the minimum
score=[]
... |
def get_user_secret_key(self) -> str:
user = self.get_user()
return getattr(user, self.options.get("user_secret_column"))
def get_user(self):
return Request.user()
def verify(self, code: str) -> bool:
"""Verify the given code (or backup code) for the given user."""
totp = pyotp.T... | The main task of the code is to enable two-factor authentication (2FA) for a user by verifying a provided code. If successful, it updates the user's 2FA status, generates backup codes (if configured), saves the changes, logs the user in, and returns `True` with unhashed backup codes. If verification fails, it returns `... | def enable(self, code) -> bool:
if not self.get_user_secret_key():
raise Exception("must user start_enabling() before.")
user = self.get_user()
if self.verify(code):
unhashed_codes = []
if self.options.get("backup_codes", False):
unhashed_codes... |
def enabled(self) -> bool:
"""Check is 2FA is globally enabled."""
return self.options.get("enabled", False)
def user_enabled(self) -> bool:
"""Check is 2FA is enabled (configuration completed) for the given user."""
user = self.get_user()
return bool(getattr(user, self.options.g... | This function determines if 2FA authentication can be skipped by checking if 2FA is disabled, the user is not enabled, or the authentication token is still valid. It returns True if any of these conditions are met, allowing the authentication step to be bypassed during the request flow. | def can_skip_auth(self):
"""Check during request flow if 2FA auth verification can be skipped."""
return not self.enabled() or not self.user_enabled() or self.is_still_valid() |
def load_page(url, wait=None, retries=10):
for i in range(retries):
try:
if wait:
time.sleep(wait) # necessary to avoid 500 errors
r = do_request(url)
return r.text
except Exception as e:
print(e)
continue
raise Exception("%s failed" % url)
def scrape_house_vote(url):
... | The main task of the code is to parse a legislative bill's webpage, extract structured data including the bill's title, sponsors, last action, versions, amendments, and voting records, and return this information in a dictionary. It processes HTML tables to identify bill details, handles nested data like amendments and... | def parse_bill(url):
print("Loading " + url)
html_doc = load_page(url, wait=1)
soup = BeautifulSoup(html_doc, 'html.parser')
bill_table = soup.find_all('table')[1]
bill = {
'url': url,
'last_action': bill_table.find_all('tr')[1].find_all('td')[1].find('i').strong.string if bill_table.find_all('tr')[... |
def metas_or_numpy_funcs(metas=False):
# this is my way to switch between metas and numpy functions
if metas:
dot = munc.ulinalg.dot
inv = munc.ulinalg.inv
eig = munc.ulinalg.eig
solve = munc.ulinalg.solve
conj = munc.umath.conj
exp = munc.umath.exp
... | The main task of this code is to perform multi-standard Through-Reflect-Line (mTRL) calibration at a single frequency, computing the calibration matrix (X), propagation constant (gamma), effective permittivity (er), and reflection coefficient (reflect_est) using T-parameters, Takagi factorization, eigenvalue decomposit... | def mTRL_at_one_freq(Slines, lengths, Sreflect, ereff_est, reflect_est, f, sw=[0,0]):
# Performing a standard mTRL without uncertainty.
# Slines: array containing 2x2 S-parameters of each line standard
# lengths: array containing the lengths of the lines
# Sreflect: 2x2 S-parameters of the measured refl... |
def metas_or_numpy_funcs(metas=False):
# this is my way to switch between metas and numpy functions
if metas:
dot = munc.ulinalg.dot
inv = munc.ulinalg.inv
eig = munc.ulinalg.eig
solve = munc.ulinalg.solve
conj = munc.umath.conj
exp = munc.umath.exp
... | This function performs TRL calibration at a single frequency, incorporating uncertainty propagation. It processes S-parameters of line and reflect standards, estimates effective permittivity, and computes calibration coefficients (X), propagation constant (γ), and reflection coefficient. It handles covariance matrices,... | def umTRL_at_one_freq(Slines, lengths, Sreflect, ereff_est, reflect_est, f, X, k, sw=[0,0],
uSlines=None, ulengths=None, uSreflect=None, ureflect=None, uereff_Gamma=None, usw=None):
# Slines: array containing 2x2 S-parameters of each line standard
# lengths: array containing the lengths of... |
def run_mTRL(self):
# This runs the standard mTRL without uncertainties (very fast).
gammas = []
lambds = []
Xs = []
ks = []
ereff0 = self.ereff_est
gamma0 = 2*np.pi*self.f[0]/c0*np.sqrt(-ereff0)
gamma0 = gamma0*np.sign(gamma0.real) # use po... | The main task of the code is to perform uncertainty analysis in the mTRL (multi-lineTRL) calibration process by propagating uncertainties through each frequency step. It initializes nominal coefficients, converts uncertainty parameters into covariance matrices, iterates over frequencies, computes calibrated parameters ... | def run_umTRL(self):
# This runs the mTRL with uncertainties
# (quite slow because of METAS UncLib, but faster than a MC analysis ;) ).
self.run_mTRL() # initial run to get nominal cal coefficients
gammas = []
lambds = []
Xs = []
ks = []
... |
def separate_conj_map_from_message(grids, alpha):
"""
grids is a list of numpy arrays, all of the same size
returns two lists, representing the message grids and the conj_map grids
n.b. some percent of each conj_map grid will be junk bits added to keep complexity above alpha
"""
if not grids:
... | The function processes input grids to separate conjugated maps and messages, constructs a conjugate map from the grids, extracts message grids using this map, and writes the resulting message grids to the specified output file. | def write_conjugated_message_grids(outfile, grids, alpha):
messages, conj_map_grids, nbits_per_map = separate_conj_map_from_message(grids, alpha)
if len(conj_map_grids) == 0:
return
conj_map = get_conj_map(conj_map_grids, nbits_per_map)
message_grids = get_message_grid_from_grids(messages, conj_... |
def get_transformation_matrices(sample_list):
joint_angles = sample_list[0]
pos = np.array(sample_list[1])
rot = np.array(sample_list[2])
matrices = [rob_transformation_matrix(joint_angles), quaternion_to_transformation_matrix(pos, rot)]
return matrices
def create_a_i_and_b_i(matrices):
ident_n... | The code's main task is to calibrate a robotic system by solving linear equations derived from transformation matrices. It processes calibration data, computes solutions for end-effector and robot-to-tracking system transformations, minimizes errors, and publishes results via a ROS2 publisher node. The process involves... | def main(args=None):
# contains all given matrices in tuples([robot_transformation, tracking_transformation])
lin_equation_parts = []
# contains all solution matrices in tuples([endeffector_to_marker, robot_to_tracking_system])
saved_solution_matrices = []
# for sample in sample_list:
matrices_l... |
def check_move(self, move: Move):
""" Check if a move is valid """
if self.check_remove(move) and self.check_place(move) and self.check_moved_stone(move):
return True # Move is valid
else:
return False
def get_opponent(self):
return (self.player % 2) + 1
def buil... | This function executes a game move by validating it, updating the board state (placing, moving, or removing pieces), adjusting player piece counters, invoking robot control methods, printing the board, and transitioning to the next player or game phase if conditions are met. | def execute_move(self, move: Move):
""" Execute a move """
if self.check_move(move):
if move.place_pos is not None:
board[move.place_pos.x][move.place_pos.y] = self.player # Place piece
self.player_pieces[self.player] -= 1
self.pieces_on_board... |
def move_to_pos_form_board(control, pos):
x_offset = 0
y_offset = 0
if pos.x == 0:
shell_origin = SAFE_POS
current_shell_offset = OFFSET_OUTER_SHELL
elif pos.x == 1:
shell_origin = MIDDLE_SHELL
current_shell_offset = OFFSET_MIDDLE_SHELL
else:
shell_origin = I... | The code's main task is to move a piece from a starting position to an ending position using a robotic arm. It involves initializing ROS2, controlling movement to the start position, activating a vacuum gripper to pick up the piece, moving to the end position, releasing the piece, and returning to a safe position. Key ... | def move_piece(pos_start, pos_end):
rclpy.init()
vacuum = VacuumClient()
control = ControlClient()
# 1. move to start pos
move_to_pos_form_board(control, pos_start)
# 2. pick up piece
vacuum.send_request(1)
lower_to_piece(control, 'board')
# 3. move to end pos
move_to_pos_form_bo... |
def move_to_next_available_storage(game, control):
if game.player == 1:
x_offset = RIGHT_STORAGE_OFFSET[0]
y_offset = RIGHT_STORAGE_OFFSET[1]
current_offset = -STORAGE_OFFSET
else:
x_offset = LEFT_STORAGE_OFFSET[0]
y_offset = LEFT_STORAGE_OFFSET[1]
current_offset ... | The main task of the code is to automate a robotic arm's process of picking up a game piece from storage, moving it to a specified board position, and placing it there. It uses ROS2 clients to control movement and vacuum actions: navigating to storage, picking up the piece, transporting it to the target location, relea... | def place_piece(game, move):
rclpy.init()
vacuum = VacuumClient()
control = ControlClient()
# board_rot = Rot.from_matrix(board_in_rob_coord[:3, :3]).as_quat()
# 1. move to storage pos
move_to_next_available_storage(game, control)
# 2. pick up piece
lower_to_piece(control, 'storage')
... |
def url_from_spec(test_spec: dict) -> str:
"""
Returns a full templated URL from the test spec.
"""
test_config = test_spec.get("config")
base_url = test_config.get("base_url")
url = test_spec.get("url")
if is_relative_url(url):
url = base_url + url
template_vars = test_config.g... | The main task of the code is to convert a YAML test specification into a Request object by extracting parameters like URL, headers, method, and dynamic variables from the test_spec and test_config. It processes headers with variable substitution, resolves dynamic connect-to settings, and constructs a Request instance w... | def request_from_spec(test_spec: dict, test_config: dict) -> Request:
"""
Transform the following YAML spec test into a Request object.
```
url: /
headers:
- "accept-encoding: br"
match:
status: 200
headers:
content-type: text/html
server: openresty
```
... |
def is_dispenser_setup(dispenser):
if len(dispenser.medicine) == 0:
return f'{dispenser.id} is not setup'
return None
def get_dispenser_and_medicine(dispenser_dict, button_clicked):
dispenser_key = button_clicked.title().replace('_', ' ')
dispenser = dispenser_dict.get(dispenser_key, None)
... | The code handles a request to dispense medicine by validating user input, checking dispenser status, and updating records. It retrieves dispenser data, processes form submissions, verifies quantity and setup status, creates dispense records, and renders the dispense page with context including form data, messages, and ... | def dispense(request):
form = DispenseForm(request.POST or None)
dispensers = list(MedicalDispensor.objects.filter(pk__in=[1, 2, 3]))
dispenser_dict = {f'Dispenser {i + 1}': dispenser for i, dispenser in enumerate(dispensers)}
setup_messages = [is_dispenser_setup(dispenser) for dispenser in dispenser_... |
def is_dead(self):
return self.collision_with_walls() or self.achieved_target() or self.collision_with_obstacles()
def achieved_target(self):
return line_intersection([self.starting_point, self.end_point], self.target)
def _get_triangle_points(self):
L = self.r / 6
H = L / 2
sta... | The main task of the code is to draw a line between two points with conditional color changes based on the object's status (dead or target achieved), and render a red triangle using predefined points. It uses two drawing contexts to separate line and shape rendering, likely for visualizing movement paths or status indi... | def draw(self):
x, y = self.starting_point
x_end, y_end = self.end_point
# the body
with new_draw():
strokeWeight(3)
if self.is_dead():
stroke(0, 0, 255)
if self.achieved_target():
stroke(0, 255, 0)
line(x... |
def _prepare_board(self):
"""
Draw layout of the game
"""
self._current_color: int = None
self._current_piece = []
self._falling_speed = self.START_FALLING_SPEED
self._next_color = self._random_color()
self._next_piece = random.choice(self.PIECES)
... | This code runs a Tetris-like game by initializing the board, spawning blocks, handling user input for movement/rotation, controlling block falling speed, checking collisions, and updating the game state. It maintains a game loop that processes input, updates block positions, places blocks when they land, checks for gam... | def run(self):
"""
Run the game
"""
# print borders
self._prepare_board()
self._running = True
# 1.st block
self._spawn_block()
self._create_next_piece()
self._print_block(self._current_piece_pos)
self._listener.start()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.