dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def advance(self):
self.tok_indx += 1
if self.tok_indx < len(self.tokens):
self.curr_token = self.tokens[self.tok_indx]
return self.curr_token
def power(self):
return self.bin_op(self.atom, (TT_PWR, ), self.factor) | This code parses unary operations (+, -) by recursively calling `factor()` and wrapping the result in a `UnaryOpNode`, otherwise delegates to `power()` for non-unary cases. It uses `ParseResult` to track errors and token advancements, returning parsed nodes or error states accordingly. | def factor(self):
res = ParseResult()
tok = self.curr_token
if tok.type in (TT_PLUS, TT_MINUS):
res.register_advancement()
self.advance()
factor = res.register(self.factor())
if res.error: return res
return res.success(UnaryOpNode(tok, factor))
return self.power() |
def setfood():
global listTurtle
i=1
while True:
valid=True
a=random.randint(-235,235)
b=random.randint(-235,235)
for j in listFood:
if distance((j[0],j[1]),(a,b))<60 and distance((a,b),(0,0))<15:
valid=False
if valid == True:
l... | The main task of the code is to initialize and start a game by setting the start time, clearing the screen, placing food, disabling click events, updating the display, and initiating snake and monster movements along with keyboard configuration for gameplay control. | def start(a,b):
global startTime,listTurtle
startTime=time.time()
t0.clear()
setfood()
g_screen.onclick(None)
g_screen.update()
movesnake()
movemonster()
configureKey(g_screen) |
def create_index_articles():
with open("articles.txt", "w", encoding="utf8") as fout:
for issue in list_issues():
for article in list_articles(issue):
fout.write(article + os.linesep)
def create_index_news():
with open("news.txt", "w", encoding="utf8") as fout:
for pa... | The main task of the code is to initialize and create indexes for three distinct data categories: articles, news, and user profiles. The `main()` function sequentially invokes three helper functions—`create_index_articles()`, `create_index_news()`, and `create_index_profiles()`—to structure or organize these data types... | def main():
create_index_articles()
create_index_news()
create_index_profiles() |
def init_local_repo(self, config):
"""
Config the local repository path
"""
self.cfg["name"] = os.path.basename(
os.path.normpath(os.path.abspath(config.local_repo_path))
)
self.cfg["main_language"] = config.main_language
self.cfg["repo_path"] = os.pat... | This method configures a repository by initializing settings and data storage paths based on 'local' or 'online' mode. It sets self.cfg with mode, date, and save paths, then initializes local/online repo structures. It prepares file paths for commit/feature data, checks for existing saved files, and loads them if prese... | def config_repo(self, config):
"""
Input:
config: dict
# compulsory parameters
|- save_path: the root path of the saved data
|- mode: "local" or "online"
# optional parameters
|- local_repo_path: the path to the... |
def _handle_button_press_event(self, event):
"""
Save the start point for the drawing, create a text box if that is
the current drawing mode.
"""
self.application_state.start_pos = event.x, event.y
if self.application_state.current_type is DrawingType.TEXT:
s... | The code defines a method `handle_event` that dispatches incoming events to specific handler methods based on the event type, such as button press, motion, button release, or keypress, by calling corresponding private functions like `_handle_button_press_event` or `_handle_keyboard_event`.) | def handle_event(self, event):
"""
Dispatch the event to the proper handler.
"""
if event.type == self.BUTTON_PRESS:
self._handle_button_press_event(event)
elif event.type == self.MOTION:
self._handle_motion_event(event)
elif event.type == self.BUT... |
def generateLargePrime(keysize):
"""
return random large prime number of keysize bits in size
"""
while True:
num = random.randrange(2 ** (keysize - 1), 2**keysize - 1)
if isPrime(num):
return num
def isCoPrime(p, q):
"""
return True if gcd(p, q) is 1
relatively ... | The code generates RSA cryptographic keys (public and private) given a specified key size. It first generates two large prime numbers, $ p $ and $ q $, then computes the RSA modulus $ N = p \times q $ and Euler's totient $ \phi(N) = (p-1)(q-1) $. It selects a public exponent $ e $ that is coprime to $ \phi(N) $ and com... | def generateKeys(keysize=1024):
e = d = N = 0
# get prime nums, p & q
p = generateLargePrime(keysize)
q = generateLargePrime(keysize)
N = p * q # RSA Modulus
phiN = (p - 1) * (q - 1) # totient
# choose e
# e is coprime with phiN & 1 < e <= phiN
while True:
e = random.ran... |
def valid_col_list(board):
some_list = [col for col in range(COLUMN_NUMBER) if get_next_open_row(board,col)!= None]
return some_list
def check_winning_move(board, choices, player):
#player_dice = get_player_dice(player)
better_choice = []
for i in choices:
if drop_dice(board, i ,player)[1]:
... | This function determines the optimal move in a turn-based game by prioritizing winning moves for the current player, avoiding opponent's winning moves, and randomly selecting otherwise. It updates the board, checks for a win, and returns the current player if they win, or 0 if no valid moves remain. | def roll_once(board, player):
while True:
possible_choice = valid_col_list(board)
if possible_choice == []:
return 0
#win for current choose and loose for others
win_choice = check_winning_move(board, possible_choice, player)
loose_choice = check... |
def get_valid_col_list(board):
valid_col_locations = np.arange(0, COLUMN_NUMBER)
valid_col_locations_new = valid_col_locations[is_valid_location(board, valid_col_locations)]
return valid_col_locations_new
'''
for col in range(COLUMN_NUMBER):
if is_valid_location(board, col):
vali... | This code implements the Minimax algorithm with alpha-beta pruning for a game, evaluating board states by recursively exploring possible moves. It determines the optimal column for the AI or player to drop a dice, considering terminal states, depth limits, and heuristic scores. The algorithm maximizes AI's score while ... | def minmax(board, depth, min_value, max_value, maximizingPlayer):
valid_locations = get_valid_col_list(board)
check_terminal = check_terminal_node(board)
if check_terminal:
if win_check(board, AI_DICE):
return(None, math.inf)
elif win_check(board, PLAYER_DICE):
return... |
def create_new_board():
board = np.zeros((ROW_NUMBER,COLUMN_NUMBER), dtype=int)
return board
def valid_col_list(board):
some_list = [col for col in range(COLUMN_NUMBER) if get_next_open_row(board,col)!= None]
return some_list
def drop_dice(board_,col ,player = None):
board = board_.copy()
if play... | The main task of the code is to perform a Monte Carlo Tree Search (MCTS) rollout. It selects child nodes using UCT values, expands the tree by generating new states from valid moves, determines game outcomes (winning states), and backpropagates results (updating visit counts and scores) up the tree. It handles both exp... | def rollout(mcts_node = None, player = None):
if mcts_node == None:
mcts_node = Node(create_new_board(), 0, None, None)
#my tree node to calcute
node = mcts_node
while node.children is not None:
uct_array = [child.uct() for child in node.children]
if None in uct_array:
... |
def create_new_board():
board = np.zeros((ROW_NUMBER,COLUMN_NUMBER))
return board
def valid_col_list(board):
some_list = [col for col in range(COLUMN_NUMBER) if get_next_open_row(board,col)!= None]
return some_list
def play(board_, column, player=None):
board = board_.copy()
if player is None:
... | The function performs a Monte Carlo Tree Search (MCTS) rollout by selecting a path via UCT values, expanding nodes with valid moves, checking for winning states, and backpropagating results to update node statistics. It creates child nodes for each possible move, prioritizes unvisited nodes, and adjusts scores based on... | def rollout(mcts_node = None):
if mcts_node == None:
mcts_node = Node(create_new_board(), 0, None, None)
#my tree node to calcute
node = mcts_node
while node.children is not None:
uct_array = [child.uct() for child in node.children]
if None in uct_array:
node... |
def create_new_board():
board = np.zeros((ROW_NUMBER,COLUMN_NUMBER), dtype=int)
return board
def simeple_AI_choice(board):
#random choice a place to drop the dice
possible_list = valid_col_list(board)
choose = -1
if len(possible_list) > 0:
choose = random.choice(possible_list)
return choos... | The code simulates 100 games between a simple AI and an MCTS-based AI, tracking win/tie counts, visit counts, and scores. It evaluates the MCTS performance by running 2000 rollouts per move, incorporating random dice drops to meet game requirements, and returns statistical results for analysis. | def test_hundred_times(mcts):
SIMPLE_AI_winning_time = 0
AI_winning_time = 0
tie_game_time = 0
visit_count_list = []
score_total_list = []
score_count_list = []
for i in range(100):
board = create_new_board()
count = 0
training_time = 2000
node = mcts
... |
def _get_days(self):
if self.date_to and self.date_from:
timedelta = self.date_to - self.date_from
return timedelta.days + 1
return 1
def _calculate_extra_bonus(self):
# Calculate national holiday overtime
self._calculate_national_holiday()
# Calculate th... | The main task of the code is to compute the number of days in a period using `_get_days()`, store it in `self.days_in_the_period`, and, if an employee ID exists, trigger additional calculations for extra bonuses and penalties. The function exits early if no employee ID is provided, ensuring subsequent steps are only ex... | def _compute_days_in_the_period(self):
self.days_in_the_period = self._get_days()
if not self.employee_id:
return
self._calculate_extra_bonus()
self._calculate_penalty() |
def specialOffersCalc(items: List, itemDict: Dict, specialOffersDict: Dict) -> Dict:
"""
Needs to return price and string
"""
offers_list = list(specialOffersDict['offers'].keys())
message_dict = {}
if "flat_discount" in offers_list:
flat_message = flatDiscountFunction(items, specialOffe... | The main task of the code is to calculate a shopping basket's total price, apply special offers discounts, and output the subtotal after discounts. It processes user-input items, computes the base total, determines applicable discounts, formats prices, and compiles a formatted output displaying the original total, disc... | def main():
"""
Main function that outputs:
Basket price:
Special offers discount:
Subtotal (after discount applied):
"""
items = input("Enter shopping items separated by spaces: ").split()
specialOffersMessage = specialOffersCalc(items, itemDict, specialOffersDict)
bas... |
def calc_goal_force(goal: wp.vec3,
pos: wp.vec3,
vel: wp.vec3,
mass: float,
v_desired: float,
dt: float):
ee_i = wp.normalize(goal - pos)
force = mass * ( ( (v_desired * ee_i) - vel ) / (Tau) )
return fo... | The function computes the total force acting on an agent in a physics simulation by combining goal-directed force, neighbor interaction force, and wall collision force. It normalizes the summed force vector and limits its magnitude to a maximum speed, ensuring realistic movement dynamics for agents in a 3D environment ... | def compute_force(rr_i: wp.vec3,
ri: float,
vv_i: wp.vec3,
mass:float,
goal:wp.vec3,
pn_rr: wp.array(dtype=wp.vec3),
pn_vv: wp.array(dtype=wp.vec3),
pn_r: wp.array(dtype=float),... |
def geocode(place):
geolocator = Nominatim(user_agent="Learning Flask")
location = geolocator.geocode(place)
if location is None: #When there are no results found, returns None.
return location
latlng_tuple = (location.latitude, location.longitude)
return latlng_tuple
def time_zone_finder(la... | The function determines the current time and date for a given location by geocoding the location to obtain its coordinates, identifying the corresponding time zone, and retrieving the time/date using timezone-specific parameters. It handles both two-part (Area/Location) and three-part (Area/Location/Region) timezone fo... | def what_time_date_is_it_at(location):
lat_lng_location = geocode(location) #user: "Seattle" #FINDS LNG LAT PAIR as a tuple
time_zone_location = time_zone_finder(lat_lng_location) #returns the time zone as "Asia/Jeruselam"
time_zone_location_split = time_zone_location.split("/")
#assumption made here i... |
def getBucketPrefix(bucket_name, bucket_key):
#Figure out prefix from known bucket_name and bucket_key
bucket_prefix = '/'.join(bucket_key.split('/')[:-2])
if len(bucket_prefix) > 0:
bucket_prefix += '/'
return bucket_prefix
def getTransitConfig(bucket_name, bucket_prefix, s3_url, config_file):
... | The main task of the code is to handle an S3 event by retrieving configuration data, connecting to a Cisco router via SSH using a private key (or password if authentication fails), and applying a configuration file from S3 to the router. The function logs execution times and ensures secure key management by deleting te... | def lambda_handler(event, context):
record=event['Records'][0]
bucket_name=record['s3']['bucket']['name']
bucket_key=record['s3']['object']['key']
bucket_region=record['awsRegion']
bucket_prefix=getBucketPrefix(bucket_name, bucket_key)
log.debug("Getting config")
stime = time.time()
conf... |
def read_inputfiles(flask, path):
if flask == 'Y':
# data_path = "/content/drive/MyDrive/Colab Notebooks/project/Capstone/preprocessing/IHMStefanini_industrial_safety_and_health_database_with_accidents_description.csv"
data_path = 'C:\\Users\\91992\\PycharmProjects\\CapstoneProject\\preprocessing'
... | This function preprocesses data for a Flask web application. It handles POST requests to initiate data cleaning, transformation (e.g., converting months to seasons/quarters, renaming columns), analysis, and saving processed data as 'prepro_data.csv'. GET requests render a preprocessing page with a directory tree. The t... | def preprocess():
flask = "Y"
path = 'C:\\Users\\91992\\PycharmProjects\\CapstoneProject\\preprocessing'
train_path = 'C:\\Users\\91992\\PycharmProjects\\CapstoneProject\\training'
if request.method == 'POST':
result = request.form
if request.form['submit_button'] == "InitiateP":
... |
def draw(G):
G["SCREEN"].fill((1, 255, 1))
room = ROOMS[G["ROOM"]]
G["SCREEN"].blit(G["ROOMIMG"][room["IMG"]], (0, 0))
for name in room["ACTORS"]:
actor = ACTORS[name]
pos, dim = actor["RECT"]
G["SCREEN"].blit(G["ACTORIMG"][actor["IMG"]], pos)
for name in room["ITEM... | This function provides an interactive editor for modifying actor properties in a game or application. It allows users to navigate and edit attributes like images, mouse inputs, states, and commands via keyboard inputs, with real-time screen updates. The editor handles selection, modification, and addition of actor data... | def actor_editor(G, name):
actor = ACTORS[name]
keys = list(actor.keys())
idx = 0
ddx = 0
offset = 0
while True:
draw(G)
G["SCREEN"].blit(drawn_piece_data(G, actor, idx, ddx, offset), (256, 0))
G["SCREEN"].blit(G["HEL32"].render("{}, {}, {}".format(idx, ddx, len(keys)), 0... |
def load_images(G):
G.update({
"ROOMIMG": load_spritesheet("rooms.png", ROOM_SPRITESHEET),
"SYSIMG": load_spritesheet("menu.png", UX_SPRITESHEET),
"ACTORIMG": load_spritesheet("actor.png", ACTOR_SPRITESHEET),
"MOUSEIMG": load_spritesheet("mouse.png", MOUSE_SPRITESHEET),
"IT... | This function runs a game editor allowing users to manage rooms, actors, items, and exits via keyboard shortcuts. It loads images, handles input for adding/removing elements, editing properties, and saving/loading data. Key actions include: ESC to exit, Ctrl+S to save, Shift+S for spritesheets, Shift+L to reload images... | def run_editor(G):
load_images(G)
while True:
draw(G)
inp = expect_input()
mods = pygame.key.get_mods()
room = ROOMS[G["ROOM"]]
if inp == K_ESCAPE and (SAVED or mods & KMOD_CTRL):
return
if inp == K_s and mods & KMOD_CTRL:
save()
... |
def lines_bin(self, img):
"""
Pipeline to convert RGB image to binary image for line finding
:param img: Image in RGB color space
:return: binary image
"""
# RGB and HLS channel picks
red = self.get_rgb_single_ch(img, 'R')
gre = self.get_rgb_single_ch(img,... | The code processes a distorted image by undistorting, warping, and applying thresholds to detect lanes. It calculates lane curvature and offset, then overlays these metrics on the original image for visualization. | def pipeline(self, dist_img):
# Undistort
dst = self.cam.undistort(dist_img, False)
# Warp
warp = self.cam.warp_img(dst)
# Apply thresholds for binary image
bin_warp = self.lines_bin(warp)
# Find lanes in warped image
lane_warp, fit_l, fit_r, off = self.fi... |
def main_is_frozen():
return (hasattr(sys, "frozen") or # new py2exe
hasattr(sys, "importers") # old py2exe
or imp.is_frozen("__main__"))
def platform():
if sys.platform.startswith('win'):
return 'windows'
elif sys.platform.startswith('darwin'):
return 'mac'
return '... | The function `get_text_resources` determines the correct file path for a given resource, adjusting for macOS py2app packaging. If the application is frozen and running on macOS, it retrieves the resource from the app bundle's Resources folder. Otherwise, it constructs the path using the main directory. The goal is to l... | def get_text_resources(resource):
"""Return the resources that are located in the root folder of the
distribution, except for the Mac py2app version, which is located
in the Resources folder in the app bundle."""
if (main_is_frozen() and (platform() == 'mac')):
resource = GetResourcePat... |
def findEntropy(df):
lastColumn = df.keys()[-1]
uniqueValues = df[int(lastColumn)].value_counts().keys().tolist()
countOfUniqueValues = df[int(lastColumn)].value_counts().tolist()
total = len(df[lastColumn])
sumOfEntropies = 0
for i in range (len(countOfUniqueValues)):
prob = countOfUniq... | This function recursively builds a decision tree by splitting the dataset based on the best attribute, creating nodes for each value of the attribute. It checks if the target attribute is pure (single label) and calculates entropy. If sub-entropy is zero, it adds a terminal node with the label; otherwise, it recursivel... | def id3(df,targetAttribute,bestAttribute,remainAttr,currentNode):
#print("BestAttribute:",bestAttribute)
#count no. of unique labels in the target attribute
from collections import Counter
cnt = Counter(x for x in df[targetAttribute])
#If there's only one label ... |
def get_random_direction(self):
return random.choice([UP, DOWN, LEFT, RIGHT])
def get_pix_pos(self):
x = TOP_BOTTOM_SPACE // 2 + self.grid_pos.x * self.app.cell_width
y = TOP_BOTTOM_SPACE // 2 + self.grid_pos.y * self.app.cell_height
return Vector2(x, y)
def get_scared_direction(self):... | The code determines the movement direction of an entity based on its personality ('random', 'scared', or default). For 'random', it selects a random direction; for 'scared', it initializes a position and chooses a scared-specific direction. Otherwise, it calculates the next cell to move toward unless in intermission, t... | def move(self):
if self.personality == 'random':
self.direction = self.get_random_direction()
elif self.personality == 'scared':
if self.first_run == True:
self.grid_pos = Vector2(13, 23)
self.pix_pos = self.get_pix_pos()
s... |
def Re_F(alpha, alpha_m, b, TMB_C):
sc = 0
for i in range(K):
sc += F(np.dot(X, alpha)+alpha_m*(TMB_C[:, i].reshape(-1, 1))+b).real
return sc/K
def Re(alpha, alpha_m, b, TMB_C):
sc = 0
for i in range(K):
sc += (F(np.dot(X, alpha)+alpha_m *
(TMB_C[:, i].reshape(-1, 1))+... | The function `Score_c` computes a composite score by evaluating multiple mathematical expressions involving parameters (alpha, alpha_m, lamda, beta, beta_m, sigma) and variables (X, TMB_E, TMB_C, b). It calculates individual scores (e.g., `Score_alpha`, `Score_beta`) using exponential, logarithmic, and arithmetic opera... | def Score_c(alpha, alpha_m, lamda, beta, beta_m, sigma, b, TMB_E, TMB_C):
Score_alpha = R*X-Re_F(alpha,alpha_m,b,TMB_C)*X
Score_alpham = R*TMB_E-Re(alpha,alpha_m,b,TMB_C)
Score_lamda = D*(1/lamda+np.log(T))-T**lamda*np.log(T)\
*np.exp(beta*X+beta_m*TMB_E+b)*np.exp(-(sigma_err**2)*(... |
def detect_qr(frame, cont):
if len(cont) == 0:
return
edge_candidates = []
for i in range(len(cont)):
cont_inside = 0
t_cnt = cont[i].reshape(4,2)
polygon = Polygon([tuple(t_cnt[0]), tuple(t_cnt[1]), tuple(t_cnt[2]), tuple(t_cnt[3])])
for c in cont:
... | This code identifies quadrilateral contours in an image, filters those resembling QR codes based on aspect ratio and area, and applies perspective correction using homography to extract and warp the detected QR code region. It returns the processed frame, warped QR code image, and homography matrix if successful. | def qr(frame, cont, z_zoom):
origimg = frame.copy()
valid_cont = []
for c in cont:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.04 * peri, True)
if len(approx) == 4:
x,y,w,h = cv2.boundingRect(approx)
area = cv2.contourArea(c)
... |
def vectorize_ticker_stream(raw_ticker_stream=[]):
"""
First, gather a cache of the most recent ticker info of each pair.
Then, once this cache is gathered: for each new ticker, update the cache
with this new value and then vectorize all of the tickers using the
cached values for each ticker.
... | The code identifies and ranks features most correlated with a target financial feature (e.g., bid price) across time windows in a ticker stream. It processes data in strides, computes feature correlations iteratively, and aggregates scores to highlight the most predictive features for the target pair. | def explore_correlated_features(raw_ticker_stream, target_pair, num_to_keep=10, stride=LARGEST_MODEL_SIZE):
num_examples = len(raw_ticker_stream)
i = 0
end = num_examples - stride
top_index_scores = {}
while i <= end:
ticker_stream, pair_cache = vectorize_ticker_stream(raw_ticker_stream[i:... |
def fit(self, X):
n_samples = X.shape[0]
self.centroids = X[np.random.choice(n_samples, size=self.k), :]
for i in range(self.max_iter):
cluster_ids = self.predict(X)
new_centroids = np.zeros(self.centroids.shape)
for c in range(self.k):
indexes... | This code calculates the average silhouette score of a dataset, measuring how similar each data point is to its assigned cluster compared to others. It computes pairwise distances, determines intra-cluster (a) and nearest inter-cluster (b) distances, then computes (b-a)/max(a,b) for each point, returning the mean score... | def silhouette(self, X):
if not hasattr(self, "centroids"):
self.fit(X)
n_samples = X.shape[0]
cluster_ids = self.predict(X)
D = self.calc_dist(X, X)
def s(i):
c = cluster_ids[i]
Ci = [_ for _ in range(n_samples) if cluster_ids[_] == c]
... |
def welcome_options(self):
print("\nWelcome to Hangman\n")
print("1. " + "Noobie (10 lives)")
print("2. " + "Intermediate (6 lives)")
print("3. " + "Expert (3 lives)")
def draw_keyboard(self):
# two windows
# self.keyboard = tk.Toplevel()
# self.keyboard.geometry(... | The main task of the code is to handle user difficulty selection for a game, assign corresponding word lists and max life values, validate input, and initialize game components like the keyboard, revealed letters display, and remaining lives counter. It ensures valid difficulty input (1-3) or exits on '0', then trigger... | def __init__(self):
self.user_dif = None
self.welcome_options()
self.user_dif = game_state['shared']['user_dif']
self.max_life = game_state['shared']['max_life']
while self.user_dif not in ["1", "2", "3"]:
self.user_dif = input(
"\nChoose difficulty by... |
def calculate_piece_length(file_to_torrent, piece_len_exp=None):
"""Calculates the piece length according to the piece length exponent. If
one is not provided, it calculates it for you.
"""
if not piece_len_exp: # then calculate it automatically
size = _calcsize(file_to_torrent)
if siz... | The function generates a meta info dictionary for a torrent file, calculating piece hashes (SHA-1) and optionally MD5/CRC32 hashes. It handles both single files and directories, structuring data with piece length, file paths, sizes, and computed hashes for torrent metadata creation. | def make_info(file_to_torrent, piece_len_exp=None, get_hash=None):
"""Creates and returns the meta info dictionary.
@param piece_len_exp integer 2^piece_len_exp used to calculate the piece
length. If piece_len_exp is not given, it (and thus the piece length) will
be calculated for you.
"""
pie... |
def convert_to_num(l):
"""
Argument: String
Returns a list of corresponding numbers. Eg, abz -> [0, 1, 25]
"""
return [(ord(c)-97) for c in l]
def convert_msg(message, n):
"""
Argument: Message (String), block length n
Converts a message into corresponding numbers and returns a list of t... | The main task of the code is to decrypt an encrypted message using a key-based matrix transformation. It converts the key into a square matrix, processes the received encrypted message, and applies the decryption function to retrieve the original text, which is then displayed in a text entry field. | def show_decrypt():
key = 'temp'
key_len = len(key)
n = int(math.sqrt(key_len))
# convert key to matrix
k = np.array(convert_to_num(key))
k = np.reshape(k, (-1, n))
msg_received = decrypt_entry.get()
text_entry.delete(0,END)
decrypt_entry.delete(0,END)
mr = convert_msg(msg_recei... |
def load_pretrained_weights(self):
self.net = network().to(self.device)
state_dict = torch.load('classvdd/weights/pretrained_parameters_{}.pth'.format(self.args.anormal_class))
self.net.load_state_dict(state_dict['model'], strict=False)
self.c = self.set_c().to(self.device)
def test(self... | The code trains the ClasSVDD model by minimizing the distance between input features and a learned center vector `c` via Adam optimization. It supports pretraining or random weight initialization, employs early stopping, and uses a multi-step learning rate scheduler. The training loop computes reconstruction loss as th... | def train(self):
"""Training the ClasSVDD model"""
if self.args.pretrain==True:
self.load_pretrained_weights()
else:
self.net.apply(weights_init_normal)
self.c = torch.randn(self.args.latent_dim).to(self.device)
self.es = EarlyStopping(patienc... |
def die(*message):
print("ERROR:", *message)
raise FatalError()
def parseCode(code):
instSet = {}
maxLine = -1
for line in code:
line = line.strip()
if line == "":
continue
# First integer on line is line number
lineNumMatch = intRe.match(line)
if... | The code reads a file's contents, parses them into instructions, and executes them. It handles errors like file access failures and fatal execution errors, ensuring the program exits silently on critical issues. | def runFile(filename):
try:
try:
with open(filename) as f:
code = f.readlines()
except:
die("could not open", filename)
else:
instructions = parseCode(code)
runInstructions(instructions)
except FatalError:
# The erro... |
def all_flash(matrix):
compare = matrix == np.zeros([n_octopuses, n_octopuses], int)
if compare.all():
return True
else:
return False
def several_steps(m, steps):
total_flashes = 0
for s in range(steps):
m = one_step(m)
while has_second_wave(m):
m = cleari... | The function determines the minimum number of steps required for the condition `all_flash(several_steps(octopuses, steps)[0])` to become true, using recursive incrementation until the condition is satisfied. | def second_part(steps):
if all_flash(several_steps(octopuses, steps)[0]):
return steps
else:
steps += 1
return second_part(steps) |
def minimumFind(count):
minV=count[0]
minIndex=0
for i in range(0,len(count)):
if(count[i]<minV):
minV=count[i]
minIndex=i
return minV,minIndex
def genWord3gramVec(w1,w2,triCount,biCount):
predict=['','','','','']
count=[0,0,0,0,0]
minV=0
minIndex=0
fo... | The main task of the code is to predict the next word in a sequence using 4-gram language model counts (quadCount), prioritizing the highest frequency 4-grams starting with input words w1, w2, w3. If no valid 4-gram matches are found, it falls back to 3-gram (triCount) and then 2-gram (biCount) models to generate possi... | def genWord4gramVec(w1,w2,w3,quadCount,triCount,biCount):
predict=['','','','','']
count=[0,0,0,0,0]
minV=0
minIndex=0
for k,v in quadCount.items():
if(k[0]==w1 and k[1]==w2 and k[2]==w3):
if(v>minV):
count[minIndex]=v
predict[minIndex]=k[3]
... |
def display_welcome(self):
print(f"Let's start a Battle!")
pass
def battle(self):
while len(self.fleet.robots) > 0 and len(self.herd.dinos) > 0:
self.robot_turn()
if len(self.herd.dinos) == 0:
pass
else:
self.dino_turn()
def sho... | The main task of the code is to execute a game sequence by first displaying a welcome message, then initiating a battle, and finally showing the winners. The method orchestrates these steps in order to run the game's core functionality, with `pass` indicating a placeholder for additional logic. | def run_game(self):
self.display_welcome()
self.battle()
self.show_winners()
pass |
def lookForAccount(self, account):
driver = self.driver
driver.get("https://www.instagram.com/"+account+"/")
sleep(3)
def goToProfile(self):
self.lookForAccount(self.username)
def getFollowLists(self, account):
driver = self.driver
n_followers, n_following = self.getFollo... | This code identifies users who follow a specified social media account but do not follow them back. It navigates to the account's profile, retrieves lists of people they follow (following) and who follow them (followers), compares these lists, and prints usernames of those who follow the account but are not in their fo... | def checkFollowersOf(self, account):
driver = self.driver
if account:
self.lookForAccount(account)
else:
self.goToProfile()
account = self.username
following, followers = self.getFollowLists(account)
print("People that don't follow " + accoun... |
def randomPoint(self, map):
return np.random.uniform(low=0, high=map.city_width), np.random.uniform(low=0, high=map.city_width)
def mod(self, x):
# make x between 0 and 2*pi
while x < 0:
x += 2*np.pi
while x > 2*np.pi:
x -= 2*np.pi
return x
def collision(s... | This function extends a 3D tree structure by iteratively generating random points, finding the nearest node, calculating a new node's position along the direction of the random point, checking for collisions, and appending the new node if valid. It returns the updated tree and a flag indicating successful connection to... | def extendTree(self, tree, endN, R_min, map, pd):
successFlag = False
while not successFlag:
# Generate Random Point
northP, eastP = self.randomPoint(map)
# Find nearest leaf.
distances = (northP-tree[:, 0])**2 + (eastP-tree[:, 1])**2
minIndex... |
def mod(self, x):
# make x between 0 and 2*pi
while x < 0:
x += 2*np.pi
while x > 2*np.pi:
x -= 2*np.pi
return x
def collision(self, startNode, endNode, map, radius):
dubinPath = dubins_parameters()
dubinPath.update(startNode[0:3], startNode.item(3... | The code plans a collision-free path from a start to an end waypoint using a tree-based algorithm. It checks direct connectivity between nodes, constructs a tree by extending paths, finds the minimum-cost path, and smooths it. The function returns a smoothed trajectory adhering to constraints like minimum segment lengt... | def planPath(self, wpp_start, wpp_end, R_min, map):
self.segmentLength = 3.5*R_min #2.5 ??
# desired down position is down position of end node
pd = wpp_end.item(2)
# specify start and end nodes from wpp_start and wpp_end
# format: N, E, D, chi, cost, parentIndex, connectsToGo... |
def send_dir(self,conn,local_server_dir):
files = os.listdir(local_server_dir)
send_data = "LIST@@"
if len(files) == 0:
send_data += "The server directory is empty"
else:
send_data += "\n".join(f for f in files)
conn.send(send_data.encode(FORMAT))
... | This function handles guest client requests by sending directory listings, processing commands like DOWNLOAD and CD, while restricting uploads/deletes. It maintains the server path, responds to commands, and terminates on logout or thread stop. | def handle_guest(self,conn,addr):
conn.send("OK".encode(FORMAT))
time.sleep(0.1)
global SERVER_PATH
local_server_path = SERVER_PATH
self.send_dir(conn,local_server_path)
while True:
data = conn.recv(SIZE).decode(FORMAT)
data = data.s... |
def send_dir(self,conn,local_server_dir):
files = os.listdir(local_server_dir)
send_data = "LIST@@"
if len(files) == 0:
send_data += "The server directory is empty"
else:
send_data += "\n".join(f for f in files)
conn.send(send_data.encode(FORMAT))
... | This code handles administrative commands from a connected client, allowing actions like listing files, uploading/downloading files, deleting, renaming, changing directories, and logging out. It maintains the server's file directory structure, processes client instructions via a loop, and terminates when logout is requ... | def handle_admin(self,conn,addr):
conn.send('OK'.encode(FORMAT))
time.sleep(0.1)
global SERVER_PATH
local_server_path = SERVER_PATH
self.send_dir(conn,local_server_path)
while True:
data = conn.recv(SIZE).decode(FORMAT)
data = data.split('... |
def change_val(self,message):
global msg
self.window['textbox'].update(disabled=False)
msg += message
self.window['textbox'].update(msg)
self.window['textbox'].update(disabled=True)
def handle_guest(self,conn,addr):
conn.send("OK".encode(FORMAT))
time.sleep(0.1)
... | This function handles client connections by receiving commands, authenticating admin requests with a password, and routing to guest or admin handling functions. It sends a connection confirmation, processes incoming data, checks the command type, and either forwards to T1/T2 handlers or sends an error. The connection i... | def handle_client(self,conn, addr):
msg = f'[NEW CONNECTION] {addr} connected\n'
self.change_val(msg)
data = conn.recv(SIZE).decode(FORMAT)
data = data.split('@@')
cmd = data[0]
time.sleep(3)
if cmd == 'T1':
self.handle_guest(conn,addr)
... |
def load_probe_metadata(self, probes_used, probes_yml_dir):
probes = []
for prb in probes_used:
# read in from probe metadata file
probe_yml_path = os.path.join(probes_yml_dir, prb['device_type'] + '.yml')
probe_yml = read_yml(probe_yml_path)
ch_cnts = [le... | This code initializes a session object by setting up parameters like animal name, date, data paths, probe configurations, and task details. It loads metadata, detects tasks, and prepares file paths for experiment data processing and analysis. | def __init__(self,
data_path: str,
animal_name: str,
date: str,
dio_id: dict,
probes_used: dict,
probes_yml_dir=DEFAULT_PROBE_DIR,
experimenter_name=None,
experiment_description=None,
... |
def hello(self):
hello = self.request.recv(1024)[:-1]
if self.traceClient:
self.logger.debug('Received hello message: ', repr(hello))
helloMsg = json.loads(hello)
helloResponse = {'id': helloMsg['id'], 'response': { 'agentId': id(self) } }
s... | This method handles client communication by receiving and processing messages. It initializes the client, polls for data with timeout handling, logs activity if enabled, and splits incoming messages using null terminators. Each message segment is decoded and processed individually until all data is handled or the conne... | def handle(self):
self.hello()
self.server.processClient(self)
while not self.finished:
if not self.poll(0.5):
continue
if self.traceClient:
self.logger.debug('Receiving from %s...' % str(self.client_address))... |
def play_bgm(mode):
if mode == "ingame":
sound_file = 'bgm.wav'
elif mode == "menu":
sound_file = 'menu_bgm.wav'
else:
sound_file = 'bgm.wav'
player.setSource(QtCore.QUrl.fromLocalFile(sound_file))
player.setLoopCount(QSoundEffect.Infinite)
player.play()
def resize_image(... | The function `frame2` sets up a game interface by creating and arranging UI elements: it displays the current score, a randomly selected question, four answer buttons, a logo, and a "Return to Menu" button with hover effects. Widgets are styled with specific fonts, colors, and layouts, then placed on a grid. The backgr... | def frame2():
play_bgm("ingame")
# ************Score placement***************
score = QLabel("Score: " + str(parameters["score"][-1]))
score.setAlignment(QtCore.Qt.AlignRight)
score.setStyleSheet(
'''
font-family: 'Georgia';
font-size: 25px;
color: '#32CD32';
... |
def clear_widgets():
try:
for widget in widgets:
if widgets[widget] != []: # if not an empty dict, hide/ remove current widget from window
widgets[widget][-1].hide()
for i in range(0,
len(widgets[widget])): # depending on how many widget ... | The main task of the code is to initialize or reset a game state by clearing UI elements and parameters, preloading data based on the last index, appending a placeholder achievement, setting an initial time of 30 seconds, and transitioning to a new frame (frame2) to start or restart the game. | def start_game():
clear_widgets()
clear_parameters()
preload_data(parameters["index"][-1])
data_to_be_synced["achievements"].append("None")
global time
time.setHMS(0, 0, 30)
frame2() |
def IsLinux():
return sys.platform.startswith('linux')
def RunEngineExecutable(build_dir, executable_name, filter, flags=[],
cwd=buildroot_dir, forbidden_output=[], expect_failure=False, coverage=False):
if filter is not None and executable_name not in filter:
print('Skipping %s due to f... | The main task of the code is to execute a series of Flutter Engine unit-tests across multiple platforms, using configurable parameters like test filters, coverage, and core dump handling. It runs test executables conditionally based on the operating system, applies platform-specific flags (e.g., Linux golden directorie... | def RunCCTests(build_dir, filter, coverage, capture_core_dump):
print("Running Engine Unit-tests.")
if capture_core_dump and IsLinux():
import resource
resource.setrlimit(resource.RLIMIT_CORE, (resource.RLIM_INFINITY, resource.RLIM_INFINITY))
shuffle_flags = [
"--gtest_repeat=2",
"--gtest_shuffl... |
def EnsureDebugUnoptSkyPackagesAreBuilt():
variant_out_dir = os.path.join(out_dir, 'host_debug_unopt')
message = []
message.append('gn --runtime-mode debug --unopt --no-lto')
message.append('ninja -C %s flutter/sky/packages' % variant_out_dir)
final_message = '%s doesn\'t exist. Please run the following comma... | The main task of the code is to run Dart unit tests in a specified build directory, ensuring required dependencies are built, executing `dart pub get` to fetch packages, filtering tests based on input, and running tests with/without observatory support. It handles both observatory-specific and general Dart tests, apply... | def RunDartTests(build_dir, filter, verbose_dart_snapshot):
dart_tests_dir = os.path.join(buildroot_dir, 'flutter', 'testing', 'dart',)
# This one is a bit messy. The pubspec.yaml at flutter/testing/dart/pubspec.yaml
# has dependencies that are hardcoded to point to the sky packages at host_debug_unopt/
# Befo... |
def a1(Sxx,Sxy):
a_sub_one = Sxy/Sxx
return a_sub_one
def Sxx(x):
n = len(x)
result = list_sum(list_square(x)) - n*(list_mean(x))**2
return result
def Sxy(x,y):
n = len(x)
result = list_sum(axb(x,y)) - n*list_mean(x)*list_mean(y)
return result
def a0(x,y):
a_naught = list_mean(y) - (... | This function calculates predicted values (yhat) using a linear regression model. It computes each prediction by multiplying the input x values with a slope coefficient (a1) derived from Sxx and Sxy statistics, then adding an intercept (a0) calculated from x and y. The result is a list of predicted y-values correspondi... | def y_Hat(x,y):
yhat = []
for items in x:
yhat.append((a1(Sxx(x),Sxy(x,y))*items) + a0(x,y))
return yhat |
def list_sum(lst):
result = 0
for items in lst:
result += items
return result
def list_square(lst):
result = []
for squared in lst:
result.append(squared**2)
return result
def a_b(lst1,lst2):
result = []
for itemsx, itemsy in zip(lst1,lst2):
result.append(itemsx-i... | The main task of the code is to compute the Sum of Squared Errors (SSE) between actual values `y` and predicted values generated by the function `y_Hat(x, y)`. It calculates the squared differences between `y` and `y_Hat(x, y)`, sums them using `list_sum` after squaring via `list_square`, and returns the result as the ... | def SSE(x,y):
result = list_sum( list_square( a_b( y,y_Hat(x,y) ) ) )
return result |
def y_Hat(x,y):
yhat = []
for items in x:
yhat.append((a1(Sxx(x),Sxy(x,y))*items) + a0(x,y))
return yhat
def list_mean(var):
var_aux = 0
for items in var:
var_aux += items
result = var_aux/len(var)
return result
def list_sum(lst):
result = 0
for items in lst:
... | The code calculates the Sum of Squared Residuals (SSR) by subtracting the mean of `y` from predicted values generated by `y_Hat(x, y)`, squaring the resulting residuals, and summing them. This measures the total deviation of observed values from predicted values in a regression model. | def SSR(x,y):
sub = []
for items in y_Hat(x,y):
sub.append(items - list_mean(y))
result = list_sum( list_square( sub ) )
return result |
def read_file(pth: Path) -> np.ndarray:
with open(pth, "r") as fp:
values = []
for line in fp.readlines():
line_elems = [bool(int(elem)) for elem in list(line.strip("\n"))]
values.append(line_elems)
arr = np.array(values, dtype=bool)
return arr
def p1_get_power_consu... | The main task of the code is to read input data from a file, compute two values—power consumption and life support rating—using helper functions, and print them. It first calculates the power consumption by analyzing binary numbers for gamma and epsilon rates. Then, it determines the life support rating by identifying ... | def main():
arr = read_file(INPUT_PATH)
print("Power consumption:", p1_get_power_consumption(arr), sep="\t")
print("Life support rating:", p2_get_life_support_rating(arr), sep="\t") |
def get_board(self):
return self.board
def set_board_position(board, position, value):
x, y = position
board[x][y] = value
def get_player(self):
return get_current_player(self.board) | This code creates a deep copy of a Node object, applying a specified move to generate a new game state. It initializes the new node's board, sets its parent, records the move, and updates the Q-table if the state exists. The function returns the new node for use in game tree exploration or reinforcement learning. | def copy(self, move):
copy = Node()
copy.board = deepcopy(self.get_board())
copy.parent = self
set_board_position(copy.get_board(), move, self.get_player().value)
copy.move = move
copy.children = None
copy.set_score((0, 0))
copy.q_table = self.q_table
if self.q_table.has_state(copy.... |
def get_available_moves(board):
available_moves = []
for i in range(0, len(board)):
for j in range(0, len(board)):
if board[i][j] == -1:
available_moves.append((i, j))
return available_moves
def get_board(self):
return self.board
def copy(self, move):
copy = Node()
copy.board = deep... | This code generates child nodes for a game state by creating copies of the current object with each available move applied, ensuring efficient reuse of computed children. It initializes self.children as an empty list if not already present, iterates through available moves, and appends new instances with each move. The... | def get_children(self):
if self.children == None:
self.children = []
for move in get_available_moves(self.get_board()):
self.children.append(self.copy(move))
return self.children |
def drawPoints(self):
#print('in draw points')
#self.triFlag = 1
#self.drewS = 1
#self.mWflag = 0
self.startDone = 0
#print(self.showStartFlag)
#print(self.showEndFlag)
if (self.showStartFlag == 1):
#print('start')
self.showStartFl... | The main task of the code is to load and visualize Delaunay triangulated points from two files (start/end) in QGraphicsScenes, with conditional rendering based on checkbox state and flags. It draws triangles, points (colored red/blue/green), and handles interactive mouse events for position capture. Triangulation is ap... | def loadDelTri(self):
if (self.checkBox.isChecked() == True):
self.splCase = 1
self.showStartFlag = 1
self.showEndFlag = 1
#print('checked')
SptsArr = np.loadtxt(self.onlyImSPtsFile,'float64')
EptsArr = np.loadtxt(self.onlyImEPtsFile,'flo... |
def doneChoosingPts(self):
self.clicked = 0
self.notDone = 1
#print('Waiting for main window click')
#mW = QMainWindow()
#mW.mousePressEvent = self.wantToSave
#self.mWflag = 1
self.startImage.setDisabled(False)
#print("I'm in donechoosing")
if (sel... | The code handles mouse click events to save user-selected image coordinates. When a click occurs outside a specific image, it records start/end points, updates visual markers (blue dots) on scenes, writes coordinates to files, and resets UI states. It ensures points are saved only after both start/end selections are co... | def wantToSave(self,event):
#print("I'm in want to save")
#self.triFlag = 1
#print('setting it to 2 in wanttosave')
#self.drewS = 0
self.drewE = 2
pressPos = event.pos()
self.StempCoords = []
self.EtempCoords = []
#check for backspace happens aut... |
def reset_scan_state(self):
self.interrupt = False
self.current_row = 0
self.current_col = 0
self.direction = 1
def scan_grid(self):
self.start_drone()
if not self.scan_job:
self._scan_next_square()
def end_scan(self):
self.interrupt = True
if ... | The code defines a method handling button presses, initiating a scan on "Start" if no job exists, and ending the scan on "End" | def button_action(self, button_number):
print(f"Button {button_number} pressed")
if button_number == "Start":
if not self.scan_job:
print("Starting scan")
self.reset_scan_state()
self.scan_grid()
elif button_number == "End":
... |
def find_by_id(self):
id_to_search = self.entry_id.get()
if(id_to_search == ""):
messagebox.showerror("Error", "ID cannot be empty !")
return
try:
status = cursor.execute("SELECT * FROM Phonebook WHERE ID = ?", id_to_search)
data = status... | This code initializes a GUI for a phone book application using Tkinter. It sets up a Treeview to display contact data (ID, name, phone, email), includes search, add, refresh, and download features, and integrates with an app controller for navigation. The interface organizes data visually, handles user interactions, an... | def __init__(self, parent, appController):
self.SortDir = True
tk.Frame.__init__(self, parent)
l_frame = Frame(self)
l_frame.pack(pady = 10)
self.label_title = tk.Label(
l_frame,
text="Phone Book",
font=("Arial", 20)
)
... |
def find_by_id(self):
id_to_search = self.entry_id.get()
if (id_to_search == ""):
messagebox.showerror (
"Error",
"ID cannot be empty !"
)
return
request = FIND_BY_ID # send request to server
client.send(request.enc... | The main task of the code is to initialize a GUI for a phone book application using Tkinter. It sets up a Treeview to display contact data (ID, name, phone, email) with scrollbars, adds search, refresh, and download buttons, and configures layout and styling for the interface. | def __init__(self, parent, appController):
tk.Frame.__init__(self, parent)
self.SortDir = True
l_frame = Frame(self)
l_frame.pack(pady = 10)
self.label_title = tk.Label(
l_frame,
text = "Phone Book",
font = ("Arial", 20)
)
... |
def set_height(self, node):
left_node_height, right_node_height = self.left_right_height(node)
max_height = self.max_height(left_node_height, right_node_height)
node.height = max_height + 1
def left_right_height(node):
if node.left_node is None:
left_node_height = -1
... | This function checks if a node in a binary tree is balanced by comparing the heights of its left and right subtrees. If unbalanced, it performs rotations (left or right) to restore balance, handling cases of double left/right heaviness with appropriate rotation sequences. The process recursively checks upward to ensure... | def balance_check(self, node):
self.set_height(node)
left_node_height, right_node_height = self.left_right_height(node)
# Checks if it's balanced at that node
if self.absolute_value(left_node_height - right_node_height) <= 1:
if node.parent:
self.balance_check... |
def reset(self):
self.xmin = -10
self.xmax = 10
self.ymin = -10
self.ymax = 10
self.input_weight = [1, 1]
self.bias = 0
def input_weight_slider_callback(self):
self.input_weight[0] = self.input_weight_slider1.get()
self.input_weight[1] = self.input_weight_... | This code initializes a GUI interface for training a neural network, setting up a plotting area to visualize input-output relationships, sliders to adjust input weights and bias, buttons to generate random data and train the model, and a dropdown menu to select activation functions. The interface allows interactive par... | def __init__(self, root, master, *args, **kwargs):
self.master = master
self.root = root
self.activation_function = "Symmetrical Hard limit"
#########################################################################
# Set up the constants and default values
##############... |
def __loglik(self, W, sigma2, gamma):
return -0.5*loglik_helper(self.X, W, sigma2) + gamma*0.5*loglik_helper(self.Y, W, sigma2)
def calcGradient(X, Y, W, sigma2, gamma):
# calculate gradient with respect to W and sigma2
D = X.shape[1]
n, m = X.shape[0], Y.shape[0]
accu_Wf = np.zeros((D, D))
... | The code implements gradient descent with Adam optimization to estimate parameters W and sigma2 in a probabilistic PCA (pPCA) model, maximizing the log-likelihood of observed data while handling missing values. It iteratively updates parameters using gradients, checks convergence, and imputes missing data in X and Y vi... | def gradient_descent(self, gamma, maxIter=50, tol=1e-2):
# initialize W and sigma2 by filling the nan value with column mean and do a MLE fit on it ?
D = self.X.shape[1]
np.random.seed(seed=2021)
W = np.random.rand(D, self.d)
sigma2 = 5.0
X_copy, Y_copy = np.nan_to_num(s... |
def covCMatMul(X, Y, gamma, Omega):
assert(X.shape[1] == Omega.shape[0])
nrow, ncol = X.shape[1], Omega.shape[1]
result = np.zeros((nrow, ncol))
for j in range(ncol):
result[:, j] = covCVecProduct(X, Y, gamma, Omega[:, j])
return result
def covVecProduct(X, v):
# v: a vector (1-d, not a ... | The main task of the code is to approximate the column space of a matrix using a randomized algorithm. It iteratively builds an orthonormal basis (Q) by projecting random vectors (Omega) through a covariance-related transformation (covCMatMul/covCVecProduct), subtracting projections onto the current basis, and orthogon... | def ColSpaceApprox_MatC(Xdata, Ydata, gamma, r=10, tol=1e-8, oversampling=0.1):
m = n = Xdata.shape[1]
#Omega = multivariate_normal.rvs(mean=np.zeros(n), size=r).T
Omega = np.random.normal(loc=0.0, scale=1.0, size=(n, r))
Y = covCMatMul(Xdata, Ydata, gamma, Omega)
j = 0
cutoff = tol/(10*np.sqrt... |
def rsvp_get_event_id(browser):
browser.get(get_link_event_list())
event_button = browser.find_element_by_css_selector('.eventList-list .eventCardHead--title')
event_link = event_button.get_attribute("href")
event_id = os.path.split(os.path.dirname(event_link))[1]
return event_id
def alert_message(m... | This function automates RSVP for an event by retrieving an event ID, introducing a delay to avoid suspicion, navigating to the event page, clicking the RSVP button, verifying RSVP status via attendee list checks, displaying the event link, and returning a boolean indicating successful RSVP. | def rsvp(browser):
# get
event_id = rsvp_get_event_id(browser)
# waiting before RSVP, so that it's not too quick, avoid people wonder
alert_message('Delay, we are going to book in {} seconds'.format(DELAY_RSVP_TIME_JSON))
time.sleep(DELAY_RSVP_TIME_JSON)
# click RSVP
browser.get(get_link_e... |
def main_login_setup(cookies=True):
# setting up and init of logging and selenium
browser = setup()
if cookies:
# login using old cookie, no need to re login
cookies_load(browser)
# check is the cookie working, otherwise login
if is_logged_in(browser):
alert_message("Cookie... | The main task of the code is to monitor a group's upcoming events on a website, check for availability, and automatically RSVP if a valid event is found. It uses a browser session, handles login/cookies, alerts the user of status updates, and exits gracefully on errors or manual interruptions. The system ensures only o... | def main():
# setting up the browser and login, decide to use cookies or new login
browser = main_login_setup(CONFIG_COOKIES)
alert_message("Start checking {} every {} seconds".format(GROUP_LIST[0], CONFIG_CHECK_TIME_SECOND))
count_try = 0
# looping each time to check
while True:
try:
... |
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
self.handle_mouse_click(event)
elif event.type == pygame.MOUSEMOTION:
self.h... | The main task of the code is to run the game loop, rendering the game background, handling user events, checking collisions, updating game elements like fruits, displaying a red dotted warning line, color order indicators, and the score, while maintaining a 60 FPS frame rate. The loop also transitions to a game-over st... | def run_game(self):
while self.running:
self.screen.blit(self.bg_image,(0, 0))
self.handle_events()
if not self.game_over:
self.check_collision()
self.update_fruits()
# Draw a warning line at the top of the box... |
def cursor_to_content(self, line) -> None:
cursor = 0
while getType(line[cursor]) == CharType.ws:
cursor += 1
return cursor
def process_lexemes_3(self, line) -> None:
self.char = line[self.current_cursor]
self.state = getState(State.nostate, self.char)
self.current_cursor += 1
while... | The main task of the code is to process each line of a file, ensuring proper newline formatting, tracking cursor positions, managing indentation stacks, and tokenizing lexemes. It handles line-by-line analysis, updates current line numbers, processes tokens, and manages leftover indents for syntax parsing, likely in a ... | def analyse(self) -> None:
last_line = self.file[-1]
if last_line[-1] != '\n':
self.file[-1] = last_line + '\n'
for line_num, line in enumerate(self.file):
self.current_line_number = line_num + 1
cursor = self.cursor_to_content(line)
if (
getType(line[cursor]) != CharTy... |
def is_weight(w):
"""Whether w is a weight, not a mobile."""
return is_leaf(w)
def size(w):
"""Select the size of a weight."""
return label(w)
def end(s):
"""Select the mobile or weight hanging at the end of a side."""
return branches(s)[0]
def sides(m):
"""Select the sides of a mobile."""
... | The function `total_weight(m)` calculates the total weight of a mobile or a single weight. If `m` is a weight, it returns its size. If `m` is a mobile, it recursively sums the total weights of all its components by iterating over each side and adding the weights of the ends. This approach ensures that nested mobile str... | def total_weight(m):
"""Return the total weight of m, a weight or mobile.
>>> t, u, v = examples()
>>> total_weight(t)
3
>>> total_weight(u)
6
>>> total_weight(v)
9
"""
if is_weight(m):
return size(m)
else:
return sum([total_weight(end(s)) for s in sides(m)]) |
def is_weight(w):
"""Whether w is a weight, not a mobile."""
return is_leaf(w)
def end(s):
"""Select the mobile or weight hanging at the end of a side."""
return branches(s)[0]
def sides(m):
"""Select the sides of a mobile."""
return branches(m)
def label(tree):
return tree[0]
def tree(label... | The code creates a new mobile structure where each node's label is replaced with the total weight of its subtree, without modifying the original mobile. It recursively processes each branch, calculates subtree totals, and constructs a new tree with updated labels. The function ensures immutability of the input mobile w... | def with_totals(m):
"""Return a mobile with total weights stored as the label of each mobile.
>>> t, _, v = examples()
>>> label(with_totals(t))
3
>>> print(label(t)) # t should not change
None
>>> label(with_totals(v))
9
>>> [label(end(s)) for s in sides(w... |
def mobile(left, right):
"""Construct a mobile from a left side and a right side."""
return tree(None, [left, right])
def side(length, mobile_or_weight):
"""Construct a side: a length of rod with a mobile or weight at the end."""
return tree(length, [mobile_or_weight])
def weight(size):
"""Construct... | The code defines a function `examples()` that constructs and returns three nested mobile structures using recursive combinations of `side()` and `mobile()` functions, representing balanced mobiles with weighted arms. Each mobile is built from sides with specified lengths and weights, including recursively embedded mobi... | def examples():
t = mobile(side(1, weight(2)),
side(2, weight(1)))
u = mobile(side(5, weight(1)),
side(1, mobile(side(2, weight(3)),
side(3, weight(2)))))
v = mobile(side(4, t), side(2, u))
return (t, u, v) |
def is_weight(w):
"""Whether w is a weight, not a mobile."""
return is_leaf(w)
def sides(m):
"""Select the sides of a mobile."""
return branches(m)
def end(s):
"""Select the mobile or weight hanging at the end of a side."""
return branches(s)[0]
def length(s):
"""Select the length of a side.... | The function `balanced(m)` checks if a mobile (tree structure) is balanced by recursively verifying two conditions: (1) all sub-branches are themselves balanced, and (2) the torque (length × total weight) on the left and right sides of each branch are equal. It returns `True` if both conditions hold, indicating the mob... | def balanced(m):
"""Return whether m is balanced.
>>> t, u, v = examples()
>>> balanced(t)
True
>>> balanced(v)
True
>>> w = mobile(side(3, t), side(2, u))
>>> balanced(w)
False
>>> balanced(mobile(side(1, v), side(1, w)))
False
>>> balanced(mobile(side(1, w), side(1, v)... |
def normalize(self, x):
self.mean = x.mean(axis=0)
self.range = x.max(axis=0) - x.min(axis=0)
return (x - self.mean) / self.range
def cost(self, x, y):
m = x.shape[0]
# Populate layer with data
self.forward_propagation(x)
# Calculate cost function with regulariza... | The code trains a model by iteratively adjusting weights using gradient descent. It normalizes input data, calculates the cost function, checks for convergence (stopping when cost changes fall below a threshold), computes gradients via backward propagation, and updates weights with a learning rate until convergence. | def train(self, x, y):
x = self.normalize(x)
last_cost = 0
while True:
new_cost = self.cost(x, y)
# Divergence condition
if abs(new_cost - last_cost) < self.epsilon:
break
last_cost = new_cost
derivatives = self.backwar... |
def setup_title(self):
self.title = PyDMLabel()
title_text = 'General Motion Calibration - {}'.format(macros.get("MAD"))
self.title.setText(title_text)
self.title.setStyleSheet("QLabel {\n"
" qproperty-alignment:AlignCenter;\n"
... | The main task of the code is to create and configure a user interface layout using PyQt/PySide. It sets up a vertical layout, adds a styled QFrame with sub-layouts, and integrates components like title, header, buttons, status indicators, and data visualization elements (degrees, coefficients, error metrics) to build a... | def setup_ui(self):
self.main_layout = QVBoxLayout()
self.setLayout(self.main_layout)
# Set up frame
self.frame = QFrame()
self.frame.setStyleSheet("QFrame#frame{\n"
" border: 1px solid: #FF17365D;\n"
"}")
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
... |
def ValidateOptions(self, setting, catagory):
match self.config:
case {"settings": {"background": str()}} if self.config[catagory][
setting
] in self.settingsfile[setting]:
pass
case _:
self.valueinput(setting, catagory, True)
d... | This function validates configuration settings for a Reddit-related application, ensuring required parameters like client credentials, username, password, and subreddit exist. It checks if the specified subreddit is valid, prompts for input if invalid, and confirms user intent for a TikTok TTS engine with session ID va... | def validatetoml(self) -> None:
self.ValidateOptions("background", "settings")
redditlogin = [
"client_id",
"client_secret",
"user_agent",
"username",
"password",
]
for i in redditlogin:
self.validatenooptions(i, "r... |
def closeConn():
try:
s.close() # close the connection
app.stop() # stop the app
except socket.error as e:
logging.warning(str(e))
def refreshConn():
try:
logging.info("Refreshing connection")
closeConn() # close existing connection (if present)
startConn()... | This function handles menu button presses by executing specific actions based on the button's label. If the button is "Close", it calls closeConn(); if "Refresh", it calls refreshConn(); if "About", it triggers aboutbox(). The main task is to dispatch user interface interactions to corresponding functions for menu-driv... | def mnuPress(button):
if button == "Close":
closeConn()
elif button == "Refresh":
refreshConn()
elif button == "About":
aboutbox() |
def get_same_route(des_lat,des_long):
conn=dbconnect()
# {des_lat:.6f}
cursor=conn.cursor()
# print(start_location)
destination_location=str(des_lat)+", "+str(des_long)
# SELECT * FROM `routes` where (((24.9085*10000) - CONVERT((slat*10000),INT)) <> 0);
# cursor.execute("SELECT * FROM `route... | The function `locate_user` identifies the nearest available ride routes by comparing the user's source and destination coordinates with stored route data. It checks for routes with similar destinations, calculates distances from the user's source to points along these routes, and selects the closest valid pickup points... | def locate_user(user_src_lat,user_src_long,user_dest_lat,user_dest_long):
# Checking for similar destination routes (dest long lat ,source long lat)
dest_data=get_same_route(user_dest_lat,user_dest_long)
# print(dest_data)
cmp_route_arr=[]
fare_type_selection=[]
if(dest_data):
for row in... |
def relative_authoritativeness(case, CB):
n_a = n_agreement(case, CB)
n_d = n_disagreement(case, CB)
return n_a / (n_a + n_d)
def absolute_authoritativeness(case, CB):
n_a = n_agreement(case, CB)
return n_a / len(CB)
def product_authoritativeness(case, CB):
rels = relative_authoritativeness(case... | This function determines and returns the authoritativeness score of a case based on the specified method (relative, absolute, product, or harmonic) by delegating to corresponding calculation functions. It raises an error for unsupported methods. | def alpha(case, CB, method):
if method == "relative":
return relative_authoritativeness(case, CB)
elif method == "absolute":
return absolute_authoritativeness(case, CB)
elif method == "product":
return product_authoritativeness(case, CB)
elif method == "harmonic":
return ... |
def create_employee_leads_leaderboard_data(self, employee, start_date=False, end_date=False):
logger = logging.getLogger("Lead Debug: ")
month_dict = actions_common.get_month_list()
# Domains for searching leads and admissions
lead_domain = [('leads_assign', '=', employee.id)]
a... | The function retrieves and compiles dashboard data, including employee performance metrics (qualitative/quantitative), lead sources, conversion rates, and organizational hierarchy. It processes input dates, fetches data from models like sales.tracker and hr.department, organizes results with color-coded visualizations,... | def retrieve_dashboard_data(self, start_date=False, end_date=False, manager_id=False):
rgba_colors = ['rgba(178, 56, 154, 0.75)', 'rgba(57, 141, 244, 0.52)', 'rgba(61, 14, 226, 0.88)',
'rgba(154, 29, 178, 0.51)', 'rgba(126, 101, 181, 0.05)', 'rgba(21, 80, 20, 0.70)',
... |
def on_init(self):
pygame.init()
pygame.font.init()
self.display_surf = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)
self.running = True
self.font = pygame.font.Font(pygame.font.get_default_font(), 12)
self.sprites = [
Sprite("images... | The code defines the main execution loop of a game or application. It initializes the system, runs a loop processing events, updating logic, and rendering frames while `self.running` is True, then cleans up resources. The loop terminates if initialization fails or when `self.running` is set to False during execution. | def on_execute(self):
if self.on_init() == False:
self.running = False
while( self.running ):
for event in pygame.event.get():
self.on_event(event)
self.on_loop()
self.on_render()
self.on_cleanup() |
def __optimization_model(self):
model = LpProblem("MTRS", LpMaximize)
# Acquire decision variables for x and y
data_decision_variables_x, data_decision_variables_y = self.__decision_data_definition()
# Build the objective function
objective_function = lpSum(data_decision_variables_x)
mode... | The main task of the code is to implement the MTRS algorithm by processing optimization model results. It thresholds request values (x) to binary values, groups associated data items (y) into structured Q entries, and returns the processed Q structure. The algorithm filters data based on maximum request values, transfo... | def __mtrs(self):
if not BENCHMARK:
print(Fore.GREEN + "Performing the MTRS Algorithm" + Style.RESET_ALL)
model, status = self.__optimization_model()
x, y = self.__preprocess_model_results(model)
# n <- max(x_i)
n = -1
for request in x:
try:
if request["value"] > n:... |
def __mtrs(self):
if not BENCHMARK:
print(Fore.GREEN + "Performing the MTRS Algorithm" + Style.RESET_ALL)
model, status = self.__optimization_model()
x, y = self.__preprocess_model_results(model)
# n <- max(x_i)
n = -1
for request in x:
try:
if request["value"] > n:... | The main task of the code is to schedule data requests for broadcasting by first applying the MTRS algorithm to select a maximum throughput request set (Q), then pruning it if the calculated transmission time exceeds a threshold (delta) using a heuristic. It subsequently optimizes Q for latency via MLRO to generate a f... | def __scheduler(self):
if not self.broadcast:
# Apply the MTRS to get a maximum throughput request set Q
Q = self.__mtrs()
# Print Q for debuging purposes
if DEBUG:
print(json.dumps(Q, indent=2))
# Calculate T(Q)
time_to_send = self.__time_to_send_requests(Q)
# ... |
def check_collection_name(self, collection_name):
try:
return self.mongodb[collection_name]
except Exception as e:
raise Exception(f"Wrong collection name or db connection:: {e}")
def scrape_game_odds(self, game_overview_url: str) -> GameDetailedOdds:
"""
FUTURE G... | This function extracts comprehensive details for a future sports game, including odds, past match data (head-to-head, stats, events), and standings. It navigates to a game URL, scrapes structured data, and compiles it into a FutureGameDetails object. Optional MongoDB storage and customizable data depth (e.g., last 5 ga... | def get_future_game_details(
self,
game_overview_url: str,
odds=True,
past_games="last_5", past_games_details=True, past_games_odds=True, past_games_events=True, past_games_stats=True,
current_standings=True,
h2h_past_games="last_10", # n-past g... |
def setaxis(lim=2):
x1=-lim
x2=lim
y1=-lim
y2=lim
z1=-lim
z2=lim
ax.set_xlim3d(x1,x2)
ax.set_ylim3d(y1,y2)
ax.set_zlim3d(z1,z2)
ax.view_init(elev=30,azim=40)
ax.grid(True)
def ppp(d1,d2,d3):
t0=np.eye(4)
t01=trasz(d1)@rotax(-90)
t12=trasz(d2)@rotax(-90)@rotay(90)
... | The main task of the code is to animate a 3D plot by incrementally varying parameters n1, n2, and n3 in separate loops. Each loop updates the plot by clearing the axes, setting the coordinate system, generating data with ppp(), and rendering the frame with dibujar(). The animation progresses sequentially through each p... | def animppp(d1,d2,d3):
n1=0
n2=0
n3=0
while n1<d1+0.01:
ax.cla()
setaxis(10)
ppp(n1,n2,n3)
n1=n1+0.2
dibujar()
while n2<d2+0.01:
ax.cla()
setaxis(10)
ppp(n1,n2,n3)
n2=n2+0.2
dibujar()
while n3<d3+0.01:
ax.c... |
def setaxis(lim=2):
x1=-lim
x2=lim
y1=-lim
y2=lim
z1=-lim
z2=lim
ax.set_xlim3d(x1,x2)
ax.set_ylim3d(y1,y2)
ax.set_zlim3d(z1,z2)
ax.view_init(elev=30,azim=40)
ax.grid(True)
def rpp(t1,d2,d3):
t0=np.eye(4)
t01=rotaz(t1)
t12=trasz(d2)
t23=rotay(90)@trasz(d3)
... | The main task of the code is to animate a 3D plot by iteratively varying parameters n1, n2, and n3 over specified ranges. It clears the plot, sets axes, updates the 'rpp' function with current parameter values, and redraws the plot in each iteration. The animation progresses by incrementing n1 in steps of 5, then n2 an... | def animrpp(t1,d2,d3):
n1=0
n2=2
n3=1
while n1<t1+0.01:
ax.cla()
setaxis(5)
rpp(n1,n2,n3)
n1=n1+5
dibujar()
while n2<d2+0.01:
ax.cla()
setaxis(5)
rpp(n1,n2,n3)
n2=n2+0.2
dibujar()
while n3<d3+0.01:
ax.cla()... |
def setaxis(lim=2):
x1=-lim
x2=lim
y1=-lim
y2=lim
z1=-lim
z2=lim
ax.set_xlim3d(x1,x2)
ax.set_ylim3d(y1,y2)
ax.set_zlim3d(z1,z2)
ax.view_init(elev=30,azim=40)
ax.grid(True)
def rrp(t1,t2,d3):
t0=np.eye(4)
t01=rotaz(t1)
t12=trasz(5)@rotay(90)@rotaz(90)@rotaz(t2)
... | This code animates a 3D plot by incrementally varying parameters n1, n2, and n3 over specified ranges. It clears the plot, sets axes, draws an RRP (likely a 3D model or graph), and updates the display in loops. Each loop iterates through n1, n2, and n3 with distinct step sizes (5, 5, 0.2) to visualize changes in the pl... | def animrrp(t1,t2,d3):
n1=0
n2=0
n3=1
while n1<t1+0.01:
ax.cla()
setaxis(5)
rrp(n1,n2,n3)
n1=n1+5
dibujar()
while n2<t2+0.01:
ax.cla()
setaxis(5)
rrp(n1,n2,n3)
n2=n2+5
dibujar()
while n3<d3+0.01:
ax.cla()
... |
def setaxis(lim=2):
x1=-lim
x2=lim
y1=-lim
y2=lim
z1=-lim
z2=lim
ax.set_xlim3d(x1,x2)
ax.set_ylim3d(y1,y2)
ax.set_zlim3d(z1,z2)
ax.view_init(elev=30,azim=40)
ax.grid(True)
def rrr(t1,t2,t3):
t0=np.eye(4)
t01=rotaz(t1)
t12=trasz(4)@rotax(90)@rotaz(t2)
t23=trasx... | This code animates a 3D plot by sequentially varying parameters n1, n2, and n3. It clears the plot, resets the axis, updates the visualization using the rrr function with current parameter values, and redraws the frame in each loop iteration. The animation progresses by incrementing each parameter by 5 until reaching t... | def animrrr(t1,t2,t3):
n1=0
n2=0
n3=0
while n1<t1+0.01:
ax.cla()
setaxis(5)
rrr(n1,n2,n3)
n1=n1+5
dibujar()
while n2<t2+0.01:
ax.cla()
setaxis(5)
rrr(n1,n2,n3)
n2=n2+5
dibujar()
while n3<t3+0.01:
ax.cla()
... |
def setaxis(lim=2):
x1=-lim
x2=lim
y1=-lim
y2=lim
z1=-lim
z2=lim
ax.set_xlim3d(x1,x2)
ax.set_ylim3d(y1,y2)
ax.set_zlim3d(z1,z2)
ax.view_init(elev=30,azim=40)
ax.grid(True)
def rrr(t1,t2,t3):
t0=np.eye(4)
t01=rotaz(t1)
t12=trasz(4)@rotax(90)@rotaz(t2)
t23=trasx... | The main task of the code is to update a visualization by clearing the current plot, applying new parameter values from sliders (n1, n2, n3), executing a processing function (rrr), and redrawing the updated graph using dibujar(). It dynamically refreshes the plot based on user inputs. | def update(val):
ax.cla()
setaxis(10)
n1=sn1.val
n2=sn2.val
n3=sn3.val
rrr(n1,n2,n3)
dibujar() |
def setaxis(lim=2):
x1=-lim
x2=lim
y1=-lim
y2=lim
z1=-lim
z2=lim
ax.set_xlim3d(x1,x2)
ax.set_ylim3d(y1,y2)
ax.set_zlim3d(z1,z2)
ax.view_init(elev=30,azim=40)
ax.grid(True)
def ppp(d1,d2,d3):
t0=np.eye(4)
t01=trasz(d1)@rotax(-90)
t12=trasz(d2)@rotax(-90)@rotay(90)
... | The main task of the code is to animate a 3D plot by incrementally updating parameters n1, n2, and n3 along three axes. It clears the plot, resets the axis, updates the visualization with ppp() at each step, and redraws the frame using dibujar() in a loop until each parameter reaches its respective threshold (d1, d2, d... | def animppp(d1,d2,d3):
n1=0
n2=0
n3=0
while n1<d1+0.01:
ax.cla()
setaxis(10)
ppp(n1,n2,n3)
n1=n1+0.2
dibujar()
while n2<d2+0.01:
ax.cla()
setaxis(10)
ppp(n1,n2,n3)
n2=n2+0.2
dibujar()
while n3<d3+0.01:
ax.c... |
def setaxis(lim=2):
x1=-lim
x2=lim
y1=-lim
y2=lim
z1=-lim
z2=lim
ax.set_xlim3d(x1,x2)
ax.set_ylim3d(y1,y2)
ax.set_zlim3d(z1,z2)
ax.view_init(elev=30,azim=40)
ax.grid(True)
def rpp(t1,d2,d3):
t0=np.eye(4)
t01=rotaz(t1)
t12=trasz(d2)
t23=rotay(90)@trasz(d3)
... | The code animates a 3D plot by iteratively varying parameters n1, n2, and n3 within specified ranges (t1, d2, d3). It clears the plot, sets axis limits, calls a plotting function `rpp()` with current parameters, and redraws the frame in each loop iteration. The animation progresses by incrementing n1 in steps of 5, n2 ... | def animrpp(t1,d2,d3):
n1=0
n2=2
n3=1
while n1<t1+0.01:
ax.cla()
setaxis(5)
rpp(n1,n2,n3)
n1=n1+5
dibujar()
while n2<d2+0.01:
ax.cla()
setaxis(5)
rpp(n1,n2,n3)
n2=n2+0.2
dibujar()
while n3<d3+0.01:
ax.cla()... |
def setaxis(lim=2):
x1=-lim
x2=lim
y1=-lim
y2=lim
z1=-lim
z2=lim
ax.set_xlim3d(x1,x2)
ax.set_ylim3d(y1,y2)
ax.set_zlim3d(z1,z2)
ax.view_init(elev=30,azim=40)
ax.grid(True)
def rrp(t1,t2,d3):
t0=np.eye(4)
t01=rotaz(t1)
t12=trasz(5)@rotay(90)@rotaz(90)@rotaz(t2)
... | The code animates a function 'rrp' by incrementally varying parameters n1, n2, and n3 over specified ranges (t1, t2, d3). It clears the plot, sets axes, updates the function with current parameters, and redraws repeatedly. Each parameter is incremented in steps (5 for n1/n2, 0.2 for n3) to create a dynamic visualizatio... | def animrrp(t1,t2,d3):
n1=0
n2=0
n3=1
while n1<t1+0.01:
ax.cla()
setaxis(5)
rrp(n1,n2,n3)
n1=n1+5
dibujar()
while n2<t2+0.01:
ax.cla()
setaxis(5)
rrp(n1,n2,n3)
n2=n2+5
dibujar()
while n3<d3+0.01:
ax.cla()
... |
def setaxis(lim=2):
x1=-lim
x2=lim
y1=-lim
y2=lim
z1=-lim
z2=lim
ax.set_xlim3d(x1,x2)
ax.set_ylim3d(y1,y2)
ax.set_zlim3d(z1,z2)
ax.view_init(elev=30,azim=40)
ax.grid(True)
def rrr(t1,t2,t3):
t0=np.eye(4)
t01=rotaz(t1)
t12=trasz(4)@rotax(90)@rotaz(t2)
t23=trasx... | The code animates a 3D plot by incrementing parameters n1, n2, n3 in separate loops. Each loop clears the plot, sets axes, updates the plot with rrr() using current n values, and redraws it via dibujar(), creating a stepwise animation across three dimensions. | def animrrr(t1,t2,t3):
n1=0
n2=0
n3=0
while n1<t1+0.01:
ax.cla()
setaxis(5)
rrr(n1,n2,n3)
n1=n1+5
dibujar()
while n2<t2+0.01:
ax.cla()
setaxis(5)
rrr(n1,n2,n3)
n2=n2+5
dibujar()
while n3<t3+0.01:
ax.cla()
... |
def setaxis(lim=2):
x1=-lim
x2=lim
y1=-lim
y2=lim
z1=-lim
z2=lim
ax.set_xlim3d(x1,x2)
ax.set_ylim3d(y1,y2)
ax.set_zlim3d(z1,z2)
ax.view_init(elev=30,azim=40)
ax.grid(True)
def scara(t1,t2,d3,t4):
t0=np.eye(4)
t01=rotaz(t1)@trasz(4)
t12=trasx(4)
t23=rotaz(t2)@t... | This code animates a SCARA robot's motion by sequentially adjusting joint parameters. It increments each joint angle (n1, n2, n3, n4) in separate loops, updating the robot's configuration and redrawing the plot for each step. The 'scara' function likely calculates the robot's end-effector position, while 'dibujar' rend... | def animscara(t1,t2,d3,t4):
n1=0
n2=0
n3=1
n4=0
while n1<t1+0.01:
ax.cla()
setaxis(5)
scara(n1,n2,n3,n4)
n1=n1+5
dibujar()
while n2<t2+0.01:
ax.cla()
setaxis(5)
scara(n1,n2,n3,n4)
n2=n2+5
dibujar()
while n3<d3+... |
def setaxis(lim=2):
x1=-lim
x2=lim
y1=-lim
y2=lim
z1=-lim
z2=lim
ax.set_xlim3d(x1,x2)
ax.set_ylim3d(y1,y2)
ax.set_zlim3d(z1,z2)
ax.view_init(elev=30,azim=40)
ax.grid(True)
def cobras800(t1,t2,d3,t4):
t0=np.eye(4)
t01=rotaz(t1)@trasz(342)
t12=trasx(425)
t23=rot... | The function animates a 3D model (cobras800) by sequentially varying parameters n1, n2, n3, and n4 in steps of 5, updating the plot each time. It clears the axis, resets the view, and redraws the model with adjusted parameters to create a dynamic visualization. The loops run until each parameter reaches its respective ... | def animcobras800(t1,t2,d3,t4):
n1=0
n2=0
n3=1
n4=0
while n1<t1+0.01:
ax.cla()
setaxis(1000)
cobras800(n1,n2,n3,n4)
n1=n1+5
dibujar()
while n2<t2+0.01:
ax.cla()
setaxis(1000)
cobras800(n1,n2,n3,n4)
n2=n2+5
dibujar()... |
def setaxis(lim=2):
x1=-lim
x2=lim
y1=-lim
y2=lim
z1=-lim
z2=lim
ax.set_xlim3d(x1,x2)
ax.set_ylim3d(y1,y2)
ax.set_zlim3d(z1,z2)
ax.view_init(elev=30,azim=40)
ax.grid(True)
def motoman(tb,t1a,t2a,t3a,t4a,t5a,t6a,t7a,t1b,t2b,t3b,t4b,t5b,t6b,t7b):
T0=np.eye(4)
Ti=rotaz(t... | The code animates a robotic arm by incrementing each joint's position (n1a to n7a, n1b to n7b, and nb) in separate loops, updating the display with `setaxis` and `dibujar` at each step. Parameters t1a to t7a, t1b to t7b, and tb define target positions for joints, with the arm moving in 5-unit increments until reaching ... | def animur5(tb,t1a,t2a,t3a,t4a,t5a,t6a,t7a,t1b,t2b,t3b,t4b,t5b,t6b,t7b):
nb=0
n1a=0
n2a=0
n3a=0
n4a=0
n5a=0
n6a=0
n7a=0
n1b=0
n2b=0
n3b=0
n4b=0
n5b=0
n6b=0
n7b=0
while n1a<t1a+0.01:
ax.cla()
setaxis(15)
motoman(nb,n1a,n2a,n3a,n4a,n5... |
def setaxis(lim=2):
x1=-lim
x2=lim
y1=-lim
y2=lim
z1=-lim
z2=lim
ax.set_xlim3d(x1,x2)
ax.set_ylim3d(y1,y2)
ax.set_zlim3d(z1,z2)
ax.view_init(elev=30,azim=40)
ax.grid(True)
def IRB1600(t1,t2,t3,t4,t5,t6):
t0=np.eye(4)
t01=rotaz(t1)#
t12=trasz(486.5)@rotax(-90)#
... | This function animates the movement of an IRB1600 robotic arm by sequentially incrementing each joint angle (n1-n6) in 5-unit steps, updating the 3D visualization for each joint's motion. It clears the plot, resets axes, and redraws the robot's configuration at each step to simulate real-time animation of the arm's mot... | def animIRB1600(t1,t2,t3,t4,t5,t6):
n1=0
n2=0
n3=0
n4=0
n5=0
n6=0
while n1<t1+0.01:
ax.cla()
setaxis(1500)
IRB1600(n1,n2,n3,n4,n5,n6)
n1=n1+5
dibujar()
while n2<t2+0.01:
ax.cla()
setaxis(1500)
IRB1600(n1,n2,n3,n4,n5,n6)
... |
def setaxis(lim=2):
x1=-lim
x2=lim
y1=-lim
y2=lim
z1=-lim
z2=lim
ax.set_xlim3d(x1,x2)
ax.set_ylim3d(y1,y2)
ax.set_zlim3d(z1,z2)
ax.view_init(elev=30,azim=40)
ax.grid(True)
def IRB1600(t1,t2,t3,t4,t5,t6):
t0=np.eye(4)
t01=rotaz(t1)#
t12=trasz(486.5)@rotax(-90)#
... | The code updates a graphical table by clearing the plot, retrieving slider values, computing a matrix using the IRB1600 robot model, and displaying rounded results in a 4x4 grid. | def update(val):
ax.cla()
setaxis(1000)
n1=sn1.val
n2=sn2.val
n3=sn3.val
n4=sn4.val
n5=sn5.val
n6=sn6.val
MTH=IRB1600(n1,n2,n3,n4,n5,n6)
valores=[n1,n2,n3,n4,n5,n6]
#robot.MoveJ(valores)
x=0
y=0
while x<4:
while y<4:
tabla._cells[(x,y)]._text.s... |
def add():
'''adds two numbers'''
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
print(f"The sum of {num1} and {num2} is {num1 + num2}")
def subtract():
'''subtracts two numbers'''
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
pr... | The code provides a menu-driven calculator that repeatedly takes user input to perform mathematical operations like addition, subtraction, multiplication, division, exponentiation, square root, cube root, factorial, and converting numbers to words, with error handling for invalid inputs and an option to exit. | def main():
while True:
# Taking input from the user
try:
select = int(input("Please select operation -\n"
"1. Add\n"
"2. Subtract\n"
"3. Multiply\n"
"4. Divide\n"
"5. Exponentation\n"
"6. Squ... |
def load_data(file_path): # Function that loads the txt data as an 2D array
with open(file_path, 'r') as data:
data = np.genfromtxt(file_path, delimiter=' ')
return data
def run_k_means(data, dimension):
run = 0
r = input("Please enter the number of times to run K-Means:\n")
r = int(r)
... | The main task of the code is to apply K-means clustering to both 2D data and 3D images. It loads 2D data, runs K-means three times with 2 clusters, then loads two 3D images, displays them, and applies K-means twice each with 3 clusters, likely for compression or segmentation. The repeated calls suggest testing or param... | def main():
# 2D
data = load_data(data_path)
run_k_means(data, 2)
run_k_means(data, 2)
run_k_means(data, 2)
# 3D
img1 = load_image(img_path1)
img2 = load_image(img_path2)
show(img1, "Original")
run_k_means(img1, 3)
run_k_means(img1, 3)
show(img2, "Original")
run_k_... |
def set_action(self):
assert self.player, "Cannot set actions on non-defined Player"
_exit = QAction('Exit', self)
_exit.setShortcut('Ctrl+Q')
_exit.setStatusTip('Exit application')
_exit.triggered.connect(self.closeEvent)
_save = QAction('Save config', self)
_sa... | The code initializes a class instance by setting up actions, widgets, initial values, and configuring a window using a regex file path parsed from a configuration. It prepares the GUI components and loads configuration settings for proper functionality. | def init(self):
self.set_action()
self.set_widgets()
self.init_values()
self.config_window.init(regex_file_path=self.config.parser_config) |
def _read_default_config(self) -> ConfigParser:
configuration = ConfigParser()
configuration.read(self.DEFAULT_CONFIG_PATH)
return configuration
def _read_user_config(self, config: ConfigParser) -> ConfigParser:
if not os.path.isdir(self.USER_CONFIG_DIR_PATH):
self._logger.d... | The code reads configuration settings from the file system, prioritizing user-defined configurations in ~/.cracker/ over default settings. It first loads default configurations using `_read_default_config`, then checks for a user-specific config directory. If found, it merges the user config with defaults via `_read_us... | def read_config(self) -> Dict[str, Any]:
"""Reads configuration from file system.
Firstly checks whether there are any user defined config in ~/.cracker/.
If config isn't there then it takes the default.
"""
# Check defaults
self._default_config = config = self._... |
def random_monster() -> int:
monster = random.randint(1, 2)
return monster
def is_combat_over(slime: Slime, goblin: Goblin) -> bool:
if slime.health < 1 or goblin.health < 1:
return True
else:
return False
def mage_slime_combat(player: Player, slime: Slime, slime_choice: str) -> None:
... | The function `combat_func` simulates a turn-based combat scenario where a player (Mage or Knight) fights a randomly selected monster (slime or goblin). It uses class-specific combat logic, checks for player death, and rewards the player with potions, level-ups, and stat updates upon victory. The loop continues until co... | def combat_func(player: Player,slime_choice: str, goblin_choice: str) -> None:
slime = Slime(70)
goblin = Goblin(70)
monster = random_monster()
while not is_combat_over(slime, goblin):
if player.p_class == "Mage":
if monster == 1:
print("You are fighting... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.