dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def _skip_ch_space(ch, fp) -> str:
if ch and ch not in ' \t\n\r':
return ch
return _skip_space(fp)
def _skip_space(fp) -> str:
while True:
ch = fp.read(1)
if not ch:
raise JSONEOFError('unexpected EOF')
if ch not in ' \t\n\r':
return ch
def _load_str(... | This function parses JSON data from a file pointer, handling objects (dictionaries), arrays (lists), booleans, null, strings, and numbers. It processes tokens sequentially, validates structure, and constructs Python data types using the provided `object_pairs_hook` for custom object creation, returning parsed values an... | def _load_obj(ch, fp, *, object_pairs_hook) -> Tuple[Value, str]:
if ch == '{':
ch = ''
pairs = []
while True:
ch = _skip_ch_space(ch, fp)
if ch == '}':
return object_pairs_hook(pairs), ''
if pairs:
if ch != ',':
... |
def check_similar_movies_in_cache(movie_id):
return similar_movies_cache.get(movie_id) is not None
def build_query_similar_movies(movie_id):
query = f"SET @{MOVIE_ID} = {movie_id};\n"
query += 'SELECT'
for property in MOVIE_DETAILS_WITH_ID:
query += f" {property}"
if property != MOVIE_DE... | The function retrieves similar movies for a given ID by checking a cache. If cached, it returns the stored data; otherwise, it queries the database, caches the result, and returns it, optimizing performance by minimizing redundant database calls. | def get_similar_movies(movie_id):
if check_similar_movies_in_cache(movie_id):
print("Found movie in cache")
return similar_movies_cache[movie_id]
else:
print("Didn't found movie in cache")
query = build_query_similar_movies(movie_id)
similar_movies_json = get_movies_from_... |
def get_fresh_data(self):
return create_strategy_instance_from_string(self.chosen_strategy, self.pair, self.interval,
self.lookback_time, Constants.NO_START_DATE, Constants.NO_END_DATE,
api_key=self.public_ke... | This code initializes a trading bot with parameters like trading pair, strategy, and API keys. It sets up data validation, logging, and a loop to continuously apply the chosen trading strategy, using either simulation mode or live trading based on input flags. | def __init__(self, pair, chosen_strategy, quantity, interval, public_key="", private_key="", is_simulation=True):
# variables initialization
self.buy_price = 0
self.public_key = public_key
self.pair = pair
self.private_key = private_key
self.usd_amount = float(quantity)
... |
def play_sound(sound):
fire = pygame.mixer.Sound(sound)
fire.play()
pygame.time.set_timer(end_sound, end_sound_time)
def reset(reason="life lose"):
global game_start, player_lives, score, gui_no, other_gui, loaded, stage_x, stage_y, first_time, meter_limit
global gui_no, level_complete
if reason... | This function handles collision detection between the player and objects in a game level. It adjusts scoring, modifies meter values, manages key collection states, and controls movement restrictions based on collision outcomes. It also resets locker states and movement flags when collisions end, ensuring proper game me... | def level_collide(obj_rect, locks, collects=-1, points=0, is_key=-1):
global right, collided, locker, mv_right, mv_left, mv_down, mv_up, score, destroy_meter, key_collected
global meter_limit
rect1 = pygame.Rect(player_x-player_w/2, player_y-player_h/2, player_w*0.8, player_h*0.8)
rect2 = pygame.Rect(ob... |
def key_press_handle(key):
global right, left, shift, other_gui, up, down, f_pressed
if key[pygame.K_d] or key[pygame.K_RIGHT]:
right = True
left = False
if key[pygame.K_a] or key[pygame.K_LEFT]:
left = True
right = False
if key[pygame.K_RSHIFT] or key[pygame.K_LSHIFT]:... | This function initializes the game by setting the display background based on the 'loaded' state, processes keyboard input for both pressed and released keys, and handles events to manage game interactions. | def game_init():
if loaded:
display_surface.fill((18, 16, 18))
else:
display_surface.fill((0, 0, 0))
keys = pygame.key.get_pressed()
key_press_handle(keys)
key_release_handle(keys)
event_handling() |
def check_bounds(rect):
if (0 < stage_x + rect[0] + rect[2] < w) and (0 < stage_y + rect[1] + rect[3] < h):
return True
def calculate_player_pos(enem_x, enem_y):
global slope_e, dx_e
dx_e = player_x - enem_x
dy = player_y - enem_y
rad = math.atan2(dy, dx_e)
angle_e = math.degrees(-rad) +... | This function draws and manages level elements (bricks or level_objects) by updating their positions, handling collisions, and spawning bullets. It checks bounds, adjusts positions, performs collision detection, and removes elements that are too small, with specific logic for enemy bullet spawning when num=1. | def draw_level_builders(num):
global bricks, level_objects
rem = []
elems = []
if num == 0:
elems = bricks
elif num == 1:
elems = level_objects
for x in elems:
if not check_bounds(x[0].rect):
pass
angs = calculate_player_pos(x[0].x, x[0].y)
x[0... |
def game_init():
if loaded:
display_surface.fill((18, 16, 18))
else:
display_surface.fill((0, 0, 0))
keys = pygame.key.get_pressed()
key_press_handle(keys)
key_release_handle(keys)
event_handling()
def write_text(text, x=w/2, y=h-150, font_name=GameArt.fonts[0], size=14, color=(2... | This code manages a game's GUI by displaying menus, controls, credits, and level completion screens. It handles mouse interactions, button clicks, and sound effects for menu navigation, transitioning between different game states like arcade mode, campaign loading, and in-game actions. | def gui_loader():
global sound_play, other_gui, game_start
game_init()
x_ = w/2
y_ = h/2
mous_pos = pygame.mouse.get_pos()
if other_gui:
if gui_no == 2:
write_text("**********A simple game made using python*********", x=330, y=340, size=20)
write_text("Art downloa... |
def draw_background():
global bgr_y, bgr_y2, background_loader, background_loader2
background_loader.get_image()
background_loader2.get_image()
display_surface.blit(background_loader.image, background_loader.rect)
display_surface.blit(background_loader2.image, background_loader2.rect)
background... | The main task of the code is to render a game stage by conditionally drawing either an initial background or a loaded version with additional elements. If `loaded` is false, it draws a standard background; if true, it draws an alternate background, two level builders (indices 0 and 1), and enemies, likely updating the ... | def draw_stage():
if not loaded:
draw_background()
else:
draw_background2()
draw_level_builders(0)
draw_level_builders(1)
draw_enemies() |
def linear_sequence(fd, s):
difference = []
sequence = []
sequence = s
difference = fd
b = 0
arithmetic_sequence = []
for x in range(0, len(sequence)):
arithmetic_sequence.append(difference[0]*(x+1))
if sequence[0] - arithmetic_sequence[0] == 0:
b = 0
else:
... | The code determines the type of a numerical sequence (linear, quadratic, cubic, etc.) by calculating successive differences between terms. It checks if differences at each level are constant, then uses corresponding functions to generate and print the nth-term formula for the identified sequence type. | def nth_terms():
sequence = input('Enter your sequence, with numbers seperated by a space (up to quintic sequence): \n')
numbers = []
numbers = sequence.split()
numbers = [int(i) for i in numbers]
first_difference = []
second_difference = []
third_difference = []
forth_difference ... |
def count(self):
"""
Updates tracks of people in video, counts finished tracks
"""
self._add_new_people()
self._count_finished_tracks()
def visualise(self, frame):
"""
Visualise tracks and optical flow
"""
# print statistics in top left corner
... | The code processes video frames in real-time to track and count people using optical flow and detection. It updates tracking, detects keypoints, counts individuals, visualizes results, and saves frames on key presses. The loop terminates on ESC, finalizes tracking, and outputs the total number of people passed. | def run(self):
while True:
# read frame from video source
ret, frame = self.cap.read()
if not ret:
break
# measure time
start = time.clock()
# optical flow update - fast
self.tracker.update(frame)
... |
def find_farthest_point(self, points:[], p:{}=None) -> {}:
max_sq_dist = 0.0
farthest_point = None
dist_point = self.center if p is None else p['data']
for point in points:
sq_dist = self._sq_dist(dist_point, point['data'])
if sq_dist > max_sq_d... | The code constructs a coreset (a representative subset) of input points by iteratively selecting the farthest points from a dynamically updated center. It initializes with two farthest points, computes an initial radius and center, then refines these until all points lie within the radius scaled by (1+ε). The coreset g... | def coreset_construct(self, points:[]) -> None:
first_point = points[0]
p1 = self.find_farthest_point(points=points, p=first_point)
p2 = self.find_farthest_point(points=points, p=p1)
self.radius = self._dist(p1['data'], p2['data']) / 2.0
self.center = (np.array(p1['data'... |
def find_farthest_point(self, point:[]=None) -> {}:
max_sq_dist = 0.0
farthest_point = -1
if point is None:
for i in range(len(self.points)):
sq_dist = self._dist2_wc_idx(i)
if sq_dist >= max_sq_dist:
max_s... | The code constructs a coreset by iteratively selecting and adjusting support vectors using farthest-point and nearest-point strategies. It initializes with two farthest points, computes kernel matrices, and updates coefficients to maintain a radius constraint. The loop adjusts coefficients or adds/removes points based ... | def coreset_construct_with_away_steps(self) -> None:
first_point = self.points[0]
pair1 = self.find_farthest_point(first_point)
pair2 = self.find_farthest_point(self.points[pair1['idx']])
# first two support vectors
self.core_indices.append(pair1['idx'])
self.co... |
def find_farthest_point(self, points:[], p:{}=None) -> {}:
max_sq_dist = -1.0 # init negative to be smaller than zero
farthest_point = None
dist_point = self.center if p is None else p['data']
for point in points:
sq_dist = self._sq_dist(dist_point, point['d... | This code constructs a coreset (a representative subset) of input points by iteratively selecting the farthest points from a dynamically updated center. It initializes the coreset with two points, computes the initial radius and center, then repeatedly adds the farthest point until all remaining points lie within a rad... | def coreset_construct(self, points:[]) -> None:
first_point = points[0]
p1 = self.find_farthest_point(points=points, p=first_point)
p2 = self.find_farthest_point(points=points, p=p1)
self.radius = self._dist(p1['data'], p2['data']) / 2.0
self.center = (np.array(p1['data'... |
def get_pkgs():
"""Retrieves packages from the packages file"""
try:
prepare(error=args.no_write)
except Exception:
abort(f"No packages list file. Create {args.file} before running.")
with args.file.open() as f:
return [
x for x in f.read().splitlines(keepends=False)... | The code's main task is to remove specified packages from a list of installed packages. It retrieves the current package list, removes each package in the input list, saves the updated list, and triggers a refresh. Error handling ensures an empty list is used if retrieval fails. | def uninstall(packages: list[str]):
try:
pkgs = get_pkgs()
except Exception:
pkgs = []
for package in packages:
pkgs.remove(package)
save_pkgs(pkgs)
refresh() |
def exit():
"""Gracefully exits"""
sys.exit(0)
def print_list():
print('\n'.join(get_pkgs()))
def refresh():
path = site.getusersitepackages()
ask(f"This will delete all installed packages in {path} before attempting to install all packages picked up by {__package__}")
shutil.rmtree(path)
p... | The code handles command-line arguments to perform package management tasks: installing, uninstalling, updating, listing, or refreshing packages based on flags like --quiet, --verbose, --help, --list, --refresh, --remove, and --update. It modifies installation commands, validates inputs, and executes corresponding acti... | def main():
if args.quiet:
INSTALL_CMD.append('-q')
if args.verbose:
INSTALL_CMD.append('-vvv')
if args.help:
parser.print_help()
exit()
if args.list:
print_list()
if args.refresh:
refresh()
if args.remove:
if not args.packages:
... |
def filter(request):
divisions_list= Division.undeleted_objects.values('name').distinct().order_by('name')
center_profit_list= Product.undeleted_objects.values('Profit_center').distinct().order_by('Profit_center')
planning_list= Product.undeleted_objects.values('planning').distinct().order_by('planning')
... | The function duplicates calendar data by deleting existing entries owned by 'marwa' for a specific product, then recreates them with the same details but under the new owner. It copies holidays, work schedules, and associated cycles, updating references to ensure data integrity. Finally, it triggers functions to genera... | def duplicate_calendar(request,division,product):
#Delete custom holidays
custom_holidays = HolidaysCalendar.undeleted_objects.all().filter(product_id = product,owner = 'marwa')
custom_holidays.delete()
##Delete custom workday
work = WorkData.undeleted_objects.all().filter(product_id = product,owner... |
def smoothing_calculate(df_data,calendar_type,product):
# make holidays and cycle_data as global varibale to reduce access to
global holidays, cycle_data
if calendar_type == 'official':
# we use holidays in is_in_open_hours function
holidays = HolidaysCalendar.undeleted_objects.values_... | The main task of the code is to handle a POST request for creating or updating production needs data. It collects form inputs, validates that "Freeze_end_date" is filled for each "Smooth_Family", processes the data using a smoothing calculation function, and saves the results along with a versioned shopfloor and cycle ... | def create_needs(request,division,product,planningapproval):
if request.method=='POST':
id = request.POST.getlist('index')
# get inputs values
division = request.POST.getlist('division')
profit_centre = request.POST.getlist('profit_centre')
order = request.POST.getlist('orde... |
def filter(request):
divisions_list= Division.undeleted_objects.values('name').distinct().order_by('name')
center_profit_list= Product.undeleted_objects.values('Profit_center').distinct().order_by('Profit_center')
planning_list= Product.undeleted_objects.values('planning').distinct().order_by('planning')
... | The code processes and calculates key performance indicators (KPIs) for production planning, including cycle times, logistics stock, and production capacity. It validates planning data, filters by version, updates cycle times from user input, computes metrics using helper functions, and renders a dashboard with visuali... | def kpis(request,division,product,planningapproval,come_from,version_number):
# initialization
demand_prod_planning.week_count=None
demand_prod_planning.week_count_axis_x=None
demand_prod_planning.month_count=None
demand_prod_planning.month_count_axis_x=None
cycle_time_kpi.cycle_mean=None
c... |
def propername(game, name, player):
while name == "":
name = input("Enter a proper player "+player+" name("
+game.discs[int(player)]+"): ")
return name
def display_board(game):
board = np.flipud(game.mat)
## print("-"*(5+game.cols*3+3))
## for i in range(game.rows):
## ... | The code implements a menu-driven interface for a two-player disc-based game (e.g., Connect Four). It handles game setup (rows, columns, win conditions), player name input, turn management, move validation (drop/pop), win/draw checks, and restart logic. The loop allows players to choose actions, enforce input constrain... | def menu():
sameplayer = False
while True:
game = Game()
while True:
rows = input("How many rows(3-20): ")
if rows.isdigit() and 3<=int(rows)<=20:
game.rows = int(rows)
break
while True:
cols = input("How many columns(3-... |
def check_move(board,row,col): #check if position is filled/empty
if board[row][col] != 0: #position is filled
return False
return True
def apply_move(board,turn,row,col,rot): #place marble and rotate
insert(board,turn,row,col) #place marble
rotate(board,rot) #rotate board
return board
def c... | The function determines the computer's move in a game based on the difficulty level. At level 1, it randomly selects a valid move. At levels 2-3, it prioritizes winning moves, blocks player victories, and for level 3, selects the best move using a scoring system. It ensures the computer either wins, prevents player win... | def computer_move(board,turn,level): #determine computer move
if level == 1: #level 1
rot = random.randint(1,8) #random rot value
while True:
row = random.randint(0,5) #random row value
col = random.randint(0,5) #random col value
if check_move(board, row, col): #i... |
def display_board(board): #display board
print(" 8 1")
print(" \u2190 \u2192")
print(" "*2,end='')
for j in range(len(board)):
print(j,end=' ')
print("\n"+" "*2+"-"*(len(board)*2-1))
for i in range(len(board)): #formating display board
if i == 2:
row =... | The code provides a menu-driven interface for a 6x6 game, allowing users to play with a friend or computer (three difficulty levels) or exit. It validates input, initializes the game board, alternates turns between players/computers, applies moves, checks for victory, and handles game restarts or exits based on user in... | def menu(): #menu function
play = True
while play:
game_board = np.zeros((6,6),dtype=int) #create 6x6 board
player = random.randint(1,2)
print("1. Play with friend")
print("2. Play with Computer(level 1: Easy)")
print("3. Play with Computer(level 2: Medium)")
pr... |
def centrality_to_dataframe(G, cen_type="all"):
if(cen_type == "all"):
#Get values of Centrality
deg_cen = nx.degree_centrality(G)
eigen_cen = nx.eigenvector_centrality(G)
betweeness_cen = nx.betweenness_centrality(G)
#Extract list to append
eigen_cen_vals = [eigen_ce... | The function combines centrality metrics from a graph with top venue publication counts, merges them into a DataFrame, renames indices using node identifiers, and returns the integrated dataset for analysis. | def centrality_top_venue_dataframe(G):
df_centrality = centrality_to_dataframe(G)
df_top_venue = no_top_venue_dataframe()
df_centrality["No.Publication in Top Venue"] = df_top_venue["No.Publication in Top Venue"]
df_centrality = df_centrality.rename(index = lambda x: find_name_with_pid(x))
return(df... |
def parse_workers(workers_csv_path):
workers = []
with open(workers_csv_path, "rb") as f:
reader = csv.DictReader(f, delimiter=",")
for i, line in enumerate(reader):
workers.append(WorkerDesc(**line))
return workers
def split_worker_sets(all_workers):
learners = [w for w in all_workers if w.job ==... | The main task of the code is to launch distributed training components (actors and learners) across multiple worker sets. It parses worker configurations, initializes TensorFlow clusters, runs actor tasks on each worker while handling failures, and executes learner processes across all worker sets. The code tracks and ... | def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
all_workers = parse_workers(FLAGS.workers_csv_path)
worker_sets = split_worker_sets(all_workers)
# run actors in each worker set
failed_actors = []
for w_set in worker_sets:
tf_cluster = to_tf_cluster(w_set)
task = 0
for worker in w_set.ac... |
def get_url(url: str, headers: Dict = {}, params: Dict = {}):
if params:
return requests.get(url, headers=headers, params=params)
return requests.get(url, headers=headers)
def filter_repository_by_owner(
repositories: List[Dict],
backup_only_owner_repos: str,
token: str = None,
) -> List[Dic... | The function fetches GitHub user repositories via API pagination, extracts metadata (name, owner, privacy), filters by specified owners, converts data to JSON, and uploads it to an S3 bucket using Boto3. It returns the filtered repository metadata list. | def get_metadata(
token: str,
backup_only_owner_repos: str,
bucket_prefix: str,
bucket_name: str,
boto3_session: boto3.Session,
) -> List[Dict]:
metadata = []
max_per_page = 100 # Max value accepted by github api
my_headers = {"Authorization": f"Bearer {token}"}
page = 1
param... |
def get_metadata(
token: str,
backup_only_owner_repos: str,
bucket_prefix: str,
bucket_name: str,
boto3_session: boto3.Session,
) -> List[Dict]:
metadata = []
max_per_page = 100 # Max value accepted by github api
my_headers = {"Authorization": f"Bearer {token}"}
page = 1
param... | The function `download_repos` downloads GitHub repositories as archives (e.g., ZIP files) using the GitHub API, authenticated with a token. It retrieves repository metadata, iterates through each repository, and constructs URLs to fetch the archive. Successful responses are uploaded to an S3 bucket specified by `bucket... | def download_repos(
token: str,
backup_only_owner_repos: str,
bucket_prefix: str,
bucket_name: str,
boto3_session: boto3.Session,
ext: str = "zip",
ref: str = "",
) -> None:
metadata = get_metadata(
token,
backup_only_owner_repos,
bucket_prefix,
bucket_nam... |
def extract_indeed(page):
"""
Scrape the job listings page on Indeed.com and return the parsed HTML.
"""
try:
scraper = create_scraper()
url = f'https://ca.indeed.com/jobs?q=developer&l=canada&start={page}'
scraper.get(url)
soup = BeautifulSoup(scraper.page_source, 'html.... | The main task of the code is to scrape job data from Indeed by iterating through pages (0–400, step 10), introducing random delays to avoid detection, transforming extracted data into a structured list, and storing it in MongoDB. The script also generates a pandas DataFrame for potential CSV export, though it is commen... | def main():
joblist = []
for i in range(0, 400, 10):
print(f'Getting page,{i}')
time.sleep(random.uniform(2, 10))
c = extract_indeed(0)
transform(c, joblist)
df = pd.DataFrame(joblist)
# df.to_csv('jobs.csv')
update_mongo(joblist)
print("script finished running... |
def load_data(traindir, valdir,augmentation=False):
#TODO: Find out the correct transformation
transformation='none'
train_transform = {
'none' : transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])... | The main task of the code is to train and evaluate deep learning models (VGG16, ResNet variants, EfficientNet, Inception) for multi-label classification. It loads datasets with weighted sampling, initializes models with custom heads, uses BCEWithLogitsLoss and SGD optimizer, trains with validation, saves checkpoints, a... | def main(args):
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler(args.ckp_dir + '/' +args.model+".log"),
logging.StreamHandler()
]
)
#Step1. CPU or GPU
device = torch.device... |
def des_nodes(G,i):
"""Returns destination airports for an airport in a graph/ network of airports
Takes the 2 arguments: graph/network of a airports, airport whose destinations needs to
identified
Args:
G= graph/network of airports
i=airport whose destinations needs... | The code generates rerouting options for a disruptee airport by evaluating alternative airports based on proximity, network overlap, and disruption impact metrics. It calculates values like change in disruption value, network proportion, and airline proportion for each candidate airport, aggregates them into a reroutin... | def rerouting_options(df,df1,i,j,G1,c1, c2, p, dis, dt, filename):
"""Returns excel file with rerouting options for a disruptee and the reouting metric
component values
Takes the 10 arguments: two dataframes, disruptee, disruptee equation value,graph/ network of airports
two cutoff values, ... |
def testSplit(nodeToSplit, atrbValues):
'''identifies splits
calculates info gain for each
identifies best and splits on that'''
informationGains = {}
for atrbName in atrbValues:
location = attributes.index(atrbName)
#fills a set for each attribute value with the numb... | The function recursively splits a decision tree node by selecting the attribute with the highest information gain, creates child nodes for each split, removes the used attribute from the list, and processes each child recursively until no attributes remain or further splitting yields no information gain, marking nodes ... | def fillLevel(node, atrbValues):
if(node == None):
return
splitOn, infoGain = testSplit(node, atrbValues)
if(infoGain == 0.0):
return
makeSplit(node, splitOn, atrbValues)
atrbValues.pop(splitOn)
#if no new attributes to split on, return as leaf node
if atrbValues == {}:
... |
def readIn(file):
attributes = []
data = {}
with open(file, 'r') as csvfile:
csvreader = csv.reader(csvfile)
attributes = next(csvreader)
attributes.remove("Day")
attributes.remove("class")
count = 1
for row in csvreader:
row.pop(0)
... | The code constructs a decision tree from a dataset ('weather_play.csv'), determines possible outcome values, initializes a tree structure with a root node, processes attribute values for splitting, and prints the resulting tree structure. | def main():
print("Starting decision tree making")
global attributes
#data, attributes = readIn('agaricus-lepiota.csv')
data, attributes = readIn('weather_play.csv')
global outcomeValues
outcomeValues = outcomeValues(data)
#print(data)
ourTree = Tree()
root = Node(data)
ourTree.... |
def create_frames(self, h):
"""Adds h row frames to the GUI environment."""
self.frames = []
for _ in range(h):
frame = Frame(self.root, bg='blue')
frame.pack(side='bottom')
self.frames.append(frame)
def create_buttons(self, w):
"""Adds w buttons to th... | This code initializes a grid-based environment for pathfinding or search algorithms, setting up UI components like frames, buttons, and walls. It configures search parameters, initializes counters for explored paths and dirt, and prepares a test environment. The constructor also prints the grid dimensions and calls the... | def __init__(self, root, width, height):
self.dirtCount = 0
self.frames = None
self.path = None
self.searchType = searchTypes[0]
self.searchEngineSet = False
self.costFunc = costFunctions[0]
self.explored = None
self.done = True
self.solution = Non... |
def setSearchEngine(self, choice):
"""sets the chosen search engine for solving this problem"""
self.searchType = choice
self.searchAgent = VacuumPlanning(self, self.searchType)
self.searchAgent.generateSolution()
self.searchEngineSet = True
self.done = False
def update_e... | The code runs the environment for a specified number of time steps, updating the environment state periodically with a set delay. It checks if the environment is done or if execution should stop, then updates the environment and triggers a GUI refresh. If in auto-mode with remaining tasks, it recursively restarts the r... | def run(self, delay=0.3):
"""Run the Environment for given number of time steps,"""
if (self.searchEngineSet == False):
self.setSearchEngine(args['searchType'])
delay = 0.5
else:
delay = 0.2
delay = 0.05
self.running = True
wh... |
def set_decoder(self, val):
three_val_input(self._decA, self._decB, self._decC, val)
def set_mux(self, val):
three_val_input(self._muxA, self._muxB, self._muxC, val)
def read_input(pin):
return 1 - int(pin.is_pressed) | The function `read_square` reads data from a specific cell in a grid by controlling a decoder for the row and multiplexers for the column. It selects the appropriate multiplexer (m1_out or m2_out) based on the column index (0-5 or 6-11) and returns the corresponding input value. | def read_square(self, row, col):
#the row is controlled by the decoder
self.set_decoder(row)
#the column is controlled by the muxes
self.set_mux(col % 6)
#then choose output based on the column
#0-5 are on the first mux
#6-11 are on the second mux
if col <... |
def set_decoder(self, val):
three_val_input(self._decA, self._decB, self._decC, val)
def set_mux(self, val):
three_val_input(self._muxA, self._muxB, self._muxC, val)
def read_input(pin):
return 1 - int(pin.is_pressed) | The main task of the code is to update a 8x12 matrix (_board) by reading input values from two sensors/multiplexers. It iterates through 8 rows, sets a decoder for each row, then scans 6 multiplexer channels per row. For each channel, it reads values from two outputs (_m1_out and _m2_out) and stores them in the corresp... | def update_board(self):
global _board
for row in range(8):
self.set_decoder(row)
for mux_val in range(6):
self.set_mux(mux_val)
self._board[row][mux_val] = read_input(self._m1_out)
self._board[row][mux_val + 6] = read_input(self._m2... |
def calculate_heuristics(self, puzzle):
heuristics = 0
for row in range(puzzle.size):
for column in range(puzzle.size):
if not puzzle.state[row][column] == 0:
heuristics += self.get_distance(puzzle.state[row][column], [row, column])
return heuristi... | This code implements an informed search algorithm (e.g., A*) to solve a puzzle. It maintains a priority queue of states to explore, selects the most promising state, checks if it's solved, and expands it to generate next states. States are added to the queue only if they haven't been visited or offer a better heuristic... | def solve(self):
states_to_visit = {str(self.puzzle.state): Node.Node(self.puzzle, 0, self.calculate_heuristics(self.puzzle),
'', self.puzzle)}
visited_states = {}
while True:
test_state = self.get_best_state(states_to_visi... |
def get_updates(offset=None):
url = URL + "getupdates?timeout=100"
if offset:
url += "&offset={}".format(offset)
js = get_json_from_url(url)
return js
def get_last_update_id(updates):
update_ids = []
for update in updates["result"]:
update_ids.append(int(update["update_id"]))
... | The main task of the code is to continuously poll for updates using a loop, process new updates by updating the last known update ID, and echo all received updates. It uses `get_updates` to fetch data, `get_last_update_id` to track progress, and `echo_all` to handle responses, with a 0.5-second delay between checks to ... | def main():
last_update_id = None
while True:
updates = get_updates(last_update_id)
if len(updates["result"]) > 0:
last_update_id = get_last_update_id(updates) + 1
echo_all(updates)
time.sleep(0.5) |
def createToneWave(self, tone):
x = np.linspace(0, self.periodo, self.fs * self.periodo)
lower, higher = tone
return (((np.sin(2 * np.pi * x * lower) + np.sin(2 * np.pi * x * higher))*1.0)/2)
def getTone(self, tone):
DTMF = {1: (697, 1209),
2: (697, 1336),
... | The code generates a tone wave, plays it via audio playback, logs the action, and optionally saves the audio file and plots if checkboxes are enabled. It also temporarily disables buttons during playback to prevent interference and re-enables them afterward. | def makeTone(self, tone):
created_tone = self.createToneWave(self.getTone(tone))
self.lockButtons()
sd.play(created_tone, self.fs)
sd.wait()
self.console("Tone {0} was reproduced".format(tone))
if self.checkBox_saveDTMF_audio.isChecked():
self.saveFi... |
def makeTone(self, tone):
created_tone = self.createToneWave(self.getTone(tone))
self.lockButtons()
sd.play(created_tone, self.fs)
sd.wait()
self.console("Tone {0} was reproduced".format(tone))
if self.checkBox_saveDTMF_audio.isChecked():
self.saveFi... | The code initializes a DTMF signal generator and analyzer GUI, setting up audio processing parameters, real-time and Fourier plots, DTMF tone generation buttons, mode selection (encoder/decoder), and file/recording controls. It configures UI elements, connects buttons to tone-generation and mode-switching functions, an... | def __init__(self, parent=None):
super(DTMF, self).__init__(parent)
self.setupUi(self)
self.periodo = 1
self.duration = 5
self.fs = 44100
self.maxFFT=0
self.maxPCM=0
self.decoding = False
self.ear = SWHear.SWHear(rate = self.fs, updatesPerSecond = ... |
def login(self, username, password):
if not self.personal_csrftoken:
self.csrftoken = self.get_csrftoken()
r = requests.post('https://prod-api-funimationnow.dadcdigital.com/api/auth/login/', data={'username': username, 'password': password, "csrfmiddlewaretoken": self.csrftoken}, headers={"R... | The main task of the code is to analyze a list of Funimation accounts by logging in, checking for duplicates, and categorizing each account as skipped, invalid, free, or premium. It logs timestamps, progress, and results, prints colored output for status, and saves account data to backup files. The function handles aut... | def checker(self, account_list):
if self.log:
with open('logs.log', 'a') as log:
t = time.localtime()
log.write('\n' + '{} {}, Info checker: Analysis type: funimation'.format(date.today(), time.strftime('%H:%M:%S', t)))
log.write('\n' + '{} {}, Info ch... |
def initialize_population_and_other_params(search_space):
search_space_len = len(search_space)
if search_space_len > 10 and search_space_len <= 100:
population_size = 4
cross_over_rate = 0.6
elif search_space_len > 100 and search_space_len <= 1000:
population_size = 8
cros... | This function implements a genetic algorithm to find the optimal solution in a given search space. It initializes population parameters, evolves the population through crossover, mutation, and selection over a set number of iterations, and tracks the best individual found. The process iteratively improves solutions by ... | def get_genetic_algorithm_solution(search_space, iter_num=100):
population_size, cross_over_rate, mutation_rate = initialize_population_and_other_params(search_space)
init_population = random.sample(search_space, population_size)
curr_population = [list(i) for i in init_population]
best_individual_wid... |
def create_inputs(lab_number):
os.system("python input_maker{0}.py".format(lab_number))
def give_compiled(file_name, compiled_file_name): #Tested
os.system("gcc {0} -lm -o {1}".format(file_name, compiled_file_name)) #If file is unable to compile the program will give user an error
#if os.path.isFile('./a.ou... | The code tests a user's compiled program against predefined test cases for a specific lab. It compiles the user's code, runs it with input files, and compares outputs to a solution's output. If any test fails, it returns the first failure's input, expected output, and actual output. If all tests pass, it returns succes... | def test_code(lab_number, test_file_name): #Tested
created_files_paths = ["path_scanner.pyc", "user_compiled_code.out"]
create_inputs(lab_number)
input_files = scan("inputs/")
#input_files = ["1", "2"]
compiled_file_path = give_compiled(test_file_name, "user_compiled_code.out")
if compiled_file_... |
def _login(self, param, action_result):
"""
This function logs into DS manager with given credentials and gets the session ID.
"""
# Filling the payload wth credentials. These are the values that user inputs in Phantom.
payload = {'dsCredentials': {"tenantName": param['accountna... | The function retrieves a specified number of log inspection events from a DS manager by authenticating with a session ID, making a REST API call with the maxItems parameter, handling errors, logging out, and returning the results in an action result object. | def _handle_get_log_inspection_events(self, param):
"""
This function returns the max number of events specified in eventsnum.
"""
# use self.save_progress(...) to send progress messages back to the platform
self.save_progress("In action handler for: {0}".format(self.get_action_... |
def _login(self, param, action_result):
"""
This function logs into DS manager with given credentials and gets the session ID.
"""
# Filling the payload wth credentials. These are the values that user inputs in Phantom.
payload = {'dsCredentials': {"tenantName": param['accountna... | The main task of the code is to retrieve web reputation events from a DS manager by authenticating via login, making a REST API call with a session ID, handling errors, logging out, and returning the results with status updates. | def _handle_getwebevents(self, param):
"""
This function returns all web reputation events.
"""
# use self.save_progress(...) to send progress messages back to the platform
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an ac... |
def _login(self, param, action_result):
"""
This function logs into DS manager with given credentials and gets the session ID.
"""
# Filling the payload wth credentials. These are the values that user inputs in Phantom.
payload = {'dsCredentials': {"tenantName": param['accountna... | The main task of the code is to retrieve all alerts from the DS manager by authenticating via login, making a REST GET request to the '/alerts' endpoint, handling potential errors during login/logout, and returning the collected alert data along with session status in the action result. | def _handle_getalerts(self, param):
"""
This function returns all alerts present on DS manager.
"""
# use self.save_progress(...) to send progress messages back to the platform
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an... |
def _login(self, param, action_result):
"""
This function logs into DS manager with given credentials and gets the session ID.
"""
# Filling the payload wth credentials. These are the values that user inputs in Phantom.
payload = {'dsCredentials': {"tenantName": param['accountna... | The function retrieves integrity monitoring events from a DS manager by authenticating via login, making a REST API call to fetch the events, logging out, and returning the results along with status updates. | def _handle_getimevents(self, param):
"""
This function returns all integrity monitoring events from DS manager.
"""
# use self.save_progress(...) to send progress messages back to the platform
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
... |
def _login(self, param, action_result):
"""
This function logs into DS manager with given credentials and gets the session ID.
"""
# Filling the payload wth credentials. These are the values that user inputs in Phantom.
payload = {'dsCredentials': {"tenantName": param['accountna... | The main task of the code is to list all report templates by authenticating via login, making a REST GET request to the '/reports' endpoint with dynamic parameters, handling API responses, logging out, and returning the results as action data with status tracking. | def _handle_list_report_templates(self, param):
"""
List all report templates.
"""
# use self.save_progress(...) to send progress messages back to the platform
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result ob... |
def _login(self, param, action_result):
"""
This function logs into DS manager with given credentials and gets the session ID.
"""
# Filling the payload wth credentials. These are the values that user inputs in Phantom.
payload = {'dsCredentials': {"tenantName": param['accountna... | This function retrieves web reputation events occurring after a specified time by authenticating via login, making a GET request to the DS manager's API with the event time filter, logging out, and returning the results. It handles session management, error checking, and data summarization for the platform. | def _handle_getwevtime(self, param):
"""
This function returns all web reputation events after specified time.
"""
# use self.save_progress(...) to send progress messages back to the platform
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
... |
def _login(self, param, action_result):
"""
This function logs into DS manager with given credentials and gets the session ID.
"""
# Filling the payload wth credentials. These are the values that user inputs in Phantom.
payload = {'dsCredentials': {"tenantName": param['accountna... | The function retrieves antimalware events occurring after a specified timestamp by authenticating with a session ID, querying the DS manager's API with the given time, and returning the results while handling authentication and logout steps. | def _handle_getevtime(self, param):
"""
This function returns all antimalware events after specified time.
"""
# use self.save_progress(...) to send progress messages back to the platform
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
... |
def _login(self, param, action_result):
"""
This function logs into DS manager with given credentials and gets the session ID.
"""
# Filling the payload wth credentials. These are the values that user inputs in Phantom.
payload = {'dsCredentials': {"tenantName": param['accountna... | The main task of the code is to list all alert types by authenticating via login, making a REST GET request to '/alert-types' with a session ID, handling API response data, and ensuring proper logout. It tracks progress, validates success/failure states, and structures results for the platform. | def _handle_list_alert_types(self, param):
"""
This function lists all alert types.
"""
# use self.save_progress(...) to send progress messages back to the platform
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action resu... |
def _login(self, param, action_result):
"""
This function logs into DS manager with given credentials and gets the session ID.
"""
# Filling the payload wth credentials. These are the values that user inputs in Phantom.
payload = {'dsCredentials': {"tenantName": param['accountna... | The function retrieves event-based tasks by authenticating via login, making a REST GET request to '/tasks/event-based', handling responses, and logging out. It returns success status with task data if all steps succeed, or failure status if any step (login, API call, logout) fails. | def _handle_list_event_based_tasks(self, param):
"""
This function lists event based tasks
"""
# use self.save_progress(...) to send progress messages back to the platform
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an acti... |
def _login(self, param, action_result):
"""
This function logs into DS manager with given credentials and gets the session ID.
"""
# Filling the payload wth credentials. These are the values that user inputs in Phantom.
payload = {'dsCredentials': {"tenantName": param['accountna... | The main task of the code is to retrieve all antimalware events from a DS manager via a REST API. It handles authentication by logging in, makes a GET request to the '/events/antimalware' endpoint using the session ID, logs out afterward, and returns the event data in the action result. Error handling is implemented fo... | def _handle_getevents(self, param):
"""
This function returns all antimalware events.
"""
# use self.save_progress(...) to send progress messages back to the platform
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action re... |
def _login(self, param, action_result):
"""
This function logs into DS manager with given credentials and gets the session ID.
"""
# Filling the payload wth credentials. These are the values that user inputs in Phantom.
payload = {'dsCredentials': {"tenantName": param['accountna... | This function authenticates via login, retrieves alert type data via API, handles session management, and returns the result. It processes parameters, performs REST calls, logs progress, and ensures proper logout, adding response data to the action result for the platform. | def _handle_describe_alert_type(self, param):
"""
Describes an alert type.
"""
# use self.save_progress(...) to send progress messages back to the platform
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result object... |
def _login(self, param, action_result):
"""
This function logs into DS manager with given credentials and gets the session ID.
"""
# Filling the payload wth credentials. These are the values that user inputs in Phantom.
payload = {'dsCredentials': {"tenantName": param['accountna... | This code retrieves details of a specific alert by authenticating with a session ID, making a REST GET request to the '/alerts/{alertid}' endpoint, handling potential errors, and returning the alert data along with session status. It ensures proper authentication, data retrieval, and session cleanup. | def _handle_describe_alert(self, param):
"""
Describes an alert.
"""
# use self.save_progress(...) to send progress messages back to the platform
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result object to self (... |
def _login(self, param, action_result):
"""
This function logs into DS manager with given credentials and gets the session ID.
"""
# Filling the payload wth credentials. These are the values that user inputs in Phantom.
payload = {'dsCredentials': {"tenantName": param['accountna... | The main task of the code is to modify an alert type by sending a POST request to a DS manager API, using parameters from 'param' to construct the payload. It handles authentication via login/logout, skips sensitive fields, and updates the alert type's details. The function returns success status with session ID or fai... | def _handle_modify_alert_type(self, param):
"""
Modifies an alert type.
"""
# use self.save_progress(...) to send progress messages back to the platform
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result object to... |
def rewire(self, neighbouring_node_ids):
added_node = self.nodes[-1]
added_pose = self.node_poses[-1]
for idx in neighbouring_node_ids:
neighbouring_pose = self.node_poses[idx] # read the pose
neighbouring_distance_origin = self.node_distanc... | This function grows a path toward a target pose using iterative expansion. It attempts to connect to the target, rewires the path tree if enabled, and stops when time expires or a path is found. Parameters control rewiring, completion checks, and search type. Returns whether a valid path was successfully generated. | def grow_to(self, end_pose : np.ndarray, iter = range(100), max_seconds = 180, star = True, finish = True, informed = False, set_angle=None, local_planner=False):
close_time=time.time() + max_seconds
added_node = True
done = False
neighbouring_node_ids = np.array([])
for i in ite... |
def get_yaml_files():
path_to_boards = get_boards_dir()
yaml_files = {}
for file in os.listdir(path_to_boards):
board_name = file.split(".")[0] # only get the part before .yaml
if board_name != "boards":
yaml_files[board_name] = os.path.join(path_to_boards, file)
return yam... | The main task of the code is to aggregate DBC data from multiple YAML files into a structured format. It reads YAML files, processes message signals with properties like start bit, length, scale, and receiver, and compiles them into a master data structure containing messages and boards. Each message's ID is adjusted b... | def get_dbc_data():
yaml_files = get_yaml_files()
master_data = {"Messages" : [], "Boards": get_boards()}
for can_board_id, board in enumerate(master_data["Boards"]):
data = read_yaml(yaml_files[board])
sender = get_board_name(yaml_files[board])
for message_key in data["Messages"]:
... |
def clean_input(input):
'''
[UNIMPLEMENTED] Remove all C style comments from input
'''
pass
def get_includes(input):
'''
Get all includes needed
'''
includes = [ "FreeRTOS.h", "unity.h", "stdlib.h", "tasks.h" ]
# for line in input:
# if (line == "TEST_IN_TASK"):
# includes.append("tasks.h")
... | The main task of the code is to process an input file by cleaning its content, extracting includes and test cases, generating output using these elements, replacing predefined placeholders with specific characters, and writing the final result to an output file. | def main(input_file, output_file):
# find includes etc.
replace = [ ('@co@', '{'), ('@cc@', '}'), ('@nl@', '\n') ]
with open(input_file, 'r') as input:
content = input.readlines()
clean_input(content)
include = get_includes(content)
tests = get_tests(content)
if len(tests) == 0:
raise Exceptio... |
def sendprogress(progressobj, value):
if progressobj is not None:
progressobj(value)
def growregions():
""" Phase 1 of maxp algorithm [Not to be called explicitly] """
partitions = ClusterpyMap()
unassigned = SetOfFeatures(LAYERFEATURES.values())
assigned = SetOfFeatures()
visited =... | The function `execmaxp` performs **Max-p clustering** on a set of spatial features. It generates multiple initial region partitions, filters those meeting a threshold, and refines them via local search with tabu constraints to maximize the number of regions (`maxp`). The algorithm returns the optimal region assignment ... | def execmaxp(layer, threshold, maxit, tabulength, maxtabusteps, progress=None):
""" Max-p clustering algorithm
Parameters are:
[1] layer -> A dictionary where keys are feature IDs and values are
ClusterpyFeatures
[2] threshold -> A double value that has to be satisfied for each regio... |
def get_pos(self):
url = self.driver.current_url
coord = [int(url.split('=')[2].split('&')[0]), int(url.split('=')[3].split('&')[0])]
self.pos = coord
if self.pos == self.expected_pos:
return True
else:
return False
def check_ready(self):
self.driv... | The code updates client data with position and readiness status, identifies bad pixels, and checks if a pixel placement is needed at the target position. If conditions are met, it picks and places a color, updates counts, and communicates with the client. Otherwise, it moves toward the target. The function also handles... | def update(self):
pos_good = self.get_pos()
if not pos_good:
self.client_dat['reboot'] = True
self.client_dat['pos'] = self.pos
self.check_ready()
self.client_dat['pix_ready'] = self.ready
bad_pixels = self.get_bad_pixels() # Get all bad pixels in view
... |
def get_pos(self):
# url = self.driver.current_url
# coord = [int(url.split('=')[2].split('&')[0]), int(url.split('=')[3].split('&')[0])]
self.pos = self.expected_pos
if self.pos == self.expected_pos:
return True
else:
return False
def check_ready(self): ... | The code updates client data by checking positional status, handling bad pixels, and deciding to place a pixel or move toward a target. If conditions are met (position matches target, readiness, and bad pixel status), it picks and places a color, updates counters, and sends data. Otherwise, it moves toward the target. ... | def update(self):
pos_good = self.get_pos()
if not pos_good:
self.client_dat['reboot'] = True
self.client_dat['pos'] = self.pos
self.check_ready()
self.client_dat['pix_ready'] = self.ready
bad_pixels = self.get_bad_pixels() # Get all bad pixels in view
... |
def train_epoch(self,batches=100):
start_time = time.time()
for b in range(batches):
X, y, person_id = self.train_dataset.random_batch()
self.train_batch(X, y, person_id)
self.eval_statistics["train-epoch_duration"].append(time.time() - start_time)
def test_epoch(self,batches=10):
start_time = time.time()... | The code's main task is to train a model over multiple epochs by iteratively performing training, testing, policy evaluation, and diagnostic output for each epoch, facilitating iterative learning and performance assessment. | def train(self):
for epoch in range(self.num_epochs):
self.train_epoch()
#print('Finished training')
self.test_epoch()
#print('Finished testing')
self.evaluate_policy(epoch)
#print('Finished evaluating')
self.output_diagnostics(epoch) |
def cos(x):
return math.cos(x*pi()/180)
def sin(x):
return math.sin(x*pi()/180)
def vect(a,b,c,d,v):
z = vect42(a,b,c,d,v)[2]
return [vect42(a,b,c,d,v)[0]*1400/(1500-z),vect42(a,b,c,d,v)[1]*1400/(1500-z)] | The code defines a function `torus` that computes a parametric representation of a torus using angles `u` and `v`, then applies a vector operation via `vect(a,b,c,d,x)` to the resulting coordinates. The main task is to generate torus points and perform a vector transformation on them. | def torus(r,u,v,a,b,c,d):
x = [r*cos(u),r*sin(u),r*cos(v),r*sin(v)]
return vect(a,b,c,d,x) |
def construct_kernel(X,y,kernel_scale_factor):
label = list(set(y))
x_1= X[np.where(y==label[0])]
x_2= X[np.where(y==label[1])]
K1_dis=euclidean_distances(np.transpose(x_1))
K2_dis=euclidean_distances(np.transpose(x_2))
epsilon1 = kernel_scale_factor*np.media... | The main task of the code is to compute a "manifest score" for feature selection using kernel methods. It constructs two kernels (K1, K2), derives operators (M, D), computes a score ranking features, and extracts sorted eigenvectors/eigenvalues of M and D to analyze significance. The function returns the score, sorted ... | def ManiFeSt(X,y,kernel_scale_factor=1,use_spsd=True):
K1,K2 = construct_kernel(X,y,kernel_scale_factor)
M,D = get_operators(K1,K2,use_spsd=use_spsd)
score = compute_manifest_score(D)
idx = np.argsort(score, 0)[::-1]
##eig_vecs
eigValM, eigVecM =np.linalg.eigh(M)
eigV... |
def keys_have_exactly_one_cut(n_keys, n_pins, n_levels, s):
for i in range(n_keys):
for p in range(n_pins):
xs = [key_index(p,l,i,n_levels,n_pins) for l in range(n_levels)]
exactly_one(xs, s)
def locks_have_at_least_one_shear(n_keys, n_locks, n_pins, n_levels, s):
for i in range(n_locks):
for p ... | The code constructs a solver with constraints ensuring keys have exactly one cut, locks have at least one shear, keys open only charted locks, avoid uncharted ones, and don't match a generated constraint. It returns the configured solver instance. | def build_solver(keyset, gencon, n_pins, n_levels):
s = Solver()
n_keys = len(keyset[0])
n_locks = len(keyset)
keys_have_exactly_one_cut(n_keys, n_pins, n_levels, s)
locks_have_at_least_one_shear(n_keys, n_locks, n_pins, n_levels, s)
keys_must_open_charted_locks(keyset, n_levels, n_pins, s)
keys_must_no... |
def parse_ast(source, lang):
"""
Parse the given code into corresponding ast.
Args:
source (str): code in string
lang (str): Set the language
Returns:
tree_sitter.Node: Method/Function root node
"""
parser.set_language(LANGUAGE[lang])
if lang in SOURCE_PREFIX_POSTFI... | This function generates an Abstract Syntax Tree (AST) sequence and a natural language (NL) description from a given source code string. It accepts parameters like the code, programming language, and optional method name. If `replace_method_name` is True, it returns both the standard NL description and a version without... | def generate_single_ast_nl(source, lang, name=None, replace_method_name=False):
"""
Generate AST sequence and nl sequence for a single source code sample.
Args:
source (str): Source code string
lang (str): Source code language
name (str): optional, name of method/function
re... |
def get_current_weather_parameters():
try:
api_key = "3e826e0f9e9479c77abab338620624bd"
base_url = "https://api.openweathermap.org/data/2.5/weather?"
current_city_name = get_current_city_only()
complete_url = base_url + "appid=" + api_key + "&q=" + current_city_name
response ... | The main task of the code is to retrieve and format current weather data for a user's location. It fetches temperature (converted from Kelvin to Celsius), humidity, and weather description from an API, then constructs a human-readable string with this information. If an error occurs (e.g., invalid data), it returns an ... | def get_current_weather():
try:
x = get_current_weather_parameters()
current_city_name = get_current_city_only()
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_temperature = current_temperature - 273.15
current_temp... |
def get_current_weather_parameters():
try:
api_key = "3e826e0f9e9479c77abab338620624bd"
base_url = "https://api.openweathermap.org/data/2.5/weather?"
current_city_name = get_current_city_only()
complete_url = base_url + "appid=" + api_key + "&q=" + current_city_name
response ... | The code fetches the current temperature in Celsius for the user's location by retrieving weather data, converting Kelvin to Celsius, and formatting the result. If an error occurs (e.g., invalid response), it returns an error message. The function relies on helper functions to get weather parameters and the city name, ... | def get_current_temprature():
try:
x = get_current_weather_parameters()
current_city_name = get_current_city_only()
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_temperature = current_temperature - 273.15
current_t... |
def lock_reward(self, step: int, amount: float):
self.reward_locked += amount
each_vest = amount / VESTING_PERIOD_INTERVALS
interval = VESTING_INTERVAL // self.step_size
e = (step // interval) * interval + interval
while amount > 0.0:
vest_amount = min(each_vest, amo... | The function processes one epoch by vesting rewards, managing expiring power/pledge, onboarding new power, and updating reward/baseline parameters. It locks rewards, adjusts circulating supply, extends expiring power if possible, calculates new power based on behavior, and decays rewards while growing the baseline. Ste... | def handle_epochs(self):
epoch = self.step_no * self.step_size
# Emit and vest rewards
self.lock_reward(self.step_no, self.epoch_reward * self.step_size)
# Vest rewards
vesting_now = self._reward_vesting.pop(self.step_no, 0.0)
if vesting_now > 0.0:
self.rewar... |
def get_valid_locations(board):
valid_loc = []
for col in range(colCount):
if is_valid_loc(board, col):
valid_loc.append(col)
return valid_loc
def is_terminal_node(board, row, col):
return winning_move(board, playerPiece, row, col) or winning_move(board, aiPiece, row, col) or len(get... | The code implements the minimax algorithm with alpha-beta pruning for a two-player game (likely Connect Four), evaluating board states to determine the optimal move for the AI player. It checks terminal conditions (win/loss/draw), recursively explores valid moves, and selects the column with the highest score for the m... | def minmax(board, depth, alpha, beta, maxPlayer, r, c):
valid_loc = get_valid_locations(board)
# print(valid_loc)
if (r == -1 and c == -1):
is_terminal = False
# for c in valid_loc:
# r = get_next_row(board, c)
# is_terminal = is_terminal_node(board, r, c)
# ... |
def get_action(self):
for c in range(colCount):
for r in range(rowCount):
if self.prev_state[r][c] == 0:
if self.state[r][c] != 0:
return c
break
def selection(self):
'''
Aim - To select the leaf node wit... | The code implements a **Monte Carlo Tree Search (MCTS)** algorithm to determine the optimal move in a game. It runs MCTS iterations within a fixed time limit, performing selection, expansion, simulation, and backpropagation. The algorithm tracks node visits and win rates, printing debug information at specific interval... | def start_the_game(self):
'''
Aim - Complete MCTS iteration with all the process running for some fixed time
'''
self.initial_time = time.time()
is_expanded = True
if (self.state[1] == np.array([0, 0, 0, 0, 0, 0, 0])).all():
count = 0
for c in rang... |
def get_valid_locations(board):
valid_loc = []
for col in range(colCount):
if is_valid_loc(board, col):
valid_loc.append(col)
return valid_loc
def is_terminal_node(board, row, col):
return winning_move(board, playerPiece, row, col) or winning_move(board, aiPiece, row, col) or len(get... | This function implements the Minimax algorithm with alpha-beta pruning for a two-player game (e.g., Connect Four). It evaluates all valid moves recursively, alternating between maximizing (AI) and minimizing (player) players. It checks for terminal states (win/loss/draw), assigns scores, and selects optimal moves by co... | def minmax(board, depth, alpha, beta, maxPlayer, r, c):
valid_loc = get_valid_locations(board)
# print(valid_loc)
if (r == -1 and c == -1):
is_terminal = False
else:
is_terminal = is_terminal_node(board, r, c)
if (is_terminal):
if winning_move(board, aiPiece, r, c):
... |
def open_image_stack(image_path):
""" open a .tif image stack
Modifies the data to work with the segmentation function.
Parameters
---------------
image_path: str
the path to the image to be opened
Returns
---------------
stack: 3D array
the image stack as a 3D array... | The main task of the code is to segment an image stack using a specified Cellpose model, generating 3D masks where each cell is labeled uniquely. It accepts image paths or arrays, applies segmentation with adjustable parameters like cell diameter, and optionally saves masks as .tif files. The function also supports cel... | def get_segmentation(image_path, model_path, diam=40, save=False, savedir=None,
track=True, name=None):
""" segment an image
Takes an image stack and segments each image separately with
the given model.
Parameters
---------------
image_path: str or 3D array
the ... |
def response_unpack(data):
hh, hl, ln, q, cmd = struct.unpack('<BBBBB', data[:5])
if not check_crc(data):
raise ValueError("Wrong CRC")
if not cmd in ResponseParser:
raise ValueError("Wrong CMD")
func = ResponseParser[cmd]
return cmd, func(data[5:-1])
def on_state(state):
draw_to... | This function reads UART data, processes specific command bytes (e.g., 0x02, 0x04), unpacks responses, and triggers actions like sending range data, starting continuous ranging threads, or stopping operations. It handles errors and maintains a loop for continuous reception, using global flags and callbacks to update st... | def read_uart():
global CONTINUE
while True:
data = uart.read(1)
if data == b'\xee':
time.sleep(0.01)
_d = uart.read(2)
if _d:
len_eq = bytearray(_d)
expected_length = len_eq[1] + 1
data += len_eq
... |
def match(terminal):
global cont_current_token
global current_token
if current_token == '$' :
print("Syntax_Analysis_OK")
exit(0)
elif current_token == terminal:
cont_current_token = cont_current_token+1
current_token = tokens_syntax[cont_current_token]
else:
... | This function parses function parameters by checking the current token. If the token is 'void', it matches and processes parameters via params_prime(). For type tokens (int, float, string), it calls var_specifier(), matches the token, and processes parameters recursively via params_prime(). The task involves syntactic ... | def params():
if current_token == 'void':
match('void')
params_prime()
elif current_token == 'int' or current_token == 'float' or current_token == 'string':
var_specifier()
match(current_token)
params_prime()
params_prime() |
def match(terminal):
global cont_current_token
global current_token
if current_token == '$' :
print("Syntax_Analysis_OK")
exit(0)
elif current_token == terminal:
cont_current_token = cont_current_token+1
current_token = tokens_syntax[cont_current_token]
else:
... | The function `params_list_prime` parses a list of parameters in a function declaration. It processes parameters separated by commas by matching commas, invoking `var_specifier` to parse variable declarations, and recursively handling subsequent parameters via `params_prime` and `params_list_prime`. If the current token... | def params_list_prime():
if current_token == ',':
match(',')
var_specifier()
match(current_token)
params_prime()
params_list_prime()
elif current_token == ')':
return |
def var_specifier():
if current_token == 'int':
match('int')
elif current_token == 'float':
match('float')
elif current_token == 'string':
match('string')
def match(terminal):
global cont_current_token
global current_token
if current_token == '$' :
print("Syntax_A... | The function `local_declarations` recursively processes local variable declarations by invoking `var_specifier` to define variable types, `match` to validate tokens, and `var_declaration_prime` to handle variable names and initializers. Its recursive call allows parsing multiple declarations sequentially, ensuring prop... | def local_declarations():
var_specifier()
match(current_token)
var_declaration_prime()
local_declarations() |
def burn(self, tree):
if self.update_fire:
tree.fire_count += 1
if tree.fire_count % self.FLAME_CYCLE == 0:
tree.fire_scale *= 1.2 if tree.fire_count < self.FLAME_PEAK * self.FLAME_CYCLE else 0.8
if tree.fire_count == self.FLAME_PEAK * self.FLAME_CYCLE:
... | This code simulates a dynamic environment with wind, robots, and fire. It runs a loop to process time steps, receive wind data, update wind conditions, and send feedback. Robots clean water, interpret custom data, and drop water based on predefined quantities. Fire simulation triggers when a drone reaches altitude >40,... | def run(self):
start_fire_now = False
while True:
step = self.step(self.time_step)
if step == -1:
break
message = self.wwiReceiveText()
if message:
self.wind.update(message)
self.wind.evolve()
... |
def lieDown(self, duration):
motors_target_pos = [-0.40, -0.99, 1.59, # Front left leg
0.40, -0.99, 1.59, # Front right leg
-0.40, -0.99, 1.59, # Rear left leg
0.40, -0.99, 1.59] # Rear right
self.movementDecomp... | The code's main task is to repeatedly execute a sequence of actions—lying down, standing up, and sitting down—within a loop that continues until the elapsed time reaches 40 units. The loop ensures these motions are performed cyclically until the time condition is met. | def run(self):
while self.getTime() < 40:
self.lieDown(1)
self.standUp(1)
self.sitDown(1) |
def process_path(_binding: BindingEntry, config: FinaliseConfigModel):
_, category, audio, text = _binding.tuple()
target_dir = (
Path(
output_dir,
process_category(
str(category.name) if category is not None else config.uncaterized_name,
config,
... | The main task of the code is to process audio and transcript data based on configuration parameters, organize files into categorized directories, generate structured output, and return a Pydantic representation of the processed data. It handles directory cleanup, binding data transformation, category indexing, audio fi... | def finalise(config: FinaliseConfigModel, db: Session = Depends(get_db)):
rmtree(output_dir, ignore_errors=True)
output_dir.mkdir()
bindings = get_all_bindings(db)
categories = set(
map(
lambda x: x.replace(" ", config.category_space_replacer),
map(
lambda... |
def _train_epoch(self, train_loader):
"""Train epoch"""
running_loss = 0
for batch in train_loader:
self.optimizer.zero_grad()
inputs, targets = batch
inputs, targets = inputs.to(self.device), targets.to(self.device)
targets = self._modify_targe... | The code trains a neural network model using the provided training data loader, with optional validation. It supports early stopping based on validation loss, saves the best model during training, and periodically saves the model at specified intervals. The function tracks and logs training and validation losses across... | def train_model(self, train_loader, validation_loader=None, num_epochs=100, model_dir="/models",
early_stopping=False, save_interval=1):
"""Train model"""
if early_stopping:
# Save best model during training
torch.save(self.state_dict(), model_dir + "/" + sel... |
def readLocations(locations_filepath):
# print("in locations")
f1 = open(locations_filepath, "r")
nodes = []
coordinates = []
t = f1.readlines()
for i in range(0, len(t)):
l = t[i]
if l != "END":
tokens = l.split()
nodes.append(tokens[0])
dist ... | The code reads node locations, plots them, and uses A* algorithm to find paths between user-specified start and end nodes. It allows excluding nodes, selecting output format (final/step-by-step), and choosing heuristics (straight-line or fewest cities). The result is visualized using plots and animations. | def main():
# read locations file
nodes, coordinates, list2d = readLocations("locations.txt")
print("look at the plot for available nodes and their connectivity")
ani_nodes(coordinates, nodes)
ani_connections(list2d, coordinates, nodes)
# print("nodes available are")
# print(nodes)
# en... |
def readLocations(locations_filepath):
#print("in locations")
f1 = open(locations_filepath,"r")
nodes = []
coordinates = []
t = f1.readlines()
for i in range(0,len(t)):
l = t[i]
if l!="END":
tokens = l.split()
nodes.append(tokens[0])
dist = []
... | The code reads node locations from a file, takes user inputs for start and end nodes, and uses depth-first search (DFS) to find all possible paths between them. It then prints the discovered paths using node coordinates. | def main():
#read locations file
nodes, coordinates,list2d = readLocations("locations.txt")
print("all the nodes are")
print(nodes)
#enter staring node
print("enter starting node")
st_node = input()
#enter ending node
print("enter ending node")
en_node = input()
#initialize... |
def infall(cl):
##Calculate the infall rate of globular clusters
## Takes GC mass in msun, Galaxy mass in msun, several internal constants of the galaxy.
## Output is in 1/Myr
mg=cl.gmass/1.E11
mgc=cl.gcmass/1.E11
a1 = 2.63
a2 = 2.26
a3 = 0.9
gfact=(2.-cl.slope) * ((a1 * pow(1./(2.-cl.slope), a2) + a3)... | The function `nsc_prop` calculates the mass, half-mass radius, density scale, and escape velocity of a nuclear star cluster (NSC) after a given time. It uses the initial mass of the cluster, infall rate, and time to compute the NSC's evolved mass. Subsequent parameters like half-mass radius, density scale, and escape v... | def nsc_prop(cl,time):
init_mass=cl.mass
infall_rate=infall(cl)[1] # 1/Myr
acc_rate=infall_rate*cl.gcmass #Msun/Myr
NSC_mass=init_mass+acc_rate*time #Msun
rhm=halfmass_rad(cl,NSC_mass)[1] #pc
scale_d=scale_den(cl,NSC_mass) #Msun/pc3
esc_vel=escape_vel(cl,NSC_mass) #cm/s
return NSC_mass,rhm,scale_d... |
def create_label_frame():
global frame
frame = Frame(
root,
background="#82D5A5",
)
frame.pack(padx=10, pady=10)
def create_button_frame():
global button_frame
button_frame = Frame(
root,
background="#82D5A5",
)
button_frame.pack(padx=10, pady=10)
... | The main task of the code is to initialize and organize various UI components (labels, buttons, frames) for a graphical interface, likely for a game or application, by calling multiple sub-functions like `create_label_frame`, `create_buttons`, and `create_reset_button` to structure the layout and interactive elements. | def create_widgets():
create_label_frame()
create_button_frame()
create_topic_label()
create_player_label()
create_reset_button()
create_buttons() |
def check_backend_connection(backend_url: str) -> bool:
try:
with urllib.request.urlopen(backend_url) as request:
response = request.read().decode('UTF-8')
print(f'Received message from server: {response}')
return True
except:
return False
def get_latest_IT_da... | The main task of the code is to continuously check a backend connection, poll GitLab for new IT data at intervals, and report updates to a backend server. It waits 60 seconds between checks (except initially), retrieves the latest data, verifies if it's new, and sends it to the backend if updated. The loop handles conn... | def main():
'''Read the data from IT and update the server, in a loop'''
print('Running main() in read_IT_data.py')
# Check backend connection
print('Checking backend connection.')
while not check_backend_connection(config.BACKEND_URL):
print('Failed to connect to backend. Sleeping for 10 s... |
def huffman_tree_encoding(string):
if string is None:
raise ValueError('Please enter a valid string')
letters , only_letters = get_freq(string)
huffman_tree, nodes = get_leaf_nodes(letters)
huffman_tree, new_nodes = get_huffman_tree(nodes, huffman_tree)
huffman_tree.sort(reverse = True)
... | The code tests Huffman encoding and decoding by encoding the input string "The bird is the word", decoding it, and verifying if the decoded string matches the original input and a predefined encoded string. It prints pass/fail results and details of the encoding process. | def test1():
print("Test 1")
input_string = "The bird is the word"
encodes_codes, codes_dict = huffman_tree_encoding(input_string)
decoded_string = huffman_tree_decoding(encodes_codes, codes_dict)
printDetails(codes_dict , encodes_codes, decoded_string, input_string)
print("Pass" if decoded_st... |
def huffman_tree_encoding(string):
if string is None:
raise ValueError('Please enter a valid string')
letters , only_letters = get_freq(string)
huffman_tree, nodes = get_leaf_nodes(letters)
huffman_tree, new_nodes = get_huffman_tree(nodes, huffman_tree)
huffman_tree.sort(reverse = True)
... | This code tests Huffman encoding and decoding by encoding the input string "She sells sea shells", decoding it, and verifying if the decoded string matches the original and if the encoded output matches a predefined string. It prints results and a separator line to indicate test completion. | def test2():
print("Test2")
input_string = "She sells sea shells"
encodes_codes, codes_dict = huffman_tree_encoding(input_string)
decoded_string = huffman_tree_decoding(encodes_codes, codes_dict)
printDetails(codes_dict , encodes_codes, decoded_string, input_string)
print("Pass" if decoded_str... |
def huffman_tree_encoding(string):
if string is None:
raise ValueError('Please enter a valid string')
letters , only_letters = get_freq(string)
huffman_tree, nodes = get_leaf_nodes(letters)
huffman_tree, new_nodes = get_huffman_tree(nodes, huffman_tree)
huffman_tree.sort(reverse = True)
... | The code tests Huffman encoding/decoding with an empty input string. It verifies that encoding an empty string produces no codes, and decoding the empty encoded data reconstructs the original empty string. The test checks if the encoded data is empty and if the decoded output matches the input, ensuring correct edge ca... | def test3():
print("Test 3 - Edge case when input string is not provided ")
input_string = ""
encodes_codes, codes_dict = huffman_tree_encoding(input_string)
decoded_string = huffman_tree_decoding(encodes_codes, codes_dict)
printDetails(codes_dict , encodes_codes, decoded_string, input_string)
... |
def return_valid_piece(self, coordinate):
"""
Returns a piece at the coordinate - if it exists.
Returns 0 otherwise
"""
cur_x = coordinate[0]
cur_y = coordinate[1]
#if coordinate contains a piece
if self.board[cur_x][cur_y] != 0:
return self.... | This function determines valid moves for a chess piece at a given coordinate by identifying the piece type and delegating to specialized move-generation methods (e.g., pawn, knight, rook). It returns a list of legal moves based on the piece's movement rules, ensuring accurate gameplay logic. | def get_valid_moves(self, coordinate):
"""
Returns a list of valid moves for the piece at a given coordinate
"""
coord_piece = self.return_valid_piece(coordinate)
if isinstance(coord_piece, pieces.Pawn):
return self.get_pawn_moves(coordinate)
if isinstance(... |
def print_board(board):
for row in board:
print(' '.join(row))
def check_winner(board, player):
# Check rows and columns
for i in range(3):
if all(cell == player for cell in board[i]) or all(board[j][i] == player for j in range(3)):
return True
# Check diagonals
if all(bo... | The code implements a Tic Tac Toe game where a human player (O) competes against a computer (X). It initializes a 3x3 board, handles player input validation, alternates turns, checks for wins/draws, and updates the board state until the game concludes with a win or draw. | def play_tic_tac_toe():
board = [['-' for _ in range(3)] for _ in range(3)]
print("Welcome to Tic Tac Toe!")
print_board(board)
while True:
# Human's move
while True:
try:
row = int(input("Enter row (0, 1, 2): "))
col = int(input("Enter column ... |
def augment(self, echo_data, truth_data, zoom, shift, angles):
size = echo_data.shape
if zoom < 1.0:
echo_data = self.scale(echo_data, zoom)
echo_data = self.fit_size(echo_data, size)
echo_data = self.rotate_and_translate(echo_data, angles, shift)
echo_da... | This function loads and preprocesses medical imaging data (echo and truth) by reading files, applying optional data augmentation (zoom, shift, rotation), normalizing values, adjusting intensity, converting to PyTorch tensors, and extracting structural metadata. It returns a tuple containing processed tensors and filena... | def __getitem__(self, index):
meta = self.metas[index]
filename = os.path.splitext(os.path.basename(meta[0][2]))[0]
echo_data = nrrd.read(meta[0][2])[0] # np.uint8
truth_data = nrrd.read(meta[0][3])[0] # np.float64
if self.augmentation:
zoom = np.random.uniform(0.9... |
def exit_due_to_error(message):
"""
Part 3 and 4: Exit the program
after a player makes an illegal move
This is an INTERNAL function called from next_move above, when
that function has determined that the move chosen by the player
violates the rules of the game... | The function `next_move` processes a player's turn in a game engine by retrieving the current player's move (either from pre-stored moves or by querying the player module), validating it, and updating the game state if valid. If invalid, it exits with an error. Valid moves trigger notifications to all players, update t... | def next_move(engineData):
"""
Part 3 and 4
Ask the module of the player whose turn it is for its next move
(player's move function.)
Check the move for validity. If invalid, exit_due_to_error is called.
If valid, all player modules are notified of the move via last_... |
def model(X_Image1, X_Image2, X_Image3, update_ops_collection, is_training):
# ***** ResNet50_4_5 ***** : Branch1x: [Start-Part4), Branch2y: [Part4-Part5), Branch3: [Part5-End]
# ******************************************************************************************************************
# Branch11: [S... | The code trains a deep neural network to classify benign and malignant masses using multi-view medical images (US, MG_CC, MG_MLO). It initializes hyperparameters, constructs a TensorFlow model with softmax output, and employs stochastic gradient descent with learning rate decay. The model is trained on augmented data b... | def run_deep_model(View_Name, randsampled_benign_masses, randsampled_malignant_masses, splitting_benign_masses, splitting_malignant_masses, test_stage, Address):
# ***** Initialization *****
update_ops_collection = 'resnet_update_ops'
resize_parameter = 100
augmentation_parameter = 24
Training_Diff ... |
def read_and_sort_json_file(keys_list, json_list):
"""Sorts json based on list of keys.
Parameters
----------
keys_list : list
List of keys specified in command line arguments
json_list : list
List of dictionaries inside json file
Raises
------
KeyError
If one t... | The main task of the code is to process and organize a list of JSON dictionaries based on specified keys, sort them, structure the data, and save the final organized JSON output into a result file. It handles control flow by sequentially reading, sorting, zipping, building, and writing the JSON data according to the pr... | def handle_control_flow(list_of_keys, json_list_of_dicts):
"""Handles the control flow of the script
Parameters
----------
list_of_keys : list
List of keys specified in command line arguments
json_list_of_dicts : list
List of dictionaries inside json file
"""
json_list_order... |
def newSolvedBoard(self):
# Create an deep copy of a fresh board
newBoard = copy.deepcopy(self.BLANK_BOARD)
# Populate the board using backtracking algorithm
self.fillPuzzle(newBoard)
return newBoard
def pokeHoles(self, startingBoard, holes):
removedVals = []
whi... | The function generates a solvable puzzle board by removing values from a solved board, creating "holes" for clues. It handles errors by recursively retrying until a valid board is created, returning the removed values, the starting board, and the solved board. | def newStartingBoard(self, holes):
# Reset global iteration counter to 0 and tries to generate a new game.
# If counter reaches its maximum limit in the fillPuzzle function, the current attemp will abort
# Error is caught and used to re-run the function until new board is created
try:
... |
def int_hull(self, interval):
'''
Given an interval (sources and sinks), return the convex hull.
'''
points = []
# strategy : add all points in convex_square(source, sink) for a given source and a given sink, then remove points if needed
for src in interval.src:
... | The code computes the "cover" of a given interval by generating intervals derived from its corner vertices. For each corner, it adjusts coordinates by ±1, checks if the resulting interval is valid (via `is_convex`), and adds it to the cover list. If `conv=True`, it returns intervals as convex hulls; otherwise, it conve... | def cover(self, interval, conv=True):
'''
Return the cover of an interval.
If conv == True, return intervals in the form of convex hulls.
If conv == False, return intervals in the form (src, snk).
Strategy: for all corner vertices, we check if the interval given when we add the... |
def powerset(elements):
'''
Generate all possible subsets of a set of elements.
'''
all_subsets = []
for subset_size in range(len(elements) + 1):
all_subsets.extend(combinations(elements, subset_size))
return [list(subset) for subset in all_subsets]
def is_convex(self, points):
'... | The function generates all valid intervals from a set of nodes by checking subsets for convexity and connectivity. If `conv=True`, it returns intervals as convex hulls; otherwise, it returns them as `Interval` objects defined by source and sink nodes. | def list_int(self, conv=True):
'''
Return the list of all the intervals possible.
If conv == True, return intervals in the form of convex hulls.
If conv == False, return intervals in the form Interval(src, snk).
'''
nodes = self.nodes
candidates = powerset(nodes)... |
def int_rank(self, interval):
'''
Given an interval, compute the interval rank.
'''
# first find a_1 and b_1 such that a_1 <= b_1
for k in range(len(interval.src)):
for l in range(len(interval.snk)):
if self.is_smaller(interval.src[k],interval.snk[l])... | The code computes the "interval replacement" of a given interval by adjusting its rank based on subsets of its cover. It iterates over non-empty subsets of the cover, modifying the result by adding or subtracting ranks of derived intervals, depending on subset size parity. The formula combines contributions from single... | def int_replacement(self, interval):
'''
Return the interval replacement of an interval. Uses the formula with the cover of the interval.
'''
repl = self.int_rank(interval) # corresponds to the empty set in the sum
cov_ps = powerset(self.cover(interval))
# compute V S
... |
def load_session():
global session
logging.info("Trying to fetch session variable from system")
try:
with open(Property.session_filepath, 'rb+') as file:
session = pickle.load(file)
except:
logging.warn('No session variable found in system')
return -1
logging.info... | The function `get_ticker` retrieves a KiteTicker instance for API interaction. It first checks if an access token is valid; if so, it returns the ticker directly. If invalid, it logs an error, repeatedly attempts login until successful, then returns the KiteTicker with the updated access token. The main task is to ensu... | def get_ticker():
load_session()
if access_token_valid():
return KiteTicker(Property.api_key, session['access_token'])
else:
logging.info('No access token found!!')
while login() == -1:
pass
return KiteTicker(Property.api_key, session['access_token']) |
def loadJson(self):
data = open('json_data/airports.json',)
json_data = json.load(data)
airport_data = json_data["airports"]
for airports in airport_data:
if airports["airport_name"] == self.travel_details["source"]:
self.source_city = airports["city_name"]
... | This code initializes a GUI window for confirming a flight booking, setting up input fields for user details like name, email, and contact information. It loads JSON data, creates interface elements, and prepares the window for user interaction to finalize the booking process. | def __init__(self, details, travel_details):
window = Toplevel()
# window = Tk()
window.title("Confirm booking - Udan Khatola")
window.geometry("800x600")
self.airline_details = details
self.travel_details = travel_details
self.source_city = ''
self.desti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.