dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def createBins(compressed=False, only_half=False, big_buckets=False):
if compressed == False:
if only_half == False:
xBin = np.asarray(
[-18.8872, -17.8872, -16.8872, -15.8872, -14.8872, -13.8872, -12.8872, -11.8872, -10.78992, -9.69264,
-8.59536, -7.49808, -6.40... | The main task of the code is to generate a heatmap visualizing MRP (likely "Margin of Victory" or similar metric) data for a specific bucket, using reshaped V_full and count_full arrays. It creates a 7x6 grid heatmap with color-mapped values, overlays annotated text showing both the MRP value and count data, and integr... | def createMRPheatmap(V_full, count_full, bucket, choice='rally', vmin=-1, compressed=False, only_half=False, big_buckets=False,
half_label=False):
xBin, yBin = createBins(compressed=True, only_half=True, big_buckets=True)
V_bucket = V_full[choice][bucket - 1, :]
V_bucket = np.reshape(... |
def createBins(compressed=False, only_half=False, big_buckets=False):
if compressed == False:
if only_half == False:
xBin = np.asarray(
[-18.8872, -17.8872, -16.8872, -15.8872, -14.8872, -13.8872, -12.8872, -11.8872, -10.78992, -9.69264,
-8.59536, -7.49808, -6.40... | The function generates a heatmap visualizing a Markov Decision Process (MDP) for a tennis rally scenario, displaying value functions (V), state visit counts, and optimal actions across a court layout. It reshapes input data into 7x6 grids, plots the value heatmap with color-coding, annotates each cell with values, coun... | def createMDPheatmap(V_full, count_full, opt_policy_full, bucket, choice='rally', vmin=-1, compressed=False, only_half=False, big_buckets=False,
half_label=False, diff=False):
xBin, yBin = createBins(compressed=True, only_half=True, big_buckets=True)
V_bucket = V_full[choice][bucket - 1, ... |
def get_policy_specific_transition_matrix(opt_policy):
T = pd.DataFrame(np.zeros((5297, 5297)))
for state in range(5292):
action = opt_policy[state][0]
T_row = get_particular_state_transition(state, action)
T.iloc[state] = T_row
T = fix_T_for_unseen_states(T)
return T.to_num... | The code implements **policy iteration** to find the optimal policy in a reinforcement learning setting. It iteratively evaluates the current policy's value function (V) using a transition matrix and updates the policy by selecting actions that maximize the expected value. If a better action is found (within a toleranc... | def solve_policy_iteration(opt_policy, max_iterations=50, eps=1e-6, n_states=5292):
for i in range(max_iterations):
change = 0
# get transition matrix for this current policy
T = get_policy_specific_transition_matrix(opt_policy)
# calculate V's (aka win absorption probs)
V ... |
def calculate_word_score(corpus_path, file_path):
"""
Calculates the TF_IDF score of every term inside the targeted text(file)
"""
global dict_for_score
analyze_target_text(file_path)
n = count_doc_frequency(corpus_path)
for key in dict_file_occur:
dict_for_score[key] = dict_for_file... | The main task of the code is to analyze a text file's content using a corpus. It calculates word scores, prints top terms, and processes sentences from the specified file path. The code loads a corpus, computes linguistic metrics for words, identifies significant terms, and performs sentence-level analysis on the targe... | def main():
corpus_path = r"D:\PSIML_PRVI\public\corpus"
file_path = r"D:\PSIML_PRVI\public\corpus\quantum\Quantum Leap.txt"
calculate_word_score(corpus_path, file_path)
print_top_terms()
analyze_text_sentences(file_path) |
def read_image(dir_path):
image = None
for file in os.listdir(dir_path):
if file.endswith('.png'):
image = Image.open(os.path.join(dir_path, file))
return image
def find_corner_coordinates(img_mat):
n, m, _ = img_mat.shape
for i in range(n):
for j in range(m):
... | The code processes a chessboard image to determine if a checkmate exists. It reads the image, identifies the board's corner and dimensions, generates a piece library, converts the board to FEN notation, locates kings, analyzes attack patterns, and checks for checkmate conditions between white and black pieces. | def main():
image_path = input()
board_image = read_image(image_path)
img_mat = np.array(board_image)
left_corner = find_corner_coordinates(img_mat)
board_dim = calculate_board_dim(img_mat, left_corner)
print("{0},{1}".format(left_corner[0], left_corner[1]))
create_pieces_library(image_pat... |
def user_select(self):
selection = self.select_gesture(self.user)
return selection
def opponent_select(self):
selection = self.select_gesture(self.opponent)
return selection
def play_round(self, user_select, opponent_select):
user_score = self.user.score
opp_score = self.... | The main task of the code is to repeatedly execute game rounds until either the user or opponent reaches a score of 2. It loops, prompting both players to select options, displaying their choices, and processing each round's outcome via the `play_round` method. The loop terminates when one player's score meets or excee... | def start_rounds(self):
while (self.user.score < 2 and self.opponent.score < 2):
user_select = self.user_select().lower()
opp_select = self.opponent_select().lower()
print(f'{self.user.name} selected {user_select}.')
print(f'{self.opponent.name} selected {opp_sele... |
def display_rules(self):
print('Welcome to Rock, Paper, Scissors, Lizard, Spock!')
print('Play vs AI or a human opponent!')
print('Pick one of five gestures against your opponent and compare them. Winner gets a point and the first player to 2 points wins the entire match!')
print('rock c... | The code's main task is to run a game by displaying rules, determining opponent type, collecting player names, and entering a loop where it starts rounds, displays winners, and checks if players want to replay. The loop continues until the user decides to stop playing. | def run_game(self):
self.display_rules()
self.is_opponent_human_or_ai()
self.get_names()
play_status = True
while(play_status == True):
self.start_rounds()
self.display_game_winner()
play_status = self.play_again() |
def shopToOCR():
try:
screenshot = OCR.capture(())
return processOCR(screenshot)
except Exception as e:
print(f"Error in shopToOCR: {e}", file=sys.stderr)
def boardToModel():
keyboard = Controller()
SimulatePressedKeys = False
try:
print("Capturing screenshots for b... | The code defines a key press handler that triggers specific functions based on pressed keys: 'd' runs OCR on champion areas, '\\' processes board data via model inference, '='/ '-' debug overlay updates, and '[' exits the program. It captures screenshots, processes data, and updates visual overlays for game champion tr... | def on_press(key):
try:
''' HERE IS WHERE THE KEYBINDS ARE HANDLED. '''
# OCR
if key == KeyCode.from_char('d'):
print("d key pressed! \n ShopToOCR Running...")
shopToOCR()
'''
List of things shopToOCR() does
1. Captures screenshot
... |
def make_stdout_script(var, body):
txt = ''
txt += ARGS_PARSE_SCRIPT
txt += f'exec({body})\n'
return txt
def make_funcout_script(var, body, out_var):
func_args_str = var_arr_to_var_str(var)
func_ret_str = var_arr_to_var_str(out_var)
txt = ''
txt += f'def script_func({func_args_str}):... | The function `make_script` generates a Python script based on input variables (`var`), script content (`body`), and output type (`out_type`). It creates different script formats: standard output (`std`), function outputs (`func`), or plot outputs (`plot`). Depending on `out_type`, it uses helper functions to construct ... | def make_script(var, body, out_type="std", out_var=None):
'''
var: variable section. Should be dict of var name - var value,
value should be numeric
body: python script, include "import" section.
out_type: type of script out.
If type == "std", no additional... |
def isCellAlive(item):
return item == '#'
def willCellSurvive(world, size, r, c):
# cell survives when it has 2 or 3 neighbors
if howManyNeibhors(world, size, r, c) == 2 or howManyNeibhors(world, size, r, c) == 3: return True
else: return False
def shouldCreateCell(world, size, r, c):
# cell is cr... | This function updates the newWorld grid based on survival and birth rules of cells from the original world. It checks each cell: if alive, it survives only if willCellSurvive returns True (else cleared); if dead, a new cell is created if shouldCreateCell returns True. The process simulates cellular automaton evolution,... | def aNewWorld(world, newWorld, size):
for r, row in enumerate (world):
for c, item in enumerate (row):
if isCellAlive(item):
if willCellSurvive(world, size, r, c):
pass
# cell is there and will survive
else:
... |
def draw_bord():
pos_x=Window_weidth/3
for i in range(LINES_PER_ORIANTAION):
pygame.draw.line(screen, BLACK, (pos_x, BUFFER), (pos_x,Window_height-TEXTBOX_Y-BUFFER), 3)
pygame.draw.line(screen, BLACK, (BUFFER,pos_x), (Window_height-TEXTBOX_Y-BUFFER,pos_x), 3)
pos_x *=2
pos_y=... | The code runs a Tic-Tac-Toe game where a human player competes against an AI. It handles mouse input to update the game board, checks for wins/ties, alternates turns, and redraws the board. The loop continues until the game ends, then resets for a new match. | def main():
#Variables
RUNNING=True
global CURRENT_TURN,GAMEBOARD,GAME_RESULT
clock = pygame.time.Clock()
while RUNNING:
for event in pygame.event.get():
if event.type == pygame.QUIT:
RUNNING = False
sys.exit()
if event.type == py... |
def get_push_event_details() -> dict:
"""
Get the details of the GitHub push event from the API.
This function will get the details of the GitHub push event from the API.
Returns
-------
dict
Dictionary containing the details of the push event.
"""
# default
push_event_deta... | The main task of the code is to process a GitHub push event, generate release notes if required, and prepare outputs for a GitHub Action. It extracts release details, constructs release tags with optional prefixes, determines if release notes should be generated, and stores these values in a dictionary. The outputs are... | def main() -> dict:
"""
Main function for the action.
Returns
-------
dict
Job outputs.
"""
job_outputs = dict()
# Get the push event details
push_event_details = get_push_event_details()
release_version = push_event_details["release_version"]
release_tag = f"{rele... |
def conv_block(x, filters, strides=(1, 1)):
x = BatchNormalization()(x)
x = LeakyReLU(alpha=.1)(x)
x = Conv2D(filters, (3, 3), strides=strides, padding='same')(x)
return x
def res_block(x, filters, downsample=True, activation=False):
if downsample:
strides = (2, 2)
else:
strides ... | This code defines a Deep Residual U-Net model for image segmentation. It constructs an encoder with residual blocks, progressively reducing spatial dimensions while increasing feature depth, then a decoder with upsampling and skip connections to reconstruct segmented output. The model uses residual learning, dropout, a... | def create_model():
input_ = Input((400, 400, 3))
conv1 = Conv2D(64, (3, 3), padding='same')(input_)
encoder1 = conv_block(conv1, 64)
encoder1 = Add() ([encoder1, conv1]) #400, 400, 64
encoder2 = res_block(encoder1, 128) #200, 200, 128
encoder3 = res_block(encoder2, 256) #100, 100, 256
enco... |
def parser():
parser = argparse.ArgumentParser(description='Process the inputs..')
# Arguments for whether the user wants to send or receive
# Defaults as sender
parser.add_argument('--sender', dest='action', action='store_true')
parser.add_argument('--receiver', dest='action', action='store_false'... | The main task of the code is to parse command-line arguments, generate a modified data array, and conditionally execute either a sender or receiver functionality based on the parsed arguments. If the action flag is set, it iterates through the array, creating and sending TCP packets using the sender module. Otherwise, ... | def main(argv):
args = parser()
fudgedLineArray = createFudgedLineArray()
# Dependent on the --sender or --receiver arguements
if args.action == True:
for i in range(len(fudgedLineArray)):
sender.Sender(createTCPPacket(args, fudgedLineArray[i]))
else:
receiver.Receiver() |
def init_logging() -> None:
logging.basicConfig(
format="%(asctime)s\t%(levelname)s\t%(message)s",
level=logging.DEBUG,
)
def get_pool(db_url: str) -> sqlite3.Connection:
conn = sqlite3.connect(db_url)
# TODO: log statements?
conn.execute(open("./sql/001_init.sql", "r").read())
... | The main task of the code is to continuously pull data from a specified URL using a client authenticated with provided credentials, storing results in a SQLite database. It runs indefinitely with a 1-minute interval between pulls, handling keyboard interrupts to gracefully exit. The code validates command-line argument... | def main(args: List[str]) -> int:
init_logging()
if len(args) != 4:
print(f"usage: {args[0]} <user> <pass> <url_like>")
return 1
username = args[1]
password = args[2]
url_like = args[3]
client = Client(username, password)
db_url = "./py_web.db"
pool = get_pool(db_url)... |
def send(sock, message):
try:
sock.send(str(len(message)).encode())
response = sock.recv(5).decode()
if response == "ready":
sock.send(message.encode())
return "success".split("\r\n")
else:
raise Exception(failure + "Expected 'ready', got \'" + response + "\'")
except Exception as e:
return ("error... | This code connects to a server, sends a command to switch to a specified board, validates the server's response, updates the global `boardName` variable if successful, and handles errors like invalid board names or unknown responses. It ensures the socket is closed properly and prints status messages for user feedback. | def board(boardNameParam):
global boardName
s = socket.socket()
s.connect((host, port))
try:
send(s, "board\r\n" + cid + "\r\n" + boardNameParam)
response = recv(s)
if response[0] == "204 No Content": print(success + "You are now on '" + boardNameParam + "'")
elif response[0] == "404 Not Found": raise Excep... |
def send(sock, message):
try:
sock.send(str(len(message)).encode())
response = sock.recv(5).decode()
if response == "ready":
sock.send(message.encode())
return "success".split("\r\n")
else:
raise Exception(failure + "Expected 'ready', got \'" + response + "\'")
except Exception as e:
return ("error... | The code connects to a server, sends a thread request with a specified path, and handles responses. If successful, it updates the current thread name and refreshes the interface. Errors like non-existent threads or unknown responses trigger failure messages. The function manages socket connections and exception handlin... | def thread(threadPath):
global threadName
s = socket.socket()
s.connect((host, port))
try:
send(s, "thread\r\n" + cid + "\r\n" + threadPath)
response = recv(s)
if response[0] == "204 No Content":
print(success + "You are now on '" + threadPath + "'.")
threadName = "/".join(threadPath.split("/")[1:])
... |
def send(sock, message):
try:
sock.send(str(len(message)).encode())
response = sock.recv(5).decode()
if response == "ready":
sock.send(message.encode())
return "success".split("\r\n")
else:
raise Exception(failure + "Expected 'ready', got \'" + response + "\'")
except Exception as e:
return ("error... | This function sends a reply to a thread via a socket connection. It constructs a reply message with the provided title and content, sends it to a server, and processes the response. If successful (201 Created), it prints a confirmation and the post link. If the thread is not found (404), it raises an error. Other error... | def reply(title, content):
s = socket.socket()
s.connect((host, port))
try:
send(s, "reply\r\n" + cid + "\r\n" + title + "\r\n" + content)
response = recv(s)
if response[0] == "201 Created":
print(success + "Successfully replied to thread. Your post is at '" + "\r\n".join(response[1:]) + "'.")
input(prom... |
def send(sock, message):
try:
sock.send(str(len(message)).encode())
response = sock.recv(5).decode()
if response == "ready":
sock.send(message.encode())
return "success".split("\r\n")
else:
raise Exception(failure + "Expected 'ready', got \'" + response + "\'")
except Exception as e:
return ("error... | This function creates a new thread by connecting to a server via socket, sending a formatted 'new' command with thread details, and handling responses. It checks for success (201) or errors (409, 404), prints status messages, and closes the connection. | def new(threadName, content):
s = socket.socket()
s.connect((host, port))
try:
send(s, "new\r\n" + cid + "\r\n" + threadName + "\r\n" + content)
response = recv(s)
threadPath = "\r\n".join(response[1:])
if response[0] == "201 Created":
print(success + "New thread successfully created at " + threadPath + "... |
def buy_price():
buy = {}
try :
try :
f = open("../Buy_prices.txt", "r", encoding="utf8")
except :
f = open("../Buy_prices.txt", "r", encoding="utf8")
lines = f.readlines()
for line in lines:
price = round(float(line.split('Price:"')[1].split('"')[0]),2)
name = line.split('Name:"')[1].split('"')[0... | The main task of the code is to continuously monitor and update item prices in a market based on real-time listings, buy prices, and profit thresholds. It fetches listings and prices, calculates target prices using profit margins and fees, and updates item prices if they meet specified profit conditions. The code also ... | def main_update():
buy = buy_price()
begin = time.time()
begin2 = time.time()
refresh_online()
while 1:
listings = get_listings()
if listings == None:
time.sleep(delay)
continue
time.sleep(delay)
all_p = all_prices()
time.sleep(delay)
for my in listings:
name = my['market_hash_name']
lowest... |
def buy_price():
buy = {}
try :
f = open("../Buy_prices.txt", "r", encoding="utf8")
lines = f.readlines()
for line in lines:
price = float(line.split('Price:"')[1].split('"')[0])
name = line.split('Name:"')[1].split('"')[0]
buy[name] = price
return buy
except :
return buy
def get_listings():
url ... | The main task of the code is to calculate and print actual profit based on buy prices and listings, first with and then without a specified condition (e.g., fees or adjustments). It retrieves initial buy prices, waits for a delay, fetches market listings, updates buy prices using listing data, and outputs profit calcul... | def main():
buy = buy_price()
time.sleep(delay)
listings = get_listings()
buy = fill_buy_prices(buy, listings)
print_actual_profit(listings, buy, True)
print_actual_profit(listings, buy, False) |
def my_item_price():
try :
req = requests.get(my_items_url, headers = shadowpay_headers)
except :
print("Shadow get my items failed")
if req.status_code != 200:
print("Shadow get my items : ", req.status_code)
data = req.json()
index = 0
my_items = []
items_id = []
for item in data["items"]:
if item["it... | The code updates item prices on the Shadowpay platform by comparing current market prices with the cost price, ensuring a minimum profit margin. It retrieves item listings, calculates potential profits, and adjusts prices dynamically to maintain profitability, using Steam prices as a fallback when market prices don't m... | def main_update():
global update_url, my_items_url, shadowpay_headers
update_url = "https://shadowpay.com/api/market/save_item_price"
my_items_url = "https://shadowpay.com/api/market/list_items"
shadowpay_headers = {'Cookie':cookie}
my_prices = my_item_price()
buy = buy_price()
withdrawn_items = fill_buy_prices(... |
def load_all(self):
pygame.init()
self.cursor = pygame.cursors.compile(cursor.cursor_data)
pygame.mouse.set_cursor((32,32), (1,1), *self.cursor)
info = pygame.display.Info()
self.ScreenWidth = info.current_w
self.ScreenHeight = info.current_h
self.screen = pygame.... | The main task of the code is to manage a game loop that handles events (e.g., quitting, ESC key), updates game state (e.g., new_game, cell_count), renders the background and UI elements, displays congratulatory messages upon completion, and toggles flashing text. It integrates Pygame for rendering and Gtk for event pro... | def mainloop(self):
self.load_all()
self.makeMenu()
self.running = True
count = 0
while self.running:
self.clock.tick(self.fps)
self.screen.blit(self.background, (0, 0))
while Gtk.events_pending():
Gtk.main_iteration()
... |
def normalizeAndReshape(data):
data = data.astype("float32") / 255
data = data.reshape(len(data), 28, 28, 1)
return data
def toCategorical(data):
return keras.utils.to_categorical(data)
def findBestRegularizer(best_hyperparameters, x_train_dist, x_train_clean, x_val_dist, x_val_clean):
regularizers ... | The code loads and preprocesses distorted and clean datasets, splits them into training/validation sets, trains an autoencoder to reconstruct clean data from distorted inputs using optimal hyperparameters, evaluates the model's performance on test data, and generates reconstructed images for analysis. | def main():
# disturbed data set
x_train_dist_full = np.load('data/distorted/X_kannada_MNIST_train_multipl_distorted.npy')
x_test_dist = np.load('data/distorted/X_kannada_MNIST_test_multipl_distorted.npy')
x_train_dist_full = normalizeAndReshape(x_train_dist_full)
x_test_dist = normalizeAndReshape(x... |
def normal_vector_stuff():
p0 = np.array([0.0, 0.0, 0.0])
p1 = np.array([1.0, 1.0, 1.0])
pt = np.array([0.5, 0.5, 0.49])
# p0 = np.array([0.0, 0.0])
# p1 = np.array([1.0, 1.0])
# pt = np.array([0.79, 0.8])
v = p1 - p0
w = pt - p0
t = np.dot(w, v) / np.dot(v, v)
d = w - (t * ... | The main task of the code is to process hydrological discharge data by transforming it into probability ranks, normalizing the data, and comparing the statistical properties and visualizations (using Mayavi) of observed vs. normalized data in a unit cube. This involves reading, filtering, ranking, and analyzing time-se... | def main():
main_dir = Path(r'P:\Synchronize\IWS\Testings\Copulas_practice\asymms_nd')
os.chdir(main_dir)
normal_vector_stuff()
in_data_file = Path(
r'neckar_norm_cop_infill_discharge_1961_2015_20190118.csv')
in_df = pd.read_csv(in_data_file, sep=';', index_col=0)
in_df = in_df[['42... |
def _castle(self, move):
col = move.cell.col
king_move = Move(move.piece, move.cell, None)
self.apply_move(king_move, True)
if col == 6:
for rook in self.pieces[move.piece.color]['r']:
if rook.col == 7:
rook_move = Move(rook, Cell(move.cell... | This method applies special moves in a game, checking if the move is a castle ('c') and executing the castle method, otherwise promoting the piece and updating available moves. | def _apply_special_move(self, move):
if move.special == 'c':
self._castle(move)
else:
self._promote(move)
self._update_moves() |
def get_strength_img(img, sigma):
"""Operate CNNNY_ENHACER algorithm
Args:
img: image to get edge
sigma: std for gaussian filter
Returns:
mag: strength image
"""
img_after_gau = ndimage.gaussian_filter(img.astype(float), sigma)
img_of_grad_x, img_of_grad_y = np.gradien... | The main task of the code is to perform image segmentation using active contours (snakes) via a greedy algorithm. It initializes contours, computes gradient magnitude for edge detection, and evolves the contours iteratively by optimizing parameters (alpha, beta, gamma) to fit object boundaries in the input image, guide... | def evolve_active_contours(th1, th2, th3, size_of_neigh, img, sigma, alpha, beta, gamma):
image = plt.imread(img)
mag = get_strength_img(image, sigma)
# io.imshow(mag, cmap='gray')
# plt.show()
get_points(image)
interpolate()
show_contours(image)
greedy_evolve(th1, th2, th3, size_of_neig... |
def get_strength_img(img, sigma):
"""Operate CNNNY_ENHACER algorithm
Args:
img: image to get edge
sigma: std for gaussian filter
Returns:
mag: strength image
"""
img_after_gau = ndimage.gaussian_filter(img.astype(float), sigma)
img_of_grad_x, img_of_grad_y = np.gradien... | The function evolves active contours on an image using three different sigma values (sigma1, sigma2, sigma3) to generate magnitude images. It applies the greedy_evolve algorithm sequentially with each sigma, updating contours and displaying results at each stage. The process involves initializing points, interpolating,... | def evolve_active_contours_sigma(th1, th2, th3, size_of_neigh, img, sigma1, sigma2, sigma3):
image = plt.imread(img)
mag1 = get_strength_img(image, sigma1)
mag2 = get_strength_img(image, sigma2)
mag3 = get_strength_img(image, sigma3)
get_points(image)
interpolate()
show_contours(image)
g... |
def get_strength_img(img, sigma):
"""Operate CNNNY_ENHACER algorithm
Args:
img: image to get edge
sigma: std for gaussian filter
Returns:
mag: strength image
"""
img_after_gau = ndimage.gaussian_filter(img.astype(float), sigma)
img_of_grad_x, img_of_grad_y = np.gradien... | The code evolves active contours on an image using a greedy algorithm with varying neighborhood sizes. It reads the image, computes a strength map, initializes contours, and iteratively refines them via three greedy_evolve calls with distinct neighbor sizes (size_of_neigh1, size_of_neigh2, size_of_neigh3), resetting co... | def evolve_active_contours_nei(th1, th2, th3, size_of_neigh1, size_of_neigh2, size_of_neigh3, img, sigma):
image = plt.imread(img)
mag = get_strength_img(image, sigma)
get_points(image)
interpolate()
show_contours(image)
global coords
global corners
temp = np.zeros_like(coords)
temp... |
def get_strength_img(img, sigma):
"""Operate CNNNY_ENHACER algorithm
Args:
img: image to get edge
sigma: std for gaussian filter
Returns:
mag: strength image
"""
img_after_gau = ndimage.gaussian_filter(img.astype(float), sigma)
img_of_grad_x, img_of_grad_y = np.gradien... | This function evolves active contours on an image using a greedy algorithm with three iterations, each adjusting contour parameters (alpha1, alpha2, alpha3) to refine the shape. It reads an image, computes edge strength, initializes points, and iteratively updates contours while displaying intermediate results. | def evolve_active_contours_alpha(th1, th2, th3, size_of_neigh, img, sigma, alpha1, alpha2, alpha3):
image = plt.imread(img)
mag = get_strength_img(image, sigma)
get_points(image)
interpolate()
show_contours(image)
global coords
global corners
temp = np.zeros_like(coords)
temp = np.c... |
def get_strength_img(img, sigma):
"""Operate CNNNY_ENHACER algorithm
Args:
img: image to get edge
sigma: std for gaussian filter
Returns:
mag: strength image
"""
img_after_gau = ndimage.gaussian_filter(img.astype(float), sigma)
img_of_grad_x, img_of_grad_y = np.gradien... | The function evolves active contours on an image using a greedy algorithm with varying beta parameters. It reads the input image, computes edge strength, initializes contour points, and iteratively updates the contours three times with distinct beta values (beta1, beta2, beta3) to adjust contour behavior. Each evolutio... | def evolve_active_contours_beta(th1, th2, th3, size_of_neigh, img, sigma, beta1, beta2, beta3):
image = plt.imread(img)
mag = get_strength_img(image, sigma)
get_points(image)
interpolate()
show_contours(image)
global coords
global corners
temp = np.zeros_like(coords)
temp = np.copy(... |
def get_strength_img(img, sigma):
"""Operate CNNNY_ENHACER algorithm
Args:
img: image to get edge
sigma: std for gaussian filter
Returns:
mag: strength image
"""
img_after_gau = ndimage.gaussian_filter(img.astype(float), sigma)
img_of_grad_x, img_of_grad_y = np.gradien... | The function `evolve_active_contours_gamma` evolves active contours on an image using a greedy algorithm with three distinct gamma parameters. It reads an image, computes edge strength via `get_strength_img`, initializes contours, and iteratively updates them using `greedy_evolve` with thresholds `th1`, `th2`, `th3`, a... | def evolve_active_contours_gamma(th1, th2, th3, size_of_neigh, img, sigma, gamma1, gamma2, gamma3):
image = plt.imread(img)
mag = get_strength_img(image, sigma)
get_points(image)
interpolate()
show_contours(image)
global coords
global corners
temp = np.zeros_like(coords)
temp = np.c... |
def get_strength_img(img, sigma):
"""Operate CNNNY_ENHACER algorithm
Args:
img: image to get edge
sigma: std for gaussian filter
Returns:
mag: strength image
"""
img_after_gau = ndimage.gaussian_filter(img.astype(float), sigma)
img_of_grad_x, img_of_grad_y = np.gradien... | The code evolves active contours on an image using three distinct threshold values (th31, th32, th33) to iteratively adjust contours based on edge strength maps. It reads an image, computes gradient magnitude with Gaussian blur, initializes contours, and applies a greedy evolution algorithm three times with different t... | def evolve_active_contours_th3(th1, th2, th31, th32, th33, size_of_neigh, img, sigma):
image = plt.imread(img)
mag = get_strength_img(image, sigma)
get_points(image)
interpolate()
show_contours(image)
global coords
global corners
temp = np.zeros_like(coords)
temp = np.copy(coords)
... |
def get_points(image):
"""get initial points
Arguments:
image {[image array]} -- input image
"""
fig = plt.figure('ACTIVE CONTOURS')
io.imshow(image)
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
fig.canvas.mpl_disconnect(cid)
def interpolate():
... | This function processes a sequence of images to evolve active contours using a greedy algorithm. It iterates through frames, computes edge strength maps with a Gaussian filter (sigma), and applies threshold-based contour evolution (th1, th2, th3) with a specified neighborhood size. For each frame, it initializes contou... | def evolve_active_contours_sequence(th1, th2, th3, size_of_neigh, img, sigma):
for i in range(0, 180, 15):
image = plt.imread(img + str(i).zfill(3) + ".jpg")
print(img + str(i).zfill(3) + ".jpg")
if (i == 0):
get_points(image)
interpolate()
show_contours(i... |
def canny_enhancer(img, sigma):
"""Operate CNNNY_ENHACER algorithm
Args:
img: image to get edge
sigma: std for gaussian filter
Returns:
Es: strength image
Eo: orientation image
"""
img_after_gau = gaussian_filter(img, sigma)
img_of_grad_x = gradient_image(img_af... | The function performs Canny edge detection on an input image by applying Gaussian filtering, enhancing edges, suppressing non-maximal pixels, and applying hysteresis thresholding to identify edge chains. It returns intermediate results (enhanced edges, non-maximal suppression output) and the final edge-detected image. | def canny_edge_detection(img, sigma, thresL, thresH):
"""Operate canny edge detection
1) CANNY_ENHANCER
2) NONMAX_SUPPRESSION
3) HYSTERESIS_THRESH
Args:
img: input image
sigma: standard deviation for gaussian filter
thresL, thresH: two thresholds
Returns:
image... |
def _prompt_workout_selection() -> str:
print("[bold cyan]Choose a workout to start from this list...[/bold cyan]")
workouts = [f for f in os.listdir(SAMPLE_WORKOUT_DIR) if f.endswith(".csv")]
for i, w in enumerate(workouts):
print(f"[cyan]{i+1}. [/cyan][bold red]{w}[/bold red]")
order = IntPro... | The main task of the code is to execute a workout countdown program by prompting for workout selection if unspecified, displaying pre-workout information, parsing the workout structure into sets, and rendering the workout plan for user execution. | def main(workout):
"""Small program to play workout set countdown on terminal"""
if workout is None:
workout = _prompt_workout_selection()
_display_pre_workout(workout)
workout_sets = _parse_workout(workout)
_display_workout(workout_sets) |
def import_file_txt(dictionary: dict, filename: str):
log.info(f"Opening TXT file '{filename}'")
with open(filename, 'r') as f:
for line in f.readlines():
# Make sure the values provided are valid, if not replace with default values.
if not is_valid_quote(line):
c... | The function `import_new_sayings` aggregates quotes from multiple file formats (TXT, CSV, XML, JSON) in a specified directory into a central dictionary. It logs progress, processes each file based on its extension by calling format-specific import functions, and consolidates all imported quotes into `new_quote_dict` fo... | def import_new_sayings():
print("Importing new quotes from files")
log.info("Importing new quotes from files")
new_quote_dict = dict()
for filename in glob.glob(os.path.join(IMPORT_PATH, '*')):
log.info(f"Attempting to import from file \"{filename}\"")
# Import quotes from a txt file int... |
def wish():
hour = int(datetime.datetime.now().hour)
if hour >= 0 and hour<12:
speak("good morning sir i am jarvis")
elif hour>=12 and hour<18:
speak("good afternoon sir i am jarvis")
else:
speak("good evening sir i am jarvis")
def STT(self):
# R = sr.Recognizer()
... | This code implements a voice-controlled AI assistant (JARVIS) that processes user commands via speech recognition (STT). It executes tasks like shutting down the PC, sending emails, searching Wikipedia, controlling volume/brightness, opening websites, playing music, and managing reminders. The assistant interacts with ... | def JARVIS(self):
wish()
while True:
self.query = self.STT()
if 'good bye' in self.query:
sys.exit()
elif "shutdown" in self.query:
speak("Do you really want to shut down your pc Say Yes or else No")
print("... |
def _enumerate(query):
"""Enumerate VDS service queries."""
while True:
unk, avail = query.Next(1)
if not avail:
return
yield unk
def _get_volume_index(self, volume_name):
m = re.match(r"[^0-9]+([0-9]+)$", volume_name)
if m:
return int(m.group(1))
... | This function extends specified volumes within a disk pack by checking if their indexes are in the provided list, then calling the _extend_volume method for eligible volumes, while ensuring proper memory management for COM interface properties. | def _extend_volumes(self, pack, volume_indexes):
for unk in _enumerate(pack.QueryVolumes()):
volume = unk.QueryInterface(vds.IVdsVolume)
volume_prop = volume.GetProperties()
try:
extend_volume = True
if volume_indexes:
volum... |
def _get_vds_service(self):
if not self._vds_service:
self._vds_service = vds.load_vds_service()
return self._vds_service
def _query_providers(self, svc):
return [unk.QueryInterface(vds.IVdsSwProvider)
for unk in _enumerate(
svc.QueryProviders(vds.... | The main task of the code is to extend specified volumes by interacting with service providers. It retrieves providers, queries their associated packs, and applies volume extensions to each pack using the provided volume indexes. The function orchestrates volume expansion across multiple providers and their resources i... | def extend_volumes(self, volume_indexes=None):
svc = self._get_vds_service()
providers = self._query_providers(svc)
for provider in providers:
packs = self._query_packs(provider)
for pack in packs:
self._extend_volumes(pack, volume_indexes) |
def IsSkipPath(Path):
'''function to determine what path should skip to check'''
if not '\\' in Path:
return False;
Sep = Path.partition ('\\')
SkipPath = Sep [2]
if SkipPath == 'Build' or SkipPath == 'Conf' or SkipPath == 'InsydeModulePkg\\H2ODebug':
print ("The skip path is " + Pat... | This function recursively copies files and directories from a source path to a destination path, preserving the directory structure. It skips specified paths using `IsSkipPath` and processes each file with `CreateFile`, ensuring hierarchical replication of the source content into the destination directory. | def CreateFiles (SrcFilePath, DestFilePath):
SrcList = os.listdir (SrcFilePath)
for SrcElem in SrcList:
if os.path.isdir (SrcFilePath + '\\' + SrcElem):
if not IsSkipPath (SrcFilePath + '\\' + SrcElem):
CreateFiles (SrcFilePath + '\\' + SrcElem, DestFilePath + '\\' + SrcElem)... |
def IsSkipPath(Path):
'''function to determine what path should skip to check'''
if not '\\' in Path:
return False;
Sep = Path.partition ('\\')
SkipPath = Sep [2]
if SkipPath == 'Build' or SkipPath == 'Conf' or SkipPath == 'InsydeModulePkg\\H2ODebug':
print ("The skip path is " + Pat... | This function compares files in two directories (OrgFolder and NewFolder), recursively identifying and creating copies of files that exist in one directory but not the other. It handles both files and subdirectories, skipping specified paths, and writes results to destination folders (DestOrgFolder and DestNewFolder) t... | def CreateDifferentFiles (OrgFolder, NewFolder, DestOrgFolder, DestNewFolder):
OrgList = os.listdir (OrgFolder)
NewList = os.listdir (NewFolder)
#
#create different files and origninal file exists but new file doesn't exist"""
#
for OrgElem in OrgList:
if OrgElem in NewList:
... |
def root_node():
global rootNode
rootNode = Node(None, curArray,prevArray,identity,0,turn,None)
def do_move(coord):
if coord == "PASS":
outFile = open("output.txt", "w")
outFile.write("PASS")
outFile.close()
else:
outFile = open("output.txt", "w")
outFile.write(s... | The function `execute_move` evaluates a game tree to determine the optimal move by identifying the maximum score among leaf nodes, randomly selecting a move from those with the highest score, and executing it. It constructs the tree with depth 3 or 4 based on valid move count, prioritizing depth 4 when fewer than 8 mov... | def execute_move():
root_node()
if rootNode.turn == 1:
do_move([2,2])
return
if len(funcs.find_valid_moves(rootNode.prevboard,rootNode.board,rootNode.iden)) < 8:
create_tree(4)
else:
create_tree(3)
#list of nodes that are currently the maximum score
maxList = ... |
def place_piece(board,loc,iden):
boardCopy = np.copy(board)
boardCopy[loc[0]][loc[1]] = iden
return boardCopy
def remove_dead(board,iden):
boardCopy = np.copy(board)
deadGroup = identify_dead(board,iden)
for item in deadGroup:
boardCopy[item[0]][item[1]] = 0
return boardCopy
def oppo... | The function `make_move` simulates a game move by first placing a player's piece on the board at the specified location, then removing any dead pieces belonging to the opponent. It returns the updated board state after these operations. | def make_move(board,loc,iden):
boardCopy= place_piece(board,loc,iden)
boardCopy = remove_dead(boardCopy,opponent(iden))
return boardCopy |
def find_capture_moves(board,iden):
captureMoves = []
groupList = get_groups(board,opponent(iden))
#find lists that only have one member in the freedom group
for index in groupList:
if len(index[1]) == 1 and index[1][0] not in captureMoves:
captureMoves.append(index[1][0])
retu... | This function identifies valid moves in a 5x5 board game by checking for captures, suicide moves, and ko situations. It skips invalid positions, ensuring moves don't result in immediate capture, self-destruction, or ko (repetition). Valid moves are collected and returned as a list of coordinates. | def find_valid_moves(prevboard,board,iden):
validMoves = []
captureMoves = find_capture_moves(board,iden)
for i in range (0,5):
for j in range(0,5):
if board[i][j] != 0:
continue
if test_suicide_move(board,iden,[i,j]) == 1 and [i,j] not in captureMoves:
... |
def roll_north(array):
return transpose(roll_west(transpose(array)))
def roll_west(array):
mirror = [row[::-1] for row in array]
roll = roll_east(mirror)
return [row[::-1] for row in roll]
def roll_south(array):
return transpose(roll_east(transpose(array)))
def roll_east(array):
return [roll_row... | The main task of the code is to perform a sequence of four directional rotations on a 2D array: first rolling it north, then west, followed by south, and finally east, returning the transformed array after all operations. | def spin_cycle(array):
arr = roll_north(array)
arr = roll_west(arr)
arr = roll_south(arr)
return roll_east(arr) |
def getProductMilestones(element, array):
for index, item in enumerate(array):
if "<b>" in item["milestone"] or "<strong>" in item["milestone"] or "<p>" in item["milestone"]:
if "Pre-submission meeting" in item["milestone"] or "Submission filed" in item["milestone"]:
date = getMi... | The main task of the code is to generate an Excel row by extracting and processing data from an item, including constructing URLs for product links, handling API responses to retrieve milestone data, cleaning HTML tags from text, and structuring the output with hyperlinks and milestone information. It dynamically build... | def getExcelRow_HCSBD(item):
table_row = [item[""+element] for element in API_REST_KEYS_LIST]
url_product = ''
#item['link_id'] = 'SBD00395'
# product url
if item['is_md']:
if item['template'] == 1:
url_product = BASE_URL_MEDICAL_1 + item['link_id']
elif item['template'... |
def test_setup(self)-> None:
self.report_data['test_setup'] = {
'step1': False,
'step2': False,
}
#######################################################################################################################
# Connecting COM port of Numato USB Relaycard... | The main task of the code is to execute a test workflow: initialize test setup, run test cases, perform teardown, record end time, and generate an HTML report. It handles exceptions by ensuring teardown occurs even if errors arise, then prints the error message. | def main(self):
try:
print('\n\nStep-1: Test Setup Initialization')
self.test_setup()
# Execution of Testcases
print('\n\nStep-2: Test Case Run')
self.testcases()
print("\n\nStep-3: Testcase Setup TearDown")
self.test_setup_te... |
def writeln(self, line_str=""):
self.write(line_str + "\n")
def add_tab(self):
self.prefix += generate_ast.TAB
def define_type(self, class_name, field_list: str):
self.write(class_name + "(" + field_list.strip() + ")")
self.writeln("{")
self.add_tab()
fields = field_list... | This code generates Java source files for an abstract syntax tree (AST) using the visitor pattern. It creates an abstract base class with subclasses defined from `sub_types`, each implementing the visitor pattern. The output includes a `Visitor` interface with methods for each subclass, enabling type-specific operation... | def define_types(self, output_dir, base_class_name, sub_types):
self.output_file = open(path.join(output_dir, base_class_name+'.java'), "w")
self.writeln("// this file is generated automatically by running src/toy/tool/generate_ast.py\n")
self.writeln("package toy.jlox;")
self.writeln(... |
def re_namespaces(root):
for k,v in root.nsmap.items():
if k == 'style':
namespaces['style'] = v
if k == 'core':
namespaces['core'] = v
if not k:
namespaces['prefix'] = v
def remove_link_from_excel(href):
link = href.attrib['formula']
if href.attrib.get('style-key') is not None and h... | This code parses an XML file, modifies specific elements' attributes (removing links and adjusting widths), and writes the updated structure back to the original file. The main task involves processing XML namespaces, extracting targeted elements, and applying transformations to attributes for data export or formatting... | def parse_xml(xmlFile):
tree = etree.parse(xmlFile+"layout.xml")
root = tree.getroot()
re_namespaces(root)
details = root.find(".//prefix:group",namespaces)
hrefs = details.findall(".//prefix:style-expression[@style-key='href-target']",namespaces)
attrb = details.findall(".//prefix:*[@core:field]",namespace... |
def extract(path,level):
with ZipFile(path,mode='r') as zipObj:
zipObj.extractall(path=args.path+level)
def parse_xml(xmlFile):
tree = etree.parse(xmlFile+"layout.xml")
root = tree.getroot()
re_namespaces(root)
details = root.find(".//prefix:group",namespaces)
hrefs = details.findall(".//prefix:style-ex... | The main task of the code is to process a specified file path by ensuring it ends with a slash, then extracting data from a `.prpt` file named "first_level.prpt", parsing XML files in the resulting directory, and compressing the contents of that directory. The workflow involves file path normalization, data extraction,... | def main():
if args.path[-1] != '/':
args.path = args.path+"/"
level = "first_level"
extract(args.path+level+".prpt",level)
parse_xml(args.path+level+"/")
compress(args.path+level+"/") |
def setWindow(self):
self.a = QtWidgets.QApplication(sys.argv)
self.w = QtWidgets.QMainWindow()
self.w.resize(640, 480)
self.w.setWindowTitle('datalogger-gui')
self.wid = QtWidgets.QWidget()
self.w.setCentralWidget(self.wid)
self.layout = QtWidgets.QGridLayout()
self.wid.setLayout(self.layout)
self.... | The code initializes a GUI application by setting up the window, connecting signals to slots for event handling, and starting the application. The constructor calls three methods: `setWindow()` to configure the window, `setSignalsSlots()` to establish event connections, and `runApp()` to launch the application. This st... | def __init__(self):
self.setWindow()
self.setSignalsSlots()
self.runApp() |
def readData():
global data
with open(params.clean_path + params.tweetFilename, "r", encoding='utf-8') as read_file:
data = json.load(read_file)
tweets = {}
cont = 0
for elem in data:
if elem["retweeted"] == True:
text = elem["RT_text"]
else:
text = el... | This code creates an inverted index for text data by calculating TF-IDF values. It processes tweets to extract tokens, computes term frequency (TF) and inverse document frequency (IDF) for each token, stores tweet IDs with TF scores, and saves the index. The function prepares data for efficient text retrieval and analy... | def createIndex(self):
tweets = readData()
N = len(tweets)
tokens = []
for tweet in tweets:
tokens += tweets[tweet]
tokensSet = set(tokens.copy())
tokensSet = sorted(tokensSet)
for token in tokensSet:
tweetIDs = []
for... |
def draw_tiles(self):
for i in range(SIZE_X):
for j in range(SIZE_Y):
self.draw_tile((i*TILE_WIDTH + + BOARD_OFFSET[0], (SIZE_Y-j-1)*TILE_HEIGHT + + BOARD_OFFSET[1]), self.bm.board[j][i], 0)
def draw_block(self, kind, pos, rot, proj):
for i in range(4): # X
for j ... | The main task of the code is to render the game board by drawing the background, tiles, active and projected blocks, next/held blocks, text elements, and high scores, updating the visual state of a Tetris-like game. | def draw_board(self):
self.win.blit(self.background, (0, 0))
self.draw_tiles()
self.draw_block(self.bm.block_kind, [self.bm.block_pos[0], self.bm.block_proj], self.bm.block_rot, 1)
self.draw_block(self.bm.block_kind, self.bm.block_pos, self.bm.block_rot, 0)
self.draw_block_extra(... |
def generate_board(self):
self.board = [[0 for j in range(SIZE_X)] for i in range(SIZE_Y)]
def load_blocks(self):
self.blocks = []
with open(BLOCKS_PATH, 'r') as csv_file:
blocks_file = list(csv.reader(csv_file))
for i in range(len(blocks_file)):
if i % 16 == 0:
... | The code initializes a game by setting up the game board, loading block data, offsets, and high scores, generating a block queue, and initializing the first block. It also resets score, lines cleared, T-spins, and level variables to their default values, preparing the game for play. | def __init__(self):
self.generate_board()
self.load_blocks()
self.load_offsets()
self.load_high_scores()
self.generate_queue()
self.generate_block()
self.holded = 0
self.score = 0
self.lines = 0
self.tspins = 0
self.level = 1 |
def glouton(coords_list):
height = 0
prev_l, prev_p = 0, 0
tower = []
for count, coords in enumerate(coords_list):
current_l, current_p, current_h = coords[1], coords[2], coords[0]
if (prev_l > current_l and prev_p > current_p) or (count == 0):
height += current_h
... | The code computes the maximum height of a tower by iteratively improving an initial greedy solution using a tabu search. It explores neighboring configurations, avoids revisiting states via a tabu list, and updates the tower if a higher configuration is found. After optimization, it sorts the blocks by area and formats... | def compute_highest_tower(coords_list):
total_height, tower = glouton(coords_list)
used_objects = []
tabou_list = []
iteration = 0
current_tower = tower
while iteration < 100:
neighbor_height, neighbor_tower, tabou_list = get_best_neighbor(current_tower, tabou_list, coords_list)
... |
def buildJobHistory(self):
""" Query coach.db to get a complete job history for self.name """
con = lite.connect('coach.db')
con.text_factory = str
with con:
con.row_factory = lite.Row
cur = con.cursor()
cur.execute("select distinct * from headCoaches ... | This code initializes an object representing a coach or professional, setting attributes like name, ID, job history (year-school-position mapping), mentors (defaultdict of lists), coworkers (uninitialized), and performance metrics. It builds job history, calculates a coaching score, initializes annual data, and prepare... | def __init__(self, name, id):
self.name = name
self.id = id
self.job_history = {}
self.mentors = defaultdict(list)
self.buildJobHistory() # job_history is a dictionary of form {int year: string school, string position)}
self.coachingScore = self.calcCoachingScore() #simpl... |
def deactivate(self):
self.parcel_api_client_instance.deactivate_command(self.cluster_name, self.name, self.version)
self.check_transition()
def undistribute(self):
self.parcel_api_client_instance.start_removal_of_distribution_command(
self.cluster_name, self.name, self.version)
... | The main task of the code is to transition the object to the "downloaded" stage by deactivating or undistributing if in previous stages, initiating a download command via the parcel API, checking state transitions, and marking the object as changed. | def downloaded(self):
if self.stage != "downloaded":
if self.stage == "activated":
self.deactivate()
if self.stage == "distributed":
self.undistribute()
self.parcel_api_client_instance.start_download_command(self.cluster_name, self.name, self.v... |
def deactivate(self):
self.parcel_api_client_instance.deactivate_command(self.cluster_name, self.name, self.version)
self.check_transition()
def undistribute(self):
self.parcel_api_client_instance.start_removal_of_distribution_command(
self.cluster_name, self.name, self.version)
... | This function transitions the object to the "available_remotely" stage by deactivating or undistributing if in "activated" or "distributed" states, removing the download command via the parcel API, checking the transition, and marking the state as changed. | def available_remotely(self):
if self.stage != "available_remotely":
if self.stage != "downloaded":
if self.stage == "activated":
self.deactivate()
if self.stage == "distributed":
self.undistribute()
self.parcel_api_... |
def downloaded(self):
if self.stage != "downloaded":
if self.stage == "activated":
self.deactivate()
if self.stage == "distributed":
self.undistribute()
self.parcel_api_client_instance.start_download_command(self.cluster_name, self.name, self.v... | The method ensures the component transitions to a "distributed" state by first handling prerequisite stages (downloading if remotely available, deactivating if activated), then initiating a distribution command via an API client, updating the state, and marking the component as changed. | def distributed(self):
if self.stage != "distributed":
if self.stage != "downloaded":
if self.stage == "available_remotely":
self.downloaded()
elif self.stage == "activated":
self.deactivate()
self.parcel_api_client_... |
def getMoveOrder(self, moves):
return sorted([m for m in moves], key = lambda m: self.heuristic[m])
def isTerminal(self, legalMoves, gameState):
#<---If you can win + 10000
if gameState.previousYX != None:
#<----If we are in a terminal state--->
self.changePlayer(gameState)
isWin, winType = g... | This function implements alpha-beta pruning with transposition table (TT) optimization for game state evaluation. It recursively explores game states, applying move ordering, hash-based memoization, and heuristic updates. The algorithm returns the best score for the current player, using TT to avoid redundant calculati... | def alphaBetaDL(self, alpha, beta, depth, state):
result = self.tt.lookup(self.hash)
if result != None:
return result
gameState = state.copyState()
d = self.__maxDepth - (self.__maxDepth - depth)
legalMoves = self.getMoveOrder(gameState.getValidMoves())
#<---Is terminal needs a state--->
if s... |
def getMoveOrder(self, moves):
return sorted([m for m in moves], key = lambda m: self.heuristic[m])
def updateHash(self, oldHash, XORin, XORout):
self.hash = oldHash ^ XORin ^XORout
def changePlayer(self, gameState):
gameState.setCurrentPlayer( 3 - gameState.getCurrentPlayer())
def alphaBetaDL(self, alpha, beta, ... | The code implements the alpha-beta pruning algorithm to determine the optimal move in a game state. It prioritizes the center move (3), evaluates legal moves recursively with depth limitation, and updates heuristic scores. By simulating each move, it calculates a value using the alpha-beta DL function, adjusts alpha/be... | def alphaBetaGetMove(self, alpha, beta, depth, gameState):
legalMoves = self.getMoveOrder(gameState.getValidMoves())
d = self.__maxDepth - (self.__maxDepth - depth)
bestMove = None
#<---we should try move 3 first (center is strongest)
if 3 in legalMoves:
legalMoves.remove(3)
legalMoves.append(3)
... |
def _get_eigvals(n, n_subdims, higher):
"""
Culculate eigvals for eigh
Parameters
----------
n: int
n_subdims: int, dimension of subspace
higher: boolean, if True, use higher `n_subdim` basis
Returns
-------
eigvals: tuple of 2 integers
"""
if n_subdims is None:
... | This function computes principal components (subspace bases) via PCA from input data matrix X. It returns a basis matrix V containing eigenvectors corresponding to top or bottom n_subdims eigenvalues (based on 'higher' parameter), optionally including eigenvalues w. The implementation uses either direct eigendecomposit... | def subspace_bases(X, n_subdims=None, higher=True, return_eigvals=False):
"""
Return subspace basis using PCA
Parameters
----------
X: array-like, shape (n_dimensions, n_vectors)
data matrix
n_subdims: integer
number of subspace dimension
higher: bool
if True, this f... |
def z(X, w, b, m):
return np.sqrt(2 / m) * np.cos((w @ X).T + b).T
def subspace_bases(X, n_subdims=None, higher=True, return_eigvals=False):
"""
Return subspace basis using PCA
Parameters
----------
X: array-like, shape (n_dimensions, n_vectors)
data matrix
n_subdims: integer
... | The code transforms input data `X` using Random Fourier Features (RFF) approximation to create a lower-dimensional representation (`newX`). It then applies PCA via `subspace_bases` to extract subspace bases from the transformed data. These bases are combined, and a final PCA (via `subspace_bases`) reduces dimensions fu... | def get_newX(X):
n_gds_dims = 11 #if you use small subspaces, take "11", if big subspaces, take "18"
n_subdims = 6
dic = None
dic = []
m = 100
n_approx = 1
sigma = 0.1
n_dims = X[0].shape[0]
if sigma is None:
sigma = np.sqrt(n_dims / 2)
w = []
b = []
fo... |
def find_config_data(func_name: str, config_file_name: str = "config.json")\
-> tuple[str, str, str] | str | tuple[str, str]:
"""Extracts the data pertaining to the main module from the
provided config file.
A try except is used to get the encoding style to be used, and to check if
a valid/pres... | The main task of the code is to render a webpage displaying COVID-19 data and news articles, handling user interactions like scheduling updates or removing articles, checking for expired updates, and scheduling repeat updates near midnight. It fetches data, processes user inputs, and returns a Flask-rendered template w... | def render_webpage():
"""Fills in (with covid data and news articles) and displays
the provided render template if the URL starts with a /.
Gets the data to display in the template via getter functions, calling
functions to display news articles (if there are any).
Uses the requests module (import... |
def collectData(x, verbose):
months = []
customers = _populate(x) #list of customers
#dictionary where the month is the key and the value is a tuple of dictionaries of DJ and ML quantities.
#create a from the least recent to the most recent date of customer purchases
counts = _createDict(datetime.s... | The code generates a visual representation of Duke Beverages' monthly sales data, comparing Duke Juice and Mango Lime sales across different graph types (bar, line, etc.). It processes input data, determines plot dimensions, labels axes, and plots the data with appropriate styles, annotations, and a legend, saving the ... | def graphCreation(x, graph = 'bar', w = None, h = None, verbose = False):
counts = collectData(x, verbose)
# CREATE GRAPH
months = list(counts.keys())
monthlyDJ = _retValues(counts.values(),'dj')
monthlyML = _retValues(counts.values(),'ml')
# SIZE OF GRAPH
nRecords = _numRecords(x)
... |
def _get_device(self):
device = STikTok.Device_Genrator()
STikTok.CaptchaSolver(
did=device["device_id"], iid=device["install_id"])
return device
def Print(text: str):
print(
f" {Fore.LIGHTBLUE_EX}->{Fore.LIGHTCYAN_EX} {text} {Fore.LIGHTBLUE_EX}<- {Fore.RESET}"... | The code initializes a class with variables to track progress (done, err), sleep intervals, and device information. It configures the console window size, sets a custom title, displays a colored banner, and prints a TikTok account creation message before invoking the main method to start the application's core function... | def __init__(self):
self.done = 0
self.err = 0
self.sleep = 300
self.run = True
self.device = self._get_device()
os.system("mode 70,10")
ctypes.windll.kernel32.SetConsoleTitleW("Made By D7 or @d7ld & F15")
print(f"{Fore.LIGHTBLUE_EX}{banner}")
Prin... |
def is_windows() -> bool:
return sys.platform.startswith('win')
def unpack_tool_to_software_dir(tool_package_folder: str, tool_package_glob_name: str,
tool_folder_glob_name=None) -> str:
if tool_folder_glob_name is None:
tool_folder_glob_name = tool_package_glob_name
... | The function `install_cmake` detects the operating system and unpacks the corresponding CMake package from the source directory into the software directory. It uses OS-specific patterns (`cmake*win64*`, `cmake*Linux*`, `cmake*Darwin*`) to select the correct package for Windows, Linux, or macOS, ensuring the appropriate... | def install_cmake():
if is_windows():
unpack_tool_to_software_dir(src_package_dir(), 'cmake*win64*')
elif is_linux():
unpack_tool_to_software_dir(src_package_dir(), 'cmake*Linux*')
else:
unpack_tool_to_software_dir(src_package_dir(), 'cmake*Darwin*') |
def is_windows() -> bool:
return sys.platform.startswith('win')
def unpack_file_to_folder(file: str, folder: str):
logger.info(f'unpacking {file}')
if file.lower().endswith('.zip'):
with zipfile.ZipFile(file, mode='r') as zf:
zf.extractall(path=folder)
elif file.lower().endswith('.ta... | The function `install_ninja` installs the `ninja` build tool by extracting OS-specific ZIP archives (Windows, Linux, or macOS) into a designated software directory. It removes any existing `ninja` binary before installation and sets execute permissions on Unix-like systems (Linux/macOS) to ensure the tool is runnable. | def install_ninja():
if is_windows():
unpack_file_to_folder(os.path.join(src_package_dir(), 'ninja-win.zip'), software_dir())
elif is_linux():
if os.path.exists(os.path.join(software_dir(), 'ninja')):
os.remove(os.path.join(software_dir(), 'ninja'))
unpack_file_to_folder(os.p... |
def is_windows() -> bool:
return sys.platform.startswith('win')
def unpack_tool_to_software_dir(tool_package_folder: str, tool_package_glob_name: str,
tool_folder_glob_name=None) -> str:
if tool_folder_glob_name is None:
tool_folder_glob_name = tool_package_glob_name
... | This function installs the FFmpeg tool by detecting the operating system and unpacking the appropriate package. On Windows and Linux, it extracts precompiled binaries, while on macOS, it also sets executable permissions for FFmpeg tools and creates symbolic links in /usr/local/bin to ensure command-line accessibility. | def install_ffmpeg():
if is_windows():
unpack_tool_to_software_dir(src_package_dir(), 'ffmpeg*win*')
elif is_linux():
unpack_tool_to_software_dir(src_package_dir(), 'ffmpeg*static.tar.xz')
else:
folder = unpack_tool_to_software_dir(src_package_dir(), 'ffmpeg*macos*')
os.chmod... |
def turtle_init(self, t=turtle):
t.hideturtle()
t.speed(0)
def draw_ui(self, t):
self.write_txt(-300, 250, "UWB Positon", "black", t, f=('Arial', 32, 'normal'))
self.fill_rect(-400, 200, 800, 40, "black", t)
self.write_txt(-50, 205, "WALL", "yellow", t, f=('Arial', 24, 'normal'))... | The main task of the code is to initialize and display a graphical user interface (GUI) using the turtle module. It sets up a turtle instance, initializes UI elements, draws anchors, starts a background thread to manage inactive tags, and enters the turtle's main event loop to keep the GUI window active and responsive. | def show(self):
self.showing = True
t_ui = turtle.Turtle()
self.turtle_init(t_ui)
self.draw_ui(t_ui)
self.draw_anchors()
thread = threading.Thread(target=self.remove_inactive_tags)
thread.start()
turtle.mainloop() |
def create_ES_classes(parameters):
"""
Creates the classes Fitness, Individual and Strategy, which are needed in a ES
:param parameters: parsed parameters
:return:
"""
# Created Fitness class with positive weights (maximization) or negative
# (minimization) according to the parsed paramet... | The main task of the code is to execute an Evolutionary Strategy (ES) algorithm by parsing parameters, initializing the ES framework, tracking population statistics (average, standard deviation, min/max fitness), maintaining the best individuals in a Hall of Fame, and running the ES algorithm. It returns convergence in... | def run_ES():
"""
Runs the programmed ES
:return: convergence info (converged to solution True/False, best individuals
fitness and number of evaluations of the fitness function) and logbook (class with
logs of the whole population on each generation)
"""
# Gets the parsed... |
def p_net(observed=None, n_z=None, beta=1.0, mcmc_iterator=0, log_Z=0.0, initial_z=None):
net = spt.BayesianNet(observed=observed)
# sample z ~ p(z)
normal = spt.Normal(mean=tf.zeros([1, config.z_dim]),
logstd=tf.zeros([1, config.z_dim]))
normal = normal.batch_ndims_to_value(1)
... | The code trains a variational autoencoder (VAE) with normalizing flows and GAN components on the Fashion MNIST dataset. It defines model architectures, computes losses (VAE, GAN, adversarial), optimizes parameters using Adam, and evaluates metrics like NLL, FID, and inception score. It also handles data preprocessing, ... | def main():
# parse the arguments
arg_parser = ArgumentParser()
spt.register_config_arguments(config, arg_parser, title='Model options')
spt.register_config_arguments(spt.settings, arg_parser, prefix='tfsnippet',
title='TFSnippet options')
arg_parser.parse_args(sys.... |
def Tbrightness(I_nu,nu):
# input I_nu in erg/s/cm2/sr/Hz
# input nu in Hz
if (I_nu < 0.):
Tb=1.
else:
h_P=const.h.cgs.value
k_B=const.k_B.cgs.value
c_light=const.c.cgs.value
Tb=h_P*nu/(k_B*np.log( 1. + (2. * h_P * nu**3 / (c_light**2 * I_nu))))
retu... | The code performs a fitting process on astronomical data cubes to determine physical parameters like temperature, velocity, and column density. It extracts data slices, calculates initial estimates (e.g., peak intensity, velocity), and uses a minimization algorithm (`Minuit`) to refine these parameters by minimizing a ... | def parspar(n):
#i = int(n/ndim)
#j = int(n%ndim)
j = n[0]
i = n[1]
T_inits=[]
vel_peaks=[]
I_peaks=[]
datas=[]
for iiso,acubo in enumerate(cubos):
data = acubo[:,j,i]
datas.append(data)
nus=nuss[iiso]
datamax = data.max()
n... |
def standardztn(points):
sum_p=np.array([0.0,0.0,0.0])
for point in points:
sum_p+=point.coordinates
norm_avg = sum_p/len(points)
norm_max = 0
for point in points:
point.coordinates -= norm_avg
norm_p = np.linalg.norm(point.coordinates)
if norm_p>norm_max:
norm_max = norm_p
for point in points:
poi... | The main task of the code is to perform k-means clustering on a dataset with varying numbers of clusters (k) and initialization methods. It iteratively tests multiple k values (from k_init to k_max + k_init) and four initialization types, computes clustering objective values, and selects the optimal cluster configurati... | def clustering_k(points,k_init,k_max,max_tries):
points, norm_avg, norm_max = standardztn(points)
ks=[]
clust_obj_values=[]
set_of_clusters=[]
init_type=[]
clust_obj = 10**6
selections = [1,2,3,4]
for selection in selections:
for itir in range(0,max_tries):
k = k_init
count=0
while count<k_max+k_... |
def __torpedo_creator(self):
"""Creates torpedoes accordingly to the maximum allowed quantity"""
if self.__screen.is_space_pressed() \
and len(self.__torpedos) < MAX_TORPEDO_ALLOWED:
x_torpedo, y_torpedo, x_speed, y_speed, orientation \
= self.__torpedo_init_d... | The main task of the code is to manage torpedo operations by orchestrating torpedo creation, operation control, interaction handling, and lifespan management through four internal methods, ensuring coordinated functionality within the system. | def __torpedo_manager(self):
"""This method manages all the operation with torpedoes"""
self.__torpedo_creator()
self.__torpedo_operator()
self.__torpedo_intersector()
self.__torpedo_life_span_manager() |
def __ship_manager(self):
"""This method manages all operation with ship """
self.__ship_handler()
self.__turn_left_right()
self.__ship_acceleration()
def __asteroid_manager(self):
"""This method manages the asteroid operations"""
self.__asteroid_operator()
self._... | The main task of the `_game_loop` method is to execute the core game mechanics by updating the ship, asteroids, and torpedoes via their respective managers, then checking for end-game conditions. It drives the game's real-time logic, ensuring movement, interactions, and termination criteria are processed in each iterat... | def _game_loop(self):
"""This method runs the game loop.
The most important method of the class"""
self.__ship_manager()
self.__asteroid_manager()
self.__torpedo_manager()
self.__end_game_manager() |
def callback_prio_set(bot, update, task):
chatID = update.callback_query.message.chat_id
if (task == 'change prio'):
change_prio(bot, update)
elif (task == 'accept prio'):
ask_start_chope(bot, update, True)
elif (task == 'help prio'):
bot.send_message(
chat_id=chatID,... | The code handles callback queries from a Telegram bot, updating user priorities in a database and adjusting message interfaces. It processes 'settings' callbacks to modify priority values, refresh displayed messages, and reconfigure inline buttons. For 'takepc' callbacks, it triggers a captcha request. The function edi... | def callback_handler(bot, update):
global mainBot
callbackData = update.callback_query.data
data = callbackData.split('|', 1)
if (data[0] == 'callback_prio_set'):
callback_prio_set(bot, update, data[1])
elif (data[0] == 'settings'):
username = update.callback_query.from_user.username... |
def set_input(self, batch):
opts = self.opts
# =================================================================================== #
# Load source images #
# =================================================================... | The code performs visualization during model testing by iterating through a dataloader, generating visual outputs from model predictions, converting tensors to images, adding text annotations, resizing, saving results to disk, and displaying them in real-time using OpenCV. It operates in evaluation mode without gradien... | def test(self):
opts = self.opts
self.model_umr.eval()
self.model.eval()
with torch.no_grad():
for i, batch in tqdm(enumerate(self.dataloader)):
self.set_input(batch)
self.iteration_num += 1
vis_dict = self.get_current_visuals()... |
def spawn_population(FLP):
"""Make an initial population with a given FLP object."""
data = FLP.get_data()
results = []
# Decide a random set of genes for each original chromosome
for i in range(ARGS.population_size):
facilities = []
for j in range(ARGS.facilities):
facilities.append(flp.Point(x=random.un... | This function runs a genetic algorithm (GA) on a Facility Layout Problem (FLP) object to optimize solutions over multiple generations. It initializes a population, iterates through generations, selects elites, generates new populations, and tracks the fittest chromosomes. The GA preserves elite solutions, evolves the p... | def GA(FLP):
"""Run the genetic algorithm on an FLP object."""
# Spawn the original population
firstborn = spawn_population(FLP)
population = firstborn
results = (ARGS.generations + 1) * [None]
# Record original population data
chromosome = best_chromosome(rank_routes(firstborn, FLP))
results[0] = (firstbor... |
def arg_value(arg):
"""Return a string indicating an arg value"""
prefix = "is "
if isinstance(arg, bool):
return prefix + ("enabled" if arg else "disabled")
return prefix + str(arg)
def input_error(message: str) -> None:
"""Send an error message to the user with usage help."""
global cli
cli.print_usage(sys... | The code runs a genetic algorithm to solve the Facility Location Problem (FLP), loading input data, executing the algorithm, calculating performance metrics (distance reduction), and visualizing results including facility placements and improvement curves. It tracks execution times for each major step and outputs stati... | def main():
"""Main program runnable."""
# Start the program timer
timer = flp.Timings()
timer.add("Start")
# Prepare the data
print("Number of facilities %s" % arg_value(ARGS.facilities))
print("Population size %s" % arg_value(ARGS.population_size))
print("Number of elites %s" % arg_value(ARGS.elites))
prin... |
def extract_spans_extraction(task, seq, io_format):
if task == "uabsa":
if io_format == "extraction":
return extract_uabsa_from_extration(seq)
elif io_format == "extraction-universal":
return extract_uabsa_from_extraction_universal(seq, io_format)
else:
ra... | This function computes evaluation metrics (F1 scores) for tasks involving span extraction by comparing predicted and gold sequences. It extracts spans from both, calculates raw and fixed (post-edit) scores, and returns results along with labels and predictions. | def compute_scores(pred_seqs, gold_seqs, sents, paradigm, task, verbose=False):
"""
compute metrics for multiple tasks
"""
assert len(pred_seqs) == len(gold_seqs)
num_samples = len(gold_seqs)
all_labels, all_predictions = [], []
for i in range(num_samples):
if "extraction" in parad... |
def decode_header(message):
header_format = struct.Struct("!6H")
id, fields, qdcount, ancount, nscount, arcount = header_format.unpack_from(message)
rcode = fields & 0b1111
z = (fields >> 4) & 0b111
ra = (fields >> 7) & 1
rd = (fields >> 8) & 1
tc = (fields >> 9) & 1
aa = (fields >> 10)... | The main task of the code is to parse a DNS message into its structured components by decoding the header, question, answer, authority, and additional sections using helper functions, then compiling them into a dictionary for return. | def decode_dns_message(message):
header, offset = decode_header(message)
questions, offset = decode_question(message, offset, header['qdcount'])
answers, offset = decode_answer_section(message, offset, header['ancount'])
authority, offset = decode_answer_section(message, offset, header['nscount'])
a... |
def decode_dns_message(message):
header, offset = decode_header(message)
questions, offset = decode_question(message, offset, header['qdcount'])
answers, offset = decode_answer_section(message, offset, header['ancount'])
authority, offset = decode_answer_section(message, offset, header['nscount'])
a... | The code decodes a DNS message and prints its structured components (header, question, answer, authority, additional) in a formatted table with aligned columns, line wrapping, and borders. It processes each section, formats fields, calculates maximum line length for alignment, and outputs the result in a readable, stru... | def print_dns_message(message):
result = decode_dns_message(message)
print_result = []
h = result['header']
print_result.append([
'Header',
'------',
'ID=%s' % result['header']['id'],
'QR=%s OPCODE=%s AA=%s TC=%s RD=%s RA=%s Z=%s RCODE=%s' % (h['qr'], h['opcode'], h['aa'... |
def compute_all_B222(triangles):
return compute_all(triangles, B222output, B222jmat)
def compute_all_B3211(triangles):
return compute_all(triangles, B3211output, B3211jmat)
def compute_all_B3212(triangles):
return compute_all(triangles, B3212output, B3212jmat)
def compute_all_B411(triangles):
return compute_all(tri... | The main task of the code is to orchestrate the computation of multiple geometric processing functions (`compute_all_B222`, `compute_all_B3211`, `compute_all_B3212`, `compute_all_B411`) on a list of triangles, likely for tasks like mesh analysis or topological calculations, and return a status code (0) indicating compl... | def compute_all_B1loop(triangles):
compute_all_B222(triangles)
compute_all_B3211(triangles)
compute_all_B3212(triangles)
compute_all_B411(triangles)
return 0 |
def fetch_countries(cache, session, urls):
cities_urls = list()
bar = IncrementalBar('fetching', max=len(urls))
for url in urls:
name = urlparse(url).path.split('/')[-1]
bar.message = to_bar_message(name)
# next forces the bar to refresh (it's needed for the message)
bar.next... | The code fetches global weather data by scraping timeanddate.com, extracting country and city URLs, handling URL normalization, and collecting temperature information. It uses caching, corrects a typo in 'kazakstan' to 'kazakhstan', and processes structured data into a dictionary for further use. | def fetch_all_temps(data_cache):
session = requests.Session()
cache = HttpCache('~/download.cache')
print(f'collecting countries list')
url = 'https://www.timeanddate.com/weather/?low=c'
data = cache.get(session, url)
soup = BeautifulSoup(data, 'html.parser')
links = list()
for link in s... |
def get_archived_contents():
archived_contents = []
archived_files = os.listdir('./archived')
for file in archived_files:
content = ''
with open('./archived/' + file, mode='r', encoding='utf-8') as f:
content = f.read()
archived_contents.append(content)
return archive... | The main task of the code is to scrape programming language-related data (including Java, Python, JavaScript, etc.) and compare it with pre-archived contents, then generate Markdown files to document the results. The function iterates through a list of languages, retrieves scraped data for each, and writes the combined... | def job():
''' Get archived contents
'''
archived_contents = get_archived_contents()
''' Start the scrape job
'''
languages = ['', 'java', 'python', 'javascript', 'go', 'c', 'c++', 'c#', 'html', 'css', 'unknown']
for lang in languages:
results = scrape_lang(lang)
write_markd... |
def inputter():
print(f"Getting Image Sources")
with open(f'{out}/metadata.json') as f:
data = json.load(f)
global sourcelist
sourcelist = data
def reprint(msg, finish=False):
global _last_print_len
print(' '*_last_print_len, end='\r')
if finish:
end = '\n'
... | The main task of the code is to split input images into patches of specified sizes (e.g., 350), organize them into directory structures, and generate metadata. It iterates through a list of source images, creates patch folders, applies image splitting, and writes metadata for each size. The process clears temporary dat... | def main():
global LOCALJSON
LOCALJSON = []
inputter()
size = [350] #, 512, 3500, 7000]
for s in size:
print(f"Carrying out imagesplitting for size = {s}")
for i in sourcelist:
global currentimg
currentimg = i
patchpath = os.path.join(f"{out}/{i['... |
def update_ig_gis_header(self, params):
self.session.headers.update({
'x-instagram-gis': self.get_ig_gis(
self.rhx_gis,
params
)
})
def get_json(self, *args, **kwargs):
"""Retrieve text from url. Return text as string or None if no data pre... | This function queries a media API to retrieve user's timeline media data, handling pagination. It constructs request parameters, updates headers, fetches JSON data, extracts media nodes from the response, and returns them along with the end cursor for subsequent requests. If no data is found, it returns (None, None). | def __query_media(self, id, end_cursor=''):
params = QUERY_MEDIA_VARS.format(id, end_cursor)
self.update_ig_gis_header(params)
resp = self.get_json(QUERY_MEDIA.format(params))
if resp is not None:
payload = json.loads(resp)['data']['user']
if payload:
... |
def is_table_filled(table):
"""
Checks if a specified table has been fully filled
:param table: table to check if has been filled
:return: True if the table if filled, False otherwise
"""
for row in table:
if 0 in row:
return False
return True
def get_available_moves_from... | The code implements the **minimax algorithm with alpha-beta pruning** to determine the best move for an AI in a game (likely a turn-based strategy game like Connect Four). It evaluates all possible moves recursively, prioritizing winning positions, and uses alpha-beta pruning to optimize performance by eliminating subo... | def minimax(table, depth, alpha, beta, maximizing_player, last_row, last_column):
"""
Minimax algorithm for determining what could be the best currently available move.
:param table: specified table to look for the best available move
:param depth: number of recursive calls left available
:param al... |
def download(self):
import zipfile
if self._check_integrity():
print('Files already downloaded and verified')
return
filename = self._get_target_folder()
zip_filename = filename + '.zip'
url = self.download_url_prefix + '/' + zip_filename
downloa... | This code initializes a dataset by setting up paths, checking data integrity, and organizing image files. It downloads data if specified, verifies its existence, and structures character images with indices for processing. | def __init__(self, root, background=True,
transform=None, target_transform=None,
download=False):
self.root = join(os.path.expanduser(root), self.folder)
self.background = background
self.transform = transform
self.target_transform = target_transform
... |
def run_engine(config):
"""
:return:
"""
number_of_documents = 0
output_path = config.savedFileMainFolder
r = ReadFile(corpus_path=config.get__corpusPath())
p = Parse(config.toStem)
m_Indexer = Indexer(output_path)
parquetPaths = []
for (dirPath, dirNames, fileNames) in os.walk(c... | The main task of the code is to process a corpus by parsing, indexing, and storing data on disk. It then retrieves top-ranked documents for given queries using an inverted index and vector similarity, outputting results with tweet IDs and scores. Parameters include corpus path, output path, stemming option, query input... | def main(corpus_path, output_path, stemming, queries, num_docs_to_retrieve):
confing = ConfigClass(corpus_path, output_path, stemming)
# run engine: parse, index, and write to disk
run_engine(confing)
# read querires
if not isinstance(queries, list):
r = reader.ReadFile(corpus_path)
... |
def split(x, t):
if t is None:
return None, None, None
elif x < t.key:
l, r, f = split(x, t.left)
t.left = r
return l, update_string(update(t)), f
elif x > t.key:
l, r, f = split(x, t.right)
t.right = l
return update_string(update(t)), r, f
else:
... | The function inserts a new node with value `x` and size `s` into a tree-like data structure. It splits the tree at position `t`, merges the right part with any existing node if needed, updates the size, creates a new node, and recombines the left part with the new node and right part to form the updated structure. | def insert(x, t, s):
l, r, f = split(x, t)
if f:
r = merge(f, r)
increase(r)
new_node = Node(x, s)
return merge(merge(l, new_node), r) |
def get_team_standing(self, team_name):
for team_standing in self['standings']:
if team_standing['team'] == team_name:
return team_standing
team_standing = {'team': team_name,
'taskStats': {},
'score': 0}
self['standi... | The main task of the code is to add a challenge to a team's task list, update their submission stats with the accepted time, and optionally recompute scores and rankings. It checks if the challenge is already submitted by the team, avoids duplicates, and triggers score recalculations if `refresh=True`.)> | def add(self, accepted_time, chall, team_name, refresh=False):
chall_id = chall.id
if chall_id not in self['tasks']:
self['tasks'].append(chall_id)
team_standing = self.get_team_standing(team_name)
if chall_id in team_standing['taskStats']:
# Challenge already ... |
def update_tasks(self):
tasks = set()
for standing in self['standings']:
tasks.update(standing['taskStats'].keys())
self['tasks'] = sorted(tasks)
def recompute_score(self, chall):
points = self.compute_points(chall)
chall_id = chall.id
# update affected team's... | The code's main task is to refresh challenge scores and rankings by updating tasks, recalculating each challenge's score, and then re-ranking them. It first updates the task list, iterates through each challenge ID to recompute its score, and finally executes a ranking process to reflect the updated scores. | def refresh(self):
self.update_tasks()
for chall_id in self['tasks']:
self.recompute_score(Challenge(chall_id))
self.rank() |
def checkout(self, ref):
self.git(['checkout', ref])
def git(self, args, **kwargs):
returncodes = kwargs.pop('returncodes', {0})
if 'cwd' not in kwargs:
kwargs['cwd'] = self.get_path()
p = subprocess.run(['git'] + args, cwd=kwargs['cwd'], capture_output=True)
print(... | The main task of the code is to retry pushing a commit to a Git repository with exponential backoff. It checks out the main branch, fetches updates, resets to the latest remote commit, pulls changes, yields control for local modifications, and attempts to push. If failures occur, it delays exponentially between retries... | def retry_push(self, commit_message, retries=PUSH_RETRIES):
for retry in range(1, retries + 1):
try:
self.checkout(MAIN_BRANCH)
self.git(['fetch', 'origin'])
self.git(['reset', '--hard', 'origin/{}'.format(MAIN_BRANCH)])
self.pull()
... |
def image_pause(file, time):
set_image(file)
update_and_pause(time)
def get_start_position(text):
width = display.measure_text(text, 1) * 1.95 # Text scale is set to 2, but in reality ~1.95
return int((240 - width) / 2)
def speak(text, start_position, open_time, close_time):
text_over_image("img/ope... | The code displays a sequence of static images with timed pauses, then outputs three lines of text ("Hello, Smithers.", "You're quite good at", "turning me on.") in a synchronized manner using the `speak` function, which likely handles text rendering with specific timing and positioning parameters. The final image is pa... | def mr_burns():
static = ["img/static1.jpeg", "img/static2.jpeg", "img/static3.jpeg", "img/static4.jpeg"]
for image in static:
image_pause(image, 0.0005)
image_pause("img/closed.jpeg", 0.8)
# Print line 1 to screen
line_1 = "Hello, Smithers."
start_position = get_start_position(line_1)
... |
def update_time_left():
print("IT IS RUNNING THE TIMER OWO")
global time_left, question
if time_left:
time_left = time_left - 1
else:
pygame.time.set_timer(UPDATE_TIME_EVENT, 0)
skip_question()
print("IT IS RUNNING THE TIMER again")
def on_mouse_down(pos):
... | This code runs a quiz game using Pygame, handling events like timer updates, mouse clicks, and key releases. It displays questions, answer options, and a countdown timer on the screen, updating visuals and game state in a loop. The game continues until the player quits, with the timer decrementing every second to creat... | def quizgame():
pygame.time.set_timer(UPDATE_TIME_EVENT, 1000)
while True:
global score, game_over, correct_answer, skip_question, on_key_up, question, index, time_left, update_time_left, clock
#CLOSES GAME IF YOU PRESS X
for event in pygame.event.get():
if... |
def print_board(board):
for row in [board[i*3:(i+1)*3] for i in range(3)]:
print('| ' + ' | '.join(row) + ' |')
def check_winner(board, player):
win_combi = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]
]
for combi in win... | This code implements a Tic-Tac-Toe game where a human player competes against an AI. It maintains two boards: one displaying initial positions and another tracking the current game state. The human selects moves (0-8), with the AI responding using a best-move algorithm. After each move, it checks for wins or draws, dis... | def play_game():
board1 = [str(i) for i in range(9)]
board2 = [blank] * 9
while True:
print("\nInitial Board:")
print_board(board1)
print()
print("Current Board:")
print_board(board2)
move = int(input("Select your move (0-8): "))
if board2[mov... |
def isNegated(tok):
negations = {"no", "not", "n't", "never", "none"}
for dep in list(tok.lefts) + list(tok.rights):
if dep.lower_ in negations:
return True
return False
def getSubsFromConjunctions(subs):
moreSubs = []
for sub in subs:
# rights is a generator
righ... | This function extracts all subject tokens from a given verb token `v`, considering negation status and handling conjunctions. It first identifies direct subjects (excluding determiners), then extends them with conjunctive subjects if none are found. The result includes the list of subjects and a flag indicating if the ... | def getAllSubs(v):
verbNegated = isNegated(v)
subs = [tok for tok in v.lefts if tok.dep_ in SUBJECTS and tok.pos_ != "DET"]
if len(subs) > 0:
subs.extend(getSubsFromConjunctions(subs))
else:
foundSubs, verbNegated = findSubs(v)
subs.extend(foundSubs)
return subs, verbNegated |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.