dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def warp_disp(img, disp):
'''
Borrowed from: https://github.com/OniroAI/MonoDepth-PyTorch
'''
b, _, h, w = img.size()
# Original coordinates of pixels
x_base = torch.linspace(0, 1, w).repeat(b, h, 1).type_as(img)
y_base = torch.linspace(0, 1, h).repeat(b, w, 1).transpose(1, 2).type_as(img)
... | This function computes an unsupervised loss for depth estimation by aligning the right image with the left using displacement maps. It warps the right image via displacement, applies a valid mask, and combines L1 loss (15%) with SSIM-based structural similarity loss (85%) to minimize differences between warped and orig... | def loss_disp_unsupervised(img_left, img_right, disp, valid_mask=None, mask=None):
b, _, h, w = img_left.shape
image_warped = warp_disp(img_right, -disp)
valid_mask = torch.ones(b, 1, h, w).to(img_left.device) if valid_mask is None else valid_mask
if mask is not None:
valid_mask = valid_mask * ... |
def instructions():
#input: none
#output: none
#process: prints instructions for blackjack
print("Two players will now play blackjack. For your turn you'll get two \
cards and have to repeatedly choose if you'd like to get another, with the \
goal of the value of your hand equaling 21 or getting as clos... | The main task of the code is to run a series of Blackjack games between two players, allowing them to repeatedly play rounds while tracking individual game wins and determining an overall winner. It handles card dealing, player turns, scoring, and result reporting, with options to replay games and track cumulative vict... | def main():
#main function runs blackjack games between two players
instructions()
#DEALING
#initializes two player objects
name1 = input("What's the name of the first player? ")
name2 = input("What's the name of the second player? ")
player1 = Player(name1)
player2 = Player(name2... |
def __get_teams_source_data(self) -> List:
""" Get Teams from ESPN
:return: list of teams
"""
content: dict = {}
url_to_query = self._base_site_url + '/teams'
try:
response = httpx.get(url_to_query)
content = response.json()
except httpx.Re... | This method generates a list of TgfpNflTeam objects by combining team data from a source with corresponding standings data. It first checks if cached teams exist; if not, it retrieves team and standings data from external sources. For each team, it merges its base information with relevant standings, constructs a TgfpN... | def teams(self) -> List[TgfpNflTeam]:
"""
Build a list of teams using the teams source and standings source data
Returns:
a list of all TgfpNflTeams
"""
if self._teams:
return self._teams
if not self._teams_source_data:
self._teams_sour... |
def _process_download_link(self, download_link, book_name):
"""
Processes a download link to download a book and clean up the files.
This method resolves the download link, initializes a web driver, navigates to the
download link, waits for the download to complete, and then cleans up ... | The function automatically downloads a book using either a direct download link or a DataFrame of links. It prioritizes a direct link if provided; otherwise, it processes multiple links from a DataFrame. If neither is available, it logs the book as not found. | def _auto_download_book(self, book_name, download_links=None, download_link=None):
"""
Automatically download the book using the provided download links or download link.
:param book_name: The name of the book.
:param download_links: A DataFrame containing the download links.
:pa... |
def _auto_download_book(self, book_name, download_links=None, download_link=None):
"""
Automatically download the book using the provided download links or download link.
:param book_name: The name of the book.
:param download_links: A DataFrame containing the download links.
:pa... | This function scrapes and downloads a book using either a direct download link, a DataFrame of links, or by searching for the book's metadata and mirrors on LibGen. It adjusts the book title if metadata is found, retrieves relevant links, and triggers the download process via _auto_download_book. | def scrape_book(self, book_name, download_link=None, download_links=None):
"""
Scrape and download the book based on the provided book name and download link(s).
:param book_name: The name of the book.
:param download_link: The direct download link.
:param download_links: A DataF... |
def ValidateAuthentication(sid) -> bool:
if (not isAuthenticatedUser(sid)):
logger.debug(f'No valid Auth for {sid}')
sio.emit("status", "Authentication Required",to=sid)
sio.disconnect(sid)
return False
return True
def getDB_Instance(sid) -> db.Database:
if (sid in dbInstance... | The function `GetChatGroups` authenticates a session, retrieves direct message chat rooms for the authenticated user, and broadcasts the list of chat rooms back to the client via a socket event. | def GetChatGroups(sid, data):
if ValidateAuthentication(sid):
msg = getDB_Instance(sid).getDirectMessageChatRooms(getUserID(sid))
sio.emit("reply", msg ,to=sid) |
def ValidateAuthentication(sid) -> bool:
if (not isAuthenticatedUser(sid)):
logger.debug(f'No valid Auth for {sid}')
sio.emit("status", "Authentication Required",to=sid)
sio.disconnect(sid)
return False
return True
def getDB_Instance(sid) -> db.Database:
if (sid in dbInstance... | The main task of the code is to send a direct message from a user to a target user after validating authentication. It retrieves the message and target name from input data, checks if the target user exists in the database, and emits a status message if the target is invalid. If valid, it sends the direct message using... | def SendMsgToUser(sid,data):
if ValidateAuthentication(sid):
msg = data["msg"]
target = data["target"]
database = getDB_Instance(sid)
user = database.getUserIDbyName(target)
if user is None:
sio.emit("status", f"User: {user} does not extist",to=sid)
re... |
def ValidateAuthentication(sid) -> bool:
if (not isAuthenticatedUser(sid)):
logger.debug(f'No valid Auth for {sid}')
sio.emit("status", "Authentication Required",to=sid)
sio.disconnect(sid)
return False
return True
def getDB_Instance(sid) -> db.Database:
if (sid in dbInstance... | The function retrieves all chat messages between a user and a target user after validating the session. It checks authentication, fetches the database instance, identifies user IDs, retrieves messages from the database, and emits them to the client via a socket event. | def GetAllChatMsgFor(sid,data):
if ValidateAuthentication(sid):
database = getDB_Instance(sid)
user = getUserID(sid)
otherUser = data["target"]
msgs = database.GetAllChatMsg(user,otherUser)
sio.emit("reply", msgs ,to=sid) |
def ValidateAuthentication(sid) -> bool:
if (not isAuthenticatedUser(sid)):
logger.debug(f'No valid Auth for {sid}')
sio.emit("status", "Authentication Required",to=sid)
sio.disconnect(sid)
return False
return True
def getDB_Instance(sid) -> db.Database:
if (sid in dbInstance... | This function retrieves chat messages between two users based on parameters like baseline and limit. It validates authentication, fetches data from a database, adjusts the query direction if older messages are requested, and emits the retrieved messages to the client via a socket connection. | def GetRelativeMsgFor(sid,data):
if ValidateAuthentication(sid):
database = getDB_Instance(sid)
user = getUserID(sid)
otherUser = data["target"]
baseline = data["baseline"]
limit = data["limit"]
oldMsgs = data["olderData"]
if oldMsgs:
limit *= -1
... |
def ValidateAuthentication(sid) -> bool:
if (not isAuthenticatedUser(sid)):
logger.debug(f'No valid Auth for {sid}')
sio.emit("status", "Authentication Required",to=sid)
sio.disconnect(sid)
return False
return True
def getDB_Instance(sid) -> db.Database:
if (sid in dbInstance... | This function updates a user's read status for a specific message in the database after validating authentication. It retrieves the database instance and user ID, extracts the message ID from input data, updates the read time in the database, and emits a confirmation message to the client. | def UpdateReadTime(sid,data):
if ValidateAuthentication(sid):
database = getDB_Instance(sid)
user = getUserID(sid)
msgID : int = data["id"]
database.UpdateReadTime(msgId=msgID,userID=user)
sio.emit("status", f"Updated Read for {msgID}",to=sid) |
def ValidateAuthentication(sid) -> bool:
if (not isAuthenticatedUser(sid)):
logger.debug(f'No valid Auth for {sid}')
sio.emit("status", "Authentication Required",to=sid)
sio.disconnect(sid)
return False
return True
def getDB_Instance(sid) -> db.Database:
if (sid in dbInstance... | The function updates a message's receive time in the database for an authenticated user, then sends a confirmation. It validates the session, retrieves the database and user ID, extracts the message ID from input data, updates the record, and emits a status event to the client. | def UpdateReciveTime(sid,data):
if ValidateAuthentication(sid):
database = getDB_Instance(sid)
user = getUserID(sid)
msgID : int = data["id"]
database.UpdateReciveTime(msgId=msgID,userID=user)
sio.emit("status", f"Updated Recive for {msgID}",to=sid) |
def tweet_info(url) :
tweet = api.get_status(process_url(url)[1])
tweet_keys = ['created_at', 'id', 'text', 'retweet_count', 'favorite_count']
tweet_values = []
for key in tweet_keys :
tweet_values.append(tweet._json[key])
user_keys = ['id', 'name', 'screen_name', 'description', 'followers... | The code analyzes a tweet from a given URL by extracting user and tweet information, preprocessing the text, calculating sentiment, user rating, and a score, then using a classifier to predict the sentiment (positive/negative). It returns structured output including username, userid, tweet text, sentiment label, and pr... | def predictor(url) :
user, tweet = tweet_info(url)
userid = user['screen_name']
text = tweet['text']
newtext = preprocess_text(tweet['text'])
prediction = calculate_sentiment(newtext)
rating = calculate_rating(userid)
score = calculate_sent_score(newtext)
df = pd.DataFrame([[prediction... |
def _get_atoms_num_in_supercell(self, super_mult_vec1, super_mult_vec2):
"""Get the atoms number in the supercell"""
return self.abs_cross_a2d(super_mult_vec1, super_mult_vec2)
def _get_supercell_vecs(self, supercell_matrix, primitive_vecs, super_a3_z):
"""Get the supercell vectors"""
# Supercell vector... | The function generates a supercell by transforming primitive unit cells using specified vectors and shifts. It calculates supercell dimensions, scales quantities, computes transformation matrices, determines atomic positions, and adjusts coordinates to ensure proper alignment and periodicity. The output includes superc... | def gen_supercell(self, super_mult_vec1, super_mult_vec2,
primitive_vecs, a3_z, quantities_list,
atom_coord_list, super_a3_z=20.0, scell_shift_x=0.0,
scell_shift_y=0.0, supercell_shift_z=0.0):
"""Generate the supercell"""
# Supercell... |
def _check_primvecs_in_layers(self):
"""Check the primitive cell vectors in different layers"""
# Get the reference vector of primitive cell
ref_primcell_vecs = self.primcell_info_list[0]["prim_vecs"]
ref_p_a1 = ref_primcell_vecs[0]
ref_p_a2 = ref_primcell_vecs[1]
# Check each primitive cell vec... | The code generates fractional coordinates for twisted layers by creating supercells with specified parameters, adjusting z-shifts iteratively to avoid coordinate overlaps, and storing the resulting supercell data. It ensures layer distances are valid and updates each supercell's vectors, quantities, and atomic coordina... | def twist_layers(self, start_z=0.0, super_a3_z=20.0):
"""Generate the twisted layers atoms fractional coordinates."""
# Check the layers firstly
self._check_primvecs_in_layers()
# For each twist layers
supercell_shift_z = start_z
for i, supercell_info in enumerate(self.supercell_info_list):
... |
def _rotate_window_to_current_time(self):
t = time.time()
t_start = int(int(t / self.step_period) * self.step_period)
if len(self.queue) <= 0 or self.queue[-1][0] != t_start:
entry = [t_start, 0]
self.queue.append(entry)
# remove old entries
... | The main task of the code is to distribute a penalty amount in a thread-safe manner. It rotates the time window to the current time, applies the penalty using `_distribute_penalty`, and marks the status as "dirty" to indicate state changes require updates. The `self.lock` ensures exclusive access during execution. | def distribute(self, amount):
with self.lock:
self._rotate_window_to_current_time()
self._distribute_penalty(amount, 1.0)
self._status_dirty() |
def _remove_from_oldest(self, amount):
# try to remove from the left
for el in self.queue:
if el[1] > 0:
to_sub_from_bucket = min(el[1], amount)
el[1] -= to_sub_from_bucket
amount -= to_sub_from_bucket
self.window_total -= to_su... | This function accepts a load value, updates the system's load tracking, ensures capacity limits are not exceeded by removing oldest entries if necessary, logs debug information, and returns a success result indicating the load was accepted. | def _submit_accept(self, load: float):
t = time.time()
entry = self.queue[-1]
response_tta = None
p_before = 100.0 * self.window_total / self.maxload
self.was_over = False
self.window_total += load
entry[1] += load
over_max_cap = self.window_total - self... |
def _remove_from_oldest(self, amount):
# try to remove from the left
for el in self.queue:
if el[1] > 0:
to_sub_from_bucket = min(el[1], amount)
el[1] -= to_sub_from_bucket
amount -= to_sub_from_bucket
self.window_total -= to_su... | This function handles load rejection logic in a rate limiter, adjusting the system's state by removing excess load, applying penalties for oversteps, and calculating the 'time to availability' (TTA) for retrying the request. It ensures the system remains within capacity limits, tracks performance overhead, and returns ... | def _submit_reject(self, load: float): # NOSONAR - single function because it must be performance - optimized
t = time.time()
response_tta = None
p_before = 100.0 * self.window_total / self.maxload
over_max_cap = self.window_total - self.max_cap
if over_max_cap > 0:
... |
def _submit_probe(self, load: float):
t = time.time()
self.num_calls += 1
self._rotate_window_to_current_time()
total_would_be = self.window_total + load
if total_would_be > self.maxload:
ret = False
else:
ret = True
self.total_o... | This function determines whether to accept or reject a load submission by first probing the system's capacity. If the probe indicates sufficient capacity, it proceeds to accept the load; otherwise, it rejects it. The function returns the result of either the acceptance or rejection process based on the probe's outcome,... | def _submit(
self, load: float = 1
) -> LoadLimiterSubmitResult:
if self._submit_probe(load=load):
return self._submit_accept(load=load)
else:
return self._submit_reject(load=load) |
def extract_num_forwarded_per_user_dist(data, v, file_name):
forwarded_events = data[(data['eventType'] == 'PktFwd')]
forwarded_events_by_user = forwarded_events.groupby('nodeId').size().values
with open(f'./res/v{v}_parsed/{file_name}_fwd_by_user_dist.json', 'w') as f:
json.dump(forwarded_events_by... | The main task of the code is to process network data by reading CSV files, analyzing message forwarding/reception distributions, calculating average age of information (AOI) and its 95th percentile, and computing excess probabilities based on communication range. It aggregates statistics and saves results before deleti... | def main(v, file_name):
data = pd.read_csv(f'./res/v{v}/{file_name}.csv')
positions = pd.read_csv(f'./res/v{v}/course_{file_name}.csv')
extract_num_forwarded_per_user_dist(data, v, file_name)
extract_num_received_per_user_dist(data, v, file_name)
extract_num_forwarded_per_seqno_dist(data, v, file_na... |
def check_data_columns(data, filter_dict=None, temp_agg=None, extra_columns=None):
'''
Checks that the data, filter dictionary and temporal aggregation are compatible, raises errors otherwise
Arguments:
data - the data frame used in the general model function
filter_dict - the filtering dictionary ... | The function processes input data by filtering, aggregating temporally, and generating model-specific responses and covariates. It returns tuples of (responses, covariates) based on the model type (1-6 or 'null'), handling tasks like binning, lag features, and filtering zero-events. Different models use distinct data t... | def model_observations(model_type, data, data_filter, temp_agg='WEEK', stan_filepath=None, max_bin=None, covariates_dict=None, ignore_zero=False):
'''
Model Observations function
Given a model type and appropriate associated information, return the required responses and covariates
Arguments:
mode... |
def check_data_columns(data, filter_dict=None, temp_agg=None, extra_columns=None):
'''
Checks that the data, filter dictionary and temporal aggregation are compatible, raises errors otherwise
Arguments:
data - the data frame used in the general model function
filter_dict - the filtering dictionary ... | The function samples parameters for generalized inner/outer models using either Stan or Metropolis-Hastings MCMC, based on specified covariates and administrative regions in Bangladesh. It generates posterior samples for event prediction models, incorporating covariates via a dictionary, and returns results for Bayesia... | def model5_sample(data, district, event_type, covariates_dict, sample_size=10000, stan_filepath=None, ignore_zero=False, stan_seed=1):
'''
Sampling function for model(s) 5 - the generalised inner/outer modelling
Uses the covariates dictionary (values should be boolean) to select the covariates and coeffici... |
def auto_max_bin(data, data_filter, temp_agg='WEEK', bin_size=0.05):
'''
Automatic maximum bin finding function for model 4
Aggregates the weeks with the most events together until the highest bin has bin_size proportion of the total count
Arguments:
data - the data as passed into model_sample
... | The main task of the code is to perform Bayesian sampling using either Stan or Metropolis-Hastings MCMC for different statistical models (types 1-6 or 'null'), based on input data, filters, and parameters. It preprocesses data, selects appropriate sampling methods, and returns posterior samples as a DataFrame or Stan f... | def model_sample(model_type, data, data_filter, sample_size=10000, temp_agg='WEEK',
parameter_info=None, stan_filepath=None, max_bin=None, covariates_dict=None, ignore_zero=False, simulated_data=None, stan_seed=1,
null_hyperparameters=[1,1], bin_size=0.05):
'''
Generalised mode... |
def CompileModel(self,lr):
self.hvd_lr = lr*np.sqrt(hvd.size())
opt = tensorflow.keras.optimizers.Adam(learning_rate=self.hvd_lr)
opt = hvd.DistributedOptimizer(
opt, average_aggregated_gradients=True)
self.model1.compile(loss=weighted_binary_crossentropy,
... | The code's main task is to perform iterative training or optimization of a machine learning model. It initializes batch size, epochs, and compiles the model with a specified learning rate. The method then runs a loop for a defined number of iterations, executing two steps (RunStep1 and RunStep2) per iteration. These st... | def Unfold(self):
self.BATCH_SIZE=self.opt['General']['BATCH_SIZE']
self.EPOCHS=self.opt['General']['EPOCHS']
self.CompileModel(float(self.opt['General']['LR']))
self.weights_pull = np.ones(self.weights_mc.shape[0])
self.weights_push = np.... |
def encrypt(message):
cipher = ''
for letter in message:
if letter != ' ':
cipher += MORSE_CODE_DICT[letter] + ' '
else:
cipher += ' '
return cipher
def decrypt(message):
message += ' '
decipher = ''
citext = ''
for letter in message:
if (letter != ' '):
i = 0
citext += letter
else:
i += 1... | The main task of the code is to encrypt subtitle text into Morse code format by loading subtitles, applying uppercase encryption with formatting tags, saving them, then decrypting and converting the text to Morse code using `txt2morse`, though the final conversion result is not stored. | def main():
#import pdb; pdb.set_trace()
if rip:
subs = pysubs2.load(rapgod_subtitles_file, encoding="utf-8")
for line in subs:
txt = encrypt(line.text.upper())
line.text = "{\\be1}" + txt
subs.save(morse_subtitles_file)
subs = pysubs2.load(morse_subtitles_file, encoding="utf-8")
for line in subs:
tx... |
def load_data(messages_filepath, categories_filepath):
"""
Load data from csv files and return the merged data as a DataFrame
:param messages_filepath: filepath to disaster_messages.csv file
:param categories_filepath: filepath disaster_categories.csv file
:return: merged DataFrame
"""
mess... | The main task of the code is to process disaster response data by loading messages and categories from CSV files, cleaning the combined dataset, and saving it into a SQLite database. The script requires three command-line arguments: message file path, category file path, and database file path. It validates input, exec... | def main():
if len(sys.argv) == 4:
messages_filepath, categories_filepath, database_filepath = sys.argv[1:]
print('Loading data...\n MESSAGES: {}\n CATEGORIES: {}'
.format(messages_filepath, categories_filepath))
load_data(messages_filepath, categories_filepath)
... |
def get_shape_list(tensor, expected_rank=None, name=None):
"""Returns a list of the shape of tensor, preferring static dimensions.
Args:
tensor: A tf.Tensor object to find the shape of.
expected_rank: (optional) int. The expected rank of `tensor`. If this is
specified and the `tensor` has a different... | The code implements a hybrid model for time series forecasting and reconstruction. It uses 1D convolution, GATs for feature/temporal attention, GRU for temporal modeling, and a VAE for reconstruction. It computes forecasting loss (next-step prediction) and reconstruction loss (VAE-based) separately, combining them base... | def __init__(self,
input_tensor,
label,
conv1d_act_fn=tf.nn.relu,
d0=7,
d1=300, #k1
d2=300, #k2
d3=300,
gamma=0.8,
tc_act_fn=tf.nn.relu,
gru_act_fn=tf.math.tanh,
... |
def get_video_description(response):
"""Send request to Youtube API and get video description"""
description = ""
items = response.json().get('items', [])
if items:
description = items[0]['snippet']['description']
return description
def find_sponsorship_disclaimers(description):
lines = ... | The function retrieves and processes sponsor information from a YouTube video's description using the YouTube API and a model. It fetches the video's description, identifies disclaimers, extracts sponsor names via the model, filters out specified organizations, and returns structured data including sponsors, disclaimer... | def find_video_sponsors(video_id: str, model) -> list:
"""Find sponsor in Youtube videos"""
result = {}
sponsorships = []
youtube_api_url = f"{YOUTUBE_API_BASE_URL}&id={video_id}&key={YOUTUBE_API_KEY}"
youtube_response = requests.get(youtube_api_url)
if youtube_response.status_code != 200 or not... |
def listCard():
suites = ('Spade', 'Club', 'Diamond', 'Heart')
groups = list(range(3,10)) + ['J', 'Q', 'K', 'A']
Card = namedtuple('Card', ['group', 'suit'])
listCard = [Card(group, suit) for group in groups for suit in suites]
listCard.append(Card('Jocker','Black'))
listCard.append(Card('Jocke... | The code implements a card game where the player bets points to guess outcomes. It initializes game roles, deducts points, and uses a loop to handle rounds: correct guesses award points, incorrect ones penalize. The game ends if the player reaches 1000 points (win) or drops below 30 points (loss), with options to conti... | def PlayGame():
# Create a list cards of 54 cards
List = listCard()
# Using list cards to create house and player
List, house_card, house, player_card, player = initRole(List)
print('YOUR POINT:',player.getPoint )
# Show the house's card first
print('\nThe House receives and shows his card... |
def getData(movieName):
print("Sending request to get movies!!!!!!")
movies = getMovies(movieName)
data = []
for movie in movies:
reviews = getReviews(movie["id"])
data.append({"title": movie["title"], "image": movie["image"], "description": movie["description"], "reviews": reviews})
... | The function processes a movie search by caching API data to avoid redundant requests. It displays the API response and visualizes movie results using Streamlit components, including expandable sections, metrics, and pie charts, based on the retrieved data and provided package name. | def process(movieName, packageName):
global lastSearched, cacheData
if(lastSearched != movieName):
data = getData(movieName)
lastSearched = movieName
cacheData = data
else:
data = cacheData
if len(data)>0:
st.text("")
st.components.v1.html("""
... |
def move_up(self, state):
x_blank, y_blank = self.find_blank(state)
if y_blank != self.height - 1:
new_state = copy.deepcopy(state)
new_state = self.swap(new_state, x_blank, y_blank, x_blank, y_blank + 1)
return new_state
return None
def move_down(self, state... | The code generates new nodes by exploring possible moves (up, down, left, right) from the current state, creating child nodes only if the new state hasn't been processed before and the move doesn't reverse the last action, thus avoiding cycles and redundant exploration in a search algorithm. | def generate_nodes(self, node):
state = node.state
last_move = node.last_move
# generating new states
up_state = self.move_up(state)
down_state = self.move_down(state)
right_state = self.move_right(state)
left_state = self.move_left(state)
if not self.pr... |
def create_node(self, state, parent, last_move):
dist = self.count_heuristic(state)
node = Node(state, parent, last_move, dist)
heapq.heappush(self.generated_nodes, node)
def get_result(self, final_node):
result_sequence = None
if final_node:
result_sequence = []
... | The code implements a search algorithm using a priority queue (min-heap) to find a path from an initial state to a goal state. It starts by creating an initial node, then repeatedly extracts the minimum node from the heap, checks if it matches the goal state, and generates successor nodes if not. Processed states are t... | def solve(self):
self.create_node(self.init_state, None, None) # creating first init node, creating a min heap
while self.generated_nodes:
if PRINT:
print("Generated nodes:", len(self.generated_nodes))
print("Processed nodes:", len(self.processed_states.keys(... |
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.
xCount = 0
oCount = 0
for row in board:
xCount += row.count(X)
oCount ... | The code implements the minimax algorithm to determine the optimal action for the current player on a given board. It evaluates all possible moves recursively, selecting the action that maximizes the player's score (if X) or minimizes the opponent's score (if O). The initial move is fixed for optimization, returning (0... | def minimax(board):
# Returns the value of optimal action for the current player on the board.
# Fixed first move for optimization
if board == initial_state():
return (0, 1)
currentPlayer = player(board)
bestValue = float("-inf") if currentPlayer == X else float("inf")
bestAction = No... |
def _download(self, path: str, user_id: Optional[int], suffix: str) -> pathlib.Path:
if user_id is None:
preliminary: Optional[pathlib.Path] = None
else:
stem = path.replace("-", "--").replace("/", "-")
preliminary = (
self._cache_location / "user" / s... | This function downloads input data for a specific year and day, hashes its content, and caches it in a structured path. If the cached file already exists, it reuses it; otherwise, it creates the necessary directory structure and stores the content. The function then returns the cached input data as a string. | def input(self, year: int, day: int) -> str:
cache_path = self._download(f"{year}/day/{day}/input", self.user_id(), ".txt")
content = cache_path.read_text()
stem = _hexdigest(content)
data_path = self.input_path(year, day, stem)
if data_path.exists():
logger.debug("Re... |
def _download(self, path: str, user_id: Optional[int], suffix: str) -> pathlib.Path:
if user_id is None:
preliminary: Optional[pathlib.Path] = None
else:
stem = path.replace("-", "--").replace("/", "-")
preliminary = (
self._cache_location / "user" / s... | This function retrieves or generates an answer for a specific problem (year/day/part) by either reusing cached data or parsing HTML content from a downloaded file. It uses a hash-based stem to identify data paths, ensuring efficient storage and retrieval. If the answer file doesn't exist, it creates it by processing th... | def answer(self, year: int, day: int, part: int) -> str:
cache_path = self._download(f"{year}/day/{day}", self.user_id(), ".html")
stem = _hexdigest(self.input(year, day))
data_path = self.answer_path(year, day, part, stem)
if data_path.exists():
logger.debug("Reusing answer ... |
def list_stack_instance_by_account(target_session, stack_set_name, account_id):
'''
List all stack instances based on the StackSet name and Account Id
'''
try:
cfn_client = target_session.client('cloudformation')
stackset_result = cfn_client.list_stack_instances(
StackSetName... | This function handles AWS account creation events by detecting new managed accounts, checking if CloudFormation stack instances exist for the account, creating missing instances in required regions, and registering the account with Sonrai. It uses the event context to identify regions, validates the event type/state, a... | def handle_new_account(event, context):
global region_name
region_name = str(context.invoked_function_arn).split(":")[3]
# Check if lifecycle even matches
if 'detail' in event and event['detail']['eventName'] == 'CreateManagedAccount':
if event['detail']['serviceEventDetails']['createManagedA... |
def create_stack_instance(
target_session, stackset_name, org_id, accounts, regions,
parameter_overrides=None,
wait_for_completion=False,
outputs=False,
allow_failures=False):
'''
Create stackset in particular account + region
'''
try:
cfn_client = target_... | This function deploys a CloudFormation stack set to core and protected accounts within an organization, ensuring initial setup for logging, auditing, and access management. It extracts organizational and regional details from the event/context, deploys stack instances to critical accounts first, then to protected accou... | def handle_initial_setup(event, context):
global region_name
try:
if event['RequestType'] in ['Create', 'Update']:
org_id = event['ResourceProperties']['OrgId']
log_archive_account = event['ResourceProperties']['LogArchiveAccount']
audit_account = event['ResourcePrope... |
def handle_new_account(event, context):
global region_name
region_name = str(context.invoked_function_arn).split(":")[3]
# Check if lifecycle even matches
if 'detail' in event and event['detail']['eventName'] == 'CreateManagedAccount':
if event['detail']['serviceEventDetails']['createManagedA... | This Lambda function handles AWS CloudFormation custom resource events. It processes account creation events, initializes resources for Create/Update requests, and sends appropriate responses (SUCCESS/FAILED) via the ResponseURL for Delete requests or exceptions, logging detailed event information throughout the proces... | def handle(event, context):
try:
LOGGER.info('Lambda Handler - Start')
LOGGER.info('REQUEST RECEIVED: {}'.format(json.dumps(event, default=str)))
if 'detail' in event and event['detail']['eventName'] == 'CreateManagedAccount':
handle_new_account(
event=event,
... |
def Browliner(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
bounding_boxes = face_detector(gray, 0)
if bounding_boxes:
for i, bb in enumerate(bounding_boxes):
face_landmark_points = lndMrkDetector(gray, bb)
face_landmark_points = face_utils.shape_to_np(face_landmark_... | The code processes a video stream using OpenCV, applying face filters (e.g., Browliner, Reply, Drug, Stronzo Meter, or default Eyeliner) based on the `face_filter` parameter. It handles real-time frame processing, timeout logic for dynamic filter effects, and optionally saves the output as an AVI file. The processed fr... | def video(src=0, face_filter='eyeliner'):
counter_timeout = 0
cap = cv2.VideoCapture(src)
if args['save']:
if os.path.isfile(args['save'] + '.avi'):
os.remove(args['save'] + '.avi')
output_video = cv2.VideoWriter(args['save'] + '.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), ... |
def check_visible_points(possible_bb_3d_points, depth_data):
"""
visible_points=[True, True, False, False]
"""
visible_points = []
# Check which points are occluded
for xyz_point in range(len(possible_bb_3d_points)):
x = int(possible_bb_3d_points[xyz_point][0])
y = int(possible_b... | This function adjusts a 3D bounding box by determining visible points using depth data, computes tightened 2D bounding box coordinates (xmin, ymin, xmax, ymax) based on the number of visible points (4-0), and assigns a color index (3or4, 2, 1, 0) to represent occlusion levels. It handles occlusion scenarios by selectin... | def tighten_bbox_points(possible_bb_3d_points, depth_data):
visible_points_status, possible_bb_3d_points = check_visible_points(possible_bb_3d_points, depth_data)
# No points with occlusion
if visible_points_status.count(True) == 4 or visible_points_status.count(True) == 3:
xmin, ymin, xmax, ymax = ... |
def adjust_points_to_img_size(width, height, bb_3d_points):
for xyz_point in bb_3d_points:
if xyz_point[0] < 0:
xyz_point[0] = 0
if xyz_point[0] > width:
xyz_point[0] = width-1
if xyz_point[1] < 0:
xyz_point[1] = 0
if xyz_point[1] > height:
... | The function filters and refines 3D bounding boxes (bb_data) into valid 2D bounding boxes by applying constraints on spatial bounds, minimum area thresholds, and intersection-over-union (IOU) overlaps. It processes depth data, adjusts points to image dimensions, calculates 2D areas, and removes invalid or overlapping b... | def filter_bounding_boxes(bb_data, depth_data, frame_width, frame_height, df_3, actor):
good_bounding_boxes = []
idx_list=[]
idx_list_1=[]
bb_data = np.array(bb_data)
depth_data = np.transpose(depth_data)
df_3 = df_3
assert actor=="vehicle" or actor=="walker"
if actor == "vehicle":
... |
def turnOff():
global OPTION
for i in range(numpix):
strip.set_pixel(i, off)
strip.show()
OPTION = 10
def clock():
global OPTION
while True:
if OPTION == 1:
showTime()
time.sleep(1)
else:
break
def counter():
count = 0
global OP... | The code defines a function `options()` that continuously checks the value of `OPTION` in a loop. Depending on `OPTION`, it triggers actions like turning off, displaying a clock, starting a counter, or setting a timer with predefined durations. The loop pauses for 2 seconds each iteration, and the current `OPTION` valu... | def options():
while True:
time.sleep(2)
if OPTION == 0:
turnOff()
elif OPTION == 1:
clock()
elif OPTION == 2:
counter()
elif OPTION in range(3, 10):
times = [255, 10, 30, 60, 120, 180, 240]
timer(times[OPTION-3])
... |
def _read(self, reg, N):
try:
tmp = int.from_bytes(self.i2cDev.readfrom_mem(_ADDR, reg, N), 'little')
except:
print("Error reading from RV3028")
return float('NaN')
return tmp
def _writeCrumb(x, n, c):
x = _writeBit(x, n, _readBit(c, 0))
return _writeB... | This function configures battery switchover by modifying a specific bit in EEPROM storage. It reads a byte from the backup memory, updates the second bit to 0b01 (enable) or 0b00 (disable) based on the 'state' parameter, and writes the modified byte back. If 'state' is invalid, it raises an error. The task involves saf... | def setBatterySwitchover(self, state = True):
tmp = self._read(_EE_BACKUP, 1)
if state is True:
tmp = _writeCrumb(tmp, 2, 0b01)
elif state is False:
tmp = _writeCrumb(tmp, 2, 0b00)
else:
print("Parameter State must be True or False")
return... |
def _read(self, reg, N):
try:
tmp = int.from_bytes(self.i2cDev.readfrom_mem(_ADDR, reg, N), 'little')
except:
print("Error reading from RV3028")
return float('NaN')
return tmp
def _setBit(x, n):
return x | (1 << n)
def _writeCrumb(x, n, c):
x = _writeB... | The code configures a trickle charger's resistance value (3k, 5k, 9k, or 15k) by modifying a byte in non-volatile memory (_EE_BACKUP). It reads the current byte, sets bit 7, writes a 2-bit code corresponding to the specified resistance, and stores the updated value. If an invalid resistance is provided, it prints an er... | def configTrickleCharger(self, R = '3k'):
tmp = self._read(_EE_BACKUP, 1)
tmp = _setBit(tmp, 7)
if R == '3k':
tmp = _writeCrumb(tmp, 0, 0b00)
elif R == '5k':
tmp = _writeCrumb(tmp, 0, 0b01)
elif R == '9k':
tmp = _writeCrumb(tmp, 0, 0b10)
... |
def _read(self, reg, N):
try:
tmp = int.from_bytes(self.i2cDev.readfrom_mem(_ADDR, reg, N), 'little')
except:
print("Error reading from RV3028")
return float('NaN')
return tmp
def _writeTribit(x,n,c):
x = _writeBit(x, n, _readBit(c, 0))
x = _writeBit(x... | This function configures a clock output by writing a specific bit pattern to an EEPROM register based on the provided frequency value (clk). It reads the current register value, modifies it using helper functions to set the appropriate bit for the given frequency, and writes the updated value back. The function support... | def configClockOutput(self, clk = 32768):
tmp = self._read(_EE_CLKOUT, 1)
if clk == 32768:
tmp = _writeTribit(tmp, 0, 0)
elif clk == 8192:
tmp = _writeTribit(tmp, 0, 1)
elif clk == 1024:
tmp = _writeTribit(tmp, 0, 2)
elif clk == 64:
... |
def setBatterySwitchover(self, state = True):
tmp = self._read(_EE_BACKUP, 1)
if state is True:
tmp = _writeCrumb(tmp, 2, 0b01)
elif state is False:
tmp = _writeCrumb(tmp, 2, 0b00)
else:
print("Parameter State must be True or False")
return... | The main task of the code is to initialize an RV3028 device by validating the provided I2C interface, checking for the device's presence on the I2C bus, and configuring battery switchover and trickle charging settings. It raises errors if the I2C device is invalid or the RV3028 is not detected, ensuring proper setup fo... | def __init__(self, i2c = None):
if isinstance(i2c, I2C) is False:
print("RV3028 requires a valid i2c device")
raise TypeError
self.i2cDev = i2c
try:
part = int(i2c.readfrom_mem(_ADDR, _ID, 1))
except Exception as e:
print("Failed ... |
def addVertice(self, v):
""" Adds a new vertice @v to the graph """
if v in self.graph.keys():
self.debuger("addVertice",f"{v} is already a vertice in the graph.")
return False
else:
self.graph[v] = []
return True
def debuger(self, function :str, m... | This code initializes a graph structure by setting up vertices and edges according to specified parameters (duplicates, loops, directed). It constructs the graph's internal representation, validates vertex/edge additions, and logs debug messages if duplicates or invalid edges are encountered. The main task is to create... | def __init__(self,
vertices: list = [],
edges: list = [],
# Graph Settings
duplicates: bool = False,
loops: bool = False,
directed: bool = False,
debug: bool = False):
s... |
def move_food(self):
move = random.randint(1, 3)
position = random.randint(1, 2) # x ili y
direction = random.randint(1, 2) # left or right
if direction is 1: # right
if position is 1: # x
new_position = move * 20
if self.is_collision({'x':... | The main task of the code is to handle player turn transitions in a game. It moves food, increments the current player, and checks if the player is disabled. If not, it sends a turn event, checks if the player's snake is surrounded, and triggers game over or snake removal logic. If the player has multiple snakes, it sw... | def change_player(self):
self.move_food()
self.steps_counter = 0
self.current_player += 1
if self.current_player == self.number_of_players:
self.current_player = 0
if self.players[self.current_player].is_disabled() is False:
self.pipe.send({'event_type': ... |
def is_border_collision(self, position):
if self.players[self.current_player].is_border_collison(position):
return True
return False
def change_player(self):
self.move_food()
self.steps_counter = 0
self.current_player += 1
if self.current_player == self.number... | The function checks if a game-ending collision occurs at `new_position`. If a collision happens (border or self), it either ends the game for the current player (if they have only one snake) or removes the current snake and switches to another. It sends an end-game event, clears the snake's graphics, and transitions to... | def check_game_over(self, new_position):
if self.is_border_collision(new_position):
if len(self.players[self.current_player].snakes) is 1:
print("Game Over")
self.pipe.send({'event_type': 'end_game', 'data': self.current_player})
time.sleep(0.1)
... |
def continue_loop(loop):
CONT_PLAYING.append(loop)
def start_loop(loop):
CUR_PLAYING.append(loop)
CONT_PLAYING.append(loop)
loop_type = loop.split("-")[0]
index = int(loop.split("-")[1])
toggle_mute(TRACK_DICT[loop_type][index])
def manage_song():
for loop in CUR_PLAYING:
if loop not... | The function detects QR codes in an image, checks their data against a list of active loops (CUR_PLAYING), and either continues existing loops or initiates new ones based on predefined loop types (LOOP_TYPES). It uses QR code data to trigger loop management actions like 'continue_loop' or 'start_loop' for audio process... | def detect_loop(image):
qr_codes = pyzbar.decode(image)
for code in qr_codes:
loop = code.data
if loop in CUR_PLAYING:
continue_loop(loop)
else:
loop_type = code.data.split("-")[0]
if loop_type in LOOP_TYPES:
start_loop(loop)
mana... |
def shuffle(self):
idx = [i for i in range(self.input.shape[0])]
np.random.shuffle(idx)
self.input = self.input[idx]
self.target = self.target[idx]
def feedforward(self):
assert self.x.shape[1] == self.W1.shape[0]
self.z1 = self.x.dot(self.W1)
self.a1 = self.sigmo... | The main task of the code is to train a neural network model by iterating over epochs, processing data in batches, performing feedforward and backpropagation to update weights, calculating mean squared error loss and accuracy, and saving model weights after each epoch. It shuffles data, computes batch loss/accuracy, av... | def train(self):
for epoch in range(self.epochs):
l = 0
acc = 0
self.shuffle()
for batch in range(self.input.shape[0]//self.batch-1):
start = batch*self.batch
end = (batch+1)*self.batch
self.x = self.input[start... |
def isleaf(self,node):
if node.x is None:
return True,[],[]
if node.x.shape[0] ==1:
return True,[],[]
splits,best=self.findbestsplit(node.x,node.y)
if sum(splits[:,3])==0 :
return True,[],[]
if sum(splits[:,2]) ==0 :
return True,[],... | This function recursively constructs a decision tree by splitting data nodes. It checks if a node is a leaf, assigns a leaf label if true, or splits data using the best feature/value, creates left/right child nodes, increments node counters, and recursively processes children to build the tree structure. | def splittree(self,node):
# node=Node(self.x,self.y,self.num)
self.nodes.append(node)
node.leaf,splits,best=self.isleaf(node)
# best=findbestsplit(x,y)
# list1, list2 = (list(t) for t in zip(*sorted(zip(x[:,int(best[0])], y))))
if node.leaf is True:
node.leafl... |
def common_elements(self, node_ids, max=1000):
"""
Generator of active elements common to given nodes.
:param node_ids:
:return:
"""
node_sets = [self.node_els[n] for n in node_ids]
elements = set.intersection(*node_sets)
if len(elements) > max:
... | This function merges two mesh nodes (rm_node and target_node) by moving both to their coordinate average. It removes shared elements, updates the target_node's position, replaces all instances of rm_node in elements with target_node, then deletes rm_node from the mesh, effectively consolidating the two nodes into one. | def merge_node(self, rm_node, target_node):
"""
Merge node rm_node with node 'target_node'.
Move both points to the average position.
:param rm_node:
:param target_node:
:param new_pos:
:return:
"""
assert rm_node != target_node
# remove... |
def common_elements(self, node_ids, max=1000):
"""
Generator of active elements common to given nodes.
:param node_ids:
:return:
"""
node_sets = [self.node_els[n] for n in node_ids]
elements = set.intersection(*node_sets)
if len(elements) > max:
... | This function identifies and repairs degenerate triangles in a mesh by projecting nodes onto the longest edge of the worst-performing triangle, splitting connected elements, and updating the mesh structure to improve geometric quality. It checks triangle edge ratios, moves nodes to corrected positions, and replaces aff... | def _check_flat_triangle(self, ele):
if ele.shape.dim < 2: return []
if ele.shape.dim == 3:
t_shapes = [Triangle(ele.shape.nodes[face]) for face in ele.shape.vtxs_faces]
face_gammas = [tria.gmsh_gamma() for tria in t_shapes]
i_min_face = np.argmin(face_gammas)
... |
def move_node(self, nid, node):
# print(" orig node: ", self.mesh.nodes[nid])
# print(" new node: ", node)
# print(" diff : ", node - np.array(self.mesh.nodes[nid]))
orig = [self._make_element(eid) for eid in self.active(self.node_els[nid])]
self.mesh.nodes[nid] = n... | The main task of the code is to repair a degenerate (flat) quadrilateral mesh element by computing the intersection of two edges, inserting a new node at the intersection point, and splitting connected elements to replace the flat element with valid non-degenerate elements. This ensures mesh quality by avoiding degener... | def _heal_quad_flat_case(self, ele, flat_nodes, pos_edge, neg_edge):
"""
:param eid:
:param flat_nodes:
:param pos_edge:
:param neg_edge:
:param tol: Approximate upper bound for fraction min_tet_height / max_edge
:return:
"""
# compute intersection... |
def move_node(self, nid, node):
# print(" orig node: ", self.mesh.nodes[nid])
# print(" new node: ", node)
# print(" diff : ", node - np.array(self.mesh.nodes[nid]))
orig = [self._make_element(eid) for eid in self.active(self.node_els[nid])]
self.mesh.nodes[nid] = n... | This function addresses a flat triangular face in a mesh by projecting an inner node onto edges of the outer face, verifying non-degeneracy, then modifying the mesh: moving nodes, removing the original element, splitting the outer face, and replacing connected elements' nodes with the inner node to resolve degeneracy. | def _heal_triangle_flat_case(self, ele, flat_nodes, outer_face):
"""
Case with single outer face splitted by other 3 faces.
:param eid:
:param shape:
:param flat_nodes:
:param outer_face:
:return:
"""
# try to project opposite node to edges
... |
def _make_element(self, eid, e_tuple=None):
if e_tuple is None:
e_tuple = self.mesh.elements[eid]
type, tags, node_ids = e_tuple
nodes = np.array([self.mesh.nodes[n] for n in node_ids], dtype=float)
shape_class = {1:Point, 2:Line, 3:Triangle, 4:Tetrahedron}
shape = sh... | This function repairs a mesh by iteratively checking and modifying elements to address issues like duplicate nodes, degenerate shapes, flat elements, and small edges. It uses a tolerance threshold (gamma_tol) to identify problematic elements and limits the number of new elements created. The process continues until no ... | def heal_mesh(self, gamma_tol=0.02, fraction_of_new_els=2):
self.gamma_tol = gamma_tol
orig_n_el = self.max_ele_id
el_to_check = collections.deque(self.mesh.elements.keys())
modified = []
while el_to_check:
el_to_check.extend(modified)
modified = []
... |
def _cluster_indices_split(self, root_node, pre_index=None):
n_samples = len(self.model.labels_)
indices = copy.deepcopy(pre_index)
if pre_index is None:
indices = np.zeros(n_samples, dtype=int)
new_cluster = max(indices) + 1
# Only need to lookup lhs as rhs is comple... | The function `_choose_optimal_split` identifies the optimal node in a linkage matrix to split, maximizing the Silhouette Index (SI) for clustering quality. It evaluates all candidate nodes, computes cluster metrics (IC, DL), and tracks the best split (highest SI). After selecting the optimal node, it updates the node l... | def _choose_optimal_split(self, nodes, clustering=None, ic_temp=None):
n_samples = len(self.model.labels_)
largest_si = 0
largest_attributes = None
largest_idx = None
largest_clustering = None
largest_ic = None
largest_dl = 0
largest_ic_attributes = 0
... |
def check_cache(self, alpha_pre_refine=0, beta_pre_refine=0):
to_hash = f'{self.name}{self.alpha}{self.beta}{self.runtime}{alpha_pre_refine}{beta_pre_refine}'
hash_string = sha256(to_hash.encode('utf-8')).hexdigest()
previously_calculated = from_cache(join(self.cache_path, hash_string))
... | The code refines model parameters (alpha, beta) and runtime settings, checks a cache for precomputed results using hash strings, performs iterative refinement if needed, caches new results, and returns optimized clustering, attributes, and SI values. | def refine(self, alpha=None, beta=None, runtime_id=0):
alpha_pre_refine = self.alpha
beta_pre_refine = self.beta
if alpha is not None:
self.alpha = alpha
if beta is not None:
self.beta = beta
self.runtime = RUNTIME_OPTIONS[runtime_id]
hash_string, ... |
def check_cache(self, alpha_pre_refine=0, beta_pre_refine=0):
to_hash = f'{self.name}{self.alpha}{self.beta}{self.runtime}{alpha_pre_refine}{beta_pre_refine}'
hash_string = sha256(to_hash.encode('utf-8')).hexdigest()
previously_calculated = from_cache(join(self.cache_path, hash_string))
... | This code optimizes a clustering process by updating parameters (alpha, beta), selecting a runtime mode, checking a cache for precomputed results, and either retrieving cached data or executing optimization steps involving candidate merging and iteration. It returns optimized clustering results, attributes, and a simil... | def optimise(self, alpha=None, beta=None, runtime_id=0):
if alpha is not None:
self.alpha = alpha
if beta is not None:
self.beta = beta
self.runtime = RUNTIME_OPTIONS[runtime_id]
hash_string, previously_calculated = self.check_cache()
if previously_calcula... |
def setup_and_init_weights(nn_structure, W_ini):
W = {} #creating a dictionary i.e. a set of key: value pairs
b = {}
for l in range(1, len(nn_structure)):
#Logistic
if W_ini == 2:
rr = np.sqrt((6 / (64 + 10)))
W[l] = r.uniform(-rr, rr, (nn_structure[l], nn_structure[l... | The main task of the code is to train a neural network using gradient descent with backpropagation. It initializes weights and biases, iteratively performs forward passes, computes output and hidden layer deltas, accumulates gradients, updates parameters using the learning rate, and tracks average cost over iterations ... | def train_nn(nn_structure, X, y, iter_num, alpha, act, W_ini):
W, b = setup_and_init_weights(nn_structure, W_ini)
cnt = 0
N = len(y)
avg_cost_func = []
print('Starting gradient descent for {} iterations'.format(iter_num))
while cnt < iter_num:
if cnt%1000 == 0:
print('Iterati... |
def setup_and_init_weights(nn_structure, W_ini):
W = {} #creating a dictionary i.e. a set of key: value pairs
b = {}
for l in range(1, len(nn_structure)):
#Logistic
if W_ini == 2:
rr = np.sqrt((6 / (64 + 10)))
W[l] = r.uniform(-rr, rr, (nn_structure[l], nn_structure[l... | This function trains a neural network with regularization using gradient descent. It initializes weights/biases, iterates over training data, performs feedforward passes, calculates layer deltas via backpropagation, updates weights/biases with regularization, and tracks average cost. The process minimizes the loss func... | def train_nn_reg(nn_structure, X, y, iter_num, alpha, lamb, act, W_ini):
W, b = setup_and_init_weights(nn_structure, W_ini)
cnt = 0
N = len(y)
avg_cost_func = []
print('Starting gradient descent for {} iterations'.format(iter_num))
while cnt < iter_num:
if cnt%1000 == 0:
prin... |
def subsample(dataset, ratio):
sample = list()
n_sample = round(len(dataset) * ratio)
while len(sample) < n_sample:
index = randrange(len(dataset))
sample.append(dataset[index])
return sample
def build_tree(train, max_depth, min_size, n_features):
root = get_split(train, n_features)
... | The code implements a random forest algorithm by building multiple decision trees using bootstrapped samples from the training data. Each tree is trained with a specified maximum depth, minimum size, and random feature selection. Predictions are aggregated through bagging (averaging) across all trees to generate final ... | def random_forest(train, test, max_depth, min_size, sample_size, n_trees, n_features):
trees = list()
for i in range(n_trees):
sample = subsample(train, sample_size)
tree = build_tree(sample, max_depth, min_size, n_features)
trees.append(tree)
predictions = [bagging_predict(trees, ro... |
def subsample(dataset, ratio):
sample = list()
n_sample = round(len(dataset) * ratio)
while len(sample) < n_sample:
index = randrange(len(dataset))
sample.append(dataset[index])
return sample
def build_tree(train, max_depth, min_size, n_features):
root = get_split(train, n_features)
... | The code implements a random forest algorithm by generating multiple decision trees using bootstrapped samples from the training data. Each tree is built with specified parameters (max_depth, min_size, n_features). Predictions are aggregated via bagging (averaging/voting) across all trees to improve accuracy and reduce... | def random_forest(train, test, max_depth, min_size, sample_size, n_trees, n_features):
trees = list()
for i in range(n_trees):
sample = subsample(train, sample_size)
tree = build_tree(sample, max_depth, min_size, n_features)
trees.append(tree)
predictions = [bagging_predict(trees, ro... |
def like_by_hashtag(self, hashtag):
#search for the hashtag in the search bar
self.search('#'+hashtag)
#click on the hashtag
self.find_elem_and_action(f'//a[@href="/explore/tags/{hashtag}/"]', False, '', True)
#find all the links in the hashtag page
links = self.driver.f... | The code's main task is to repeatedly perform social media actions—liking, commenting, and navigating—using random hashtags, with error handling that retries up to a specified number of attempts (MAX_ATTEMPTS) if exceptions occur, ensuring resilience against transient failures during automated interactions. | def commands(self):
attempts = 0
while True:
try:
# like a post by a random hashtag
self.like_by_hashtag(random.choice(self.hashtags))
# navigate back to home page
self.go_home()
# comment and like a post by a ra... |
def inOrder(self, root):
if root is not None:
self.inOrder(root.left)
print(root.val, end=' ')
self.inOrder(root.right)
def preOrder(self, root):
if root is not None:
print(root.val, end=' ')
self.preOrder(root.left)
self.preOrder(r... | The main task of the code is to print the in-order, pre-order, descending-order, and level-by-level traversal sequences of a binary tree rooted at `self.root`, using recursive traversal methods and storing level-order values in `self.vals` for output. | def printInfo(self):
root = self.root
print('\nIn-order: ', end='\t')
self.inOrder(root)
print('\nPre-order: ', end='\t')
self.preOrder(root)
print('\nDesc-order: ', end='')
self.descOrder(root)
print('\nLevel by level order: ')
self.vals = []
... |
def _print_shortcuts_keys(self):
print("Control keys:")
print("Esc - Exit and Close.")
print(Settings.CONTROL_COLORMAP_NEXT + " - Colormap Next")
print(Settings.CONTROL_COLORMAP_PREV + " - Colormap Previous")
print(Settings.CONTROL_INTERPOLATION_NEXT + " - Interpolation Next")
... | This method displays the next frame onscreen by first showing shortcut keys on the user's initial run, then updating the image frame, displaying the processed image, and setting up click and keyboard event handlers. | def display_next_frame_onscreen(self):
# Display shortcuts reminder to user on first run
if not self._displaying_onscreen:
self._print_shortcuts_keys()
self._displaying_onscreen = True
self.update_image_frame()
self._show_processed_image()
self._set_cl... |
def _print_shortcuts_keys(self):
"""Print out a summary of the shortcut keys available during video runtime."""
print("The following keys are shortcuts for controlling the video during a run:")
print("Esc - Exit and Close.")
print("S - Save a Snapshot of the Current Frame")
print... | The main task of the code is to display a live camera feed on the screen. On the first call, it shows shortcut keys to the user, updates the image frame, displays the processed image, and sets up click/keyboard event handlers for interaction. | def display_next_frame_onscreen(self):
"""Display the camera live to the display"""
# Display shortcuts reminder to user on first run
if not self._displaying_onscreen:
self._print_shortcuts_keys()
self._displaying_onscreen = True
self.update_image_frame()
... |
def __getNewDocuments(self, stock : str):
"""
Private method to query new documents and update them
"""
if self.__queryNewDocuments():
self.getNews(stock)
self.__updateData(("currentDate", TimeManager.getCurrentDate()))
self.__saveNewDocuments()
... | The main task of the code is to retrieve and process stock status information by querying an LLM with the stock name, updating sources, and returning the processed response. | def getStockStatus(self, stock : str):
"""
Public method to get the stock status
"""
self.__getNewDocuments(stock)
response : dict = self.ask(config.llmQuestions["statusStock"] + " " + stock)
response = self.__updateSources(response)
return response |
def read_dictionary():
"""
This function reads file "dictionary.txt" stored in FILE
and appends words in each line into a Python list
"""
with open(FILE,'r') as f:
for line in f:
dic_list.append(line.strip())
def check_input(s):
global word_list
if len(s)!=7:
return True
for i in range(len(s)):
if i %... | The code's main task is to execute a boggle word-finding algorithm by reading a dictionary, validating four rows of user-input letters, and measuring the algorithm's speed using a timer. It checks input legality, processes the grid with `find_word`, and outputs the elapsed time for performance evaluation. | def main():
"""
TODO:
"""
start = time.time()
####################
read_dictionary()
while True:
row_1 = input('1 row of letters: ').lower()
if check_input(row_1) :
print('Illegal input')
break
row_2 = input('2 row of letters: ').lower()
if check_input(row_2):
print('Illegal input')
break
... |
def init_main_window(self):
""" Creates and returns instance of Tk"""
gui_main = Tk()
gui_main.geometry(f"{WIDTH}x{HEIGHT}")
gui_main.resizable(width=False, height=False)
gui_main.title("HUJI Boggle!")
gui_main.configure(background=BG_COLOR)
return gui_main
def cr... | This code initializes a game application by setting up a main window, defining game elements (canvas, textbox, time, score), creating game frames, and starting the main event loop to run the GUI. | def __init__(self, letters):
self.__letters = letters
self.__root = self.init_main_window()
self.frames = {}
# game elements
self.__game_cubes = []
self.__elements = {
"canvas" : "",
"textbox" : "",
"time" : "",
"... |
def approx_LS_solution(X,l,Y,constraint):
A = pseudo_inverse(X,l)[0].dot(Y)
cond=pseudo_inverse(X,l)[1]
if constraint == 'none':
return A, cond
if constraint == 'nearest_orth':
U,P=polar_decomp(A+identity(A.shape[0]))
return U-identity(U.shape[0]), cond
if constraint == 'p... | The function `fit_dynamical_system` fits a dynamical system model to high-dimensional time-series data using PCA and linear regression with ridge regularization. It computes model parameters (MT), evaluates performance via metrics like R², AIC, BIC, and GCV, and optionally applies K-fold cross-validation to assess gene... | def fit_dynamical_system(X,nDim,cv,par):
### X is #CELLS x #TIMEPOINTS x #CONDITIONS
N = X.shape[0]
T = X.shape[1]
C = X.shape[2]
method = par[0];
nchunks = par[1];
nrandsampl = par[2];
l = par[3] # ridge parameter
number_par = par[4]## for AIC and BIC formulae
constraint = par[5]... |
def token(self):
"""Return the next token."""
# Are there still some tokens left? then just return the next one
if self._token_list:
tok = self._token_list[0]
self._token_list = self._token_list[1:]
return tok
# Read a new line
s = self.read_... | The function `read_motion` parses motion data from a file. It checks for the keyword "MOTION", reads the number of frames, and extracts the frame time. It validates syntax by ensuring expected tokens like "Frames:" and "Frame Time:" are present. Then, it reads frame values, verifies their count matches predefined chann... | def read_motion(self):
"""Read the motion samples."""
# No more tokens (i.e. end of file)? Then just return
try:
tok = self.token()
except StopIteration:
return
if tok != "MOTION":
raise SyntaxError("Syntax error in line %d: 'MOTION' expected,... |
def token(self):
"""Return the next token."""
# Are there still some tokens left? then just return the next one
if self._token_list:
tok = self._token_list[0]
self._token_list = self._token_list[1:]
return tok
# Read a new line
s = self.read_... | This function parses a node's data from a structured format, reading its name, offset coordinates, channel definitions, and hierarchical children. It processes tokens like "OFFSET," "CHANNELS," "JOINT," and "End," recursively building a tree of nodes. Errors are raised for invalid syntax or unknown keywords, ensuring p... | def read_node(self):
"""Read the data for a node."""
# Read the node name (or the word 'Site' if it was a 'End Site' node)
name = self.token()
self._node_stack[-1].name = name
tok = self.token()
if tok != "{":
raise SyntaxError("Syntax error in line %d: '{' ... |
def read_hierarchy(self):
"""Read the skeleton hierarchy."""
tok = self.token()
if tok != "HIERARCHY":
raise SyntaxError("Syntax error in line %d: 'HIERARCHY' expected, "
"got '%s' instead" % (self._line_num, tok))
tok = self.token()
if t... | The code reads a file by opening it, parsing its hierarchical structure via `read_hierarchy()`, notifying listeners of the hierarchy with `on_hierarchy()`, and then reading motion data through `read_motion()` to process file content in a structured manner. | def read(self):
"""Read the entire file."""
with open(self.filename, 'r') as self._file_handle:
self.read_hierarchy()
self.on_hierarchy(self.root)
self.read_motion() |
def _consider_file(file_path: str) -> bool:
return _file_extension(file_path) in FILE_EXTENSIONS_2_CONSIDER
def _remove_duplicates(reference_file_path: str, dir_path: str) -> Iterator[int]:
""" Walks through all file system objects residing in dir_path,
either checks whether duplicate of file residing u... | The function `get_reference_file` recursively traverses a directory tree, identifies files that should be considered for duplicate removal, and eliminates duplicates while yielding the disk space (in bytes) reclaimed from each removal. It uses progress tracking and recursion to handle nested directories, ensuring effic... | def get_reference_file(dir_path: str) -> Iterator[int]:
""" Walks through all file system objects residing in dir_path,
either triggers duplicates search and removal if encountering file which
ought to be considered, or recurses on encounter of non-empty directory
respectively
Args:... |
def get_teams():
"""
Pulls all of the current teams from the NBA api and returns a dictionary containing the team names and their IDs
:return: A dictionary containing the team names and their team ID
"""
nba_teams = teams.get_teams()
teams_dict = {}
# We only need the team's name and th... | The main task of the code is to generate CSV files containing NBA season game data for a specified number of seasons, starting from the most recent season. It calculates season years, retrieves game data, and saves each season's data as a CSV file with a filename formatted as "games_{season}.csv". | def get_data(num_seasons, curr_season):
"""
Creates CSV files for num_seasons seasons. curr_season is the season that happened most recently.
Example: if curr_season is 22 and num_seasons is 4, CSV files will be created for seasons 2018-19, 2019-20, 2020-21,
and 2021-22.
:param num_seasons: The... |
def forward_train(self, **kwargs):
target, x_last, img, current_device = self.get_train_input(**kwargs)
t = uniform_sampler(self.num_timesteps, img.shape[0], current_device)
x_t = self.q_sample(target, x_last, t, current_device)
z_t = torch.cat((img, x_t), dim=1)
pred_logits = se... | The main task of the code is to determine whether to execute training or testing logic based on the `return_loss` flag. If `return_loss` is `True`, it calls `forward_train` for training; otherwise, it performs testing by invoking `simple_test_instance` or `simple_test_semantic` depending on the model's task type. It al... | def forward(self, img_metas, return_loss=True, **kwargs):
"""Calls either :func:`forward_train` or :func:`forward_test` depending
on whether ``return_loss`` is ``True``.
Note this setting will change the expected inputs. When
``return_loss=True``, img and img_meta are single-nested (i.e... |
def catchup_run(out_dir):
dry_run=False
for run_string in os.listdir(out_dir):
print('Catching up {:}'.format(run_string))
run_string_length = len(run_string) + 1
dict={}
for runs in os.listdir(out_dir + '/' + run_string):
if '{:}_'.format(run_string) in runs:
... | The code parses configuration parameters from a file (`run.aux`) to set up simulation runs. It reads variables like output directory, run type, ring sizes, temperature, seeds, and potential settings. It converts these into structured options (e.g., boolean flags, numerical ranges) and initializes directories. Based on ... | def import_aux():
##################################################################
#import aux
with open('run.aux', 'r') as f:
skip = f.readline()
output = str(f.readline().split()[0])
skip = f.readline()
dry_run = (f.readline().split(... |
def count_steps(instructions: str, nodes_input: str) -> int:
node_map: dict[str, dict[str, str]] = create_node_map(nodes_input)
nodes: list[str] = [n for n in node_map if n.endswith("A")]
print("Starting nodes:", nodes)
# determine loop lengths of each starting value
loop_lengths: list[int] = []
... | (The main task of the code is to compute the number of steps from input data, print the result, and save it. It loads input via `load_input()`, calculates steps using `count_steps()`, outputs the value with `print()`, and stores it via `write_result()`. The function orchestrates data processing, calculation, and result... | def main():
n_steps: int = count_steps(*load_input())
print(n_steps)
write_result(n_steps) |
def _create_cells(self):
for row in range(self.num_rows):
_cell_rows = []
for col in range(self.num_cols):
_cell_rows.append(Cell(self._win))
self._cells.append(_cell_rows)
for col in range(self.num_cols):
for row in range(self.num_rows):
... | This code initializes a maze generator by setting up a grid of cells with specified dimensions and sizes, creating adjacency lists for connections, breaking walls recursively to form paths, and solving the maze. It uses randomization for maze generation and includes methods for visualizing the maze via a window. | def __init__(
self,
x1,
y1,
num_rows,
num_cols,
cell_size_x,
cell_size_y,
win=None,
seed=None
):
self._x1 = x1
self._y1 = y1
self.num_rows = num_rows
self.num_cols = nu... |
def resize(image, factor_value):
current_img_width = image.shape[1]
scale_percent = 100
if(current_img_width > factor_value):
scale_percent = factor_value/current_img_width*100
width = int(current_img_width * scale_percent / 100)
height = int(image.shape[0] * scale_percent / 100)
di... | The main task of the code is to process an input image by resizing, cropping, converting to grayscale, enhancing brightness/contrast, applying thresholding, erosion, and combining results via bitwise OR to produce a modified image. | def ImageProcess(image, factor_value):
resized = resize(image,factor_value)
cropped = transformation(resized)
width = cropped.shape[1]
height = cropped.shape[0]
cropped = cropped[5:(height-5)]
gray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
gray = BrightnessContrast(3,gray)
ret,thresh... |
def camera():
vid = cv2.VideoCapture(0) #creates camera video object
vid.set(cv2.CAP_PROP_FRAME_WIDTH, 1920) #sets camera width
vid.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080) #sets camera height
while True:
ret, frame = vid.read() #gets one frame from camera feed
cv2.imshow("normal",frame) #... | The code generates a list of random words from a dictionary file, displays them, waits for user input, captures an image, annotates it, and converts the result to a PDF. | def generate_practice():
global practice_length
global practice_text
f = open(sys_dir+"\dictionary.txt", "r")
dict = f.readlines()
for i in range(practice_length):
practice_text.append(dict[randint(0, 45382)][:-1])
print("------------------")
print("")
for i in practice_tex... |
def camera():
vid = cv2.VideoCapture(0) #creates camera video object
vid.set(cv2.CAP_PROP_FRAME_WIDTH, 1920) #sets camera width
vid.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080) #sets camera height
while True:
ret, frame = vid.read() #gets one frame from camera feed
cv2.imshow("normal",frame) #... | The code collects user-input text (number of words) and captures an image, then processes the image with annotations and converts it to PDF, storing data globally for later use. | def create_practice():
global practice_length
global practice_text
global image
print("Please type how many words to input")
print("Length:",end="")
length = input()
practice_length = int(length)
practice_text = []
print("Type words")
for i in range(practice_length):
text... |
def generate_practice_test():
global practice_length
global practice_text
f = open(sys_dir+"\dictionary.txt", "r")
dict = f.readlines()
for i in range(practice_length):
practice_text.append(dict[randint(0, 45382)][:-1])
print("------------------")
print("")
for i in practic... | The code's main task is to generate a practice test, capture an image via a camera, measure the time taken for image acquisition, annotate the captured image, and convert the annotated result into a PDF document. It logs the duration of the image capture process and outputs the annotated image as a PDF. | def take_test():
generate_practice_test()
starting = time.time()
print("START TIME! - Launching Camera...")
image = camera()
stopping = time.time()
output = annotate_image(image)
print("Time Taken: " + str(stopping - starting))
convertPDF(output) |
def already_voted(request, poll):
hash = request_hash(request)
return poll.vote_set.filter(hash__exact=hash).exists()
def request_hash(request):
hasher = hashlib.md5()
hasher.update(request.META['REMOTE_ADDR'])
hasher.update(request.META['HTTP_USER_AGENT'])
return hasher.hexdigest()
def create(r... | This code processes a vote submission for a poll by validating the selected choice, checking if the poll is active and the user hasn't already voted, incrementing vote counts, and using a Bloom filter to track unique voters' IPs. It updates the poll's vote data and stores the Bloom filter state, ensuring only new voter... | def vote(request, poll):
try:
choice_name = request.POST['choice']
selected_choice = poll.choice_set.get(choice=choice_name)
except (KeyError, Choice.DoesNotExist):
return render_to_response('detail.html', {'poll':poll, 'error_message':"You didn't select a choice."},
cont... |
def MakeHardwareStationInterface(
scenario: Scenario,
meshcat: Meshcat = None,
*,
package_xmls: typing.List[str] = [],
):
builder = DiagramBuilder()
# Visualization
scene_graph = builder.AddNamedSystem("scene_graph", SceneGraph())
plant = MultibodyPlant(time_step=scenario.plant_config.t... | Your returnThe function creates a HardwareStation diagram for simulation or hardware control based on the `hardware` flag. When `hardware=False` (default), it constructs a diagram with a MultibodyPlant, SceneGraph, visualizers, and drivers from the scenario. When `hardware=True`, it returns a HardwareStationInterface f... | def MakeHardwareStation(
scenario: Scenario,
meshcat: Meshcat = None,
*,
package_xmls: typing.List[str] = [],
hardware: bool = False,
parser_preload_callback: typing.Callable[[Parser], None] = None,
parser_prefinalize_callback: typing.Callable[[Parser], None] = None,
):
"""
If `hardw... |
def send_permission(self, permission='launch', waitfor='permission_needed'):
msg = self.receive_data_line()
while waitfor in msg.decode() or 'received' not in msg.decode():
self.send_data(permission)
msg = self.receive_data_line()
while 'received' in msg.decode():
... | The code listens for incoming messages, processes commands like 'left', 'right', 'position', or 'plan', updates the robot's direction or state accordingly, and breaks the loop after handling each command. It continuously waits for input, sending permissions and executing actions based on received data. | def listen(self):
while True:
msg = self.receive_data_line().decode()
if 'left' in msg:
self.send_permission(waitfor='left')
self.direction += 360 - 90
self.direction %= 360
elif 'right' in msg:
self.send_permiss... |
def shuffle(X, y, epoch):
"""
Permute the training data for SGD.
:param X: The original input data in the order of the file.
:param y: The original labels in the order of the file.
:param epoch: The epoch number (0-indexed).
:return: Permuted X and y training data for the epoch.
"""
np.r... | The code trains a neural network using stochastic gradient descent (SGD) with adaptive learning rates (RMSProp-like updates). It shuffles training data per epoch, computes gradients via forward/backward passes, accumulates squared gradients for normalization, updates weights, and logs training/validation cross-entropy ... | def train(X_tr, y_tr, X_te, y_te, nn):
"""
Train the network using SGD for some epochs.
:param X_tr: train data
:param y_tr: train label
:param X_te: train data
:param y_te: train label
:param nn: neural network class
"""
alpha = nn.w1
beta = nn.w2
lr = nn.lr
epochs = nn... |
def _get_data(self, gt):
self._gt_update(gt)
# convert each object to a feature vector
data = []
for i in range(len(gt['features'])):
feature = gt['features'][i]
if feature['properties']['label'] not in ['Ground', 'Trajectory', 'Slingshot']:
# create record and append to training_data
unit = []
... | The main task of the code is to classify geographic features in the input data (`gt`) using a machine learning model, determine novelty based on prediction confidence thresholds, and update feature properties with classification labels, material, shape, and novelty flags. It applies secondary classifiers for novel obje... | def classify(self, gt, switchoff=False):
if switchoff:
return gt
if len(gt) < 1: # if gt is empty
return gt
data = self._get_data(gt)
if len(data) < 1: # if there are only basic objects data will be empty
return gt
data = np.array(data) # format for sklearn
labels = self.model.predict(data)
... |
def version():
version = '1.1'
return version
def decrypt(string,key,setting_one,setting_two):
word_list = string.split('-')
words = []
for word in word_list:
letters = word.split('|')
letter_list = []
for letter in letters:
decrypted = decrypts(int(letter),key,se... | This code defines a command-line interface (CLI) tool for encrypting and decrypting messages using layered keys. It accepts arguments for version info, changelog, encryption, and decryption. When decrypting, it reads an encrypted file, processes it with three keys, and outputs the decrypted result. Similarly, encryptio... | def cli():
parser = ArgumentParser()
parser.add_argument('--version', help='displays version info', action='store_true')
parser.add_argument('--changes', help='find out what has changed', action='store_true')
parser.add_argument('--decrypt', help='decrypts a message')
parser.add_argument('--encrypt'... |
def hasModifier(selector):
"""Returns whether selector has a modifier (with or without value)."""
if isElement(selector):
return '_' in selector.split('__')[1]
return '_' in selector
def split_selector(selector):
"""Splits selector into its components, along with the necessary
leading underscores."""
bl... | This function extracts and processes CSS declaration blocks, handling media queries and adjusting selectors' specificity. It detects URLs/src paths requiring path fixes, modifies declarations based on selector modifiers, and stores results in the declarations dictionary, returning updated selector and start index for f... | def get_declaration_block(block, line, lines, line_idx, start_idx, selector, declarations):
"""Grabs the current declaration block and saves it to declarations.
Handles media queries as well.
If a file path enclosed in url(...) or src(...) is detected in any
declaration that will have... |
def isSelector(line, block):
"""Returns whether line begins with a BEM class selector for the
given block."""
return line.startswith(f'.{block}')
def get_declaration_block(block, line, lines, line_idx, start_idx, selector, declarations):
"""Grabs the current declaration block and saves it to declarations.
... | The main task of the code is to parse a CSS file from a specified path, extract and organize CSS declarations into a dictionary where keys are selectors and values are lists of declarations. It handles selectors, media queries, and adjusts declaration strings based on selector structure, including fixing file paths and... | def get_declaration_blocks(block):
"""
Reads {block}.css sorting all declarations into a dict of the form
declarations = {selector: ['declaration1', 'declaration2', ...]}.
"""
path = f'./blocks/{block}/{block}.css'
declarations = collections.defaultdict(list)
with open(path, 'r') as block_css:
li... |
def ccl_to_frames(video_file: str, dir = './recent'):
if not os.path.exists(dir):
os.makedirs(dir)
print("Converting ccl to frames...")
cap = cv2.VideoCapture(video_file)
fps = cap.get(cv2.CAP_PROP_FPS)
# Hardcoded Crop... I should figure out a way to detect cropped boundaries
... | The main task of the code is to convert a video file into synchronized WebVTT captions. It processes the video by extracting frames, converting them to text lines, removing duplicates, and generating captions with a 750ms duration. The function returns structured caption data for the video. | def video_file_to_captions(video_file: str) -> WebVTT:
frames = ccl_to_frames(video_file, f'./{song_name}')
lines = frames_to_text(frames)
lines = remove_duplicate_lines(lines)
# lines = remove_invalid_lines(lines)
captions = text_to_captions(lines, 750)
return captions |
def download_subs_from_youtube(url: str, title: str, path: str) -> bool:
if not os.path.exists(path):
os.mkdir(path)
ydl_opts = {'paths': {'home': path},
'outtmpl': f'{title}.%(ext)s',
'writesubtitles': True,
'subtitleslangs': ['en-GB', 'en', 'en... | This function downloads subtitles for songs from YouTube, processes videos for missing subtitles by converting frames to text, applying spell checks, and generating VTT caption files. It handles song lists, delays, and saves processed captions in specified paths. | def download_subs(artists: List[str], song_names: List[str], delays: List[int], sub_path: str, ccl_path: str):
songs = [f'{s[0]} - {s[1]}' for s in list(zip(artists, song_names, delays))]
ccl_songs = [song for song in songs if not download_subs_from_youtube(get_youtube_link(song[0], song[1]), song[1], sub_path)... |
def ccl_to_frames(video_file: str, dir: str = '') -> List[TimedFrame]:
if not os.path.exists(dir) and dir != '':
os.makedirs(dir)
print("Converting ccl to frames...")
cap = cv2.VideoCapture(video_file)
fps = cap.get(cv2.CAP_PROP_FPS)
# Hardcoded Crop... I should figure out a way to... | The main task of the code is to convert a video file into WebVTT captions by extracting frames, generating text from frames, caching results, applying spell checks, removing duplicates, and formatting text with a delay. It leverages caching to avoid redundant processing and ensures accurate, cleaned captions for video ... | def video_file_to_text(video_path: str, cache_name: str, delay: int, use_cache: bool = False, cache_path: str = '/Users/alexchen/Coding/Projects/cclyrics_to_ttml') -> WebVTT:
# I think the way I want to design the database aspect of this is to define a cache section in a config file
# and then have a sub folder... |
def reset_env():
global env, channel
env.reset()
global start_x, start_z, obs_queue
obs_queue = Queue(maxsize=TEMPORAL_WINDOW)
env.reset()
start_x, _, start_z, _, _, _, _, _, _, _, _ = get_obs()
init_drive()
def get_obs():
decision_steps, terminal_steps = env.get_steps(behavior_name)
... | The code simulates an autonomous driving task in an environment, tracking distance traveled, steps taken, and whether the run completed successfully. It uses a neural network model to predict actions based on observation data stored in a queue, updating the environment state iteratively until a crash or predefined stop... | def drive():
global model, obs_queue
reset_env()
x, _, z, _, _, _, _, _, _, _, _ = get_obs()
last_pos = (x, z)
distance, steps, finished = 0.0, 0, 0.0
while not is_crashed():
x, _, z, xx, _, zz, s1, s2, s3, s4, s5 = get_obs()
if dist(x, z, xx, zz) < 5.0:
break
... |
def reset_env():
global start_x, start_z, obs_queue
obs_queue = Queue(maxsize=TEMPORAL_WINDOW)
env.reset()
start_x, _, start_z, _, _, _, _, _, _, _, _ = get_obs()
init_drive()
def get_obs():
decision_steps, terminal_steps = env.get_steps(behavior_name)
return decision_steps.obs[0][0,:]
def i... | The code drives an autonomous agent in a simulated environment using a pre-trained neural network model. It loads model weights, processes sensor observations, predicts actions via the model, executes them, and tracks metrics like distance traveled, steps taken, and crash status. The agent avoids abrupt movements by ch... | def drive():
global model, obs_queue
reset_env()
model.load_state_dict(torch.load('model_weights.pth'))
model.eval()
x, _, z, _, _, _, _, _, _, _, _ = get_obs()
last_pos = (x, z)
distance, steps, finished = 0.0, 0, 0.0
while not is_crashed():
x, _, z, xx, _, zz, s1, s2, s3, ... |
def render_background(self):
background_image = pygame.image.load("./images/puddle.jpeg")
self.surface.blit(background_image, (0,0, 500, 200))
if self.difficulty_level=="Expert":
colour = (255,0,0)
pygame.draw.rect(self.surface, colour, pygame.Rect(0, 0, 900, 600), 2)
def... | This function refreshes the game screen by rendering the background, updating and drawing the main snake (and friend snake for two-player mode), drawing yuckies and yummies, displaying the score, updating the display, and checking collisions for walls, self-eating, yummy consumption, and yuckies. It ensures all game el... | def refresh_screen(self):
self.render_background()
self.snake.update_frame() # this updates the co-ordinates AND includes the draw function
if self.players == 2:
self.snake_friend.update_frame() # this updates the co-ordinates AND includes the draw function
self.yuckies1.dr... |
def make_snake(self):
if self.players == 1:
self.snake = Snake(self.surface, 3, self.players, "only") # arguments => the type of game_window // number of snake sections
self.snake.draw()
elif self.players == 2:
self.snake = Snake(self.surface, 3, self.players, "firs... | The code implements a snake game loop with menu navigation, player controls (keyboard for player 1, 'WASD' for player 2), collision handling, game speed control, and game-over logic. It initializes game elements, processes user inputs to change snake direction, updates the game state, and renders the screen while manag... | def run(self):
intro_menu = True
while intro_menu: # This loop allows for game menu parameters to be set before playing
self.game_menu()
intro_menu = False
game_running = True
pause_on_interchange = False
self.make_snake()
self.m... |
def conv(inpOp, nIn, nOut, kH, kW, dH, dW, padType, name, phase_train=True, use_batch_norm=True, weight_decay=0.0):
with tf.variable_scope(name):
l2_regularizer = lambda t: l2_loss(t, weight=weight_decay)
kernel = tf.get_variable("weights", [kH, kW, nIn, nOut],
initi... | This function implements an Inception module with multiple parallel convolutional branches (1x1, 3x3, 5x5) and a pooling branch, concatenating their outputs. It uses TensorFlow, applies batch normalization, and returns a combined feature map capturing multi-scale features for deep neural networks. | def inception(inp, inSize, ks, o1s, o2s1, o2s2, o3s1, o3s2, o4s1, o4s2, o4s3, poolType, name,
phase_train=True, use_batch_norm=True, weight_decay=0.0):
# print('name = ', name)
# print('inputSize = ', inSize)
# print('kernelSize = {3,5}')
# print('kernelStride = {%d,%d}' % (ks,ks))
# p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.