dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_check_number(self, doc):
self.check_number = ""
for p in doc.pages():
page_content = p.getText()
m = re.match(r'.*\n([0-9A-Z\s]+)\nDUPLICATE\nCOPY\n', page_content, re.DOTALL)
if m is not None:
self.check_number = m.group(1)
ret... | The main task of the code is to extract specific information from a PDF document, including text from a defined area using regex, check numbers, message codes, and process pages for further data handling. It opens the PDF, extracts structured data, applies pattern matching, and prepares the document for additional proc... | def process_pdf(self):
doc = fitz.open(os.path.join(self.abs_path, "document.pdf"))
self.info = doc[0].getText("text", clip=fitz.Rect(360,144,576,252))
self.info = re.match(r'([A-Z]+\s[0-9].{2}\s[0-9]+\n)([0-9]*\n)?([0-9]*\n)?([0-9\.\,]*\n)?Date\sof\sRemittance', self.info, re.DOTALL)
... |
def scroll_to_element(self, element):
desired_y = (element.size['height'] / 2) + element.location['y']
window_h = self.drive.execute_script('return window.innerHeight')
window_y = self.drive.execute_script('return window.pageYOffset')
current_y = (window_h / 2) + window_y
scroll_... | The main task of the code is to automate accessing a claims portal by navigating through web elements, selecting options, submitting forms, and downloading remittance documents. It handles date input, switches browser windows, captures screenshots, processes PDFs, extracts data, saves it as JSON, and uploads informatio... | def main(self):
self.drive.get(self.report_url)
select_tins = WebDriverWait(self.drive, 20).until(EC.element_to_be_clickable((By.ID, "tins")))
time.sleep(3)
try:
self.drive.find_element(By.CLASS_NAME, "acsCloseButton").click()
except:
pass
... |
def plot_canvas(self, figsize=(8, 7)):
"""
The base plot being updated during the simulation For the 2D
simulations, we use a scatter plot. For the 1D chain we use a quiver
plot showing the XZ plane. This plot is saved in the self.plot variable
Spins are filtered to remove enti... | This function generates interactive widgets for controlling a magnetic simulation, allowing users to select plot components (x/y/z/hls), adjust Zeeman field values, set DMI magnitude, choose initial states (e.g., Skyrmion, Vortex), configure simulation parameters (time, steps), and control boundary pinning. Widgets upd... | def generate_widgets(self):
"""
Generate the plot and the widgets with different options for
the simulation
"""
self.plot_canvas()
# Select which m component to plot ------------------------------------
mcomp_dropdown = ipw.Dropdown(options=['x', 'y', 'z', 'h... |
def _get_template(url_path):
"""
Given a basic path, find an HTML or Markdown file
"""
# Try to match HTML or Markdown files
if _template_exists(url_path + ".html"):
return url_path + ".html"
elif _template_exists(os.path.join(url_path, "index.html")):
return os.path.join(url_pa... | The function `render_to_response` generates an HTTP response by rendering a template (HTML or Markdown) based on the request path. It locates the appropriate template, handles Markdown by extracting wrapper templates and context, and returns a response using `response_class`. If no template is found, it redirects or ra... | def render_to_response(self, context, **response_kwargs):
"""
Return a response, using the `response_class` for this view, with a
template rendered with the given context.
Pass response_kwargs to the constructor of the response class.
"""
# Response defaults
resp... |
def findName(self, player):
for child in player.children:
if child == '\xa0':
continue
if child.text != '':
return child.get_text().strip()
return ''
def verifyPlayer(self, players, game, name):
playerData = players.get(name, -1)
if... | This function processes a game set by extracting top and bottom player names and scores from HTML elements, verifies their existence in the player list, and calculates Elo ratings for each score pair using the eloCalc method. | def processSet(self, game, players):
topPlayer = game.find(class_='bracket-player-top')
bottomPlayer = game.find(class_='bracket-player-bottom')
if topPlayer: topPlayerName = self.findName(topPlayer)
else: return
if bottomPlayer: bottomPlayerName = self.findName(bottomP... |
def processLoneOtherRounds(self, players):
for brackets in self.otherRounds:
self.quickrun(brackets, players)
def bracketRound(self, bracket, players, index):
round = bracket[self.indices[index]]
games = round.find_all(class_='bracket-game')
for game in games:
sel... | The code processes a tournament bracket by sequentially handling winners and losers rounds. It first processes winners rounds, identifies the first loser, and ensures they are properly placed in losers rounds. It then iterates through rounds, alternating between winners and losers brackets as needed, advancing players ... | def run(self, players):
if not self.winnersRounds and self.otherRounds:
self.processLoneOtherRounds(players)
return
self.bracketRound(self.winnersRounds, players, 0) # always run winners round 1 first [0,0,0] -> [1,0,0]
firstLoser = self.findFirstLoser(self.winners... |
def __get_moves_list(self, side: SideType) -> list[Move]:
"""Get the list of moves for the specified side.
Args:
side (SideType): The side for which to get the moves.
Returns:
list[Move]: The list of moves for the specified side.
"""
moves_list = self.__... | This function recursively predicts all possible move sequences for a given side in a board game, considering both regular and required moves. It explores moves up to a maximum depth, branching based on whether a move results in a kill and if required subsequent moves exist. The function tracks current moves, accumulate... | def __get_predicted_moves_list(
self,
side: SideType,
current_prediction_depth: int = 0,
all_moves_list: list[Move] = [],
current_moves_list: list[Move] = [],
required_moves_list: list[Move] = [],
) -> list[Move]:
"""
Predict all possible moves.
... |
def perform_move(self, direction):
if direction == "DOWN":
self.board = np.rot90(self.board)
has_pushed = self.slide_right_2()
has_merged = self.merge_elements_2()
self.slide_right_2()
self.board = np.rot90(self.board, 3)
move_made = has_pushed or has_merged
elif direction == "UP":
self.board ... | The main task of the code is to evaluate and select the optimal move direction (up/down/left/right) for a game board by simulating multiple random moves in each direction, calculating their average evaluation scores, and executing the highest-scoring move. It uses Monte Carlo simulations to predict outcomes, resets the... | def mover(self):
actual_board = np.copy(self.board)
move_results = np.zeros(4)
move_results = np.zeros(4)
#game_gui = gg.Game_gui()
for first_move in range(4):
for _ in range(self.NUMBER_OF_SEARCHES):
move_was_made = self.perform_move(self.DIRECTIONS[first_move])
if not move_was_made:
... |
def get_args():
help_text = """CME Node Recall Booster"""
parser = OptionParser(usage=help_text)
parser.add_option("-H", "--host", dest="host", default = "", help="the url for the DB", metavar="HOST_ADDRESS")
parser.add_option("-d", "--db", dest="database", defau... | The main task of the code is to train and evaluate multiple machine learning classifiers (primarily Logistic Regression) on categorized data, selecting the best-performing model for each category. It fetches input data, iterates through unique categories, trains specified classifiers, identifies the optimal model for e... | def main_1():
start = time.time()
## Get input arguments
(options, args) = get_args()
## Fetch input data to be classified
#train_data_df = get_data_df(options, args)
train_data_df = get_data_df_2(options, args)
#sys.exit()
#print(train_data_df.shape)
#print(train_data_df.columns)... |
def compile(self):
write_c = c_gen.c_program(self.x_eq, self.y_eq)
if write_c == 0:
compile_c()
else:
print("C program not compiled!")
def reset_image(self):
self.z = 1.0
self.x = 0.0
self.y = 0.0
self.run_and_open()
def run_and_open(self):... | The code defines the Mandelbrot set iteration equations for x and y, sets a clipping threshold, compiles the code, resets the image buffer, and executes the rendering to display the Mandelbrot fractal visualization. | def open_mandelbrot(self):
self.x_eq = "x * x - y * y + cx"
self.y_eq = "2 * x * y + cy"
self.clipping_eq = "2.0"
self.compile()
self.reset_image()
self.run_and_open() |
def compile(self):
write_c = c_gen.c_program(self.x_eq, self.y_eq)
if write_c == 0:
compile_c()
else:
print("C program not compiled!")
def reset_image(self):
self.z = 1.0
self.x = 0.0
self.y = 0.0
self.run_and_open()
def run_and_open(self):... | This code generates the Burning Ship fractal by defining mathematical equations for x and y coordinates, setting a clipping threshold, compiling the equations, resetting the image buffer, and then rendering and displaying the fractal pattern. | def open_burning_ship(self):
self.x_eq = "x * x - y * y + cx"
self.y_eq = "2 * fabsl(x * y) + cy"
self.clipping_eq = "2.0"
self.compile()
self.reset_image()
self.run_and_open() |
def compile(self):
write_c = c_gen.c_program(self.x_eq, self.y_eq)
if write_c == 0:
compile_c()
else:
print("C program not compiled!")
def reset_image(self):
self.z = 1.0
self.x = 0.0
self.y = 0.0
self.run_and_open()
def run_and_open(self):... | The main task of the code is to retrieve equations from input fields, close the input window, and trigger processing steps by calling `compile()`, `reset_image()`, and `run_and_open()` to handle and visualize the equations. | def set_equation(self):
self.x_eq = self.entry_x.get()
self.y_eq = self.entry_y.get()
self.clipping_eq = self.entry_clipping.get()
self.entry_window.destroy()
self.eq_window_open = False
self.compile()
self.reset_image()
self.run_and_open() |
def set_quality(self, w, h):
self.w = w
self.h = h
self.master.geometry(f"{w}x{h}")
self.run_and_open()
def reset_image(self):
self.z = 1.0
self.x = 0.0
self.y = 0.0
self.run_and_open()
def create_render_window(self):
if not self.render_window_open... | This code initializes a GUI application for a fractal viewer, setting up a window with menus to select fractal types (Mandelbrot, Burning ship, Custom), adjust image quality, and interact with fractal visuals via zooming, dragging, and resizing. It prepares variables for rendering equations, user input handling, and dy... | def __init__(self, master):
self.master = master
self.master.title("Fractal Viewer")
# initial size of window
self.master.geometry("480x270")
self.image = None
self.image_tk = None
self.canvas = None
self.z = 1.0
self.x = 0.0
self.y = 0.0
... |
def get_imagepath(each, output_dir, output_filepath):
if(output_filepath != ''):
return output_filepath
imagename = each.getElementsByTagName("imagename")
#print("GI:IMAGENAME=", imagename)
fileName = imagename[0].firstChild.nodeValue
fileName = fileName.split('/')
if len(fileName) > 1:
fileName = fileName[-1... | This code parses XML annotations for images, extracts fiducial points and isopter data, calculates scaling and rotation parameters, constructs hierarchical structures for isopter curves, and generates PDF visualizations. It checks for sufficient fiducials, annotated curves, and eye information, then logs or outputs res... | def parseAnnotation(inputfile, output_dir, output_filepath, use_log):
inputfile = inputfile
dom = xml.dom.minidom.parse(inputfile)
images = dom.getElementsByTagName("annotation-per-image")
log_fh = None
logName = "log.txt"
#if (use_log):
# log_fh = open(logName,"w")
# log_fh.write("Image" + "\t" + "Sufficient ... |
def get_imagename(each):
imagename = each.getElementsByTagName("imagename")
oldFileName = imagename[0].firstChild.nodeValue
#print("DEBUG: starting value of oldFileName = ", oldFileName)
#newFileName = []
oldFileName = oldFileName.split('/')
if len(oldFileName) > 1:
oldFileName = oldFileName[1]
else:
oldFile... | The code parses an XML file to extract image annotations, calculates scaling factors from fiducial points, computes rotation and ratio parameters, rotates fiducial points, collects isopter data, and returns key coordinates (mX, mY, scale) and isopters for further processing. Your return | def parseAnnotation(inputfile):
inputfile = inputfile
dom = xml.dom.minidom.parse(inputfile)
images = dom.getElementsByTagName("annotation-per-image")
for each in images:
#Name of the output PDF
fileName = get_imagename(each)
#print("DEBUG: get_imagename: %s --> %s" % (each, fileName))
#sys.exit()
#Check... |
def get_imagepath(each, output_dir, output_filepath):
if(output_filepath != ''):
return output_filepath
imagename = each.getElementsByTagName("imagename")
fileName = imagename[0].firstChild.nodeValue
fileName = fileName.split('/')
if len(fileName) > 1:
fileName = fileName[-1]
else:
fileName = fileName[0]
... | This code parses XML annotations of images, processes fiducial markers to calculate scaling and rotation parameters, constructs hierarchical data structures (HOS) from isopter/scotoma points, and updates the XML with derived information like rotated fiducial coordinates and isopter labels. It handles edge cases for mis... | def parseAnnotation(inputfile, output_dir, output_filepath, use_log):
inputfile = inputfile
dom = xml.dom.minidom.parse(inputfile)
images = dom.getElementsByTagName("annotation-per-image")
log_fh = None
logName = "log.txt"
if (use_log):
#log_fh = open(logName,"w")
#log_fh.write("Image" + "\t" + "Sufficient F... |
def usage():
print("Usage: %s [-i <FILE>]" % os.path.basename(__file__))
def normativeData():
nd_I4e = { 0: 84, 15: 82, 30: 78, 45: 69, 60: 61.5, 75: 57, 90: 55, 105: 56.5, 120: 57.5, 135: 59.5, 150: 60, 165: 60.5, 180: 60, 195: 60, 210: 60, 225: 60, 240: 60.5, 255: 62.5, 270: 68, 285: 72.5, 300: 74.5, 315: 77.5, 330... | This code processes input image annotations by interpolating normative isopter data, identifies the largest isopter contour, calculates intersections with radial lines, and generates updated annotations. It extrapolates missing data points, writes results to a new file, and handles XML formatting for image analysis. | def main(argv):
## process arguments
inputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:",["input="])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
usage()
sys.exit()
elif opt in ("-i", "--input"):
inputfile = arg
print ('Input file is ', inputfile)... |
def usage():
print (__doc__)
def check_linearRing(to_add_x, to_add_y):
points = []
#print ("input points")
for i in range(0, len(to_add_x)):
points.append([to_add_x[i], to_add_y[i]])
# print(to_add_x[i], to_add_y[i])
original_ring = Polygon(points)
#print ("checking")
if (original_ring.is_valid == False):
... | This code parses command-line arguments for input file, output directory, output file path, and logging settings. It validates inputs and invokes `parseAnnotation()` with parsed parameters to process the input file, likely for annotation tasks. The `check_linearRing()` calls appear to be debug/test statements. | def main(argv):
inputfile = ''
output_dir = './'
output_filepath = ''
use_log = True
try:
opts, args = getopt.getopt(argv,"huo:pi:s",["input=", "output-dir=", "output-file-path=", "no-log"])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
usage()
sys.exit()
el... |
def rev_comp(pattern):
rev = pattern[::-1]
comp = [comp_map[x] for x in rev]
return ''.join(comp)
def get_neighbours_upto_d(pattern, d):
neighborhood = one_neighborhood(pattern)
if d > len(pattern):
return []
for _ in range(d-1):
for pattern in neighborhood:
neighborh... | The function counts the frequency of all approximate k-mers (including exact matches and reverse complements) within a Hamming distance d from every possible k-mer in the input text. It iterates through each k-mer, generates its neighbors up to distance d, adds their reverse complements, removes duplicates, and tallies... | def get_all_apprx_kmer_freqs(text, k, d):
ans = {}
for i in range(len(text) - k + 1):
exact_kmer = text[i:i+k]
revcomp_kmer = rev_comp(exact_kmer)
apprx_kmers = get_neighbours_upto_d(exact_kmer, d)
apprx_kmers_rc = get_neighbours_upto_d(revcomp_kmer, d)
all_kmers = remove... |
def duration(request,a):
if(a=='1 Hr'):
return '01:00'
elif(a=='2 Hr'):
return '02:00'
elif(a=='3 Hr'):
return '03:00'
elif(a=='4 Hr'):
return '04:00'
elif(a=='5 Hr'):
return '05:00'
else:
return '00:30'
def PriceCalc(tm,type):
hr,mn=tm.split("... | The function handles POST and GET requests for a card list interface, processes form data including vehicle details and duration, validates vehicle numbers using regex, calculates parking prices, filters user data based on location input, and renders appropriate HTML templates with dynamic context variables like time, ... | def card_list(request):
print('inside cardlist')
from datetime import datetime
hr =datetime.now().strftime("%H")
mn =datetime.now().strftime("%M")
if request.method == "POST":
import re
try:
context['O_Username'] = request.POST['O_name']
context['VType'] = req... |
def calculate_body_turn_radius(self, linear_speed, angular_speed):
if angular_speed != 0.0:
body_turn_radius = linear_speed / angular_speed
else:
# Not turning, infinite turn radius
body_turn_radius = None
return body_turn_radius
def calculate_wheel_turn_radiu... | This function calculates wheel RPMs for a robot's differential drive system based on desired linear and angular velocities. It computes body and wheel turn radii, derives RPMs for right and left wheels, applies them to move the robot, waits 0.5 seconds, then stops the wheels. | def set_cmd_vel(self, linear_speed, angular_speed):
body_turn_radius = self.calculate_body_turn_radius(linear_speed, angular_speed)
wheel = "right"
right_wheel_turn_radius = self.calculate_wheel_turn_radius(body_turn_radius,
an... |
def calculate_body_turn_radius(self, linear_speed, angular_speed):
if angular_speed != 0.0:
body_turn_radius = linear_speed / angular_speed
else:
# Not turning, infinite turn radius
body_turn_radius = None
return body_turn_radius
def calculate_wheel_turn_radiu... | The code calculates the required RPM for left and right wheels of a differential drive robot based on given linear and angular speeds, using turn radius calculations for each wheel to determine their respective motor speeds. | def set_cmd_vel(self, linear_speed, angular_speed):
body_turn_radius = self.calculate_body_turn_radius(linear_speed, angular_speed)
wheel = "right"
right_wheel_turn_radius = self.calculate_wheel_turn_radius(body_turn_radius,
an... |
def init_board(self):
"""Initializes the game board."""
for i in range(ROWS):
for j in range(COLS):
self.board[i][j] = Block(i, j)
def init_bombs(self):
"""Initializes bomb locations."""
bombs_placed = 0
while bombs_placed < BOMB_COUNT:
i =... | The code initializes a game board for a puzzle or strategy game, setting up a 2D grid structure, placing bombs, and generating hints. It creates a Pygame surface for rendering the board visually and prepares the game state by calling methods to populate the board with bombs and calculate adjacent hint values for each c... | def __init__(self):
# Initialize the board and displayed_board
self.displayed_board = pygame.Surface((WIDTH, HEIGHT))
self.board = [[None] * COLS for i in range(ROWS)]
self.init_board()
self.init_bombs()
self.init_hints() |
def arrangeTetrominos(currentOrder = ['z6', 'b3', 't7', 'f4', 'c1', 'l0', 'o1', 's0']):
global grid
grid = [[0,0,0,0,0,0,1],[0,0,0,0,0,0,1], [0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [0,0,0,1,1,1,1] ]
if(mPo != None and dPo != None):
grid[mPo[0]][mPo[1]] = 1
grid[dP... | This code generates all permutations of a given list of elements, counts them, and checks if each permutation can form 7 fixed blocks using the arrangeTetrominos function. When a valid permutation is found, it records the solution in a file. The backStep variable limits recursion depth, and the global count tracks tota... | def permutations(elements =['b3', 'c1', 'f4', 'l0', 'o1', 's0', 't7', 'z6'], current_permutation = []):
global count
global backStep
global solution
if len(elements) == 0:
count+=1
# print(current_permutation)
blocksFixed = arrangeTetrominos(current_permutation)
# pri... |
def subsets_k(collection, k):
yield from partition_k(collection, k, k)
def calcHappiness(rooms, happiness):
totalHappiness = 0
for room in rooms:
room = list(room)
room.sort()
for i in range(len(room)):
for j in range(i+1, len(room)):
totalHappiness += happiness[room[i]][room[j]]
return totalHappin... | The function `bruteforce_k` computes the maximum achievable happiness by optimally assigning `n` people into exactly `k` rooms, ensuring each room's stress does not exceed `s_max/k`. It iterates through all possible `k`-room partitions, evaluates their total happiness and stress, filters valid configurations, and track... | def bruteforce_k(happiness, stress, n, s_max, k):
"""
Only brute forces solutions that uses k rooms
"""
print(k, end="", flush=True)
# corresponding max stress limit in room k:
stress_limit = s_max / k
s = list(range(n))
maxHappiness = 0
optimalRoom ... |
def subsets_k(collection, k):
yield from partition_k(collection, k, k)
def calcHappiness(rooms, happiness):
totalHappiness = 0
for room in rooms:
room = list(room)
room.sort()
for i in range(len(room)):
for j in range(i+1, len(room)):
totalHappiness += happiness[room[i]][room[j]]
return totalHappin... | This function determines the optimal breakout room configuration by brute-forcing all possible partitions of students, maximizing total happiness while ensuring each room's stress level does not exceed the calculated limit per room count. It iterates through subsets, validates stress constraints, and tracks the configu... | def bruteforce(happiness, stress, n, s_max):
# possible number of breakout rooms:
breakout_rooms = list(range(1, n+1))
# corresponding max stress limit in each room:
stress_limit = [s_max / num_room for num_room in breakout_rooms]
s = list(range(n))
maxHappiness = 0
optimalRoom = None
... |
def get_credentails(config_file: str) -> tuple:
"""
Reads credentials from config.ini file.
Returns tuple of credenitals.
"""
creds_config = configparser.ConfigParser()
creds_config.read(config_file)
user = creds_config['credentials']['username']
password = creds_config['credentials']['... | The main task of the code is to authenticate using credentials from a config file, validate a base URL, establish a session, retrieve a list of file paths from the server, and download all identified files with progress tracking using a progress bar. The code handles URL validation, session authentication, file listing... | def main():
# Get credentials from file
user, password = get_credentails("config.ini")
# Get base url
base_url = get_url("config.ini")
validated_url = validate_url(base_url)
print(f"Using {validated_url}")
# Start the session
session = requests.Session()
session.auth = (user, p... |
def OpenAppLog( self, bUseStdErr, bReopen ):
global log
try:
Log.OpenLog( self.logFile, bUseStdErr, self.bFlushLogs )
except IOError as e:
log = Log.OpenLog( self.emergencyLog, False, self.bFlushLogs )
log.warn( '{} WARN OpenAppLog failed to write to main log:{} {} err:{}'.format(Log.times... | This function processes incoming commands by checking the event's command type and executing corresponding actions, such as reopening logs, generating statistics, preparing to exit, handling persistent app commands, or managing unhandled events. It updates `extraEvents` based on the command and returns the modified val... | def HandleEvCommand( self, event, extraEvents ):
command = event.Command()
if command == eCommandType.CMD_REOPEN_LOG:
Log.CloseLog()
self.OpenAppLog(0,1)
extraEvents = self.UserCmdReopenLog( event, extraEvents )
elif command == eCommandType.CMD_STATS:
extraEvents = self.GenerateStats... |
def HandleEvCommand( self, event, extraEvents ):
command = event.Command()
if command == eCommandType.CMD_REOPEN_LOG:
Log.CloseLog()
self.OpenAppLog(0,1)
extraEvents = self.UserCmdReopenLog( event, extraEvents )
elif command == eCommandType.CMD_STATS:
extraEvents = self.GenerateStats... | This function processes incoming events by routing them to specific handler methods based on their type, updates the 'extraEvents' list with results, and returns it. It logs event handling if verbosity is enabled, supporting various event types like commands, URLs, results, and errors through dedicated methods. | def HandleNewEvent( self, event, extraEvents ):
if self.beVerbose: log.info( '{} HandleNewEvent:{}'.format(Log.timestamp,str(event)) )
if event.EventType() == eEventType.EV_COMMAND:
extraEvents = self.HandleEvCommand( event, extraEvents )
elif event.EventType() == eEventType.EV_PERL:
extraEvents... |
def CheckDateChanges( self ):
d = datetime.fromtimestamp( Log.epochSecs )
self.dateStringNow = d.isoformat(' ')
newMonth = d.month
newDay = d.day
newHour = d.hour
newMinute = d.minute
if newMinute != self.curMinute:
log.info( '{} CheckDateChanges curMinute:{} newMinute:{}'.format(Log.... | The main task of the code is to continuously process events from stdin and other file descriptors using epoll, handle deserialized TxProc objects, manage application events, execute regular tasks, and serialize/send events via sockets until termination conditions (e.g., EOF, errors) are met. It includes error logging, ... | def Run( self ):
while not self.bTimeToDie:
Log.GenerateTimestamp()
if self.bCheckDateChanges: self.CheckDateChanges()
self.StartLoopProcess()
if self.bMainLoopVerbose: log.info( '{} Run waiting for new packet/event frozen:{}'.format(Log.timestamp,self.bFrozen) )
# wait for new events... |
def uploadalerTreshold(self):
indicator='alert_threshold'
for adminlevels in SETTINGS[self.countryCodeISO3]['levels']:#range(1,self.admin_level+1):
trigger_file_path=self.affectedFolder +'affected_' + str(self.leadTimeValue) + '_' + self.countryCodeISO3 + '_admin_' + str(adminlevels) + '_'... | The code's main task is to execute three upload operations: setting an alert threshold, uploading calculated affected data, and uploading a raster file. This method likely handles data processing and transmission for analysis or visualization, coordinating multiple data types for further use in a system. | def upload(self):
self.uploadalerTreshold()
self.uploadCalculatedAffected()
self.uploadRasterFile() |
def is_discrete(probs):
probs = np.array(probs)
if len(probs.shape) == 1:
return enough_duplicates(probs)
elif len(probs.shape) == 2:
for k in range(probs.shape[1]):
if not enough_duplicates(probs[:, k]):
return False
return True
else:
raise Va... | The function `get_calibration_error` computes the calibration error of a model's predicted probabilities against true labels. It calculates the $ L_p $ calibration error, choosing between binning or scaling methods based on input data type. Parameters include the norm $ p $, debiasing flag, and calibration mode ('margi... | def get_calibration_error(probs, labels, p=2, debias=True, mode='marginal'):
"""Get the calibration error.
Args:
probs: A numpy array of shape (n,) or (n, k). If the shape is (n,) then
we assume binary classification and probs[i] is the model's confidence
the i-th example is 1. O... |
def _update(batch):
return_dict, loss = _calculate_loss(batch)
optim.zero_grad()
mem_optim.zero_grad()
loss.backward()
mem_optim.step()
optim.step()
return return_dict
def _eval_model():
model.eval()
###### Valid data
avg_rec = tx.utils.Ave... | This function trains a model over epochs by iterating through batches, performing updates, logging progress at specified intervals, evaluating the model periodically, and saving checkpoints. It maintains average metrics, resets recorders for logging, and ensures the model remains in training mode after evaluations. | def _train_epoch(epoch):
model.train()
step = 0
best_eval_results = np.array([0.0])
avg_rec = tx.utils.AverageRecorder()
for batch in train_data_iterator:
return_dict = _update(batch)
avg_rec.add(return_dict)
if step % config_data.display_steps... |
def decay_length(decay_width, x, m_X, epsilon, decay_dictionary):
gamma = (x * E_0) / m_X
total_decay_width = 0
for decay in decay_dictionary:
weight, mass, visibility = decay_dictionary[decay]
if decay == "hadrons":
weight = Rpp(m_X) * weight
... | The code computes the expected number of detectable events for a particle decay process, considering parameters like decay length, visibility, and cross-section. It iterates over x-values, calculates contributions using decay_length and visible_branching_ratio, applies a numerical check, and aggregates results via dNdX... | def compute_events(N_mu, m_X, epsilon, width, case):
events = np.zeros_like(m_X)
for (i, x) in tqdm(enumerate(xs)):
# if x >= 0.5 and x < 0.504:
length = decay_length(width, x, m_X, epsilon, decay_dictionary) * 100 # cm
visibility = visible_branching_ratio(width, ... |
def _tcp_connect(self):
"""
connect to the remote socket and find the zybo board.
"""
print("tcp connecting..", end="")
connected = False
# try to connect to the TCP Socket
try:
addr = QHostAddress(self._QP_IP)
self._tcpsocket.connectToHost... | The code initializes a TCP socket with specified IP and port, sets up data storage, connects to a server, and configures DMA if possible. It also spawns a QThread with a UDP worker for concurrent data handling, ensuring readiness for data reception and verification. | def __init__(self, ip=QP_IP, port=QP_PORT):
super().__init__()
self._QP_IP = QHostAddress(QP_IP)
self._QP_PORT = port
self.version = 0
# self._BUFFER_SIZE = BUFFER_SIZE
# storage for retrieiving tcp data
self.data = None
# create the tcp socket
s... |
def __BannerAttack(self)->None:
print("\n\n====================================================")
print("==================== Attack AD =====================")
print("====================================================\n")
def DefaultConfig(self, ouput_file:str, format_hash:str) -> dict:
... | This code performs Kerberos exploitation by checking for ASREP and Kerberoastable hashes in Active Directory. It configures hash formats, checks LDAP/SMB for roastable users, and runs John the Ripper to crack hashes if enabled. The task involves hash extraction, validation, and password cracking based on user-configure... | def StartKerbExploit(self,user_config: dict) -> None:
self.__BannerAttack()
config_ASREP = self.DefaultConfig('ASREPHash.hash','--format=krb5asrep')
config_file_kerb = self.DefaultConfig('kerbHash.hash','--format=krb5tgs')
config_ASREP['isHashFound'] = self.ASREP_Roastable_LDAP(config_... |
def evaluate_parse_condition(condition, event):
"""
This function is used to evaluate the junctions, this function would evaluate from the base case then move upward.
:param condition: This is the condition defined in the rule.json
:param event: This is the event stream from the queue
:return: bool
... | The function processes an event stream according to specified rules by evaluating conditions for each event, executing corresponding actions if conditions are met, filtering out invalid events, and outputting the processed results to both console and file. | def process_events(event_stream, rules):
lst = []
for event in event_stream:
for r in rules['rules']:
result = evaluate_parse_condition(r['conditions'], event)
if result:
for action in r['actions']:
event = perform_action(action, event)
... |
def create_customer_managed_key(account_id, key_arn, key_alias, use_cases, reuse_key_for_cluster_volumes, encodedbase64, user_agent):
version = '1.3.0'
# api-endpoint
URL = "https://accounts.cloud.databricks.com/api/2.0/accounts/"+account_id+"/customer-managed-keys"
if use_cases == 'BOTH':
... | This AWS Lambda function handles CloudFormation custom resource creation events by executing actions like creating customer-managed keys, credentials, storage configurations, networks, or workspaces based on input parameters. It logs events, processes requests, captures results in `responseData`, and sends success/fail... | def handler(event, context):
# make sure we send a failure to CloudFormation if the function is going to timeout
timer = threading.Timer((context.get_remaining_time_in_millis()
/ 1000.00) - 0.5, timeout, args=[event, context])
timer.start()
print('Received event: %s' % json.dumps(event))
... |
def padskel(mask):
'''
Runs skimage.morphology.skeletonize on a padded version of the mask, to avoid errors.
Parameters
----------
mask = an opencv image
Returns
-------
skel = a skeleton (boolean array)
'''
mask = cv2.copyMakeBorder(mask,20,20,20,20,cv2.BORDER_CONSTANT... | The code generates a centerline from a binary mask by skeletonizing the mask, identifying key structural features (poles and centroid), and pruning the skeleton to form a simplified central line representation. The output is a 2D boolean array highlighting the centerline. | def create_centerline(mask):
'''
Finds the centerline of a mask
Parameters
---------
mask = an opencv image (should have only one nonzero value)
Returns
-------
centerline = a 2d boolean array (True where the centerline is, False everywhere else)
'''
new_mask=mask[:,:,0... |
def get_pages(self, page_range):
""" Download the page_xml data for a sequence of pages
from Transkribus and process the text of a pages.
Returns a list of page objects (i.e. dicts). """
pages = []
range_length = int(page_range['end'].pageNr) - int(page_range['start'].p... | The main task of the code is to compare the textual content of two sets of pages (original and censored) by extracting words from each and analyzing their differences. It retrieves pages using provided ranges, extracts words with optional line-break handling, and then compares the resulting word lists to identify discr... | def compare_pipeline(self, page_range_original, page_range_censored):
""" Eats a two page range dicts containing two Cts objects (start, end) produced
by the select_range_pipeline() function. """
original_pages = self.get_pages(page_range_original)
censored_pages = self.get_pages(pag... |
def readPlain(array: list[bytes]) -> str:
return binascii.hexlify(array).decode("utf-8")
def readSwapHex(array: list[bytes]) -> int:
return int(readSwapEndianness(array),16)
def readSwapEndianness(array: list[bytes]) -> str:
swap = readPlain(array)
#split (for), reverse([::-1]) and merge(join) all together
return ... | The code parses Bitcoin blocks starting from blk1125.dat to detect Lightning Network (LN) channel transactions. It processes each block's header and transactions, checking for specific script patterns in outputs (e.g., "52...52ae") indicative of LN channel events. When detected, it exits and compiles closed channels in... | def main():
#Starting block (before block 1120 there are no LN transaction for sure)
count = 1125
#count = 0
path = "./"
active_channels = {}
closed_channels = []
start_time = time.time()
while count != -1:
filename = "blk" + "".join(['0' for x in range(5-len(str(count)))]) + str(count) + ".dat"
if not o... |
def TrueProbability(ML_home: float, ML_opposition: float, estimated_bias: float)-> float:
implied_home = Moneyline2Prob(ML_home)
implied_opposition = Moneyline2Prob(ML_opposition)
total_p = implied_home + implied_opposition
vig_A = (total_p - 1)/2
p = implied_home - vig_A + estimated_bias # true pro... | The function calculates the average expected geometric gain for a single Kelly bet in a game. It uses the true probability derived from moneyline odds and an estimated bias, computes the Kelly ratio, and applies the geometric gain formula: (1 + b*X)^true_p * (1 - X)^(1 - true_p), where b is the odds conversion, X is th... | def ExpectedGeometricGain(ML_home: float, ML_opposition: float, estimated_bias: float) -> float:
'''
Average expected geometric gain for one game, single kelly bet
'''
true_p = TrueProbability(ML_home, ML_opposition, estimated_bias)
b = Moneyline2Odds(ML_home)
X = KellyRatio(ML_home, ML_oppositi... |
def _check_events(self):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == py... | The main task of the code is to run a game loop that continuously checks for events, updates game elements (ship and bullets), maintains a 60 FPS frame rate, and renders the screen, creating an interactive game experience. | def run_game(self):
while True:
self._check_events()
self._update_screen()
self.clock.tick(60)
self.ship.update()
self._update_bullets() |
def reAuthenticate(self):
print('Follow link: ')
url = 'https://id.twitch.tv/oauth2/authorize?client_id='+self.client_id+'&redirect_uri=http://localhost&response_type=code&scope='+self.req_scopes
print(url)
auth_code = input('Enter Authorization Code')
url = 'https://id.twitch.tv... | The main task of the code is to authenticate with Twitch by checking for an existing access token stored in a file, loading it if available, and validating its status; if the token is missing or invalid, it triggers re-authentication and validation to obtain or refresh the necessary credentials for Twitch API access. | def tw_authentication(self):
#check if previously given access token is stored
if os.path.exists(self.name+'/tw_token.pickle'):
print('Loading Twitch Access Token From File...')
with open(self.name+'/tw_token.pickle', 'rb') as token:
try:
self.... |
def validateToken(self):
print('Validating OAuth Token...')
headers = {'Authorization': 'OAuth %s' %(self.token)}
r = requests.get('https://id.twitch.tv/oauth2/validate', headers=headers)
print(r.json())
#if the response from the validation request is not 200, then refresh the ac... | This code handles chat message events by checking time intervals to trigger hourly checks, run ads, process commands (with mod checks), and detect spam. It validates tokens, sends Discord links, executes ad runs, and processes user commands like '!ad' while enforcing spam detection for all messages. | def on_pubmsg(self, c, e):
current_time = datetime.now(tz.UTC)
#find the time difference, the difference would be a HH:MM:SS string, so split it by ':' to get a HH, MM, SS list.
hour_difference = str(current_time - self.last_hourly_check).split(':')
time_since_last_ad = str(current_time ... |
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
count = no_of_moves_made(board)
if winner(board) or count == 9:
return True
else:
return False
def player(board):
"""
Returns player who has the next turn on a board.
"""
count = no_of_m... | The code implements the **minimax algorithm** to determine the **optimal action** for the current player on a board. It evaluates all possible actions recursively, calculating their utility by simulating game outcomes. For the maximizing player (X), it selects the action with the highest utility; for the minimizing pla... | def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
if terminal(board):
return None
optimal_action = None
if player(board) == X:
optimal_util = float('-inf')
else:
optimal_util = float('inf')
for action in actions(board):... |
def welcome_message(self):
print('Welcome to my devCodeCamp OOP Project')
def pick_a_side(self):
pick_a_side = int(input('Choose your team: (0) Robots; (1) Dinosaurs'))
if pick_a_side == 0:
print('You chose the fleet of Robots')
return pick_a_side
elif pick_a_side... | The main task of the code is to initiate a battle sequence by displaying a welcome message, allowing the user to select a team, and determining an initial condition via a coin flip to establish game dynamics or turn order. | def start_battle(self):
self.welcome_message()
self.team = self.pick_a_side()
self.flip_coin() |
def parse_rules(data):
# Create a dictionary of bags, with a list of sub bags
bag_rules = {}
for rule in data:
outerBag, contents = rule.split(" bags contain ")
bag_rules[outerBag] = []
if not 'no' in contents:
inners = ([b.split(" ") for b in contents.split(', ')])
... | The main task of the code is to read input data from a file, parse it into structured bag rules, and execute two problem-solving functions (`part1` and `part2`) using these rules. The code processes each line of the input, extracts relevant information about bag containment rules, and applies the parsed data to compute... | def main():
with open(inputfile) as f:
data = f.read().splitlines()
bag_rules = parse_rules(data)
part1(bag_rules)
part2(bag_rules)
return |
def __InGameControls(self, event):
keys = pygame.key.get_pressed()
if event.type == pygame.KEYDOWN:
self.tetromino.TetroControls(event.key)
if event.key == pygame.K_SPACE:
if self.tetromino.Hold(self.tetroHold) == self.tetromino:
... | The code defines a game loop for a Tetris-like game, handling user input, updating the game state, managing tetromino movement and collision detection, checking for line clears and level progression, and rendering the game UI. It processes events like quitting, updates the score and UI, and triggers game over condition... | def GameLoop(self):
global CLOCK, RUNNING, TIME_INTERVAL, STATE
timer = pygame.time.get_ticks()
self.clock.tick(FPS)
self.GameUI.UpdateUI()
for event in pygame.event.get():
if event.type == pygame.QUIT:
RUNNING = False
STATE = None
... |
def __BackgroundAnimation(self):
i, j = 0, 0
self.scene.blit(self.scene.surfImage, (0, 0))
while j < self.__nStarFall:
self.__rndStarTopPosition[j] += self.__rndStarSpeed[j]
self.__rndStarLeftPosition[j] += random.randint(-1, 1)
self.scene.blit(self.__fallin... | This function manages menu state transitions by updating the active scene, handling background animations (except in Login state), and rendering the appropriate menu interface (Login, Main Menu, Game Modes, Score Board, Credits) based on the current menuState value, then updating the display. | def MenuLoop(self):
self.scene.ActiveFrame()
self.__fall += 2
if self.menuState != "Login":
self.__BackgroundAnimation()
if self.menuState == "Login":
self.__LoginMenu()
elif self.menuState == "Main Menu":
self.__MainMenu()
... |
def add(*names):
for name in names:
browser.element('#new-todo').type(name).press_enter()
def assert_todos(*names):
todos.should(have.exact_texts(*names))
def edit(name: str, new_name: str):
return start_edit(name, new_name).press_enter()
def delete(name: str):
todo(name).hover().element('.destr... | This test function verifies the basic workflow of a to-do list application, including adding items, editing, deleting, canceling edits, toggling completion status, and clearing completed tasks. It ensures correct behavior by asserting the expected state of the to-do list after each operation, validating functionality l... | def test_basic_todos_workflow(self):
add('a', 'b', 'c')
assert_todos('a', 'b', 'c')
edit('a', 'a edited')
delete('a edited')
assert_todos('b', 'c')
cancel_editing('b', 'b to be canceled')
toggle('b')
clear_completed()
assert_todos('c') |
def getActualUser():
global ID_ACTUAL_USER
conn = sqlite3.connect('data/field_database.db')
cursor = conn.cursor()
cursor.execute("""SELECT username FROM users WHERE id=?""", (ID_ACTUAL_USER,))
return(list(cursor.fetchall())[0])
def createfield(username):
global logLabel
global logLabel2... | The main task of the code is to create a Tkinter GUI window for user management, allowing users to switch between existing users, create new users, delete users, and view logs. The window includes elements like labels, input fields, a dropdown list of users, and action buttons, with specific styling and platform-specif... | def changeUserWindow():
global logLabel
global choiceListCombo
global actualLabel
userWin = tkinter.Toplevel()
userWin.wm_title("User switch")
userWin.wm_geometry("300x200")
userWin.wm_minsize(300, 200)
userWin.wm_maxsize(300, 200)
if sys.platform == "win32":
userWin.wm_ico... |
def _get_error_message_from_exception(self, e):
""" This function is used to get appropriate error message from the exception.
:param e: Exception object
:return: error message
"""
try:
if hasattr(e, 'args'):
if len(e.args) > 1:
err... | The main task of the code is to detonate a file by retrieving its details from a vault, checking its presence on a server via SHA-256 hash, uploading it if absent, and polling for scan results. It handles errors, validates responses, and returns action statuses or results based on API interactions with a threat intelli... | def _detonate_file(self, param):
action_result = self.add_action_result(ActionResult(param))
params = {'apikey': self._apikey}
vault_id = param['vault_id']
try:
_, _, file_info = ph_rules.vault_info(container_id=self.get_container_id(),
... |
def _make_rest_call(self, action_result, endpoint, params=None, body=None, headers=None, files=None, method="get"):
""" Returns 2 values, use RetVal """
url = BASE_URL + endpoint
self.save_progress(VIRUSTOTAL_MESSAGE_CREATED_URL, url=url)
try:
request_func = getattr(request... | This function submits a URL to VirusTotal for scanning if not already present, checks for existing reports, and polls for results. It handles API requests, error checking, and updates action results with scan status or outcomes. | def _detonate_url(self, param):
action_result = self.add_action_result(ActionResult(param))
params = {'apikey': self._apikey}
params['resource'] = param['url']
# the 'scan' param will tell VT to automatically
# queue a scan for the URL if a report is not found
params['sca... |
def _lookup_file(self, param):
json_key = phantom.APP_JSON_HASH
query_url = FILE_API_ENDPOINT
return self._query_file_url(param, json_key, query_url)
def _lookup_url(self, param):
json_key = phantom.APP_JSON_URL
query_url = URL_API_ENDPOINT
return self._query_file_url... | This function determines the action type from input parameters and executes corresponding handling methods like file lookup, URL/domain/IP queries, detonation, report retrieval, or connectivity tests, then returns the result. | def handle_action(self, param):
"""Function that handles all the actions
Args:
param (dict): Parameters sent in by a user or playbook
Return:
A status code
"""
result = None
action = self.get_action_identifier()
if (action == self.ACTIO... |
def load_meta_file(root, file=None):
if file is None:
file = META_FILE
file = os.path.join(root, file)
if check_integrity(file):
return torch.load(file)
else:
msg = ("The meta file {} is not present in the root directory or is corrupted. "
"This file is automatica... | The function parses and prepares the ImageNet2012 validation images archive by extracting files, verifying integrity via MD5, organizing images into subfolders named by WordNet IDs (wnids), and moving files into structured directories for dataset compatibility. It handles default filenames, loads wnids from a meta file... | def parse_val_archive(root, file=None, wnids=None, folder="val"):
"""Parse the validation images archive of the ImageNet2012 classification dataset
and prepare it for usage with the ImageNet dataset.
Args:
root (str): Root directory containing the validation images archive
file (str, option... |
def check_integrity(fpath, md5=None):
if not os.path.isfile(fpath):
return False
if md5 is None:
return True
return check_md5(fpath, md5)
def parse_devkit_archive(root, file=None):
"""Parse the devkit archive of the ImageNet2012 classification dataset and save
the meta information in... | The main task of the code is to ensure the dataset's directory structure is properly initialized by checking the integrity of a metadata file and parsing required archives. If the metadata file is corrupted or missing, it parses the devkit archive. If the split directory (train/val) doesn't exist, it parses the corresp... | def parse_archives(self):
if not check_integrity(os.path.join(self.root, META_FILE)):
parse_devkit_archive(self.root)
if not os.path.isdir(self.split_folder):
if self.split == 'train':
parse_train_archive(self.root)
elif self.split == 'val':
... |
def verify_str_arg(value, arg=None, valid_values=None, custom_msg=None):
if not isinstance(value, torch._six.string_classes):
if arg is None:
msg = "Expected type str, but got type {type}."
else:
msg = "Expected type str for argument {arg}, but got type {type}."
msg =... | The main task of the code is to initialize an ImageNet dataset loader, handling deprecated download flags, verifying the dataset split, parsing archives, loading metadata, and mapping class identifiers (WNIDs) to human-readable class names while setting up indices for efficient data access. | def __init__(self, root, split='train', download=None, **kwargs):
if download is True:
msg = ("The dataset is no longer publicly accessible. You need to "
"download the archives externally and place them in the root "
"directory.")
raise RuntimeError... |
def debug_initialize_weights(fan_out, fan_in):
"""intialize the weights of a layer with fan_in
incoming connections and fan_out outgoing connections using a fixed
strategy, this will help you later in debugging
"""
# Initialize W using "sin", this ensures that W is always of the same
#... | The code verifies the correctness of a neural network's backpropagation implementation by comparing analytical gradients (from the code) with numerical gradients (computed via finite differences). It creates a small network, initializes parameters, computes gradients using both methods, and checks their similarity. A s... | def check_nn_gradients(Lambda=None):
"""Creates a small neural network to check the backpropagation gradients
Creates a small neural network to check the backpropagation gradients,
it will output the analytical gradients produced by your backprop code
and the numerical gradients (computed using com... |
def reflect_pad(X, padsize):
"""Pre-net padding.
:param X
Input image tensor
:param padsize
Amount by which to pad the image tensor
"""
h = tf.pad(X, paddings=[[0, 0], [padsize, padsize], [padsize, padsize],
[0, 0]], mode='REFLECT')
return h
def relu(X... | The code creates a transformation network for image processing, following Johnson's specifications. It processes input X with convolutional layers, residual blocks for feature learning, and upsampling (via deconvolution or resizing) to generate output. Instance normalization and ReLU activations are used, with scaled_t... | def create_net(X, upsample_method='deconv'):
"""Creates the transformation network, given dimensions acquired from an
input image. Does this according to J.C. Johnson's specifications
after utilizing instance normalization (i.e. halving dimensions given
in the paper).
:param X
tf.Tensor with... |
def imread(path):
"""Wrapper around cv2.imread. Switches channels to keep everything in RGB.
:param path:
String indicating path to image.
"""
img = cv2.imread(path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return img
def imresize(img, scale):
"""Depending on if we scale the image ... | The code trains a neural network to perform image style transfer by combining content and style losses. It uses a pre-trained VGG16 model to extract features, computes Gram matrices for style, and optimizes a transformation network to align content images with the target style. The loss function integrates content simi... | def train(style_img_path, model_name, args):
"""main
:param args:
argparse.Namespace object from argparse.parse_args().
"""
# Unpack command-line arguments.
train_dir = args.train_dir
style_img_path = args.style_img_path
model_name = args.model_name
preprocess_size = args.preproc... |
def train(style_img_path, model_name, args):
"""main
:param args:
argparse.Namespace object from argparse.parse_args().
"""
# Unpack command-line arguments.
train_dir = args.train_dir
style_img_path = args.style_img_path
model_name = args.model_name
preprocess_size = args.preproc... | The function performs neural style transfer using a pre-trained VGG16 model, combining content from the content image and style from the style image. It calculates content loss, style loss, and denoise loss, then iteratively optimizes a mixed image via gradient descent to achieve the desired style while preserving cont... | def style_transfer(args, fst_training,
content_image, style_image,
content_layer_ids, style_layer_ids,
content_img_path, style_img_path, result,
model_name,
weight_content=1.5, weight_style=10.0,
weight_... |
def load_signal(self):
signal_name = self.signal_params['name']
signal_params = self.signal_params['params']
signal_data_path = self.signal_params['data_path']
signal_ticker = self.signal_params['ticker']
self.signal = signal_map[signal_name](
signal_name, signal_da... | The main task of the code is to update or initialize trading-related data entries. If existing data exists, it loads entries, updates positions/profit values, records orders, and saves changes. If not, it creates a new directory, initializes empty DataFrames for positions, predictions, and profit values, then saves the... | def update_entries(self):
self.load_signal()
if self.is_existing_pt():
self.load_entries()
self.update_positions()
self.update_pv()
self.record_existing_open_orders_and_new_orders()
self.save_entries()
else:
self.ma... |
def install_upgrade_required_package(self, project_root, in_venv: bool = False, python=None):
if not python:
python = self.get_python()
packages = [
{
"name": "setuptools",
"command": f"{python} -m pip install setuptools"
}
]
... | The function processes a PWebSM descriptor file by reading its YAML content, installing required packages in a virtual environment, executing start scripts, handling dependencies, and running end scripts to configure or update a project based on the descriptor. | def process_pwebsm_file(self, project_root, file_path: str):
pweb_sm: PWebSM = self.yaml_converter.read_yaml_object_from_file(file_path_with_name=file_path, od_object=PWebSM())
if not pweb_sm:
raise Exception("Invalid descriptor file for PWeb Source Management")
self.install_upgrade_... |
def project_root_dir(self, directory=None):
root_path = FileUtil.getcwd()
if directory:
root_path = FileUtil.join_path(root_path, directory)
return root_path
def get_pwebsm_file_name(self, env=None):
env_postfix = ""
if env:
env_postfix = "-" + env
... | The function `run_pwebsm` locates and validates a PWeb source management file by determining the project root directory, generating the file name based on the environment, checking its existence, and processing it if found. It raises an exception if the file is missing, ensuring proper handling of PWeb source managemen... | def run_pwebsm(self, project_root=None, env=None, directory=None):
if not project_root:
project_root = self.project_root_dir(directory=directory)
pwebsm_file = self.get_pwebsm_file_name(env=env)
pwesm_file_path = FileUtil.join_path(project_root, pwebsm_file)
if not FileUtil.... |
def apply_inventory_effect(player, effect):
if effect['type'] == "add_to_inventory":
bonus = effect.get('bonus')
if bonus:
add_to_inventory(player, bonus)
def apply_health_reduction(player, effect):
global is_running
if effect['type'] == "health_reduction":
amount = effec... | The function `apply_player_effect` applies game effects to a player based on the type specified in the `cell_effect` dictionary, such as adding inventory items, reducing health, teleporting, or initiating monster fights, by calling corresponding helper functions. | def apply_player_effect(player, cell_effect):
if cell_effect:
if isinstance(cell_effect, dict):
if cell_effect['type'] == "add_to_inventory":
apply_inventory_effect(player, cell_effect)
elif cell_effect['type'] == "health_reduction":
apply_health_red... |
def move_direction(direction, row, col):
new_row, new_col = row, col
if direction == 'W':
new_row -= 1
elif direction == 'S':
new_row += 1
elif direction == 'A':
new_col -= 1
elif direction == 'D':
new_col += 1
return new_row, new_col
def check_position(board, r... | The function `move_player` updates a player's position on a board based on a given direction. It checks if the new position is valid and passable, updates the board's symbols, increases the player's life if below 100, and applies any effects from the new cell. The board is returned with updated player position and stat... | def move_player(board, player, direction):
row, col = player['row'], player['col']
new_row, new_col = move_direction(direction, row, col)
if check_position(board, new_row, new_col) and is_passable(board, {'row': new_row, 'col': new_col}):
current_cell = key_for_symbol(board, new_row, new_col)
... |
def Get_center_position(self):
return np.sum(self.position ,axis = 0)
def one_step(self,position,action):
self.get_vector(position,self.numParticle)
self.get_total_force(self.numParticle, action)
self.calculate_tensor(self.numParticle)
self.update(self.numParticle, self.force_tot... | This code simulates an environment step where an agent's action influences the system's state over 200 sub-steps. It calculates a reward based on the displacement of a "center position" between steps, increments a step counter, and terminates the episode after 200 steps. The function returns the observation, reward, te... | def step(self, action : np.ndarray):
done = False
info = {}
self.input_action = action
self.center_position = self.Get_center_position()
for i in range(200):
#self.one_step(self.input_action)
self.one_step(self.position,action)
#self.minis... |
def file_name(file_dir):
label=[]
img = []
path_list = os.listdir(file_dir)
path_list.sort()
for filename in path_list:
if 'mat' in filename:
if 'ROI' in filename:
label.append(os.path.join(filename))
else:
img.append(os.path.join(filename))... | The main task of the code is to train a 3D U-Net model for medical image segmentation using GPU-accelerated CuPy arrays. It loads training/validation data from .mat files, computes statistical normalization parameters, and performs hyperparameter tuning (learning rate, batch size, sigma, beta). The model uses dice loss... | def main():
file = '..//train//'
val = '..//validate//'
trainImgName, trainLabelName = file_name(file)
trainImgList, trainlabelList = [], []
valImgName, valLabelName = file_name(val)
valImgList, vallabelList = [], []
'''
Flip = RandomFlipLayer(flip_axes=[1])
Flip.random... |
def _is_scaffold(x):
for i in range(x.shape[0]):
for j in list(x[i].nonzero()[0]):
if i != j and _contains(x[j], x[i]):
return False
return True
def _contains(row1, row2):
return _is_subset(row2.nonzero()[0], row1.nonzero()[0])
def _remove_zero_vertices(x):
idx = x.an... | The main task of the code is to transform an adjacency matrix into a "scaffold" form by iteratively removing dominated rows/columns until the matrix satisfies the scaffold condition. It fills the diagonal with 1s, zeroes out rows/columns that contain other rows, removes zero-vertex entries, and finally resets the diago... | def core_scaffold(x):
_check_adjacency_matrix(x)
x_res = x.copy()
np.fill_diagonal(x_res, 1)
while not _is_scaffold(x_res):
# for every row, check if it contains other rows
for i in range(x_res.shape[0]):
for j in list(x_res[i].nonzero()[0]):
if i != j and _... |
def populate_event_page(my_scroll):
for i in range(len(all_the_events)):
#print(all_the_events.loc[i])
my_frame = tk.Frame(my_scroll.viewPort)
my_frame.grid(row=i, column=0, sticky='nsew')
this_event_name = tk.Text(my_frame, wrap='word', font=HeaderFo... | Your return
The code initializes a Tkinter GUI with three tabs (Events, Neighborhoods, Twitter) using `ttk.Notebook`. Each tab contains labels and scrollable frames to display dynamic content. It sets up layouts, configures grid weights for responsiveness, and calls functions (`populate_event_page`, `populate_hood_pa... | def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
tabControl = ttk.Notebook(self)
ls_tab1 = ttk.Frame(tabControl)
ls_tab2 = ttk.Frame(tabControl)
ls_tab3 = ttk.Frame(tabControl)
tabControl.add(ls_tab1, text ='Events')
tab... |
def populate_event_page(my_scroll):
for i in range(len(all_the_events)):
#print(all_the_events.loc[i])
my_frame = tk.Frame(my_scroll.viewPort)
my_frame.grid(row=i, column=0, sticky='nsew')
this_event_name = tk.Text(my_frame, wrap='word', font=HeaderFo... | This code initializes a GUI with three tabs (Events, Neighborhoods, Twitter) using Tkinter's ttk.Notebook, sets up scrollable frames for dynamic content loading, and configures layout/grid parameters for each tab's interface elements. | def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
tabControl2 = ttk.Notebook(self)
ls2_tab1 = ttk.Frame(tabControl2)
ls2_tab2 = ttk.Frame(tabControl2)
ls2_tab3 = ttk.Frame(tabControl2)
tabControl2.add(ls2_tab1, text ='Events')
tab... |
def is_complete_graph():
for i in range(num_vertices_and_colors):
for j in range(num_vertices_and_colors):
if i != j:
if adj_matrix[i][j] != 1:
return False
else:
if adj_matrix[i][j] != 0:
return False
return... | The code evaluates the fitness of a graph-coloring solution by counting adjacent node conflicts and comparing the number of colors used to the graph's chromatic number. It calculates conflicts where adjacent nodes share the same color, then determines the chromatic number based on the graph's structure (complete, cycli... | def fitness_func(solution, solution_idx):
"""Calculate the fitness of the solution."""
conflicts = 0
for i in range(num_vertices_and_colors):
for j in range(i + 1, num_vertices_and_colors):
if adj_matrix[i][j] and solution[i] == solution[j]:
conflicts += 1
solution_n... |
def K(a,b):
return radial_kernel(0.5,a,b)
def calc_b(ps, K):
s, s_t, _ = ps[0]
return ind_no_b(s, ps, K) - s_t
def plot(classA, classB, ps, b):
plt.plot([p[0] for p in classA], [p[1] for p in classA],'b.')
plt.plot([p[0] for p in classB], [p[1] for p in classB],'r.')
plt.axis('equal')
xgrid=... | The code implements a Support Vector Machine (SVM) optimization using a kernel method. It generates synthetic data, constructs a kernel matrix, and solves a constrained quadratic optimization to find support vectors (α). It calculates the bias term (b) and plots the decision boundary. The task involves data preparation... | def main():
global t, N
classA, classB = test_gen.test_classes_3()
data_points = test_gen.generate_input_data(classA, classB)
x = [p.coords for p in data_points]
t = [p.target for p in data_points]
C=20
N = len(data_points)
start = numpy.zeros(N)
P = numpy.array([[t[i]*t[j]*K(x[i], x... |
def getCookies(driver):
cookies = {}
for cookie in driver.get_cookies():
cookies[cookie["name"]] = cookie["value"]
return cookies
def getAccountId(driver):
accountsUri = driver.find_element(By.CLASS_NAME, "breadcrumb").find_element(By.TAG_NAME, "li").find_element(
By.TAG_NAME, "a").get_a... | The main task of the code is to download journal pages from a website using an authenticated session. It retrieves cookies and account ID, iterates through pages up to MAX_JOURNALS, constructs API URLs, and calls a helper function to download each page. The process stops if a page fails to download. | def downloadJournals(driver):
cookies = getCookies(driver)
accountId = getAccountId(driver)
for page in range(1, MAX_JOURNALS):
journalPageUrl = "{}/accounts/{}/journal_api?page={}".format(SITE, accountId, page)
logging.info("Trying Page: {}".format(journalPageUrl))
if not downloadJo... |
def getCredentials():
user = USER
if not user:
user = (input("Please enter Email: ") or "").strip()
password = PASSWORD
if not password:
password = getpass.getpass("Please enter Password (Masked): ")
return user, password
def getWebDriver():
driver = None
if not driver:
... | The main task of the code is to automate logging into a website using provided credentials, download journals, and manage browser operations. It retrieves user credentials, launches a browser, logs in, downloads journals, and closes the browser, with error handling for missing credentials and logging each step for tran... | def main():
user, password = getCredentials()
if not user or not password:
raise PermissionError("No Credentials Set. Ensure you set Environment Variables, or type it Interactively.")
logging.info("Launching Browser ....")
driver = getWebDriver()
logging.info("Logging In ....")
login(d... |
def weights_initiate(layers,seed,X_train):
rows,cols = X_train.shape
matrix_wt = []
#Randomizing weights generation
for i in range(len(layers)):
if i==0:
np.random.seed(seed)
m_1 = np.random.randn(layers[i],rows+1)
matrix_wt.append(m_1)
else:
... | The function `multi_layer_nn` trains a multi-layer neural network using gradient descent. It initializes weights, iteratively updates them via backward propagation over specified epochs, computes test set mean squared error (MSE) after each epoch, and returns the final weights, MSE history, and test predictions. Key ta... | def multi_layer_nn(X_train,Y_train,X_test,Y_test,layers,alpha,epochs,h=0.00001,seed=2):
mse = []
matrix_wt = weights_initiate(layers,seed,X_train)
# print(matrix_wt)
for i in range(epochs):
matrix_wt = backward_prop(X_train,Y_train,layers,matrix_wt,h,alpha)
# print(matrix_wt)
pre... |
def check_username(user): #function to check whether entered username is present in the file or not
'''checks username is present in the file or not'''
data=open("usernames//username.txt",'r')
usernames=[]
info=True
index=0
for player... | The main task of the code is to validate user login credentials by checking if the provided username exists in a file, encrypting the input password, and comparing it with the stored encrypted password of the corresponding user. If valid, it proceeds to open the game; otherwise, it displays warnings for invalid credent... | def log_game(entry,password,log_in): #function to check whether the login id is valid or not
'''checks user's login credentials'''
user_name=entry.get()
pass_user=password.get()
if isfile('usernames//username.txt'):
exp,index=check_username... |
def new_flight(time, destination):
Flights_Dict.setdefault(time, destination)
def show_destination(time):
try:
print(Flights_Dict[time])
except KeyError:
print("-")
def cancel_flight(time):
Flights_Dict.pop(time)
def delay_flight(time, delay):
destination = Flights_Dict[time]
hr,... | The main task of the code is to process flight data and execute operations on them. It reads flight details, adds them to a system, and handles commands like showing destinations, canceling, delaying, rerouting flights, and counting flights based on user inputs. | def main():
flights , ops = map(int, input().split())
for _ in range(flights):
flight = input().split()
time, destination = flight
new_flight(time, destination)
for _ in range(ops):
operation = input().split()
if operation[0] == "destination":
show_dest... |
def preprocess_train(self):
# Step 2: Feature Selection
if self.verbose:
print('Selecting features...')
self.dfs['train'] = self.feature_selection(warn=True, **self.dfs['train'])
# Step 3A: Process graph (optional)
if self.use_network:
self.dfs['train']['... | The code preprocesses data for a given set (e.g., train/test) by performing feature selection, optional graph processing, semantic encoding, feature engineering, and concatenation of user, tweet, and metadata features. It applies transformations based on flags (e.g., use_network, use_tweet) and returns processed data a... | def preprocess(self, set_name):
if set_name == 'train':
return self.preprocess_train()
# Step 2: Feature Selection
self.dfs[set_name] = self.feature_selection(
warn=False,
**self.dfs[set_name]
)
# Step 3A: Process graph (optional)
if s... |
def get_data(self, dataset_name: str = None, nrows: Optional[int] = None):
"""Receive the dataset"""
if dataset_name == 'MIB':
config = self.local_file_reader.get_mib_config()
self.dfs = self.local_file_reader.read_mib(
config,
self.label_col,
... | The code processes a dataset through a machine learning pipeline, including data retrieval, preprocessing, classification, test prediction, result grouping (if needed), and evaluation with timing metrics, using either pandas dataframes or alternative methods based on configuration flags. | def run(
self,
dataset_name: str = 'MIB',
nrows: Optional[int] = None
):
"""Process the pipeline"""
# Step 1: Get the input dataset
if self.verbose:
print(f'Getting {dataset_name} dataset...')
self.get_data(dataset_name, nrows)
# Step 2+3:... |
def __make_frequency_dict(self, text):
frequency = {}
for character in text:
if character not in frequency:
frequency[character] = 0
frequency[character] += 1
return frequency
def __make_heap(self, frequency):
for key in frequency:
node... | This function encodes input data into a byte array using Huffman coding. It builds a frequency dictionary (or uses the provided one), constructs a priority queue, generates a Huffman tree, creates binary codes for each character, encodes the data, pads the result for alignment, and converts it to a byte array for effic... | def encode(self, data, frequency_dict=None):
"""
:param data: string to encode
:param frequency_dict: frequencies dict (Optional)
:return: byte array of the encoded result
"""
data.rstrip()
"""
If frequency_dict arrives by parameter, we assign it.
... |
def available(grid):
result = []
for i in range(8):
for j in range(8):
if (grid[j][i] == 0):
result.append(i)
break
return result
def minimax(grid, depth, currentPlayer, alpha, beta):
available_cols = available(grid)
random.shuffle(available_cols)
... | The code trains a machine learning model to predict heuristics by simulating multiple games using a minimax algorithm. For each batch of games, it collects grid states and corresponding heuristic values, then trains the model with mean squared error. The process iterates over batches, updating the model with each batch... | def optimal_data(batches, batch_size, depth):
batch = 0
while (batch < batches):
print(f"Batch {batch + 1}")
final=[]
heuristics=[]
successes = 0
while (successes < batch_size):
print(f"Game {successes + 1}")
mod10 = 2*random.randint(0, 4)
... |
def add_dither(x, level=8):
return x + level * (np.random.rand(*x.shape)*2-1)
def compute_vad(s, win_length=160, win_overlap=80, n_realignment=5, threshold=0.3):
# power signal for energy computation
s = s**2
# frame signal with overlap
F = framing(s, win_length, win_length - win_overlap)
# sum... | This function performs voice activity detection (VAD) on an audio signal. It converts the signal to int16, pads with silence, applies dithering, computes VAD using energy thresholds and sliding windows, applies a median filter to smooth results, and converts frame-based VAD labels to time-stamped speech segments. The o... | def energy_vad(signal, threshold, median_window_length, samplerate=8000):
if signal.dtype != np.int16:
signal = (signal * 2**15).astype(np.int16)
signal = np.r_[np.zeros(samplerate // 2), signal, np.zeros(samplerate // 2)] # add half second of "silence" at the beginning and the end
np.random.seed(3... |
def bound(n, maxi, mini):
if n > maxi:
return maxi
elif n < mini:
return mini
else:
return n
def nearBall(app, x, y):
if distance(x - app.ballX, y - app.ballY) < 100:
return True
else:
return False
def adjust(targetX, targetY, x, y, v= 3):
xTrue, yTrue... | The function `refreshPlrs` updates the positions of all players (home and away) based on the ball's location and team possession. It adjusts each player's coordinates using conditional logic, prioritizing ball proximity and random movement when no ball control is detected. Offsets (`offX`, `offY`) are calculated relati... | def refreshPlrs(app, home, away):
#ballstuff
if app.ballX < app.centerX - 50:
offX = bound((app.ballX - app.centerX), 100, 0)
offY = bound(app.ballY - app.centerY, 80, -80)
else:
offX = bound((app.ballX - app.centerX)*4, 700, 0)
offY = bound(app.ballY - app.centerY, 80, -80)
... |
def findBaller(app):
for pos in app.opposition.players:
if app.opposition.players[pos].hasBall == True:
return pos
def refreshPlayerPos(app):
app.team.players[app.selectedPlayer].coordinates = (app.currPX, app.currPY)
app.team.players[app.selectedPlayer].facing = app.currFacing
refr... | This function manages soccer game mechanics: initiates AI kicks, tracks ball possession between teams, handles possession cooldowns, updates shooting animations with color-coded timing, manages game clock progression, transitions to halftime/game over states, and checks for goals, player collisions, and out-of-bounds e... | def gameMode_timerFired(app):
#AI restart play
if app.kickoff == False and app.oppositionPossession == True:
app.kickDelay += 1
if app.kickDelay == 10:
pos = findBaller(app)
app.opposition.players[pos].facing = 'd'
app.opposition.players[pos].makePass(app, 1)
... |
def get_winner(board, grid_size):
directionX = [1, 0, 1, -1]
directionY = [0, 1, 1, 1]
win_length = 4 if grid_size >= 4 else grid_size
def is_valid(x, y):
return 0 <= x < grid_size and 0 <= y < grid_size
for y in range(grid_size):
for x in range(grid_size):
player = boa... | The code processes a user's move in a game, saves the move, checks for a win/draw, updates player statistics, toggles turns, and triggers an AI move (as 'O') if the AI is the opponent. It handles game outcome logic, updates the board state, and ensures proper game progression. | def perform_create(self, serializer, piece):
print("user move")
serializer.save(piece=piece)
game = serializer.instance.game
board = game.get_board()
# Check for a win after the user's move
winner = get_winner(board, game.grid_size)
if winner == 'X':
... |
def name(pokemon):
nome = jsonPokemon(pokemon)
if nome != None:
return nome['name']
else:
return "???"
def id(pokemon):
ide = jsonPokemon(pokemon)
if ide != None:
return ide['id']
else:
return "???"
def tipo(pokemon):
tipos = jsonPokemon(pokemon)
info_str=... | The code initializes a Pokémon object by stripping leading zeros from the input name and assigning attributes like name, ID, type, weight, height, abilities, and image using corresponding functions. It processes the name to fetch data, ensuring consistent formatting by removing leading zeros before retrieving informati... | def __init__(self,nome="pikachu"):
self.name = name((nome.lstrip('0')))
self.id = id(nome.lstrip('0'))
self.type = tipo((nome.lstrip('0')))
self.weight = Weight(nome.lstrip('0'))
self.height = height(nome.lstrip('0'))
self.abilities = abilities((nome.lstrip('0')))
... |
def _print(self, *args, level = 0):
'''
Print out texts when verbose mode is enabled
'''
if self._verbose == True:
args = list(args)
if level == 1:
args.insert(0, f'{"":4}')
elif level == 2:
args.insert(0, f'{"":8}')
elif level == 3:
args.insert(0, f'{"":12}')
elif level == 4:... | The main task of the code is to construct execution plans by integrating parent and child relationships of a given module. It starts with the module itself, retrieves parent plans, then appends child plans, ultimately adding these combined plans to the execution plan list for structured processing. | def _createExecutionPlans(self, module):
'''
Manage and put together the parent tree and children tree
'''
current_plans = [[module]]
self._print('Checking relationships...')
current_plans = self._getParentPlans(current_plans)
current_plans = self._getChildrenPlans(current_plans)
self._executi... |
def _resetCounter(self):
'''
For each execution plan, resetting both the counter and memory
'''
self._script_counter = {}
def _createExecutionPlans(self, module):
'''
Manage and put together the parent tree and children tree
'''
current_plans = [[module]]
self._print('Checking relationships...... | The main task of the code is to prepare execution plans based on input unit tests and settings. If enabled, it processes each unit test by resetting counters, appending lists directly to execution plans, or generating new plans via _createExecutionPlans for non-list inputs. It then removes duplicate entries from the ex... | def preparePlans(self, list_unit_tests = []):
'''
Preparing the plans according to the settings and list passed.
This function also prepare the execution tree for parents and children possibilities
'''
if self._is_enabled == True:
for unit_test in list_unit_tests:
self._resetCounter()
if isins... |
def preparePlans(self, list_unit_tests = []):
'''
Preparing the plans according to the settings and list passed.
This function also prepare the execution tree for parents and children possibilities
'''
if self._is_enabled == True:
for unit_test in list_unit_tests:
self._resetCounter()
if isins... | The code's main task is to execute unit tests by either preparing a list of tests or using a provided list, running each execution plan, and resetting plans afterward. It checks if unit testing is enabled, prepares plans if a list is given, iterates through execution plans to run them, then resets the plans. | def execute(self, list_unit_tests = None):
'''
Entry point to start the unit tests
Either prepare a list and execute or pass the list as argument to perform both actions at once
'''
if self._is_enabled == True:
if list_unit_tests != None:
self.preparePlans(list_unit_tests)
for ep in se... |
def is_float_list(lst):
"""Determine if object is list of floats"""
if not isinstance(lst, list) or len(lst) == 0:
return False
for elem in lst:
if not isinstance(elem, float):
return False
return True
def is_list_list(lst):
"""Determine if object is list of sublists of f... | This code initializes a Vector object by validating and processing input 'values'. It handles lists (flat or 2D rectangular), integers (for row count), and ranges (start-end). It sets the shape attribute and stores values as a list of lists, ensuring data integrity through type checks and raising errors for invalid inp... | def __init__(self, values):
self.values = []
if isinstance(values, list):
if is_float_list(values):
self.shape = (1, len(values))
self.values.append(values.copy())
elif is_list_list(values) and is_rectangular(values):
self.shape = (... |
def conv_layer(input, filter, kernel, stride=1, layer_name="conv"):
with tf.compat.v1.name_scope(layer_name):
network = tf.compat.v1.layers.conv2d(inputs=input, filters=filter, kernel_size=kernel, strides=stride, padding='SAME')
return network
def Max_Pooling(x, pool_size=[3,3], stride=2, padding='V... | The code implements a DenseNet model for image classification. It starts with a convolutional layer and max-pooling, followed by multiple dense blocks (each with 4 layers) and transition layers to reduce spatial dimensions. A final dense block with 32 layers is applied, followed by batch normalization, ReLU, global ave... | def Dense_net(self, input_x):
x = conv_layer(input_x, filter=2 * self.filters, kernel=[7,7], stride=2, layer_name='conv0')
x = Max_Pooling(x, pool_size=[3,3], stride=2)
for i in range(self.nb_blocks) :
x = self.dense_block(input_x=x, nb_layers=4, layer_name='dense_'+str(i))
... |
def clearallcombo(self):
filesize = self.filelistbox.GetCount()
size = self.annotatelistbox.GetCount()
for i in range(0, size):
self.annotatelistbox.Delete(0)
for i in range(0, filesize):
self.filelistbox.Delete(0)
def drawimage(self, fileindex, annot... | This code deletes a selected annotation from a list, updates associated data structures, and refreshes the UI. It confirms user intent via a dialog, removes the annotation from display and data, and deletes the file entry if no annotations remain. It then resets UI elements and redraws the image with the updated data. | def ondeleteannotate(self, event):
dial = wx.MessageDialog(None, 'Are you sure to delete this censor?', 'Censorface',
wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
result = dial.ShowModal()
if(result != wx.ID_YES):
return
curr_index = self.filelistbox.Ge... |
def showdialog(self, title, message, default = ""):
dlg = wx.TextEntryDialog(self,message, title)
dlg.SetValue(default)
if dlg.ShowModal() == wx.ID_OK:
value = dlg.GetValue()
else:
value = default
dlg.Destroy()
return value
def drawimage(s... | This method modifies the censor thickness for a selected file and annotation. It retrieves user input via a dialog, updates the thickness value in a 2D list, redraws the image with the new thickness, and updates the status bar. If an error occurs during execution, it catches exceptions, displays an error message, and l... | def onmodifythickness(self, event):
try:
curr_index = self.filelistbox.GetSelection()
curr_annotate = self.annotatelistbox.GetSelection()
thickness = int(self.showdialog("Modify Thickness", "Change the censor thickness you want.", "{}".format(self.thickness[curr_index][curr_a... |
def loadScoreboard(scoreboard_path):
try:
# Reading in the scoreboard from a csv file.
# In practice, this would be a SQL Querry to a database.
scoreboard = pd.read_csv(scoreboard_path, index_col=0)
# Ensuring that Points column datatype is integer to enable nume... | This code initializes a Hangman game by welcoming the user, loading data files (ux_data and scoreboard), prompting for the player's name and the hangman's name, loading answer data, and starting the game if the user doesn't quit. It handles file loading errors and logs game actions. | def __init__(self):
print('''WELCOME TO HANGMAN!!!
To quit the game, simply type \'quit\'''')
# User Interaction data
try:
self.ux_data = pd.read_csv(os.path.join(os.getcwd(), 'DATA', 'ux_data.csv'))
except FileNotFoundError:
self.ux_data = None
... |
def _handle_help(self):
if "--help" in sys.argv:
print(f"usage of {sys.argv[0]}")
for flag, default in self.data.items():
type_, message = self.data_type[flag], self.messages[flag]
print(f"\t-{flag} {type_} - default: {default}")
print(f"\t... | This method parses command-line arguments or configuration, handling help flags, environment variables, conditional logic, and validation. It prevents re-parsing, sets internal states, and exits on failure. If verbose is enabled, it activates startup messages. After processing all handlers, it marks parsing as complete... | def parse(self, verbose: bool = {}) -> None:
if verbose:
self.print_at_startup = True
if self.parsed:
raise Exception("There is a saying... If you're parsed you can't be parsed again")
self._handle_help()
self._handle_print()
self._handle_encrypted()
... |
def _estimate_distribution(X, shrink=False, cov_estimator='ledoit_wolf'):
alphas = [1e-3, 1e-2, 1e-1, 1]
mu = X.mean(axis=0)
Sigma = empirical_covariance(X)
if shrink or not _is_posdef(Sigma):
if cov_estimator == 'ledoit_wolf':
Sigma_shrink = ledoit_wolf(X, assume_centered=True)[... | (model_x_knockoff performs FDR-controlled variable selection using Model-X Knockoff methodology. It generates knockoff variables, computes test statistics, determines a threshold based on specified FDR, and returns selected features. Key steps: data standardization, covariance estimation, knockoff generation, statistic... | def model_x_knockoff(X, y, fdr=0.1, offset=1, loss='least_square',
method='equi', statistics=stat_coefdiff_lasso,
shrink=False, centered=True,
cov_estimator='ledoit_wolf', seed=None):
"""Model-X Knockoff inference procedure to control False Discoveries ... |
def get_input(self, text):
return input(text)
def check_csv(self):
if not isfile("blacklist_log.csv"):
log = open("blacklist_log.csv", "w")
writer = csv.writer(log)
writer.writerow(["Application Name", "Application Path"])
log.close()
if not isfil... | The main task of the code is to prompt the user to start monitoring, validate their input (y/n), and either initiate monitoring by calling `check_csv()` and `monitor()` methods or exit if the user selects 'n'. It recursively re-prompts for invalid inputs and returns an exit message when the user chooses to terminate th... | def user_input(self):
user = self.get_input("Would you like to start monitoring? [y/n]\n")
if user.upper() == "Y":
print("Now monitoring your established connections")
self.check_csv()
self.monitor()
elif user.upper() != "N":
print("Please type [y]... |
def getNextDictAP(dict):
all_ap = []
for ap in dict:
value = dict[ap]
if(isBoolean(value)):
all_ap.append(assignNextBool(ap, dict))
elif(isNumber(value)):
all_ap.append(assignNextBin(ap, dict))
else:
all_ap.append(assignNextVal(ap, dict))
return conjunct(all_ap)
def trans(pre, post):
return "(("+pr... | This code generates a Boolean formula representing transitions in a finite state machine (FSM). It iterates through all reachable states, computes transitions to next states using logical disjunctions, and writes these transitions to a file with AND operators. The output file encodes the FSM's transition relations as a... | def gen_R():
all_transitions = []
R_bool = open(parsed_model_file_R_name, "w")
for state in fsm.pick_all_states(fsm.reachable_states):
transitions = []
curr = state.get_str_values()
# print('from')
# print(curr)
# print('to')
post_list = [] # list of all next states
for post_state in fsm.pick_all_state... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.