dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_user_board(self) -> None:
print(heading(self.leaderboard.username))
for index, ship in enumerate(self.ships["names"]):
length: str = self.ships["length"][index]
direction_input: str = 'h'
direction_absent: bool = True
while True:
... | The main task of the code is to let the user choose between manually creating a board or automatically generating it. It validates the input (manual/auto), then triggers corresponding board creation methods: manual input followed by auto-generation for both user and CPU boards, or purely auto-generated boards. The func... | def choose_board_creation(self):
print(heading(self.leaderboard.username))
print('Create board \'manual\' or \'auto\'\n')
user_input: str = ''
while True:
user_input = input('manual or auto: ')
if user_input.lower() not in ['manual', 'auto']:
in... |
def create_boards(self) -> None:
for y in range(self.height):
self.user_board.append(['.' for x in range(self.width)])
self.hits_board.append(['.' for x in range(self.width)])
self.cpu_board.append(['.' for x in range(self.width)])
def choose_board_creation(self):
pri... | The main task of the code is to initialize and start a game by creating game boards, allowing the user to select a board creation method, and then executing the gameplay loop. The method `start` orchestrates these steps sequentially: first generating the boards, then handling user input for board configuration, and fin... | def start(self) -> None:
self.create_boards()
self.choose_board_creation()
self.play() |
def rotateDeal(deal: dict, n: int) -> dict:
# rotates deal n seats counter-clockwise
deal["Dealer"] = shift(deal["Dealer"], n)
for seat in deal['Seats']:
seat["Direction"] = shift(seat["Direction"], n)
return deal
def buildSingleHand(hand: str) -> str:
return f'<TABLE width="300" border="0" ... | The main task of the code is to generate HTML content representing a bridge deal. It formats either a single hand or a table of hands based on specified seats, applies rotation if requested, and optionally appends an auction table. The output combines structured hand data and auction details into a cohesive HTML string... | def build(deal : dict, args) -> str:
html = ''
# rotate deal if necessary
if args.rotate:
rotateDeal(deal, args.rotate)
# if a single seat is specified, format it as a single line
seatsToShow = args.north * 'N' + args.east * 'E' + args.south * 'S' + args.west * 'W'
if len(... |
def cek_user(name):
user = read_user()
if name in user:
return user
return False
def create_config(name):
uuid = random_uuid()
config = read_config()
inbounds = []
for i in config["inbounds"]:
if i["protocol"] == "vless" or i["protocol"] == "vmess":
new_user = {"... | The code creates a user account by generating unique VMess, Vless, and Trojan configurations with WebSocket and gRPC protocols. It checks if the user exists, generates a UUID, constructs encoded connection strings, stores them in a dictionary, updates user data, restarts the Xray service, and returns the configurations... | def create_acount(name):
if cek_user(name): return {"status": 404, "message": "user already exist.."}
uuid = create_config(name)
data_vmessWs = {"add": domain,"aid": "0", "host": "","id": str(uuid),"net": "ws","path": "/xrayvws","port": "443","ps": name,"scy": "auto","sni": "","tls": "tls","type": "","v":... |
def synthesize_speech_long(self, text, filepath):
sentences = text.split(".") # simple split by dot
wavs = []
s_prev = None
for text in sentences:
if text.strip() == "":
continue
text += "." # add it back
noise = torch.randn(1, 1, 256... | This code synthesizes speech from text, handling long texts via a dedicated method and short texts using a diffusion model. It generates audio by inferring from text and noise, calculates the real-time factor (RTF) for performance, then writes the output to a file at 24kHz sampling rate. | def synthesize_speech(self, text, filepath):
if len(text.split(".")) > 1:
self.synthesize_speech_long(text, filepath)
else:
start = time.time()
noise = torch.randn(1, 1, 256).to(self.device)
wav = self.inference(text, noise, diffusion_steps=5, embedding_sc... |
def get_style_image_features(image):
""" Get the style image features
Args:
image: an input image
Returns:
gram_style_features: the style features as gram matrices
"""
preprocessed_style_image = preprocess_image(image)
outputs = inception(preprocessed_style_image)
style_outp... | The function performs neural style transfer by generating an image that combines the style of a given style image with the content of a content image. It initializes a generated image from the content image, iteratively updates it using a specified optimizer, and balances style and content loss with provided weights. T... | def fit_style_transfer(style_image, content_image, style_weight=1e-2, content_weight=1e-4,
optimizer='adam', epochs=1, steps_per_epoch=1):
""" Performs neural style transfer.
Args:
style_image: image to get style features from
content_image: image to stylize
style_target... |
def ID():# Validator that a path is given
verificarPath()
if sys.argv[2].split("=")[0] == "id":
path = sys.argv[2].split("=")[1]
if path != "":##verify that is not empty
return path
else:
return ''
else:
return ''
def listaArchivos(path):####ask for ex... | The code's main task is to search for files based on a specified ID type (protein, accession, or name) and accession number, or return all files if no ID is provided. It processes input arguments, determines the search type, filters files using corresponding functions, and returns matched files. If the ID format is inv... | def queryfiles():##loop through the files to get the match you want to search according to waht to look for
filestot=[]
if ID() != '': ##Search for a file with the specific id
files=listaArchivos(location(sys.argv))## files in wich we are going loop
type=ID().split(':')[0]#Getting the type of se... |
def queryfiles():##loop through the files to get the match you want to search according to waht to look for
filestot=[]
if ID() != '': ##Search for a file with the specific id
files=listaArchivos(location(sys.argv))## files in wich we are going loop
type=ID().split(':')[0]#Getting the type of se... | The function processes genomic data files based on user-specified options. It validates input arguments, extracts query parameters, and dispatches tasks to specialized functions for handling file listings, genome statistics, header details, DNA sequences, protein lists, and protein sequences. The core task is to route ... | def Principalfunction(): # function that does something depending on the option arg
specificfiles=queryfiles()
if len(sys.argv) != 4:
raise Exception('Enter valid options')
else:
queryoption=sys.argv[3]#available files, totals, header, dnaseq, proteinlist, proteinseq
if queryoption==... |
def _set_scoped_token(
self, resource_type: str, resource_name: str, resource_actions: list
):
if not self.auth_client: # Registry does not require authentication
return
url = (
f"{self.auth_service}?scope={resource_type}:{resource_name}"
+ f":{','.join(... | The main task of the code is to retrieve a Docker manifest from a container registry by making an HTTP GET request to a specified endpoint. It constructs the manifest URL using the provided name and tag, sets necessary headers and authentication tokens, fetches the manifest data, and optionally expands the configuratio... | def get_manifest(
self, name: str, tag, expand_config: bool = True
) -> DockerManifest:
self.last_name = name
# reference = f"{name}:{tag}"
# self.last_reference = reference
self._set_scoped_token("repository", name, ["pull"])
self.http_client.headers["Accept"] = spec... |
def get_percentage_best_instances(instances, percentage, fitness_function):
number_of_best_instance = int(len(instances) * percentage)
return get_number_best_instances(instances, number_of_best_instance, fitness_function)
def mutation_local_search(instance, fitness_function, constraint=(lambda x: True)):
def compar... | The main task of the code is to generate the next generation of instances in a genetic algorithm by selecting top-performing instances, applying crossover and mutation, and optionally enhancing them via local search. It preserves the best 10% of instances, performs crossover on random pairs, applies mutation with a spe... | def generate_next_generation(instances, population_size, fitness_function, constraint=(lambda x: True), probability_of_mutation=0.0, mutate_local_search_best=False, mutate_local_search_all=False, max_time_per_instance=float('inf')):
new_instances = list()
new_instances.extend(get_percentage_best_instances(instances, ... |
def show_message_box(self, title, message):
msg_box = QMessageBox()
msg_box.setWindowTitle(title)
msg_box.setText(message)
msg_box.setIcon(QMessageBox.Warning)
msg_box.setStandardButtons(QMessageBox.Ok)
msg_box.exec_()
def get_selected_checkbox_value(self, checkboxes):
... | The code's main task is to collect user input data (name, contact details, health status, and exposure history), validate completeness, store it in a SQLite database and CSV file, and display a quarantine alert if certain conditions are met. It handles checkbox selections, performs data insertion with error handling, a... | def add_entry(self):
name = self.entry_name.text()
phone = self.entry_phone.text()
email = self.entry_email.text()
address = self.entry_address.text()
last_place_visited = self.entry_last_place_visited.text()
# Check if all fields are filled
if not name or not ph... |
def show_message_box(self, title, message):
msg_box = QMessageBox()
msg_box.setWindowTitle(title)
msg_box.setText(message)
msg_box.setIcon(QMessageBox.Warning)
msg_box.setStandardButtons(QMessageBox.Ok)
msg_box.exec_()
def clear_other_fields(self):
self.entry_sear... | The main task of the code is to search a SQLite database for contacts matching a user-input search term, display results in a new GUI window, and handle cases with no results or database errors. It queries multiple fields (name, phone, email, etc.) using wildcards, formats results into a text view, and clears other UI ... | def search_entry(self):
search_term = self.entry_search.text()
try:
# Search for entries in the database that match the search term
self.c.execute('''SELECT * FROM contacts WHERE
name LIKE ? OR phone LIKE ? OR email LIKE ? OR address LIKE ? OR last_... |
def initialize_rocks() -> List[List[Tuple[int, int]]]:
rocks = []
for line in puzzle_input:
rocks.append([eval(coordinates) for coordinates in line.split(' -> ')])
return rocks
def get_rocks_min_max_indices(rocks: List[List[Tuple[int, int]]]) -> Tuple[int, int, int, int]:
min_x = min_y = 1000000... | The code simulates sand pouring into a grid with rock obstacles. It first calculates how many sand units fall before hitting the grid edge (14.1), then repeats with an extended floor to determine when sand can no longer settle (14.2). The results are printed as counts, followed by the final grid state showing sand dist... | def main():
rocks = initialize_rocks()
min_x, min_y, max_x, max_y = get_rocks_min_max_indices(rocks)
normalize_rocks(rocks, min_x)
14.1
scan = initialize_scan_map(min_x, max_x, max_y)
add_rocks_to_scan(scan, rocks)
add_sand_starting_point(scan, min_x)
try:
i = 0
while Tr... |
def stop():
global server_socket
if server_socket:
server_socket.close()
server_socket = None
def handle_user_credentials(client):
send_header(client)
client.sendall('<html><body>'.encode('utf-8'))
client.sendall('<h1>User Configuration</h1>'.encode('utf-8'))
client.sendall('<fo... | This code sets up a web server on a microcontroller (e.g., ESP32) to handle HTTP requests for user/Wi-Fi configuration. It initializes Wi-Fi in station and access point modes, binds a socket to the specified port, and listens for client connections. Upon receiving requests, it parses URLs, handles endpoints like '/user... | def start(port=80):
global server_socket
addr = socket.getaddrinfo('0.0.0.0', port)[0][-1]
stop()
wlan_sta.active(True)
wlan_ap.active(True)
wlan_ap.config(essid=ap_ssid, password=ap_password, authmode=ap_authmode)
server_socket = socket.socket()
server_socket.bind(addr)
server_... |
def set_opt_model_path_and_log(self, train_loader, model_id):
model_name = self.name + '_' + train_loader.name + '_' + str(model_id)
self.opt_model_path = CKPT_PATH + model_name + '.ckpt'
self.last_model_path = CKPT_PATH + model_name + '_last.ckpt'
def set_log(self, ckpt_path):
model_name = ckpt_path.split(CKPT... | This code trains a model using provided data loaders, iterating over epochs to perform training and validation phases. It initializes paths, logs, and model settings, accumulates loss, saves checkpoints, and adjusts the learning rate dynamically during each epoch to optimize model performance. | def train(self, train_loader, val_loader, model_id=0, polygon_version='polygon50'):
self.set_opt_model_path_and_log(train_loader, model_id)
self.set_log(self.opt_model_path)
self.polygon_version = polygon_version
for epoch_id in range(1, self.num_epoch + 1):
self.epoch_id = epoch_id
self.show_epoch_info(... |
def load_ckpt(self, ckpt_path="opt"):
if ckpt_path == "opt": ckpt_path = self.opt_model_path
if ckpt_path == "last": ckpt_path = self.last_model_path
self.model.load_state_dict(torch.load(ckpt_path))
def run_epoch(self, loader):
if loader.is_training: self.model.train()
else: self.model.eval()
self.refresh_... | The main task of the code is to evaluate a pre-trained model using a test dataset. It loads the model weights from a checkpoint, runs an inference epoch on the test data, displays detailed counting results, and saves generated masks. The function combines model evaluation, performance analysis, and output preservation ... | def test(self, ckpt_path, test_loader):
self.load_ckpt(ckpt_path)
self.run_epoch(test_loader)
self.eval_rc.show_detail_counting_result()
self.save_masks(ckpt_path, test_loader) |
def collect_seeds(self, min_num_pixels=256):
run_id = 1
q = queue.Queue()
for i in range(self.height):
for j in range(self.width):
if self.dual_map[i, j] == SEED_LEVEL and self.pixel_id[i][j] == 0:
buffer = {(i, j): True}
q.put((i, j))
while not q.empty():
p = q.get()
for id1 in... | The main task of the code is to process data through a sequence of steps: collecting initial seeds, gathering their neighbors, expanding iteratively via a loop, and generating an instance map. This workflow likely supports tasks like graph traversal, data exploration, or information retrieval, structuring relationships... | def process(self):
self.collect_seeds()
self.collect_neighbors()
self.expand_loop()
self.produce_instance_map() |
def compute_genotype_similarity(genotype_matrix: np.ndarray) -> np.ndarray:
"""Compute the genetic similarity between groups of haplotypes
at every genotyped marker. At each marker, divide the haplotypes into
two groups based on the parental allele each haplotype inherited. In
each group, calculate all... | The function calculates a confidence interval for the marker index with the maximum distance peak by performing bootstrap resampling. It resamples mutation spectra and genotypes, computes distances via IHD scans, records peak markers across permutations, and returns the percentile-based bounds defining the specified co... | def calculate_confint(
spectra: np.ndarray,
genotype_matrix: np.ndarray,
covariate_matrix: np.ndarray,
distance_method: Callable = compute_manual_chisquare,
n_permutations: int = 10_000,
progress: bool = True,
adjust_statistics: bool = True,
conf_int: float = 90.0,
) -> Tuple[int, int]:
... |
def compute_node_entropy(self,label):
# compute the entropy of a tree node (add 1e-15 inside the log2 when computing the entropy to prevent numerical issue)
# calculate the probability 'p' of the label
entropies = []
for l in range(10):
p = (label == l).sum() / max(l... | The code recursively builds a decision tree by splitting data based on selected features. It checks if a node should be a leaf using entropy thresholds and majority voting for labels. If not a leaf, it selects the optimal feature, splits data into left/right subsets, and recursively constructs child nodes until termina... | def generate_tree(self,data,label):
# initialize the current tree node
cur_node = Tree_node()
# compute the node entropy
node_entropy = self.compute_node_entropy(label)
# determine if the current node is a leaf node based on minimum node entropy (if yes, find the corresponding ... |
def __get_trimmed_name(name, trim_serializer_output):
key = "Serializer"
return name[:-len(key)] if trim_serializer_output and name.endswith(key) else name
def __map_choices_to_union(field_name, choices):
'''
Generates and returns a TS union type for all values in the provided choices OrderedDict
''... | The function processes a Django REST framework field to generate a TypeScript field name and type, handling nested serializers, enums, and custom mappings. It determines the type based on field properties, applies camelCase formatting if enabled, and appends '[]' for many-to-many fields, returning the transformed name ... | def __process_field(field_name, field, context, serializer, trim_serializer_output, camelize,
enum_choices, enum_values, enum_keys):
'''
Generates and returns a tuple representing the Typescript field name and Type.
'''
if hasattr(field, 'child'):
is_many = True
field... |
def __get_trimmed_name(name, trim_serializer_output):
key = "Serializer"
return name[:-len(key)] if trim_serializer_output and name.endswith(key) else name
def __process_field(field_name, field, context, serializer, trim_serializer_output, camelize,
enum_choices, enum_values, enum_keys):
... | The main task of the code is to generate a TypeScript interface from a Django REST Framework (DRF) serializer by mapping its fields to appropriate TypeScript data types. It processes each field to determine its type, adds optional modifiers (?) for non-required or read-only fields, handles nullability, and includes ann... | def __get_ts_interface(serializer, context, trim_serializer_output, camelize, enum_choices,
enum_values, enum_keys, annotations):
'''
Generates and returns a Typescript Interface by iterating
through the serializer fields of the DRF Serializer class
passed in as a parameter, and m... |
def __generate_imports(context, trim_serializer_output):
imports_str = ''
if context in __imports:
for package, serializers in __imports[context].items():
names = []
for serializer in serializers:
name = __get_trimmed_name(
serializer.__name__,... | This function generates TypeScript interfaces from DRF serializers, writing them to a specified file. It uses context parameters to determine which serializers to process, with options to customize output formatting (e.g., trimming, camelCase, enum handling). It also generates accompanying TypeScript enums if enabled, ... | def generate_ts(output_path, context='default', trim_serializer_output=False, camelize=False,
enum_choices=False, enum_values=False, enum_keys=False, annotations=False):
'''
When this function is called, a Typescript interface will be generated
for each DRF Serializer in the serializers dict... |
def __generate_interfaces(context, trim_serializer_output, camelize, enum_choices, enum_values,
enum_keys, annotations):
if context not in __serializers:
return []
return [__get_ts_interface(serializer, context, trim_serializer_output, camelize,
e... | The function `get_ts` generates TypeScript interfaces and enums based on the provided context and formatting options (e.g., trimming, camelize, enum handling). Instead of writing output to a file like `generate_ts`, it returns the combined result as a raw string. It processes interfaces and enums separately, ensuring u... | def get_ts(context='default', trim_serializer_output=False, camelize=False, enum_choices=False,
enum_values=False, enum_keys=False, annotations=False):
'''
Similar to generate_ts. But rather than outputting the generated
interfaces to the specified file, will return the generated interfaces
a... |
def add_gang(routine, dimension):
'''
routine: Subroutine object
dimension: RangeIndex object
Add acc loop gang to loops in routine matching dimensions.
'''
loops = [l for l in FindNodes(Loop).visit(routine.body) if l.variable == dimension.index]
loop_map = {}
for l in loops:
... | This function adds parallelism configurations to a subroutine. It conditionally incorporates gang, vector, and sequential processing based on provided RangeIndex objects, then universally applies parallel processing via add_parallel(routine). The main task is to configure a subroutine with specified parallel execution ... | def add_acc(routine, gang=None, vector=None, sequential=None):
'''
routine: Subroutine object
gang: RangeIndex object
vector: RangeIndex object
sequential: RangeIndex object
'''
if gang:
add_gang(routine, gang)
if vector:
add_vector(routine, vector)
if sequential:... |
def make_module(routine):
"""
Create a module based on routine name.
"""
module_name = routine.name + "_MOD"
return Module(name = module_name)
def remove_associate(routine):
"""
routine: Subroutine object
Substitute all acssociated variables with their original variable,
then repl... | The function `hoist_fun` transforms a computational driver code by optimizing and restructuring its structure. It declares dimension objects for array transformations, creates a module, and modifies the driver's code by removing redundant elements (e.g., hooks, unused variables), hoisting loops for parallelism, and reo... | def hoist_fun(driver):
# Declare dimension objects needed for transformation
horizontal = Dimension(name='horizontal', size='klon', index='jlon', bounds=('kidia', 'kfdia'))
vertical = Dimension(name='vertical', size='klev+1', index='jlev', bounds=('0', 'klev'))
gdim = Dimension(name='gdim', size='3', i... |
def getTransactions(blockId):
transactionList =list()
args = [blockId]
sp = 'getTransactionsperBlock'
answers = useReturnDb(args, sp)
for answer in answers:
transactionList.append(answer[0])
return transactionList
def deleteMoreTransactions(transactionDeleteList):
connection = connec... | The code compares a provided TransactionList with database transactions for a specific block. It identifies transactions to delete (present in DB but not in list) and add (present in list but not in DB), then executes these operations while handling potential MySQL errors. | def checkTransactions(TransactionList, blockId):
transactionDeleteList = list()
transactionUpdateList = list()
transactionsDB = getTransactions(blockId)
for transaction in transactionsDB:
if transaction not in TransactionList:
args = (transaction, blockId)
transactionDele... |
def Hash(self, newBlock):
tempString = {'blockId': newBlock.Id, 'transactions': newBlock.data, 'previousHash': newBlock.previousBlockHash }
blockString = json.dumps(tempString).encode()
return hashlib.sha256(blockString).hexdigest()
def proofOfWork(self, blockId, currentHash):
temp = url... | The code resolves blockchain conflicts by validating a block's hash via proof-of-work. If valid (answer=1), it updates the block and propagates its hash. If requiring consensus (answer=2), it queries a remote service to verify transactions, updates hashes, and ensures consistency across the network. | def resolveConflicts(self, block, isNew):
self.currentHash = self.Hash(block)
answer = self.proofOfWork(block.Id, self.currentHash)
if answer == 1:
deleteBlockTransactions(block.Id)
addTransaction(block)
self.updateBlock(block)
self.sendHash(block.... |
def getDbBlocks():
args = None
sp = 'getAllBlocks'
answer = useReturnDb(args, sp)
return answer
def proofOfWork(self, blockId, currentHash):
temp = url + "Transaction/CheckHash/"
payload = {'BlockchainNumber': blockId, 'Hash': currentHash}
headers = {'Content-Type': 'application/... | The main task of the code is to validate a blockchain by verifying each block's proof-of-work, updating hashes, resolving conflicts, and ensuring consistency. It processes new blocks from the database, checks their validity, creates new blocks if needed, handles transaction propagation, and extends the chain up to the ... | def valid_chain(self, lastBlockId):
num = 0
newBlocks = getDbBlocks()
for block in newBlocks:
answer = self.proofOfWork(block[0], block[1])
if answer == 0:
newBlock = Block(block[0], self.currentHash)
self.currentHash = self.Hash(newBlo... |
def sale(self, row):
volume = self.apply_sale_commission(self.price * self.stocks_count)
self.benefit = volume - self.volume
self.volume = volume
self.current_portfolio += self.volume
self.fill_report_dict(row.name)
self.is_bought = False
def buy(self, row):
self.... | The code executes trading actions based on a strategy's DataFrame, updating a portfolio by buying/selling assets according to 'action' column values. It iterates through rows, triggers buy/sale methods conditionally, ensures final sale if holdings remain, and calculates profit percentage and net benefit. An exception i... | def trade(self, portfolio, trade_value, column='open'):
self.strategy.analyze()
self.trade_value = trade_value
self.start_portfolio = portfolio
self.current_portfolio = portfolio
df = self.strategy.df
if 'action' in df.columns:
i = 0
for index, r... |
def cors_lap(igs,xs,ndots):
h,w,_ = igs.shape
igs = np.linalg.norm(igs,axis=2)
igs = apply_gaussian(igs, 3)
al = [igs]
ps = set()
for s in range(3,xs+1,2):
al.append(apply_gaussian(igs, s))
l = np.abs(al[-1]-al[-2])
th = l.max()*0.8
pad_l = s//2
l... | The code computes corresponding points between two input images (igs_in and igs_ref) by analyzing gradient orientations, applying Gaussian smoothing, Sobel edge detection, and matching local features using a distance metric. It uses RANSAC to refine correspondences, ensuring robustness by filtering out mismatches. The ... | def set_cor_mosaic(igs_in, igs_ref):
ls = cors_lap(igs_in,xs,ndots)
lsr = cors_lap(igs_ref,xs,ndots)
ga_size = 3
in_ga=apply_gaussian(np.linalg.norm(igs_in,axis=2), ga_size)
ir_ga=apply_gaussian(np.linalg.norm(igs_ref,axis=2), ga_size)
sobel3x=np.array([[-1,0,1],[1,2,1]])
sobel3y=np.array... |
def build_gaussian_pyramid(pixel_grid, size, levels):
pyramid = []
curr_grid=pixel_grid
for _ in range(levels):
curr_grid = apply_gaussian(curr_grid, size).astype(np.uint8)
pyramid.append(curr_grid)
curr_grid = downsample(curr_grid)
return pyramid
def build_laplacian_pyramid(gaus... | This code blends two images using pyramid decomposition. It constructs Gaussian and Laplacian pyramids for both input images and a mask, then combines them hierarchically to produce a seamless blended image, leveraging multi-scale detail preservation and mask-guided fusion for natural transitions between the input imag... | def blend_images(left_image, right_image, mask):
print("building pyramids")
gaussian_pyramid_left = build_gaussian_pyramid(left_image, g_size, levels)
laplacian_pyramid_left = build_laplacian_pyramid(gaussian_pyramid_left)
gaussian_pyramid_right = build_gaussian_pyramid(right_image, g_size, levels)... |
def build_gaussian_pyramid(pixel_grid, size, levels=5):
'''
Build and return a Gaussian pyramid.
Args:
pixel_grid (ndarray): 3D numpy array representing an RGB image.
size (int): Kernel size.
levels (int): Number of levels.
Returns:
list of ndarray: List of 3D numpy arr... | The code blends two images using Laplacian pyramids and a horizontal mask. It constructs Gaussian and Laplacian pyramids for both input images, creates a mask dividing the image width into left (0) and right (255) halves, builds a Gaussian pyramid for the mask, and combines the pyramids to reconstruct a smoothly blende... | def blend_images(left_image, right_image):
'''
Smoothly blend two images by concatenation.
Tip: This function should build Laplacian pyramids for both images,
concatenate left half of left_image and right half of right_image
on all levels, then start reconstructing from the smallest one.
A... |
def stretch(igs,horizontal=True):
h,w,c = igs.shape
igs_tch = None
if horizontal:
igs_tch = np.zeros((h,2*w,c))
else:
igs_tch = np.zeros((2*h,w,c))
print("from",igs.shape)
print("to ",igs_tch.shape)
if horizontal:
for r in range(h):
for c in range... | The code performs three main tasks: (1) Image stretching (horizontal) of a toy image, (2) Image mosaicing by aligning two porto images using homography computation and warping, and (3) Image rectification of a phone image via edge detection, Hough transform for line detection, and geometric correction. Each step saves ... | def main():
##############
# step 0: stretching
##############
# read images
img_o = Image.open(datadir+'toys.jpg').convert('RGB')
igs_o = np.array(img_o)
horizontal = True
igs_tch = stretch(igs_o, horizontal)
img_tch = Image.fromarray(igs_tch.astype(np.uint8))
suffix = 'hori... |
def paused():
global pause
pygame.mixer.music.pause()
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
... | The code defines a game loop for a simple car-dodging game using Pygame. It initializes player movement, obstacle generation, collision detection, and scoring. The loop handles keyboard inputs for car control, pauses, and music toggling. Obstacles move downward, increasing in size as the player dodges them. Collision t... | def game_loop():
global pause
pygame.mixer.music.play(-1)
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
thing_start_X = random.randrange(0, display_width)
thing_start_Y = -600
thing_speed = 7
thing_width = 100
thing_height = 100
dodged = 0
gameEx... |
def get_safe_squares(data, sim_body):
fake_data = data
fake_data["you"]["body"] = sim_body[1:]
fake_data["you"]["head"] = sim_body[0]
return len(get_safe_moves(fake_data, fake_data["you"]))
def simulate_next_move(body, move):
sim_body = body
#print("SIM BODY:", sim_body)
for i in range(len(s... | The function evaluates possible moves for a snake in a game, calculating a safety score for each move by assessing factors like available safe squares, proximity to food, hazards, and health. It prioritizes moves that maximize safety, reward food acquisition, avoid hazards, and prioritize food-seeking when health is lo... | def prune_safe_moves(data, moves):
body = data["you"]["body"]
board = data["board"]
food = board["food"]
random.shuffle(moves)
safest = 0
temp = 0
safest_move = moves[0]
head = data["you"]["head"]
for move in moves:
temp = get_safe_squares(
data, simulate_next_mov... |
def handshake():
global sequenceNo
global acknowledgementNo
# create and send an empty syn packet
synPack = DataPack('', sequenceNo, acknowledgementNo, "0100")
ssocket.sendto(pickle.dumps(synPack), (receiver_host_ip, receiver_port))
addLog("snd", 'S', str(synPack.seqNo), str(synPack.ackNo), str(... | The code manages client-side file transfer operations by initiating a handshake to establish a connection, segmenting the file into manageable parts, and transmitting the data. | def handle_client():
handshake()
segmentFile()
dataTransmission() |
def __check_existence(self, column_name, column_value, table_name):
check_query = f"SELECT {column_name} FROM {table_name} WHERE {column_name} == {column_value}"
self.cursor.execute()
return len(self.cursor.fetchall()) != 0
def __seed_artist_table(self, index, details):
profile_pict, pro... | The main task of the code is to populate a database with artist and album data from MusixMatch. It generates unique artist IDs using UUIDs, checks for existing entries, and seeds artist and album tables with scraped data. The function ensures no duplicate artist IDs by regenerating UUIDs if necessary, then inserts arti... | def __seed_db(self):
if not self.connection:
return
smm = ScrapeMusixMatch()
for artist in smm():
artist_id = f"artist:{uuid.uuid1()}"
while self.__check_existence("artist_id", artist_id, "artist"):
artist_id = f"artist:{uuid.uuid1()}"
... |
def __connect(self):
try:
self.connection = psycopg2.connect(user=self.__POSTGRES_USER,
password=self.__POSTGRES_PASSWORD,
host="127.0.0.1",
port="5432",
... | The code's main task is to reset and initialize a database by connecting, dropping specified tables, creating new tables, seeding initial data, retrieving "album" data, and closing the connection, ensuring a fresh database setup for testing or deployment. | def __call__(self):
self.__connect()
self.__drop_tables(["album", "artist", "genre", "song", "song_translation"])
self.__create_tables()
self.__seed_db()
self.__get_data("album")
self.__close_connection() |
def read_args():
parser = argparse.ArgumentParser(
description="Create a new test project or test dataset on Synapse")
parser.add_argument(
"--raw-data-folder",
help=(
"Optional. Synapse ID of the Bridge Raw Data folder "
"to query for test data. Defaults to syn26253352, which "
... | The main task of the code is to set up test data on Synapse by authenticating with a service account, checking for an existing project, creating a new one if needed using a YAML template, and curating a dataset from a raw data folder and query. It logs progress and ensures test data is ready for downstream processing. | def main():
logger.info('Begin setting up test data.')
args = read_args()
# get synapse client
ssm_parameter = 'synapse-bridgedownstream-auth'
syn = get_synapse_client(ssm_parameter=ssm_parameter)
# see if project exists and get its id
principal_id = '3432808' # BridgeDownstream Synapse service account... |
def get_data_mapping(data_mapping_uri):
"""
Get a mapping to dataset identifiers from S3.
Args:
data_mapping_uri (str): The S3 URI in the format s3://bucket-name/key-name
Returns:
dict: A mapping to dataset identifiers.
"""
s3_client = boto3.client("s3")
logger = logging.ge... | The main task of the code is to validate data from S3 objects against predefined schemas and mappings, using AWS services (Glue, S3, SSM, SQS) and Synapse authentication. It retrieves workflow parameters, processes data validation, logs results, and routes invalid data to an SQS queue. The code handles STS token manage... | def main():
# Configure logger
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Instantiate boto clients
glue_client = boto3.client("glue")
ssm_client = boto3.client("ssm")
sqs_client = boto3.client("sqs")
synapseclient.core.cache.CACHE_ROO... |
def rgb_to_grayscale(image):
# Takes image of the shape HxWx3.
R, G, B = image[:, :, 0], image[:, :, 1], image[:, :, 2]
res = (R*0.299 + G*0.587 + B*0.114)
#res = res.astype(np.uint8)
return res
def gaussian_blur(image, size, sigma):
# Takes size and sigma values for the gaussian function and ap... | This function performs Canny Edge Detection on an RGB image by converting it to grayscale, applying Gaussian blur, calculating gradient magnitude/direction with Sobel filters, performing non-maximum suppression, and using hysteresis thresholding to identify and connect edges. It returns the final edge map after analyzi... | def canny_edge_detection(image, gaussian_blur_size, gaussian_blur_sigma, hysteresis_t1, hysteresis_t2):
# Runs Canny Edge Detection algorithm for the given RGB image.
edges = None
# Step 1: Convert the image to grayscale
gray_image = rgb_to_grayscale(image)
# Step 2: Apply Gaussian Blur
blurre... |
def extracted_text(self):
extractedInformation=''
for i in range(len(self.images)):
extractedInformation += pytesseract.image_to_string(self.images[i])
return extractedInformation
def final_function_combined(self,raw_data):
info=self.spliting_with_newline_char(raw_data)
info_l=self... | The code combines data from a header and footer into a single dictionary. It extracts raw header text, processes it into a dictionary (`f_dic`), extracts footer data into another dictionary (`b_dic`), and merges them using the union operator (`|`). The final merged dictionary is returned as `final_dic`, integrating bot... | def combined_data(self):
raw_header=self.extracted_text()
f_dic=self.final_function_combined(raw_header)
b_dic=self.extracting_footer(raw_header)
final_dic=f_dic|b_dic
return final_dic |
def _get_encoding(self, batch, doc):
input_ids, attention_masks, type_ids, attribute_ids = bert_prepare_from_raw_dataset(self.tokenizer, batch, doc,
self.device, self.MAX_LEN,
... | The code processes input pairs by encoding them into hidden states, computes cross-attention interactions, extracts features, applies a CNN for fusion, generates hash codes via linear layers, and predicts matching scores using softmax. It measures encoding, interaction, and block computation times for performance track... | def forward(self, batch, doc):
self.encode_start += time.time()
hs_q, Q_mask = self._get_encoding(batch[0], doc)
Q = hs_q[2:3]
hs_a, A_mask = self._get_encoding(batch[1], doc)
A = hs_a[2:3]
Q_Amask_matrix = torch.matmul(Q_mask.unsqueeze(dim=-1).float(), A_mask.unsqueeze(d... |
def load_namelist(filename):
with open(filename) as f:
lines = filter(lambda x: len(x.strip()) >= 1, f.readlines())
return list(map(lambda x: x.strip().strip('"'), lines))
def enrichment_pvalue(
ref_set: Sequence or Set,
que_set: Sequence or Set,
universe: Union[List, Set],
... | The code defines a test function to evaluate statistical enrichment analysis. It loads reference, query, and universe datasets, then tests two methods: single-set enrichment p-value calculation and multi-set p-values with randomization. Results are logged for validation. | def __test__():
datadir = Path(__file__).parent / 'test_data'
universe = load_namelist(datadir / 'universeSet.txt')
ref_set = load_namelist(datadir / 'refSet.txt')
que_set = load_namelist(datadir / 'querySet.txt')
# test 1
res = enrichment_pvalue(ref_set, que_set, universe)
logging.info(res... |
def generate_token():
client_id = "DylanThi-SlideRul-PRD-1aba4315e-34bf385d"
with open("/home/dylan/ebay-client-secret", "r") as f:
client_secret = f.read().rstrip()
authorization = b"Basic " + base64.b64encode(bytes(client_id + ":" + client_secret, 'utf-8'))
r = requests.post(
"https:/... | The main task of the code is to append items to an existing collection by their IDs. It generates a token if not provided, retrieves item data using `item_full_data_simple` with a specified origin, and adds each item to the existing data via `append_to_existing`. The function ensures items are marked as "added_directly... | def append_by_id(item_ids, token=None):
if token is None:
token = generate_token()
for item_id in item_ids:
origin = 'added_directly'
item = item_full_data_simple(item_id, token, origin=origin)
append_to_existing([item]) |
def hurestic(self,seq):
if(self.H==1):
return self.h1(seq)
elif(self.H==2):
return self.h2(seq)
def getIndex(self,index):
j = index%PUZZLE
i = int(index/PUZZLE)
return i,j
def swap(self,i,j,seq):
c = seq[i]
seq[i] = seq[j]
seq[j] = ... | This code implements an Iterative Deepening A* (IDA*) search algorithm to solve a sliding puzzle. It explores nodes by recursively expanding states, checking if the current sequence matches the goal state (FINSTATE). If not, it calculates a cost using depth and a heuristic, pruning paths exceeding maxCost. The function... | def ids(self,node,FINSTATE,maxCost):
seq = node.key.copy() #Getting the sequnce
depth = node.value #Getting the depth of node
#print("Checking node:",seq," Depth:",depth)
#Checking if the node is the answer
if seq == FINSTATE:
self.finNode = node
ret... |
def hurestic(self,seq):
if(self.H==1):
return self.h1(seq)
elif(self.H==2):
return self.h2(seq)
def ids(self,node,FINSTATE,maxCost):
seq = node.key.copy() #Getting the sequnce
depth = node.value #Getting the depth of node
#print("Checking node:",seq,... | This function performs iterative deepening search with a threshold-based heuristic to find a path from an initial state to a final state. It initializes a root node, iteratively explores states, and adjusts the threshold based on the cost returned by the search. If the cost exceeds the threshold or a solution is found,... | def search(self,INITSTATE,FINSTATE):
self.startTime = time.time()
tracemalloc.start()
self.root = Node(INITSTATE,0)
threshhold = self.hurestic(INITSTATE)
while True:
self.expanded = 0
self.maxdepth = 0
self.parent = []
self.parent... |
def printGameList(bowlingGames, bmSettings, gameStatus):
while True:
h.titleMe(f"{gameStatus} Games List", False)
gamesList = bowlingGames[gameStatus]
selectionToUUID = []
selectedGame = None
ticker = 0
for u in gamesList.keys():
selectionToUUID.append(u)... | The code provides a menu-driven interface for managing bowling games, allowing users to view active/archived games, add new games with UUIDs, archive games, save/load game data, and return to the main menu. It uses functions like printGameList, addGame, switchGameStatus, saveGameList, and loadGames to handle specific t... | def gamesMenu(bowlingGames, bmSettings):
bowlingGames = bowlingGames
bmSettings = bmSettings
while True:
h.titleMe("Games Menu", False)
print("Please make a selection from the options below:")
print("1) View current active games")
print("2) Add new game")
print("3) ... |
def show(self):
if(len(self.AccountList) > 0):
for i in range(0, len(self.AccountList)):
if(i == 0):
print("\n\n0. Return");
print("\n" + str(i + 1) + ". " + self.AccountList[i].Name);
try:
selectedAcc: int = int(input("... | The main task of the code is to display a password manager menu, allowing users to view stored accounts/passwords, add new entries, or exit. On first call, it shows a welcome message. The loop repeatedly presents options, processes user input, and executes corresponding actions (showing data, generating new accounts, o... | def mainMenu(self, firstCall: bool):
if(firstCall):
print("\n\nWelcome to Password Manager v" + appVersion);
firstCall = False;
while(True):
# Show options
print("\n\n1. Show accounts/passwords");
print("\n\n2. New account/password");
... |
def error(self):
print(self.current_char)
raise Exception('Invalid character. ')
def advance(self):
self.pos += 1
if self.pos > len(self.text) - 1:
self.current_char = None
else:
self.current_char = self.text[self.pos]
def escape_sequence(self) -> int:
... | This function parses a string literal from the input, collecting characters into a bytearray. It checks for opening quotes, processes escape sequences (like \\n), and appends ASCII values of valid printable characters. It returns the bytearray upon closing quotes or raises an error for invalid input. | def string(self) -> bytearray:
result = bytearray()
if self.current_char != '"':
self.error()
self.advance()
while self.current_char is not None and self.current_char != '\n' and self.current_char in printable:
if self.current_char == '"':
self.adv... |
def skip_whitespace(self):
while self.current_char is not None and self.current_char.isspace():
self.advance()
def integer(self) -> int:
result = ''
while self.current_char is not None and self.current_char.isdigit():
result += self.current_char
self.advance()... | This method identifies and returns the next token from the input stream by checking the current character's type, handling whitespace, digits, strings, identifiers, and punctuation, then advancing the scanner or raising an error if no valid token is found. | def get_next_token(self) -> Token:
while self.current_char is not None:
if self.current_char.isspace():
self.skip_whitespace()
continue
if self.current_char.isdigit():
return Token(TokenType.INTEGER, self.integer())
... |
def predict_person(img_path):
# To Predict the person in the image
img=resize_img(img_path)
(h, w) = img.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(img, (300, 300)),0.007843, (300, 300), 127.5)
net.setInput(blob)
detections = net.forward()
for i in np.arange(0, detections.shape[2]):
confidence = detec... | The code detects a person in an image, resizes it, extracts eyes/lips, removes the background, generates a mask, and crops skin with color data. If extraction fails, it uses the full image. Returns cropped skin, color tone, mask, and resized image; otherwise, returns None if no person is found. | def masking_and_colorization(file_path):
# Check person in image and mask and crop the image
label = predict_person(file_path)
if label:
img=resize_img(file_path)
try:
eyes_lips=extract_eyes_and_lips(file_path)
output=bg_remove(eyes_lips)
mask=get_mask(output)
crop_skin,avrg_color_tone_input=crop(o... |
def create_leaf(part: pd.DataFrame,
target_column: str = t_col) -> int:
"""
create a terminal node / leaf
:param part: data in the leaf
:param target_column: column that is checked vor majority voting
:return: int
"""
# return the most frequent value (always 0/1) from the da... | The function recursively splits a decision tree node (dictionary) into child nodes until reaching the maximum depth, minimum leaf size, or achieving a pure node (single class). It modifies the node in-place, converting child nodes into leaves if they meet termination criteria (e.g., size ≤ min_size, pure class distribu... | def split(node: dict,
max_depth: int,
min_size: int,
depth: int = 1,
target_column: str = t_col) -> None:
"""
takes in a dict and modifies (recursively splits) it
until max depth is reached or the sub-dicts (child nodes) are pure
the dict is modified in place
... |
def normalize_name(game_name):
if game_name in mapping:
return [mapping[game_name]]
normalized_name = game_name
for char in ":'\"?!%$^*/\\":
normalized_name = normalized_name.replace(char, '')
# Gnome sometimes removes the '-' and sometimes keep it.
# So make up all possibily combi... | The code scrapes and stores historical viewer and streamer data for a game from SullyGnome, using normalized names to handle variations. It skips existing files if specified, collects monthly statistics from 2015 to the prior month, and saves results in JSON format with error handling. | def scrape_game(game_name, game_id=None, skip_existing=False):
normalized_names = normalize_name(game_name)
for normalized_name in normalized_names:
#print('Game={}, normalized={}'.format(game_name, normalized_name))
game_output_dir = 'output/games'
make_dir(game_output_dir)
i... |
def read_mapping():
with open('config/mapping.json', 'r') as infile:
container = json.load(infile)
for entry in container:
if 'name' in entry and 'normalized' in entry:
mapping[entry['name']] = entry['normalized']
else:
logger.fatal('Mal-formed... | The main task of the code is to scrape game data from websites using command-line arguments. It supports parsing specific URLs, individual games, StreamCamel game lists, or company-specific games. The code caches requests, processes HTML content, and invokes `scrape_game` with parameters like game names, IDs, and skip ... | def main(args):
read_mapping()
parser = argparse.ArgumentParser(description='GnomeSully Scrapping')
parser.add_argument("--url", type=str, help="Full game URL to parse")
parser.add_argument("--game", type=str, help="Game to parse (e.g. Fortnite)")
parser.add_argument("--streamcamel_games", default=... |
def BFS(size):
puzzle = Board(GoalBoard(size))
puzzle = puzzle.generate_random_initial_state(100)
print("Puzzle to be solved")
puzzle.printState()
print("Steps")
solver = Solver(puzzle)
initialTime = time.time()
path,count = solver.BFS()
finalTime = time.time()
step = 0
nodeS... | The main task of the code is to present a menu-driven interface for solving a board problem using different algorithms. Users can select options to set the board size, solve using BFS, Iterative Deepening, both methods, or input values from a text file. The program validates the board size and executes the chosen solve... | def main():
option = 0
size = 0
while(option != 5):
print("1.- Enter the board size")
print("2.- Solve the board using of BFS")
print("3.- Solve the board using Iterative Deepening")
print("4.- Solve the board using BFS and Iterative Deepening")
print("5.- Enter value... |
def _handle_login_message(self, client: socket.socket, data: str) -> None:
"""
Gets socket and message data of login message and checks the username and password if match.
If not - sends error and finished. If all ok, sends OK message and adds user and address
to logged_users.
... | The function routes incoming client messages to the appropriate handler based on the command (e.g., login, logout, get_score), validates input types, and raises TypeErrors for invalid arguments. It uses conditional checks to call specific private methods for each command, ensuring proper message processing and error ha... | def handle_client_message(self, client: socket.socket, cmd: str, data: str) -> None:
"""
Gets message cmd and data and calls the right function to handle command.
Then, the message will be appended to the `_messages_to_send` list.
------
Parameters
------
client:... |
def get_best_split(features, labels):
"""
Finds the best feature and threshold to split the data to maximize information gain.
Args:
features (np.ndarray): Array of feature data.
labels (np.ndarray): Corresponding array of labels.
Returns:
tuple: A tuple containing ... | The function recursively constructs a decision tree by selecting optimal or random features to split data, using information gain. It creates leaf nodes when labels are pure or samples fall below a pruning threshold. The tree splits data recursively, building left and right subtrees until termination conditions are met... | def build_tree(features, labels, pruning_threshold, feature_selection="optimized"):
"""
Recursively builds a decision tree using the given features and labels.
Args:
features (np.ndarray): The feature data.
labels (np.ndarray): The corresponding labels.
pruning_threshold (int): ... |
def reset_game(self):
self.player, self.entities, self.game_map, self.message_log, self.game_state = \
get_game_variables(self.constants)
def load_saved_game(self):
self.player, self.entities, self.game_map, self.message_log, self.game_state = load_game()
def play_game(self) -> bool:
... | This code defines the main game loop that handles the game's primary operations, including displaying the main menu, processing user inputs (keyboard/mouse events), and transitioning between the menu and gameplay. It manages starting a new game, loading saved games (with error handling for missing files), and exiting t... | def run(self):
""" Main game loop """
show_main_menu = True
show_load_error_message = False
main_menu_background_image = tcod.image_load('menu_background.png')
key = tcod.Key()
mouse = tcod.Mouse()
while not tcod.console_is_window_closed():
tcod.sys... |
def advance(self):
self.token_idx += 1
if self.token_idx < len(self.tokens):
self.current_token = self.tokens[self.token_idx]
return self.current_token
def power(self):
return self.binary_operation(self.atom, (TT_POW, ), self.factor) | This method parses a factor, handling unary plus/minus operators by recursively parsing the operand and returning a UnaryOpNode, or delegating to the power method for non-unary cases. | def factor(self):
'returns NumberNode if the current token is an INT or FLOAT'
res = ParseResult()
tok = self.current_token
if tok.type in (TT_PLUS, TT_MINUS):
res.register(self.advance())
factor = res.register(self.factor())
if res.error:
... |
def rnd(self, power_of_command: int) -> int:
"""Returns a randomly generated + or - integer,
influenced by the incoming power factor"""
pos = 1
if getrandbits(1):
pos = -1
result = (randrange(1, 5) + randrange(power_of_command)) * pos
logging.debug(f'Rnd resul... | This function generates random movement patterns or shapes based on a peak value, selecting from options like drawing lines, creating squiggles, placing dots, or forming note heads. It logs the current position, chooses a random action (0–5), executes the corresponding motion (e.g., moving to a new point, squiggling, o... | def mid_energy_response(self, peak):
(x, y, z, r, j1, j2, j3, j4) = self.pose()
logging.debug(f'Current position: x:{x} y:{y} z:{z} j1:{j1} j2:{j2} j3:{j3} j4:{j4}')
"""between 2 and 8 make shapes in situ"""
# randomly choose from the following c hoices
randchoice = randrange(6)... |
def go_position_draw(self):
"""moves directly to pre-defined position 'Ready Position'"""
x, y, z, r = self.draw_position[:4]
self.move_to(x, y, z, r, wait=True)
def high_energy_response(self):
"""move to a random x, y position"""
self._set_queued_cmd_clear()
self.move_y_... | This function enables manual control of a robotic arm or drawing mechanism via a gamepad, allowing real-time movement and predefined actions. The left joystick controls X/Y positioning, while right buttons trigger specific movements (e.g., dots, squiggles). Triggers adjust pen height. Input scaling maps 0-255 values to... | def joystick_control(self, gamepad):
""" for use as a rapid prototyping tool in place of autonomous behaviour.
Left joystick move x & y axis,
right buttons activate differnt pre-defined moves
right trigger & bumper lifts pen"""
# scaling vars
old_min = 0
old_max =... |
def go_position_draw(self):
"""moves directly to pre-defined position 'Ready Position'"""
x, y, z, r = self.draw_position[:4]
self.move_to(x, y, z, r, wait=True)
def clear_alarms(self) -> None:
"""clear the alarms log and LED"""
msg = Message()
msg.id = 20 # this should b... | The code controls a "drawbot" by processing real-time input signals (user_in) to generate affectual responses. It operates in nested cycles (Daddy, Child, Baby), evaluating input energy levels (HIGH: >0.8, MEDIUM: 0.3–0.8, LOW: ≤0.1). HIGH triggers random data fills and exits to the Daddy cycle, MEDIUM initiates mid-en... | def drawbot_control(self):
"""Listens to the realtime incoming signal that is stored in the dataclass ("user_input")
and calculates an affectual response based on general boundaries:
HIGH - if input stream is LOUD (0.8+) then emit, smash a random fill and break out to Daddy cycle...
... |
def getName() -> str:
name = None
while not name:
name = input("What is your name: ")
if name.strip() == "":
name = None
print("You must enter a name.")
elif name == "rootADMIN":
admin()
return name
def getInt(message: str) -> int:
valid = Fals... | The code processes user input for a theme park visit, calculates costs for different ticket types, checks capacity limits, handles parking requests, generates tickets, and prints details. It loops continuously to serve multiple visitors, validating inputs and managing payments within a structured data flow. | def main() -> None:
while True:
print("Welcome to Copington Theme Park")
splitName = getName().split(" ")
surname = splitName[len(splitName)-1]
children = getInt(
f"How many children are there? (£{PARKDATA.childCost} each): ")
adults = getInt(
f"How ma... |
def check_environment(project_vars):
if not exists(project_vars["working_directory"]):
print("Working directory not found... Have you run clone_repos.py?", file=sys.stderr)
exit(1)
if len(listdir(project_vars["working_directory"])) == 0:
print("Working directory is empty... Have you ru... | The main task of the code is to generate and configure a MkDocs documentation site by checking the environment, creating guides, building the main page, configuring MkDocs settings, and executing the build process using provided project variables. | def main(project_vars):
check_environment(project_vars)
generated_guides = make_generated_guides(project_vars)
create_main_page(project_vars, generated_guides)
create_mkdocs_config(project_vars, generated_guides)
mkdocs_build() |
def get_n_neighbors_dict(self, range_value):
vote_dict = {range_value: []}
for t0 in self.data[range_value]:
votes = []
# set the time_series to compute its distance matrix
self.set_time(t0)
self.cal_distance_matrix()
distance_list = self.dist... | This function initializes three dictionaries (`vote`, `label`, `poses`) by iterating over `self.random_range` and populating them with values retrieved from `get_n_neighbors_dict`, `get_label_dict`, and `get_pos_dict` methods respectively for each index. The main task is to collect neighbor votes, labels, and positions... | def get_vote_label_pos_dict(self):
self.vote, self.label, self.poses = {}, {}, {}
for i in self.random_range:
self.vote[i] = self.get_n_neighbors_dict(i)[i]
self.label[i] = self.get_label_dict(i)[i]
self.poses[i] = self.get_pos_dict(i)[i] |
def get_vote_label_pos_dict(self):
self.vote, self.label, self.poses = {}, {}, {}
for i in self.random_range:
self.vote[i] = self.get_n_neighbors_dict(i)[i]
self.label[i] = self.get_label_dict(i)[i]
self.poses[i] = self.get_pos_dict(i)[i]
def get_pos_predict_result_li... | The main task of the code is to evaluate the correctness of predictions across different steps (from 1 to k) for a given range value. It calculates the average correctness metric for each step by comparing predicted results with true labels, then returns a list of these averaged correctness values. | def merge_vote(self, range_value):
self.get_vote_label_pos_dict()
L_d = self.vote.get(range_value)
correct_list, predict_result = [], []
for i in range(1, self.k + 1):
correct_label, predict_list = self.get_pos_predict_result_list(L_d, range_value, i)
correct = se... |
def echo(text):
"""Python 2 version of print(end='', flush=True)."""
sys.stdout.write(u'{0}'.format(text))
sys.stdout.flush()
def hit_any(loc, segments):
"""Return True if `loc' matches any (y, x) coordinates within segments."""
# `segments' -- a list composing a worm.
return loc in ... | This code implements a terminal-based snake game where a worm navigates a grid, consumes nibbles to grow, avoids self-collision, and adjusts speed dynamically. The main task is to handle game loop logic, rendering, input processing, collision detection, and score calculation for a snake-like game in the terminal. | def main():
"""Program entry point."""
# pylint: disable=too-many-locals
# Too many local variables (20/15)
term = Terminal()
worm = [Location(x=term.width // 2, y=term.height // 2)]
worm_length = 2
bearing = Direction(*LEFT)
direction = left_of
nibble = Nibble(location=worm[... |
def generate_random_points(n, max_xy):
x, y = max_xy
return [(random.randint(0, x), random.randint(0, y)) for i in range(0, n)]
def snakefy(points):
frame_i = 0
snake = [points.pop(), points.pop()]
for p in points:
WIDTH, HEIGHT = 640, 480
surface = cairo.ImageSurface(cairo.FORMAT_AR... | The code generates a snake-like path from 10 random points within a 640x480 canvas and draws it using the provided context. It creates random points, arranges them into a snake pattern, then renders the shaped path. | def draw(da, ctx):
n = 10
max_xy = (640, 480)
src = generate_random_points(n, max_xy)
src = snakefy(src)
draw_snake(ctx, src) |
def load_file_common_positive_negative_features(file, vectorizer_filename, classifier_filename, data_json):
# If the given file is an excel sheet
# print(vectorizer_filename)
ngram_vectorizer = joblib.load(vectorizer_filename)
svm = joblib.load(classifier_filename)
if len(file) == 0 and len(data_js... | The code generates positive and negative attributes from product reviews by training a logistic regression model on preprocessed text data, extracting top n-gram features with highest coefficients, filtering them using keyword lists and sentiment polarity thresholds, and returning the top X attributes for each category... | def generate_common_positive_negative_attributes_test(file, top_x_attributes, vectorizer_filename,
classifier_filename, data_json):
df = load_file_common_positive_negative_features(file, vectorizer_filename, classifier_filename, data_json)
keyword_list = loo... |
def nlp_core_dataProces(name, comment):
neural_coref_output = new_neural_coref(name, comment)
text = remove_specialchars(neural_coref_output)
text = " ".join(text.split())
text = text.replace("'", "`")
blob = TextBlob(text)
split_sentences = split_sentence_simplified(blob)
return split_sent... | The main task of the code is to extract and analyze sentiment scores from reviews by identifying hidden entities and their associated sentences. It uses a pre-trained SVM classifier and vectorizer to predict sentiment (negative, neutral, positive) for the entire review and individual hidden entity sentences. The functi... | def Extract_Score(df, classifier_filename, vectorizer_filename, list_of_entity_name, max_pos_threshold, max_neg_threshold):
result = []
ngram_vectorizer = joblib.load(vectorizer_filename)
svm = joblib.load(classifier_filename)
for i, row in df.iterrows():
processed_text = nlp_core_dataProces(row... |
def generate_common_positive_negative_attributes_test(file, top_x_attributes, vectorizer_filename,
classifier_filename, data_json):
df = load_file_common_positive_negative_features(file, vectorizer_filename, classifier_filename, data_json)
keyword_list = loo... | The function identifies common positive and negative attributes from text data using machine learning. It preprocesses text, vectorizes features, trains a logistic regression model to find optimal hyperparameters, extracts significant features based on coefficients, and filters them using sentiment analysis (TextBlob) ... | def generate_common_positive_negative_attributes(file, top_x_attributes, Bigram_Boolean, vectorizer_filename,
classifier_filename, data_json):
if Bigram_Boolean == "True":
dic_common_positive_negative_features = generate_common_positive_negative_attributes_te... |
def generate_entity_specific_positive_negative_attributes_test(file, top_x_attributes, vectorizer_filename,
classifier_filename, data_json, list_of_entity_name):
# print("Bigram ---------------------------------------------")
df, positive_keyword_li... | The function generates entity-specific positive and negative attributes by analyzing text data. It preprocesses comments, vectorizes text, trains a logistic regression classifier to identify significant features, filters these features by sentiment using TextBlob, and returns a dictionary containing lists of positive a... | def generate_entity_specific_positive_negative_attributes(file, top_x_attributes, Bigram_boolean,
vectorizer_filename, classifier_filename, data_json,
list_of_entity_name):
if (type(list_of_entity_nam... |
def jsontodf(data_json, file):
if len(file) == 0 and len(data_json) == 0:
print("Do provide a data file or json file")
# Needs a check
return "Do provide a data file or json file"
if file and len(data_json) == 0:
if (file.endswith('.xlx') or file.endswith('.xlsx')):
... | The function extracts positive and negative attributes from reviews and hidden entity sentences using classifiers and thresholds. It updates sentiment labels (positive/negative) based on attribute counts, processes original and modified reviews, and returns a structured dataset with annotated attributes and predicted s... | def ExtractHidden_Score_Generate_Attributes(data_json, data_file, classifier, vectorizer, atr_thres_pos, atr_thres_neg,
global_pos_list, global_neg_list, list_of_entity_name, max_pos_threshold, max_neg_threshold):
if type(global_neg_list) != list:
global_neg_list ... |
def load_file_to_extract_hidden_entities(file, vectorizer_filename, classifier_filename, data_json):
# print(flag, "flag")
if len(file) == 0 and len(data_json) == 0:
print("Do provide a data file or json file")
# Needs a check
return "Do provide a data file or json file"
if file and... | The function extracts hidden entities from text reviews, predicts sentiment for both the full review and individual entity-related sentences, and compares sentiment scores with/without entities. It uses a classifier and vectorizer for sentiment analysis, returns structured results including entity names, original revie... | def extracting_hidden_entities_and_reviews_and_sentiment_prediction(file, vectorizer_filename, classifier_filename,
data_json, list_of_entity_name, max_threshold=DEFAULT_THRESHOLD_CONST,min_threshold=DEFAULT_NEG_THRESHOLD_CONST):
# print("Data:\n")... |
def pronoun_resolution(row):
breakdown_list = simple_sentences_breakdown(row['Name'], row['Comment'])
print(breakdown_list)
return [breakdown_list]
def extract_hidden_entities(review, list_of_entity_name):
#print("after spliting:"+review)
if type(list_of_entity_name) != list:
list_of_entity... | The code identifies hidden entities in each row of a DataFrame by resolving pronouns and extracting entities. It compares these extracted entities against a reference list in the 'From Compare' column, flagging missing entities. The results are stored in new columns 'Result' (extracted entities) and 'Missing' (unmatche... | def searchHiddenEntity(df, list_of_entity_name):
result = []
for i, row in df.iterrows():
neu_cor = pronoun_resolution(row)
extracted_sentences, review_without_hidden_entity = extract_hidden_entities(neu_cor[0], list_of_entity_name)
s = extracted_sentences.keys()
row['Result'] =... |
def opt_to_ABCD(text):
if text=='opt1':
return 'A'
elif text=='opt2':
return 'B'
elif text=='opt3':
return 'C'
elif text=='opt4':
return 'D'
def decode_ans(str):
if str == 'A' or str=='opt1' :
return 1
elif str == 'B' or str=='opt2' :
return 2
elif str == 'C' or str==... | This function processes a user's quiz response by checking if the question was already answered, validating the selected answer against the correct one, updating the user's results, and sending the next quiz question if the current one is newly answered. | def send_next(update,context):
query = update.callback_query
obj=json.loads(update.callback_query.data)
sel_opt=obj['text']
ques_id=obj['question-id']
flag=False
# Check if user already answer the question in user result list
for q in user_result:
if q['id']==ques_id:
flag=True
break
#... |
def readFile(fileInput):
f = open(fileInput, 'r')
data = []
for line in f.readlines():
data.append(str(line).replace("\n", "").replace("L", "#"))
f.close()
return data
def findSteadyState(data):
rows = len(data)
cols = len(data[0])
changedState = True
while changedState:
... | The code processes input data to solve two parts of a seating arrangement problem. Part one calculates the number of occupied seats in a steady state using one set of rules, while Part two applies different rules to determine the occupied seats in another steady state. Both parts read input data, compute the steady sta... | def main():
data = readFile("../resources/day11_input.txt")
#data = readFile("../resources/test.txt")
data2 = data.copy()
print("Part one: ")
print(data)
steadyState = findSteadyState(data)
numOccupied = 0
for row in steadyState:
numOccupied += row.count("#")
print(steadySt... |
def toMathMLStrings(html_filename):
with open(html_filename, "r", encoding="utf-8") as f:
xml = f.read()
soup = BeautifulSoup(xml, features='lxml')
mathml_strings = []
for mms in soup.find_all("math"):
if mms["display"] != "block": # skip non-block equations
continue
... | The code reads a file, converts its mathematical expressions into operator trees, generates graph representations of these trees, and returns a list of these graph structures for further analysis or visualization. | def getTreesFromFile(filename):
trees = []
mathml_strings = toMathMLStrings(filename)
for i, e in enumerate(mathml_strings): # plot operator trees of all block equations in given test file
root = toOpTree(e[0])
G = graphTree(root)
trees.append(G)
return trees |
def toMathMLStrings(html_filename):
with open(html_filename, "r", encoding="utf-8") as f:
xml = f.read()
soup = BeautifulSoup(xml, features='lxml')
mathml_strings = []
for mms in soup.find_all("math"):
if mms["display"] != "block": # skip non-block equations
continue
... | The code processes a file to generate and visualize operator trees for each equation. It converts equations to MathML, constructs operator trees, creates graph representations, and plots them with LaTeX-cleaned labels, iterating through all equations in the input file. | def plotTreesFromFile(filename):
mathml_strings = toMathMLStrings(filename)
for i, e in enumerate(mathml_strings): # plot operator trees of all block equations in given test file
root = toOpTree(e[0])
G = graphTree(root)
plotTree(G, cleanUpLatex(e[1])) |
def get_floors_number():
return roll_3d6()
def get_branches_number(floors_number):
max_branches_number = floors_number - 4
branches_number = 0
while (roll_1d10() >= 7 and branches_number <= max_branches_number):
branches_number += 1
return branches_number+1
def roll_branch(branches_number,... | The main task of the code is to construct a hierarchical network (NET) of interconnected "Floor" nodes. It initializes floors, creates a root branch, ensures each branch has at least one floor, randomly distributes remaining floors across branches, and updates node levels via breadth-first traversal. The function retur... | def construct_NET():
## SET UP ##
floors_number = get_floors_number()
branches_number = get_branches_number(floors_number)
all_floor = np.empty(floors_number, dtype=object)
bottom_branch = []
# Filling the NET
for id in range(floors_number):
all_floor[id] = Floor(id+1, 1)
# roo... |
def read_datasets(path):
with open(path) as f:
datasets = yaml.safe_load(f)
return {d['name']: d for d in datasets}
def train_sklearn_model(args, dataloader_train, dataloader_valid, num_labels, metric_factory, log_file):
print(f'Building training data ...', file=sys.stderr)
xs = []
ys = []... | The code's main task is to train and evaluate machine learning or deep learning models for audio classification or detection tasks. It loads datasets, configures model types (e.g., SVM, ResNet, VGGish), prepares data loaders, trains models (sklearn or PyTorch), and evaluates performance using accuracy or mean average p... | def main():
datasets = read_datasets('datasets.yml')
parser = argparse.ArgumentParser()
parser.add_argument('--batch-size', type=int, default=32)
parser.add_argument('--epochs', type=int, default=30)
parser.add_argument('--lrs', type=str)
parser.add_argument('--params', type=str)
parser.add... |
def write_class_packages_uml_notation(self, plantuml_file: io.TextIOWrapper, i: int) -> None:
"""a method to write `.py` class package names in UML notation to a `.puml` file"""
# extract the class package name from each `.py` file contained in the argvs list
class_package_name: str = self.set_... | This method generates a UML class inheritance diagram by scanning specified `.py` files, extracting class structures, methods, attributes, and relationships, then writing them in PlantUML syntax to a `.puml` file. It creates a dedicated directory for outputs, writes UML headers/footers, and processes each file to docum... | def generate_class_inheritance_model(self) -> None:
"""a method to scan each `.py` file in the argvs list and write programatically generated UML to a `.puml` file in the local project directory"""
# create a new folder in the local project directory to store the `.puml` file and class inheritance diag... |
def updateScore(self, action: Action):
"""Updates the score based on the reward of moving from startPoint to endPoint"""
self.score += self.getReward(action)
def putMarkers(self):
fPoint, sPoint = random.sample(self.pPositions, 2)
while fPoint == self.taxiPosition or sPoint == self.taxi... | The main task of the code is to finalize the game by updating the score after a customer drop-off, resetting the customer pickup status, restoring the original grid layout, repositioning game objects, displaying the final score, and resetting the score to its initial value. | def endGame(self):
# self.isGameFinished = True
self.updateScore(Action.DROP_OFF)
self.isCustomerPickedUp = False
self.originalGrid[self.firstTaxiPosition[0]
][self.firstTaxiPosition[1]] = ROAD_SYMBOL
self.putMarkers()
self.locateObjects(self.... |
def getValidMoves(self) -> List[Action]:
"""Returns a list of valid moves for the taxi"""
validMoves = [Action.NORTH, Action.WEST, Action.EAST,
Action.SOUTH, Action.PICK_UP, Action.DROP_OFF]
grid = self.currentGrid
x = self.taxiPosition[0]
y = self.taxiPosi... | This code handles keyboard input to control a game agent's movements and actions. It maps arrow keys to directional moves (NORTH/SOUTH/EAST/WEST), 'p' to pick-up, and 'd' to drop-off. It updates the score, checks move validity, and updates the game state/grid visualization if the game is not finished. | def on_press(self, key):
# print("received key:", key)
if self.isGameFinished:
return
validMoves = self.getValidMoves()
selectedAction = None
if key == Key.up:
selectedAction = Action.NORTH
self.updateScore(selectedAction)
if Acti... |
def build_images(surface, regions):
return {name: load_image_from_surface(region, surface) for name, region in regions}
def parse_regions(atlas_json):
for region in atlas_json["regions"].values():
name = parse_name_from_filepath(region["filepath"])
yield name, region
def _load_json(self):
... | This code initializes a sprite atlas by loading a sprite sheet image, parsing region data from a JSON file, building individual sprite images, and organizing them into a dictionary for efficient access during animation or rendering. | def __init__(self, name="atlas"):
self.name = name
sheet = pygame.image.load(self._image_path).convert_alpha()
self.images = build_images(sheet, parse_regions(self._load_json()))
self.sprites = build_sprite_dict(self.images.keys()) |
def neighbor_cells(cell):
x, y = cell
north_cell = x, y + 1
east_cell = x + 1, y
south_cell = x, y - 1
west_cell = x - 1, y
return north_cell, east_cell, south_cell, west_cell
def filter_to_only_in_maze(cells, x_size, y_size):
return [cell for cell in cells if is_in_maze(cell, x_size, y_size... | The code generates a maze by removing walls between cells using a depth-first search algorithm. It starts at a given cell, explores unvisited neighbors, and records the removed walls to form connected paths. The output is a list of wall removals representing the maze's structure. | def make(x_size=10, y_size=10, start=(0, 1)):
visited_cells = set()
visited_cells.add(start)
stack = [start]
removed_walls = []
while stack:
current_cell = stack.pop()
all_neighbors = neighbor_cells(current_cell)
only_in_maze = filter_to_only_in_maze(all_neighbors, x_size, y_... |
def log_params(self, iteration):
if iteration == 0:
row = ['day','cluster',]
row += list(map(lambda s: 'cluster'+str(s), range(self.k)))
row += list(map(lambda la: la+'_mu', self.labels))
idxs = np.concatenate([[str(i)+str(j) for j in range(self.dim)] for i in ran... | The main task of the code is to perform iterative clustering by repeatedly calling `self.step()` until the maximum number of iterations (`self.max_iter`) is reached or convergence is achieved. It logs parameter values at each iteration, tracks the number of iterations executed, and terminates the process by closing a f... | def clustering(self):
# Parameters already initialized in init
iteration = 0
#self.visualize_cont(gmm=self, iteration=-1, probs=False)
#self.visualize_cont(gmm=self, iteration=iteration)
self.log_params(iteration)
while self.step():
iteration = iteration + 1
... |
def init_params(self):
return self.rand_init()
def maximize(self):
# compute new probabilities for each cluster
sum_per_cluster = np.sum(self.post_probs,axis=0)
self.cl_probs = sum_per_cluster / self.n
# compute new means and variances
for k in range(self.k):
... | The code initializes a clustering model by setting up parameters, logging, and data structures. It configures variables for the number of clusters (k), data dimensions, and bounds. If initial probabilities are not provided, it generates them and initializes cluster means (mu) and covariances (sigma). If provided, it va... | def __init__(self, data, k, threshold=0.1, max_iter=1000, probs=None, labels=None):
# initialize logging
self.file = open(f'logs_{k}/params.csv', 'w')
self.writer = csv.writer(self.file)
# initializing basic variables
self.threshold = threshold
self.max_iter = max_iter
... |
def player_to_location(self, player: str) -> tuple[str, str]:
for deck in self.data["decks"]:
for room in self.data["decks"][deck]["rooms"]:
if player in self.data["decks"][deck]["rooms"][room]["players"]:
return deck, room
raise ValueError(f"Player [{play... | This function determines if a player can use a specified ability in their current location by checking if the ability exists, is enabled, and can be executed with given dice rolls, returning True if all conditions are met, otherwise False. | def use_ability(self, player: str, ability: str, rolls: list[int]) -> bool:
deck, room = self.player_to_location(player)
if ability not in self.data["decks"][deck]["rooms"][room]["abilities"]:
return False
if not self.data["abilities"][ability]["enabled"]:
return False
... |
def initGPIO():
if socket.gethostname() == 'orangepizero':
GPIO.setmode(GPIO.BOARD)
def initPin(pinNo):
if socket.gethostname() == 'orangepizero':
GPIO.setup(pinNo, GPIO.OUT)
def parseData(data):
rawStr = data.split(",")
devNo = rawStr[0].split(":")[1]
action = rawStr[1].split(":")[1... | The code reads device configuration from a file, initializes GPIO pins, sets up a UDP socket for broadcasting, and continuously listens for incoming data. It parses received data and handles Ctrl+C interrupts. The main tasks include configuration loading, hardware initialization, UDP communication setup, and real-time ... | def main():
signal.signal(signal.SIGINT, signal_handler)
configParser = ConfigParser.RawConfigParser()
configFilePath = r'config.txt'
configParser.read(configFilePath)
global DEVICE_NO
DEVICE_NO = configParser.get('DEVICE-INFO', 'deviceNo')
global UDP_PORT
UDP_PORT = configParser.get... |
def configure(self):
upper = (0, 0, 0)
lower = (255, 255, 255)
lowerRobot1 = lowerRobot2 = lowerRobot3 = lowerRobot4 = lowerObstacle = lower
upperRobot1 = upperRobot2 = upperRobot3 = upperRobot4 = upperObstacle = upper
while True:
image = self.vs.read()
bl... | The code's main task is to detect robots and obstacles, calculate paths using potential field planning, and coordinate robot movements by sending routes via sockets. It transitions between initialization, start, and running states, handling robot localization, path execution, and message communication (e.g., start, end... | def run(self):
if self.state == self.Init:
# Get the capture and identify the robots and objects.
# Calculate the routes
# Send the each routes to responsible robots.
# Set current robot to zero
# Set state to running
(self.lowerRobot1, se... |
def display_text(self, message, duration: Union[float, None]=2.0, alpha: float=1.0):
"""Display text on the screen."""
self.textblock.colouring.set_colour(alpha=alpha)
self.textblock.set_text(str(message))
self.text.regen()
self.text.draw()
self.text_thread.cancel()
... | The code checks for IR remote commands, logs received commands, and triggers actions like toggling playback pause, navigating slides, or displaying text based on specific keys (e.g., KEY_PLAY, KEY_LEFT). It updates the display with symbols or image names and manages slideshow navigation via prev_slide() and next_slide(... | def check_irw(self):
"""Check for IR remote commands and handle them."""
if not self.irw:
return
command = self.irw.get_key()
if not command:
return
logging.info('IR command received: {}'.format(command))
if command == "KEY_PLAY"... |
def update_alpha(self):
if self.foreground_alpha >= 1.0:
return
self.foreground_alpha = min(self.foreground_alpha + self._delta_alpha, 1.0)
self.slide.unif[44] = self.foreground_alpha
def check_irw(self):
"""Check for IR remote commands and handle them."""
if not sel... | The code defines a playback loop that continuously updates visual elements (slide, text), checks for time-based slide transitions, manages alpha values, and interacts with a motion sensor. It runs while the display loop is active, pauses when needed, and triggers the next slide when the current time exceeds the schedul... | def play(self):
"""Playback loop."""
while self.display.loop_running():
self.update_alpha()
self.slide.draw()
self.text.draw()
self.check_irw()
self.current_time = time.time()
if self.current_time > self.next_time and not self._pau... |
def get_src_line(self, i):
if self.load_in_memory:
return self.src_lines[i]
else:
return self.src_cache[i].decode('latin1')
def get_tgt_line(self, i):
if self.load_in_memory:
return self.tgt_lines[i]
else:
return self.tgt_cache[i].decode('l... | The function calculates similarity between two texts (source and target) using specified metrics like cosine, WMD, Jaccard, etc. It retrieves text data via IDs if not provided, applies preprocessing (cleaning), and returns similarity scores based on the chosen metric, leveraging models like Word2Vec for WMD variants or... | def pair_similarity(self, src_id, tgt_id, src=None, tgt=None):
"""
Compute a similarity between two texts: source and target.
:param src: the src text
:param tgt: the tgt text
:param src_id: the id of the src text in the index
:param tgt_id: the id of the tgt text in the... |
def read_submission_file(submission_file):
read_protein = True
read_ligand = False
protein_pdb = ''
ligands_poses = {}
with open(submission_file) as f:
lines = f.readlines()
for line in lines:
if read_ligand:
try:
if not (line.startsw... | The function processes ligand data from a submission file, generating a DataFrame with ligand information. It identifies nearby protein residues for each ligand atom group, adds metadata like entry name and atom counts, and returns the structured DataFrame for further analysis. | def generate_entry_df(entry_name):
"""Process ligand information generated by read_submission_file
:param entry_name: dictionary produced by read_submission_file
:return: dataframe with ligand information
"""
entry_dict = read_submission_file(entry_name)
prot_atmgrp, lig_df = process_entry(entry... |
def get_reference_interactions(ref_pdb, ref_sdf, dist_cutoff=3):
"""Get residues from ref_pdb that are within dist_cutoff for each ligand in ref_sdf.
The ligand names from ref_sdf will be used to label the interactions
:param ref_pdb: reference pdb file
:param ref_sdf: reference sdf
:param dist_cuto... | The code processes multiple files to evaluate and score protein-ligand interactions against a reference dataset. It loads interaction data, filters valid entries, maps ligand names, compares interactions, ranks entries by score, and exports results to a CSV file. | def main():
confProDy(verbosity='none')
ref_df = get_reference_interactions("T1124_ref_protein.pdb", "T1124_ref_ligands.sdf")
df_list = []
for filename in tqdm(glob("/Users/pwalters/DATA/CASP/T1124/*")):
basename = PurePath(filename).parts[-1]
df_list.append([basename, generate_entry_df(... |
def get_available_letters(letters_guessed):
'''
letters_guessed: list (of letters), which letters have been guessed so far
returns: string (of letters), comprised of letters that represents which letters have not
yet been guessed.
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
not_yet_gue... | The code implements an interactive Hangman game where the user guesses letters in a secret word. It provides feedback on each guess, displays remaining attempts, and shows partially guessed letters. The game allows hints (using '*') to reveal matching words from a list. It enforces rules like limiting guesses, deductin... | def hangman_with_hints(secret_word):
'''
secret_word: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secret_word contains and how many guesses s/he starts with.
* The user should s... |
def get_cos_ang_bet_prop_vect_B_vect(r,theta,phi,theta_dash,phi_dash):
if len(np.shape(r))>0:
print('get_cos_ang_bet_prop_vect_B_vect')
k_vect_polar =np.array([1,r*theta_dash,r*np.sin(theta)*phi_dash])
B_vect_polar =B_func(r,theta,1.0)
k,B =get_vector_modulus(k_vect_polar),get_vector_modulus(B_vect_polar)
retur... | This function calculates the difference between a given value Y and the derivatives of a function F with respect to angles theta_dash and phi_dash, using plasma physics parameters like plasma frequency, cyclotron frequency, and refractive index. It computes these derivatives by combining geometric, density, and electro... | def minimize_func(theta_phi_dash,r,theta,phi,Y,Bp,nu,mode,n_p0,interp_rho,rho_fact):
theta_dash,phi_dash =theta_phi_dash[0],theta_phi_dash[1]
cos_psi =get_cos_ang_bet_prop_vect_B_vect(r,theta,phi,theta_dash,phi_dash)
my_rho =density_func(r,theta,phi,n_p0,interp_rho,rho_fact)
nu_p =get_plasma_freq(my_rho)
nu... |
def get_B_from_nu(nu,harm_no): #nu in MHz, B in gauss
return nu/(2.8*harm_no)
def B_func(r,theta,Bp):
Br,Bt=(np.cos(theta))/r**3,(0.5*np.sin(theta))/r**3
return np.array([Br*Bp, Bt*Bp,0])
def convert_spherical_to_cartesian_coord(V,r,theta,phi): #here V is an array with components are the r,theta,phi components of ve... | The function calculates initial conditions for a physical model involving magnetic fields and wave propagation. It solves for angles theta0 and phi0 using numerical methods, computes related vectors (B, k), and determines valid initial parameters (n, s) for two symmetric scenarios. These parameters are essential for si... | def get_initial_condition(nu,harm_no,Bp,L,R_A,phi01,n_p0,mode,rho_fact,min_x5_arr,min_y5_arr,min_z5_arr,max_x5_arr,max_y5_arr,max_z5_arr):
B =get_B_from_nu(nu,harm_no) #B in gauss, nu in MHz
h =(Bp/B)**(1/3.0)
ini_guess01 =np.arcsin(np.sqrt(h/L))
ans =optimize.root(func2,x0=ini_guess01,args=(L,Bp,B))
if ans['s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.