dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def solution_to_pst(solution):
# P N B R Q K
solution_pst = numpy.asarray(solution).reshape(6, 64)
global pawnEvalBlack
global knightEvalBlack
global bishopEvalBlack
global rookEvalBlack
global queenEvalBlack
global knightEvalBlack
pawnEvalBlack = list(reversed(solution_pst[0])... | The code evaluates a chess-playing strategy's performance using a genetic algorithm. It simulates games, assesses board positions with Stockfish, and calculates a fitness score based on game outcomes (checkmates, draws, losses) and move count. Higher scores reward checkmates, penalize losses, and balance move efficienc... | def fitness_func(solution, solution_idx):
solution_to_pst(solution)
total_score = 0
board = chess.Board()
number_of_moves = 0
while not board.is_game_over() and number_of_moves < 80:
board.push(next_move(get_depth(), board, debug=False))
# # print every 10th move
... |
def next_move(depth: int, board: chess.Board, debug=True) -> chess.Move:
"""
What is the next best move?
"""
debug_info.clear()
debug_info["nodes"] = 0
t0 = time.time()
move = minimax_root(depth, board)
debug_info["time"] = time.time() - t0
if debug == True:
print(f"info {d... | The code simulates three chess games, evaluates outcomes using a depth-based move generator and an evaluation function, adjusts a total score based on wins and board evaluations, and returns a calculated value derived from the score. | def start():
"""
Start the command line user interface.
"""
total_score = 0
for i in range(3):
board = chess.Board()
number_of_moves = 0
while not board.is_game_over() or number_of_moves < 100:
board.push(next_move(get_depth(), board, debug=False))
... |
def getLastLayer(objectList):
"""Return the last menu layer from objectList"""
temp = 2
for item in objectList:
if item.layer > temp and item.layer != 9:
temp = item.layer
return temp
def updateList(objectList, boxList, backOrder, warehouse, lastGraph, pageNum):
"""Called when ac... | This function checks mouse clicks on UI elements to trigger actions like adding/removing boxes, updating lists, navigating pages, or handling buttons in a warehouse management system. It processes interactions with objects such as "add," "remove," "list," "graph," and "backOrder" to modify the interface, data structure... | def checkClicks(objectList, boxList, backOrder, warehouse, mousePos, lastAction, lastGraph, pageNum):
"""Checks what mouse clicked on"""
for item in objectList:
if pygame.Rect.collidepoint(item.rect, mousePos[0], mousePos[1]):
if item.type == "add":
createMenu.removeMenu(obje... |
def find_min_dist_and_angle_veh(bb, dr, veh_feats, norm_factor=10):
if len(veh_feats) < 1:
return 0, 0, 0, -1
dist_angle_speed = [
(np.linalg.norm(bb[:2] - veh[0]), angle_between(dr, veh[1].reshape(2)), veh[2], veh[3]) for veh in veh_feats]
dist_min, angle_min, speed_min, v_id_min = min(dist... | The code extracts features related to pedestrian-vehicle interactions (v2p), environmental context (semantics, signals), and crossing status for each pedestrian. It computes metrics like nearest vehicle distance/angle, group proximity, crosswalk proximity, 2D joint orientations, semantic labels, and crossing indicators... | def extract_v2p_and_env(ped_to_analyze, ped_results, veh, frames_ped_veh, semantics, signals):
for ped_id in tqdm(ped_to_analyze):
num_group, d_veh, a_veh, s_veh, c_veh, d_cw, a_cw, sem, sig, cros, head, body, head_o, body_o \
= [], [], [], [], [], [], [], [], [], [], [], [], [], []
for ... |
def update_dicts(list_of_same_ids, detection_results, frames_ped_veh, height_factor=1.7, norm_factor=5, treat_cam=True):
keys_to_deal = ['frames', 'bboxes', 'joints_3d']
if treat_cam:
keys_to_deal.append('pred_cam')
list_of_same_ids = list(sorted(set(list_of_same_ids)))
ref_id = list_of_same_ids... | The function processes detection data by updating pedestrian and vehicle results, filters out failed updates, extracts environmental interactions, and saves cleaned results to CSV files. It iterates through lists, adjusts parameters for different object types, and ensures only successful entries are retained for furthe... | def update_all_and_save(list_of_list, detections, signals, base_name):
ped_results = detections['ped_results']
veh = detections['veh']
frames_ped_veh = detections['frames_ped_veh']
semantics = detections['semantics']
failed_ped, failed_veh = [], []
for l in list_of_list:
... |
def toArrayCoords(i):
return i-1
def toNumCoords(c):
return ord(c.lower()) - 96
def rankToArrayCoords(i):
return 8-i
def processMove(movestring, board):
# convert c2c3 to 2,1 2, 2
x1 = toArrayCoords(toNumCoords(movestring[0]))
x2 = toArrayCoords(toNumCoords(movestring[2]))
y1 = rankToArrayC... | The main task of the code is to determine if a specified player's king ('black' or 'white') is in check on a given chessboard. It locates the king's position, then checks every opposing piece to see if any can legally move to the king's square using a move-processing function. If any such piece exists, it returns True ... | def checkForCheck(color, board):
# return true if color 'is in check'
if color != 'black' and color != 'white':
return('info', 'must pass black or white to checkForCheck')
# find the king
for col in 'abcdefgh':
for row in range(1, 9):
x = toArrayCoords(toNumCoords(col))
... |
def _checkTimeList(time):
body = _getS3Object('TimeList.json')
list = json.loads(body)
for row in list:
if (time.hour == int(row['hour'])):
for k,v in row.iteritems():
if (k != 'hour' and k != 'tweet' and time.minute == v):
return True
return False... | The code's main task is to check if the current time in Japan Standard Time falls within a predefined schedule. If true, it retrieves a tweet's text and linked images, uploads the images to Twitter, and posts the tweet with media. If not, it returns the check result. The function handles scheduled tweet automation with... | def lambda_handler(event, context):
ret = {}
jst = pytz.timezone('Asia/Tokyo')
jst_now = datetime.now(jst)
flag = _checkTimeList(jst_now)
if (flag):
tweet = _pickupTweet()
images = _getImages(tweet["link"])
media_ids = _uploadTweetImage(images)
status = _tweet(tweet[... |
def drop_tables():
print("\n\033[1m" + style.BRIGHT_RED + "DROPPING TABLES..." + style.RESET + "\033[0m")
try:
with connection.cursor() as cursor:
cursor.execute(f"DROP TABLE IF EXISTS phase_two_item CASCADE")
cursor.execute(f"DROP TABLE IF EXISTS phase_two_comment CASCADE")
... | The code initializes a database by dropping existing tables, creating new ones, generating fake data, and returning a success response indicating the database was initialized. | def init_db(request):
drop_tables()
create_tables()
gen_fake_data()
return Response({"message": "Database initialized successfully"}, status=status.HTTP_201_CREATED) |
def getEWGs(mol):
EWGindices = []
for key in groups:
patt = Chem.MolFromSmarts(groups[key])
EWGindices.append(mol.GetSubstructMatches(patt))
print(EWGindices)
return set(flatten(EWGindices))
def BFestimate(m, index, ewgids, parent, basic=False): #breadth-first algorithm
searched = [i... | The code estimates molecular properties by identifying functional groups (COOH, N) and applying BFestimate with specific parameters. It excludes certain atoms (e.g., amide Ns) and calculates values for remaining nitrogens, returning the modified molecule. | def estimateMolecule(m):
EWGindices = getEWGs(m)
COOHindices = []
for x in m.GetSubstructMatches(Chem.MolFromSmarts(acids["COOH_al"])):
COOHindices.append(x[1])
for i in COOHindices:
print(BFestimate(m, i, EWGindices, 4.8))
excludeindices = [] #amide Ns, etc.
for e in ... |
def build_estimate(df, col_to_predict: str, fileName: str, max_epoch_number=21):
best_rmse = 2000
best_mape = 0.3
best_epoch = 0
min_epoch = 2
best_fit_model = None
if IS_DEBUG_MODE_ON:
max_epoch_number = min_epoch+1
for i in range(min_epoch, max_epoch_number):
x_train, y_tra... | The main task of the code is to build and evaluate a machine learning model for time-series prediction. It trains the model using historical data, splits data into pre- and post-delimiter periods, generates predictions for both intervals, and visualizes results if debug mode is enabled. The function also plots final pr... | def MAIN_build_and_score_ml_model_core(df: DataFrame, col_to_predict: str, fileName: str):
best_model = build_estimate(df, col_to_predict, fileName)
x_train_before, y_train_before, x_test_before, y_test_before, scaler_before = prepare_data_3d(df, col_to_predict, start_date, delimiter_date)
x_train_after, y_... |
def get_model(self):
if not self.model:
raise Exception("Model not loaded")
return self.model
def get_sequences_from_text(self, texts: List[str]):
tokenizer = self.get_tokenizer()
sequences = tokenizer.texts_to_sequences(texts)
return sequences
def get_input_from_sequ... | The function predicts labels for a given text query using a preloaded model, processes prediction results into labeled outputs, optionally includes the top predicted label, and returns structured results in JSON format if specified. | def predict_text(self, query: str, include_top=True, encode_json=True):
model = self.get_model()
sequences = self.get_sequences_from_text([query])
x_input = self.get_input_from_sequences(sequences)
preds_array = model.predict(x_input)[0]
preds = [self.get_label_pred(i, x) for i, ... |
def check_downloading(self):
"""Check the status of any episodes that are currently being downloaded."""
torrents = requests.get(f'{Constants.qbit_url}/api/v2/torrents/info').json()
if self.episodes_downloading:
for episode_number, magnet_link in self.episodes_downloading[:]:
... | The main task of the code is to initiate the download of episodes or an entire season by checking current download status, managing ongoing downloads, and determining whether to perform batch or individual downloads. It updates the user on progress, indicating completion if all episodes are downloaded or specifying the... | def start(self):
"""Start downloading episodes or the entire season."""
print('-'*80)
print(f'Looking into {self.name}')
if self.episodes_downloading:
self.check_downloading()
if self.airing:
self.check_currently_airing()
if self.episodes_to_down... |
def read_log():
config_file = 'lab6.config'
try:
with open(config_file) as f:
data = f.read()
header = re.findall(r'\[.*]', data)
content = re.findall(r'(.*)=(.*)', data)
if len(header) == 3:
liness = str(content[2]).split()[1][1:-2]
... | The code's main task is to execute a sequence of operations: first reading a log file via `read_log()`, then reading additional data with `read()`, and finally parsing the collected information using `parse()`. This workflow likely processes and analyzes log data for further use, such as generating reports or extractin... | def run():
read_log()
read()
parse() |
def datetime_test(date):
datetime_string = "%d/%b/%Y:%H:%M:%S %z"
return datetime.strptime(date, datetime_string)
def return_log_entry_object(line):
return LogEntry(line)
def list_log_entry_object():
list_log = []
for lines in read_log():
try:
list_log.append(LogEntry(lines))
... | The main task of the code is to parse a log entry string into objects, compare two parsed dates, and demonstrate handling of HTTP log data. It creates a log entry object, processes a log line into structured data, and checks date arguments using predefined functions. | def run():
first_date = datetime_test('23/Oct/2020:18:28:41 +0200')
second_date = datetime_test('24/Oct/2020:02:00:38 +0200')
My_line = '172.16.17.32 - - [18/Oct/2020:01:30:43 +0200] "GET /robots.txt HTTP/1.1" 404 196 "-" ' \
'"Mozilla/5.0 (compatible; SemrushBot/6~bl; +http://www.semrush.com/... |
def load_user_config() -> List[str]:
try:
if USER_CONFIG_FILE.is_file(): # pylint: disable=no-member
args = []
with open(USER_CONFIG_FILE, encoding="utf-8") as fp:
for line in fp:
line = line.strip()
if not line or line.startsw... | This code defines a command-line interface for downloading and processing media files (e.g., HLS streams) using ffmpeg. It parses arguments for input URLs, output paths, concurrency, batch processing, and logging. It validates inputs, handles user configurations, and executes either single-file downloads or batch opera... | def main() -> int:
user_config_options = [] if USER_CONFIG_DISABLED else load_user_config()
parser = ArgumentParser()
add = parser.add_argument
add("m3u8_url", help="the VOD URL, or the batch mode manifest file")
add(
"output",
nargs="?",
type=pathlib.Path,
default=N... |
def load(self):
self.maze = pygame.image.load('images/maze.png')
self.maze = pygame.transform.scale(self.maze, (maze_width, maze_height))
#Opening walls file, creating list with x and y coords of walls
with open("walls.txt", 'r') as file:
for yindex, line in enumerate(file):... | This code initializes a Pygame game environment by setting up the display, clock, game state, and essential game elements like walls, coins, and enemies. It loads assets, creates a player object at the loaded player position, spawns enemies, and prepares the game loop. The main task is to initialize all components requ... | def __init__(self):
self.screen = pygame.display.set_mode((width, height))
self.clock = pygame.time.Clock()
self.running = True
self.state = 'start'
self.cell_width =maze_width//cols
self.cell_height = maze_height//rows
self.walls = []
self.coins = []
... |
def search_method_3(file_name):
result = False
global totalguesses
# Start by reading the list of words into a Python list
f = open(file_name)
words = f.readlines()
f.close
# How many words are there
number_of_words = len(words)
## Cleans up the formatting so that it only look... | The main task of the code is to search for a password using multiple methods (methods 3, 4, and various iterations of methods 1 and 2) in sequence until the password is found. It measures the total time taken and the number of guesses made, then reports the results, including guesses per second, to evaluate the efficie... | def main(Input_Password):
Totalstarttime = time.time()
tests = 0
found_password = False
if not found_password:
found_password = search_method_3("passwords.txt")
if not found_password:
print("Method 3 did not work!")
found_password = search_method_4("passwords.txt")
if... |
def user(question) -> str:
user_input = input(question)
while not len(user_input) > 0:
user_input = input(question)
return user_input
def make_requests(self, user=False, number=1000) -> None:
result = requests.get(self.url())
print(f"Parsing data from {self.url()}..."... | The main task of the code is to prompt the user to choose between downloading a default set of 1000 Bible verses or a custom number, then execute corresponding requests based on input. It uses conditional logic to either call `make_requests()` with default parameters or user-specified values, followed by invoking the `... | def main(self):
print("Starting Script")
customised = self.user("Do you want the download the default 1000 verses? (y/n) ").casefold()
if re.match(r"(y|yes|yeah)", customised):
self.make_requests()
elif re.match(r"(n|no|nah)", customised):
print("1000 verses are a... |
def _choose_network(self):
setup = input("Load a pre-trained network(1) or train a network(2): ")
if setup == "1":
cust = input("Load latest(1) or specify network(2): ")
if cust == "1":
print("Loading network...")
self.nn.load_saved_network(load_la... | The code provides a menu-driven interface for interacting with a network. It allows users to test the network, visualize data, select a new network, or exit. The loop continuously prompts for input, executing corresponding methods based on user choices until the exit option is selected. | def run(self):
self._choose_network()
while True:
usr_input = input(
"Test the network(1), visualize the network(2), choose a new network(3) or quit(4): ")
if usr_input == "1":
self.test_network()
elif usr_input == "2":
... |
def _initialize_plots(self):
"""Initialize values for plotting
of loss and validation accuracy.
"""
self.loss_values = []
self.batch_values = []
self.validation_accuracy = []
plt.ion()
self.fig, (self.ax1, self.ax2) = plt.subplots(2, 1,
... | The main task of the code is to train a neural network using stochastic gradient descent by iterating over training data in batches, computing gradients, updating weights, tracking loss and validation accuracy, adjusting the learning rate per epoch, and optionally saving the trained network. It also initializes plots, ... | def train_network(self, save_network=True):
"""This is the main function in
training the neural network. For each
pass on the training data, it splits the data
into batches, computes gradients and updates weights
with stochastic gradient descent algorithm.
"""
... |
def parse(snailfish_num, depth=0, parent=None, side=None):
left,right = snailfish_num
result = SnailfishNumber(None, None, None, parent, side, depth)
if isinstance(left, int):
result.left = SnailfishNumber(left, None, None, result, left_side, depth+1)
else:
result.left = parse(left, depth+1, result, le... | The code processes a list of snailfish numbers by parsing each input, sequentially adding them using `add_snailfish_num`, and computing the final magnitude of the resulting sum. It initializes with the first parsed number, iterates through the rest, accumulates their sum, and returns the magnitude of the total. | def part1(input):
total = parse(input[0])
for next in map(parse, input[1:]):
total = reduce(add_snailfish_num(total, next))
return calc_magnitude(total) |
def add_snailfish_num(op1, op2):
parent = SnailfishNumber(None, op1, op2, None, None, 0)
op1.side = left_side
op2.side = right_side
op1.parent = parent
op2.parent = parent
stack = [parent.right, parent.left]
while stack:
current = stack.pop()
current.depth += 1
if current.left and current.r... | The code's main task is to add two snailfish numbers using `add_snailfish_num`, reduce the result according to snailfish rules (explosions/splits), and compute the magnitude of the final reduced number. | def calc_mag(num1, num2):
sum = add_snailfish_num(num1, num2)
return calc_magnitude(reduce(sum)) |
def parse_http_req(self, request):
headers = request.split('\r\n')
request_dict = dict()
self.log = '"{request}"'.format(request=headers[0])
request_info = headers[0].split()
if len(request_info) != 3:
raise Exception('400')
request_dict['METHOD'] = request_in... | This code handles HTTP requests via a socket connection in a loop. It receives data, parses HTTP requests, processes them with error handling, generates responses, logs results, and closes the socket when done. | def run(self):
while not self.close:
data = self.sock.recv(BUFF_SIZE)
if not data:
continue
code = '200'
request = None
try:
request = self.parse_http_req(str(data, 'utf-8'))
self.setup_timer(request)
... |
def is_filtered(bytes_, filtered):
for i in bytes_:
if i in filtered:
return True
return False
def get_settable_regs():
possible_regs = []
for i in regs64: # get settable regs
if i.pop or i.mov_imd_qwd and i.name != 'rsp':
possible_regs.append(i)
return poss... | The function `base_and` generates and returns an assembly "and" instruction (or alternative forms) for a register `reg`, ensuring it passes a filter check. It prioritizes specific `and` forms with masks (0xf000, 0xfffffffffffff000) or uses another register for the operation. If filtered, it attempts a shift-based equiv... | def base_and(reg, filtered):
if reg.name[-1] == 'x':
short_and = asm(f'and {reg.name[1:]}, 0xf000')
if not is_filtered(short_and, filtered):
return short_and
and_ = asm(f'and {reg.name}, 0xfffffffffffff000')
if not is_filtered(and_, filtered):
return and_
settable_r... |
def conn():
if args.LOCAL:
r = process([exe.path])
if args.DEBUG:
gdb.attach(r)
elif args.SSH_LOCAL:
session = ssh('asg','pwnable.kr', 2222, 'Mak1ng_shelLcodE_i5_veRy_eaSy')
r = session.process(["/home/asg/asg"])
gdb.attach(r)
else:
r = re... | The main task of the code is to generate and send a filtered shellcode to a remote service to extract a flag. It connects to the service, identifies forbidden bytes and the flag file location, constructs a shellcode that reads the flag from the identified file, and ensures the code avoids forbidden bytes while adhering... | def main():
global r
#while True:
r = conn()
SYSCALL = b"\x0f\x05"
############ SETUP ############
r.recv(1024)
r.sendline()
r.recvuntil(b'these are filtered set of bytes:')
r.recvline()
filtered = r.recvuntil(b'flag is inside this file: [', drop=True)
info(f"Filtered bytes... |
def geom_v(x1, x2, x3):
"""Compute normal and area of triangle element.
Args:
x1: Point 1 of triangle. (e, 3)
x2: Point 2 of triangle. (e, 3)
x3: Point 3 of triangle. (e, 3)
Returns:
n: normalized normal of triangle (e, 3)
A: area of triangle (e,)
"""
u = x2... | The function `BuildSystem_v` constructs matrices $ A $ and $ B $ for solving boundary integral equations, using either the Burton-Miller method or a dual-surface approach. It computes integral matrices (Lk, Mk, Nk) in batches from input geometry data, applies method-specific formulations (e.g., Burton-Miller's regulari... | def BuildSystem_v(k, elems_x1, elems_x2, elems_x3, type, method):
"""equation 4.17 & 4.18"""
rows = elems_x1.shape[0]
cols = elems_x1.shape[0]
p = (1. / 3.) * (elems_x1 + elems_x2 + elems_x3)
n_p, l_elem = geom_v(elems_x1, elems_x2, elems_x3)
p_on_q = np.eye(rows, dtype=np.dtype('bool'))
ba... |
def show_tool_edit():
"""
Display the tool editing menu.
:return: None
"""
print(' -- -- -- Tool EDITOR -- -- -- ')
print(' 0. Back')
print(' 1. Change Name')
print(' 2. Lend Tool')
print(' 3. Add/Remove from Collection')
print(' 4. Add to Category')
print(' 5. Sell')
pri... | The function 'tool_edit' provides a menu-driven interface to modify tool details (name, lendability, ownership). It executes actions like renaming, lending, adding to collections/categories, selling, or marking as returned, using parameters like username, barcode, and tool name to interact with associated functions bas... | def tool_edit(uname, barcode, tool_name, lendable):
"""
Gets input from the tool editing menu and executes appropriate command.
:param uname: username of the owner of the tool.
:param barcode: barcode of the tool.
:param tool_name: name of the tool.
:param lendable: lendability of the tool.
... |
def tools_by_cat():
"""
Prints the tools in a specific category.
:return: None
"""
os.system('cls')
global conn
cursor = conn.cursor()
# Get a list of all categories
sql = '''
SELECT "cat_name" FROM "category"
'''
cursor.execute(sql)
all_cats = cursor.fetchall() # lo... | The main task of the code is to display a tool menu for browsing options (View By Category, View By Collection, View All Tools) and execute corresponding commands based on user input. It runs in a loop, clears the screen, shows the menu, handles input validation, and triggers functions like tools_by_cat(), tools_by_col... | def browse_tools():
"""
Display the tool menu and executes appropriate command.
:return: None
"""
while True:
os.system('cls')
print(' -- -- -- ALL TOOL MENU -- -- -- ')
print(' 0. Exit')
print(' 1. View By Category')
print(' 2. View By Collection')
pr... |
def show_user_menu():
"""
Display the user menu.
:return: None
"""
print(' -- -- -- User Menu -- -- -- ')
print(' 0. Back')
print(' 1. Add Tool')
print(' 2. Edit Tool')
print(' 3. View your Tools')
print(' 4. View your Borrowed Tools')
print(' 5. View your Collections')
p... | The main task of the code is to display a user menu, handle input for tool management (add, edit, view), track borrowed tools, view collections, and receive recommendations. It loops until the user selects "Exit" (option 0), clearing the screen and executing corresponding functions like `add_tool`, `edit_tool`, or `vie... | def user_menu(uname, user_name):
"""
Gets input from the user on the user menu and execute appropriate command.
:param uname: username of user.
:param user_name: first name of user.
:return: None
"""
while True:
os.system('cls')
print('Hello,', user_name[0], user_name[1])
... |
def _modify(_text: str, _d: Dict[str, Union[str, Callable]]) -> str:
"""
Helper function to bulk modify a string
:param _text: the string to modify
:param _d: dictionary of match and replacement expressions
:return: returns the modified text
"""
for _k, _v in _d.i... | This code parses a TMD file into an HTML string by extracting blocks like 'extends', 'filters', and content, converting markdown-like syntax to HTML tags, handling custom template directives, and rendering the final HTML using Django's template engine with provided context variables. | def parse(self, context: Dict) -> str:
"""
Function to parse the tmd file into a html string
:param context: dictionary of context variables
:return: html string
"""
_txt = self._modify(self.raw, {
# r"\/\/.*?\n": r"\n",
r"(-\[.+?(?:\n|$))": r"-[\n... |
def vort500Plot(standaloneFig, ax=None):
if standaloneFig:
fig = plt.figure()
px = 1/plt.rcParams["figure.dpi"]
fig.set_size_inches(1920*px, 1080*px)
ax = plt.axes(projection=ccrs.LambertConformal())
ax.set_extent(axExtent, crs=ccrs.PlateCarree())
windsAtHeightPlot(500, F... | This function generates a 4-panel weather forecast plot with Lambert Conformal map projections, adding colorbars, titles, and custom layouts. It creates a 3x4 grid, adjusts spacing, plots atmospheric data (vorticity, isotachs, temperatures, RH), and saves the figure with metadata. | def fourPanelPlot():
fig = plt.figure()
px = 1/plt.rcParams["figure.dpi"]
fig.set_size_inches(1920*px, 1080*px)
gs = GridSpec(3, 4, figure=fig, width_ratios=[0.01, 1, 1, 0.01], height_ratios=[1, 1, 0.1])
gs.update(left=75/1920,right=1-(75/1920), top=.9925, bottom=0.01, wspace=0, hspace=0.02)
cax... |
def europeVort500Plot(standaloneFig, ax=None):
if standaloneFig:
fig = plt.figure()
px = 1/plt.rcParams["figure.dpi"]
fig.set_size_inches(1920*px, 1080*px)
ax = plt.axes(projection=ccrs.LambertConformal(central_longitude=5))
ax.set_extent(europeExtent, crs=ccrs.PlateCarree())... | The code generates a four-panel meteorological plot for Europe, creating subplots with Lambert Conformal projections to display 500 hPa vorticity, 250 hPa jet stream isotachs, 850 hPa temperatures, and 700 hPa relative humidity. It adds colorbars, sets titles, adjusts layout, and saves the image with metadata, using he... | def europeFourPanelPlot():
fig = plt.figure()
px = 1/plt.rcParams["figure.dpi"]
fig.set_size_inches(1920*px, 1080*px)
gs = GridSpec(3, 4, figure=fig, width_ratios=[0.01, 1, 1, 0.01], height_ratios=[1, 1, 0.1])
gs.update(left=75/1920,right=1-(75/1920), top=.9925, bottom=0.01, wspace=0, hspace=0.07)
... |
def sw_replace(sentence, num_stopwords):
new_sentence = ""
words = word_tokenize(sentence)
for i in range(len(words)):
space = " "
if words[i] in back_space:
space = ""
if i + 1 < len(words):
if words[i + 1] in front_space:
space = ""
e... | This code processes user search requests on text files (XML/JSON), analyzing content to count characters, words, sentences, and stopwords. It handles file deletion, searches for terms in documents, replaces text based on queries, and calculates similarity to suggest related terms. Results include statistics, modified t... | def search(request):
search_err = delete_msg = user_search = jsonfile = xmlfile = stem_search = nofile = ""
total_chars = total_words = total_sentences = total_searches = total_stopwords = 0
sim_word = []
set_words = set()
files = os.listdir(BASE_DIR + '/files')
if request.method == 'POST':
... |
def stem(sentence):
lemmas_sent = []
tagged_sent = pos_tag(sentence)
for tag in tagged_sent:
wordnet_pos = get_wordnet_pos(tag[1]) or wordnet.NOUN
lemmas_sent.append(wnl.lemmatize(tag[0], pos = wordnet_pos))
return lemmas_sent
def have_spe(word):
for x in spe_ch_list:
if x i... | This code handles search functionality in a web application. It processes user queries, performs text stemming, searches for matching documents in a database, and displays paginated results. If no exact match is found, it suggests similar terms using a similarity metric. It also supports statistical views showing word ... | def multiple_search(request):
show = gogo = 0
show_page = 1
search_err = user_search = file = ""
if 'page' in request.GET:
if request.GET.get('page').find('~') != -1:
user_search = request.GET['page'].split('~')[1]
if user_search != '': gogo = 1
if request.method == '... |
def getExcel():
global df, Threshold, percentile, col7, col8, col9, col10, OutputExcelFile, HedgedExcelFile
import_file_path = HedgedExcelFile
df_hedged = pd.read_excel(import_file_path)
col7 = df_hedged.iloc[:, [0]]
col8 = df_hedged.iloc[:, [1]]
col9 = df_hedged.iloc[:, [2]]
col10 = df_he... | The function initializes global variables with input parameters and processes Excel data by calling `getExcel()`, `getDeclineCurveData()`, and `create_excel()` to generate or update response data, ultimately returning the processed result stored in the global `Response` variable. | def setObjecABCValues(product, threshold, bc_mmscfg, gor, curveType, oilPrice, oilSD, gasPrice, gasSD, royalty, priceUC, fixedCost, indProdCost, oilProdCost, gasProdCost, costBelowPerc, indProdSD, excelFile, hedgedExcelFile):
global Response, Product, Threshold, BC_MMSCFG, GOR, CurveType, OilPrice, OilSD, GasPrice,... |
def save_data(self):
with open('clients_info', 'wb') as f:
pickle.dump([self.clients, self.nickNames, self.groupes], f)
def updata_member(self, group):
unames = group.members
obj = PACKET('GROUP_ADDED', group.admin)
obj.uname = group.admin
obj.group_name = group.name
... | The function creates a group if the group name is unique and members are valid. It checks if nicknames exist, are not blocked, and processes valid/invalid entries. If valid, it creates the group, updates data, and sends a confirmation; otherwise, it returns error messages for invalid names or blocked members. | def create_group(self, obj):
if obj.group_name not in self.groupes:
nickNames = obj.members
unames = []
valid_nickNames = []
invalid_nicknames = []
b_unames = []
for nickName in nickNames:
if nickName in self.nickNames:
... |
def rec_packet(self, conn):
while True:
l = conn.recv(10).decode('utf-8')
if l:
l = int(l)
while True:
packet = conn.recv(l)
if packet:
obj = pickle.loads(packet)
retur... | This function continuously listens for incoming packets on a connection, processes them based on their type by forwarding messages, managing groups, sending data, or stopping the client. It handles various packet types like individual/group messages, group creation, and registration details, with fallback logging for i... | def lisen_forever(self, conn):
while True:
obj = self.rec_packet(conn)
if obj.TYPE == 'I_MESSAGE':
self.froward_message(obj)
elif obj.TYPE == 'G_MESSAGE':
print('Groip mess here')
self.froward_message_group(obj)
elif... |
def rec_packet(self, conn):
while True:
l = conn.recv(10).decode('utf-8')
if l:
l = int(l)
while True:
packet = conn.recv(l)
if packet:
obj = pickle.loads(packet)
retur... | The main task of the code is to handle client requests by receiving packets, determining their type (e.g., REGISTER, LOGIN, LOGIN_REC), and delegating processing to the corresponding method. After handling one packet, the function exits immediately via the return statement. | def handle_client(self, conn):
while True:
obj = self.rec_packet(conn)
if obj.TYPE == 'REGISTER':
self.register_client(conn, obj)
elif obj.TYPE == 'LOGIN':
self.login_client(conn, obj)
elif obj.TYPE == 'LOGIN_REC':
s... |
def determineCandidateSplits(self, trainInst):
candidateSplit = []
if trainInst.empty:
return candidateSplit
for column in trainInst.columns[:-1]:
trainInst_sorted = trainInst.sort_values(by=str(column))
featureSplit = []
refLabel = trainInst_sorte... | This function recursively constructs a decision tree node by determining the best feature and threshold to split the training data, creating leaf nodes when splitting stops, and recursively building subtrees for each subset of data divided by the split. | def makeSubtree(self, trainInst):
candidateSplit = self.determineCandidateSplits(trainInst)
if self.canStopSplit(candidateSplit):
leafNode = Node(None, None, None, None, trainInst.iloc[0]["label"])
return leafNode
else:
feature, threshold, label = self.findBe... |
def df_from_phase_bson(filename, path):
"""
Create 2 Pandas DataFrames from bson file of phase variable. The phase bson files provided has 2 different dataframe in same file,
so it is necessary to separe them for the differen use of the variables
Parameters:
filename: name (string) of the b... | The function calculates linear regression parameters (slope, intercept, uncertainty, R-value) for the time/volume-volume curve during constant pressure phases in multiple files. It identifies regions of linearity, detects slope changes, and returns results for each file, including timestamps and indices of slope transi... | def time_volume_over_volume(filenames, path,slope_limit=2,starting_points=200,slope_points=20,figure=False):
"""
This function calculate the parameters and its uncertainty of the linear regression of time/volume- volume curve in the linear part (pressure constant)
It does it for all the target files in a di... |
def __add_trajectory(self, individual_id):
if individual_id not in self.trajectories:
trj = _Trajectory(individual_id, len(self.dataset_maps.timeslots))
self.trajectories[individual_id] = trj
def __add_visit(self, cell, time, trj_id, true_names=False, compact=False):
trj = self.t... | This code initializes a data structure to map trajectories and visits into a matrix, using either standard or compact coordinates. It processes input visit lists, constructs trajectory objects, populates a 2D matrix of sets with visit data, and optionally translates coordinates to a compact format if specified. The `__... | def __init__(self, dataset_maps, visit_list, true_names=False, compact = False):
self.dataset_maps = dataset_maps
self.trajectories = dict()
for triplet in visit_list:
self.__add_trajectory(triplet[0])
self.__add_visit(triplet[1], triplet[2], triplet[0], true_names)
... |
def energy(self):
if self.ones != None:
return self.myones()
else:
return self.mymean()
def copy_state(self, state):
return deepcopy(state)
def move(self):
self.random_generator() | The code performs simulated annealing at a constant temperature, exploring the state space by iteratively making moves. It calculates energy changes, accepts worse states probabilistically based on temperature, tracks acceptance and improvement rates, and updates the best state found. The function returns the final ene... | def run(self, temp):
"""Anneals a system at constant temperature and returns the state,
energy, rate of acceptance, and rate of improvement."""
energy = self.energy()
prev_state = self.copy_state(self.state)
prev_energy = energy
accepts, improves = 0, 0
for _ in r... |
def run(self, temp):
"""Anneals a system at constant temperature and returns the state,
energy, rate of acceptance, and rate of improvement."""
energy = self.energy()
prev_state = self.copy_state(self.state)
prev_energy = energy
accepts, improves = 0, 0
for _ in r... | The code performs simulated annealing to minimize a system's energy by iteratively cooling the temperature, exploring states, and updating the best solution until acceptance and improvement rates fall below thresholds. It returns the optimal state and corresponding energy. | def anneal(self):
"""Minimizes the energy of a system by simulated annealing.
Parameters
state : an initial arrangement of the system
Returns
(state, energy): the best state and energy found.
"""
step = 0
# Note initial state
temp = self.Tmax
... |
def energy(self):
if self.ones != None:
return self.myones()
else:
return self.mymean()
def update(self, *args, **kwargs):
self.update_dict(*args, **kwargs)
def move(self):
self.random_generator()
def run(self, temp):
"""Anneals a system at constant temper... | This function determines the optimal maximum temperature (Tmax) for simulated annealing by iteratively adjusting the temperature until the acceptance rate of energy states reaches approximately 98%, ensuring efficient exploration of the solution space while balancing exploration and exploitation. | def find_max_T(self):
# Attempting automatic simulated anneal...
# Find an initial guess for temperature
step = 0
temp = 0.0
energy = self.energy()
self.update(step, temp, energy, None, None)
while temp == 0.0:
step += 1
self.move()
... |
def copy_state(self, state):
return deepcopy(state)
def __new_risk(self):
self.risk_colocs = dict()
for i in range(0, len(self.state.visits)):
individuals = self.dataset.total_matrix[self.state.visits[i], i]
for ind in individuals:
if ind in self.risk_colo... | This code initializes an attacker's state and setup for a simulation/optimization process. It processes spatial coordinates to build neighbor relationships based on distance limits, selects an initial trajectory (by risk or user input), copies states, sets simulation parameters (steps, energy, logging), and prepares fo... | def __init__(self, dataset, distance_limit=None, initial_state_id=None, t_max=None, log_file=None, alpha=0.98, ones=None):
self.alpha = alpha
self.dataset = dataset
self.risk = dict()
self.risk_colocs = dict()
self.distance_dict = dict()
self.ones = ones
for index... |
def ai_move(board):
best_score = -math.inf
move = None
for i in range(9):
if board[i] == " ":
board[i] = "O"
score = minimax(board, 0, False)
board[i] = " "
if score > best_score:
best_score = score
move = i
return m... | This code implements a Tic-Tac-Toe game where an AI plays against a human user. The AI makes the first move, then players alternate turns. The game validates user input, updates the board, and checks for win/draw conditions after each move. It prints the board state and announces the result when the game concludes with... | def game():
board = [" "] * 9
print("AI's turn")
ai_move_index = ai_move(board)
board[ai_move_index] = "O"
print_board(board)
while True:
while True:
try:
user_move_index = int(input("Enter your move (1-9): ")) - 1
if user_move_index not i... |
def check_max_hangs(user_id):
# check that the user has not reached their max hangs for the week
max_hangs = User.query.filter_by(id=user_id).first().max_hang_per_week
confirmed_hangs = Hang.query.filter_by(week_of=attempt_week).filter(or_(Hang.user_id_1 == user_id, Hang.user_id_2 == user_id),Hang.state.in_... | The code schedules mutual hangs between users by checking if both have available slots and haven't exceeded their weekly hang limits. If valid, it identifies overlapping time slots, randomly selects one, updates the hang state to 'accepted', and records the finalized slot. If no overlap exists or limits are exceeded, t... | def schedule_mutual_hangs(mutual_hangs):
for index, row in mutual_hangs.iterrows():
# check that both users have not reached their max hangs for the week
# if they have, then we can't schedule the hang and the state is still prospect
if not check_max_hangs(row.user_id_1) or not check_max_han... |
def schedule_mutual_hangs(mutual_hangs):
for index, row in mutual_hangs.iterrows():
# check that both users have not reached their max hangs for the week
# if they have, then we can't schedule the hang and the state is still prospect
if not check_max_hangs(row.user_id_1) or not check_max_han... | The code schedules user hangs by prioritizing mutual connections and retrying declined SMS hangs before new prospects, ensuring slot availability and weekly limits are respected through database queries and dynamic schedule adjustments. | def schedule_hangs():
hangs = pd.read_sql(Hang.query.filter_by(week_of=attempt_week).order_by(Hang.priority.desc()).statement, conn)
# go through the mutuals hangs first, then the sms hangs
# the original loop doesn't work as well because we can't guarantee position of ID
mutual_hangs = hangs[hangs.fri... |
def process_accept_type(self, accept_type):
dic_type = {"application/json":"json", "application/xml":"xml", "text/html":"html", "text/plain":"txt"}
# if not exist, then set as NONE
return dic_type.get(accept_type, "NONE")
def handle_GET_file_request(self, src_path):
# Process GET request... | This function parses HTTP requests by splitting headers and body, extracts method, path, HTTP version, and Accept type, processes headers into a dictionary, and routes GET/POST requests to respective handlers while storing request data. | def parse_data(self, request):
header, body = request.split("\r\n\r\n")
headers = header.split("\r\n")
#logging.debug(f"Received Processing Request: Header -> {header}, Body -> {body}")
method, src_path, self.http_version = headers[0].split(" ")
# Request with Accept type
... |
def get_driver_for_chrome(self):
chrome_options = Options()
chrome_options.add_argument("--window-size=1920,1080")
prefs = {"profile.managed_default_content_settings.images": 2}
chrome_options.add_experimental_option("prefs", prefs)
service = ChromeService(executable_path=ChromeD... | The main task of the code is to download Wall Street Journal (WSJ) articles for each day of a specified month. It uses Selenium to handle webpage timeouts, extract article links via XPath, and save them to daily CSV files. The function initializes a browser, navigates to the WSJ, waits for dynamic content, iterates thr... | def download_articles_for_one_month(self):
try:
TimeOut.timeout_func(logger, self.driver.get, [self.url, ])
except TimeOutException:
try:
TimeOut.timeout_func(logger, self.driver.quit)
except TimeOutException:
logger.warning("chrome fai... |
def get_driver_for_chrome(self):
chrome_options = Options()
chrome_options.add_argument("--window-size=1920,1080")
prefs = {"profile.managed_default_content_settings.images": 2}
chrome_options.add_experimental_option("prefs", prefs)
service = ChromeService(executable_path=ChromeD... | The main task of the code is to automate a Chrome browser workflow: initialize a driver, navigate to a homepage and sign in, then attempt to download content. If exceptions occur during execution, it logs errors, attempts to gracefully quit the driver, and recursively restarts the process by reinitializing the driver a... | def main_entry(self):
try:
self.driver = self.get_driver_for_chrome()
self.open_homepage_and_sign_in()
self.try_to_download()
except Exception as exc:
logger.exception("web driver exception: %s", str(exc))
try:
TimeOut.timeout_f... |
def get_space_jacobian(self, arm_positions=None):
"""get the space jacobian of the current or the specific joint positions.
:param arm_positions [array-like]: the input joint positions if None, use current joint positions, defaults to None
:return [np.ndarray(6,7)]: 6x7 space jacobian(rot(3), t... | The function computes the body Jacobian matrix by transforming the space Jacobian using the inverse of the end-effector's SE3 transformation. It calculates the spatial Jacobian via `get_space_jacobian`, determines the end-effector pose (current or specified), converts the orientation and position into an adjoint matrix... | def get_body_jacobian(self, arm_positions=None):
"""get the body jacobian of the current or the specific joint positions.
:param arm_positions [array-like]: the input joint positions if None, use current joint positions, defaults to None
:return [np.ndarray(6,7)]: 6x7 space jacobian
"""... |
def override_globals():
global BOARD_SIZE, DEPTH_LIMIT, WINNING_LENGTH, MOVE_THREE_DISTANCE, CENTER
for arg in sys.argv[1:]:
if arg.startswith("--size="):
try:
BOARD_SIZE = int(arg.split("=")[1])
CENTER = BOARD_SIZE // 2
except ValueError:
... | The main task is to run a game where an AI (player 'X') plays against a human (player 'O') on a customizable board, using a specified evaluation function. The AI selects optimal moves, the game checks for wins/draws, and displays the board state and configuration parameters like board size, depth limit, and evaluation ... | def main():
override_globals()
print(f"BOARD_SIZE={BOARD_SIZE} --size={BOARD_SIZE}")
print(f"DEPTH_LIMIT={DEPTH_LIMIT} --depth={DEPTH_LIMIT}")
print(f"WINNING_LENGTH={WINNING_LENGTH} --winning-length={WINNING_LENGTH}")
print(f"MOVE_THREE_DISTANCE={MOVE_THREE_DISTANCE} --move-three-distance={MOVE_THR... |
def _test_option_type(option_type):
if (option_type != "c") and (option_type != "p"):
raise GBS_InputError("Invalid Input option_type ({0}). Acceptable value are: c, p".format(option_type))
def _approx_implied_vol(option_type, fs, x, t, r, b, cp):
_test_option_type(option_type)
ebrt = math.exp((b -... | The function `_newton_implied_vol` computes the implied volatility of an option using the Newton-Raphson method. It starts with an approximate volatility, iteratively adjusts it to minimize the difference between the calculated option value and the target price (`cp`), using derivatives (vega) for convergence. If the m... | def _newton_implied_vol(val_fn, option_type, x, fs, t, b, r, cp, precision=.00001, max_steps=100):
# make sure a valid option type was entered
_test_option_type(option_type)
# Estimate starting Vol, making sure it is allowable range
v = _approx_implied_vol(option_type, fs, x, t, r, b, cp)
v = max(_... |
def get_interest_free_rate(symbol):
""" Values from solend """
allowed_symbols = ['ETH', 'BTC', 'SOL']
if symbol not in allowed_symbols:
raise Exception(f"Symbol {symbol} not in {allowed_symbols}")
interest_free_rates = {
'BTC': 0.04 / 100,
'ETH': 0.85 / 100,
'SOL': 2.43... | This function calculates the implied volatility of an option using the Euro Implied Volatility formula. It validates input parameters, retrieves risk-free rates, converts expiration dates to years, determines call/put type, and invokes the euro_implied_vol function with market data to compute the result. | def get_implied_volatility_from_item(item):
# option_type = "p" or "c"
# fs = price of underlying
# x = strike
# t = time to expiration
# v = implied volatility
# r = risk free rate
# q = dividend payment
# ... |
def create_slots():
for slot in SLOTS:
create_slot({ "id": slot, "timings": SLOTS[slot]})
def create_faculties():
for faculty in FACULTIES:
create_faculty({ "name": faculty })
def create_courses():
for course in COURSES:
create_course(course)
def register_courses():
responses = [... | The main task of the code is to initialize academic entities (slots, faculties, courses), register courses to faculties, and generate a timetable by orchestrating these components. It sets up data structures, assigns course-faculty relationships, and compiles a structured schedule, likely for educational planning or re... | def main():
create_slots()
create_faculties()
create_courses()
register_courses()
timetable() |
def for_num_token():
status = read_number()
return Token(TokenType.NUM, main_read_part, file_line) if status else ""
def for_ws_token():
global read_line
read_line = read_line[1:]
return ""
def for_kw_or_id_token():
status = read_keyword_or_id()
if status:
if main_read_part not in la... | The main task of the code is to read and return the next token from an input file, handling different token types (numbers, whitespace, letters, symbols, etc.) by calling specialized helper functions. It manages file reading, line tracking, and EOF handling, returning appropriate tokens or an EOF token when no more inp... | def get_next_token():
global read_line, file_line, main_read_part
if is_empty(read_line):
read_line = input_file.readline()
file_line += 1
if is_empty(read_line):
with open('input.txt', 'r') as f:
hello = f.readlines()
temp_line_number = len(hello) + 1 if hell... |
def parse_bit_rows(input_data, total_val_per_bit_column):
row_index = 0
for bits_row_string in input_data:
column_index = 0
loop_val = bits_row_string
for bit in loop_val:
parse_bit_char(bit, column_index, total_val_per_bit_column)
column_index += 1
row_index += 1
def get_search_bit(bit_position, total_... | The code calculates the gamma and epsilon rates for part 1 by analyzing bit columns in input data, then determines oxygen and CO₂ ratings recursively for part 2. It converts these binary values to decimal and computes the product of gamma × epsilon and oxygen × CO₂ for results. | def calc(self):
total_val_per_bit_column = []
parse_bit_rows(self.input_data, total_val_per_bit_column)
gamma = ""
epsilon = ""
char_pos_index = 0
for total_val in total_val_per_bit_column:
gamma += str(get_search_bit(char_pos_index, total_val_per_bit_column, is_oxygen_rating=True))
epsilon += str(ge... |
def roll( self, probability ):
rand = random.random()
cumulativeProbability = 0
index = 0
for i in range(0, len(probability)):
cumulativeProbability += probability[i]
index = i
if rand < cumulativeProbability:
return index
self.log.warning("Assigning value based on unassign... | The main task of the code is to recombine V, D, J, and C gene segments into valid DNA/RNA sequences by applying stochastic modifications (e.g., chewback trimming, nucleotide additions), ensuring proper reading frames, and validating the resulting CDR3 region for functional amino acid sequences and absence of early stop... | def recombinate( self, V, D, J, C):
self.log.info("Recombinate() called...")
self.log.debug("Arguments: %s", (V, D, J, C))
DNA = None
RNA = None
vIndex, vAllele = V
jIndex, jAllele = J
cIndex, cAllele = C
# Determine our chromosome number from the J segment index
chromosome = None... |
def print_grid(board):
for i in range(3):
for j in range(3):
print(board[i][j], end=" ")
print("\n")
def turn_human(board):
while True:
print("Place O in: ")
x = int(input("X: "))
y = int(input("Y: "))
if x >= 0 or x < 3 or y >= 0 or y < 3:
... | The main task of the code is to simulate a tic-tac-toe game between a human and computer. It initializes a 3x3 board, alternates turns (human first), updates the board after each move, checks for a winner, and prints the board state until a winner is determined. | def main():
board = [['?', '?', '?'], ['?', '?', '?'], ['?', '?', '?']]
winner = None
print_grid(board)
while winner is None:
turn_human(board)
turn_computer(board)
print_grid(board)
winner = checkWinner(board)
print()
print_grid(board) |
def get_process_order(self, scope, action):
for order, process in enumerate(self.__processes):
if (process.scope == scope) and (process.action == action):
return order
return -1
def is_same_function(self, order, function):
return self.__processes[order].function == in... | This code updates a process in a system by checking for conflicts with existing consolidated processes. If the new process differs in tracking status or function and is already consolidated, it prompts the user to confirm a rollback to the last valid backup. If confirmed, it rolls back, updates the process, and re-cons... | def update_process(self, scope, action, function, description, tracked=True):
order = self.get_process_order(scope, action)
already_consolidated = self.__last_consolidated >= order
different_tracked = self.__processes[order].tracked != tracked
both_tracked = (self.__processes[order].trac... |
def process_exists(self, scope, action):
if self.get_process_order(scope, action) == -1:
return False
return True
def update_process(self, scope, action, function, description, tracked=True):
order = self.get_process_order(scope, action)
already_consolidated = self.__last_con... | The main task of the code is to either update an existing process or add a new one to the system. It checks if a process with the given scope and action already exists; if so, it updates it, otherwise, it creates a new process, adds it to the internal list, and triggers a consolidation step to manage process organizati... | def add_process(self, scope, action, function, description, tracked=True):
if self.process_exists(scope, action):
self.update_process(scope, action, function, description, tracked)
else:
process = self.Process(scope, action, function, description, tracked)
self.__proc... |
def reset_observation(self):
# reset the image
for row in range(self.envsY):
for column in range(self.envsX):
if np.isnan(self.envs[row][column]):
# self._envs_nan[row][column] = np.nan
color = BUFFER_COLORS
wafer_ch... | The code resets the environment by initializing the agent's position, resetting counters (steps, distance), copying the environment state, configuring special cells (ODD_TEST) with Gaussian distribution, updating observation data, and preparing for the next step. It handles different modes, updates probe interactions, ... | def reset(self):
# reset the environment
self.y, self.x = self.location[np.random.randint(len(self.location))]
self.y_last, self.x_last = self.y, self.x
self.steps = 0
self.dist = 0
self.total_dist = 0
self.show_dist = 0
self.num_color = np.zeros(self.num_... |
def attempt_data_resolution(self):
"""Ensures that data resolution has already been attempted. Nuances:
* It does *not* re-resolve if resolution has already happened.
* It's ok if there remain unresolvable dependencies.
"""
if not hasattr(self, '_resolved_data'):
... | The code's main task is to load a fixture into storage if it doesn't already exist. It first attempts to resolve the fixture's data, checks for existing storage, and raises an error if resolution fails. If the fixture is resolvable and doesn't exist, it creates and logs the fixture. Debug logs track existence checks an... | def load(self):
"""Loads this fixture into storage unless it already exists. Raises
UnresolvedFixtureError if the fixture's data cannot be resolved.
"""
self.attempt_data_resolution()
if self.exists():
logger.debug('Fixture already exists, nothing to load: %s' % self... |
def attempt_data_resolution(self):
"""Ensures that data resolution has already been attempted. Nuances:
* It does *not* re-resolve if resolution has already happened.
* It's ok if there remain unresolvable dependencies.
"""
if not hasattr(self, '_resolved_data'):
... | The code's main task is to unload a fixture by first resolving its data, checking if it exists, and if so, deleting it while logging the action. It ensures the fixture is removed only if it exists, avoiding unnecessary operations and logging debug messages for tracking. | def unload(self):
self.attempt_data_resolution()
if not self.exists():
logger.debug('Fixture does not exist, nothing to unload: %s' % self)
return
self.delete()
logger.debug('Unloaded fixture: %s' % self) |
def function_name_to_relation_name(function: str) -> str:
"""Converts the given function name to a canonically corresponding relation
name.
Parameters:
function: function name to convert.
Returns:
A relation name that is the same as the given function name, except that
its firs... | The main task of the code is to syntactically convert a given logical formula into an equivalent formula without function invocations. It replaces function calls with relations, ensuring the transformed formula holds in a model if and only if the original holds in the corresponding model with no function meanings. The ... | def replace_functions_with_relations_in_formula(formula: Formula) -> Formula:
"""Syntactically converts the given formula to a formula that does not
contain any function invocations, and is "one-way equivalent" in the sense
that the former holds in a model if and only if the latter holds in the
canonica... |
def find_options2(data):
result = []
for i in range(1, 10):
options = []
for count, value in enumerate(data):
if value is not None or \
i in get_row_values(data, get_row(count)) or \
i in get_column_values(data, get_column(count)) or \
... | The main task of the code is to process a dataset by iterating through matrices and identifying answers within specific squares. For each detected answer in a square, it updates the original data by assigning the matrix index (i+1) to positions determined by a count value. The function returns the modified data array w... | def find_answer(source_data):
data = source_data.copy()
for i, matrix in enumerate(find_options2(data)):
for square_number in range(1, 10):
square = get_square_values(matrix, square_number)
answer_in_square = check_answer_in_square(square)
if answer_in_square:
... |
def clear_possible_options(self):
for cell in self.cells:
cell.possible_options_row = set()
cell.possible_options_column = set()
def get_matrix(self, value):
matrix = Field(self.get_matrix_values(value))
matrix.matrix_optimize()
return matrix
def fill_possible_val... | This method determines possible values for Sudoku cells by analyzing each 3x3 square. It checks rows and columns within squares for existing numbers, then fills possible values in empty cells based on which rows/columns have non-None values. By iterating through all values (1-9) and squares, it updates constraints to n... | def only_possible_values(self):
self.clear_possible_options()
for value in range(1, 10):
matrix = self.get_matrix(value)
for square_number in range(1, 10):
square = matrix.get_square_cells(square_number)
rows_in_square = [[square[0], square[1], sq... |
def only_possible_values(self):
self.clear_possible_options()
for value in range(1, 10):
matrix = self.get_matrix(value)
for square_number in range(1, 10):
square = matrix.get_square_cells(square_number)
rows_in_square = [[square[0], square[1], sq... | This code iterates through numbers 1-9 to search for valid placements in a Sudoku-like grid. If 'hard' is True, it first narrows down possible values. For each number, it retrieves the corresponding matrix and checks rows, columns, and 3x3 squares for valid positions, updating the grid's state through constraint propag... | def make_search(self, hard):
for value in range(1, 10):
if hard:
self.only_possible_values()
matrix = self.get_matrix(value)
self.find_answer_in_square(matrix, value)
self.find_answer_in_row(matrix, value)
self.find_answer_in_column(ma... |
def make_search(self, hard):
for value in range(1, 10):
if hard:
self.only_possible_values()
matrix = self.get_matrix(value)
self.find_answer_in_square(matrix, value)
self.find_answer_in_row(matrix, value)
self.find_answer_in_column(ma... | This function attempts to solve a puzzle by iteratively searching for items until all 81 are found. It uses `make_search` and `check_found` methods, adjusting based on the `hard` parameter. If no new items are found in a step, it terminates. If `print_info` is True, it outputs the board state and steps taken to reach t... | def find_answer(self, hard=True, print_info=False):
i = 0
break_text = ''
while self.found != 81:
i += 1
found_before = self.found
self.make_search(hard)
self.check_found()
if found_before == self.found:
break_text = f'f... |
def _create_heading(self, root, row, text):
label = Label(root,text=text,font="Calibri 11 bold")
label.grid(row=row,column=0,columnspan=2,sticky='we', padx=10, pady=5)
def _create_file_selection(self, root, row, file_type, text, default=""):
label = Label(root,text=text)
# Creating an i... | The code creates a GUI for inputting parameters and file selections, organizing controls into sections with headings. It uses Tkinter to set up a window with two columns, adding file selectors, text inputs, checkboxes, and a process button. The GUI updates internal variables and waits for the "Process" button press to ... | def run(self):
# Creating GUI window and specifying some parameters, such as the
# window title, dimensions and relative weights of the two columns. The
# interface is set up as two columns - the left states the variable name
# and the right is where the user inputs the relevant values... |
def extract_query_ids(query):
queries = re.findall(r'(?:join|from) query_(\d+)', query, re.IGNORECASE)
return [int(q) for q in queries]
def create_tables_from_query_ids(user, connection, query_ids):
for query_id in set(query_ids):
query = _load_query(user, query_id)
results, error = query.d... | This code executes a SQL query against an in-memory SQLite database, infers column data types from query results, formats the output as structured JSON with columns and rows, and handles errors like empty results or user interruptions. It creates temporary tables based on query IDs and user context before execution, th... | def run_query(self, query, user):
connection = sqlite3.connect(':memory:')
query_ids = extract_query_ids(query)
create_tables_from_query_ids(user, connection, query_ids)
cursor = connection.cursor()
try:
cursor.execute(query)
if cursor.description is n... |
def clean_data(text: str):
"""Preprocesses the text with tokenization, case folding, stemming and lemmatization, and punctuations
Parameters
----------
text : str
The title or abstract of an article
Returns
-------
list
A list of tokens
"""
tokens = pre_clean(text)
... | The code performs document retrieval by searching for papers matching given title and abstract queries, using similarity methods like Okapi or LTN-LNN. It filters stop words, computes relevance scores, and returns top results (up to max_result_count), optionally restricting to a specific category. It prints and returns... | def search(title_query: str, abstract_query: str, max_result_count: int = 10, method: str = 'ltn-lnn',
weight: float = 0.5, stop_words_list=None, paper_id_map=None, tf_doc=None, idf_dict=None, doc_dict=None,
okapi_idf=None, category='all', df=None):
if stop_words_list is None:
stop_wor... |
def handle_request(event, links, request_handler, *args):
request_id = str(generate_id())
request_dir = "userData/" + request_id
os.mkdir(request_dir)
vkHandler.send_message('downloading attachments...')
download_files(links, request_dir, *args)
vkHandler.send_message('processing files...')
... | The `bot_loop` function processes incoming VK (VKontakte) messages by listening for new events. When a message is detected, it retrieves attached photos and commands, then executes request handling using a dedicated function. Errors during processing trigger an error message to the user, ensuring feedback on failures. ... | def bot_loop():
print("Bot loop started.")
for event in vkHandler.listen():
if event.type == vkHandler.longpoll.VkBotEventType.MESSAGE_NEW:
photos, command = vkHandler.get_photos_links(), vkHandler.get_command()
try:
handle_request(event, photos, get_img_request_h... |
def get_puzzle(complex:bool = False) -> str:
"""Returns puzzle with high or medium complexity.
Args:
complex (bool, optional):An option if harder puzzle is required. Defaults to False.
Returns:
str: Returns puzzle string.
"""
if complex:
return '4.....8.5.3..........7......... | The main task of the code is to solve a Sudoku puzzle using constraint propagation and search. It displays the puzzle at various stages: original, replaced dots with numbers, eliminated values, reduced via only-choice, and fully solved via search if necessary. The function checks if the puzzle is solved, and if not, ap... | def main(display_units:bool=False):
"""This is the main function to do all the main functionalities.
Args:
display_units (bool, optional): A option to display units. Defaults to False.
"""
if display_units:
print(f"boxes : \n{boxes}\n")
print(f"row_units : \n{row_units}\n")
... |
def done(self):
return self.at >= self.end
def peek(self):
return self.line[self.at] if self.at < self.end else None
def next(self):
k = self.peek()
self.at += 1
return k
def parse_single_quote(self):
token = ""
self.next() # ignore leading quote.
while self.peek() != "'":
if self.done():
raise ... | This function parses a token by reading characters from the input until it encounters whitespace or a newline, handling escape sequences and quoted strings. It constructs the token by processing each character, including handling backslashes for escaping and invoking methods to parse single or double-quoted strings. | def parse_token(self):
token = ""
while not self.done() and self.peek() not in ' \t\n':
current = self.peek()
if current == '\\':
self.next()
if self.done():
raise ParseIncomplete()
elif self.peek() in " \t\\'\"":
token += self.next()
elif self.peek() == '\n':
self.next()
el... |
def get_valid_locations(board):
valid_locations = []
for col in range(columns):
if is_valid_location(board, col):
valid_locations.append(col)
return valid_locations
def is_terminal_node(board):
return winning_move(board, PLAYER_PIECE) or winning_move(board, AI_PIECE) or len(get_valid_locations(board)) == 0
def... | This code implements the Minimax algorithm with alpha-beta pruning to determine the optimal move for a player in a turn-based game (likely Connect Four). It recursively evaluates all possible future moves up to a specified depth, maximizing the AI's score while minimizing the opponent's, and uses pruning to improve eff... | def minimax(board, depth, alpha, beta, maximizingPlayer):
valid_locations = get_valid_locations(board)
is_terminal = is_terminal_node(board)
if depth == 0 or is_terminal:
if is_terminal:
if winning_move(board, AI_PIECE):
return (None, 100000000000000)
elif winning_move(board, PLAYER_PIECE):
return (N... |
def draw_board(clr,board):
for c in range(columns):
for r in range(rows):
pygame.draw.rect(screen, clr, (c*SQUARESIZE, r*SQUARESIZE+SQUARESIZE, SQUARESIZE, SQUARESIZE))
pygame.draw.circle(screen, GREY, (int(c*SQUARESIZE+SQUARESIZE/2), int(r*SQUARESIZE+SQUARESIZE+SQUARESIZE/2)), RADIUS)
for c in range(column... | The code implements a Connect 4 game with a human player and AI opponent. It uses Pygame for rendering, tracks game time, handles user input, executes the minimax algorithm for AI moves, checks win/tie conditions, and displays results. The game alternates turns, updates the board visually, and concludes with a winner a... | def play_game(clr, user_ip, turn, depth):
game_over = False
pygame.display.set_caption("Connect 4 Game")
draw_board(clr,board)
pygame.display.update()
start_time = time.time()
while not game_over:
# Calculate time elapsed since start
elapsed_time = int(time.time() - start_time)
minutes = elapsed_time //60
... |
def similarity(rule1,rule2,d):
unions = []
intersections = []
indexes = []
difference = 0
for i in range( len(rule1) - 1 ):
union = rule1[i] | rule2[i]
intersection = rule1[i] & rule2[i]
unions.append(union)
intersections.append(intersection)
if intersection =... | This function generates new rules by comparing pairs of existing rules in `rulesCurrentCategory`, checking for similarity patterns. If a valid pattern is found, it creates a new rule using `create_rule` and appends it to the list. After processing all pairs, it removes redundant rules via `deleteRedundant` and returns ... | def search_patterns(rulesCurrentCategory, d, originalRules,otherRules,ratio):
newRules = []
for i in range( 0, len(rulesCurrentCategory) ):
r1 = rulesCurrentCategory[i]
for j in range(i+1, len(rulesCurrentCategory)):
r2 = rulesCurrentCategory[j]
# print('comparing',r1,r2)
... |
def createCategoriesDict(Rules):
dictionary_of_classes = dict()
for rule in Rules:
rule_class = rule[-1]
if rule_class not in dictionary_of_classes:
dictionary_of_classes[rule_class] = []
dictionary_of_classes[rule_class].append(rule)
else:
dictionary_... | The main task of the code is to extract and process rules by categorizing them, iterating through each category to apply transformations, and aggregating the resulting rules into a final list. It uses helper functions to split rules by category, process them with parameters `d` and `ratio`, and return the refined set o... | def ruleExtraction(Rules,d,ratio):
finalRules = [ ]
categoriesDict = createCategoriesDict(Rules)
for category in categoriesDict:
[rulesCurrentCategory,otherRules] = getCategory(category,categoriesDict)
rules = iterate(rulesCurrentCategory,d,otherRules,ratio)
[finalRules.append(rule) ... |
def open_file(self):
file_exists = False
while not file_exists:
self.KB_file = input("Enter the KB file name: ")
try:
f = open(self.KB_file, "r")
file_exists = True
except IOError:
print("File not found, ... | The main task of the code is to process a knowledge base (KB) by extracting the last clause as the original clause, removing it from KB, applying original steps to KB and the original clause, then checking for contradictions in the modified KB. This suggests a logic reasoning or theorem-proving process, analyzing KB fo... | def main(self):
KB = self.open_file()
orig_clause = KB[-1]
KB.pop()
self.original_steps(KB, orig_clause)
self.find_contradiction(KB) |
def drawGameState():
canvas.delete("move")
highlightLastMove()
highlightSq()
drawPieces()
canvas.place(x=0, y=0, anchor="nw")
def gameOverCheck():
global gameState, gameOver
if gameState.checkmate:
gameOver = True
if gameState.whiteTurn:
drawText("Black win by che... | This code handles mouse click events in a chess game, allowing a player to select and execute moves by capturing clicks on the board. It updates the game state, validates moves against available options, switches turns, and triggers AI control when applicable. The function processes coordinates, adjusts for board orien... | def mouseOnClick(event):
global gameState, validMoves, selectedSq, clicks, moveMade, gameOver, playerTurn
if playerTurn:
if not gameOver:
x, y = event.x, event.y
column = x // SQ_SIZE
row = y // SQ_SIZE
if not playerColor:
column = DIMENSIO... |
def syndrome_mask(code_size, repetitions):
'''
Creates a surface code grid. 1: X-stabilizer. 3: Z-stabilizer.
'''
M = code_size + 1
syndrome_matrix_X = np.zeros((M, M), dtype=np.uint8)
# starting from northern boundary:
syndrome_matrix_X[::2, 1:M - 1:2] = 1
# starting from first row i... | The code benchmarks the performance of Maximum Weighted Matching (MWPM) and Graph Neural Network (GNN) decoders on a rotated surface code. It generates quantum error correction circuits with specified parameters, simulates error syndromes, and evaluates decoder accuracy, logical failure rates, and computational time fo... | def testing(code_size: int, repetitions: int, error_rate: float, test_size: int):
circuit = stim.Circuit.generated(
"surface_code:rotated_memory_z",
rounds=repetitions,
distance=code_size,
after_clifford_depolarization=error_rate,
after_reset_flip_probability=error_rate,
... |
def getNeh(E,eps,F):
#TMP
#return np.random.normal((E/eps),np.sqrt(F*(E/eps)),np.shape(E))
N=np.round(np.random.normal((E/eps),np.sqrt(F*(E/eps)),np.shape(E)))
return np.maximum(0,N)
def passTrig(E):
return np.random.random(E.shape)<eff.trigEff(E)
def getSmeared(E, F=0, doLowEbias=False, seed=None):... | This function simulates energy spectra for nuclear recoils (NR), electronic recoils (ER), and (n,gamma) interactions by calculating ionization energies, phonon energies, applying detector resolution smearing, trigger logic, and efficiency cuts. It returns binned event counts in specified energy bins for each interactio... | def buildSimSpectra_ee(Ebins, Evec_nr, Evec_er, Evec_ng, dEvec_ng, Yield, F_NR, scale_g4=1, scale_ng=1, doDetRes=True, seed=1):
V=const.V
G_NTL=const.G_NTL
eps=const.eps
F=const.F
np.random.seed(seed)
###############
#Yield, Fano, Resolution
###############
##########... |
def check_login_status():
try:
login_status = check_session('login_status')
except Error as e:
print("Unknown error when checking login status session", e)
else:
return login_status
def remove_session(session_key):
try:
session.pop(session_key, None)
except Error as e... | The code handles user login by checking session status, validating credentials, and managing 2FA. It redirects authenticated users, processes login forms, checks passwords via bcrypt, locks accounts on failed attempts, sends 2FA tokens, and renders the login template with error messages or tokens for user feedback. | def login():
print('login route')
if 'superadmin_status' in session:
return redirect(url_for('superadmin'))
elif 'admin_status' in session:
return redirect(url_for('admin'))
if check_login_status():
print('account logged in')
return redirect(url_for('home'))
form=l... |
def remove_all_session_user():
try:
remove_session('login_status')
remove_session('login_id')
remove_session('username')
remove_session('latest_reset_token')
remove_session('admin_status')
remove_session('superadmin_status')
except Exception:
print("Error ... | The code handles admin login by checking session status, validating credentials against a database, implementing 2FA via email, enforcing account lockouts after failed attempts, and applying rate limiting. It redirects authenticated users, manages session clearance, and renders the login template with error flags for i... | def admin_login():
if 'superadmin_status' in session:
return redirect(url_for('superadmin'))
elif 'admin_status' in session:
return redirect(url_for('admin'))
# Auto clear session
remove_all_session_user()
form = login_form(request.form)
account_locked = False
invalid_pass_... |
def login(self):
try:
auth_object = self.get_auth_object()
print("before", self.browser.title)
self.browser.get("https://en-gb.facebook.com/login.php")
# filling the forms
WebDriverWait(self.browser, 30).until(EC.presence_of_element_located((By.XPAT... | The main task of the code is to retrieve and extract Facebook profile posts by logging into the account, navigating to a specified user profile, scrolling through the profile to load all posts (based on the provided total_posts count), and extracting the HTML content and profile information. The function returns the ex... | def get_profile_posts(self, profile, sleep_times=8):
self.login()
searchurl = "https://m.facebook.com/profile.php?id=" + profile.get("userid")
print("searchurl: ", searchurl)
self.browser.get(searchurl)
print("total_posts: ", profile.get("total_posts"))
self._scroll_... |
def format_value_object(obj):
"""Helper function to format objects without IDs."""
name = obj.__class__.__name__
compact_obj = formatted_dict(obj)
formatted_args = ", ".join(["{}={!r}".format(k, v) for k, v in compact_obj.items()])
return "{}({})".format(name, formatted_args)
def format_collection(o... | The function `format_stripe` returns a user-friendly string representation of Stripe objects by checking their type: it uses `format_value_object` for `StripeObject` (value objects without identity), `format_collection` for `ListObject` (collections with "data" attribute), and `format_entity` for other objects with IDs... | def format_stripe(obj):
"""
Provide a more user-friendly representation of Stripe objects.
- StripeObject is a "value object" that doesn't have its own identity.
We provide a verbose representation of it.
- Collection is something that has a "data" attribute.
- Everything else usually have an... |
def ipalv(otx, ip, IndicatorTypes):
alerts = []
result = otx.get_indicator_details_by_section(IndicatorTypes.IPv4, ip, 'general')
# Return nothing if it's in the whitelist
validation = getValue(result, ['validation'])
if not validation:
pulses = getValue(result, ['pulse_info', 'pulses'])
... | The function `mainalv` interacts with the AlienVault OTX API to assess if a provided IP or URL is malicious. It retrieves an API key from a file, queries the OTX server, and checks alerts for the input. If alerts exist, it generates a markdown-formatted string indicating potential maliciousness, alert count, and a sour... | def mainalv(ip,url):
"""
mainalv is managing alienvault api configuration and call api for IP or api for url. return a string in markdown style.
:param ip:ip from user
:param url:url from user
"""
from OTXv2 import OTXv2
import IndicatorTypes
############# API config #############
... |
def featureToSplit(data):
data = np.array(data)
attribute_count = data.shape[1]-1
label_col = [i[-1] for i in data]
infGain = []
for j in range(attribute_count):
# attribute_col = [i[j] for i in data]
infGain.append(inf_Gain(data, j))
# print(infGain)
if max(infGain) > 0:
... | This code recursively constructs a decision tree by selecting the optimal feature to split the dataset at each node, stopping when all labels are uniform, no further splits are possible, or the maximum depth is reached. It returns a tree structure where each node maps a feature to its child nodes, built using majority ... | def createTree(data, depth, max_depth):
label = [i[-1] for i in data]
depth = int(depth)
max_depth = int(max_depth)
if label.count([label[0]]) == len(label):
return label[0]
if featureToSplit(data) == None:
return max(sorted(label, reverse=True), key=label.count)
if depth > max... |
def std_form (n):
n = str (n)
if n[0] == "-":
sign = "-"
n = n[1:]
else:
sign = ""
i = n.find (".")
e = n.find ("e")
if i > 0:
integer = n[:i].replace ("-", "")
remainder = n[i+1:]
for i in range (len (remainder)):
if all (remainder... | This function rounds a number based on specified parameters: decimal places (dp), significant figures (sf), nearest multiple (nearest), and rounding direction (up/down). It handles negatives, scientific notation, and adjusts formatting accordingly, returning the rounded value with proper sign and precision. | def around (number, dp = None, sf = None, nearest = None, direction = None):
t = type (number)
sign = ""
if str(number)[0] == "-":
sign = "-"
number = str(number)[1:]
if sign == "-":
if direction == "up":
direction = "down"
elif direction == "down":
... |
def round_up (n):
l = [i for i in str(n)][::-1]
sign = ""
if l[0] == "-":
l = l[1:]
sign = "-"
for i in range (len (l)):
if l[i] != "9":
l = ["0" for c in l[:i]] + [str (int (l[i]) + 1)] + l[i+1:]
break
else:
l = ["0" for i in l] + ["1"]
... | The main task of the code is to test multiple rounding and formatting functions (`round_up`, `around`, `eval_exp`, `set_sf`, `std_form`) with diverse input values, including integers, floats, strings, negatives, and edge cases. It runs test cases to validate the behavior of these functions under different parameters (e... | def run_tests ():
from numpy import linspace
l = [1234, 8999, 134139, 10090, 99]
for c in l:
result = round_up (c)
print(f"Input: {c}, \nOutput: {result}")
l = [0.0006, 2.9999, .5, .51, 13718.35253, 0.42, 0.000080000001, 1.42,
"340000", 3.00, "134.... |
def addForest(self):
# First iteration will seed a forest and the rest will randomly add adjacent or make a new seed
self.board[randint(0, (len(self.board) - 1))][randint(0, (len(self.board) - 1))] = self.forestCode
# Random placement of forests, 1/3 of tiles should be forests
self.treeT... | The main task of the code is to generate a 100x100 game board initialized with plains ('p000'), then add diverse terrain features like forests, mountains, silver, quarries, and metal via methods. It tracks changes using a 'changed' list, setting up a structured map for further game logic. | def generateBoard(self):
self.plainsCode = 'p000'
self.forestCode = 'f000'
self.stoneCode = 'q000'
self.silverCode = 's000'
self.metalCode = 'm000'
self.mountainCode = 'v000'
self.castleCode = 'c000'
# Makes a list of lists
self.board = []
... |
def setPictures(self):
self.castle = Image.open('Images/Castle.jpg').resize((self.tileSize, self.tileSize))
self.forest = Image.open('Images/tiles/tree.png').resize((self.tileSize, self.tileSize))
self.plains = Image.open('Images/tiles/s_flowers.png').resize((self.tileSize, self.tileSize))
... | The code initializes a game board by setting tile size, loading images, generating the board structure, and assigning both ASCII and visual board representations, though it notes a potential redundancy in reusing the 'board' variable for multiple purposes. | def __init__(self, master):
self.master = master
self.tileSize = 20
self.setPictures()
self.generateBoard()
# Did the dumb, self.board is also used for the ASCII
# layout of the board and then I reassigned it here
# and used it multiple time through the files.
... |
def clear_screen(canvas):
if settings.debug:
temp_canvas = np.ndarray((settings.width, settings.height, 3), dtype=int)
temp_canvas.fill(0)
return temp_canvas
else:
matrix.Clear()
return canvas
def draw_text(canvas, x, y, font, text, color=None):
char_x = x
for char in text:
glyph = font[ord(char)]
cha... | The main task of the code is to run a clock display loop that continuously updates the time on an offscreen canvas. It formats the current time as a string with leading zeros, alternates between colon and space for blinking effect, handles settings changes, and redraws the time every 0.05 seconds until stopped. | def run(self):
logging.debug('starting clock')
# if not settings.debug:
# offscreen_canvas = matrix.CreateFrameCanvas()
# Run the clock loop until stopped
while True:
# Check to see if we have stopped
if self.stopped():
self.offscreen_canvas = clear_screen(self.offscreen_canvas)
return
# C... |
def clear_screen(canvas):
if settings.debug:
temp_canvas = np.ndarray((settings.width, settings.height, 3), dtype=int)
temp_canvas.fill(0)
return temp_canvas
else:
matrix.Clear()
return canvas
def draw_text(canvas, x, y, font, text, color=None):
char_x = x
for char in text:
glyph = font[ord(char)]
cha... | This code runs a loop to display the current time in words on an offscreen canvas, updating every 0.05 seconds. It converts hours and minutes to textual representations using a predefined mapping, clears the canvas each frame, positions the text centrally, and handles settings changes or stop signals to terminate the l... | def run(self):
logging.debug('starting text clock')
# Run the clock loop until stopped
while True:
# Check to see if we have stopped
if self.stopped():
self.offscreen_canvas = clear_screen(self.offscreen_canvas)
return
# Check for a settings change that needs fto be loaded
if settings.update... |
def clear_screen(canvas):
if settings.debug:
temp_canvas = np.ndarray((settings.width, settings.height, 3), dtype=int)
temp_canvas.fill(0)
return temp_canvas
else:
matrix.Clear()
return canvas
def draw_text(canvas, x, y, font, text, color=None):
char_x = x
for char in text:
glyph = font[ord(char)]
cha... | This code renders a financial data display on an offscreen canvas, showing a stock symbol, current price, price change (with color-coded increase/decrease), and a graph (line, filled, or bar type) visualizing historical price data. It clears the canvas, draws text elements, calculates pixel positions for the graph base... | def draw_screen(self):
self.offscreen_canvas = clear_screen(self.offscreen_canvas)
display_symbol = settings.ticker['symbol']
draw_text(self.offscreen_canvas, 2, 1, self.font, display_symbol, [255, 255, 255])
if len(self.df) > 0:
price = '${:.2f}'.format(self.c_vals[0])
draw_text(self.offscreen_canvas, ... |
def get_prices(self):
logging.debug('getting prices')
yf_ticker = yf.Ticker(settings.ticker['symbol'])
self.df = yf_ticker.history(period=settings.ticker['graph_period'], interval=settings.ticker['graph_resolution'], prepost=True).sort_index(ascending=False).reset_index()
if len(self.df) > 0:
self.df['t']... | The code runs a loop to continuously update and display prices on a screen, checking for settings changes and refreshing prices every 15 seconds. It initializes price data, handles stop signals, reloads settings if changed, updates prices when needed, redraws the display, and pauses briefly before repeating. | def run(self):
logging.debug('starting ticker')
self.price_update_time = int(time.mktime((datetime.now() + timedelta(seconds = 15)).timetuple()))
self.get_prices()
self.draw_screen()
# Run the ticker loop until stopped
while True:
# Check to see if we have stopped
if self.stopped():
self.offscre... |
def set_base_attitude(self, q, update=True):
"""
Sets the base attitude
The base attitude is the attitude corresponding to the origin of the scene.
When the base attitude changes, the star positions must be updated. Not doing so will
leave the display in an inconsistent state. T... | The method `set_catalog` updates the object's base attitude, time, and internal catalog reference from the provided `catalog` object. If `update` is True, it also triggers a star display. | def set_catalog(self, catalog, update=True):
self.set_base_attitude(catalog.att, update=False)
self.set_time(catalog.date, update=False)
self._catalog = catalog
if update:
self.show_stars() |
def generate_dupes_info(photos_df, dup_indexes, preferred_folder = False, verbose=0):
if len(photos_df[dup_indexes]) == 0:
return
if verbose >= 1: print("{}Remove pre-report{}".format(Fore.GREEN,Fore.RESET))
# All that shouldn't be removed yet (and therefore susceptible of analysis)
photos_df_dups = photos... | This function processes duplicate photo entries in a DataFrame by generating duplicate information, reporting duplicates, and creating scripts for deduplication. It handles two duplicate types: 'full' and 'digest', updating the DataFrame with removal flags and persistence versions. The process involves generating repor... | def deduplication_process(photos_df, dup_full, dup_digest, output_script, label, working_info = None, preferred_folder=False, goal=0, verbose=0):
# process all entries from the input
photos_df.loc[:, 'should_remove'] = REMOVAL_CODE_IGNORE
photos_df.loc[:, 'persist_version'] = PERSIST_VERSION_KEEP
if sum(dup_fu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.