dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def check_sekali_pakai(peminjaman_diajukan,list_booked_peminjaman):
list_booked_peminjaman_by_ruangan = list_booked_peminjaman.filter(ruangan__id=peminjaman_diajukan['ruangan'])
for peminjaman in list_booked_peminjaman_by_ruangan:
print(peminjaman)
if int(peminjaman.perulangan.jenjang) ==... | The function checks if submitted room bookings (izin_kegiatan_data) conflict with existing booked periods. It filters active bookings, iterates through each submitted request, and uses duration-specific checks (sekalai_pakai, harian, mingguan, bulan) to detect overlaps. Returns False if any conflict is found, otherwise... | def is_available(izin_kegiatan_data):
list_booked_peminjaman = PeminjamanRuangan.objects.exclude(perulangan__tanggal_akhir__lt=datetime.date.today())
list_peminjaman_diajukan = izin_kegiatan_data['peminjaman_ruangan']
print(list_peminjaman_diajukan)
for peminjaman_diajukan in list_peminjaman_diajukan... |
def run_model(self, x, small_shape=(128, 128, 128), shape=(256, 256, 256), bbox_margin=.1):
x = torch.from_numpy(x).to(next(self.model.parameters()).device)
x = torch.nan_to_num(x)
mask = torch.zeros_like(x)
x_small = F.interpolate(x[None, None], small_shape, mode='nearest-exact')[0, 0]
... | This code processes neuroimaging data by applying a model to generate a brain mask, thresholding and postprocessing the mask, applying it to the input image, calculating total intracranial volume (TIV), and saving the masked image, mask, and TIV metrics in NIfTI format with specified output paths. | def run(self, input, brain_path=None, mask_path=None, tiv_path=None, threshold=.5, n_dilate=0):
img = nib.load(input) if isinstance(input, str) else input
x = nib.as_closest_canonical(img).get_fdata(dtype=np.float32)
x = x[..., 0] if len(img.shape) == 4 else x
mask = self.run_model(x.cop... |
def _parse_timestamp(arg: str):
_time_arg = {}
arg = _split_until_statement(arg)
r = re.search(r"(now)|(epoch) (\d{1,64})|(time) ([\d,\-,\:,\/,\ ]{1,64})", arg, re.IGNORECASE)
if r:
if r.group(1):
_time_arg = {
"arg": r.group(1),
"style": StyleEnum.STR... | The code parses input arguments into a dictionary containing four parameters: time, offset, recursion, and end conditions, using helper functions to extract each value. | def condition_parser(arg: str):
return {
"time": _parse_timestamp(arg),
"offset": _parse_offset(arg),
"recursive": _parse_recursion(arg),
"until": _parse_end(arg)
} |
def isTerminal(self):
"""Checks whether state is a terminal state
Returns:
A bool indicating whether this is a terminal state, i.e. no more actions can be taken
"""
return len(self.ps) == 1 or len(self.getActions()) == 0 or self.kingStuck()
def getActions(self) -> li... | The main task of the code is to generate all reachable states from the current state by processing possible captures. It retrieves actions via `self.getActions()`, applies `self.nextState()` to each capture pair (p1, p2), and returns a dictionary mapping these captures to their resulting states. If the state is termina... | def transition(self) -> dict:
"""Returns a list of states which can be reached from this state
Uses self.getActions() to retreive a list of possible captures.
Each capture is then given to self.nextState() and the resulting states are stored in a dictionary.
Returns:
... |
def _get_dates_cache_no_cache(self, start_date, end_date):
dates = pd.date_range(start_date, end_date)
self.days_cache = max(0, len(dates) - self.days_no_cache)
self.dates_cache = dates[0: self.days_cache]
self.dates_no_cache = dates[self.days_cache:]
def get_df_toggl(self):
# If... | The code initializes a Toggl API client, reads an API token from a file, and sets up parameters for date ranges, caching, and Google Sheets export. It creates DataFrames to store Toggl time-tracking data and summaries, determines cached vs. non-cached dates, fetches Toggl data, and optionally aggregates/exported result... | def __init__(self, toggl_token_path=TOGGL_TOKEN_PATH, toggl_cache_path=TOGGL_CACHE_PATH,
start_date=START_DATE_DEF, end_date=END_DATE_DEF, days_no_cache=3,
id_gsheet=ID_GSHEET_2122, export_to_ghseet=True):
# create a Toggl object and set our API key
self.toggl_cache_pa... |
def on_received_message_2( client, userdata, msg ):
"""
Processing message 2 of the registration process.
This message is sent by the platform.
The first shared key is generated in this function after
getting the public key generated by the platform for the hand-shake.
The... | This function processes registration messages by validating sequential steps (msg 2, 4, 6, 8) using global state. It checks verification codes, platform authenticity, and user type, sending errors for failures. If all steps succeed, it releases the connection. | def on_registration( client, userdata, json_message ):
"""
This function handle each message received during
registration process.
"""
global connected, connection_failed
global msg_2, msg_4, msg_6
number = int( json_message.get( "msg", 0 ) )
if number == 2:
msg_2 = on_r... |
def load_config(self, **kwargs):
"""Load configuration from user-provided input params"""
if 'gameId' in kwargs:
self.game_api_result = API.get_random_game()
self.game_map = self.game_api_result['map']
elif 'mapId' in kwargs:
self.game_api_result = API.get_def... | The code initializes an object by loading configuration settings, restoring its state, performing preparation tasks, and setting a flag to indicate it's active. The constructor uses keyword arguments to configure the instance, ensuring it's ready for operation by calling setup methods and activating the running state. | def __init__(self, **kwargs):
"""Constructor just sets everything up"""
self.load_config(**kwargs)
self.load_state()
self.prepare()
self.running = True |
def get_live_counts(self):
"""
Get live counts of cells of each color, and total.
Compute statistics.
"""
def _count_live_cells(state):
livecells = 0
for i in range(len(state)):
if (state[i][0] >= 0) and (state[i][0] < self.rows):
... | The main task of the code is to determine the next step in a simulation process. If the simulation is not running or has halted with a victor found, it returns current live counts. Otherwise, it advances to the next generation, updates the moving average of live counts, and returns the new live counts for the current g... | def next_step(self):
if self.running is False:
return self.get_live_counts()
elif (self.halt and self.found_victor):
self.running = False
return self.get_live_counts()
else:
self.generation += 1
live_counts = self.next_generation()
... |
def get_grid_pattern(pattern_name, rows, columns, xoffset=0, yoffset=0, hflip=False, vflip=False, rotdeg=0):
# convert list of strings to list of lists (for convenience)
ogpattern = get_pattern(pattern_name, hflip=hflip, vflip=vflip, rotdeg=rotdeg)
ogpattern = [list(j) for j in ogpattern]
blank_row = ["... | The main task of the code is to generate two distinct cellular automaton patterns: a combined oscillator pattern using two randomized "quadrupleburloaferimeter" oscillators and a "timebomb" pattern, then return their URLs. It introduces randomness in positioning via seed-based offsets and combines patterns using union ... | def timebomb_oscillators_twocolor(rows, cols, seed=None):
# set rng seed (optional)
if seed is not None:
random.seed(seed)
centerx1a = cols//2 + cols//4
centerx1b = cols//4
centery1a = rows//4
centery1b = centery1a
centerx1a += random.randint(-10, 10)
centerx1b += random.randin... |
def get_grid_pattern(pattern_name, rows, columns, xoffset=0, yoffset=0, hflip=False, vflip=False, rotdeg=0):
# convert list of strings to list of lists (for convenience)
ogpattern = get_pattern(pattern_name, hflip=hflip, vflip=vflip, rotdeg=rotdeg)
ogpattern = [list(j) for j in ogpattern]
blank_row = ["... | The main task of the code is to generate two distinct rabbit patterns on a grid with randomized positions and orientations, then return their URLs. It creates two groups of rabbits, applies random offsets and flips, combines them into patterns, and outputs two URLs representing these patterns for a two-color design. | def fourrabbits_twocolor(rows, cols, seed=None):
# set rng seed (optional)
if seed is not None:
random.seed(seed)
rabbit_locations1 = [
(cols//4, rows//4),
(cols//2 + cols//4, rows//4),
]
rabbits1 = []
for (x,y) in rabbit_locations1:
x += random.randint(-5,5)
... |
def get_pattern_size(pattern_name, **kwargs):
"""
Returns: (nrows, ncols)
"""
pattern = get_pattern(pattern_name, **kwargs)
return (len(pattern), len(pattern[0]))
def get_grid_pattern(pattern_name, rows, columns, xoffset=0, yoffset=0, hflip=False, vflip=False, rotdeg=0):
# convert list of string... | The code generates two spaceship patterns using 'backrake2' generators positioned at the grid's bottom, with random offsets. It creates 15 alternating colored 'block' patterns spaced vertically, combines them with generators via pattern_union, and returns URLs for both composite patterns. | def twospaceshipgenerators_twocolor(rows, cols):
# backrake 2 laying trail of glider ships
# both backrakes start at very bottom
# squares in middle, of alternating colors
(xdim, ydim) = get_pattern_size('backrake2')
spaceship1x = cols//4;
spaceship2x = cols//2 + cols//4;
spaceshipy = rows ... |
def get_grid_pattern(pattern_name, rows, columns, xoffset=0, yoffset=0, hflip=False, vflip=False, rotdeg=0):
# convert list of strings to list of lists (for convenience)
ogpattern = get_pattern(pattern_name, hflip=hflip, vflip=vflip, rotdeg=rotdeg)
ogpattern = [list(j) for j in ogpattern]
blank_row = ["... | The function generates two distinct two-color patterns by placing four randomized 'rpentomino' shapes symmetrically around the center of a grid. It creates one pattern on the left side (with negative xoffsets) and another on the right side (with positive xoffsets), applying random horizontal/vertical flips and offsets.... | def eightr_twocolor(rows, cols):
centerx = cols//2
centery = rows//2
# color 1
r1a = get_grid_pattern(
'rpentomino',
rows,
cols,
xoffset=centerx - random.randint(5,10),
yoffset=centery + random.randint(-10, 10),
hflip=bool(random.getrandbits(1)),
... |
def get_grid_pattern(pattern_name, rows, columns, xoffset=0, yoffset=0, hflip=False, vflip=False, rotdeg=0):
# convert list of strings to list of lists (for convenience)
ogpattern = get_pattern(pattern_name, hflip=hflip, vflip=vflip, rotdeg=rotdeg)
ogpattern = [list(j) for j in ogpattern]
blank_row = ["... | The main task of the code is to generate two distinct color patterns using randomly positioned and flipped 'piheptomino' shapes, symmetrically placed around the grid's center. It creates four offset variations for each color (left/right of center), combines them into unified patterns, and returns their URLs for visuali... | def eightpi_twocolor(rows, cols):
centerx = cols//2
centery = rows//2
# color 1
p1a = get_grid_pattern(
'piheptomino',
rows,
cols,
xoffset=centerx - random.randint(5,10),
yoffset=centery + random.randint(-10, 10),
hflip=bool(random.getrandbits(1)),
... |
def policy_ss(Pi, a_grid, y, r, beta, eis, tol=1E-9):
# initial guess for Va: assume consumption 5% of cash-on-hand, then get Va from envelope condition
coh = y[:, np.newaxis] + (1+r)*a_grid
c = 0.05 * coh
Va = (1+r) * c**(-1/eis)
# iterate until maximum distance between two iterations falls be... | The function computes the steady-state distribution and associated variables in a dynamic economic model. It calculates optimal asset holdings (a), consumption (c), and value function (Va) using policy_ss, derives lottery distributions (a_i, a_pi) from asset choices, and determines the stationary distribution (D) via d... | def steady_state(Pi, a_grid, y, r, beta, eis):
Va, a, c = policy_ss(Pi, a_grid, y, r, beta, eis)
a_i, a_pi = get_lottery(a, a_grid)
D = distribution_ss(Pi, a, a_grid)
return dict(D=D, Va=Va,
a=a, c=c, a_i=a_i, a_pi=a_pi,
A=np.vdot(a, D), C=np.vdot(c, D),
... |
def policy_ss(Pi, a_grid, y, r, beta, eis, tol=1E-9):
# initial guess for Va: assume consumption 5% of cash-on-hand, then get Va from envelope condition
coh = y[:, np.newaxis] + (1+r)*a_grid
c = 0.05 * coh
Va = (1+r) * c**(-1/eis)
# iterate until maximum distance between two iterations falls be... | The code computes the steady-state distribution and associated variables for an economic model. It calculates value functions (Va), consumption (c), and assets (a) using a policy function, derives the distribution (D), interpolates lottery values (a_i, a_pi), and aggregates assets (A) and consumption (C) via weighted s... | def steady_state(Pi, a_grid, y, r, beta, eis):
Va, a, c = policy_ss(Pi, a_grid, y, r, beta, eis)
D = distribution_ss(Pi, a, a_grid)
a_i, a_pi = interpolate_lottery_loop(a, a_grid)
return dict(D=D, Va=Va,
a=a, c=c, a_i=a_i, a_pi=a_pi,
A=np.vdot(a, D), C=np.vdot(c, D)... |
def check_win(self, player):
# Checks if player won
if self.check_col_win(player) or self.check_row_win(player) or self.check_diag_win(player):
return True
return False
def check_tie(self):
# Checks for tie
for row in self.board:
for space in row:
... | This function implements the Minimax algorithm with alpha-beta pruning to determine the optimal move for a player in a tic-tac-toe-like game. It evaluates game states recursively, assigning scores based on win/tie conditions, and selects the best move by maximizing the player's score (for 'O') or minimizing the opponen... | def minimax_alpha_beta(self, player, depth, alpha, beta):
if depth > 0:
if self.check_win('O'):
return (10, None, None)
elif self.check_win('X'):
return (-10, None, None)
elif self.check_tie():
return (0, None, None)
els... |
def print_instructions(self):
# Prints the instructions to the game
print("\tWelcome to TicTacToe!")
print("\tPlayer 1 is X and Player 2 is O")
print("\tTake turns placing your pieces - the first to 3 in a row wins!")
return
def print_board(self):
# Prints the board
... | The main task of the code is to execute a tic-tac-toe game by alternating turns between players 'X' and 'O', checking for win or tie conditions after each move, and displaying the game outcome (win or tie) once the game concludes. | def play_game(self):
# Runs the game
self.print_instructions()
self.print_board()
while not self.check_tie() and not self.check_win('X') and not self.check_win('O'):
self.take_turn('X', 5)
self.print_board()
if not self.check_win('X') and not self.chec... |
def is_train_test_file_exists(self):
try:
logging.info("Checking if training and testing file are available or not")
is_train_file_exist=False
is_test_file_exist=False
train_file_path=self.data_ingestion_artifact.train_file_path
test_file... | The main task of the code is to validate data by checking the existence of train/test files, verifying dataset schema compliance, and detecting data drift. If all validations pass, it returns a `DataValidationArtifact` with success status and file paths, logging completion. If errors occur, it raises a `HousingExceptio... | def initiate_data_validation(self) ->DataValidationArtifact:
try:
self.is_train_test_file_exists()
self.validate_dataset_schema()
self.is_data_drift_found()
data_validation_artifact=DataValidationArtifact(
schema_file_path=self.data_va... |
def prevent_Excess(spectra, photo, bands, interpFlag):
"""
This function removes extensions from the list to calibrate because of
insufficient photometric data or bad quality flags.
"""
# First, find the min/max date for which we have photometry taken on each side of the spectroscopic observation
... | This function calibrates spectra by identifying extendable extensions, computing scale factors and warping functions, then applying these to scale spectra. It outputs a FITS file with calibrated data, handling plotting, bad data filtering, and coaddition based on flags. Key steps include determining valid extensions, c... | def calibSpec(obj_name, spectra, photo, outBase, filters, plotFlag, coaddFlag,
interpFlag, redshift):
"""
This function will determine extensions which can be calibrated,
calculate the scale factors, warping function, and output a new fits file
with the scaled spectra.
Parameters
... |
def BFS(start_st,goal_st,forbidden):
current = start_st
expanded = []
fringe = []
limit = 1000
while(len(expanded) != limit):
generate_children(current,forbidden)
if not already_expanded(current,expanded):
expanded.append(current)
fringe = fringe + current.children
if is_goal_st(current,goal_st):
... | The code reads input parameters to execute a specified search algorithm (BFS, DFS, etc.) on a state-space problem. It parses a file to extract the start state, goal state, and forbidden states, then applies the chosen search method to navigate from the start to the goal while avoiding forbidden states. Input validation... | def main(argv):
# search mode
search_mode = argv[0]
# start and goal state
start_st = State()
goal_st = State()
# forbidden list
forbidden = []
# input file
f = open(argv[1])
lines = f.readlines()
if (len(lines) < 2):
return 1
temp = lines[0].split("\n")
if (len(temp[0]) != 3):
return 1
start_st.ini... |
def BFS(self):
# keep a queue for BFS
queue = Queue()
# enqueue the start state to the queue as a tuple (state, parent_state)
self.start_state.set_parent(State(None))
queue.enqueue(self.start_state)
self.expanded.append((self.start_state.get_state(), None))
# ke... | The code executes a specified search algorithm (BFS, DFS, IDS, Greedy, A*, Hill Climbing) based on `self.search_algorithm`, populating `visited` and `expanded` lists with states. It then returns a string representation of the search path and visited states via `toString()`. The method handles algorithm selection, execu... | def solve(self):
# run requested search algorithm populating the visited and expanded lists
if (self.search_algorithm == 'B'):
self.BFS()
elif (self.search_algorithm == 'D'):
self.DFS()
elif (self.search_algorithm == 'I'):
self.IDS()
elif (self... |
def assign_players(self):
if not self.training_mode:
user_role = input("Would you like to play as x or o? ")
if user_role == "x":
self.ai_is_X = False
self.ai_turn = False
def play_turn(self, data):
pos_code = self.code_from_board() # retrieve cod... | The main task of the code is to execute a game loop where players take turns making moves, check if the game has ended after each move, and announce the winner once the game concludes. It initializes player roles, uses position data from the trainer, and terminates when the game finishes. In non-training mode, it expli... | def play_game(self):
self.assign_players() # determine who is x and o
data = self.trainer.code_to_pos
while not self.finished:
# play a turn
self.play_turn(data)
# check if game is over
self.check_game_status() # will adjust finished value to T... |
def encode_new_move(sq, turn):
new_move = 3**(sq - 1) * (2 - (turn % 2))
return new_move
def process_node(self, old_code, old_pos, ai):
# old_pos is a position object representing the position being evaluated (without new move added)
# old_code is the integer code for old_pos
# a... | The code evaluates all available moves in a game state, using a minimax algorithm to determine the best move that minimizes loss. It checks each move's outcome, assigns scores (-1 for loss, 0 for draw, 1 for win), and selects the move with the highest score. If multiple moves yield the same result, it randomly chooses ... | def choose_move(self, old_code, old_pos, ai):
# old_pos is a position object representing the position being evaluated (without new move added)
# old_code is the integer code for old_pos
# ai is True if ai is x, false if ai is o
turn = old_pos.get_turn()
options = old_pos.get_ava... |
def pkg_config(cfg):
"""Returns PkgConfig pkg config object."""
pkg_config_py = os.path.join(
os.path.dirname(os.path.abspath(os.path.expanduser(__file__))),
"pkg_config.py"
)
libpkg = {"__file__": pkg_config_py}
exec(compile(open(pkg_config_py, "rb").read(), pkg_config_py, "... | This script parses command-line arguments to retrieve and output hardware configuration details from a JSON file. It loads a VTA config, processes it, and prints specified parameters like memory banks, widths, FPGA specs, or generates TCL scripts. The main task is to query and export hardware configuration data based o... | def main():
"""Main funciton"""
parser = argparse.ArgumentParser()
parser.add_argument("--use-cfg", type=str, default="",
help="path to the config json")
parser.add_argument("--cflags", action="store_true",
help="print the cflags")
parser.add_argument(... |
def f3(url):
"""Extract everything between 'dir' and '@' from GMaps Route URL."""
match = re.search(r"dir(.+?)@", url)
text = ""
if match:
text = match.group(1)
else:
st.write("Regex Fail ")
substrings = re.split(r"(?<!\\)/(?!\\)", text)
substrings = [x for x in substrings if... | The code extracts latitude and longitude coordinates from Google Maps route URLs while preserving the original order of locations. It processes each URL to identify coordinates, stores them in a list with default placeholders, and maintains location identifiers to ensure order consistency. Additional functions (f1, f2,... | def get_lat_long(urls, num_loc):
"""Extract (latitude, longitude) from Google Maps Route URL with original order maintained."""
lat_long = [(-1, -1)] * (num_loc)
lat_long1 = []
# This is to ensure final output url loc_names are same as that of the original
loc_identifier = []
cnt = 0
for url... |
def stop_flashing(self):
[timer.stop() for timer in self.unclicked_buttons_timers]
print('Flash stopped')
def send_lsl(self, flash=True):
# sending the event markers
# send number 1 when the flash starts
# send number 2 when the flash ends
if flash:
self.outle... | This method finalizes the player's turn by stopping visual feedback, sending a termination signal to an external app, cleaning UI elements, receiving a response, processing the move, updating the interface to indicate the computer's turn, and scheduling a transition to the computer's board view after a 2-second delay. | def complete_player_board_view(self):
self.stop_flashing()
# send LSL termination signal to RenaLabApp
self.send_lsl(flash=False)
# clean up flashing stylesheets
[button.setStyleSheet('background-color: none;') for button in self.buttons]
# receive response back from Ren... |
def draw_sheet(image):
line(image, -SHEET_WIDTH / 2, SHEET_DISTANCE,
SHEET_WIDTH / 2, SHEET_DISTANCE,
3, SHEET_COLOR)
line(image, SHEET_WIDTH / 2, SHEET_DISTANCE,
SHEET_WIDTH / 2, SHEET_DISTANCE + SHEET_HEIGHT,
3, SHEET_COLOR)
line(image, SHEET_WIDTH / 2, SHEET_DISTANCE +... | This code generates a visual simulation of a robotic arm's position by converting input coordinates (x, y) into shoulder and elbow angles, then rendering the arm on a black image with color based on the z-value. It also draws calibration sheet lines, contours (if available), and overlays text with coordinates, angles, ... | def apply(self, x, y, z):
img = np.zeros((VIEW_HEIGHT, VIEW_WIDTH, 3), np.uint8)
shoulder_angle, elbow_angle = sheet_coords_to_angles(x, y, self.profile)
draw_sheet(img)
if self.contours:
draw_contours(img, self.contours)
color = (0, int(255 * z), int(255 * (1 - z)))... |
def chart_excel_ranges(chart):
if type(chart) != list and type(chart[0]) != list:
print("Check if your tables is a nested LIST -- should be! ")
else:
max_col = len(chart[0])
max_col_letter = get_column_letter(max_col)
max_row = len(chart)
headers_range_str = f"A1:{max_col... | This function creates or updates an Excel workbook with multiple sheets, each containing formatted data from the input dictionary. It handles both new workbooks and existing ones, adding sheets, appending data rows, applying autofilters, cell formatting, and adjusting column widths based on content. | def excel_multi_writer(output_charts_dict, loadWorkbook=None):
if not loadWorkbook:
wb = Workbook()
existing_sheets = len(wb.sheetnames)
needed_sheets = len(output_charts_dict)
while existing_sheets < needed_sheets:
wb.create_sheet()
existing_sheets += 1
... |
def api_items(query,nextPageToken=False):
json_response = requests.get(query)
response = json.loads(json_response.text)
items = response["items"]
if nextPageToken == False:
return items
else:
if "nextPageToken" in response:
nextPageToken = response["nextPageToken"]
... | The function retrieves YouTube playlist data by querying each ID in `ids_list`, paginating through results to collect video details (e.g., video ID, position, playlist metadata). It merges this with video-specific data from `video_query`, removing entries with invalid video IDs, and returns a combined dictionary of val... | def playlist_query(ids_list, pageLimit = None):
finalDict = {}
for element in ids_list:
apiQuery = f"{apiBaseUrl['playlist']}{element}&key={ytApiKey}"
print(apiQuery)
nextPageToken = True
pageIndex = 1
if not pageLimit:
pageLimit = 500
while nextPageTo... |
def api_items(query,nextPageToken=False):
json_response = requests.get(query)
response = json.loads(json_response.text)
items = response["items"]
if nextPageToken == False:
return items
else:
if "nextPageToken" in response:
nextPageToken = response["nextPageToken"]
... | The function fetches popular YouTube videos for each country in the input list, extracting detailed metadata (title, channel, duration, etc.) and paginating through API results. It aggregates all video data into a dictionary keyed by video ID, then enriches this data with additional video-specific information via a sec... | def most_popular_query(country_list):
finalDict = {}
# countryCounter = 0
for element in country_list:
# countryCounter+=1
# counter = 0
print(f"Country: {element}")
apiQuery = f"{apiBaseUrl['mostPopular']}{element}&key={ytApiKey}"
nextPageToken = True
while n... |
def html_soup(url,containers_html_tag=None):
with requests.Session() as session:
myClient = urlopen(url)
page_html = myClient.read()
myClient.close()
page_soup = BeautifulSoup(page_html, "html.parser")
if containers_html_tag == None:
return page_soup
else:... | The function `rss_xml_main` fetches YouTube video data from RSS feeds using provided channel IDs, extracts metadata like titles, links, views, and ratings, and compiles it into a dictionary. It then merges this data with additional information from `video_query`, returning a combined dictionary of video details. | def rss_xml_main(ids_list):
finalDict = {}
base_rss_url = "https://www.youtube.com/feeds/videos.xml?channel_id="
for id in ids_list:
id = base_rss_url+id
videos = html_soup(id, containers_html_tag = 'entry')
for video in videos:
videoDict = {
"Video ID": v... |
def eliminate(values):
"""
Go through all the boxes, and whenever there is a box with a value, eliminate this value from the values of all its peers.
Input: A sudoku in dictionary form.
Output: The resulting sudoku in dictionary form.
"""
solved_values = [box for box in values.keys() if len(valu... | The main task of the code is to iteratively apply constraint propagation techniques (elimination, only_choice, naked_pairs, naked_twins, box_line_reduction) to solve a Sudoku puzzle. It repeatedly reduces possibilities until the puzzle is solved, stalls (no new values are determined), or becomes unsolvable (a box has n... | def reduce_puzzle(values):
"""
Iterate eliminate() and only_choice(). If at some point, there is a box with no available values, return False.
If the sudoku is solved, return the sudoku.
If after an iteration of both functions, the sudoku remains the same, return the sudoku.
Input: A sudoku in dicti... |
def reduce_puzzle(values):
"""
Iterate eliminate() and only_choice(). If at some point, there is a box with no available values, return False.
If the sudoku is solved, return the sudoku.
If after an iteration of both functions, the sudoku remains the same, return the sudoku.
Input: A sudoku in dicti... | The code solves a Sudoku puzzle using depth-first search with propagation, enforcing diagonal constraints by pruning invalid branches early. It reduces the puzzle, checks for a valid solution, selects the box with fewest possibilities, and recursively explores valid assignments while ensuring diagonal rules are not vio... | def search(values):
"Using depth-first search and propagation, create a search tree and solve the sudoku."
# First, reduce the puzzle using the previous function
values = reduce_puzzle(values)
# reduce_puzzle can fail once eliminate or only_choice results in sudoku rule violations
if values is False... |
def square_buffer_generator(freq, phase, sample_rate, dutycycle=0.5):
buffer = []
nr_of_samples = get_samples_count(sample_rate, freq)
samples_per_period = sample_rate / freq
phase_in_samples = ((phase / 360) * samples_per_period)
scaler = freq / sample_rate
shift: float = dutycycle / 2
for... | The code generates synchronized digital signals for RGB LED control by creating three square-wave buffers at distinct frequencies (red, green, blue), aligning them via LCM-based length extension, and combining their bits into a unified buffer for simultaneous LED color output. | def create_digital_buffer():
# Create 3 digital clock pattern buffers at 3 different frequencies
# We will use these to drive the RGB LED
# Each signal will turn the LED either Red, Blue or Green
# Do we want to play around with phase, offset and duty cycle ?
square_dutycycle = 0.5
square_offse... |
def setDistancesFromFileCar(self):
try:
f = open(CARFILE, "r")
for line in f:
array = [float(format(float(x[0:len(x) - 1]), '.1f')) for x in line[1:len(line)-1].split(",")]
self.distancesC.append(array)
except IOError:
return 0
def setD... | This code initializes a distance matrix by loading car and bike travel distances from files, randomly dividing parking nodes, applying a legacy traveling matrix transformation to both distance sets, and printing a completion message. | def inititateDistanceMatrix(self):
self.setDistancesFromFileCar()
self.setDistancesFromFileBike()
self.divideParkingNodesAtRandom()
self.distancesB = self.legacyTravelingMatrix(self.distancesB)
self.distancesC = self.legacyTravelingMatrix(self.distancesC)
print("Finished"... |
def addNodesZeroIndexed(inputProblem):
numPNodes = inputProblem["numPNodes"]
numCNodes = inputProblem["numCNodes"]
nodes = list(range(numCNodes+numPNodes))
pNodes = list(range(numPNodes))
cNodes = list(range(numPNodes+1,numPNodes+1 + numCNodes))
inputProblem["nodes"] = nodes
inputProblem["pN... | The code generates a series of snapshots at evenly spaced time intervals by dividing the maximum time limit into specified steps. It reads input problem data, real and artificial operator paths, then creates snapshots using these inputs at each time step. The snapshots are collected and returned as a list for analysis ... | def generate_snapshots(steps,exampleFileName):
pathFileName = output_file_path
artificialFilename = output_file_arti
inputProblem = addNodesZeroIndexed(readExampleFile(exampleFileName))
realOperatorsPaths = readPaths(pathFileName)
artificialPaths = readPaths(artificialFilename)
maxTime = int(gen... |
def getSelectedContestants(self, max_contestants, min_contestants):
return len(max_contestants) + len(min_contestants)
def calcAdvantage(self, max_contestants, min_contestants):
myTeamPower = self.calcPower(max_contestants, 1)
bobsTeamPower = self.calcPower(min_contestants, 2)
return (m... | This function recursively selects contestants to maximize or minimize an advantage value, depending on whether it's the user's team member's turn. It evaluates all possible unpicked contestants, computes the advantage for each choice, and returns the optimal advantage value along with the selected contestant ID. Tie-br... | def minmax(self, n, max_contestants, min_contestants, unpicked_contestants, myTeamMember):
# base case
picked = self.getSelectedContestants(max_contestants, min_contestants)
if picked == n or picked == 10:
adv = self.calcAdvantage(max_contestants, min_contestants)
# print... |
def getSelectedContestants(self, max_contestants, min_contestants):
return len(max_contestants) + len(min_contestants)
def calcAdvantage(self, max_contestants, min_contestants):
myTeamPower = self.calcPower(max_contestants, 1)
bobsTeamPower = self.calcPower(min_contestants, 2)
return (m... | This function implements alpha-beta pruning to select the optimal contestant for a team, recursively evaluating advantages by alternating between maximizing (when myTeamMember is True) and minimizing (when False) strategies. It returns the best advantage value and the selected contestant ID, with tie-breaking favoring ... | def alphaBeta(self, n, max_contestants, min_contestants, unpicked_contestants, alpha, beta, myTeamMember):
# base case
picked = self.getSelectedContestants(max_contestants, min_contestants)
if picked == n or picked == 10:
adv = self.calcAdvantage(max_contestants, min_contestants)
... |
def getTeamlists(self, contestants):
unpicked = {}
myteam = {}
bobsTeam = {}
for id in contestants:
data = contestants[id]
if data[3] == 0:
unpicked[id] = data
elif data[3] == 1:
myteam[id] = data
else:
... | The code initializes a strategy selection mechanism for picking contestants, using either a minmax algorithm (if `alg` is True) or an alpha-beta pruning approach (if `alg` is False). It evaluates potential moves to determine the optimal contestant ID (`self.id`) to select, based on team compositions and unpicked contes... | def __init__(self, n, alg, contestants):
self.unpicked, self.myTeam, self.bobsTeam= self.getTeamlists(contestants)
self.id = 0
#print("myTeam")
#print(self.myTeam)
#print("Bob's team")
#print(self.bobsTeam)
#print("unpicked")
#print(self.unpicked)
... |
def generate_l_sequences(a,b,c,k1,k2,InX,l,M,N):
Out_Seq = [[InX[0]],[InX[1]],[InX[2]],[InX[3]],[InX[4]],[InX[5]]]
seq_In = InX
sequence_size = 2
while sequence_size <= (l + 2 * M * N):
seq_Out = systemX(a,b,c,k1,k2,seq_In)
seq_In = seq_Out
seq1 = Out_Seq[0]
seq1.append(seq_Out[0])
seq2 = Out_Seq[1... | The code decrypts an image using a cryptographic method involving sequence generation, permutation, and substitution. It loads the image, splits channels, generates a sequence, applies permutation and substitution transformations, and saves the decrypted image as 'decrypt.png' | def decrypt (a,b,c,k1,k2,InX,ruta):
im = Image.open(ruta)
im.load()
M,N = im.size
R,G,B = im.split()
l = 1
InXSequence = generate_l_sequences(a,b,c,k1,k2,InX,l,M,N)
Salida2 = discard_old_l_values_of_sequences (InXSequence,l)
R_aux = transform_image_to_value(R,M,N)
G_aux = transform_image_to_value(G,M,N)
B_au... |
def stop_periodic_measurement(self):
self._send_command(_SCD4X_STOPPERIODICMEASUREMENT, cmd_delay=500)
def _set_command_value(self, addr, cmd, buf, value, cmd_delay = 0):
buf[0] = (cmd >> 8) & 0xFF
buf[1] = cmd & 0xFF
self._crc_buffer[0] = buf[2] = (value >> 8) & 0xFF
self._crc_b... | This function forces sensor recalibration using a specified CO2 value by stopping periodic measurements, sending a calibration command, waiting, reading the response, and validating the result. If the calibration fails (correction value = 0xFFFF), it raises an error requiring the sensor to be active for 3 minutes prior... | def force_calibration(self, target_co2):
"""Forces the sensor to recalibrate with a given current CO2"""
self.stop_periodic_measurement()
self._set_command_value(self._addr, _SCD4X_FORCEDRECAL, self._buffer, target_co2)
time.sleep(0.5)
self._read_reply(self._addr, self._buffer, 3... |
def stop_periodic_measurement(self):
self._send_command(_SCD4X_STOPPERIODICMEASUREMENT, cmd_delay=500)
def _send_command(self, cmd, cmd_delay = 0):
self._cmd[0] = (cmd >> 8) & 0xFF
self._cmd[1] = cmd & 0xFF
self._i2c.writeto(self._addr, self._cmd)
sleep_ms(cmd_delay)
def _read_re... | This code performs a self-test on a sensor device by stopping periodic measurements, sending a self-test command with a 10-second delay, reading the response, and raising an error if the first two bytes of the reply are non-zero, indicating failure. | def self_test(self):
"""Performs a self test, takes up to 10 seconds"""
self.stop_periodic_measurement()
self._send_command(_SCD4X_SELFTEST, cmd_delay=10000)
self._read_reply(self._addr, self._buffer, 3)
if (self._buffer[0] != 0) or (self._buffer[1] != 0):
raise Runti... |
def get_port_forward():
""" Get UDM SE/PRO port forwarding rules
Returns:
dict: Port forwarding entries
"""
target_url = f"https://{os.environ['UNIFI_API_HOST']}/proxy/network/api/s/default/rest/portforward"
try:
auth = unifi_api_logon()
response = do_unifi_req... | The code supervises Kubernetes services in the "prism-servers" namespace, ensuring port forwarding rules match their assigned external IPs. It checks each service's LoadBalancer status, compares with existing forwards, creates/deletes rules as needed, and updates PrismServer status objects with forwarding availability.... | def supervise_ips():
"""
Supervises services in prism-servers ns and checks if they have an External-IP asigned.
If yes, checks if a port forwarding rule exists for them.
"""
try:
client = utils.kube_auth()
api = client.resources.get(api_version="v1", kind="Service")
... |
def compute_missing_cells_mask(self, close_ksize=5):
"""
Compute a binary img-scale mask,
"""
# Create white binary img
icellmask = np.full((self.imgshape[0], self.imgshape[1]), 255, np.uint8)
# Mask everything except table, as defined by corner nodes (not the larger sup... | The main task of the code is to filter missing cell contours by retaining only those that lie inside the defined table corners. It computes a mask for missing cells, generates their contours, and applies a spatial filter using the table's corners to exclude contours outside the table boundary. | def compute_filtered_missing_cell_contours(self):
"""
Filter the given missing
"""
missing_cells_mask = self.compute_missing_cells_mask()
missing_cell_contours = self.compute_missing_cell_contours(missing_cells_mask)
table_corners = self.table_corners # fine table corner... |
def fetch_data():
""" download and store data files from OSF"""
print_with_line('fetch data')
# Approach 1: copy the entirety of the OSF repo, e.g.
print_then_call("osf", "-p", osf_project, "clone", "-U", str(here / "data"))
def build_data():
print_with_line('workup data')
print_then_call(pytho... | The main task of the code is to orchestrate a workflow by sequentially executing data fetching, data construction, figure generation, and completion notification. It prints progress updates, calls `fetch_data()` to retrieve data, `build_data()` to process it, `build_figures()` to generate visualizations, and finally co... | def all_():
print('building everything!')
fetch_data()
build_data()
build_figures()
print_with_line('building done!') |
def _save_df(self):
header = parse_header(self._header_line)
description = parse_description(self._description_line, header[0])
self._dfs[header[0]] = description, pd.DataFrame(
self._table, columns=header[1:]
)
self._table = []
self._header_line = ""
... | This method processes the next line from an iterator. It handles end-of-iteration by saving data, then delegates line processing: hash-prefixed lines to _hashline(), others to _tline(). | def _next_line(self):
try:
line = next(self._lines)
except StopIteration:
self._save_df()
raise
if line.startswith("#"):
self._hashline(line)
else:
self._tline(line) |
def terminated(self):
if ((self.map[self.currentLocation[0]][self.currentLocation[1]]) == 0):
return False
else:
return True
def getBestActionFromQtable(self, currentLocation):
x = currentLocation[0]
y = currentLocation[1]
input_list = self.qTable[x][y]
... | This function implements a Q-learning agent that balances exploration and exploitation in a grid-based environment. It starts at a given location, iteratively selects actions (randomly or based on the Q-table), updates its Q-values, tracks rewards, and updates a heatmap. The agent continues until termination, accumulat... | def exploreOrExploit(self, chance):
self.currentLocation = deepcopy(self.startLocation)
reword = 0.0
while not self.terminated():
# If action = 0 then explore
# If action = 1 then exploit
explore = random.uniform(0, 1) < chance
if explore:
... |
def terminated(self):
if ((self.map[self.currentLocation[0]][self.currentLocation[1]]) == 0):
return False
else:
return True
def updateExploreRecord(self):
x = self.currentLocation[0]
y = self.currentLocation[1]
if self.exploreRecordMap[x][y] == '?':
... | This code implements a Q-learning agent that explores an environment by balancing exploration (random actions) and exploitation (best actions from the Q-table). It updates the Q-values based on rewards, tracks the agent's location, and accumulates total rewards. The loop continues until termination or time expires, rec... | def exploit(self, exploreRate):
self.currentLocation = deepcopy(self.startLocation)
reword = 0.0
while not self.terminated() and (time.time() - self.startTime) < self.totalRuntime:
self.updateExploreRecord()
rand = random.uniform(0, 1)
if rand >= exploreRate:... |
def terminated(self):
if ((self.map[self.currentLocation[0]][self.currentLocation[1]]) == 0):
return False
else:
return True
def updateExploreRecord(self):
x = self.currentLocation[0]
y = self.currentLocation[1]
if self.exploreRecordMap[x][y] == '?':
... | The code implements an agent's exploration phase in a Q-learning algorithm. It initializes the agent's position, iteratively selects random actions, updates the Q-table with rewards, tracks the agent's path via a heatmap, and accumulates total rewards. The loop continues until termination or time limit, recording rewar... | def explore(self):
self.currentLocation = deepcopy(self.startLocation)
reword = 0.0
while not self.terminated() and (time.time() - self.startTime) < self.totalRuntime:
self.updateExploreRecord()
nextAct = random.choice(self.actions)
preLocation = deepcopy(sel... |
def display_word_table(word_commonalities):
for (word, freq) in word_commonalities:
print(f"{word:<10} | {freq:<5.2}")
def sort_by_word_commonality(words):
sort_by = operator.itemgetter(1)
return sorted(
[(word, calculate_word_commonality(word)) for word in words],
key=sort_by,
... | The code simulates a computer guessing a secret word by iteratively narrowing down possible candidates. It uses feedback from each guess (green/yellow/gray indicators) to update constraints on letter positions, eliminating invalid options. The computer selects guesses based on word frequency and matches constraints, ai... | def play_game(secret_word):
possible_words = WORDS.copy()
word_vector = [set(string.ascii_lowercase) for _ in range(WORD_LENGTH)]
for attempt in range(1, ALLOWED_ATTEMPTS + 1):
print(f"\nAttempt {attempt} with {len(possible_words)} possible words")
display_word_table(sort_by_word_commonalit... |
def deliver(msg): # upon receive a message
global msg_see_before
global myqueue
global node_name
global timestamp
#print("point 1")
# if have seen before and this time is just a R-multicast from someone else
msg_see_before_lock.acquire()
if msg.MessageID in msg_see_before:
# pri... | The code receives data from a client socket, parses JSON messages, checks for duplicates using a global set with a lock, and delivers/multicasts non-duplicate messages. It ensures message uniqueness, processes valid messages by adding them to a queue, and closes the socket upon receiving empty data. | def __receive(client_socket):
global msg_see_before
global myqueue
while True:
recv_data=client_socket.recv(156).decode('utf-8')
#print("point 9")
if len(recv_data)>0:
# print("receive data:",recv_data,"from client socket",client_socket)
msg=json.loads(recv_dat... |
def read_config(filename):
with open(filename) as f:
node_num=int(f.readline())
# print(node_num)
node_info=[]
for _ in range(node_num):
node_info.append(f.readline())
#print(node_info)
return node_num,node_info
def tcp_listen(host,port):
tcp_server_socket... | The code sets up a network node to connect to other nodes using TCP, listens for messages on a specified port, waits for all connections to be established, and logs performance metrics like message transmission times and bandwidth to a file upon encountering an error. It uses threading for concurrent connections and me... | def main():
if len(sys.argv) != 4:
print('Incorrect input arguments')
sys.exit(0)
global node_name
global connection_bulid
global tcp_socket_dict
global ALL_CONNECTED
global time_record
node_name = sys.argv[1]
port = int(sys.argv[2])
host = '127.0.0.1' # can connect w... |
def get_pattern_response(self, message):
message = [self.lemmatize_word(word.lower()) for word in nltk.word_tokenize(message)]
# Search the pattern intents file first
for intent in self.pattern_intents['Intents']:
if self.message_match(intent['Patterns'], message):
r... | The code's main task is to generate a response based on either a predefined pattern or detected emotion. It first checks for a pattern-matched response; if none is found, it analyzes the message's emotion and returns a response tailored to that emotion. | def get_response(self, message):
pattern_response = self.get_pattern_response(message)
if pattern_response:
return pattern_response
else:
emotion = self.detect_emotion(message)
response = self.get_response_by_emotion(emotion)
return response |
def _build_opt_grp_title(self, group: _ArgumentGroup, prefix: str, sub_title_prefix: str, title_prefix: str) -> str:
title_text, elements = "", prefix.split(" ")
if title_prefix is not None:
title_prefix = title_prefix.replace("{prog}", elements[0])
if title_prefix:
... | This function generates a structured documentation section for a command-line option group. It creates a titled section with a unique ID, includes the group's description if present, and lists each option as a bullet point. The section is built using the group's title, prefix, and actions, ensuring proper formatting an... | def _mk_option_group(self, group: _ArgumentGroup, prefix: str) -> section:
sub_title_prefix: str = self.options["group_sub_title_prefix"]
title_prefix = self.options["group_title_prefix"]
title_text = self._build_opt_grp_title(group, prefix, sub_title_prefix, title_prefix)
title_ref: st... |
def _build_sub_cmd_title(self, parser: ArgumentParser, sub_title_prefix: str, title_prefix: str) -> str:
title_text, elements = "", parser.prog.split(" ")
if title_prefix is not None:
title_prefix = title_prefix.replace("{prog}", elements[0])
if title_prefix:
titl... | This function generates a structured section for a subcommand by constructing a title with optional aliases, creating a reference ID, and aggregating description, usage, and option groups from an ArgumentParser into a document section. | def _mk_sub_command(self, aliases: list[str], help_msg: str, parser: ArgumentParser) -> section:
sub_title_prefix: str = self.options["group_sub_title_prefix"]
title_prefix: str = self.options["group_title_prefix"]
title_text = self._build_sub_cmd_title(parser, sub_title_prefix, title_prefix)
... |
def make_id(key: str) -> str:
return "-".join(key.split()).rstrip("-")
def _mk_usage(self, parser: ArgumentParser) -> literal_block:
parser.formatter_class = lambda prog: HelpFormatter(prog, width=self.options.get("usage_width", 100))
texts = parser.format_usage()[len("usage: ") :].splitlines()
... | The code constructs a document structure (home_section) for a CLI interface, including title, description, usage, option groups, and sub-commands. It dynamically generates sections based on parser configurations, formats descriptions appropriately, and aggregates all elements into a list of Node objects for output. | def run(self) -> list[Node]:
# construct headers
self.env.note_reread() # this document needs to be always updated
title_text = self.options.get("title", f"{self.parser.prog} - CLI interface").strip()
if not title_text.strip():
home_section: Element = paragraph()
els... |
def _l2reg(weight_decay=1e-4):
return l2(weight_decay)
def _dense_block(x, nb_layers, nb_filters, growth_rate, dropout):
block_layers = [x]
for _ in range(nb_layers):
layer = _convolution_block(x, growth_rate, dropout)
block_layers.append(layer)
x = Concatenate(axis=3)([x, layer])
... | This function constructs a Fully Convolutional DenseNet (FC-DenseNet) model for image segmentation or classification. It builds dense blocks with specified layers, transition layers for downsampling, and skip connections for feature reuse. The model uses growth rate, compression, and dropout parameters to control compl... | def DenseNet(dense_block_layers=None, growth_rate=16, initial_nb_filters=48, compression=1.0, dropout=0.2,
model_name_suffix="", input_size=(224, 224, 3)):
nb_filters = initial_nb_filters
nb_conv_layers = 0
if dense_block_layers is None:
dense_block_layers = [4, 5, 7, 10, 12, 15]
s... |
def set_player_turn(self, turn):
if turn in TictactoeGame.VALID_TURN_ENTRY:
self.player_turn = turn
else:
self.player_turn = env.CIRCLE
print("The 'player_turn' paramter was not recognized, and thus set to CIRCLE.\n")
def set_ai(self, ai):
if ai is TictactoeGa... | The code initializes a Tic-Tac-Toe game by setting the current player's turn, configuring the AI opponent (defaulting to MINIMAX_COMP_NAME), creating a game instance, and initiating gameplay via the play() method. It prepares the game environment and triggers the main game loop to start player vs. AI interaction. | def __init__(self, player_turn=env.CIRCLE, ai=MINIMAX_COMP_NAME):
self.set_player_turn(player_turn)
self.set_ai(ai)
self.game = env.Tictactoe()
self.play() |
def BruteLen1(x):
global num_guess, match
for i in range(len(strngs)):
num_guess += 1
guess = x + strngs[i]
guess_hash = str(hashlib.md5(str.encode(guess)).hexdigest())
match = FindMatch(guess, guess_hash, num_guess)
if match:
break
return match
def BruteL... | The code performs a brute-force password cracking attack by allowing the user to select a character set, generating password guesses of varying lengths, and checking for a match. It tracks the number of attempts and elapsed time, displaying results if the password is cracked or reporting failure with statistics if not. | def Bruteforce_crack():
global strngs, start_time, num_guess
num_guess = 0 #Initialize guess counter
match = False #Initialize boolean that will become True when password is cracked
while True:
#Prompt user for choice
print("Choose character set for brute force attack from the follo... |
def generateKeys(bitlength, seed):
p = generate_prime(bitlength,20)
q = generate_prime(bitlength,20)
n = p*q
pq =(p-1)*(q-1)
e = generate_prime(bitlength, 20)
while (e>n):
e = generate_prime(bitlength,20)
d = pow(e,-1,pq)
retKey = rsakey(bitlength, e, d, n)
return retKey
def writeKeyToFile(key... | This code processes command-line arguments to control a cryptographic tool, handling key generation, encryption/decryption, digital signatures, and cracking. It toggles verbosity, sets input/output files, generates keys, encrypts/decrypts files using public/private keys, signs data, verifies signatures, and attempts to... | def main():
global verbose, showPandQ, outputFileName, inputFileName
outputFileName = "output.txt"
inputFileName = "input.txt"
keyName = "default"
seed = 0
i = 1
while i < len(sys.argv):
if sys.argv[i] == "-verbose":
verbose = not verbose
elif sys.argv[i] == "-... |
def find_min_edge(path_grid: list):
min_cell: Cell = None
for row in path_grid:
for cell in row:
if (cell.get_cost() is None) or (not cell.get_edge()):
continue
if min_cell is None:
min_cell = cell
elif cell.get_cost() < min_cell.get_c... | The code implements Dijkstra's algorithm to find the minimum cost path from the top-left to the bottom-right corner of a grid. It maintains a grid of cells with calculated path costs, updating each cell's cost and parent when a cheaper route is found. The algorithm iteratively selects the cell with the lowest current c... | def part_one():
array = Utils.get_file_as_array('Inputs/Day15.txt')
grid = [[int(c) for c in line.strip('\n')] for line in array]
# maze will continue to be solved until the end is reached
# maintain a grid of the cheapest discovered path to reach any position
# from whatever the current cheapest 'e... |
def convert(i: int):
if i > 9:
return convert(i-9)
return i
def find_min_edge(path_grid: list):
min_cell: Cell = None
for row in path_grid:
for cell in row:
if (cell.get_cost() is None) or (not cell.get_edge()):
continue
if min_cell is None:
... | The code reads a grid from a file, expands it 5 times in each dimension by incrementing values, then uses Dijkstra's algorithm to find the minimum path cost from the top-left to the bottom-right corner of the expanded grid, dynamically updating cell costs and recalculating neighbors as needed. | def part_two():
array = Utils.get_file_as_array('Inputs/Day15.txt')
grid = [[int(c) for c in line.strip('\n')] for line in array]
big_grid = []
for i in range(5):
for row in grid:
big_row = []
for j in range(5):
for e in row:
big_row.ap... |
def get_piece(self, name):
# this does not take into account if the piece is a king
for piece in self.pieces:
if piece.name == name:
return piece
def next_user_moves(self, player_pieces):
# returns final possible moves for the player
final_possible_moves = []
... | The function calculates how many times a specified game piece can be captured by the opponent's moves. It determines the enemy color, generates all possible enemy moves, and counts instances where the target piece is absent from the board after each move, indicating a potential capture. | def can_be_eaten(self, piece_name):
'''returns how many times a piece can be eaten by an enemy'''
count = 0
piece = self.get_piece(piece_name)
if piece.color == "Red":
enemy_color = "White"
else:
enemy_color = "Red"
possible_moves... |
def calculate_stats(self):
'''resets the values for the number of pieces of the board'''
red = 0
white = 0
red_kings = 0
white_kings = 0
for piece in self.pieces:
if piece.color == "White":
white += 1
if piece.is_king:
... | The function checks if a game is over by verifying if the current player has no remaining pieces or no valid moves. It returns True when either condition is met: if the player's piece count is zero or if no moves are possible for their pieces. | def check_game_over(self, color_turn):
'''returns true if there are no more pieces left or all pieces are cornered'''
over = False
self.calculate_stats()
if color_turn == "White" and self.white_pieces == 0:
over = True
elif color_turn == "Red" and self.red_pieces =... |
def pieces_of_color(self, color):
# returns pieces of specific color
# pass "White" or "Red"
pieces = []
for piece in self.pieces:
if piece.color == color:
pieces.append(piece)
return pieces
def can_be_eaten(self, piece_name):
'''retur... | The code calculates a game score for the AI by evaluating white pieces' value (5 for regular, 8 for king), positional bonuses (7 for edge pieces), penalties for being capturable, and rewards for potential captures of red pieces. The final score combines these factors with a 1000-point bonus per white piece over red, pr... | def calculate_score(self):
outcome = 0
white_pieces = self.white_pieces
red_pieces = self.red_pieces
for piece in self.pieces_of_color("White"):
if piece.is_king:
outcome += 8
else:
outcome += 5
# i... |
def check_path(self):
self.path = []
self.end_is_reachable = False
self.cells_that_can_be_the_start = []
for cell in self.interface.enemyPath:
if self.can_be_start(cell):
self.cells_that_can_be_the_start.append(cell)
if not len(self.cells_that_can_be_t... | The code's main task is to add a new level directory by checking input validity. If valid, it increments the level number based on existing directories and creates a new level folder. If invalid, it displays an error message. | def add(self):
if self.check_path() and self.check_info():
level_number = len(
os.listdir("{}Levels/".format(self.directory))) + 1
self.make_level_dir(level_number)
else:
reply = QMessageBox.question(self, 'Message', "Wrong input",
... |
def check_path(self):
self.path = []
self.end_is_reachable = False
self.cells_that_can_be_the_start = []
for cell in self.interface.enemyPath:
if self.can_be_start(cell):
self.cells_that_can_be_the_start.append(cell)
if not len(self.cells_that_can_be_t... | The code's main task is to validate conditions for editing a game level. It checks if the current level exists, path/info are valid, and the level is in the directory. If all conditions are met, it dumps level data; otherwise, it alerts the user with a "Wrong input" message via a QMessageBox. | def edit(self):
if self.current_level is not None \
and self.check_path() \
and self.check_info() \
and self.current_level in os.listdir(
"{}Levels/".format(self.directory)):
self.dump_level_info()
else:
reply = ... |
def add(self):
if self.check_path() and self.check_info():
level_number = len(
os.listdir("{}Levels/".format(self.directory))) + 1
self.make_level_dir(level_number)
else:
reply = QMessageBox.question(self, 'Message', "Wrong input",
... | This method handles button click events to perform actions like adding, editing, or deleting levels/waves. It updates wave properties (unit, delay), manages UI elements (lists, inputs), and synchronizes data between the GUI and internal structures (e.g., `self.level`, `self.wave`). | def buttonClicked(self):
sender = self.sender()
if sender == self.add_level:
self.add()
elif sender == self.edit_level:
self.edit()
elif sender == self.remove_level:
self.delete()
elif sender == self.add_wave:
self.wave.wave["Unit"]... |
def createPath(cameFrom,curNode):
path = [curNode]
while curNode in cameFrom.keys():
curNode = cameFrom[curNode]
path.append(curNode)
path = path[::-1]
return path
def fscore(M, key, curNode, goal):
f = gscore(M,key,curNode) + hscore(M, key,goal)
return f
def gscore(M,node1,node2... | This function implements the A* algorithm to find the shortest path from a start node to a goal node in a graph. It uses a frontier set to track unexplored nodes with tentative scores, an explored set for processed nodes, and a gScore dictionary to store the cost to reach each node. The algorithm iteratively selects th... | def shortest_path(M,start,goal):
#initialize sets for frontier and explored
frontier = {start:0}#Visited not expanded
explored = set()#visited and expanded
gScore={}
gScore[start]=0
path=[]
curGScore=0
cameFrom={}
#initialize current state
curNode = start
while fron... |
def get_branch_name(branch_in):
temp = branch_in.split('/')
if len(temp) > 1:
return '/'.join(temp[1:])
else:
return branch_in
def run_command(command_body, cwd):
command_result = local('cd {} && {}'.format(cwd, command_body), capture=True)
print(command_result)
return command_result
def merge_to_de... | The function clones a specified Git branch from a URI, merges it into the 'develop' branch, and optionally pushes the merged changes. If `no_push_uri` is True, it skips the push step. Key tasks: cloning, merging, conditional pushing. | def process_pre_merge_branch(PUSH_URI, pre_merge_branch_in, cwd, no_push_uri = False):
branch_name = get_branch_name(pre_merge_branch_in)
run_command('git clone -b {} {} .'.format(pre_merge_branch_in, PUSH_URI), cwd)
merge_to_develop_branch(pre_merge_branch_in, cwd)
if no_push_uri:
print('no pushing commi... |
def run_command(command_body, cwd):
command_result = local('cd {} && {}'.format(cwd, command_body), capture=True)
print(command_result)
return command_result
def merge_to_master_branch(branch_to_merge, cwd):
checkout_branch('master', cwd)
run_command('git merge --ff-only "{}"'.format(branch_to_merge), cwd)
de... | The function clones a specified pre-merge branch, merges it into the master branch, and optionally pushes the merged changes. It first clones the pre-merge branch using git, merges it into master via `merge_to_master_branch`, then conditionally pushes the result to the remote repository unless `no_push_uri` is True. Th... | def process_pre_merge_master_branch(PUSH_URI, pre_merge_branch_in, cwd, no_push_uri = False):
'checkout pre-merge-master branch'
'on master branch, merge pre-merge-master and re-test'
run_command('git clone -b {} {} .'.format(pre_merge_branch_in, PUSH_URI), cwd)
merge_to_master_branch(pre_merge_branch_in, cwd... |
def get_branch_name(branch_in):
temp = branch_in.split('/')
if len(temp) > 1:
return '/'.join(temp[1:])
else:
return branch_in
def run_command(command_body, cwd):
command_result = local('cd {} && {}'.format(cwd, command_body), capture=True)
print(command_result)
return command_result
def merge_to_fe... | The function clones a specified test branch from a given URI, merges it into a new 'feature/' branch, and optionally pushes the merged changes to the remote repository. If 'no_push_uri' is True, it skips the push step. The process involves git operations like cloning, merging, and pushing within a specified working dir... | def process_test_branch(PUSH_URI, test_branch_name, cwd, no_push_uri = False):
branch_name = get_branch_name(test_branch_name)
feature_branch_name = 'feature/'+branch_name
# CAUTION: using cwd inside run_command
run_command('git clone -b {} {} .'.format(test_branch_name, PUSH_URI), cwd)
merge_to_feature_... |
def get_branch_name(branch_in):
temp = branch_in.split('/')
if len(temp) > 1:
return '/'.join(temp[1:])
else:
return branch_in
def run_command(command_body, cwd):
command_result = local('cd {} && {}'.format(cwd, command_body), capture=True)
print(command_result)
return command_result
def merge_to_pr... | The function processes a feature branch by cloning it, merging into a pre-merge branch, and optionally pushing changes. It clones the feature branch into a local repository, merges it into a 'pre-merge' branch, and conditionally pushes the merged commits to a remote URI, skipping the push if specified. | def process_feature_branch(PUSH_URI, feature_branch_in, cwd, no_push_uri = False):
branch_name = get_branch_name(feature_branch_in)
pre_merge_branch = 'pre-merge/'+branch_name
# CAUTION: using cwd inside run_command
run_command('git clone -b {} {} .'.format(feature_branch_in, PUSH_URI), cwd)
merge_to_pre... |
def get_branch_name(branch_in):
temp = branch_in.split('/')
if len(temp) > 1:
return '/'.join(temp[1:])
else:
return branch_in
def run_command(command_body, cwd):
command_result = local('cd {} && {}'.format(cwd, command_body), capture=True)
print(command_result)
return command_result
def merge_to_pr... | The function processes a fix branch by cloning the repository, creating a pre-merge branch, merging changes, and optionally pushing the merged commit to a remote URI. It takes parameters like the push URI, branch name, working directory, and a flag to skip pushing. The task involves preparing a fix branch for merging a... | def process_fix_branch(PUSH_URI, fix_branch_in, cwd, no_push_uri = False):
branch_name = get_branch_name(fix_branch_in)
pre_merge_branch = 'pre-merge/'+branch_name
# CAUTION: using cwd inside run_command
run_command('git clone -b {} {} .'.format(fix_branch_in, PUSH_URI), cwd)
merge_to_pre_merge_branch(fix_... |
def categorize_branch(branch_to_test):
if branch_to_test[0:4] == 'fix/':
return CONST_BRANCH_FIX
elif branch_to_test == 'develop':
return CONST_BRANCH_DEVELOP
elif branch_to_test == 'pre-merge-master':
return CONST_BRANCH_PRE_MERGE_MASTER
elif branch_to_test[0:8] == 'feature/':
return CONST_BRA... | The main task of the code is to determine the type of the current Git branch (e.g., test, feature, fix, pre-merge, develop, pre-merge-master) and execute branch-specific merging logic by calling corresponding processing functions. It uses `categorize_branch` to identify the branch type, then routes the workflow to merg... | def main(PUSH_URI, TEMP_DIR):
print('starting merger')
print(f'current branch {TRAVIS_BRANCH}')
if categorize_branch(TRAVIS_BRANCH) == CONST_BRANCH_TEST:
# test branch will merge to feature branch
print("this is test branch, will checkout to feature branch")
process_test_branch(PUSH_URI, TRAVIS_BRANC... |
def print_matrix(matrix):
print("=================================")
for i in range(len(matrix)):
print("[ ", end="")
for j in range(len(matrix[i])):
if j != 0:
if int(matrix[i][j]) == matrix[i][j] or abs(math.floor(matrix[i][j]) - matrix[i][j]) <= 0.00000000001:
... | The code performs LU decomposition on a given matrix and computes its inverse. It reads an n×n matrix, decomposes it into lower (L) and upper (U) triangular matrices via recursive factorization, then calculates the inverse using these decompositions. The original matrix, L, U, and the inverse are printed for verificati... | def main():
n = int(input())
A = [[0.0 for i in range(n)] for j in range(n)]
U = [[0.0 for i in range(n)] for j in range(n)]
L = [[0.0 for i in range(n)] for j in range(n)]
for i in range(n):
A[i] = [float(x) for x in input().split()]
print("A:")
print_matrix(A)
U[0] = A[0].copy... |
def print_matrix(matrix, n, m):
print("=================================")
for i in range(n):
print("[ ", end="")
for j in range(m):
if j != 0:
if int(matrix[i][j]) == matrix[i][j] or abs(
math.floor(abs(matrix[i][j])) - abs(matrix[i][j])) <= 0... | The main task of the code is to convert a matrix into reduced echelon form, compute its null space, row space, and column space bases, and analyze linear combinations. It reads an input matrix, transforms it using recursive algorithms, prints the reduced echelon form, and derives fundamental subspaces for linear algebr... | def main():
n, m = input().split()
n = int(n)
m = int(m)
A = [[0.0 for i in range(m + 1)] for j in range(n)]
for i in range(n):
A[i] = [float(x) for x in input().split()] + [0.0]
print("Matrix A:")
print_matrix(A, n, m)
reduced_echelon_A = copy.deepcopy(A)
recursive_reduced_e... |
def sample_action(self, obs):
return self.epsilon_greedy(obs)
def update(self):
pass
def reset(self):
# self.q_table = np.random.rand(self.num_states, self.num_actions)
pass | The main task of the code is to train an agent by interacting with an environment for a specified number of steps. It accumulates rewards per episode, updates the agent's policy using observed transitions, and resets the environment when episodes terminate or truncate. The function returns a list of total rewards for e... | def learn(self, env, step_limit):
obs, info = env.reset()
reward_per_episode = []
sum_of_reward = 0
for _ in range(step_limit):
action = self.sample_action(
obs
) # agent policy that uses the observation and info
next_obs, reward, ter... |
def sample_diffuse(node, H, T, num):
# sample num states in the diffuse part of a node
states = []
for _ in range(num):
sample_policy_init_state(node, T)
for _ in range(H):
action = node.value.env.action_space.sample()
state, _, terminated_truncated, info = node.value... | The code trains a policy using a discriminator network to evaluate states. It iteratively samples states, trains the discriminator to classify node states, checks if the minimum discrimination value meets a threshold, and trains the policy if not. The main task is to learn a policy that meets a discrimination threshold... | def policy_learning(state_buffer, root, nodes, discrim_threhold, H, T, device):
# parameters
step_limit = 100000
p2d_ratio = 30
discrim_epoch = 1000
iterations = 40
discrim_lr = 1e-4
discrim_bs = 64
num_skills = root.count() - 1
mapping = root.get_mapping()
print("==============... |
def get_all_rows(table_name, *args):
cursor = db_connection.cursor()
cursor.execute(f"SELECT {', '.join(args)} FROM {table_name}")
rows = cursor.fetchall()
# Get column headers for dictionary use
columns = [column[0] for column in cursor.description]
return columns, rows
def get_exempt_patient_... | The main task of the code is to fetch patient and notification data from MySQL tables, identify exempt patients based on notification status, and send targeted notifications to non-exempt patients using their personal details and flag IDs. | def lambda_handler(event, context):
# Make MySQL request to fetch all rows from Patients table with required columns
patients_columns, patients_rows = get_all_rows("Patients", "patient_ID", "first_name", "family_name", "mobilePhone", "emailAddress", "flag_ID")
# Make MySQL request to fetch all rows from No... |
def get_E(self):
# DESCRIPTION
# Generate matrix E,using
# eigenvectors of covariance matrix.
return self.get_eigen()[1]
def get_A(self):
# DESCRIPTION
# Generate matrix A, containing two
# arrays of samples.
eigvals,eigvects=self.get_eigen()
... | The main task of the code is to compute a matrix $ X $ by performing a matrix multiplication of $ E $ and $ A $ using NumPy's `dot` function, then adding the matrix $ \mu $ to the result. The function retrieves $ E $, $ A $, and $ \mu $ from the class instance, combines them via linear algebra operations, and returns t... | def calc_X(self):
E = self.get_E()
A = self.get_A()
Mu = self.get_Mu()
X=np.dot(E,A)+Mu
return X |
def getUnassignedLocation(puzzle):
flat_puzzle = [i for row in puzzle for i in row]
index = flat_puzzle.index(0) if 0 in flat_puzzle else -1
return [index // 9, index % 9] if index >= 0 else [9, 9]
def isSafe(puzzle, row, col, num):
return (
not usedInRow(puzzle, row, num)
and not usedI... | This function solves a Sudoku puzzle using backtracking. It identifies the next empty cell, attempts valid numbers from a filter, checks safety, and recursively solves. If no valid number works, it backtracks. The filter likely restricts possible values for efficiency. | def solve_sudoku(puzzle, filter):
# get the next free cell.
row, col = getUnassignedLocation(puzzle)
# if the cell is 9,9 the sudoku is solved.
if (row == 9 and col == 9): return True
# try insert 1 thru 9.
for i in filter[row][col]:
if isSafe(puzzle, row, col, i):
puzzle[r... |
def validate(puzzle):
# check sizes.
if len(puzzle) != 9: return False
if False in [len(row) == 9 for row in puzzle]: return False
# check counts.
if max([row.count(i) for row in puzzle for i in range(1, 10)]) > 1: return False
if max([getPuzzleCol(puzzle, col).count(i) for col in range(9) ... | The main task of the code is to solve a Sudoku puzzle by validating the input, generating a filter for possible values, and applying a solving algorithm. If the puzzle is invalid, it returns False; otherwise, it returns the solved puzzle. | def sudoku_solver(PUZZLE):
# validate the puzzle
if not validate(PUZZLE): return False
FILTER = filter_sudoku(PUZZLE)
solved = solve_sudoku(PUZZLE, FILTER)
return PUZZLE |
def actualization_date(answer = "no"):
answer = answer.lower().split()[-1]
if answer == "yes":
return str(datetime.date.today())
else:
return None
def add_or_substract(data, amount, account_1, account_2):
key_1, id_1 = search_for_index(data, account_1)
key_2, id_2 = search_for_index(... | The main task of the code is to update a balance sheet by adjusting specified accounts with a given amount, set a new date, and optionally display the formatted balance sheet. It modifies the dictionary structure, ensures totals are calculated, and temporarily alters a header for proper display before reverting it, ret... | def new_or_current_balance(balance_sheet, account_1, account_2, amount):
#Create the date object
actual_date = actualization_date("yes")
#This sets the date of the new balance sheet
balance_sheet["Assets"][17] = f"Date: {actual_date}"
#This makes the corresponding additions and substractions to t... |
def watch_list_of_accounting_items(answer):
breaker_of_list_loop = True
if answer == "yes":
while breaker_of_list_loop == True:
#accounting_item: Which type of accounting item? Assets, Liabilities or Equity?
accounting_item = input("Which type of accounting item? Assets, Liabilit... | The main task of the code is to create or modify a balance sheet CSV file by allowing users to input changes to accounts (assets, liabilities, equity) and their amounts. It handles both new files (initialized with predefined account structures and zero balances) and existing files (loaded from CSV, modified, and saved ... | def main():
#Question 0: Are we working with a new file? (yes/no)
new_file = input("Are we working with a new file?(yes/no) ").lower()
#new_file = "no"
#see_list_of_items: Whould you like to see a list of the availables accounts first? (yes/no)
see_list_of_items = input("Whould you like to see a lis... |
def update_trial_values(self):
same_participant = True
if self.index >= len(self.plan): #end of the file
return False
trial_str = self.plan[self.index]
trial_str = trial_str.replace('\r\n', '')
trial_str = trial_str.replace('\n', '')
... | The main task of the code is to log trial data by recording selected targets, trial parameters, and timestamps into a list. It checks if the experiment should continue by updating trial values; if not, it saves the accumulated data as a semicolon-separated string, names the file with the participant ID, and transitions... | def stop_trial(self):
selected_target = self.canvas.selected_target
self.times.append((self.shapes[selected_target], self.shapes[self.pos_target],self.t, self.condition, self.mat_size))
self.index = self.index + 1
if self.update_trial_values():
self.setup_trial()
els... |
def get_data():
return yaml.full_load(os.environ["CAMPSITES"])
def campsite_schedule_cron(source, site_name, facility_id, start_date, number_of_nights, consecutive_nights_required):
if datetime.strptime(start_date, "%m-%d-%Y") < datetime.today():
print(source, site_name, facility_id, start_date, number_... | The code schedules cron jobs for campsites and permits based on availability data. It retrieves data, iterates through campsites and permits entries, extracts details like dates, IDs, and requirements, then calls respective scheduling functions to set up recurring tasks. | def check_availability():
data = get_data()
if data:
for source, entries in data.get('campsites', {}).items():
for entry in entries:
site_name = entry['name']
facility_id = entry['facility_id']
start_date = entry['start_date']
n... |
def get_moves(gid, board):
"""Returns a string of the moves played in the game"""
moves = ''
for val in board.stream_game_state(gid):
moves = val['state']['moves']
break
return moves
def make_move(move, made_moves, gid, berserk_board):
"""Makes a move on the board after checking it i... | The function `command_move` handles user input for a move in a game, validates it, and processes the move. It checks if the game is over after each move. If the user inputs 'back', it exits without ending the game. After a valid move, it waits for the computer's turn, prints the computer's move, and checks again for ga... | def command_move(gid, berserk_board, colour):
"""The (make) move command. Returns True if the game is over, False if not."""
moves = get_moves(gid, berserk_board)
move = input("Input Move: ")
while move != 'back' and not make_move(move, moves, gid, berserk_board):
print("That move is invalid. Pl... |
def get_title(source: dict) -> str:
return source.get("sub", "")
def get_text(source: dict) -> str:
text = source.get("com")
if text:
return cleanhtml(text)
return ""
def get_image_link(source: dict) -> str:
ext = source.get("ext")
i_name = source.get("tim")
if ext and i_name:
... | The function creates a JSON file containing data from a 4chan thread, including the thread's title, text, image link, and replies. It fetches thread data via an API using the provided thread index, extracts relevant information from the response, and saves it in a specified directory with a filename based on the thread... | def create_file(no: int, directory: str) -> None:
"""
Creates a file with title, text and link on image of thread and comments with text and image link
:param no: index of thread (["no"] parameter in API)
:param directory: directory where to save file
:return: nothing
"""
link = fr"https://b... |
def set_catalog_mod_date():
with open("config.json", "r") as file:
config = json.load(file)
config["catalog_modified_date"] = datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S') + " GMT"
with open("config.json", "w") as file:
json.dump(config, file)
def change_comments(no: int, path: s... | The function `check_catalog` updates files in a specified directory based on data from an external catalog. It loads configuration details, fetches catalog data, and iterates through entries to either update existing files with new comments or create new files. It enforces a 1-second delay per iteration to manage reque... | def check_catalog() -> None:
"""
:return: updates files from catalog
"""
with open("config.json", "r") as file:
config = json.load(file)
directory = config["folder_path"]
last_modified = config["catalog_modified_date"]
set_catalog_mod_date()
reply = requests.get(CATALOG).json()
... |
def set_archive_mod_date():
with open("config.json", "r") as file:
config = json.load(file)
config["archive_modified_date"] = datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S') + " GMT"
with open("config.json", "w") as file:
json.dump(config, file)
def change_comments(no: int, path: s... | The main task of the code is to synchronize and update archived threads by fetching new entries from a remote source, checking local files for existence, updating or creating files as needed, and updating the configuration file with the latest processed thread identifier. | def archive_rec() -> None:
"""
Updating archived threads
:return: nothing
"""
with open("config.json", "r") as file:
config = json.load(file)
last_local_thread = config["last_archive_element"]
last_modified = config["archive_modified_date"]
set_archive_mod_date()
reply = requ... |
def format_data(data: str) -> list:
"""Converts the input data into a list of tuples"""
new_data = []
for i, line in enumerate(data):
game_str, draws = line.split(":")
game = []
for j, draw in enumerate(draws.split(";")):
draw = draw.strip()
colors = draw.spli... | The main task of the code is to process input data by formatting it, then compute and print two distinct results (Part 1 and Part 2) derived from the processed data using separate functions. The `main` function orchestrates data formatting and result generation, outputting both parts for analysis or display. | def main(data: str) -> None:
data = format_data(data)
print(f"Part 1: {part1(data)}")
print(f"Part 2: {part2(data)}") |
def speelbare_kolommen(bord):
kolommen = []
for kol in range(kolom_aantal):
if is_kolom_vol(bord, kol):
kolommen.append(kol)
return kolommen
def einde_spel(bord):
return winst(bord, 1) or winst(bord, 2) or len(speelbare_kolommen(bord)) == 0
def winst(bord, speler):
# check voor h... | This code implements the Minimax algorithm with alpha-beta pruning to determine the optimal move in a Connect Four-like game. It evaluates all playable columns, recursively explores game states up to a given depth, and selects the move that maximizes/minimizes the score depending on whether the bot or human is playing.... | def minmax(bord, diepte, alpha, beta, maximaliseren):
# pak speelbare kolommen en sorteer ze op middelste.
kolom_keuze = speelbare_kolommen(bord)
kolom_keuze.sort(key=middelste)
# Check of er vier op een rij is of een vol speelbord.
if einde_spel(bord):
if winst(bord, mens):
retu... |
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who has the next turn on a board.
"""
xCounter = 0
oCounter = 0
for i in ra... | The code implements the **minimax algorithm** with **depth-first search (DFS)** and **pruning** to determine the optimal move for the current player on a tic-tac-toe board. It recursively evaluates all possible game states, assigns scores based on terminal outcomes (win, lose, draw), and propagates scores upward. When ... | def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
#Copying
newBoard = initial_state()
for i in range(3):
for j in range(3):
newBoard[i][j] = board[i][j]
newState = State(newBoard,None,None) #Convert to State
stack = []
st... |
def ask_user_input(self) -> str:
user_input = input('Your guess: ')
user_input_mod = user_input.strip().upper()
return user_input_mod
def try_solution(self, user_input: str) -> None:
if len(user_input) == 0:
print("You haven't entered anything; try again.")
return... | This code runs a game loop that repeatedly prints the current game state, prompts the user for a guess, checks the guess against the solution, and updates the game state based on the game's internal logic until the exit condition is met. | def loop(self) -> None:
while self.exit:
self.state.print()
guess = self.ask_user_input()
self.try_solution(guess)
self.state = self.update_state(gamecode=self.state.gamecode) |
def check_club_create():
create_df = get_df_from_sheet('club_create')
#print(edit_df.index)
if len(create_df.index)==0: return
club_df = get_df_from_sheet('club')
# Move approved changes to the club sheet
approved_changes = create_df[create_df['is_approved'].isin(['Y','y'])]
for i in approv... | The code defines a function `run_checks` that sequentially executes three validation or testing functions: `check_club_create` (validates club creation), `check_club_edit` (validates club editing), and `check_event_create` (validates event creation). Its main task is to run these checks to ensure core functionalities r... | def run_checks():
check_club_create()
check_club_edit()
check_event_create() |
def get_review_series(review_path = '/home/kalvin_kao/yelp_challenge_dataset/review.csv'):
#review_path = '/home/kalvin_kao/yelp_challenge_dataset/review.csv'
review_df = pd.read_csv(review_path)
five_star_review_df = review_df[review_df['stars']==5]
#five_star_review_series = five_star_review_df['text'... | The code trains a neural network model to generate synthetic text (likely fake hotel reviews) using real five-star Yelp reviews. It processes review data, builds a vocabulary, converts text to ID sequences, and trains a model with specified parameters (e.g., 2 layers, 1024 hidden units). The trained model is saved, and... | def train_attack_model(training_samples=20000, test_samples=1000, review_path = '/home/kalvin_kao/yelp_challenge_dataset/review.csv'):
#training_samples=20000
#test_samples=1000
#review_path = '/home/kalvin_kao/yelp_challenge_dataset/review.csv'
five_star_reviews = get_review_series(review_path)
tra... |
def get_review_series(review_path = '/home/kalvin_kao/yelp_challenge_dataset/review.csv'):
#review_path = '/home/kalvin_kao/yelp_challenge_dataset/review.csv'
review_df = pd.read_csv(review_path)
five_star_review_df = review_df[review_df['stars']==5]
#five_star_review_series = five_star_review_df['text'... | This code trains a neural network model to generate synthetic text using five-star Yelp reviews. It processes review data, creates a vocabulary, converts text to numerical IDs, defines model parameters, and trains the model. The output includes the trained model, vocabulary mappings, and parameters for text generation ... | def train_attack_model(training_samples=20000, test_samples=1000, review_path = '/home/kalvin_kao/yelp_challenge_dataset/review.csv'):
#training_samples=20000
#test_samples=1000
#review_path = '/home/kalvin_kao/yelp_challenge_dataset/review.csv'
start_format = time.time()
five_star_reviews = get_rev... |
def get_review_series(review_path = '/home/kalvin_kao/yelp_challenge_dataset/review.csv'):
#review_path = '/home/kalvin_kao/yelp_challenge_dataset/review.csv'
review_df = pd.read_csv(review_path)
five_star_review_df = review_df[review_df['stars']==5]
#five_star_review_series = five_star_review_df['text'... | The code trains a neural network model to generate text using Yelp reviews, preprocessing data by creating a vocabulary, converting reviews to ID sequences, and running training with specified parameters. It returns the trained model, vocabulary mappings, and model parameters for later use in text generation tasks. | def train_attack_model(training_samples=20000, test_samples=1000, review_path = '/home/kalvin_kao/yelp_challenge_dataset/review.csv'):
#training_samples=20000
#test_samples=1000
#review_path = '/home/kalvin_kao/yelp_challenge_dataset/review.csv'
start_format = time.time()
five_star_reviews = get_rev... |
def ucitajMnist(mnist):
for i in range(70000):
slika = mnist.data[i].reshape(28,28)
bin_slika = ((color.rgb2gray(slika)/255.0)>0.80).astype('uint8')
bin_slika = pozicioniranjeSlike(bin_slika)
mnist_brojevi.append(bin_slika)
def ddistanca(broj,brojevi) :
... | The main task of the code is to process a video stream, detect white-colored objects (interpreted as digits) using OpenCV, track their movement, recognize digits via MNIST model, and sum values of digits that cross a predefined line. It uses image masking, dilation, object labeling, and distance tracking to identify an... | def main():
brojevi = []
frejm = 0
ucitajMnist(mnist)
donja = np.array([160 , 160 , 160],dtype = "uint8")
gornja = np.array([255 , 255 , 255],dtype = "uint8")
kernel = np.ones((2,2),np.uint8)
while(1):
ret, slika = video0.read()
if not ret: break
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.