dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def cek_posisi(self):
head_x, head_y = self.snake_body[0]
return (
head_x < 0 or
head_x >= area_width or
head_y < 0 or
head_y >= area_height or
(head_x, head_y) in self.snake_body[1:]
)
def game_over(self):
global runni... | The code defines a game loop that checks for collisions, updates game elements, and schedules the next iteration. It first checks the snake's position; if a collision occurs, it triggers a game-over state and exits. Otherwise, it processes food, updates snake movement, and recursively calls itself after a delay defined... | def game_loop(self):
if self.cek_posisi():
self.game_over()
return
self.cek_food()
self.snake_movement()
self.after(self.speed, self.game_loop) |
def process_image(path):
#Get contours with wordle information
img = cv2.imread(path)
dim = (1200,1900)
img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray, 255,
cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRES... | The main task of the code is to process an input image by detecting and analyzing its contours, generate data from these contours, visualize the contours on the image, save the result as 'test.png', and finally use the extracted data to solve a Wordle puzzle, returning the solution. | def final_action(image):
img, contours = process_image(image)
data = process_contours(img, contours)
cv2.drawContours(img, contours, -1, (0,255,0), 3)
cv2.imwrite('test.png', img)
return solve_wordle(data) |
def kzq(q, L, Q):
return Q + ((2*np.pi * q)/L)
def Aq(q, L):
frac = 1/L
integ = complex_integrate(L, q, L/12, (11*L)/12)
return frac*integ
def pi_n(m, n, x):
fator = cmath.sqrt(1 - x**2)
frac = 1/fator
aux = s.lpmn(m, n, x)[0]
pi_val = aux[m][n]*frac
return pi_... | The code computes a complex sum involving exponential terms and functions Aq, pi_n, tau_n, and kzq. It iterates over q values, calculates contributions from each, and returns the scaled total. The main task is evaluating a mathematical series with parameters n and z0, likely for wave propagation or signal processing. | def gn(n, z0):
soma = []
total = 0
Q = 0.8*k
primeiroTermoDem = (-2)/(n*(n + 1))
qs = np.arange(-75, (75 + 1))
for q in qs:
k_zq = kzq(q, L, Q)
k_termo = k_zq/k
primeiroTermoSum = Aq(q, L)/(1 + k_termo)
primeiroTermoMul = pi_n(1, n, k_termo) + tau_n(1, n, k_termo)
exponencial = ... |
def get_publishers(review):
"""
Takes a ReviewObj.
Returns a list of potential publishers. Searches using pub_ends, capitalization, and associates.
For reference:
-------------
pub_ends = ['co','company','inc','incorporated','firm','press','group', 'pub','publishers','publishing',
... | The code extracts publisher and person names from text, obscures matches for anonymization, and initializes spans. It uses helper methods to retrieve names and apply obfuscation, storing results in instance variables for further processing. | def __findnames(self):
self.pub_names = get_publishers(self)
self.no_pubs_text = self.__obscure_matches(name = 'pub')
self.person_names = get_names_following_titles(self)
self.no_people_text = self.__obscure_matches(name = 'person')
self.spans = '' |
def make_tokens(self):
self.tokens_raw = word_tokenize(self.full_text)
def make_tidy(self):
#adding space around certain problem punctuation
txt = re.sub(',',' , ',self.full_text)
txt = re.sub(';',' ; ',txt)
txt = re.sub(':',' : ',txt)
txt = re.sub('"',' " ',txt)
... | This code initializes an object to process document metadata and text, extracting entities like title, author, and publisher candidates. It tokenizes text, cleans data, maps extracted candidates to known publishers, and selects top matches for entity identification. | def __init__(self, title, full_text, known_publishers, **kwargs):
# instantiate with metdata from db
self.title = title
self.full_text = full_text
self.known_publishers = known_publishers
self.__dict__.update(kwargs)
self.make_tokens()
self.make_tidy()
se... |
def remove_punct(word, dash = True):
if dash == True:
return ''.join((x for x in word if (x.isalnum()) or (x == '-') or (x=='–')))
def __assign(self):
self.first_name = ''
self.first_initial = ''
self.middle_name = ''
self.middle_initial = ''
self.initials = ''
... | The code initializes a name processing system by splitting the input name into parts, extracting the title, determining gender from the title using a dictionary, and preparing attributes like last name and name parts. It calls methods for gender assignment, name generation, formatting, and variant retrieval, assuming n... | def __init__(self, name):
self.full_name = name
self.name_parts = [x.lower() for x in self.full_name.split()]
self.title = remove_punct(self.name_parts[0])
# ASSUMES ALMOST ALL NEUTRAL TITLES ARE MEN
try:
self.title_gender = title_gender_dict[self.title]
excep... |
def __findnames(self):
self.pub_names = get_publishers(self)
self.no_pubs_text = self.__obscure_matches(name = 'pub')
self.person_names = get_names_following_titles(self)
self.no_people_text = self.__obscure_matches(name = 'person')
self.spans = ''
def __prep_for_collocations(sel... | This code initializes a text processing class by cleaning and tokenizing input text, extracting named entities, preparing data for collocation analysis, and handling obscure matches. It stores original/cleaned text, tokenized versions, and processes named entities and contextual patterns for further linguistic analysis... | def __init__(self, aps_id, txt):
self.review_id = aps_id
self.original_text = txt
self.cleaned_text = preprocess_text(txt)
self.cleaned_toks = word_tokenize(self.cleaned_text)
self.__findnames()
self.coll_toks_ind = word_tokenize(self.__prep_for_collocations())
... |
def download_files_list():
url = f"https://{BUCKET_NAME}/files_list.data"
data_list = requests.get(url, allow_redirects=True)
return data_list
def compare_data(split_text, saved_files):
set_file = {file.file_name for file in saved_files}
set_split_text = set(split_text)
set_diff = set_split_text... | The function downloads data, checks if it's newer than a given date, compares it with existing database records, and saves any new files and their extracted JSON data to the database, returning the last modified date. | def download_and_save_to_database(session, date):
data = download_files_list()
header = data.headers
if header['Last-Modified'] == date:
return date
split_text = data.text.split("\n")
saved_files = session.query(db.File)
new_files = compare_data(split_text, saved_files)
for file in... |
def _isReadable(self):
brs = False
if self._isOpen() and self._breadable :
brs = True
return brs
def _Close(self):
if self._isOpen() :
self._file.close()
self._file = None
self._icursor = -1
self._breadable = False
self._bwriteable = False
self._bappendable = False
d... | This method attempts to open a file for reading, resetting its cursor and block size. It checks if the file exists, handles exceptions by logging errors, and ensures proper closure if failures occur. Returns True on success, False otherwise. | def _rOpen(self, reopen = False):
brs = False
if not self._isReadable() :
self._Close()
if not self._isOpen() or reopen :
if self.Exists() :
try :
self._file = FileIO(self.getFilePath(), 'r')
self._file._blksize = self._package_size
#Reset the File Curso... |
def _isWriteable(self):
brs = False
if self._isOpen() and self._bwriteable :
brs = True
return brs
def _Close(self):
if self._isOpen() :
self._file.close()
self._file = None
self._icursor = -1
self._breadable = False
self._bwriteable = False
self._bappendable = False... | The function _wOpen attempts to open a file for writing, checking writability and existence. It creates the file if it doesn't exist, handles exceptions, sets internal states like block size and writability, and logs errors if failures occur. It returns a boolean indicating success (True) or failure (False) of the open... | def _wOpen(self):
brs = False
if not self._isWriteable() :
self._Close()
if not self._isOpen() :
if self.Exists() :
try :
try :
self._file = FileIO(self.getFilePath(), 'w')
except FileExistsError as e :
#Ignore the File does already exists Ex... |
def clearErrors(self):
self._arr_rpt = []
self._arr_err = []
self._sreport = None
self._serror = None
self._err_code = 0
def _isReadable(self):
brs = False
if self._isOpen() and self._breadable :
brs = True
return brs
def _rOpen(self, reopen = False):
brs = False
if not ... | The code reads a file in chunks, clears previous errors, opens the file if not already open, processes each chunk by decoding and storing non-empty content, handles exceptions by logging errors and closing the file, and returns a boolean indicating read success. It also closes the file in non-persistent mode after read... | def Read(self):
brs = False
#Clear previous Errors
self.clearErrors()
if not self._isReadable() :
self._rOpen(True)
if self._isOpen() :
scnk = None
brd = True
#Reset the Content Buffer
self._scontent = None
try :
while brd :
scnk = self._fil... |
def _isReadable(self):
brs = False
if self._isOpen() and self._breadable :
brs = True
return brs
def _rOpen(self, reopen = False):
brs = False
if not self._isReadable() :
self._Close()
if not self._isOpen() or reopen :
if self.Exists() :
try :
self._file =... | The main task of the code is to read a chunk of data from a file, manage file state (opening/closing), handle read errors, and return a success status. It checks if the file is readable, reads a chunk using `_file.read`, appends non-empty data to `_arr_content`, logs errors if exceptions occur, and closes the file if r... | def readChunk(self):
brs = False
if not self._isReadable() :
self._rOpen(True)
if self._isOpen() :
scnk = None
brd = True
#Reset the Content Buffer
self._scontent = None
try :
scnk = self._file.read(self._package_size)
if scnk != '' :
self._... |
def clearErrors(self):
self._arr_rpt = []
self._arr_err = []
self._sreport = None
self._serror = None
self._err_code = 0
def _isWriteable(self):
brs = False
if self._isOpen() and self._bwriteable :
brs = True
return brs
def _wOpen(self):
brs = False
if not self._isWritea... | The main task of the code is to write content to a file in chunked packages, handling potential errors during the write process. It checks if the file is openable, converts content to bytes, and writes it in segments defined by a package size. The code tracks written bytes, manages partial writes, and logs errors if th... | def Write(self):
brs = False
#Clear previous Errors
self.clearErrors()
if not self._isWriteable() :
self._wOpen()
if self._isOpen() :
#Build the Content String
arrcntnt = bytes(self.getContent(), sys.stdout.encoding)
icntntln = len(arrcntnt)
iwrtstrt = 0
iwrten... |
def fire_bullet(settings: Settings, screen: Surface, ship: Ship, bullets: Group) -> None:
if len(bullets) < settings.bullets_allowed:
new_bullet = Bullet(settings, screen, ship)
bullets.add(new_bullet)
def start_game(settings: Settings, screen: Surface, stats: GameStats, ship: Ship, scoreboard: Scor... | This function handles keyboard input events in a game, controlling ship movement (left/right), firing bullets, starting the game when 'P' is pressed (if inactive), and exiting the game when 'Q' is pressed. | def check_keydown_events(event: Event, settings: Settings, screen: Surface, stats: GameStats, ship: Ship,
scoreboard: Scoreboard, aliens: Group, bullets: Group) -> None:
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving... |
def check_alien_bullet_collisions(aliens: Group, bullets: Group) -> dict:
return pygame.sprite.groupcollide(bullets, aliens, True, True)
def check_high_score(stats: GameStats, scoreboard: Scoreboard):
if stats.score > stats.high_score:
stats.high_score = stats.score
scoreboard.prep_high_score()
... | This function updates bullet positions, removes off-screen bullets, checks for collisions between bullets and aliens, updates the score upon collisions, checks for high scores, and triggers a new alien fleet if necessary. | def update_bullets(settings: Settings, screen: Surface, stats: GameStats, scoreboard: Scoreboard, ship, aliens: Group,
bullets: Group) -> None:
bullets.update()
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
bullets.remove(bullet)
collisions = check_alien_... |
def check_fleet_edges(settings: Settings, aliens: Group) -> None:
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(settings, aliens)
break
def check_aliens_hit_bottom(screen: Surface, aliens: Group) -> bool:
screen_rect = screen.get_rect()
for ali... | The function updates alien movement, checks for edge collisions, and detects if aliens hit the ship or screen bottom. If so, it triggers the `ship_hit` response to handle game state changes like reducing lives or ending the game. | def update_aliens(settings: Settings, stats: GameStats, screen: Surface, scoreboard: Scoreboard, ship: Ship,
aliens: Group, bullets: Group) -> None:
check_fleet_edges(settings, aliens)
aliens.update()
if pygame.sprite.spritecollideany(ship, aliens) or check_aliens_hit_bottom(screen, alien... |
def exit_game(stats: GameStats):
write_high_score(stats)
pygame.quit()
sys.exit()
def check_keydown_events(event: Event, settings: Settings, screen: Surface, stats: GameStats, ship: Ship,
scoreboard: Scoreboard, aliens: Group, bullets: Group) -> None:
if event.key == pygame.K_RI... | This function processes Pygame events to handle user inputs in a game. It checks for quit requests, keyboard presses/releases, and mouse clicks on the play button. Depending on the event type, it triggers actions like exiting the game, controlling the ship, or starting gameplay. The function delegates specific tasks to... | def check_events(settings: Settings, screen: Surface, stats: GameStats, play_button: Button, ship: Ship,
scoreboard: Scoreboard, aliens: Group, bullets: Group) -> None:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_game(stats)
elif event.type == pyg... |
def get_user_id(credential): # get user id from access token
for i in range(len(credential)):
if credential[i] == " ":
username = credential[(i+1):]
break
cursor.execute(f"SELECT * FROM public.users WHERE login = '{username}'")
records = list(cursor.fetchall())
return rec... | The function `update_draft` manages article lifecycle actions (save, publish, delete, revert to draft) with authorization checks. It updates database records, modifies file content, adjusts article status, handles hashtags, and logs events. It ensures only authors can edit/deactivate articles, validates permissions, an... | def update_draft(article_name, action, article, credentials): # main: "/create/{article_name}"
user_id = get_user_id(credentials) # get user id
stop_sessions_check(user_id, 0) # check if administrator stopped sessions
article_desc = authorization_check_draft(credentials, article_name) # get article info
... |
def authorization_check_published(article_name, credentials):
user_id = get_user_id(credentials) # get user id
stop_sessions_check(user_id, 0) # check if administrator stopped sessions
if credentials[0] == '5': # check if user is banned
return exception(status.HTTP_423_LOCKED, "You are banned on ser... | This function updates an article's status in a database based on the 'action' parameter (approve/reject). It checks authorization, updates the article's status, date, and description, clears a review file if approved, or marks it as deleted if rejected. It logs events and returns status updates with article details. | def update_article_status(article_name, action, reason, credentials): # main: "/published/{article_name}"
article_desc = authorization_check_published(article_name, credentials) # get article info
user_id = get_user_id(credentials)
if action == "approve":
date = get_current_date()
cursor.exe... |
def get_user_id(credential): # get user id from access token
for i in range(len(credential)):
if credential[i] == " ":
username = credential[(i+1):]
break
cursor.execute(f"SELECT * FROM public.users WHERE login = '{username}'")
records = list(cursor.fetchall())
return rec... | This function authorizes user access to an article by verifying credentials, checking if the article exists, ensuring it's approved, and confirming user permissions. It returns article details like content, status, ratings, and reviews if authorized, or raises HTTP errors for bans, non-existent articles, or unauthorize... | def authorization_check_article(credentials, article_name): # main: "/archive/{article_name}"
user_id = get_user_id(credentials) # get user id
stop_sessions_check(user_id, 0) # check if administrator stopped sessions
if credentials[0] == '5':
return exception(status.HTTP_423_LOCKED, "You are banned ... |
def get_user_id(credential): # get user id from access token
for i in range(len(credential)):
if credential[i] == " ":
username = credential[(i+1):]
break
cursor.execute(f"SELECT * FROM public.users WHERE login = '{username}'")
records = list(cursor.fetchall())
return rec... | The function handles user reviews for an article by either sending or deleting them. It checks if a user has already reviewed the article, updates or inserts their review into a database and a text file, and logs events. If the action is 'delete', it removes the review and marks it as deleted in the database. The funct... | def send_review(article_name, action, rate, review_text, credentials): # main:"/archive/{article_name}"
user_id = get_user_id(credentials) # get user id
stop_sessions_check(user_id, 0) # check if administrator stopped sessions
article_desc = authorization_check_article(credentials, article_name) # get artic... |
def search_lane_centerline(self, x, y, r):
result = {}
for lane_id in self.lane_ids:
centerline = self.mapAPI.get_lane_as_interpolation(lane_id, 0.05, InterpolationMethod.INTER_METER)[
'xyz_midlane'][:, :2]
if self._is_line_within_area(centerline, x,... | The function `search_static_map` retrieves static map elements like lanes, boundaries, crosswalks, and stop lines within a specified radius `r` around coordinates `(x, y)`. It aggregates these elements into a dictionary and returns them for further processing or analysis. | def search_static_map(self, x, y, r):
result = {}
lanes = self.search_lane_centerline(x, y, r)
boundaries = self.search_lane_boundary(x, y, r)
crosswalks = self.search_crosswalk(x, y, r)
stoplines = self.search_stopline(x, y, r)
result['lanes'] = lanes
result['b... |
def sol(self):
"Return theta1, z1, theta2, z2 given the initial condition."
if self.restart is None:
if self.method == "Radau":
y = solve_ivp(deriv, (0, self.tmax), self.y0, method='Radau', dense_output=True,
args=(self.L1, self.L2, self.m1, self.m... | The code generates and visualizes time-domain and frequency-domain (FFT) plots for two angular variables (theta1 and theta2). It creates 2x2 subplots: time-domain signals and their corresponding frequency spectra, marking detected peaks if enabled. Theoretical angular velocity lines are added under specific parameter c... | def fft_plot(self, show_peak=True, peak_num=2, setpeak=True, threshold=0):
"Return 2*2 plots of time domain and omega domain in terms of theta1 and theta2."
t = self.t
theta1, z1, theta2, z2 = self.sol()
omega, Theta1, Theta2 = self.fft()
if show_peak:
omega1_pval, om... |
def create_domain_snapshot(self): # Creating a snapshot of domains before forward checking
domain_snapshots = {}
for variable in self.problem.variables:
if (not variable.has_value):
domain_snapshots[variable] = variable.domain[:]
return domain_snapshots
def select_un... | This code implements a backtracking algorithm for solving constraint satisfaction problems. It recursively assigns values to unassigned variables, checks for consistency, and uses forward checking to prune domains. If a valid assignment is found, it returns True; otherwise, it backtracks by restoring domain states and ... | def backtracking(self):
length_of_unassigned_variables = len(self.problem.get_unassigned_variables())
if (length_of_unassigned_variables == 0):
return True
domain_snapshots = self.create_domain_snapshot()
var = self.select_unassigned_variable()
self.problem.print_as... |
def defaultdir(snake):
'''
Gets the starting direction to move the snake in so it doesn't immediately die.
'''
neighbour_pos = neighbours(snake["head"])
for pos in neighbour_pos:
if pos in snake["positions"]:
neighbour_pos.remove(pos)
next_pos = random.choice(neighbour_pos)
... | The main task of the code is to update the snake's position during gameplay by moving its head in the current direction, handling edge wrapping, clearing the tail cell, and propagating new positions to body segments. It also checks for collisions with objects in the new head position and schedules the next movement ste... | def movesnake(snake):
'''
Fills and empties cells based on the direction the snake is moving in.
'''
global state
global movedir
global game
global powerups
if movedir == (0, 0): # Set starting direction
movedir = defaultdir(snake)
if state == "PLAYING":
cell = snake[... |
def show_question(question, last_attempt, cid, mid, qpid, quiz, error_message = None,notification=None, previous_question=None):
conn1 = sql.connect('db.sqlite3')
conn1.row_factory = sql.Row
quiz_type = 'Exam'
can_skip = False
if previous_question:
delay_time = time_left_on_question(last_att... | This function processes a user's answer to a quiz question by validating the input type, updating the database with the answer, and redirecting to the next question or displaying an error message. It handles different question types (MCQ, integer, float, etc.), checks for existing answers, and updates or inserts record... | def check(qid, atno, mid, qpid, cid):
conn = sql.connect('db.sqlite3')
conn.row_factory = sql.Row
records = conn.execute("select * from yaksh_questionpaper where id = ?", (qpid,))
for record in records:
quizid = record['quiz_id']
records2 = conn.execute("select * from yaksh_quiz where id... |
def has_questions(qpid):
conn1 = sql.connect('db.sqlite3')
conn1.row_factory = sql.Row
records = conn1.execute("select * from yaksh_questionpaper_fixed_questions where questionpaper_id = ?", (qpid,))
for record in records:
if record:
return "true"
return "false"
def view_module(m... | This function manages the initiation of a quiz attempt by verifying prerequisites such as quiz validity, user eligibility, and prior attempts. It checks if the quiz has questions, hasn't expired, and if the user is allowed to attempt it. If valid, it either starts a new attempt or resumes an in-progress one, rendering ... | def start(qpid, mid, cid, attempt_num=None):
#print("hi")
conn1 = sql.connect('db.sqlite3')
conn1.row_factory = sql.Row
records = conn1.execute("select * from auth_user where username = ?",(session['username'],))
for record in records:
user_id = record['id']
status = has_questions(qpid)
... |
def getYcc(self):
max_hsamp_factor=max(self.hsamp_factor)
max_vsamp_factor=max(self.vsamp_factor)
self.comp=create(None,self.comp_num)
self.comp_width=create(0,self.comp_num)
self.comp_height=create(0,self.comp_num)
self.block_width=create(0,self.comp_num)
self.bl... | This code initializes an image processing class by setting input parameters (image, quality, output path, comment), retrieving image dimensions, and preparing components for processing: YCC conversion, DCT tables, Huffman encoding, and coefficient extraction. It establishes foundational data and methods for subsequent ... | def __init__(self,image,quality,out,comment):
logger.info('initing input image')
self.image=image
self.image_width,self.image_height=image.size
self.quality=quality
self.out=out
self.comment=comment
self.getYcc()
self.initDct()
self.initHuff()
... |
def _internal_decode(self):
i, cd = 1, self.get_next_bit()
while cd > self.maxcode[self.hftbl][i]:
cd = (cd << 1) + self.get_next_bit()
i += 1
j = self.valptr[self.hftbl][i]
j += cd - self.mincode[self.hftbl][i]
return self.huffval[self.hftbl][j]
def exten... | This function decodes AC coefficients using run-length encoding. It processes data in a loop, updating the `zz` array with decoded values. When encountering a zero run (`ssss == 0`), it adjusts the counter `k` based on the run length `r`. For non-zero values, it computes the coefficient using `extend` and `receive` fun... | def decode_ac_coefficients(self):
k = 1
self.zz = [0] * 64
while True:
rs = self._internal_decode()
ssss = rs % 16
r = rs >> 4
if ssss == 0:
if r == 15: k += 16
else: return
else:
k += r
... |
def embedData3(self):
logger.info('embedding data in image by f3')
coeff=self.iJpegE.coeff
byte_embed=len(self.data)
if byte_embed>0x7fffffff: byte_embed=0x7fffffff
logger.info('totally %d bytes to embed by f3'%len(self.data))
bit_embed=byte_embed&1
byte_embed>>=1... | The code's main task is to embed data into an image at different levels (3, 4, or 5) using a password. It initializes data and password attributes, writes image headers, selects the appropriate embedding method based on the 'level' parameter, and finalizes the image writing process. The method delegates specific embedd... | def write(self,level,data,password):
self.data=data
self.password=password
self.iJpegE.writeHeads()
if level=='3': self.embedData3()
elif level=='4': self.embedData4()
elif level=='5': self.embedData5()
self.iJpegE.writeImage() |
def create(value=None, *args):
if len(args) and args[0]:
return [create(value,*args[1:]) for i in range(round(args[0]))]
else: return value
def get_block_count(self):
square = lambda x: x * x
if self.nf == 1:
return square((self.x + 7) / 8)
elif self.nf == 3:
... | This code performs Huffman decoding on image data, processing AC coefficients from multiple components. It decodes MCU blocks, updates prediction values, stores coefficients in a buffer, and checks for EOI (End of Image) termination. The loop continues until all data is processed or EOI is encountered, finalizing the d... | def readImage(self):
logger.info('huffman decoding')
pred = create(0, self.nf)
self.CNT = 0
buff = create(0, 2 * 8 * 8 * self.get_block_count())
pos, mcu_count = 0, 0
while True:
for n_comp in range(0, self.nf):
for cnt in range(self.h[n_comp] ... |
def extractData3(self):
logger.info('extracting data in image by f3')
coeff=self.iJpegD.coeff
i,pos=0,-1
finish,length=0,0
need_extract=0
byte_extract=0
while i<32:
pos+=1
j=pos-pos%64+ZAGZIG[pos%64]
if j%64==0 or coeff[j]==0: c... | The code processes image data by reading headers and image content, then extracts specific data based on the provided 'level' parameter (3, 4, or 5) using corresponding methods. It stores the 'password' but does not use it in the extraction steps. | def read(self,level,password):
self.password=password
self.iJpegD.readHeads()
self.iJpegD.readImage()
if level=='3': self.extractData3()
elif level=='4': self.extractData4()
elif level=='5': self.extractData5() |
def is_product_exception(self, product) -> bool:
if any(word in product.lower() for word in self.exception_goods):
return True
return False
def add_sales_tax(self, index: int, item: Item):
sales_tax = calculate_sales_tax(item.price)
item.price = item.price + sales_tax
... | The code calculates sales tax for non-exception items in an order and applies import tax to imported products. It iterates through each item, checks if it's not an exception, adds sales tax if applicable, and adds import tax if the item is imported. | def calculate_sales_tax(self):
for index, item in enumerate(self.order):
if item is not None:
if not self.is_product_exception(item.name):
self.add_sales_tax(index, item)
if is_product_imported(item.name):
self.add_import_tax(in... |
def restrict(self, embeddings):
num_examples = self.get_tensor_shape(embeddings, 0)
embedding_norms = tf.norm(embeddings, axis=1)
mask = tf.greater(embedding_norms, tf.ones([num_examples]) * self.res)
normalized_embeddings = tf.nn.l2_normalize(embeddings, axis=1) * self.res
retur... | This code initializes a neural network model for processing linguistic elements using embeddings and transformation matrices. It sets up variables for center embeddings, relational embeddings, and context-specific embeddings, applies transformations, and prepares placeholders for input data. The model includes mechanis... | def __init__(self, data, args):
# random initialize the weights
self.data = data
vocab_size = data.vocab_size
self.vocab_size = data.vocab_size
embed_size = self.embed_size = 300
self.res = args.restrict
self.weight = args.weight
rel_length = args.relation... |
def final_position(h_a):
#h_a - height where atmosphere ends (m)
return np.array([0,0,h_a])
def final_velocity(m_s, r_s, h_a): #find final orbital (goal) velcocity of object
#m_s - mass of planet (kg)
#r_s - radius of planet (m)
return np.array([math.sqrt(G*m_s/(r_s + h_a)),0.,0.])
def at_groun... | This function simulates the motion of an object under gravitational acceleration, updating its position and velocity iteratively until it reaches ground level. It calculates acceleration, updates displacement and velocity using time step dt, and returns the final vertical velocity when the object hits the ground. | def get_initial_v(s_0, m_s, r_s, h_a, r_b, m_b, dt):
s = final_position(h_a) #current position variable (m)
v = final_velocity(m_s,r_s,h_a) #current velocity variable (m/s)
t_count = 0 #printing counter
v_store = np.array([])
while not at_ground(s, s_0):
a = accel(m_s,r_s,s[2],v, r_b, m_b) ... |
def filtering_compsci_courses(courses: list) -> (dict, set):
"""Takes out compsci and ics courses from all course list, removes unnecessary information, and returns a dictionary containing individual course dictionaries and a set of all
necessary prerequisites from such courses."""
compsci_courses = dict()... | The main task of the code is to fetch computer science course data via an API, filter and process course prerequisites, and generate course suggestions. It first retrieves data, extracts prerequisites, processes them, and iterates through suggested courses, printing each recommendation. The code combines data scraping,... | def main():
scrape, prereq_set = filtering_compsci_courses(make_api_call())
prereqs(prereq_set)
for suggestion in offer_course_suggestions(scrape):
print(suggestion) |
def prepare_data(df_ma_res, df_ma_trades):
#sort
df_ma_res.sort_values(
by=['pair', 'total_gain'],
ascending=[True, False],
inplace=True)
#remove time zone since it can causes issues sometimes
#set the timezone to None
df_ma_trades['time'] = [ x.replace(tzinfo=None) for x ... | The main task of the code is to process input dataframes (`df_ma_res`, `df_ma_trades`) by preparing them, adding their contents to Excel sheets via `writer`, and generating visualizations/charts linked to the data, all to organize and output analytical results in a structured workbook format. | def process_data(df_ma_res, df_ma_trades, writer):
prepare_data(df_ma_res, df_ma_trades)
add_pair_sheets(df_ma_res, writer)
add_pair_charts(df_ma_res, df_ma_trades, writer) |
def placeButton(self,window):
self.setGeometry(int(self.startPostionX(window)), int(self.startPositionY(window)), int(ArenaButton.buttonSizeX(window)), int(ArenaButton.buttonSizeY(window)))
def stylebutton(self,window):
self.setStyleSheet("""
QWidget {
border: 10px soli... | This code initializes a custom button widget with a name, text, and window. It increments a counter, sets up the button's appearance and position, applies an elastic animation effect, and initializes a settings menu. The main task is to create an animated, stylized button with interactive features in a GUI application. | def __init__(self,name,text,window):
self.name = name
ArenaButton.counter += 1
super().__init__(text,window)
self.placeButton(window)
self.stylebutton(window)
self.anim = QPropertyAnimation(self, b'geometry')
self.anim.setDuration(1000)
self.anim.setEasing... |
def init(self, xd, tfs):
"""Transform xd to canonical space for initialization
Args:
xd (tensor): deformed points in batch. shape: [B, N, D]
tfs (tensor): bone transformation matrices. shape: [B, J, D+1, D+1]
Returns:
xc_init (tensor): gradients. shape: [B, ... | The code computes canonical correspondences of deformed points (xd) by initializing estimates (xc_init), optimizing them via a search (xc_opt), and applying implicit differentiation corrections during training. It uses bone transformations (tfs) and conditional inputs (cond) to refine predictions, ensuring gradient con... | def forward(self, xd, cond, tfs, eval_mode=False):
"""Given deformed point return its caonical correspondence
Args:
xd (tensor): deformed points in batch. shape: [B, N, D]
cond (dict): conditional input.
tfs (tensor): bone transformation matrices. shape: [B, J, D+1, ... |
def get(url) -> dict:
data = {}
result = requests.get(url)
if result:
data = result.json()
return data
def get_pokemon_info(pokemon_name: str) -> dict:
poke_url = f"https://pokeapi.co/api/v2/pokemon/{pokemon_name}"
pokemon = get(poke_url)
return pokemon
def process_pokemon_info(pokem... | This code handles GET requests to fetch Pokémon data from an API. It retrieves the 'name' parameter from the query string, fetches the Pokémon's information using get_pokemon_info, processes the result to extract abilities, and returns them as a JSON response. | def poke_api_view(request):
if request.method == "GET":
pprint(request.GET)
poke_name = request.GET.get("name")
if poke_name:
result = get_pokemon_info(poke_name)
habilities = process_pokemon_info(result)
return JsonResponse(habilities) |
def checkResolutionRequest(self, aircraft, data):
aircraft.type = AircraftCategory.RA
aircraft.advisory = Advisory(AdvisoryType.RA)
aircraft.advisory.isSend = True
aircraft.advisory.alert = data["alert"]
aircraft.advisory.minimalVerticalSpeed = data["minimalVerticalSpeed"]
... | This code processes aircraft messages by handling resolution requests, responses, interrogations, and long squitters. For resolution requests, it checks aircraft type and sends advisories if applicable. For responses, it updates acceptance status. Interrogations trigger long squitter transmission, while long squitters ... | def handleMessage(self, message):
if message.get("type") == MessageType.RESOLUTION_REQUEST.name:
data = message.get("data")
aircraft = self.knownAircrafts[message.get('address')] # type: Aircraft
# print(f"Received RESOLUTION_REQUEST from {aircraft.identification}: {data}")
... |
def gen_jrds(self):
self.max_jrd = {}
self.part_sum_jrd = {}
self.ttl_jrds = 0
#calculating max_jrd for every jrd
for tm in range(len(self.dfs)):
for gm in range(len(self.dfs[tm][0][0])):
jrd, ano, tipo = self.dfs[tm][0][0][gm][5].ite... | The code initializes an object with dataframes (`dfs`), sequence length (`bptt`), and validation flag (`is_valid`). It sets attributes like batch size (`bs`) and calls methods to generate data structures (`gen_jrds`, `gen_def_data`) and process data (`process`), preparing the instance for subsequent operations like tra... | def __init__(self, dfs, bptt, is_valid = False):
self.dfs = dfs
self.bs = len(dfs)
self.bptt = bptt
self.is_valid = is_valid
self.gen_jrds()
self.gen_def_data()
self.process() |
def latlngToGlobalXY(lat, lng):
# Calculates x based on cos of average of the latitudes
x = radius*lng*math.cos((p0.lat + p1.lat)/2)
# Calculates y based on latitude
y = radius*lat
return {'x': x, 'y': y}
def getAllScreenX(global_x):
all_screen_x = []
for i in range(0,len(global_x)):
... | The main task of the code is to convert geographical coordinates (latitude/longitude) from an input file into screen coordinates using global coordinate transformations, then save the resulting x and y screen coordinates as a structured JSON file. The process involves reading tabular data, calculating global and screen... | def createJSONfile(input,output):
df = pd.read_table(input)
all_pos = latlngToGlobalXY(df["latitude"],df["longitude"])
global_x =all_pos['x'].to_numpy()
global_y =all_pos['y'].to_numpy()
df['global_x'] = global_x
df['global_y'] = global_y
dict = {}
dict['x'] = getAllScreenX(globa... |
def _get_post_install_cmd(self) -> List[str]:
return [
" ".join(["\n"]),
*self._parse_kernel_release_cmd(),
" ".join(["\n"]),
*self._copy_vmlinuz_cmd(),
" ".join([""]),
*self._copy_system_map_cmd(),
" ".join([""]),
*... | The function generates a list of shell commands to install a kernel build, including configuring with environment variables, executing make commands, adding post-install steps, creating a kernel.efi image if requested, installing the configuration file, and organizing the install directory structure. | def _get_install_command(self) -> List[str]:
# install to installdir
cmd = [
" ".join(['echo "Installing kernel build..."']),
" ".join(
self.make_cmd
+ ["CONFIG_PREFIX=${SNAPCRAFT_PART_INSTALL}"]
+ self.make_install_targets
... |
def _get_post_install_cmd(self) -> Set[str]:
return [
" ".join(["\n"]),
*self._parse_kernel_release_cmd(),
" ".join(["\n"]),
*self._copy_vmlinuz_cmd(),
" ".join([""]),
*self._make_initrd_cmd(),
" ".join([""]),
]
def _mak... | The main task of the code is to generate a list of installation commands. It includes initial directory setup, post-install steps, optional EFI image creation, configuration file installation, and directory organization. The function aggregates these components into a command list for execution during the installation ... | def _get_install_command(self) -> Set[str]:
# install to installdir
cmd = [
" ".join(['echo "Sorting install directory..."']),
]
# add post install steps
cmd.extend(
self._get_post_install_cmd(),
)
# create kernel.efi if requested
... |
def _configure_compiler(self) -> None:
# check if we gcc or another compiler
if self.options.kernel_compiler:
# at the moment only clang is supported as alternative, warn otherwise
if self.options.kernel_compiler != "clang":
click.echo("Only other 'supported' comp... | The main task of the code is to generate a list of shell commands for building a kernel. It configures the compiler, sets environment variables for kernel source paths, and aggregates subcommands from helper methods to handle file linking, initrd download, ZFS cloning, build cleaning, configuration, compilation, instal... | def get_build_commands(self) -> List[str]:
click.echo("Getting build commands...")
self._configure_compiler()
# kernel source can be either SNAPCRAFT_PART_SRC or SNAPCRAFT_PROJECT_DIR
return [
" ".join(['[ -d ${SNAPCRAFT_PART_SRC}/kernel ] && KERNEL_SRC=${SNAPCRAFT_PART_SRC} ... |
def _link_files_fnc_cmd(self) -> List[str]:
return [
" ".join(["# link files, accept wild cards"]),
" ".join(
["# 1: reference dir, 2: file(s) including wild cards, 3: dst dir"]
),
" ".join(["link_files() {"]),
" ".join(["\tif [ -d ${1}... | The main task of the code is to generate a list of shell commands for a build process, combining environment variable echoes, file linking, initrd downloading, installation steps, and a completion message. It aggregates commands from helper methods like `_link_files_fnc_cmd`, `_download_generic_initrd_cmd`, and `_get_i... | def get_build_commands(self) -> List[str]:
click.echo("Getting build commands...")
return [
" ".join(['echo "PATH=$PATH"']),
" ".join(['echo "SNAPCRAFT_PART_SRC=$SNAPCRAFT_PART_SRC"']),
" ".join([""]),
*self._link_files_fnc_cmd(),
" ".join([""]... |
def forward_prop(self, X):
"""Calculates the forward propagation of the neuron"""
self.__A = self.sigmoid_act(np.matmul(self.__W, X) + self.__b)
return (self.__A)
def gradient_descent(self, X, Y, A, alpha=0.05):
"""Calculates one pass of gradient descent on the neuron"""
dz = A -... | This code trains a neural network by performing gradient descent over multiple iterations, validating input parameters, tracking cost, optionally printing progress, plotting the cost curve, and returning evaluation results after training. | def train(self, X, Y, iterations=5000, alpha=0.05,
verbose=True, graph=True, step=100):
"""Trains the neuron"""
if type(iterations) != int:
raise TypeError("iterations must be an integer")
if iterations <= 0:
raise ValueError("iterations must be a positive i... |
def __set_in_progress(self, value):
self.__inprogpress = value
if value == True:
self.__update_and_publish_availabilitys(new_met_conditions=None, new_unmet_conditions=["not_allready_running"]),
else:
self.__update_and_publish_availabilitys(new_met_conditions=["not_allread... | This code initializes a ROS2 action server with custom callbacks, condition checks, and status management. It sets up goal handling, feedback publication, result processing, and cancellation logic, while monitoring preconditions and advertising action availability through a publisher. | def __init__(
self,
node: Node,
action_type,
action_name,
execute_callback_inner: Callable[[ServerGoalHandle],Any],
conditions: List[str],
*,
callback_group=None,
handle_accepted_callback=default_handle_accepted_callback,
cancel_callback=la... |
def randomPoint(p,s,wp):
probSum = 0
randValue = random.random() # random value between 0 and 1
sumation = 0
for i,q in enumerate(p):
sumation += d(q,s)*wp[i]
res=0
for i, point in enumerate(p):
probSum += wp[i]*d(point,s)/sumation
if probSum > randValue: return i
... | The code implements k-means++ initialization followed by Lloyd’s algorithm for clustering. It selects initial centroids using a probabilistic method to avoid poor initialization, then iteratively refines clusters by assigning points to nearest centroids and recalculating centroids until the total within-cluster distanc... | def kmeansPP(p,wp,k,iter):
print("Running k-means++, to obtain initial centers...")
pc = np.copy(p)
wpc = np.copy(wp)
s1 = random.randint(0,len(p)-1) # pick random starting point
s= np.zeros(shape=(k,p.shape[1]))
s[0] = np.copy(p[s1])
pc = np.delete(pc,s1,0)
wpc = np.delete(wpc,s1)
f... |
def run_key_tests(ciphertext, alphabet):
"""Runs Kasiski and Friedman tests and outputs results"""
kasiski = kasiski_test(ciphertext)
friedman = friedman_test(ciphertext, alphabet)
out = "Kasiski test gives this as the most likely: " + str(kasiski) + "\n Friedman test gives: " + str(friedman)
... | The code cracks a Vigenère cipher by analyzing ciphertext, testing key lengths, generating cosets, suggesting likely letters via frequency analysis, and decrypting using a user-provided key. It prints the ciphertext, runs key tests, prompts for key length, analyzes cosets, and deciphers with the chosen key. | def crack(ciphertext, alpha, eng_freq):
"""Main crack function"""
print("Your cipher text is: " + ciphertext)
out = run_key_tests(ciphertext, alpha)
print(out)
x = int(input("Choose the key length you'd like to try: "))
cosets = make_cosets(ciphertext, x)
for index in range(len(cosets)... |
def timeout(ticks=256): ## timeout for 256 ticks == ~0.01 second delay
for c in range(1, ticks):
for d in range(1, ticks):
pass
return
def write_command(self, cmd):
self.write(const.bram_registers['COMMAND'], cmd)
def serialize_command(self):
self.write_control(const.bus_commands['SERIALIZE'])
def read_stat... | The code performs a OneWire bus search to discover and enumerate all connected devices by executing the SEARCH ROM command. It handles protocol errors, checks for existing devices, and stores unique ROM identifiers in a list. The function returns the count of discovered devices and their addresses, ensuring duplicates ... | def search(self, search_cmd=const.bus_commands['SEARCH_ROM']):
"""
SEARCH ROM [F0h]
The master learns the ROM codes through a process of elimination that requires the master to perform
a Search ROM cycle as many times as necessary to identify all of the slave devices.
Returns the count of all device IDs disc... |
def reset(self):
"""
RESET
Master sends a reset pulse (by pulling the 1-Wire bus low for at least 8 time slots)
and any/all [DS18B20] devices respond with a presence pulse.
NOTE: This MUST be called prior to any ROM commands/device functions as a part of the
necessary initialization process
(exceptions... | This function sends a MATCH_ROM command to target a specific 1-Wire device using its 64-bit ROM address. It resets the bus, writes the address to hardware registers, and waits for the targeted device to respond. If no response is received within a timeout, it logs an error and returns False; otherwise, returns True upo... | def match_rom(self, address):
"""
MATCH ROM [55h]
The match ROM command allows to address a specific slave device on a multidrop or single-drop bus.
Only the slave that exactly matches the 64-bit ROM code sequence will respond to the function command
issued by the master; all other slaves on the bus will wait... |
def basicEda(df):
### Produces the basic information about the dataframe ###
printDfInfo(df)
printDfHead(df)
printDfShape(df)
printDfColumns(df)
printDfDescription(df)
printDfUniques(df)
def categoricalEda(df):
### Runs an EDA for the categorical attributes in the dataframe ###
categoricalAttributes =... | The main task of the code is to perform a comprehensive Exploratory Data Analysis (EDA) by sequentially executing three specialized EDA functions: basicEda, categoricalEda, and numericalEda, which analyze the dataset's structure, categorical variables, and numerical variables respectively, providing a holistic overview... | def eda(df):
### Calls all 3 EDA's (Basic, Categorical, and Numeric) ###
basicEda(df)
categoricalEda(df)
numericalEda(df) |
def load(self):
model_file_name = self.params["model_dir"] + "Batch-A2C_" + self.env_names[0] + ".ptm"
agent_state = torch.load(model_file_name, map_location= lambda storage, loc: storage)
self.actor.load_state_dict(agent_state["Actor"])
self.critic.load_state_dict(agent_state["Critic"])... | The code initializes a reinforcement learning agent for environments with either discrete or continuous action spaces, sets up actor and critic networks (deep or shallow based on input type), trains the agent using collected rewards, and saves models when performance improves. It handles environment interaction, policy... | def run(self):
self.envs = SubprocVecEnv(self.env_names)
self.state_shape = self.envs.observation_space.shape
if isinstance(self.envs.action_space.sample(), int): # Discrete action space
self.action_shape = self.envs.action_space.n
self.policy = self.discrete_policy
... |
def add_item(self):
# Boolean to check whether to add new item to tree view or edit the already existing item in tree view
add = True
data = [] # Declaring list variable to store each item detail to be written to the tree view.
db = sqlite3.connect('./' + self.database_name)
... | The code initializes a GUI for an EPOS system, configuring frames, widgets, and database connections. It reads configuration details, sets up a tree view for item display, connects to a database to retrieve product types, and prepares interfaces for adding items, calculating totals, and processing payments. | def __init__(self):
# list that includes the headings to be displayed in tree view.
self.display_headings = []
# list to hold types of product to be displayed on button
self.product_types = []
# Variable to store the final amount
self.total_amount = 0
# list to... |
def l2_norm(v: np.array) -> np.array:
assert_column_vector(v)
return np.sqrt(v.T.dot(v))
def householder_reflector(hyperplane_vector: np.array) -> np.array:
"""
Householder's reflector matrix
Properties: orthogonal
"""
assert_column_vector(hyperplane_vector)
n = len(hyperplane_vector)
... | This function performs QR decomposition on a square matrix using Householder reflections, transforming the input matrix into an orthogonal matrix Q and an upper triangular matrix R. The method iteratively applies Householder reflectors to zero out subdiagonal elements in R, while updating Q to maintain orthogonality. T... | def qr_decomposition(matrix: np.array) -> Tuple[np.array, np.array]:
"""
Householder reflection method
The simplest, numerically stable QR decomp method.
Be aware of the catastrophic cancellation when determining the Householder mirror.
It's also useful for the linear least squares.
"""
#... |
def vector(x: float, y: float, z: float) -> np.array:
return np.fromiter([x, y, z], dtype=np.float64)
def unit(vector):
# dot(x, x) = ||x|| ^ 2
return vector / length(vector)
def __reflectance(self, cosine: float, refraction_ratio: float) -> float:
# Schlick's approximation for reflectance
r... | This code determines whether to reflect or refract an incoming ray based on material properties and angle of incidence. It calculates reflection/refraction direction, checks if refraction is possible, and returns a scattered ray with white attenuation, prioritizing reflection if refraction is impossible or less likely ... | def scatter(self, ray: Ray, hit_record: HitRecord) -> ScatteredRay:
color = vector(1.0, 1.0, 1.0)
refraction_ratio = (1.0 / self.index_of_refraction) if hit_record.front_face else self.index_of_refraction
unit_direction = unit(ray.direction)
cos_theta = min(np.dot(-unit_direction, hit... |
def scatter(
prng_key,
intersection: Intersection,
lambertian_materials,
metal_materials,
dielectric_materials,
) -> ScatteredRay:
# TODO(smucha): improve disaptch extensibility to multiple material types
return lax.cond(
intersection.material_index < len(lambertian_materials),
... | The code computes the color of a ray in a 3D scene by simulating light scattering through multiple bounces, using probabilistic methods for Lambertian, metal, and dielectric materials. It traces intersections with objects, accumulates hit records, and combines attenuation factors from each scattering event to determine... | def compute_ray_color(
ray_direction,
seed,
ray_origin,
world,
lambertian_materials,
metal_materials,
dielectric_materials,
max_scatter_steps: int = 4,
) -> jnp.array:
ray = Ray(ray_origin, ray_direction)
prng_key = random.PRNGKey(seed[0])
prng_keys = random.split(prng_key, ... |
def vector(x: float, y: float, z: float) -> jnp.array:
return jnp.array([x, y, z], dtype=jnp.float32)
def generate_random_scene(
prng_key,
number_of_spheres: int,
number_of_lambertian_materials: int,
number_of_metal_materials: int,
number_of_dielectric_materials: int,
):
assert number_of_sph... | The code renders a ray-traced image of a randomly generated 3D scene with Lambertian, metal, and dielectric materials. It uses JAX for vectorized ray sampling, accumulates pixel colors across batches, applies gamma correction, and outputs the result as a PPM image. The scene includes 50 spheres and various materials, w... | def main():
seed = 7
aspect_ratio = 3.0 / 2.0
image_width = 800
image_height = int(image_width / aspect_ratio)
channels_num = 3
starting_key = random.PRNGKey(seed)
camera = Camera(
lookfrom=vector(13, 2, 3),
lookat=vector(0, 0, 0),
vector_up=vector(0, 1, 0),
... |
def registration(faceid):
global face_id
global registration_status
global recentactivity
face_id = faceid
# Start capturing video
vid_cam = cv2.VideoCapture(0)
# Detect object in video stream using Haarcascade Frontal Face
face_detector = cv2.CascadeClassifier('haarcascade_frontalface... | The function `myCommandCallback` processes incoming commands by executing specific actions based on the type and value of `cmd.data['command']`, including triggering registration, training data, or image recognition tasks. | def myCommandCallback(cmd):
m = cmd.data['command']
if(isinstance(m, int)):
registration(m)
elif(m == "Register"):
traindata()
elif(m == "recognize"):
recognizeImg() |
def i_can_win_now(self):
options = self.list_by_level(8, self.my_color)
return len(options) > 0, options
def i_will_lose(self):
return not self.i_can_win_now()[0] and self.two_fours_against_me()
def is_winning_attack(self):
options = self.list_by_criticality([5, 4, 3, 2], self.my_color)
... | The code determines the best move in a game by prioritizing immediate winning moves, avoiding imminent losses, executing urgent defensive actions, and defaulting to tree search if no critical moves are found. | def suggest(self):
i_can, move = self.i_can_win_now()
if i_can:
return move
if self.i_will_lose():
return "Giving up"
is_winning, move = self.is_winning_attack()
if is_winning:
return move
is_urgent, move = self.is_urgent_defe... |
def detect_object(self):
detected_obj = self.detect_obj(frame=self.photo_target)
if len(self.objects_tracked) == 0:
# First Object added
for current_obj in detected_obj:
class_id, label, boxes = current_obj
t_cv = self.set_tracker(name=self.tracke... | This code tracks objects in a video frame by either detecting new objects on specific frames or updating existing tracks. It processes ROI checks, labels objects, displays bounding boxes, calculates processing time, and returns the processed image for real-time object tracking. | def track_object_inframe(self, frame, count_frame):
self.count_frame = count_frame
self.photo_target = frame
timer = cv.getTickCount()
if self.count_frame == 1 or count_frame % self.frame_for_detect == 0:
self.detect_object()
else:
self.update_track_objec... |
def _is_changelist(self, request):
opts = self.opts
return request.resolver_match.url_name == "{}_{}_changelist".format(
opts.app_label, opts.model_name
)
def get_changelist_queryset(self, request):
queryset = self._get_queryset(request)
filter = self.get_changelist_f... | This method determines the queryset to return based on the request type. If the request corresponds to a changelist view, it calls `get_changelist_queryset` to fetch the appropriate data. Otherwise, it uses the default `_get_queryset` method. The primary task is to dynamically select and return the correct queryset dep... | def get_queryset(self, request):
if self._is_changelist(request):
return self.get_changelist_queryset(request)
return self._get_queryset(request) |
def __draw_opened_cell(self, canvas, cell):
if cell.is_mine():
self.__draw_mine(canvas, cell)
else:
self.__draw_image(canvas, cell, False, False)
def __draw_marked_cell(self, canvas, cell):
self.__draw_image(canvas, cell, False, True)
def __draw_image(self, canvas, cell, ... | This method determines the visual representation of a cell on a canvas by checking its state: if the cell is open, it draws an opened cell; if marked, it draws a marked cell; otherwise, it draws a default closed cell image. | def __draw_cell(self, canvas, cell):
if cell.is_open():
self.__draw_opened_cell(canvas, cell)
elif cell.is_marked():
self.__draw_marked_cell(canvas, cell)
else:
self.__draw_image(canvas, cell, True, False) |
def __draw_cell(self, canvas, cell):
if cell.is_open():
self.__draw_opened_cell(canvas, cell)
elif cell.is_marked():
self.__draw_marked_cell(canvas, cell)
else:
self.__draw_image(canvas, cell, True, False)
def __check_is_over(self, canvas):
if self.__g... | The main task of the code is to render the game board on a canvas by iterating through each cell in a grid, drawing individual cells using `__draw_cell`, checking if the game is over with `__check_is_over`, and rendering bottom elements via `__draw_bottom` to complete the visual update. | def __draw(self, canvas):
for x in range(self.__rows):
for y in range(self.__cols):
cell = self.__field.get_cells()[x][y]
self.__draw_cell(canvas, cell)
self.__check_is_over(canvas)
self.__draw_bottom(canvas) |
def getKing(self):
# return the position of the KING
return np.where(self.__board == 3)
def isKingOnThrone(self):
# check if the KING is on the throne
king = self.getKing()
return king[0][0] == self.getCenterCoordinate() and king[1][0] == self.getCenterCoordinate()
def nEnemiesCl... | The code checks if a king is captured in a board game by evaluating the number and positions of enemy pieces around the king based on his location: on the throne, near the throne, near the camp, or elsewhere. It returns True if enemy pieces meet specific count and positional criteria, indicating capture, otherwise Fals... | def isKingCaptured(self):
# check if the KING is captured
king = self.getKing()
king_x = king[0][0]
king_y = king[1][0]
# if king is on the edge of the board return False
if king_x == 0 or king_x == self.__size - 1 or king_y == 0 or king_y == self.__size - 1:
... |
def print_board(elements):
for i in range(9):
if i % 3 == 0:
print() # Print newline after every third element
if elements[i] == -1:
print("_", end=" ") # Print underscore for empty tile
else:
print(elements[i], end=" ") # Print the number for non-empty... | The code solves the 8-puzzle problem by taking user-input start and goal states, checking solvability, and using a solver function to find the solution path. It prints the initial board, reports solvability, and displays the number of moves required if solvable. | def main():
global g
start = list()
goal = list()
print("Enter the start state:(Enter -1 for empty):")
for i in range(9):
start.append(int(input()))
print("Enter the goal state:(Enter -1 for empty):")
for i in range(9):
goal.append(int(input()))
print_board(start) # Pr... |
def _get_all_actions(self, data: Any) -> Generator[str, None, None]:
"""Recursively get all action names from workflow data"""
if isinstance(data, dict):
for key, value in data.items():
if key == self.workflow_action_key:
yield value
elif i... | The function updates a GitHub Actions workflow file by identifying newer versions of specified actions, replacing outdated ones, and returning a set of markdown-formatted update records. It parses YAML data, checks each action against available versions, and applies updates if newer versions exist. Errors in parsing or... | def _update_workflow(self, workflow_path: str) -> set[str]:
"""Update the workflow file with the updated data"""
updated_item_markdown_set: set[str] = set()
try:
with open(workflow_path, "r+") as file, gha_utils.group(
f'Checking "{workflow_path}" for updates'
... |
def readImage(self, mazePath: str) -> np.ndarray:
img = cv2.imread(mazePath, 0)
ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
return img
def _setDefaults(self) -> None:
height, width = self.binaryImage.shape
verticalCells = height // self.CELL_SIZE
horizontal... | The code initializes a maze processing class by loading an image, converting it to a binary format, setting default parameters, constructing a graph representation of the maze, and initializing an optional annotator for further processing. | def __init__(self, mazeImagePath: Optional[str] = None):
self.mazeImagePath = mazeImagePath
if mazeImagePath:
self.originalImage = cv2.imread(str(self.mazeImagePath))
self.binaryImage = self.readImage(str(self.mazeImagePath))
self._setDefaults()
self._cre... |
def readImage(self, mazePath: str) -> np.ndarray:
img = cv2.imread(mazePath, 0)
ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
return img
def _setDefaults(self) -> None:
height, width = self.binaryImage.shape
verticalCells = height // self.CELL_SIZE
horizontal... | The method `setMazeImage` loads a maze image from the specified path, converts it to a binary format for processing, initializes default settings, and constructs a graph representation of the maze to enable pathfinding or analysis tasks. | def setMazeImage(self, mazeImagePath: str) -> None:
self.mazeImagePath = mazeImagePath
self.originalImage = cv2.imread(mazeImagePath)
self.binaryImage = self.readImage(mazeImagePath)
self._setDefaults()
self._createGraph() |
def draw_board(self):
center = Point(self.CENTER.x, self.CENTER.y)
size = self.hexagon_size
Q = []
D = {}
hive = []
# draw hive
if self.hive:
for insect in self.hive:
type = insect[0]
pid = insect[2]
hex... | The main task of the code is to render the game's UI by drawing the game board, defining bordered regions (up, left, right, center) using Pygame, and rendering corresponding menus in each region to create an interactive interface for a game. | def display_game(self):
self.draw_board()
# up
pygame.draw.rect(self.display, self.BLACK,
self.rect_up_region, 0)
pygame.draw.rect(self.display, self.WHITE,
self.rect_up_region, 1)
# left
pygame.draw.rect(self.display, se... |
def handle_board_mouse_click(self):
self.hex_selected = Hex(self.hex_hover.q, self.hex_hover.r)
if self.current_player.hex_hand_selected and self.hex_selected:
insect = self.get_insects_in_hex(self.hex_selected)
if insect and insect[2] == self.current_player.id:
... | This function handles mouse clicks in different game regions: it processes board interactions in the center, resets UI elements in the upper region, and manages left/right region actions like deselecting pieces and triggering specific handlers, all while checking if the game is active. | def handle_mouse_click(self):
if self.current_region == 'center' and not self.game_over:
self.handle_board_mouse_click()
if self.current_region == 'up':
if not self.game_over:
self.info_msg = ''
self.possible_placements = None
self.possible... |
def update_stats(self, player):
if player.id == 'p1':
rect = self.rect_left_region
elif player.id == 'p2':
rect = self.rect_right_region
insects = player.non_placed_insects
hexagons = []
queen_bee_count = 0
beetle_count = 0
grasshopper_c... | This code initializes and manages a hexagon-based game loop, handling player input, game state updates, and rendering. It sets up game parameters, processes events like clicks and movements, updates player statistics, and continuously redraws the game screen while maintaining game flow and interactions. | def game_loop(self):
new_game(self.mode, self.level)
self.info_msg = ""
self.hexagon_size = 40
self.current_region = None
self.hex_selected = None
self.hex_hover = None
self.game_over = False
stats = get_game_stats()
self.p1 = stats[1]
self... |
def denoise_signal(args, mix_batch, G_model):
"""
Return predicted clean speech.
mix_batch and G_model: Located on GPU.
"""
X = stft(mix_batch, args.fft_size, args.hop_size)
X_mag = get_magnitude(X).permute(0,2,1)
mask_pred = G_model(X_mag).permute(0,2,1)
mask_pred = mask_pred.unsqu... | This function processes audio batches to evaluate and train a student model against teacher and original models. It denoises inputs, computes SISDR metrics, calculates losses (SISDR or custom), and updates the student model via backpropagation if an optimizer is provided. Results are aggregated and returned as mean SIS... | def run_iter(args, tot_s, tot_x, student_model, ori_student_model, teacher_model, student_optimizer=None, trtt=None):
stu_res = []
tea_res = []
ori_res = []
loss_res = []
for idx in range(0,len(tot_s),args.batch_size):
speech_batch = tot_s[idx:idx+args.batch_size].to(torch.device("cuda"))
... |
def stft(signal, fft_size, hop_size):
window = torch.hann_window(fft_size, device=signal.device)
S = torch.stft(signal, n_fft=fft_size, hop_length=hop_size, window=window)#, return_complex=False)
return S
def get_magnitude(S):
S_mag = torch.sqrt(S[..., 0] ** 2 + S[..., 1] ** 2 + 1e-20)
return S_mag
... | The code trains/evaluates a speech enhancement model by mixing speech with noise, applying STFT, using the model to predict masks, reconstructing speech via ISTFT, and calculating SISDR loss. It iterates through speech and noise batches, computes loss, and performs backpropagation if in training mode. The main task is ... | def run_se(args, model, speech_dataloader, noise_dataloader, is_train=True, optimizer=None):
total_loss = np.zeros(len(speech_dataloader))
noise_iter = iter(noise_dataloader)
for batch_idx, speech_batch in enumerate(speech_dataloader):
try:
noise_batch = next... |
def write_file(file_path, content):
# this right here sucks
out_text = "\n".join([line[2:] for line in content.splitlines()]).lstrip("\n")
path(file_path).write_text(out_text)
def populate_c_template():
make_dir("templates/c")
touch_file("templates/c/input.txt")
write_file("templates/c/main.c",
"""
#include <... | The main task of the code is to create and initialize a directory of project templates for multiple programming languages (C, Python, Rust) by writing a guide file explaining template structure, symlinking rules, and reserved names. It populates template directories, ensures shared input files, and exits after setup. | def populate_templates():
write_file("templates/howto.txt",
"""
This is the directory containing project templates for various
languages.
Each template is a directory, and in that directory are all of the
files and folders for the template that will be copied when making a
new project.
If a templat... |
def check_dir_exists(name):
dir_path = path(name)
if not dir_path.exists():
print("\"%s\" directory not found. Making a new one..." % name)
try:
dir_path.mkdir()
return True # directory created
except:
exit_with_error("Failed to create directory \"%s\"" % name)
elif dir_path.is_file():
exit_with_err... | The code automates setting up a new Advent of Code solution directory by determining the next available day number, prompting for puzzle details, selecting a template, and creating structured folders with symbolic links to input files. It handles existing solutions, directory validation, and template copying to streaml... | def main():
# ensure that all of the directories exist
check_dir_exists("solutions")
if check_dir_exists("templates"):
populate_templates()
# get the paths for the templates and existing solution projects
templates = [t for t in path("templates").glob("*") if t.is_dir()]
solutions = [e for e in path("soluti... |
def _is_collide(self, others):
cur_bubble = (self.center, self.radius)
result = False
for bubble in others:
if bubble is not self and bubble.status == "alive":
oth_bubble = (bubble.center, bubble.radius)
if is_circles_collide(cur_bubble, oth_bubble):
... | This code controls an object's movement with probabilistic direction choices (left, right, or else). It updates position every 200 frames, checks for collisions with bubbles/walls, and adjusts position accordingly. If hitting the roof, it sets the object's status to "dead". The movement logic incorporates collision det... | def move(self, bubbles):
global FRAME_COUNT, BUBBLES
PROB_LEFT, PROB_RIGHT, PROB_ELSE = self.left_prob, 0.2 - self.left_prob, 1 - (self.left_prob + 0.2 - self.left_prob)
choices = ["l"] * int(PROB_LEFT * 100) + ["r"] * int(PROB_RIGHT * 100) + ["e"] * int(PROB_ELSE * 100)
if FRAME_COUNT %... |
def is_left_pressed(self):
return self.is_key_pressed(pygame.K_LEFT)
def is_right_pressed(self):
return self.is_key_pressed(pygame.K_RIGHT)
def is_up_pressed(self):
return self.is_key_pressed(pygame.K_UP)
def is_down_pressed(self):
return self.is_key_pressed(pygame.K_DOWN) | The code determines the direction based on pressed keys by setting dx and dy values (-1 or 1) for left/right (x-axis) and up/down (y-axis). It returns a Point object representing the selected direction, prioritizing key presses to calculate movement coordinates. | def get_direction(self):
"""Gets the selected direction based on the currently pressed keys.
Args:
self (InputService): An instance of InputService.
Returns:
Point: The selected direction.
"""
dx = 0
dy = 0
if self.is_left_pressed():
... |
def refresh_screen():
os.system('cls')
print_logo()
def print_list(item_list):
for i, words in enumerate(item_list):
return i, words
def edit_order_status(picked_order):
refresh_screen()
print(f'"status":{picked_order["status"]}')
status_options = ['preparing', 'out for delivery', 'compl... | The code allows users to edit specific fields of an order dictionary, such as customer details, courier, or status. It displays available fields, prompts for selection, and updates the dictionary accordingly. Special handling is provided for courier selection from a list and status modification via a separate function.... | def edit_dict(picked_order, courier_list):
refresh_screen()
while True:
key_list = ['customer_name', 'customer_address',
'customer_phone', 'courier', 'status']
print_list(key_list)
order_key_index = int(
input('pick the number of the option you want to ed... |
def adamw_optimizer(num_train_steps: int, warmup_ratio: float = .1,
init_learning_rate: float = 3e-5):
"""
Notes
- Compatible only with tensorflow.float32 dtype
"""
return optimization.create_optimizer(
init_lr=init_learning_rate,
num_train_steps=num_train_steps,
num_... | This code trains a model using batched data, shuffling the dataset each epoch. It processes inputs and outputs as tensors, computes loss iteratively with a specified optimizer and loss function, and logs per-batch losses. The training loop runs for a given number of epochs, returning a DataFrame of losses organized by ... | def train(self, encoded_outputs: np.ndarray, text_inputs: Iterable, text_weights: Iterable,
batch_size: int = 4, epochs: int = 100, optimizer = None, evaluation_split: float = 0.,
loss_fn: callable = MeanSquaredError(), **kwargs) -> pd.DataFrame:
if optimizer is None: # Use default AdamW optim... |
def make_slide_content_class(name: str, shapes: SlideShapes):
body = []
for shape in shapes:
if field := make_data_field(shape):
body.append(field)
return ClassDef(
name=name,
bases=[], keywords=[],
body=body,
decorator_list=[dataclass_decorator]
)
def... | This function generates Python classes for a slide and its content, including optional alias classes based on slide notes. It creates a SlideX class with attributes for content and position, and a SlideXContent class for shapes. If the slide has notes matching a regex, it adds alias classes inheriting from the original... | def make_slide_class(slide: Slide, slide_index: int) -> list:
slide_class_name = f"Slide{slide_index}"
content_class_name = f"{slide_class_name}Content"
klass = [
make_slide_content_class(content_class_name, slide.shapes),
ClassDef(
name=slide_class_name,
bases=[Name(... |
def use_default_filename_if_missing(self, nb_filename):
if nb_filename is None:
nb_filename = self.nb_filename
return nb_filename
def read_file(self, nb_filename=None):
nb_filename = self.use_default_filename_if_missing(nb_filename)
assert os.path.exists(nb_filename)
... | The main task of the code is to process an IPython notebook file by reading its content, parsing its structure (cells, metadata, format), and optionally writing the processed notebook back to the file. It uses a default filename if none is provided, processes the notebook data, and returns a dictionary with the filenam... | def process_nb_file(self, nb_filename=None, b_write_file=False):
# TODO : see if use_default_filename_if_missing() is necessary here;
# read_file() calls it too
nb_filename = self.use_default_filename_if_missing(nb_filename)
# read the content of the file
self.nb_node = s... |
def send_data(self, cmd, content):
payload = cmd + " " + content
encoded = bytearray(payload.encode("utf-8"))
length_of_encoded = len(encoded)
prefix = str(length_of_encoded) + " "
encoded[0:0] = prefix.encode("utf-8")
try:
self.connection.send(encoded)
... | The code handles user login by validating username and password format, checking against a database, and authenticating the user. It enforces alphanumeric characters, length limits, and bans, then sets login status, retrieves user data, disconnects existing sessions, joins default channels, loads permissions, and logs ... | def __login(self, content):
try:
username = content.split(" ")[0]
password = content.split(" ")[1]
except IndexError:
self.send_data("!error", "invalid info provided")
return
if not Client.check_if_contains_only_alphanumeric(username):
... |
def send_data(self, cmd, content):
payload = cmd + " " + content
encoded = bytearray(payload.encode("utf-8"))
length_of_encoded = len(encoded)
prefix = str(length_of_encoded) + " "
encoded[0:0] = prefix.encode("utf-8")
try:
self.connection.send(encoded)
... | The code registers a new user by validating the username (alphanumeric, max 16 chars) and password (max 24 chars), creating the account if valid. On success, it sets login status, joins the default channel, loads permissions, sends a welcome message, and logs the registration. Errors are reported for invalid input, exi... | def __register(self, content):
try:
username = content.split(" ")[0]
password = content.split(" ")[1]
except IndexError:
self.send_data("!error", "invalid info provided")
return
if not Client.check_if_contains_only_alphanumeric(username):
... |
def __cmd_help_login(self):
help_string = """
=========================================
| Usable commands are: |
| * !login <username> <password> |
| * !register <username> <password> |
=========================================
""".strip()
self.send_data("!box", help... | The main task of the code is to continuously receive and process incoming data from a network connection. It reads data in chunks, extracts message lengths, ensures full data reception, decodes and parses the received data, handles connection errors, and terminates the connection upon disconnection or invalid data, whi... | def __loop_receive(self):
self.__cmd_help_login()
try:
buffer = bytearray()
while True:
buffer += self.connection.recv(16)
length_as_string = buffer.decode("utf-8").split(" ", 1)[0]
length_of_length = len(length_as_string) + 1
... |
def makeGameDataFrame(teamStats, gameData):
###list that will have game data
result = []
##nested for loop that will go through
##each day
for month in range(4,8):
for day in range(1,31):
schedules = mlb.games(2021,month,day)
games = mlb.combine_games(schedules)
... | (The code merges 2021 team batting and pitching statistics into a unified dataset, prepares normalized game data columns, trains a predictive model using this data, and generates predictions for games on June 12, 2021. It combines ERA, WHIP, K/9, AVG, OBP, and SLG metrics from both teams, scales features, constructs a ... | def main():
##pulling data as a data frame
teamBatting = team_batting(2021)
teamPitching = team_pitching(2021)
teamPitching = teamPitching[["teamIDfg", "Team","ERA","WHIP","K/9"]]
teamBatting = teamBatting[ ["teamIDfg","AVG","OBP","SLG"]]
teamStats = teamPitching.merge(teamBatting)
teamSta... |
def initial_grounding(self, mentions):
# mentioned objects from the expression
obj_mentions = mentions["objects"]
# dictionary to store lists of associated grounding objects
grounded = defaultdict(list)
# store ungrounded relations in a list
ungrounded = []
# cand... | The main task of the code is to construct a directed graph representing candidate spatial relations between objects in a scene based on input expressions. It uses initial grounding to identify objects, processes spatial relations iteratively, decomposes complex relations, matches candidates when possible, and prunes in... | def relate(self, mentions):
"""
Relates objects in the scene based on spatial relations mentioned in the input expression.
Parameters:
- mentions: A dictionary containing mentions from the input expression.
Returns:
- candidate_graph: A directed graph representing the c... |
def get_distance(self, x1, x2):
return math.sqrt((x1[0] - x2[0])**2 + (x1[1] - x2[1])**2)
def reset(self):
data = None
while data is None:
try:
data = rospy.wait_for_message('scan', LaserScan, timeout=5)
except:
pass
print("New Goa... | The code updates the robot's target position if the new goal is beyond a specified threshold distance. It then resets the environment, uses a predictive model to generate actions, and iteratively executes these actions in a loop until the task is completed, ensuring continuous navigation toward the updated target. | def goal_callback(self, goal_data):
temp = [goal_data.target_pose.pose.position.x, goal_data.target_pose.pose.position.y]
if self.get_distance(self.target, temp) > FRONTIER_THRESH:
self.target[0] = goal_data.target_pose.pose.position.x
self.target[1] = goal_data.target_pose.pose.... |
def add_signal(self):
self.signals.append(self.sinewave)
self.signals_names.append(self.signalname)
self.ui.comboBox_choosesignal.addItem(
self.signals_names[self.signal_ID])
self.draw_summition()
def removesignals(self):
for i in range(0, len(self.signals_names)):
... | This code initializes a GUI application for signal processing, setting up UI elements like graphs, checkboxes, and input fields. It connects user interactions (e.g., sliders, buttons) to functions for drawing signals, adjusting parameters, and handling file operations. The code prepares plotting tools, initializes sign... | def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.graphChannels = [
self.ui.graphicsView_sample, self.ui.graphicsView_recover]
self.setChannelChecked = [self.ui.checkBox]
self.channel... |
def compute_harris_response_map(
image_bw: np.ndarray,
ksize: int = 7,
sigma: float = 5,
alpha: float = 0.05
) -> np.ndarray:
"""Compute the Harris cornerness score at each pixel (See Szeliski 7.1.1)
Recall that R = det(M) - alpha * (trace(M))^2
where M = [S_xx S_xy;
S_xy S_... | Your return The main task of the code is to implement the Harris Corner detector by computing a normalized Harris response map, applying non-maximum suppression with a 7×7 kernel to extract interest points, and removing border points. It returns up to `k` interest points' coordinates (x, y) and their confidence scores ... | def get_harris_interest_points(
image_bw: np.ndarray,
k: int = 2500
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Implement the Harris Corner detector. You will find compute_harris_response_map(),
nms_maxpool_pytorch(), and remove_border_vals() useful.
Make sure to normalize your respons... |
def encode(string):
"""Function encoding string, take in string, converts it to bytes, encodes using base64, then decodes bytes back to
string and return result"""
string_in_bytes = str.encode(string)
return base64.standard_b64encode(string_in_bytes).decode()
def decode(string):
"""Function decoding... | The main task of the code is to run an interactive menu loop allowing users to encode/decode text, generate passwords, view logs, or exit. It repeatedly prompts for a function choice, executes the corresponding action (e.g., calling encode(), decode(), pwd_generator(), or log_return()), and handles input validation. Th... | def main():
is_on = True
while is_on:
choice = input("Please select the function (encode/decode/password generator/logs) or type quit to exit: ").lower()
if choice == "exit":
is_on = False
elif choice == "encode":
not_encoded_text = input("Please enter text you wo... |
def set_beginning_poz(self):
if self.DNA[0][0] >= len(self.DNA[0]):
start_position = random.choice(self.myGarden.free_start_positions)
else:
start_poz_index = self.DNA[0][0]
start_position = self.DNA[0][start_poz_index]
self.DNA[0][0] += 1
w... | The main task of the code is to simulate a monk raking a garden by moving through sand areas, counting raked spots, and managing start positions. It iterates through possible starting points, attempts to rake in a direction, tracks successful raking progress, and updates the garden's state. If movement fails (e.g., get... | def rake_garden(self):
turn_index = 1
# Turn:
while self.num_of_raked_places < self.myGarden.num_of_sand_places:
if len(self.myGarden.free_start_positions) > 0:
self.set_beginning_poz()
else:
break
# ak je vobec mozne z danej... |
def filterCurrentPixel(self):
center = len(self.mask)//2
pix = [self.currentPixel[0],self.currentPixel[1],self.currentPixel[2]]
summed = [0, 0, 0]
for y in range(0, len(self.mask)):
for x in range(0, len(self.mask[0])):
maskValue = self.mask[x][y]
... | The code processes each pixel in an image grid by iterating through rows (y) and columns (x), applying a filter to the current pixel via `filterCurrentPixel()`, and advancing to the next pixel using `nextX()` and `nextY()`. After completing all pixels, it prints "100.00%" and "Done" to indicate task completion. The mai... | def filterImage(self):
for y in range(0, self.sizeY - 1):
for x in range(0, self.sizeX - 1):
self.filterCurrentPixel()
self.nextX()
self.nextY()
print("100.00%")
print("Done") |
def num_allowed_dice(score, opponent_score):
"""Return the maximum number of dice allowed this turn. The maximum
number of dice allowed is 10 unless the sum of SCORE and
OPPONENT_SCORE has a 7 as its ones digit.
>>> num_allowed_dice(1, 0)
10
>>> num_allowed_dice(5, 7)
10
>>> num_allowed... | The code simulates a turn-based game between two players using their respective strategies. Each strategy determines the number of dice rolled based on current and opponent scores. The game alternates turns, updating scores via `take_turn`, and checks if a player has met or exceeded the goal. If so, it returns the winn... | def play(strategy0, strategy1):
"""Simulate a game and return 0 if the first player wins and 1 otherwise.
A strategy function takes two scores for the current and opposing players.
It returns the number of dice that the current player will roll this turn.
If a strategy returns more than the maximum al... |
def _get_rotation_direction(self, robot_yaw):
"""
Get the current rotation direction of the robot.
Parameters:
robot_yaw (float): yaw of the robot in degree
Returns:
rotation (int): +1 -> left; -1 -> right
"""
rotation = self._calc_angle_change(r... | The main task of the code is to process laser scan data to detect and update depth jumps (discontinuities) in the environment. It uses both single-scan analysis and comparisons between consecutive scans to identify obstacles or changes in depth. The results are stored, debug data is optionally written to files, and val... | def _process(self, scan, movement, robot_yaw):#, rotation):
"""
Starts the process of determing and updating the depth jumps using the given parameters.
Parameters:
scan (Scan): laser scan information to process
rotation (int): rotation direction of robot for given scan
... |
def _process(self, scan, movement, robot_yaw):#, rotation):
"""
Starts the process of determing and updating the depth jumps using the given parameters.
Parameters:
scan (Scan): laser scan information to process
rotation (int): rotation direction of robot for given scan
... | The code processes depth sensor data in real-time by visualizing depth jumps and depth discontinuities, updating visualizations at a specified frequency, handling queued sensor data through a processing function, and saving debug information including average processing time and historical data for analysis. | def run(self):
angle_change = 0
last_time = 0
gap_visualisation_gnt = GapVisualiser('Depth Jump Sensor')
gap_visualisation_single_scan = GapVisualiser('Depth Discontinuities Single Scan')
while not rospy.is_shutdown():
if self.odom_available and self.scan_available:... |
def get_dates(start, end,
today, yesterday,
thisweek, thismonth, thisquarter, thisyear,
lastweek, lastmonth, lastquarter, lastyear):
start = start.strftime("%Y-%m-%d")
end = end.strftime("%Y-%m-%d")
if today:
start, end = get_dates_today()
elif yesterday... | The main task of the code is to summarize daily note log data from 'YYYY-MM-DD.md' files within a user-specified time period (e.g., today, this week, last quarter). It uses parameters like `from_`, `to`, and temporal keywords to define the analysis range, extracts relevant log data from the given path, and stores the r... | def dailylog(log, path, out,
from_, to,
today, yesterday,
thisweek, thismonth, thisquarter, thisyear,
lastweek, lastmonth, lastquarter, lastyear):
"""Summarize daily note log data
Multiple options are provided for specifying the time period. Only the
daily log da... |
def main_position_trade(direction,avg_price,volume):
# returns main position TXID
price = avg_price
if direction not in [_BUY_,_SELL_]:
raise Exception('Invalid parameter')
return trade(direction,price,volume,_K_CURR_)
def orderFillCheck():
#returns true if main order has filled, false if no... | The code executes a trade (buy/sell) by opening a position, waits for it to fill, and then closes the position using an opposite-direction order if successful. If the initial trade doesn't fill, it cancels the order. It manages transaction IDs, sends status updates, and handles position closure logic based on order exe... | def make_trade(direction,volume,price,calcprice):
global mainTXID,closeTXID, stoplosscount,closedirection
if direction == _BUY_:
opp_direction = _SELL_
else: # Must be _SELL_
opp_direction = _BUY_
closedirection = opp_direction
mainTXID = main_position_trade(direction,price,volume)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.