dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def arming_transition(self):
self.flight_state = States.ARMING
print("arming transition")
self.arm()
self.take_control()
def plan_path(self):
self.flight_state = States.PLANNING
t0 = time.time()
print("Searching for a path ...")
TARGET_ALTITUDE = 5
SAFETY_DISTANCE = 5
self.target_position[2] = TARG... | This function manages state transitions for a drone's flight control system. It checks the current flight state and performs actions like arming, path planning, takeoff, or manual mode transitions based on conditions such as mission status, arming status, and guidance state, ensuring proper sequence execution during au... | def state_callback(self):
if self.in_mission:
if self.flight_state == States.MANUAL:
self.arming_transition()
elif self.flight_state == States.ARMING:
if self.armed:
self.plan_path()
elif self.flight_state == States.PLANNING:
self.takeoff_transition()
elif self.flight_state == States.DISA... |
def arming_transition(self):
self.flight_state = States.ARMING
print("arming transition")
self.arm()
self.take_control()
def plan_path(self):
self.flight_state = States.PLANNING
t0 = time.time()
print("Searching for a path ...")
TARGET_ALTITUDE = 5
SAFETY_DISTANCE = 5
self.target_position[2] = TARG... | The code defines a state callback function that manages flight state transitions for a drone. It checks the current flight state and triggers actions like arming, path planning, takeoff, or manual mode based on conditions such as whether the drone is armed or guided. The function ensures proper progression through miss... | def state_callback(self):
if self.in_mission:
if self.flight_state == States.MANUAL:
self.arming_transition()
elif self.flight_state == States.ARMING:
if self.armed:
self.plan_path()
elif self.flight_state == States.PLANNING:
self.takeoff_transition()
elif self.flight_state == States.DISA... |
def arming_transition(self):
self.flight_state = States.ARMING
print("arming transition")
self.arm()
self.take_control()
def plan_path(self):
self.flight_state = States.PLANNING
t0 = time.time()
print("Searching for a path ...")
TARGET_ALTITUDE = 5
SAFETY_DISTANCE = 5
self.target_position[2] = TAR... | This function manages flight state transitions during a mission. It checks the current flight state and triggers appropriate actions: arming, path planning, takeoff, or manual mode transitions based on conditions like arming status and guided mode. The core task is orchestrating drone operation phases through state-dep... | def state_callback(self):
if self.in_mission:
if self.flight_state == States.MANUAL:
self.arming_transition()
elif self.flight_state == States.ARMING:
if self.armed:
self.plan_path()
elif self.flight_state == States.PLANNING:
self.takeoff_transition()
elif self.flight_state == States.DISA... |
def get_portfolio_volatility(self, action) -> np.float_:
'''Given portfolio daily returns to calculate Volatility
Return:
Volatility of portfolio
'''
# initialization
portfolio_returns = self.get_portfolio_returns(action)
portfolio_returns = np.array(portfoli... | The code defines the 'step' function in an environment, which processes an agent's action by calculating a reward based on negative portfolio volatility, checking if the episode is done, updating the state to the next time step, and returning the new state, reward, done flag, and an empty info dictionary. | def step (self, action):
'''
Core function in environment. Take action as input, and
respond to agent.
Args:
action: np.array
shrinkage intensity
Returns:
state: np.array
reward: float
done: Bool
''' ... |
def send(self, message, send_linefeed=True):
linefeed = self.linefeed if send_linefeed else ""
try:
self.serial.write(f"{message}{linefeed}".encode())
self.serial.flush()
except SerialException as e:
raise ControllerException(f"Failed to send {message} to cont... | This function generates and executes a G-code movement command to move specified machine axes to absolute positions using parameters from the provided waypoint. It constructs a command string with G0 (rapid move), G90 (absolute mode), and G53 (machine coordinates), sends it, waits for confirmation, then returns the res... | def move(self, waypoint):
"""Move specified axis to absolute position.
Commands:
G0: rapid move, move linearly on all axes
G2: clockwise arc move
G3: counter-clockwise arc move
G53: machine coordinate system
G90: Switch to absolution positioni... |
def update_position(self):
# todo: describe behavior
self.send("?", send_linefeed=False)
message = self.receive()
try:
m = self.pos_pattern.search(message).groupdict()
except AttributeError:
raise ControllerException(f"Unexpected output while determining m... | This function performs an incremental relative movement along a specified axis (x, y, or z) using microstepping. It calculates steps based on the motor's microstep size and a given factor, updates the target position, sends a Grbl command with a maximum feed rate (F8000), waits for confirmation, and ensures the motor r... | def jog(self, axis: str, ms_factor: int):
"""Incremental relative movement on given access.
Grbl requires feed rate for every jog, set to max-ish 8000.
Arguments:
axis (str): x, y, or z (see Motor.allowed_axes)
ms_factor (int): Microstep size factor, should be positive ... |
def send(self, message, send_linefeed=True):
linefeed = self.linefeed if send_linefeed else ""
try:
self.serial.write(f"{message}{linefeed}".encode())
self.serial.flush()
except SerialException as e:
raise ControllerException(f"Failed to send {message} to cont... | The code's main task is to reset a device by sending a specific control command (`\x18`), reinitialize the system without establishing a new connection, and then receive a response or data from the device. | def reset(self):
self.send(f"\x18")
self.initialize(connect=False)
self.receive() |
def get_position(self):
return self.latitude, self.longitude
def get_movement_direction(self):
return self.latitude - self.prev_latitude, self.longitude - self.prev_longitude
def update_position(self, latitude, longitude):
self.set_position(latitude, longitude)
# each time we update the... | The main task of the code is to update a car's position based on its current state. If the car is BOOKED and a random condition is met, it generates new coordinates by adding randomized movement to its current position, with error handling to prevent invalid values. If the state is RETURNING, it moves the car toward a ... | def update(self, core_instance):
"""
Main method of the class. It decides when the car changes state and what that state is.
:param core_instance: Instance of the Core class.
"""
if self.state == self.BOOKED and random.choice([True, False]):
latitude, longitude = self... |
def calculate_average_velocity_a(mesh, sol, cons):
A = calculate_cross_section(mesh)
u = calculate_average_velocity(mesh, sol, cons, A)
return u
def calculate_average_velocity_b(mesh, sol, cons):
A = cross_sectional_area(mesh, cons)
u = calculate_average_velocity(mesh, sol, cons, A)
re... | This function calculates a geometry factor (gm) for fluid flow analysis using cross-sectional areas, average velocities, circumference, viscosity, and pressure drop parameters. It computes intermediate values like cross-sectional areas (Ac_a, Ac_b), average velocities (u_a, u_b), and circumference (lc), then applies th... | def geometry_factor(mesh, sol, cons, params):
u_a = calculate_average_velocity_a(mesh, sol, cons)
u_b = calculate_average_velocity_b(mesh, sol, cons)
lc = calculate_circumference(mesh, cons)
Ac_a = calculate_cross_section(mesh)
Ac_b = cross_sectional_area(mesh, cons)
mu = params['viscosity']... |
def check_history(pod, title):
"""See if Pod was already played from recent history."""
try:
PLAYED = pandas.read_csv(BETTERRANDOM_HIST, index_col=0)
except FileNotFoundError:
PLAYED = pandas.DataFrame(columns=["Podcast", "Title"])
return any(PLAYED[-BETTERRANDOM_HISTCOUNT:].isin([pod, t... | The main task of the code is to process a podcast or YouTube playlist by fetching and playing audio/video content based on user-defined parameters (e.g., range of episodes, history checks). It handles local files, YouTube links, and HTTP-based podcasts, using `mpv` for playback, `youtube-dl` for metadata, and history t... | def process_podcast(podchoice):
"""Process Podcast."""
# if --podcast is used we will only process a matching name
pod = podchoice["title"]
url = podchoice["url"]
lastcount = None
firstcount = None
youtubelink = False
print(pod, url)
if "lastcount" in podchoice.keys():
lastco... |
def get_keyword_tweets(self,keyword):
keyword_tweets = []
for i,tweet in enumerate(twitter.TwitterSearchScraper(f"{keyword} since:{self.start_time} until:{self.end_time}").get_items()):
tweet_date = (tweet.date).strftime('%Y-%m-%d %H:%p')
keyword_tweets.append(
... | The main task of the code is to iterate through a list of keywords, search for tweets using each keyword, log the results and errors, and save the tweet data if found. It handles exceptions during search and saving processes, updates timestamps, and maintains a status log with current time, keyword, and result counts. | def initiate_search(self):
for keyword in self.keywords:
try:
keyword_tweets=self.get_keyword_tweets(keyword)
print(f"finding keyword:{keyword} Found :{len(keyword_tweets)}")
self.status_log=self.status_log+"\n"+(f"{CURRENT_TIME} : {ke... |
def getConfig():
hostname = subprocess.check_output(['hostname'], encoding='utf-8').strip()
username = subprocess.check_output(['whoami'], encoding='utf-8').strip()
configName = "/home/" + username + "/Documents/NHNTBerggruen/config/" + hostname + ".yaml"
# configName = "/home/" + username + "/Documents... | The code manages a device communication system by querying audio devices, loading configuration settings, and logging interactions. It alternates between sending and receiving messages based on a predefined mode, using a YAML config to control message exchange counts and group sizes. The system logs all sent/received m... | def main():
# ----------------------------------------
# START
devices = sd.query_devices()
print(devices)
# read the yaml file
config = getConfig()
localMsgCount = 0
totalMsgCount = 0
sendCount = config.get("send_order")
# prevent alsa audio errors
alsaErrorHandling(... |
def getConfig():
username = subprocess.check_output(['hostname'], encoding='utf-8').strip()
configName = "/home/se/Documents/NHNTBerggruen/config/" + username + ".yaml"
# configName = "/home/lauria/Documents/mfadt/research/NHNTBerggruen/config/" + username + ".yaml"
with open(configName, 'r') as file:
... | The main task of the code is to facilitate a send/receive conversation protocol based on a YAML configuration, logging interactions. It initializes settings, handles audio errors, creates timestamps logs, waits for a start command, alternates between sending questions and receiving responses using GGWave protocols, and... | def main():
# read the yaml file
config = getConfig()
# prevent alsa audio errors
alsaErrorHandling()
# create a log file
os.makedirs("/home/se/Documents/NHNTBerggruen/logs/", exist_ok = True)
t = datetime.datetime.now()
filename = "/home/se/Documents/NHNTBerggruen/logs/" + t.strftim... |
def draw_rectangle(self,painter):
# draw black box
painter.setPen(Qt.black)
painter.drawRect(0,0,self.W-1,self.H-1)
painter.setPen(Qt.red)
if self.roi_type=="2d" and self.slice_num==self.roi_z:
painter.drawRect(self.roi_x,self.roi_y,self.roi_w,self.roi_h)
if s... | The code handles the painting event of a Qt widget by initializing a QPainter, drawing a rectangle, a circle (for an initial point), and a label, then finalizing the painter. | def paintEvent(self,event):
super().paintEvent(event)
self.painter=QPainter(self)
self.painter.begin(self)
self.draw_rectangle(self.painter)
# draw circle for initial point
self.draw_circle(self.painter)
# draw label
self.draw_label(self.painter)
s... |
def SVI_adc(iv,x,_m,_sigma):
y = (x-_m)/_sigma
s = max(_sigma,1e-6)
bnd = ((0.00001,-4*s,0),(max(iv.max(),1e-4),4*s,4*s))
z = np.sqrt(np.square(y)+1)
A = np.column_stack([np.ones(len(iv)),y,z])
a,d,c = optimize.lsq_linear(A,iv,bnd,tol=1e-12,verbose=False).x
return... | The code optimizes SVI volatility model parameters to fit implied volatility data while satisfying arbitrage constraints (butterfly, calendar spreads) and envelope conditions. It calculates a weighted sum of squared differences between model-generated volatility and market data, penalizing violations of financial const... | def opt_msigma(msigma,iv,weight,bid,ask,x,par_):
_m,_sigma = msigma
_y = (x-_m)/_sigma
_a,_d,_c = SVI_adc(iv,x,_m,_sigma)
par=[_a,_c/_sigma,_d/_c,_m,_sigma]
vol_SVI = svi_quasi(_y,_a,_d,_c)
consButterfly = butterflyArbitrage(par,x)
consEnvelope = envelopeConditio... |
def gSVI_raw(par, moneyness):
a, b, rho, m, tau = par
SVI = []
for k in moneyness:
svi = svi_raw(par, k)
SVI.append(svi)
return SVI
def butterflyArbitrage(par,moneyness):
a, b, rho, m, tau = par
g = []
for k in moneyness:
gi = gfun(par,k)
g.append(gi)
... | This function computes an optimization objective by calculating the sum of squared weighted discrepancies between model-implied volatility (from gSVI_raw) and market volatility, adjusted by arbitrage constraints (butterflyArbitrage) and envelope conditions (envelopeCondition). It combines these factors into a loss func... | def globalOptimization(X, volMarket,weight,bid,ask,moneyness):
vol_SVI = gSVI_raw(X, moneyness)
consButterfly = butterflyArbitrage(X, moneyness)
consEnvelope = envelopeCondition(vol_SVI, bid, ask,10)
OF = np.array([(vol/volMar - 1)*bi*ei*w for vol,volMar,bi,ei,w
in zip(vol_SVI, volM... |
def remove_from_pool(self,transactions_list):
seen = set()
for t in transactions_list:
seen.add(t.make_hash().hexdigest())
temp_pool = []
for t in self.transaction_pool:
if t.make_hash().hexdigest() not in seen:
temp_pool.append(t)
self.transaction_pool = temp_pool
def process_transaction(... | The main task of the code is to validate a received block against the last block in the chain, process its transactions by updating the transaction pool, resolving duplicates, and executing transactions. If valid, the block is appended to the blockchain, and the mining timestamp is updated. If validation fails, conflic... | def receive_block(self):
last_block = self.chain[-1]
block = self.new_block
validated = block.validate_block(last_block,self.difficulty)
if validated == 0:
#put unmined transactions back to pool
print("validated")
self.curr_block.listOfTransactions.reverse() #must be placed back with the orde... |
def mine_block(self):
#mine the current block
nonce = 0
prefix = '0'*self.difficulty
solved = False
while not self.block_received:
self.curr_block.set_nonce(nonce)
h = self.curr_block.make_hash()
if h.startswith(prefix):
solved = True
print("Block mined: ",h)
break
# nonce = random.... | The code's main task is to continuously mine blocks when the current block reaches capacity, handle incoming transactions, and process newly received blocks. It maintains the blockchain by appending mined blocks, updating UTXOs, and creating new blocks after each addition. The loop ensures persistent mining, transactio... | def mining_loop(self):
# self.create_new_block(self.chain[-1])
while True:
if not self.block_received:
if len(self.curr_block.listOfTransactions) == self.capacity:
print("DAEMON:starting mining..")
res = self.mine_block()
if res == 0:
self.chain.append(self.curr_block)
... |
def build_frequency_dict(text: bytes) -> dict[int, int]:
"""
Return a dictionary which maps each of the bytes in <text> to its
frequency.
>>> d = build_frequency_dict(bytes([65, 66, 67, 66]))
>>> d == {65: 1, 66: 2, 67: 1}
True
>>> d1 = build_frequency_dict(bytes([65, 66, 67, 66, 67, 67, 67... | The function `compress_file` compresses the contents of an input file using Huffman coding. It reads the input file's binary data, constructs a frequency dictionary, builds a Huffman tree, generates binary codes for each symbol, and calculates the average bits per symbol. The compressed data, along with the Huffman tre... | def compress_file(in_file: str, out_file: str) -> None:
"""
Compress contents of the file <in_file> and store results in <out_file>.
Both <in_file> and <out_file> are string objects representing the names of
the input and output files.
Precondition: The contents of the file <in_file> are not empty.... |
def vec_format_standardization(
vec: Union[list, np.ndarray], std_type: Optional[str] = 'list'
) -> Union[list, np.ndarray]:
assert type(vec) == list or type(vec) == np.ndarray
assert std_type == 'list' or std_type == '1darray'
if std_type == list:
if type(vec) == np.ndarray:
vec_s... | This function computes the exponential map from the se(3) Lie algebra to the SE(3) group, generating a 4×4 homogeneous transformation matrix. Given a screw axis (6D vector) and scalar θ, it constructs the transformation by handling two cases: (1) pure rotation (unit ω) using Rodrigues' formula, and (2) pure translation... | def exp_se3(screw_axes, theta) -> np.ndarray:
S = vec_format_standardization(screw_axes)
assert len(S) == 6
omega = np.array([S[0], S[1], S[2]])
v = np.array([S[3], S[4], S[5]])
exp_se3 = np.zeros((4, 4))
if np.linalg.norm(omega) == 1:
omega_ss = vec2so3(omega)
exp_omega =... |
def get_html_obj(self):
if self.html_obj is None:
html_str = self.get()
self.html_obj = BeautifulSoup(html_str, "html.parser")
return self.html_obj
def extract_element_text(self, tag, **kwargs):
html_obj = self.get_html_obj()
el = html_obj.find(tag, kwargs)
... | The code's main task is to scrape specific data elements from a webpage's HTML. If `fetch_products` is False, it extracts DKP text, product price, and title using CSS selectors and returns them in a dictionary. If `fetch_products` is True, it retrieves a list of products. The method conditionally processes HTML element... | def perform_scrape(self):
html_obj = self.get_html_obj()
if not self.fetch_products:
dkp = self.extract_element_text("span", **{"class": "text-caption color-400"})
dkp = dkp.strip() if dkp is not None else None
price_str = self._perform_price_sel... |
def maybe_convert_to_torch(x, y):
if not isinstance(x, Tensor):
x = torch.from_numpy(x)
if not isinstance(y, Tensor):
y = torch.from_numpy(y)
return x, y
def linear_cka_distance(x: Tensor, y: Tensor, reduce_bias: bool) -> Tensor:
"""Linear CKA used in Kornblith et al. 19
Args:
... | The function `compute_similarity` calculates the similarity between two tensors `x` and `y` using a specified method (`sim_name`). It converts inputs to PyTorch tensors, selects a similarity metric (e.g., CKA, SVCCA, PWCCA, CCA), computes the distance or similarity score, and returns `1 - res` as the final similarity v... | def compute_similarity(x: Tensor, y: Tensor, sim_name: str):
x, y = maybe_convert_to_torch(x, y)
if "cka" in sim_name:
res = linear_cka_distance(x, y, False)
elif "svcca" in sim_name:
accept_rate = float(sim_name.split("_")[1])
res = svcca_distance(x, y, accept_rate=accept_rate, bac... |
def set_high(pin):
gpio.output(pin, gpio.HIGH)
def send(byte):
bits = byte_to_bits(byte)
set_low(namedPins["EN"])
set_line(bits[0:4])
set_high(namedPins["EN"])
time.sleep(TIME_TO_DELAY)
set_low(namedPins["EN"])
set_line(bits[4:8])
set_high(namedPins["EN"])
time.sleep(TIME_TO_DELA... | The code defines a function `send_command` that sends a given command to a device by first setting the `RS` pin to high, transmitting the command, and then resetting the `RS` pin to low. This sequence is typically used in hardware communication protocols, such as with LCD displays, to signal the start and end of a comm... | def send_command(command):
set_high(namedPins["RS"])
send(command)
set_low(namedPins["RS"]) |
def readInFile(filename):
with open(filename) as f:
datapts = []
for line in f:
datapts.append(list(map(float, line.split(" "))))
return datapts
def kStartingPoints(k, datapts, tight, loose):
centers, canopies = canopyAlgo(datapts, tight, loose)
newTight = tight
newLoose ... | The function `runExperiment` executes a K-means clustering experiment by reading data, initializing cluster centers using canopy-based selection, running K-means with specified iterations, calculating clustering error, and logging timing/error metrics to an output file. It optionally plots results. | def runExperiment(filename, k, tight, loose, iterations, outputFile, plotPts=False):
#READ IN THE DATA POINTS
datapts = readInFile(filename)
#FIND STARTING POINTS
start = time.time()
centers, startCanopy = kStartingPoints(k, datapts, tight, loose)
clusterTime = time.time() - start
... |
def returnEdges(self):
mat = self.return2DFaces()
edgelist = []
top_ind = [(2,1,2),(1,0,1),(0,1,3),(1,2,4)]
mid_ind = [(2,1),(1,3),(3,4),(4,2)]
bottom_ind = [(0,1,2),(1,2,4),(2,1,3),(1,0,1)]
#white series clockwise, viewed from top: green to red
for ind in top_ind:
edgelist.append([ mat[0][ind[0]][i... | The main task of the code is to update a 3D cube's faces using input data, process each piece to fill null faces, refresh edge and corner lists, and validate the cube's structure. It iterates through faces, applies updates to the cube's slices, ensures all pieces have valid faces, and checks the cube's integrity before... | def updateCube(self,faces):
for key in faces.keys():
for i in range(3):
for j in range(3):
self.cube[self.slices[key]][i, j].addFace(key, faces[key][i, j])
for layer in self.cube:
for row in layer:
for piece in row:
piece.fillNullFaces()
self.edgelist = self.returnEdges()
self.cornerlis... |
def getWhiteEdges(self):
edges = self.edgelist
WhiteEdges = []
layer1 = []
layer2 = []
layer3 = []
for i in range(len(edges)):
edge = edges[i]
if 5 in edge:
WhiteEdges.append([edge,i])
if i>7:
layer1.append([edge,i])
... | This function solves the middle layer cross of a Rubik's cube by rotating edge pieces into their correct positions. It uses predefined rotations and position mappings to align colors, checks for matches after each rotation, and applies the correct move. If a match is found, it executes the rotation and recursively call... | def solveCrossLayer2(self):
#slots all pieces in the mid layer into corresponding positions of the cross
index = [(0,4),(1,4),(0,5),(1,5),(0,6),(1,6),(0,7),(1,7)]
rotations = [lambda x:x.L(), lambda x:x.Fi(),\
lambda x:x.B(), lambda x:x.Li(),\
lambda x:x.R(), lambda x:x.Bi(),\
lam... |
def getMidEdges(self):
edges = self.edgelist
middle = []
top = []
for i in range(len(edges)):
edge = edges[i]
if (5 not in edge) and (0 not in edge):
if i>3:
middle.append([edge,i])
else:
top.... | The code executes Layer 2 solving by first running Layer 1 solver, then iteratively processing mid-edges until the last mid-edge value reaches 4. It repeatedly slots and pushes mid-edges in a loop, breaks when condition met, then compresses the algorithm for optimization. The main task is solving a puzzle's second laye... | def runLayer2Solver(self):
self.runLayer1Solver()
while True:
crct = self.getMidEdges()[-1]
if crct==4:
break
self.slotMidEdges(None)
self.pushMidEdges()
self.compressAlgo()
return |
def getWhiteEdges(self):
edges = self.edgelist
WhiteEdges = []
layer1 = []
layer2 = []
layer3 = []
for i in range(len(edges)):
edge = edges[i]
if 5 in edge:
WhiteEdges.append([edge,i])
if i>7:
layer1.append([edge,i])
... | This code solves the cross in the third layer of a Rubik's cube by positioning white edge pieces into their correct locations. It checks for the target position of each piece, applies necessary rotations (F, L, B, R), and adjusts the cube state. If a piece is in the top layer, it ensures proper alignment through double... | def solveCrossLayer3(self):
#tries to directly slot pieces in top into the cross. if not possible, pushes them to middle layer
layer3 = self.getWhiteEdges()[3]
if len(layer3) == 0:
return
index = [0,1,2,3]
rotations = [lambda x:x.F(), lambda x:x.L(), lambda x:x.B(), lambda x:x.R()]
positions = [(1,1), (1... |
def getWhiteEdges(self):
edges = self.edgelist
WhiteEdges = []
layer1 = []
layer2 = []
layer3 = []
for i in range(len(edges)):
edge = edges[i]
if 5 in edge:
WhiteEdges.append([edge,i])
if i>7:
layer1.append([edge,i])
... | This code solves the cross of a Rubik's cube by iteratively checking and resolving white edge pieces in three layers. It loops until all four white edges are correctly placed (crct == 4), applying layer-specific solving methods for layers 1, 2, and 3. After completing the cross, it compresses the algorithm for optimiza... | def runCrossSolver(self):
while True:
WhiteEdges,layer1,layer2,layer3,crct = self.getWhiteEdges()
if crct == 4:
break
if len(layer1)>crct:
self.solveCrossLayer1()
#print("in layer1")
if len(layer2) > 0:
self.solveCrossLayer2()
#print("in layer3... |
def stop(self) -> None:
self.state = State.Stopped
self._player.stop()
self.track_list = []
self.track = Track()
self.track_index = -1
def play_by_index(self, index: int) -> None:
if index < len(self.track_list) and index >= (0 - len(self.track_list)):
self.tr... | This function handles the end-of-file event in a media player. It checks the current playback state and mode to decide whether to stop playback, repeat the current track, or transition to the next track, ensuring compliance with the player's configured behavior for track progression and repetition. | def on_end_file(self, event: mpv.MpvEvent) -> None:
if self.state == State.Playing and self._player.idle_active:
if self.mode == Mode.SingleTrack or self.track.type == TrackType.Direct:
self.stop()
elif self.mode == Mode.RepeatTrack:
self.play_by_index(sel... |
def save_data(self):
with open(self.filename, "wb") as handle:
pickle.dump(self.data, handle, protocol=pickle.HIGHEST_PROTOCOL)
def reset(self, seed=None):
if self.data is None:
self.data = []
else:
self.plot_data(self.counter)
self.counter += 1
... | This code handles keyboard inputs to control an environment. It maps specific keys to actions (e.g., movement, interaction) and triggers corresponding methods. Pressing "escape" saves data and exits, while "backspace" resets the environment. Other keys execute predefined actions via a dictionary mapping, with unknown k... | def key_handler(self, event):
key: str = event.key
print("pressed", key)
if key == "escape":
self.save_data()
self.env.close()
self.closed = True
return
if key == "backspace":
self.reset()
return
key_to_act... |
def print_all_package_status_and_total_mileage():
print("Cumulative Mileage of Trucks: ",
truck1.total_distance_travelled + truck2.total_distance_travelled + truck3.total_distance_travelled, "miles")
for i in range(1, 41): # Assuming package IDs are 1 through 40
package = hash_table.lookup(i)... | This code presents a menu-driven interface for a package tracking system, allowing users to print all package statuses and mileage, check individual or all package statuses at a specific time, or exit the program. It validates user input and handles errors, looping until the exit option is selected. | def main_menu():
while True:
print("\n***************************************")
print("1. Print All Package Status and Total Mileage")
print("2. Get a Single Package Status with a Time")
print("3. Get All Package Status with a Time")
print("4. Exit the Program")
print... |
def update_thresh_slope():
global past_lines
global thresh_slope
for key in ['r','l']:
temp_slope = 0
for lines in past_lines[key]:
temp_slope += slope(lines)
thresh_slope[key] = temp_slope/len(past_lines[key])
def find_leftmost_line(lines):
try:
leftmost_line... | The code processes left (l) and right (r) lane lines by maintaining a history of past 20 lines, updating slope thresholds, filtering lines based on gradient similarity to these thresholds, and returning filtered lines for further processing. It ensures only lines with slopes within ±5 degrees of the threshold are retai... | def valid(frame_no, lines):
global past_lines
r,l = lines
if len(past_lines['r']) == 20:
if len(r) > 0:
past_lines['r'].pop(0)
past_lines['r'].append(r[0])
else:
past_lines['r'].pop(0)
past_lines['r'].append(r)
if len(past_lines['l']) == 20... |
def inverse_perspective(image):
points = np.float32([(40,320),(0,480),(600,320),(640,480)])
transformed_points = np.float32([[0,0],[0,480],[640,0],[640,480]])
matrix = cv2.getPerspectiveTransform(points,transformed_points)
image = cv2.warpPerspective(image,matrix,(640,480))
return image
def apply_th... | The main task of the code is to preprocess an image by resizing, converting to grayscale, applying Gaussian blur, performing inverse perspective transformation, thresholding to detect lines, and filtering valid lines based on frame number for further analysis. | def preprocess(frame,frame_no):
frame = cv2.resize(frame,(640,480))
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gaus = cv2.GaussianBlur(gray, (5,5),1.5)
inv_gaus = inverse_perspective(gaus)
colors = [[255, 0, 0],[ 255, 127, 0],[255, 255, 0],[ 0, 255, 0],[ 0, 0, 255],[46, 43, 95],[139, 0, 255]]
... |
def calculate_local_utilities(self, dataset: Dataset) -> None:
"""Calculates the local utilities of all items in the dataset by using utility-bin array."""
self._utility_bin_array_LU = {}
for transaction in dataset.transactions:
for item in transaction.items:
if item ... | The code executes the EFIM algorithm for high-utility itemset mining. It processes a dataset, iteratively calculates local and subtree utilities, filters promising items, renames them, sorts transactions, removes empty ones, and recursively searches for high-utility itemsets using a utility-bin array approach. The algo... | def run(self) -> None:
"""Starts the EFIM algorithm."""
self._start_time = time.time()
self._dataset = Dataset(self.input_file, self.sep)
self.logger.info(f"Items int to str: {sorted(self._dataset.int_to_str.items())}")
# Do steps 2-5 of Algorithm 1 in loop
len_promising... |
def parse_lg(lg):
sym = []
for lg_line in lg:
# Remove whitespace and split by ","
lg_line = lg_line.replace(" ", "").split(',')
if lg_line[0] != "O":
continue
# Select symbol id and associated stroke id (only integers, we remove the letters)
sym.append([lg_l... | The code generates images from hypothetical linguistic symbols by extracting selected strokes from inkml traces, converting each into a dim x dim image, and compiling them into a numpy array for further processing or analysis. | def gen_img_from_lg_hypotheses(inkmltraces, lg, dim):
if type(lg) == str:
lg = lg.split("\n")
# Get list of stroke ids selected for each hypothetical symbol in lg
sym_list = parse_lg(lg)
# Get traces belonging to each hypothetical symbol in sym_list
traces_sel_list = get_strokes_from_lg(ink... |
def check_query(query):
"""This function check query style"""
if "." not in query or ":" not in query:
print_mal_query()
return 0
return 1
def print_no_conj():
"""This function print no conjunction error"""
print("The logic operator is not in conjunction with key words")
def get_db()... | This function processes a query by splitting it using a keyword, validates the resulting parts, retrieves a database collection, and performs a search using a specified logic operator with the split query components as values. | def logic_operator(keyword, query, logic):
"""This function return logic results"""
query_list = re.split(keyword, query)
query_1 = query_list[0]
query_2 = query_list[1]
if check_query(query_1) is 0 or check_query(query_2) is 0:
print_no_conj()
exist_db = get_db()
collection_name = q... |
def call_api_get(get_url):
response = requests.get("http://127.0.0.1:5000/" + get_url)
print_response_status(response, "get")
def call_api_put(put_url):
response = requests.put("http://127.0.0.1:5000/" + put_url)
print_response_status(response, "put")
def call_api_post(post_url):
file = open("data.j... | The main task of the code is to parse command-line arguments using argparse, handle options like URL, JSON file, HTTP methods (GET/PUT/POST/DELETE), and execute corresponding functions (e.g., API calls, URL validation, data export). It processes inputs to trigger specific actions based on user-provided flags, returning... | def parsing():
"""This function add and parse the command"""
parser = argparse.ArgumentParser()
parser.add_argument('-url', action='store', type=str, help='the url to search for')
parser.add_argument('-js', action='store', type=str, help='the json file to read from')
parser.add_argument('-s', action... |
def _countdown(self):
"""complete timer"""
if self.tick:
self.text_entry.config(state="normal")
if self.t != -1:
self._update_timer()
self.t -= 1
time.sleep(1)
self.window.update()
self._countdown()
d... | The main task of the code is to initialize and start a typing test by clearing feedback, initiating a countdown, comparing typed text against the correct input, and resetting the test after completion. It manages the test lifecycle, ensuring the interface updates dynamically during the process. | def _start_test(self):
"""start typing test"""
#clear any initial feedback
self.feedback_textbox.delete(1.0, END)
self.tick = True
self._countdown()
if self.tick:
self._compare_typed_text()
self._reset_test()
self.window.update() |
def get_storcli_json(storcli_args):
"""Get storcli output in JSON format."""
# Check if storcli is installed and executable
if not (os.path.isfile(storcli_path) and os.access(storcli_path, os.X_OK)):
SystemExit(1)
storcli_cmd = shlex.split(storcli_path + ' ' + storcli_args)
proc = subprocess... | The main task of the code is to retrieve and process storage controller information using the StorCLI tool. It collects data from all controllers, processes common details with `handle_common_controller`, and applies driver-specific handling for 'megaraid_sas' or 'mpt3sas' controllers. Finally, it outputs collected met... | def main(args):
""" main """
global storcli_path
storcli_path = args.storcli_path
data = get_storcli_json('/cALL show all J')
try:
# All the information is collected underneath the Controllers key
data = data['Controllers']
for controller in data:
response = con... |
def error(self):
max_value = self.minimize()
h, k = 0, 0
null_indexes = self.search_null()
for index in null_indexes:
i, j = index
tmp = self.min_in_row(i, j) + self.min_in_col(j, i)
if tmp >= max_value:
h, k = i, j
max_... | This function determines the conditions of an error and a selected element in a matrix. It copies the matrix, introduces an error by setting a value to infinity, records the error state, restores the matrix, reduces it, and finds the minimum weight. It then adjusts indices based on the error state and returns the error... | def get_condition(self):
selected_matrix = self.array.copy()
i, j, error_weight = self.error()
self.array[i][j] = np.inf
error_cond = (self.array.copy(), self.numbers_rows.copy(), self.numbers_cols.copy())
self.array = selected_matrix
self.reduce(i, j)
selected_... |
def minimize(self):
return self.minimize_rows() + self.minimize_cols()
def get_condition(self):
selected_matrix = self.array.copy()
i, j, error_weight = self.error()
self.array[i][j] = np.inf
error_cond = (self.array.copy(), self.numbers_rows.copy(), self.numbers_cols.copy())
... | The code constructs a decision tree by iteratively adding conditions and updating parameters. It builds the tree structure, adjusts node depths with error/selected weights, and updates data arrays until the dataset size is ≤2. Finally, it retrieves the solution path using `get_way` with tracing enabled if specified. | def solve(self, tracing=False):
tree = DecisionTree(self.minimize())
node = tree.cur_node()
while True:
cond, error_weight, selected_weight = self.get_condition()
tree.add_depth_for_node(node, cond=cond, weight0=error_weight, weight1=selected_weight)
node = tr... |
def drawScreen(self, screen, *args): # calls all the functions necessary to draw/redraw the screen
screen.fill(pg.Color("white"))
try:
self.drawBoard(screen, list(map(lambda a: a.end, args[0])), args[1])
except IndexError:
self.drawBoard(screen)
self.drawPieces(s... | This function handles user input events in a board game, primarily processing mouse clicks for piece selection/movement and keyboard inputs for undo/redo. It validates moves, updates the game state, detects check/checkmate/stalemate conditions, and redraws the screen accordingly. The core task is enabling player intera... | def registerEvent(self, selected, event, screen):
# Check for QUIT event
if event.type == pg.QUIT:
running = False
elif event.type == pg.MOUSEBUTTONDOWN:
if event.button == 3:
selected = None
self.drawScreen(screen)
return
... |
def _send_pass_(self, password):
self._send_cmd_(Command.PASSWORD, password)
def _send_nick_(self, nick):
self._send_cmd_(Command.NICK, nick)
def _send_user_(self, username, hostname, servername, realname):
self._send_cmd_(Command.USER, f"{username} {hostname} {servername} {realname}") | The code initializes a socket connection to a server, authenticates using a password, sets a nickname, and sends user details. It then starts two background threads: one for periodic pings and another for continuous loop operations, likely handling communication or maintaining the connection. | def start(self):
self.s = socket.socket()
self.s.connect((self.address, self.port))
self._send_pass_(self.password)
self._send_nick_(self.nick)
self._send_user_(self.userData.username, self.userData.hostname, self.userData.servername, self.userData.realname)
Thread(targe... |
def create_game():
return [0] * 9
def determine_result(state):
if has_won(state, Player.One):
return Result.PlayerOneWon
elif has_won(state, Player.Two):
return Result.PlayerTwoWon
elif is_board_full(state):
return Result.Draw
else:
return None
def position_to_index(p... | The code simulates a turn-based game where players alternate making moves based on their chosen strategy. It tracks the game history, updates the state after each move, and checks for a result (win/draw) after each turn. The loop continues until a result is determined, then returns the game history, final state, and ou... | def play_game(choose):
player = Player.One
history = []
state = create_game()
result = determine_result(state)
while result is None:
position = choose[int(player) - 1](history, state)
index = position_to_index(position)
history.append(index)
state = place(state, posit... |
def remove_piece(self, row, col):
'''
Removes the piece from a board cell given its row/column coordinates.
Parameters
----------
row : int
Row number of the board cell.
col : int
Column number of the board cell.
'''
self.board_gri... | The main task of the code is to move a double stone (tower) by splitting it into two parts and placing one stone each in two adjacent cells on the game board. It removes the original tower, checks target cells for compatibility, creates new single stones or merges with existing ones of the same color, and updates the b... | def move_tower(self, piece, next_row_1, next_col_1, next_row_2, next_col_2):
"""
Distributes a double stone (tower) over the next and upper next cells of the game board.
Parameters
----------
piece : Piece
Game piece/stone to move.
next_row_1 : int
... |
def get_piece(self, row, col):
"""
Retrieves the piece from a board cell given its row/column coordinates.
Parameters
----------
row : int
Row number of the board cell.
col : int
Column number of the board cell.
Returns
-------
... | The function sacrifices a tower (double stone) by converting it into a wall (single stone) to remove an opponent's wall on the next cell. It reduces the tower's stack size, removes the opponent's piece, and updates player-specific counts for towers and walls. Errors are raised if the target isn't a valid piece or the c... | def sacrifice_tower(self, piece, next_row_1, next_col_1):
"""
Sacrifices a double stone (tower) to remove a simple one (wall) of the opponent on the next cell.
Parameters
----------
piece : Piece
Game piece/stone to move.
next_row_1 : int
Row numb... |
def flipCardsInHand(self, hand):
for i in range(len(hand.getHand())):
hand.getHand()[i] = hand.getHand()[i].flipCard()
def nextTurn(self):
if self._board.getNumFaceUp() == 3:
self.theTurn() # the Turn
elif self._board.getNumFaceUp() == 4:
self.theRiver()
def ... | This code runs a game loop for a poker-like game, handling user input (keyboard events) for actions like quitting, raising bets, checking, folding, and restarting. It updates game state variables, processes win conditions, manages pot amounts, and renders game elements (text, cards) on the screen using Pygame. The core... | def run(self):
# Game loop
while True:
for event in pygame.event.get():
# Stops game!
if event.type == QUIT:
return
if event.type == pygame.KEYDOWN:
# ESCAPE Key Pressed - Stops game!
... |
def _royalFlush(self, allCards):
# Dictionaries {key, value}
# Ex: {1: 1, 13: 1, 12: 1, 11: 1, 10: 1}
temp = dict()
# Adds each card numeric value in the temp dict
# The int value in the key-value pair is how we determine the royal flush
for card in allCards:
... | The main task of the code is to evaluate a poker hand's strength by checking for specific combinations (e.g., royal flush, straight, pairs) using cards from both the board and the player's hand. It returns a numerical score (1–10) corresponding to the highest-ranking combination found, with 10 for the strongest (royal ... | def _checkHand(self, board, hand):
# Sets cannot have repeated items
allCards = set()
# Adds all card options from board and hand
for i in range(len(board.getHand())):
allCards.add(board.getHand()[i])
for i in range(len(hand.getHand())):
allCards.add(han... |
def save_asset(asset, asset_api_id, type):
try:
if type == 'crypto':
api_url = get_api_coingecko(asset_api_id, 'usd')
raw = requests.get(api_url)
data = format_coingecko(raw.json())
elif type == 'equity':
api_url = get_api_vantage(asset_api_id)
... | The code reads a portfolio from an input source, iterates through each asset to extract its API ID and type, then saves the asset details and metadata using two separate functions. Finally, it saves market-related data. The main task is to process and store portfolio asset information along with metadata and market dat... | def process_json():
portfolio = IO.read_portfolio()
for asset in portfolio:
asset_data = portfolio[asset]
save_asset(asset, asset_data['api_id'], asset_data['type'])
save_asset_metadata(asset, asset_data['api_id'])
save_market() |
def initialize_session_state():
if 'chat_history' not in st.session_state:
st.session_state['chat_history'] = []
if 'generated' not in st.session_state:
st.session_state['generated'] = ["Hello! Ask me anything about 🤗"]
if 'past' not in st.session_state:
st.session_state['past'] =... | The main task of the code is to create a Streamlit-based RAG (Retrieval-Augmented Generation) chatbot that allows users to upload documents, select a model (e.g., Llama 2, OpenAI), and interactively query the chatbot. The system processes uploaded files, splits them into chunks, generates embeddings, builds a FAISS vec... | def main():
#load_dotenv()
# Initialize session state
initialize_session_state()
st.title("Multi-Docs RAGs ChatBot :books:")
# Initialize Streamlit
st.sidebar.title("Document Processing")
uploaded_files = st.sidebar.file_uploader("Upload files", accept_multiple_files=True)
select_model=s... |
def playable(self, row, col):
# Returns True if and only if there is no tile currently at (row, col)
return self.board[row][col] == EMPTY
def add_tile(self, row, col):
# add a tile to the board, and prevent invalid tiles from being clicked on in the future
self.board[row][col] = self.turn
self.board[row][col... | The function `new_move` validates a move at specified coordinates, adds the tile to the board if legal, switches the current player, and updates the score. It raises an error for invalid moves, printing debug info. | def new_move(self, row, col):
if not self.playable(row, col):
print('uh oh', row, col)
print(self.board)
print('legal', [x for x in self.legal_moves if self.legal_moves[x]==1])
raise ValueError('ILLEGAL MOVE')
# add the tile to the board
self.add_tile(row, col)
# switch the current player
self.... |
def build_head(self,token: Token):
if token.level == 1:
return f"\\part{{{token.contents}}}"
elif token.level == 2:
return f"\\section{{{token.contents}}}"
elif token.level == 3:
return f"\\subsection{{{token.contents}}}"
elif token.level == 4:
... | The main task of the code is to convert a list of tokens into LaTeX-formatted text by processing each token according to its type. It iterates through the tokens, delegates each to a specific builder method (e.g., headings, paragraphs, code blocks), collects the generated LaTeX fragments into a list, and finally joins ... | def build_latex(self,tokens: list[Token]):
contents_tree = []
for token in tokens:
if token.type == TokenTypes.TYPE_HEAD:
contents_tree.append(self.build_head(token))
elif token.type == TokenTypes.TYPE_PARAGRAPH:
contents_tree.append(self.build_par... |
def get_coin_price_data(soup, coin_name):
"""
Get price data (today, yesterday, history)
:param soup: soup html
:param coin_name: name of coin
:return: nothing
"""
logging.info('Coin price processing begins...')
# Get all divs that contain coin statistics
coin_data[conf.table_key.co... | The main task of the code is to scrape cryptocurrency information from a website, including price data, summaries, and historical details, then update SQL database tables with the collected data. It also retrieves Google search results for the coin and logs errors if connectivity issues occur. | def get_coin_info(coin_name):
"""
Scrap all the information of a crypto coin
:param coin_name: the name of the coin out of the following list:
'bitcoin', 'ethereum', 'tether', 'binance-coin', 'cardano', 'dogecoin', 'xrp', 'usd-coin',
'polkadot-new', 'uniswap', 'litecoin', 'solana', 'theta'
:retu... |
def Heuristic_To_Meta(data):
heuristic_sol=SolverHeuristic(data)[str_cars]
matched=[-1]*data[str_n]
for pool in heuristic_sol:
driver=pool[0]-1
for passenger in pool:
matched[passenger-1]=driver
return matched
def fitness_function(n,max_distance,matched,max_pay,min_passenger_... | The code implements a genetic algorithm to solve an optimization problem, likely vehicle routing or scheduling. It initializes a population with heuristic solutions, evolves them through selection, crossover, and mutation over generations, and returns the best solution's metrics, including cost, configuration, and runt... | def genatic_algorithm(data):
start_time = time.time()
n=data[str_n]
max_distance=data[str_dis]
max_pay=data[str_pay]
min_passenger_fare=data[str_fare]
min_passengers=data[str_min_cap]
capacity=data[str_cap]
locations=data[str_location]
dist=np.linalg.norm(np.array(locations)[:, None]... |
def ReadTestSet(test_set):
testFiles = [join(test_set, f) for f in listdir(test_set) if isfile(join(test_set, f))]
testFiles.sort(reverse=False, key=sortFile)
return testFiles
def ReadTextFile(testFile):
print("Reading test file: {0}".format(testFile))
with open(testFile) as f:
# add n, m to... | The main task of the code is to process a set of test files by applying four different solving methods (MIP, Heuristic, DP, Meta-Heuristic) to each test case. It iterates through the test files, reads each case, computes solutions using the respective solvers, and prepares a summary (though it remains incomplete). The ... | def main_testfile(test_set):
testFiles = iter(ReadTestSet(test_set))
testFile=next(testFiles, None)
summary=[]
while testFile != None:
# get current test file path
testFile_parent = testFile.split("/")[0]+'_output'
testFile_name = testFile.split("/")[-1]
testFile_name = t... |
def plottingTime(name: str, filePath: str, fileNames: str, clusterName: str):
capitalName = name.capitalize()
clusterName = clusterName.capitalize()
plt.figure(figsize=(16, 9))
plt.xticks(fontsize=14, rotation=0)
plt.tick_params(axis='x', which='both', direction='in', length=8, width=1.5)
plt.yticks(fontsize=14)... | This function identifies and processes text files in a specified directory that match a cluster name pattern. It generates three types of plots (time, speedup, bandwidth) using data from these files. The function validates file existence, extracts relevant filenames, and sequentially calls plotting functions to visuali... | def plot_all(filePath: str, name: str, clusterName: str):
startSequence = clusterName
endSequence = ".txt"
matchingFiles = []
for fullFilename in glob.glob(os.path.join(filePath, "*")):
fileName = os.path.basename(fullFilename)
if re.match(f"{startSequence}.*{endSequence}$", fileName):
matchingFiles.a... |
def initialization(self, Xc, Xe, Y, w=1.):
'''
Initialization of parameters for both classification and propensity models before running EM algorithm. The parameters of each models are initialized following their respective method: see `initialization` methods for `cmodel` and `emodel`.
... | This function implements the Expectation-Maximization (EM) algorithm to iteratively fit a probabilistic model by alternating between computing expected values (E-step) and maximizing parameters (M-step). It updates model parameters until the change in log-likelihood falls below a tolerance threshold or reaches a maximu... | def _fit(self, Xc, Xe, Y, w=1., tol=1e-6, max_iter=1e4, warm_start=False, balance=False):
if not warm_start:
self.initialization(Xc, Xe, Y, Y, w)
it = 0
delta = 1
last_ll = self.loglikelihood(Xc, Xe, Y, w)
warm_start = False
while abs(delta) > tol and it < max... |
def initialization(self, Xc, Xe, Y, w=1.):
'''
Initialization of parameters for both classification and propensity models before running EM algorithm. The parameters of each models are initialized following their respective method: see `initialization` methods for `cmodel` and `emodel`.
... | The code estimates parameters of a PU learning model (classifier and propensity) using an EM algorithm. It performs multiple random initializations, trains each for a limited iteration, and selects the one with the highest log-likelihood. The optimal parameters are then refined until convergence, using weighted data an... | def fit(self, Xc, Xe, Y, w=1., tol=1e-6, max_iter=1e4, warm_start=False, balance=False, n_init=20, iter_init=20):
'''
Estimation of PU learning model parameters (classifier and propensity) through EM algorithm. Multiple random initialization are considered and trained over a few iterations. Then, only t... |
def aggregate_data_by_district(
assignments: List[Assignment],
data: Dict[str, Dict[str, str | int]],
n_districts: int,
n_counties: int,
county_to_index: Dict[str, int],
district_to_index: Dict[int | str, int],
) -> Dict[str, Any]:
"""Aggregate census & election data by district."""
tot... | The function analyzes a district plan by aggregating data and shapes, calculating metrics like population deviation, partisan fairness, minority opportunity, compactness, and splitting. It compiles these into a scorecard, rates dimensions (e.g., proportionality, competitiveness), and trims precision, returning a compre... | def analyze_plan(
assignments: List[Assignment],
data: Dict[str, Dict[str, str | int]],
shapes: Dict[str, Any],
graph: Dict[str, List[str]],
metadata: Dict[str, Any],
alt_minority: bool = False, # If True, add an alternative minority opportunity rating
) -> Dict[str, Any]:
"""Analyze a plan... |
def _train_step(
self,
batch_idx,
batch,
loss_func,
optimizer,
scaler,
batch_size,
acc_steps,
):
with torch.cuda.amp.autocast(enabled=self.mixed_prec):
if len(batch) == 2:
inp, tar = batch
inp = inp.t... | This function trains a neural network model on provided training data while validating on validation data, handling checkpointing, mixed-precision training, and logging metrics like loss, OCR scores, and SSIM. It supports multiple validation datasets, custom optimizers/schedulers, and data loading configurations, itera... | def train_on(
self,
train_data,
val_data,
num_epochs,
batch_size,
loss_func,
save_path,
save_epochs=50,
optimizer=torch.optim.Adam,
optimizer_params={"lr": 2e-4, "eps": 1e-3},
scheduler=torch.optim.lr_scheduler.StepLR,
sched... |
def _train_step(
self,
batch_idx,
batch,
loss_func,
optimizer,
scaler,
batch_size,
acc_steps,
):
with torch.cuda.amp.autocast(enabled=self.mixed_prec):
if len(batch) == 2:
inp, tar = batch
inp = inp.t... | This function trains a neural network model using specified data loaders, optimizer, and loss function, with validation and logging. It supports mixed precision, checkpointing, learning rate scheduling, and optional loss penalties. Training proceeds over multiple epochs, logging metrics like loss and error, and saving ... | def train_on(
self,
train_data,
val_data,
num_epochs,
batch_size,
loss_func,
save_path,
save_epochs=50,
optimizer=torch.optim.Adam,
optimizer_params={"lr": 2e-4, "eps": 1e-3},
scheduler=to... |
def canExtract(self):
if self.tree_map and self.pack_file:
return True
return False
def errorWindow(self, title, message):
msg = QtWidgets.QMessageBox()
msg.setIcon(QtWidgets.QMessageBox.Critical)
msg.setText(message)
msg.resize(400, 300)
# msg.setInf... | This code extracts files from a data.pack archive by initiating a worker thread. It validates prerequisites, prompts for a destination folder, disables UI elements, sets up a progress bar, and connects signals to handle extraction progress, completion, and errors. | def extractFile(self, file):
if self.canExtract() is False:
return self.errorWindow('Error', 'Please select the data.pack and file tree first.')
# treeToList(files)
path = askdirectory(title='Select destination folder')
if path == '':
# User clicked cancel
... |
def importation(path,y_min,y_max):
dico={}
for year in range(y_min,y_max):
x=importation_year(path,year)
for word in x.keys():
try:
dico[word][year]=x[word]
except:
dico[word]={}
dico[word][year]=x[word]
return dico
def ... | The function `chronocloud` generates a timeline-based word cloud (chronocloud) by processing historical word frequency data. It imports word frequencies from specified periods, extracts year, frequency, and resilience metrics for each word, sorts resiliences in descending order, and constructs a chronocloud visualizati... | def chronocloud(resolution,resiliences,periods,data_folder):
debut=datetime.now()
path=data_folder+'/'
words_frequencies=importation(path,periods[0],periods[-1])
words_carac={}
for word in words_frequencies:
year=extract_year(words_frequencies[word])
frequency=extract_frequency(words... |
def pad_with_zeros(plaintext_binary):
"""Pad with zeros such that the length is divisible by 64."""
plaintext_len = len(plaintext_binary)
target_len = 64 * ((plaintext_len-1) // 64 + 1)
zero_padding = '0'*(target_len - plaintext_len)
plaintext_binary += zero_padding
return plaintext_binary
def get_round_keys():
... | The code encrypts a plaintext message using a block cipher. It converts the text to binary, pads it with zeros, divides it into 64-bit blocks, and encrypts each block with round keys. The encrypted binary blocks are joined and converted back to text for the final ciphertext. | def encrypt_message(plaintext):
"""Encrypts the plaintext."""
plaintext_binary = helper.convert_text_to_binary(plaintext)
plaintext_binary = pad_with_zeros(plaintext_binary)
plaintext_len = len(plaintext_binary)
round_keys = get_round_keys()
ciphertext_binary = []
for i in range(0, plaintext_len, 64):
block ... |
def idm_train(self):
if self.verbose:
self.pbar.set_description_str(desc=f'Training IDM', refresh=True)
if not self.idm.training:
self.idm.train()
if self.iupe_dataset is not None:
datasets = [self.random_dataset, self.iupe_dataset]
names = ['ran... | The code trains an Inverse Dynamics Model (IDM) and a policy network, logging their accuracy and loss. It generates a new data ratio (Alpha) and updates a visualization board. If verbose, it displays a progress bar tracking training steps. The function orchestrates model learning, metric tracking, and data generation f... | def learn(self, total_timesteps: int = None, reset_num_timesteps: bool = False) -> None:
if self.verbose:
size = len(self.random_dataset.dataset) + len(self.expert_dataset.dataset)
if self.iupe_dataset is not None:
size = len(self.iupe_dataset.dataset)
... |
def loadMatrix(self): # updates gui from board matrix
self.pieceImage = [[ImageTk.PhotoImage(Image.open("src/images/none_blank.png")) for x in range(8)] for y in range(8)]
for r in range(8):
for c in range(8):
self.location = self.b.getImage(r, c)
self.pieceIm... | This function handles chess piece movement on a GUI board by tracking tile clicks. It highlights selected tiles, executes moves, updates the game state, checks for check/checkmate, disables tiles upon game over, and triggers pawn promotions. It also prevents player overrides during CPU turns and initiates CPU moves asy... | def tileClick(self, r, c, playerInitialized):
if self.b.checkTurn() == 1 and self.gm == "CPU" and playerInitialized:
return False # prevents player from overriding cpu moves
global prevR, prevC, newR, newC, prevBG, gameOver
print(str(r) + "," + str(c) + " has been clicked!")
... |
def get_ineq(line):
match = re.search('[<>]=?|=', line)
if match:
return match.group()
else:
raise NotImplementedError
def check_left_with_premises(left_lst, premises):
for left in left_lst:
if left.replace(' ','') in premises:
continue
## if every s... | The function `check_rewrite` verifies if a mathematical expression (split into left and right parts by `=>`) can be rewritten or is equivalent under given premises or a goal. It checks inequality relations (`=`, `>=`, `<=`) using symbolic simplification with `sympy`, validating conditions like equality, sign of ratios,... | def check_rewrite(obj, goal=None, premises=None):
assert len(obj.split('=>')) == 2
left, right = obj.split('=>')
left_ineq, right_ineq = get_ineq(left), get_ineq(right)
if premises is not None:
if not check_left_with_premises([left], premises):
return False
else:
if ... |
def check_left_with_premises(left_lst, premises):
for left in left_lst:
if left.replace(' ','') in premises:
continue
## if every symbol has positive exp
check = False
if get_ineq(left) == '>=':
check_expr = left.split('>=')[0].strip()
... | The function `check_substitute` verifies if substituting terms in a logical expression (split by `=>`) aligns with given premises or goals. It splits the input into left and right parts, validates inequalities, replaces terms using premises, simplifies both sides with SymPy, and checks equality. It returns a boolean in... | def check_substitute(obj, premise, goal=None, premises=None):
assert len(obj.split('=>')) == 2
left, right = obj.split('=>')
if premises is not None:
check_left_with_premises([left], premises)
else:
check_left_with_goal(left, goal)
left_ineq, right_ineq = get_ineq(left), get_ineq(r... |
def check_left_with_premises(left_lst, premises):
for left in left_lst:
if left.replace(' ','') in premises:
continue
## if every symbol has positive exp
check = False
if get_ineq(left) == '>=':
check_expr = left.split('>=')[0].strip()
... | The function `check_implication` verifies if a mathematical implication (structured as `A => B`) logically follows from given premises. It splits the input into left and right sides, checks consistency with premises, and evaluates inequalities (e.g., `>=`). For multiple left expressions, it validates transitive chains ... | def check_implication(obj, premises):
assert len(obj.split('=>')) == 2
left, right = obj.split('=>')
left_lst = [x.strip() for x in left.split(',')]
check_left_with_premises(left_lst, premises)
if len(left_lst) >= 2:
left_ineq_lst = [get_ineq(x) for x in left_lst]
right_ineq = ... |
def clear(obj):
out = re.sub(r'\/\*.*?\*\/','', obj, flags=re.DOTALL)
out = out.replace('^', '**')
out = out.split('\n')
new_obj = []
for line in out:
if line.strip():
new_obj.append(line)
return new_obj
def get_premises(obj_lst):
assert obj_lst[0].startswith('[premises]'... | The code processes a formal proof from a text file, verifying each step's validity. It reads premises and a goal, iterates through proof steps (rewrite, substitute, imply), checks their correctness using helper functions, and updates premises/goal accordingly. If a step is invalid, it attempts SymPy-based rewriting or ... | def main(args):
solution = os.path.join('solutions_15', args.solution)
with open(solution, 'r') as f:
obj_lst = clear(f.read())
print('\n'.join(obj_lst))
premises, goal = get_premises(obj_lst), get_goal(obj_lst)
# begin solution
assert obj_lst[2] == '[proof]'
ptr = 3
solved = ... |
def clear(self):
'''
Remove all lines from plot
'''
self.ax.lines = []
def draw_arm(self, kin):
'''
Draw the arm
Parameters
kin: kinematic model to draw
'''
# draw arm
self.draw_line(np.array([0,0,0]), kin.t_matrix_0_1.pos)
self.draw_line(kin.t_matrix_0_1.pos, kin.t_matrix_0_2.pos)
self... | This function updates a robotic arm's joint angles based on slider inputs, recalculates transformation matrices, redraws the arm's position, and prints the updated angles and end-effector coordinates in response to slider changes. | def joint_slider_update(val):
'''
Function called when joint angle slider changes
'''
self.kin.update_joint_angles(np.array([
self.joint1_t_slider.val,
self.joint2_t_slider.val,
self.joint3_t_slider.val,
self.joint4_t_slider.val,
self.joint5_t_slider.val,
self.joint6_t_slider.val,
... |
def clear(self):
'''
Remove all lines from plot
'''
self.ax.lines = []
def draw_arm(self, kin):
'''
Draw the arm
Parameters
kin: kinematic model to draw
'''
# draw arm
self.draw_line(np.array([0,0,0]), kin.t_matrix_0_1.pos)
self.draw_line(kin.t_matrix_0_1.pos, kin.t_matrix_0_2.pos)
self... | This function updates a robotic arm's position and orientation based on slider inputs. It converts Euler angles to a quaternion, calculates inverse kinematics for the new position, updates transformation matrices, redraws the arm, and prints joint angles and end-effector positions. | def pos_slider_update(val):
'''
Function called when position slider changes
'''
# rotation matrix where we want end effector
yaw = math.radians(self.yaw_slider.val)
pitch = math.radians(self.pitch_slider.val)
roll = math.radians(self.roll_slider.val)
'''
# rotation matrix from euler angles... |
def clear(self):
'''
Remove all lines from plot
'''
self.ax.lines = []
def draw_arm(self, kin):
'''
Draw the arm
Parameters
kin: kinematic model to draw
'''
# draw arm
self.draw_line(np.array([0,0,0]), kin.t_matrix_0_1.pos)
self.draw_line(kin.t_matrix_0_1.pos, kin.t_matrix_0_2.pos)
self... | This code animates a robotic arm's movement by processing a queue of joint angles. It clears the current plot, updates the kinematic model for each joint configuration in the queue, generates animation frames, and displays the motion. After completing the animation, it renders the final pose of the arm using the last j... | def run_queue(self):
start_time = time.time()
# if no moves to make, return
if len(self.mot.queue) == 0:
return
final_joint_angles = self.mot.queue[-1]
# render with artists
self.clear()
artists = []
temp_kin = Kinematics()
while len(self.mot.queue) != 0:
# update joint angles of kinematic mo... |
def _raise(e):
raise e
def axes_dict(axes):
axes, allowed = axes_check_and_normalize(axes,return_allowed=True)
return { a: None if axes.find(a) == -1 else axes.find(a) for a in allowed }
def normalize_mi_ma(x, mi, ma, clip=False, eps=1e-20, dtype=np.float32):
if dtype is not None:
x = x.a... | This function normalizes an image by computing min and max values using specified percentiles along given axes, then applies normalization. It first validates axes dimensions, identifies the channel axis, calculates percentiles for min/max, and returns the normalized image with specified data type and parameters. | def before(self, img, axes):
len(axes) == img.ndim or _raise(ValueError())
channel = axes_dict(axes)['C']
axes = None if channel is None else tuple((d for d in range(img.ndim) if d != channel))
self.mi = np.percentile(img,self.pmin,axis=axes,keepdims=True).astype(self.dtype,copy=False)
... |
def trajectory_generator(Tse_init, Tsc_init, Tsc_final, Tce_grasp, Tce_standoff, k):
# likely use ScrewTrajectory or CartesianTrajectory
method = 5 # cubic time scaling
# A trajectory to move the gripper from its initial configuration to a "standoff" configuration a few cm above the block.
tf1 = 10 # 1... | The main task of the code is to generate and simulate a robotic arm's trajectory for end-effector motion control. It initializes transformation matrices, computes a trajectory using a generator function, and iterates through the trajectory points to apply feedback control. The code updates the robot's state, calculates... | def main():
# input for trajectory generator
Tsc_init = np.array([[1, 0, 0, 1],[0, 1, 0, 0],[0, 0, 1, 0.025],[0, 0, 0, 1]])
Tsc_final = np.array([[0, 1, 0, 0],[-1, 0, 0, -1],[0, 0, 1, 0.025],[0, 0, 0, 1]])
#state = np.array([0., 0., 0., 0., 0.0, -0.01, -0.02, 0., 0., 0., 0., 0., 0.])
#(Tse_init, _) ... |
def get_commands_from(chara_name: str) -> list:
character = get_character_detail(chara_name)
movelist = get_character_movelist(character)
result = []
for move in movelist:
result.append(move["Command"])
return list(result)
def get_close_matches_indexes(word, possibilities, n=3, cutoff=0.6):... | This function finds the closest matching moves to a given move name for a specified character by simplifying the input move and comparing it against a list of simplified moves, returning the top 5 closest matches with a similarity threshold of 0.5. | def get_similar_moves(move: str, chara_name: str) -> list:
move_list = get_commands_from(chara_name)
moves_indexes = get_close_matches_indexes(move_simplifier(move), map(move_simplifier, move_list), 5, 0.5)
result = []
for index in moves_indexes:
result.append(move_list[index])
return resu... |
def get_current_set():
config = load_config()
if "current_test" in config:
return config["current_test"]
return ""
def check_tests(current_set):
number = 0
try:
while run_unit_tests(current_set, number):
number += 1
except ValueError as e:
number = -1
... | The function `show` processes an exercise request by converting the input number to an integer, retrieving the current exercise set, and handling redirections for invalid states or completion. If the number is 0, it dynamically determines the test count. It fetches the exercise description and renders the `exercise.htm... | def show(number):
number = int(number)
current_set = get_current_set()
if not current_set:
return redirect("/choose-exercise-set", code=302)
if number == 0:
number = check_tests(current_set)
if number == -1:
return redirect("/exercise-set-completed", code=302)
descri... |
def flatten_data(fetched_data: List[Dict]) -> pd.DataFrame:
flattened_list = [flatten_individual(data) for data in fetched_data]
return pd.DataFrame(flattened_list)
def rename_columns_of_flattened_df(flattened_df: pd.DataFrame):
columns_with_defaults = {
'NumberOfReviewers': 0,
'... | The code processes database data by fetching, flattening nested structures, renaming columns for clarity, and prioritizing abnormal recordings, ultimately returning a structured pandas DataFrame for analysis. | def process_data(db: Client) -> pd.DataFrame:
fetched_data = fetch_data(db)
flattened_data = flatten_data(fetched_data)
renamed_data = rename_columns_of_flattened_df(flattened_data)
processed_data = prioritize_abnormal_recordings(renamed_data)
return processed_data |
def _resize_surface(self, size: (int, int)) -> None:
"""Makes the game surface resizeable"""
self._surface = pygame.display.set_mode(size, pygame.RESIZABLE)
def _update_world(self) -> None:
"""Updtates the game based on game event changes"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
... | The code initializes a Pygame game loop, setting up a timer for snake movement, updating the game state, redrawing the screen at 30 FPS, and checking for game-over conditions to terminate the loop. It manages display resizing, game logic, and clean shutdown of Pygame when the game ends. | def run(self):
pygame.init()
self._resize_surface(self._display_surface)
clock = pygame.time.Clock()
pygame.time.set_timer(moveSnakeForward, 1000)
while self._running:
clock.tick(30)
#I don't remember this
self._update_world()
self._redraw()
try:
if self._game_play.check_game_over():
... |
def __update_kernel_width(self, t):
""" Update to the Neighborhood Radius """
self.kernel_width = self.initial_kernel_width * np.power(np.e, (-t / self.tau_2))
def __update_learning_rate(self, t):
self.learning_rate = self.initial_learning_rate * np.power(np.e, (-t / self.tau_1))
def __hypercube... | The code initializes parameters and structures for a model, setting grid dimensions (X, Y), kernel width (tau_1/tau_2), learning rate, and a 3D map for data storage. It also initializes hypercube weights using input samples, preparing the model for subsequent operations like training or prediction. | def __initialize(self, samples):
self.X, self.Y = 4, 4
self.tau_1 = 8.0
self.tau_2 = 8.0
self.__update_kernel_width(t=0)
self.__update_learning_rate(t=0)
self.map = [[[0 for i in range(len(samples[0]))] for col in range(self.X)] for row in range(self.Y)]
self.__hy... |
def __initialize(self, samples):
self.X, self.Y = 4, 4
self.tau_1 = 8.0
self.tau_2 = 8.0
self.__update_kernel_width(t=0)
self.__update_learning_rate(t=0)
self.map = [[[0 for i in range(len(samples[0]))] for col in range(self.X)] for row in range(self.Y)]
self.__hy... | This code trains a self-organizing map (SOM) by iteratively updating neuron weights to minimize quantization errors. It tracks sliding-window averages and standard deviations of errors, adjusting learning rate and kernel width over epochs. Training stops when the standard deviation of quantization errors falls below 0.... | def train(self, samples):
self.__initialize(samples)
stopping_condition = False
epoch_counter = 0
sliding_window = 30
quantization_errors = [0 for i in range(len(samples))]
avg_quantization_errors = [0 for i in range(len(samples))]
std_dev_quantization_errors = [0... |
def matchingModelandPredictWeight(models_Predict_Weights_df):
models_List = ['vit_base', 'vit_large', 'AlexNet', 'vgg16', 'vgg19', 'resnet50', 'resnet101']
models_Predict_Weights_List = []
for model in models_List:
# Filter the DataFrame based on 'model_name' column
filter... | The code processes video frames for classification using multiple models, handling both 4-grid and 1-grid video structures. It loads model weights, applies transformations, predicts frame labels, saves results as CSV files, and calculates accuracy against provided labels if enabled. The task involves batch processing v... | def main(args):
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
data_transform = transforms.Compose(
[transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])
# read class_... |
def randLine():
randNum = random.randint(1, 10)
str = ""
for x in range(randNum):
str += randWord()
return str
def randWord():
word_url = "https://www.mit.edu/~ecprice/wordlist.100000"
response = requests.get(word_url)
WORDS = response.content.splitlines()
return random.choice(WO... | The code generates a modified code file by replacing placeholders like <randWord> and <loop> with random elements and content from external files, then writes the updated code to a new file, likely for obfuscation or dynamic code generation purposes. | def randCode():
print("Using rand code will drastically increase the gas price but will bypass the...")
fullPath = "autoSol\\inputs\\"
newFileName = "autoSol\\junkCode.txt"
with open(fullPath + 'function\\function1.txt','r') as firstfile, open(newFileName,'a') as secondfile:
for line in firstfil... |
def isConverged(self):
# checks if the algorithm converged by comparing the new log with the previous log
newLog = self.logLikelyhood()
if self.completedIterations >= self.maxIterations:
print(f"Maximum iterations ({self.maxIterations}) reached")
return True
elif... | The code performs the Expectation-Maximization (EM) algorithm for clustering. It iterates between E-step (computing membership probabilities) and M-step (updating model parameters) until convergence. After completing iterations, it assigns each data point to the cluster with the highest membership weight using `argmax`... | def run(self):
# main loop to run the code
while (not self.isConverged()):
self.expectationStep()
self.maximizationStep()
self.completedIterations += 1
print(f" Iteration {self.completedIterations} of {self.maxIterations}") # , end='\r')
clusterAs... |
def __create_session(self, folder_id):
'''
Create an upload session. Return sessionUpload object.
'''
print('')
while True:
print('Calling POST PublicAPI/REST/sessionUpload endpoint')
url = 'https://{0}/Panopto/PublicAPI/REST/sessionUpload'.format(self.ser... | This method uploads a video file by creating a session, uploading the video and its manifest file in parts, finalizing the upload, and monitoring its processing progress. | def upload_video(self, file_path, folder_id):
'''
Main upload method to go through all required steps.
'''
# step 1 - Create a session
session_upload = self.__create_session(folder_id)
upload_id = session_upload['ID']
upload_target = session_upload['UploadTarget']... |
def initialize_NN(self, layers):
weights = []
biases = []
num_layers = len(layers)
for l in range(0,num_layers-1):
W = self.xavier_init(size=[layers[l], layers[l+1]])
b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32)
... | This code initializes a physics-informed neural network (PINN) for solving partial differential equations (PDEs). It sets up training data, collocation points, and neural network architecture with parameters mu and nu. The model minimizes a combined L2 loss on solution predictions (u) and PDE residuals (f), using Adam ... | def __init__(self, X_u, u, X_f, layers, lb, ub, mu, nu, idn):
# lower and upper bound for the spatiotemporal domain
self.lb = lb
self.ub = ub
# training points for x and t
self.x_u = X_u[:,0:1]
self.t_u = X_u[:,1:2]
# values of the solution u in... |
def initialize_NN(layers):
weights = []
biases = []
num_layers = len(layers)
for l in range(0,num_layers-1):
W = xavier_init(size=[layers[l], layers[l+1]])
b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32)
weights.append(W)
biases.append(b)
... | This code initializes a physics-informed neural network (PINN) for solving PDEs. It sets up training data, defines neural network layers, initializes weights/biases, creates TensorFlow placeholders, and constructs prediction graphs. Loss functions for data fitting (u_loss) and PDE residuals (f_loss) are defined, along ... | def idn_init(self, t, x, u, u_layers, pde_layers):
# Training Data for Identification
self.t = t
self.x = x
self.u = u
# Layers for identification
self.u_layers = u_layers
self.pde_layers = pde_layers
# Initialize NNs for identification
... |
def initialize_NN(layers):
weights = []
biases = []
num_layers = len(layers)
for l in range(0,num_layers-1):
W = xavier_init(size=[layers[l], layers[l+1]])
b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32)
weights.append(W)
biases.append(b)
... | This code initializes a physics-informed neural network (PINN) for solving partial differential equations (PDEs). It sets up training data for initial/boundary conditions and collocation points, defines neural network layers, constructs TensorFlow placeholders, and formulates a loss function combining residuals from in... | def sol_init(self, x0, u0, tb, X_f, layers):
# Training Data for Solution
X0 = np.concatenate((0*x0, x0), 1) # (0, x0)
# lower and upper bounds for the domain
X_lb = np.concatenate((tb, 0*tb + self.lb_sol[1]), 1) # (tb, lb[1])
X_ub = np.concatenate((tb, 0*tb + self.ub_sol[1]), 1)... |
def create_pool(self):
# flush the old pool which could have lingering subprocesses
if self.pool:
self.pool.terminate()
self.pool.close()
self.pool.join()
# create pool, disabling SIGINT so parent process can handle it
handler = signal.signal(signal.SI... | This method initializes the class by setting source, destination, and patch directories, converting them to absolute paths, ensuring directories exist, and scanning files within each directory to prepare for processing. It also initializes data structures to track files and errors, and creates a processing pool for sub... | def initialize(self, src, dst, pch):
self.src = src
self.dst = dst
self.pch = pch
self.src_files = {}
self.dst_files = {}
self.pch_files = {}
self.has_error = False
self.create_pool()
# initialize directories
self.trace(f"Preparing file inf... |
def perform_hash(verbose, filename):
trace(verbose, f"Hashing {filename}...")
hash = hashlib.sha1()
try:
with open(filename, "rb") as inpfile:
block = inpfile.read(io.DEFAULT_BUFFER_SIZE)
while len(block) != 0:
hash.update(block)
block = inpfil... | The main task of the code is to apply patches to a source file to generate a destination file, verifying hash matches before applying patches or copying files. If patches fail, it retries downloads with fallback mechanisms, ensuring data integrity through hash checks and handling errors gracefully by attempting direct ... | def apply_patches(self):
# lazily hash source only once and only if/when necessary
src_hash = None
# process all of the patches
for patch in self.patches:
# try applying the current patch
try:
# check if dst already matches the manifest
... |
def trace(self, str):
trace(self.verbose, str)
def makedirs(dir):
os.makedirs(os.path.abspath(dir), exist_ok=True)
def iterate_dirs(self, dir):
for entry in getattr(self, f"{dir}_files").values():
if entry.is_dir:
yield entry
def generate_queue(self):
# search for... | The code generates delta patches between source and destination files, manages a manifest with metadata (UIDs, GIDs, hashes), creates directory structures, processes patches in parallel, replaces large delta patches with direct copies when needed, and writes the final manifest to a JSON file. | def generate(self):
# cleanup the patch directory
self.trace(f"Cleaning {self.pch}...")
shutil.rmtree(self.pch, ignore_errors=True)
makedirs(self.pch)
# populate src/dst manifest with files/dirs metadata
for dir in ["src", "dst"]:
for entry in getattr(self, f... |
def read_manifest(self):
self.trace(f"Reading manifest...")
with open(os.path.join(self.pch, "manifest.json"), "r") as inpfile:
self.manifest = json.load(inpfile)
# check manifest version
if self.manifest["metadata"]["manifest"]["version"] > 1.0:
self.error(f'Man... | The code applies a manifest to a destination directory by creating directories with specified permissions, applying patches in parallel, removing extraneous files/dirs, and setting file properties like mode, ownership, and timestamps according to the manifest. | def apply(self):
# read the manifest file
self.read_manifest()
# create destination directories, in tree order, applying manifest permissions
for (name, entry) in sorted(self.iterate_manifest("dst", True), key=lambda tuple: tuple[0]):
mkdir(os.path.join(self.dst, name), mode... |
def read_manifest(self):
self.trace(f"Reading manifest...")
with open(os.path.join(self.pch, "manifest.json"), "r") as inpfile:
self.manifest = json.load(inpfile)
# check manifest version
if self.manifest["metadata"]["manifest"]["version"] > 1.0:
self.error(f'Man... | The code validates the integrity of files against a manifest by checking if each file exists locally, ensuring hash matches, and verifying attributes like uid, gid, mode, size, and mtime. It also identifies missing files in the manifest and ensures all local files are accounted for in the manifest. | def validate(self):
# read the manifest file
self.read_manifest()
# generate local hashes
self.trace(f"Generating hashes...")
local_manifest = defaultdict(dict)
self.generate_hashes(local_manifest, ["src", "dst", "pch"])
dir_lookup = {"s": "src", "d": "dst", "p"... |
def read_manifest(self):
self.trace(f"Reading manifest...")
with open(os.path.join(self.pch, "manifest.json"), "r") as inpfile:
self.manifest = json.load(inpfile)
# check manifest version
if self.manifest["metadata"]["manifest"]["version"] > 1.0:
self.error(f'Man... | The code analyzes potential storage savings by identifying case-insensitive filename matches, moved files with matching names, and oversized xdelta3 patches. It calculates and reports byte savings for each scenario, comparing source and destination metadata to optimize data transfer efficiency. | def analyze(self):
# read the manifest file
self.read_manifest()
# populate src/dst manifest with files/dirs metadata
local_manifest = defaultdict(dict)
self.trace(f"Collecting local file metadata...")
for dir in ["src", "dst"]:
for entry in getattr(self, f"{... |
def rmtree(self, dir):
retries = 50
while retries:
try:
if os.path.isdir(dir):
shutil.rmtree(dir)
return
except:
print(f"shutil.rmtree: {sys.exc_info()[1]}")
time.sleep(0.10)
retri... | The code initializes a DeltaPatcher test environment by configuring settings, setting up a temporary directory, and preparing test directories ("src", "dst", "pch"). It configures HTTP parameters, ensures repeatability with a fixed random seed, and initializes state variables for testing. The setup includes cleanup, di... | def __init__(self, zip):
settings = DeltaPatcherSettings()
settings.zip = zip
settings.stop_on_error = True
settings.verbose = True
settings.http["base"] = "http://localhost:8080/"
settings.http["user"] = "test"
settings.http["pass"] = "pass"
settings.http... |
def generate_convex_polygon(point_list):
curr_set_of_point = np.array(point_list)
curr_hull = ConvexHull(curr_set_of_point)
result = []
for index in curr_hull.vertices:
result.append(point_list[index])
return result
def calc_polygon_area(vertices):
if len(vertices) < 3:
return 0
... | The code calculates the ratio of the area of the intersection between two convex polygons (generated from mouse and port points) to the area of the mouse polygon, returning this normalized intersection area as a measure of overlap. | def calculate_intersection_area(mouse_points, port_points):
mouse_polygon = generate_convex_polygon(mouse_points)
port_polygon = generate_convex_polygon(port_points)
mouse_area = calc_polygon_area(mouse_polygon)
intersect_polygon = intersect(mouse_polygon, port_polygon)
return calc_polygon_area(in... |
def evalimage(net:Yolact, path:str, save_path:str=None):
frame = cv2.imread(path)
if args.flip:
frame = cv2.flip(frame, 1)
frame_clip = cv2.flip(frame, 1)
frame_rotate = cv2.rotate(frame_clip, cv2.ROTATE_90_COUNTERCLOCKWISE)
frame_rotate = torch.from_numpy(frame_rotate).cuda().float()
ba... | The function `evaluate` assesses a Yolact model's performance on images or videos using specified detection parameters (e.g., NMS settings). It routes inputs to evaluation functions (`evalimage`, `evalimages`, `log_video`) based on command-line arguments, handling single images, batches, or video files. The task involv... | def evaluate(net:Yolact, dataset, train_mode=False):
net.detect.use_fast_nms = args.fast_nms
net.detect.use_cross_class_nms = args.cross_class_nms
cfg.mask_proto_debug = args.mask_proto_debug
# TODO Currently we do not support Fast Mask Re-scroing in evalimage, evalimages, and evalvideo
if args.ima... |
def reshape(self, width, height):
# self.getNoteX.cache_clear()
self.game.width, self.game.height = width, height
self.octaveWidth, self.pianoHeight = self.octaveAspectClamper.clamp(width / (self.noteCount / 12), height * .1)
def getNoteX(self, pitch):
if pitch < self.middleNote:
... | This code updates a game state by advancing time, processing events (like ESC key and window resize), updating particle systems, adjusting particle source positions based on pressed keys, and pruning outdated history entries. | def update(self, dt: float, events: list[Event]):
self.time += dt
self.particles.update(dt)
for event in events:
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.game.popState()
elif event.type == VIDEORESIZE:
se... |
def getNoteWidth(self, pitch):
return ((12 - 0.7*5) / 7, 0.7)[self.isNoteBlack(pitch)] * self.octaveWidth / 12
def getNoteX(self, pitch):
if pitch < self.middleNote:
return self.getNoteX(pitch + 1) - (self.getNoteWidth(pitch + 1) + self.getNoteWidth(pitch)) / 2
if pitch > self.middle... | This code draws a musical note visualization on a surface. It calculates the note's width and position based on pitch, then creates a rectangle with height proportional to the note's duration. The rectangle's color varies depending on whether the note is black or white, with a border added for visibility. | def drawNote(self, surface: Surface, pitch: int, timePressed: float, timeReleased: float):
width = self.getNoteWidth(pitch)
rect = (self.getNoteX(pitch) - width / 2, self.getTimeY(timePressed), width, (timeReleased - timePressed) * self.timeScale)
pygame.draw.rect(surface, (0, 100, 255) if self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.