dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def _refersh_params(self):
self._queue_lengths = np.zeros(16)
self._waiting_times = {}
self._number_of_cars_on_map = 0
def _run(self, net):
starvation_counter = dict(
(key, dict((small_key, 0) for small_key in range(4))) for key in self._junctions)
traci.start(self._s... | The main task of the code is to evaluate a neural network's performance by running it with refreshed parameters, then calculating and returning key metrics: RMS waiting time loss, harmonic mean loss, average queue length, and average waiting time. These metrics assess the network's efficiency and accuracy in handling t... | def run_test_net(self, net):
self._refersh_params()
self._run(net)
return {
"RMS_WAITING_TIME_LOSS": self._rms_waiting_time(),
"HARMONIC_MEAN_LOSS": self._harmonic_mean_fitness(),
"AVERAGE QUEUE LENGTH": self._average_queue_length(),
"AVERAGE WAITI... |
def get_parent(self, dir):
"""
Iterates inversely from root directory (GoogleDrive) to get the parent title and id.
Start from root folder in source path (backup folder).
"""
# The last parent is always the root in GoogleDrive from Settings.py
parent = self.settings.root
... | This function uploads copied file paths to a destination directory by determining their relative structure, identifying the correct parent directory, creating file entries, and initiating the upload process, mimicking Google Drive's organizational logic. | def upload_paths(self):
"""Uploads copied paths."""
for path in self.copied_paths:
# Path relative to the destiny directory
# Similar structure as in GoogleDrive
path = Path(path)
dir = path.relative_to(self.settings.dst)
# parent title and i... |
def compare_dir(self, src, dst):
"""Compare directories."""
cmp = filecmp.dircmp(src, dst)
return cmp
def copy_left(self, cmp):
"""Copy files or directories only found in source"""
if not cmp.left_only:
return
for path in cmp.left_only:
src = Pat... | The code's main task is to compare source and destination directories, identify new or modified files, and copy them. It uses `compare_dir` to detect differences, then copies missing files (`copy_left`), updated files (`copy_modified`), and processes subdirectories (`copy_subdir`) to synchronize the directories. | def copy(self):
"""Compare the directories and copy new or modified files."""
self.cmp = self.compare_dir(self.src, self.dst)
self.copy_left(self.cmp)
self.copy_modified(self.cmp)
self.copy_subdir(self.cmp) |
def read(x):
with open(x) as f:
line = f.readlines()
for y in range(len(line)):
line[y] = line[y].strip('\n')
return line
def create_string(x):
arr = ['','']
flag = 0
for y in x:
if y.isnumeric():
arr[flag-1] = insert(arr[flag-1],int(y)+1)
else:
... | The code processes input text by reading and transforming it into two strings. It constructs a nested list structure based on the length of these strings, then computes alignment and dynamic programming results using `getali` and `dac`. Finally, it returns the last alignment result and sliced versions of the dynamic pr... | def main():
tex = sys.argv[1]
t1 = read(tex)
t2 = create_string(t1)
list1 = []
list2 = []
rip1 = len(t2[0])
rip2 = 2
for x in range(rip1):
for y in range(rip2):
list1.append(x)
list2.append(list1)
list1 = []
#t2 = ["GGGG","AAAAAAAA"]
#t2[0... |
def parse_arguments() -> argparse.Namespace:
parser = ArgumentParser()
parser.add_argument("scheme_type", choices=SCHEME_TYPES, default=None, nargs="?")
parser.add_argument("-n", "--number", type=int, default=5, help="Number of colors in a scheme. Defaults to 5.")
parser.add_argument("-p", "--primary", ... | The main task of the code is to parse command-line arguments, generate schemes based on those arguments, and print the resulting schemes. The `main()` function orchestrates this workflow by sequentially calling `parse_arguments()` to handle input parameters, `generate_schemes()` to create the schemes, and `print_scheme... | def main() -> None:
args = parse_arguments()
schemes = generate_schemes(args)
print_schemes(schemes) |
def ssd(self, l_idx, r_idx):
array_len = r_idx - l_idx + 1
median_idx = l_idx + array_len//2
d = 0
for i in range(array_len):
idx = i + l_idx
add = abs(self.data[idx] - self.data[median_idx])
d += add
return d
def fill_remaining_rows(self):
for k in range(1,self.K):
# print("ONEDKMeans | fill ro... | The code performs K-means clustering in one dimension by initializing a distance matrix, filling it with squared distances, and iteratively computing clusters for varying k-values. It returns distance metrics, final cluster assignments, and centroids for the specified number of clusters (K). | def run(self):
# print("ONEDKMeans | start")
for i in range(self.D.shape[1]):
self.D[0][i] = self.ssd(0, i) # fill first row.
# print("ONEDKMeans | fill other rows")
self.fill_remaining_rows()
distances_by_k = []
cluster_by_k = []
centroids_by_k = []
for k in range(1, self.K + 1):
cluster = se... |
def print_indexed_items(self, items, attr):
[print(f'{idx + 1}. {getattr(item, attr)}')
for idx, item in enumerate(items)]
def list_book_options(self, author):
choice = ''
while (not CLI.valid_choice(['add', 'menu', 'exit'], choice) and not choice.isdigit()):
choice = input... | This function presents options to view books by an author, return to the main menu, or exit. It validates user input, allowing selection by author index (digit), printing all authors ('pa'), or navigating to the book options. It loops until a valid choice is made, then returns the selected option for further processing... | def list_author_options(self):
choice = ''
while (not CLI.valid_choice(['pa', 'menu', 'exit'], choice) and not choice.isdigit()):
choice = input(
"To see all books by an author enter the number of the author\nTo return to main menu type 'menu'\nTo exit type 'exit'\n")
... |
def print_indexed_items(self, items, attr):
[print(f'{idx + 1}. {getattr(item, attr)}')
for idx, item in enumerate(items)]
def list_author_options(self):
choice = ''
while (not CLI.valid_choice(['pa', 'menu', 'exit'], choice) and not choice.isdigit()):
choice = input(
... | This code provides a CLI menu for managing authors and books, allowing users to view all authors ('pa'), view all books ('pb'), add an author ('aa'), or exit. It validates user input, displays indexed lists, and loops until 'exit' is chosen, offering persistent menu options. | def start(self):
# self.print_indexed_items(self.authors, 'name')
choice = ''
while (not CLI.valid_choice(['pa', 'pb', 'aa', 'exit'], choice)):
choice = input(
"To see all authors enter 'pa'\nTo see all books enter 'pb'\nTo add an author type 'aa'\nTo exit type 'exit... |
def flippa_left(image):
return np.rot90(image, 1, (0,1))
def calc_seam(image, seams):
height, width, _ = image.shape
image_map, skip = cum_map(image)
mask = np.zeros((height, width), dtype=np.bool)
for i in range(seams):
smallest = np.argmin(image_map[-1])
for j in reversed(ran... | The main task of the code is to visualize and color the seams that would be removed when reshaping an image to a specified new shape. It calculates the number of seams based on the difference between the original and target dimensions, generates a mask for these seams, and applies the specified color to the masked regi... | def visualise_seams(image, new_shape, show_horizontal, colour):
"""
Visualises the seams that would be removed when reshaping an image to new image (see example in notebook)
:param image: The original image
:param new_shape: a (height, width) tuple which is the new shape
:param carving_scheme: the c... |
def flippa_back(image):
return np.rot90(image, -1, (0,1))
def delete_vert_seams(image, amount_of_seams, scale_factor):
scaled_image = np.repeat(image, scale_factor, axis=1).reshape(image.shape[0], image.shape[1] * scale_factor, 3)
mask = np.repeat(calc_seam(image, amount_of_seams % image.shape[1]), scale_fa... | The function deletes horizontal seams from an image by first flipping it horizontally, then removing vertical seams using the specified amount and scale factor, and finally flipping it back to restore the original orientation. | def delete_horz_seams(image, amount_of_seams, scale_factor):
return flippa_back(delete_vert_seams(flippa_left(image), amount_of_seams, scale_factor)) |
def inception_model_files_check():
dest_directory = FLAGS.model_dir
if not os.path.exists(dest_directory):
os.makedirs(dest_directory)
filename = INCEPTION_URL.split('/')[-1]
filepath = os.path.join(dest_directory, filename)
if not os.path.exists(filepath):
def _progress(count, block... | The code trains a neural network using transfer learning with the Inception model, fine-tuning a new softmax layer for image classification. It caches bottleneck features from training/validation/test images, trains the model over specified steps, evaluates accuracy, and exports the trained graph and labels. The proces... | def main(_):
if tf.gfile.Exists(FLAGS.summaries_dir):
tf.gfile.DeleteRecursively(FLAGS.summaries_dir)
tf.gfile.MakeDirs(FLAGS.summaries_dir)
inception_model_files_check()
graph, bottleneck_tensor, jpeg_data_tensor, resized_image_tensor = (
graph_creation())
# create list of all ... |
def get_split(df, split):
"""
get train or test split
"""
return df[df['split'] == split]
def process_split(df, los_df, feat_colnames, label_colname, cutoff, missing_method='zero_fill', **kwargs):
"""
get features, labels, and ids for split
"""
df_ids = df['hadm_id']
df = df.loc[:, f... | The code trains a classifier (XGBoost, Gradient Boosting, or KNN) on combined training/validation data, evaluates it on test data, computes performance metrics (AUC, AUPRC, accuracy, F1, precision, recall), and returns the model, predictions, labels, and metrics. It normalizes features if specified and determines an op... | def main(df, normalize, **kwargs):
train_set = get_split(df, 'train')
val_set = get_split(df, 'val')
train_set = pd.concat([train_set, val_set])
test_set = get_split(df, 'test')
train_set, train_labels, train_ids = process_split(train_set, **kwargs)
test_set, test_labels, test_ids = process_spli... |
def get_residency_per_target_qps(stats, stats_root_dir):
# determine used C-states
state_names = ['C0']
check_state_names = ['C1', 'C1E', 'C6']
for state_name in check_state_names:
instance_name = stats_root_dir
if state_name in stats[instance_name][0]['server']['CPU0']:
... | The main task of the code is to generate and save three types of statistical data (residency, power, usage) per target QPS into separate CSV files. It retrieves data using three functions and writes them to CSV files named 'residency_per_target_qps.csv', 'power_per_target_qps.csv', and 'usage_per_target_qps.csv' in the... | def write_csv_all(stats, stats_root_dir):
raw = get_residency_per_target_qps(stats, stats_root_dir)
write_csv(stats_root_dir + 'residency_per_target_qps' + '.csv', raw)
raw = get_power_per_target_qps(stats, stats_root_dir)
write_csv(stats_root_dir + 'power_per_target_qps' + '.csv', raw)
... |
def system_conf_fullname(system_conf):
l = [
'turbo={}'.format(system_conf['turbo']),
'kernelconfig={}'.format(system_conf['kernelconfig']),
'hyperthreading={}'.format(system_conf['ht'])
]
if 'freq' in system_conf:
l.append('freq={}'.format(system_conf['freq']))
return '-... | The code generates a PDF containing multiple plots for each system configuration. It creates a text page for each configuration, plots residency, total QPS, latency, and power metrics per target QPS, and conditionally includes residency plots based on the kernel configuration. Interactive display is enabled if specifie... | def plot(stats, system_confs, qps_list, interactive):
pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
for system_conf in system_confs:
firstPage = plt.figure()
firstPage.clf()
txt = system_conf_fullname(system_conf)
firstPage.text(0.5,0.5, txt, transform=firstPage.tr... |
def plot_residency_per_target_qps(stats, system_conf, qps_list):
raw = get_residency_per_target_qps(stats, system_conf, qps_list)
width = 0.35
fig, ax = plt.subplots()
header_row = raw[0]
bottom = [0] * len(header_row[1:])
labels = [str(int(int(c)/1000))+'K' for c in header_row[1:]]
... | The function generates multiple plots (residency, total QPS, latency, power) for system configurations, saves them into a PDF, and optionally displays them interactively. It filters out 'disable_cstates' configs, creates figures for each metric, and ensures proper cleanup of plots and the PDF file. | def plot_stack(stats, system_confs, qps_list, interactive=True):
pdf = matplotlib.backends.backend_pdf.PdfPages("all.pdf")
for system_conf in system_confs:
if system_conf['kernelconfig'] != 'disable_cstates':
fig1 = plot_residency_per_target_qps(stats, system_conf, qps_list)
pdf.... |
def generateAssumption(self):
clues = list()
for i in range(self.size):
for j in range(self.size):
if self.board[i][j] != 0:
clues.append(index(i+1, j+1, self.board[i][j], self.boxSize))
return clues
def productEncoding(self):
long_formula ... | This code initializes a puzzle solver by setting up a grid from raw data, calculating grid dimensions, generating initial clues, and preparing product and binomial encodings for solving. It stores the puzzle board, grid size, subgrid size, assumptions, encodings, and an empty solution list for later computation. | def __init__(self, rawData: list[list[int]]):
self.board = rawData
self.size = rawData.__len__()
self.boxSize = int(math.sqrt(self.size))
self.clues = self.generateAssumption()
self.product_encoding = self.productEncoding()
self.binomial_encoding = self.binomialEncoding()... |
def get_height(self, current_node):
if current_node is None:
return 0
return current_node.height
def more_height_child(self, current_node):
left_subtree = self.get_height(current_node.left_child)
right_subtree = self.get_height(current_node.right_child)
if left_subtr... | This function checks if a node in an AVL tree is unbalanced after deletion by comparing the heights of its left and right subtrees. If the height difference exceeds 1, it identifies the heavier child nodes (y and x) and calls a balancing method. It then recursively checks the parent node to ensure the tree remains bala... | def _check_deletion(self, current_node):
if current_node is None:
return
left_height = self.get_height(current_node.left_child)
right_height = self.get_height(current_node.right_child)
if abs(left_height - right_height) > 1:
y = self.more_height_child(current_no... |
def listen(self):
self.sock = socket(AF_INET, SOCK_STREAM) # Command socket
self.bind()
self.sock.listen(5)
print(f"Listening for connection at {self.sock}")
logging.info(f"Listening for connection at {self.sock}")
self.accept()
self.welcome()
def recv_data(self):... | This code defines a server's 'serve' method that listens for incoming commands, processes them by dynamically invoking corresponding methods, and handles the 'QUIT' command to close and restart the listener. It uses eval to execute method calls based on received commands, with error handling for unimplemented features. | def serve(self):
'''Serve method'''
self.listen()
while True:
self.recv = self.recv_data()
cmd = self.recv[0]
if cmd == 'QUIT':
self.QUIT()
self.close()
self.listen()
else:
evaluation_... |
def validate_request(self: Self) -> bool:
if not self.is_json:
current_app.logger.error('invalid mimetype')
return False
return True
def to_json(self: Self, request_data: bytes) -> t.Any: # noqa: ANN401
try:
return json.loads(request_data)
except Valu... | This method handles incoming requests by validating the request's MIME type, parsing JSON data, and dispatching it either as a batch request or individual request with appropriate error handling. | def dispatch_request(
self: Self,
) -> t.Tuple[t.Any, int, t.Union[Headers, t.Dict[str, str], t.Tuple[str], t.List[t.Tuple[str]]]]:
if not self.validate_request():
raise ParseError(
data={
'message': f'Invalid mime type for JSON: {request.mimetype}, '
... |
def MultiplyWithoutReducing(self,f,v):
"""
Multiplies two field elements and does not take the result
modulo self.generator. You probably should not use this
unless you know what you are doing; look at Multiply instead.
NOTE: If you are using fields larger than GF(2^15), you sho... | This function multiplies two field elements modulo a generator polynomial. It first computes the product without reduction using MultiplyWithoutReducing, then performs polynomial division by the generator using FullDivision. The result is the remainder of this division, representing the product in the quotient ring def... | def DoMultiply(self,f,v):
"""
Multiplies two field elements (modulo the generator
self.generator) and returns the result.
See MultiplyWithoutReducing if you don't want multiplication
modulo self.generator.
"""
m = self.MultiplyWithoutReducing(f,v)
return s... |
def GetRandomElement(self,nonZero=0,maxDegree=None):
"""
Return an element from the field chosen uniformly at random
or, if the optional argument nonZero is true, chosen uniformly
at random from the non-zero elements, or, if the optional argument
maxDegree is provided, ensure tha... | The main task of the code is to verify the correctness of a polynomial division function (`FullDivision`) by generating random non-zero polynomials `a(x)` and `b(x)`, performing division to obtain quotient `c` and remainder `d`, then checking if `b*c + d` reconstructs the original polynomial `a`. This ensures the divis... | def TestFullDivision(self):
"""
Test the FullDivision function by generating random polynomials
a(x) and b(x) and checking whether (c,d) == FullDivision(a,b)
satsifies b*c + d == a
"""
f = 0
a = self.GetRandomElement(nonZero=1)
b = self.GetRandomElement(n... |
def FullDivision(self,f,v,fDegree,vDegree):
"""
Takes four arguments, f, v, fDegree, and vDegree where
fDegree and vDegree are the degrees of the field elements
f and v represented as a polynomials.
This method returns the field elements a and b such that
f(x) = a(x) ... | The code implements the **Extended Euclidean Algorithm** for polynomials, computing the greatest common divisor (GCD) of two polynomials `a` and `b`, along with Bézout coefficients `x` and `y` such that `d = a*x + b*y`, where `d` is the GCD. It recursively divides polynomials, uses polynomial division (`FullDivision`),... | def ExtendedEuclid(self,d,a,b,aDegree,bDegree):
"""
Takes arguments (d,a,b,aDegree,bDegree) where d = gcd(a,b)
and returns the result of the extended Euclid algorithm
on (d,a,b).
"""
if (b == 0):
return (a,self.unity,0)
else:
(floorADivB, a... |
def ExtendedEuclid(self,d,a,b,aDegree,bDegree):
"""
Takes arguments (d,a,b,aDegree,bDegree) where d = gcd(a,b)
and returns the result of the extended Euclid algorithm
on (d,a,b).
"""
if (b == 0):
return (a,self.unity,0)
else:
(floorADivB, a... | The code computes the multiplicative inverse of an element `f` in a finite field using the Extended Euclidean Algorithm. It calls `ExtendedEuclid` with parameters involving the field's unity, `f`, a generator, the degree of `f`, and the field size `n`. The result's second component (index `[1]`) yields the inverse, ens... | def DoInverseForBigField(self,f):
"""
Computes the multiplicative inverse of its argument and
returns the result.
"""
return self.ExtendedEuclid(self.unity,long(f),self.generator,
self.FindDegree(long(f)),self.n)[1] |
def ConvertListToElement(self,l):
"""
This method takes as input a binary list (e.g. [1, 0, 1, 1])
and converts it to a decimal representation of a field element.
For example, [1, 0, 1, 1] is mapped to 8 | 2 | 1 = 11.
Note if the input list is of degree >= to the degree of the
... | This code initializes a finite field GF(2^p) by setting up generator polynomials and configuring arithmetic operations (multiply, divide, inverse) based on parameters. It uses lookup tables (LUT) for efficiency when enabled or field size is small, otherwise employs direct computation or long integers for larger fields.... | def __init__(self,n,gen=0,useLUT=-1):
"""
This method constructs the field GF(2^p). It takes one
required argument, n = p, and two optional arguments, gen,
representing the coefficients of the generator polynomial
(of degree n) to use and useLUT describing whether to use
... |
def isFinishedGameOnCurrentState(self, state:Matrica,player:Player):
return state.isEndOfGame(player)
def procenaStanja(self, state:Matrica, player: Player, cilj1: List[int], cilj2: List[int])-> int:
dist = 0
list1 = state.A_star(player,1,cilj1)
list2 = state.A_star(player,1,cilj2)
... | The code implements the minimax algorithm with alpha-beta pruning to determine the optimal move for a player in a game state. It evaluates terminal states, recursively explores possible moves, and selects the best state for the maximizing player ('O') or the worst for the minimizing player ('X'), using depth limits and... | def minimax(self, state: Matrica, depth: int,alfa:int, beta:int, player: Player):
#procena stanja, vracanje procene za krajnje stanje
if self.isFinishedGameOnCurrentState(state,player):
return [state,0]
if depth == 0:
return [state, self.procenaStanja(state, state.player... |
def printBoard(self):
'''Printing board on the console'''
print("Trenutno stanje matrice:", end="\n")
self.matrica.printBoard()
def playTurn(self, player: Player) -> Player:
'''Player (Human or Computer) plays the turns'''
print(f"Trenutno igra {player.sign} \n")
... | The main task of the code is to alternate turns between the player and computer in a game (likely tic-tac-toe), update game states after each move, check for a winning condition, and declare the winner once the game ends. It uses `playTurn` for the player's move and `playComputer` for the AI's move, switching turns unt... | def playGame(self): #promeniti ovu funkciju tako da neizmenicno igraju igrac i kompjuter
'''Zapocni igru, igraju igraci naizmenicno'''
winner = None #Player()
self.printBoard()
while True:
if self.onTurn == 'X':
currentPlayer = self.playTurn(self.matrica.play... |
def populate_queryset_values(self, objects, *fieldnames):
"""
Sets values on objects in the existing queryset from a given set of objects and optional set of fieldnames
:param collections.Iterable objects: a list of objects with data to use as a source for updates to apply within the queryset
... | This method performs a bulk update on model instances, updating specified fields for all objects in the queryset. It supports concurrent updates using multiple workers, sends pre/post update signals, and returns either the count of updated records or a filtered queryset. It handles batching, ensures database connection... | def update_fields(self, *fieldnames, objects=None, batch_size=None, send_signal=True,
concurrent=False, max_concurrent_workers=None, return_queryset=False):
"""
Performs a hetergeneous update
:param fieldnames:
:param objects:
:param batch_size:
:pa... |
def log_error(response_code):
if response_code != 200:
logger.error('Something went wrong!')
def save_genres(genre):
genre, created = Genres.objects.get_or_create(
name=genre['name'], defaults={'source_id': genre['id']}
)
if created:
logger.info(f'New ... | The code downloads movie genres and popular films from an API, saving data to a database. It fetches genre lists first, then retrieves movie details across specified pages (start_page to end_page). Errors are logged, and results are stored using save_films_and_actors. If end_page=0, only the start_page is processed. Th... | def download_by_page(self, start_page, end_page=0):
sys.stdout.write('Start\n')
movie_genres_data = requests.get(f'{settings.GENRES_URL}movie/list?api_key={settings.API_KEY}')
self.log_error(movie_genres_data.status_code)
for genre in movie_genres_data.json()['genres']:
self.... |
def CheckWhichGPUCardsActive(node):
activecards=[]
cmdstr='nvidia-smi'
job='ssh %s "%s"'%(node,cmdstr)
p = subprocess.Popen(job, stdout=subprocess.PIPE,shell=True)
nodedead,output=CheckForDeadNode(p,node)
lines=output.split('\n')
count=-1
for line in lines:
linesplit=line.split()... | The function identifies already active computational nodes in a cluster, either by checking GPU card usage (if `gpunodes=True`) or by detecting running programs (from `programexceptionlist`). It returns a list of active nodes, appending GPU-specific identifiers when applicable. If exceptions are detected, nodes are mar... | def AlreadyActiveNodes(nodelist,programexceptionlist=None,gpunodes=False):
activenodelist=[]
if verbosemode==True:
disablebool=False
else:
disablebool=True
for nodeidx in tqdm(range(len(nodelist)),desc='Checking already active nodes',disable=disablebool):
node=nodelist[nodeidx]
... |
def WriteToLogFile(string,loghandle=None):
now = time.strftime("%c",time.localtime())
if loghandle!=None:
loghandle.write(now+' '+string+'\n')
loghandle.flush()
os.fsync(loghandle.fileno())
masterloghandle.write(now+' '+string+'\n')
masterloghandle.flush()
os.fsync(masterlogh... | The main task of the code is to identify and check active CPU and GPU resources by filtering GPU-only nodes, mapping GPU cards to nodes, and returning lists of available CPU nodes, GPU cards, and their associated OS/CUDA versions. It logs progress, excludes GPU-only nodes from CPU lists if specified, checks node activi... | def GrabCPUGPUNodes():
WriteToLogFile('*************************************')
WriteToLogFile("Checking available CPU nodes and GPU cards")
nodes,cpunodesonlylist,gpunodesonlylist=ReadNodeList(nodelistfilepath)
cpunodes,gpucards,nodetoosversion,gpunodetocudaversion=PingNodesAndDetermineNodeInfo(nodes)
... |
def MakeScratch(node,jobpath,bashrcpath,loghandle,scratchdir):
cmdstr='[ -d "%s" ] && echo "Directory Exists"'%(scratchdir)
output=CheckOutputFromExternalNode(node,cmdstr)
if CheckOutputFromExternalNode(node,cmdstr)==False:
mkstr='mkdir '+scratchdir
process,nodedead=CallSubprocess(node,jobpa... | This function submits a job by checking if a scratch directory exists for the job, creating it if necessary, initiating a subprocess for the job, tracking the process in a dictionary, and removing the job from the queue. It returns the updated process tracking and job info. | def SubmitJob(node,jobpath,bashrcpath,job,loghandle,jobtoprocess,jobtoscratchdir,jobinfo):
if job in jobtoscratchdir.keys():
scratchdir=jobtoscratchdir[job]
if scratchdir!=None:
MakeScratch(node,jobpath,bashrcpath,loghandle,scratchdir)
process,nodedead=CallSubprocess(node,jobpath... |
def CheckBashrcPathsAllNodes(nodes,nodetoosversion,gpunodetocudaversion,ostocudaversiontobashrcpaths):
newnodes=[]
for node in nodes:
bashrcpath,accept=DetermineBashrcPath(nodetoosversion,gpunodetocudaversion,ostocudaversiontobashrcpaths,node)
if accept==True:
newnodes.append(node)
... | This function distributes computational jobs to available nodes by evaluating node resources (RAM, scratch space, CPU/GPU capabilities) against job requirements. It filters compatible nodes, assigns jobs based on resource matching, and maps jobs to nodes while logging assignments. It handles both CPU and GPU jobs, chec... | def DistributeJobsToNodes(nodes,jobs,jobtoscratchspace,nodetoosversion,gpunodetocudaversion,ostocudaversiontobashrcpaths,jobtoram,jobtonumproc,activenodes,cpujobs=False):
nodetojoblist={}
if len(nodes)!=0:
newnodes=CheckBashrcPathsAllNodes(nodes,nodetoosversion,gpunodetocudaversion,ostocudaversiontobash... |
def SubmitJobsLoop(nodetojoblist,jobtologhandle,jobinfo,jobtoprocess,finishedjoblist,nodetoosversion,gpunodetocudaversion,ostocudaversiontobashrcpaths):
if verbosemode==True:
disablebool=False
else:
disablebool=True
for nodeidx in tqdm(range(len(list(nodetojoblist.keys()))),desc='Cycling th... | The main task of the code is to submit, monitor, and manage jobs on CPU/GPU nodes by looping until all jobs complete. It distributes jobs to nodes, checks termination status, updates logs, reads job info, partitions tasks, and reallocates resources dynamically, ensuring continuous processing with sleep intervals and lo... | def SubmitJobs(cpunodetojoblist,gpunodetojoblist,inputbashrcpath,sleeptime,jobtologhandle,jobinfo,nodetoosversion,gpunodetocudaversion,ostocudaversiontobashrcpaths,currenttime,mastererrorloghandle,masterfinishedloghandle):
jobnumber=len(jobtologhandle.keys())
jobtoprocess={}
finishedjoblist=[]
while len... |
def get_closest_waypoint(self, pose):
return self.get_closest_index(pose, self.waypoints.waypoints)
def get_closest_light(self, pose):
return self.get_closest_index(pose, self.lights)
def get_dist(self, point1, point2):
return math.sqrt((point1.x - point2.x) ** 2 + (point1.y - point2.y) ** 2 + (... | Your return
The function identifies the nearest visible traffic light ahead of the vehicle, calculates its location relative to the car, and determines its color state. It returns the index of the waypoint closest to the traffic light's stop line and the light's color (as per `TrafficLight` enum). If no valid light i... | def process_traffic_lights(self):
"""Finds closest visible traffic light, if one exists, and determines its
location and color
Returns:
int: index of waypoint closes to the upcoming stop line for a traffic light (-1 if none exists)
int: ID of traffic light color (spe... |
def request_to_league_client(url: str, method: str = 'GET'):
request_method = requests.post if method == 'POST' else requests.get
lockfile_dict = lockfile.get_lockfile_content()
encrypted_auth = lockfile_dict['encrypted']
url = url.format(port=lockfile_dict['port'])
try:
resp = request_metho... | The function fetches match history and ranked stats for a team's summoners by querying the League client, extracting summoner data, retrieving account IDs, and compiling match history and rankings from APIs, returning structured data or None on error. | def fetch_my_teams_match_history() -> List[Dict]:
resp = request_to_league_client(MY_TEAM_SUMMONERS)
content = resp.json()
print(content)
try:
summoners = list(map(
lambda obj: {
'summoner_id': obj['summonerId'],
'championId': obj['championId'],
... |
def state_to_agent(self):
state_as_list = []
for i in range(DIMENSIONS[0]):
state_as_list.append([]*DIMENSIONS[1])
for j in range(DIMENSIONS[1]):
state_as_list[i].append(self.state[(i + 1, j + 1)][0])
return state_as_list
def get_legal_action(self, number_... | The code simulates a turn-based game episode where players take turns making legal moves in their control zones. It prints the game state, applies actions, updates scores, and alternates player order based on the 'swapped' flag. The loop continues until states 'S1', 'S2', or 'S3' no longer exist in the game state. | def play_episode(self, swapped=False):
while 'S1' in self.state.values() or 'S2' in self.state.values() or 'S3' in self.state.values():
obs_state = self.state_to_agent()
for line in obs_state:
print(line)
print()
if not swapped:
... |
def eval_state(state, zoc):
""" returns my point minus rival's points """
myPoints = 0
rivalPoints = 0
for row in range(len(state)):
for col in range(len(state[row])):
if state[row][col] == 'H' or state[row][col] == 'I':
if (row, col) in zoc:
myPoi... | The code implements a Minimax algorithm with alpha-beta pruning for game state evaluation. It recursively explores possible moves for a maximizing or minimizing player, considering two turn orders ('first'/'second'). The function evaluates game states, selects optimal child states, and adjusts the state (via 'change_st... | def miniMax(state, zoc, notZoc, order, depth, alpha, beta, maximizingPlayer, action_org):
posInfinity = float('inf')
negInfinity = float('-inf')
best_child = state
best_action = action_org
if depth == 0:
return eval_state(state, zoc), state, action_org
if maximizingPlayer and order == '... |
def parse_args():
parser = argparse.ArgumentParser(description="Analyze GBOML model results with specific criteria.")
parser.add_argument('-m', '--mode', help="Mode of operation: analyze_json or analyze_csv", default='analyze_json', choices=['analyze_json', 'analyze_csv'])
# parser.add_argument('-s', '--sce... | The main task of the code is to execute different analysis functions based on the provided mode argument. It parses command-line arguments, then calls either analyze_json_files() or analyze_csv_files() depending on whether the mode is 'analyze_json' or 'analyze_csv', respectively, to process and analyze data from JSON ... | def main():
args = parse_args()
if args.mode == 'analyze_json':
analyze_json_files(args)
elif args.mode == 'analyze_csv':
analyze_csv_files(args) |
def init():
global h
# Public key, g^s
h = comp_large(g, s, q)
print('\nInitial conditions of the system:')
#print('p: {}'.format(p))
print('\nq is a large prime chosen by the voting authorities. It is often a \"safe\" prime, meaning that (q-1)/k is also prime, in order to prevent small-su... | The main task of the code is to simulate a secure voting system using ElGamal encryption. It allows five voters to cast encrypted votes, leverages the scheme's multiplicative homomorphism to tally votes without decrypting individual ballots, and decrypts the aggregated result to determine the winner between candidates ... | def main():
init()
print('\nNow it\'s time to act as the voters. There are 5 voters in our system. Each voter generates a random private key (in our case, the computer does it for them). They then encrpt their vote using their private key and the voting authority public key using ElGamal encryption. KEY CO... |
def __init_krampus(self) -> None:
krampus = Struct()
krampus["min"] = Float([0x10])
krampus["current"] = Float([0x14])
krampus["max"] = Float([0x18])
self._krampus = krampus
def __init_settings(self) -> None:
settings = Struct()
settings["hp"] = self.make_krampus(... | The code initializes an object by calling three private methods: `__init_krampus`, `__init_settings`, and `__init_unit`, each likely responsible for configuring specific components or settings of the class. The main task is to set up the object's internal state and prepare it for operation by executing these initializa... | def __init__(self):
self.__init_krampus()
self.__init_settings()
self.__init_unit() |
def doStep(app):
app.dx = app.xVel
#x-direction isn't affected by gravity
app.yVel += app.gravity
#since the y-cord are inverted in canvas, we add the gravity to the vel
app.dy = app.yVel
#change per second is the new velocity
app.x0 += app.dx
app.y0 += app.dy
def isInFrame(app):
pla... | The function updates the ball's position, tracks its trajectory, checks for collisions, updates the score upon collision, and adjusts movement vectors. It maintains a history of the ball's recent positions and ensures collision detection and response are handled within the game loop. | def updateBall(app):
doStep(app)
isInFrame(app)
app.ballPos.append((app.x0+app.r, app.y0+app.r))
if len(app.ballPos)>2:
app.ballPos.pop(0)
flag, x1, y1, x2, y2 = isColliding(app)
if flag:
app.score += 3
vectorCalc(app, x1, y1, x2, y2)
doStep(app) |
def exist(self, state):
return self.get_son(state) is not None
def add_son(self, state, move):
son = Tree(self, state, self.get_cost() + 1, move)
self.__sons.append(son)
return son
def get_son(self, state):
for son in self.get_sons():
if son.get_state().equals(state):... | This function recursively inserts a sequence of states and moves into a tree structure. It processes the first element of sol_path by either creating a new node (if the state doesn't exist) or retrieving an existing one, then continues inserting the remaining path into the child node. The main task is to construct or t... | def insert_in_sequence(self, sol_path):
if bool(sol_path):
state, move = sol_path[0].get_state(), sol_path[0].get_move()
sol_path.pop(0)
new_son = self.add_son(state, move) if not self.exist(state) else self.get_son(state)
new_son.insert_in_sequence(sol_path) |
def add_fractions(a, b): return simplify([a[0]*b[1] + b[0]*a[1] , a[1]*b[1]])
def multiply_fractions(a, b): return simplify([a[0]*b[0], a[1]*b[1]])
def geometric_series(r):
if r == [1,1]: return r
difference = substract_fractions([1,1], r)
return divide_fraction([1,1], difference) | The code updates a matrix representing transition probabilities in a Markov chain. It modifies entries to account for paths through a specified node, sets direct transitions to/from the node as certain, and adjusts self-loop probabilities using a geometric series to ensure valid probability distributions. | def calculate_probabilities(mat, node):
for i in range(len(mat)):
for j in range(len(mat)):
if(i != node and j != node):
mat[i][j] = add_fractions(mat[i][j], multiply_fractions(mat[i][node], mat[node][j]))
for i in range(len(mat)):
mat[i][node] = mat... |
def is_terminal(state): return all(n==0 for n in state)
def get_probability_matrix(mat):
probability_matrix = []
for i in range(len(mat)):
probability_matrix.append([None] * len(mat))
for j in range(len(mat)):
probability_matrix[i][j] = divide_fraction([mat[i][j],1], [sum(mat[i]),1])... | The code calculates the probabilities of ending in each terminal state from the initial state in a Markov chain, represented by matrix `m`. It first handles edge cases, identifies terminal and non-terminal states, constructs a transition probability matrix, computes absorption probabilities, and simplifies results to h... | def solution(m):
# Edge case: Starting state is also terminal
if is_terminal(m[0]): return [1] + [0]*(len(m)-1) + [1]
# Clean non-significant values
for i in range(len(m)): m[i][i] = 0
terminal_states = [i+1 for i, state in enumerate(m[1:]) if is_terminal(state)]
non_terminal_states = [i+1 for... |
def connect_wifi(self):
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
sta_if.active(True)
sta_if.connect(passwords.wifi_ssid, passwords.wifi_psk)
while not sta_if.isconnected():
print("waiting to connect to wifi")
machine.idl... | The code's main task is to initialize a device's operations by connecting to Wi-Fi, updating the display, and processing incoming requests. The `start` method triggers these actions sequentially: first establishing a Wi-Fi connection, then refreshing the display, and finally handling any pending requests or tasks. This... | def start(self):
print(self.connect_wifi())
self.update_display()
self.handle_requests() |
def writeCmd(args):
#recieving the pressed button id and passing the button text to mapped CLI
cmd = args.cget(('text'))
print("clickedButton", cmd)
#avialable commands can be changed to dictionary
clicked_Button = ['Buzzer', 'LED', 'Display', "Valve-Open","Valve-Close",
"Regu... | This code defines a GUI interface with buttons for testing hardware functions (e.g., Buzzer, LED, Valve) and corresponding "Pass" buttons to record test outcomes. It initializes buttons for commands like "writeCmd" and "collectResult," arranges them in a grid layout, and includes a mode selection dropdown. The primary ... | def userPassFail():
global buzzer_btn_Pass, led_btn_Pass,Display_btn_Pass,shutoff1_btn_Pass,gas_on_btn_Pass
global shutoff2_btn_Pass,remove_btn_Pass,lock_btn_Pass,unlock_btn_Pass,gsm_btn_Pass
global selfTest_btn_Pass,amode_btn_Pass,ui_btn_Pass, nfc_btn_Pass
global mode_var, mode
#Buttons to run the... |
def portbaudInput():
global connect_btn, refresh_btn
port_label = Label(root, text="Available Port(s): ", bg="white")
port_label.grid(column=0, row=0, pady=20, padx=10)
port_bd = Label(root, text="Baude Rate: ", bg="white")
port_bd.grid(column=0, row=1, pady=20, padx=10)
refresh_btn = Button(r... | This code initializes a Tkinter GUI for a CSM System Check application, creating input fields for MCU/GSM stop current values, buttons to save/cancel entries, and integrates port settings, part numbers, and baud rate configurations. It sets up the interface with specific styling, layout, and event handlers for user int... | def csmcheck_menu_init():
global root, graph, msc_entry, gsc_entry
root = Tk()
root.title("CSM System Check")
root.geometry("925x700")
root.config(bg="light blue")
root.option_add("*Font", "Montserrat 10")
msc_val = StringVar()
gsc_val = StringVar()
portbaudInput()
partNumbe... |
def get_region_box(input, predict, biases, n, index, i, j, w, h):
"""
:param input: feature map (numpy array)
:param predict: prediction result
:param biases: biases
:param n: index of preset number of boxes
:param index: index
:param i: index of row
:param j: index or column
:param ... | The function processes a convolutional feature map to detect objects by applying confidence thresholds, non-maximum suppression (NMS), and formatting predictions into bounding boxes with class labels and confidence scores. It reshapes input data, computes object and class probabilities, filters high-confidence detectio... | def set_up_detection_out(input, num_classes, coords =4, confidence_threshold = 0.4, nms_threshold = 0.4,
biases = [1.578, 3.456, 2.330, 2.096, 3.835, 2.885, 2.586, 4.704, 1.475, 1.396], num_box=5):
"""
set_up_detection_out is the function should be used
:param input: feature map fro... |
def generate_random_train_lines(self, number_trainlines, all_train_lines, length, nodes):
# This function will generate the train lines randomly for the global company scenario
train_lines = []
valid = True
for i in range(number_trainlines):
starting_station = random.choice(n... | The function calculates the optimal train network configuration by generating random train lines, evaluating their benefits, selecting top-performing lines, improving them, optimizing frequencies, and returning the best-performing train line configuration with optimal frequencies and maximum benefits. | def calculate_the_best_train_lines(self, max_min_number_train_lines, all_train_lines, max_min_station_per_line, nodes, mapping, values_trips, number_improved_train_lines, number_frequency_train_lines, number_trials, number_random_train_lines, plotting, two_companies_scenario, lines_top, lines_bottom):
# This fu... |
def calculate_optimal_trajectories(self, stations, mapping):
# This function will calculate the optimal trajectories (if all the connections are available)
all_train_lines = []
for line in self.lines[1:]:
elements = line.split('\t')
init_node = int(elements[1])
... | The code optimizes train line configurations and frequencies for two cooperating companies through iterative improvement. It reads initial data, alternates optimizing top and bottom companies' lines, checks for convergence, calculates benefits/costs, and exports results to Excel. The goal is to find a cooperative equil... | def coop_scenario(self):
previous_top_train_lines = ast.literal_eval(pd.read_excel('Two_companies_iteration.xlsx')['Top Company Lines'].tolist()[0])
previous_top_frequency = ast.literal_eval(pd.read_excel('Two_companies_iteration.xlsx')['Top Company frequency'].tolist()[0])
previous_bottom_train... |
def calculate_optimal_trajectories(self, stations, mapping):
# This function will calculate the optimal trajectories (if all the connections are available)
all_train_lines = []
for line in self.lines[1:]:
elements = line.split('\t')
init_node = int(elements[1])
... | The function processes Excel data to analyze train line efficiency and financial outcomes for different company scenarios (two companies, cooperation, global). It calculates costs, benefits, user metrics, and updates Excel files with results, comparing scenarios through iterative computations and outputting key perform... | def solutionner(self):
# Debugging function
top_company_line = ast.literal_eval(pd.read_excel('Two_companies_iteration.xlsx')['Top Company Lines'].tolist()[0])
top_company_frequency = ast.literal_eval(pd.read_excel('Two_companies_iteration.xlsx')['Top Company frequency'].tolist()[0])
bot... |
def calculate_optimal_trajectories(self, stations, mapping):
# This function will calculate the optimal trajectories (if all the connections are available)
all_train_lines = []
for line in self.lines[1:]:
elements = line.split('\t')
init_node = int(elements[1])
... | This function calculates optimal train lines for a global company by evaluating multiple scenarios, computing metrics like benefits, pollution, and passenger behavior, and exporting results to Excel. It determines the best trajectories, analyzes costs and profits, and visualizes the optimal train network with key perfo... | def calculate_global_train_lines(self):
# This function will calculate the best train lines for the global company
mapping = {node: node-1 for node in range(1, 25)}
all_train_lines = self.calculate_optimal_trajectories(range(1,25), mapping)
two_companies_scenario = False
n_i... |
def calculate_construction_costs(self):
# This function will calculate the construction costs of the network for the two companies
nodes_top_company = [1, 2, 3, 4, 5, 6, 7, 8, 0]
shared_nodes = [10, 11, 9, 15, 17]
nodes_bottom_company = [13, 14, 12, 16, 18, 20, 21, 22, 23, 19]
n_... | The main task of the code is to execute a sequence of operations including calculating construction costs, adjusting values, determining global and local train line configurations, simulating cooperative scenarios, and generating visualizations through plotting. These steps collectively support a comprehensive analysis... | def main(self):
self.calculate_construction_costs()
self.change_values()
self.calculate_global_train_lines()
self.calculate_local_train_lines()
self.coop_scenario()
self.plotting_graph() |
def _create_cells(self):
for col_Value in range(self.num_cols):
col = []
for row_Value in range(self.num_rows):
point1 = Point((self.x1 + self.x1 * col_Value) * self.cell_size_x,
(self.y1 + self.y1 * row_Value) * self.cell_size_y)
... | This code initializes a maze generator by setting up grid parameters, creating cells, breaking walls recursively to form paths, and resetting visited states. It uses randomization based on a seed to generate unique mazes, with methods for creating the maze structure, defining entry/exit points, and preparing for pathfi... | def __init__(self, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, window, seed=None):
self.x1: int = x1
self.y1: int = y1
self.num_rows: int = num_rows
self.num_cols: int = num_cols
self.cell_size_x: int = cell_size_x
self.cell_size_y: int = cell_size_y
sel... |
def display_jobs(self):
"""Optimized display of jobs."""
with self.lock:
max_y, max_x = self.screen.getmaxyx()
current_jobs = len(self.jobs)
string_size = max_x - self.left_margin - 1
self.screen.addstr(
1, self.left_margin, self.header[:s... | This function handles keyboard inputs in a curses-based interface to navigate and manage job listings. It allows users to cancel jobs, view output files via 'less' or 'tail', SSH into nodes, and resize the interface. The loop continuously updates the display, processes key events, and handles errors, exiting on 'q' or ... | def key_event_handler(self):
self.screen.nodelay(True)
sleep_time = 0.1
self.display_jobs()
while True:
try:
key = self.screen.getch()
if key != -1:
if key == ord("q") or key == ord("Q"):
break
... |
def process_database_gene(rName, inFileName, geneAliasDict, GenesInfo, averagesimilarterm, simCutoff, ovlpcorfCutoff, seedGeneList, wkdir):
outFilePrefix = wkdir + "Database_JI/" + rName
jaccard_index = calcJIforTerms(GenesInfo, seedGeneList, inFileName, geneAliasDict)
writeJIterms(jaccard_index, outFilePre... | This function processes gene set data to compute Jensen-Shannon Index (JI) features for biological terms. It reads a file listing gene sets, determines whether to process gene-level or term-level JI based on data type, and applies corresponding calculations. Results are optionally inserted into a dataset as vectors ord... | def process_input(geneSetDataList, GenesInfo, geneAliasDict, seedGeneList, wkdir, suffix, inserttodataframe=True, averagesimilarterm=True, simCutoff=0.5, ovlpcorfCutoff=0.9, geneOrder=[], dataset=False):
with open(geneSetDataList, "r") as scFn:
for line in scFn:
info = line.strip().split("\t")
... |
def createGeneList(geneList):
GeneInfo = {}
for gene in geneList:
GeneInfo[gene] = Gene_JI(gene, 0)
return GeneInfo
def labelSeedGenes(GeneInfo, seedGeneList):
for g in seedGeneList:
try:
GeneInfo[g].markGene()
except KeyError:
pass
return GeneInfo
de... | The main task of the code is to process a gene dataset by calculating Jensen-Inequality (JI) annotations using seed genes, gene set data, and similarity thresholds. It creates an output directory, maps gene aliases, processes input data with specified parameters (e.g., similarity cutoffs), and saves the enhanced datase... | def main(dataset, geneSetDataList, seedGeneList, SUFFIX, outPATH=dirname, inserttodataframe=True, averagesimilarterm=True, simCutoff=0.5, ovlpcorfCutoff=0.9):
## Create folder to store JI result
if not os.path.exists(outPATH + SUFFIX + "Database_JI"):
os.makedirs(outPATH + SUFFIX + "Database_JI")
#... |
def add_checker(x, y, board, player):
board_computed = compute_counts(x, y, board, player)
board[x][y] = player
for y in range(8):
for x in range(8):
if board_computed[x][y] == player:
board[x][y] = player
return board
def score_human(x, y, board):
oneScore = 0
... | This function handles a human player's move in a board game (likely Othello/Reversi). It checks if the clicked position is a valid move, updates the board and score, switches turns, and highlights new allowed moves. If no valid moves remain, it declares the game over. | def humanclick(event):
global AllowedMoves
global turn
x = int((event.x ) / 50)
y = int((event.y) / 50)
if [x, y] not in AllowedMoves:
return
if turn == 1:
player = 1
if turn == 2:
player = 2
if [x, y] in AllowedMoves:
pouli.delete("all")
boa... |
def allowed_move(x, y, board, player):
if board[x][y] != 0:
return False
returned = False
if player == 1:
this_player = 1
opponent = 2
else:
this_player = 2
opponent = 1
if y > 0:
if board[x][y - 1] == opponent:
returned = check_up(x, y, bo... | The code handles a human click event in a Reversi/Othello game, validating the move, updating the board, and triggering the computer's turn. It checks for allowed moves, highlights them, selects the computer's optimal move (maximizing flipped pieces), updates the score, and alternates turns until no moves remain, displ... | def computerclick(event):
global AllowedMoves
#Human move
x = int((event.x ) / 50)
y = int((event.y) / 50)
if [x, y] not in AllowedMoves:
return
player = 1
AllowedMoves = []
checkForAllowed = False
for i in range(8):
for j in range(8):
if allowed_m... |
def allowed_move(x,y,board,player):
if board[x][y]!=0:
return False
returned = False
if player == 1:
this_player = 1
opponent = 2
else:
this_player = 2
opponent = 1
if y>0:
if board[x][y-1] == opponent:
returned = check_up(x,y,board,this_pl... | The function `human_play` handles a human player's turn in a board game (likely Reversi/Othello). It identifies valid moves, prompts the player for input, validates the move, updates the board, calculates the score, and displays the result. It ensures moves are within bounds and allowed, providing feedback for invalid ... | def human_play(board,player):
print('\nPLAYER: ',player,' HAS THE NEXT MOVE')
#list of allowed moves
AllowedMoves = []
checkForAllowed = False
for i in range(8):
for j in range(8):
if allowed_move(i,j,board,player):
checkForAllowed = True
All... |
def allowed_move(x,y,board,player):
if board[x][y]!=0:
return False
returned = False
if player == 1:
this_player = 1
opponent = 2
else:
this_player = 2
opponent = 1
if y>0:
if board[x][y-1] == opponent:
returned = check_up(x,y,board,this_pl... | The main task of the code is for the computer to determine its optimal move in a game like Reversi/Othello by evaluating all allowed moves, selecting the one that flips the most tiles, updating the board, and printing the result. It checks for valid moves, handles no-move scenarios, calculates tile reversals, and execu... | def computer_play(board,player):
#list of allowed moves
AllowedMoves = []
checkForAllowed = False
for i in range(8):
for j in range(8):
if allowed_move(i,j,board,player):
checkForAllowed = True
AllowedMoves.append([i,... |
def set_flow_pkt(self):
self.set_flow_mean_std("fwd", "pkt")
self.set_flow_mean_std("bwd", "pkt")
self.set_flow_len_size_min_max_mean_std()
def set_flow_iat(self):
self.set_flow_mean_std("all", "iat")
self.set_flow_mean_std("fwd", "iat")
self.set_flow_mean_std("bwd", "iat... | The code's main task is to generate a list of network flow features for analysis, including packet statistics, inter-arrival times, protocol details, and flow dynamics. It compiles attributes like packet size, duration, direction-specific metrics (forward/backward), flag counts, window sizes, and labels, returning them... | def to_list(self, label=0):
self.set_flow_pkt()
self.set_flow_iat()
self.set_flow_speed()
self.set_flow_dp_ratio()
return [self.no,
self.time,
self.src,
self.srcport,
self.dst,
self.dstport,
... |
def perturb(S, t, phi, r, sign=1, Heading=True, Speed=False):
"""S is the set of neighbours to be perturbed by speed or heading at time t
This function sets phi and r for the perturbed pedestrians"""
for i in S:
j = [0, 1, 2, 12, 13, 14, 15, 16, 17, 27, 28, 29].index(i)
if Heading == True:
... | The function simulates pedestrian movement by perturbing heading or speed based on input parameters, updates positions over time, tracks a "real" person's movement, records final heading/speed values in a dataframe, and returns perturbed/unperturbed data along with neighbor lists. It adjusts virtual neighbors' speed/he... | def all_together(i, S, position, phi, r, copy_position, copy_phi, copy_r,
data=my_exp1_final_heading_data, h=True, s=False, sign2=1):
"""get the final headings and speed of the pedestrian following the model from the given perturbed subset S
when h is true heading is perturbed, when s True the... |
def make_blob(start, output, end=None, label=None):
return { "start": start, "output": output, "end": end if end else start, "label": label }
def get_pointer(address, bank=None):
if bank is None:
bank = get_bank(address)
return (rom[address + 1] * 0x100 + rom[address]) % 0x4000 + bank * 0x4000
def dump_channel(sta... | The function `dump_sound` generates data blobs and labels for sound channels from a ROM. It processes channel headers, extracts channel-specific data, creates labeled blobs for each channel, and aggregates them. It handles multiple channels, constructs structured output with headers and addresses, and returns lists of ... | def dump_sound(header, sound_name, prefix="", is_sfx=True):
blobs = []
blobs.append(make_blob(header, "{}{}:\n".format(prefix, sound_name)))
labels = []
final_channel = (rom[header] >> 6) + 1
for i in range(final_channel):
channel_num = (rom[header] & 0b1111) + 1
start_address = get_pointer(header + 1)
if i ... |
def get_pointer(address, bank=None):
if bank is None:
bank = get_bank(address)
return (rom[address + 1] * 0x100 + rom[address]) % 0x4000 + bank * 0x4000
def dump_channel(start_address, sound_name, channel, prefix="", is_sfx=True, address=None):
blobs = []
labels = []
branches = set()
if address is None:
blobs... | The main task of the code is to generate assembly code for drum kits by iterating through memory pointers, extracting audio data chunks, formatting them with drum names, and writing the structured output to a file. It creates pointer tables, processes 6 drumkits each with 13 drums, collects binary blobs, adjusts format... | def dump_all_drumkits():
blobs = []
pointer_table = "Drumkits:\n"
pointer_tables = []
drumkit_pointer = 0xe8e52
for drumkit in range(6):
pointer_table += "\tdw Drumkit{}\n".format(drumkit)
drumkit_table = "Drumkit{}:\n".format(drumkit)
drum_pointer = get_pointer(drumkit_pointer + drumkit * 2)
for drum in r... |
def get_pointer(address, bank=None):
if bank is None:
bank = get_bank(address)
return (rom[address + 1] * 0x100 + rom[address]) % 0x4000 + bank * 0x4000
def dump_sound(header, sound_name, prefix="", is_sfx=True):
blobs = []
blobs.append(make_blob(header, "{}{}:\n".format(prefix, sound_name)))
labels = []
final_... | The function `export_all_sounds` extracts and processes sound data from a ROM file. It iterates over sound names, retrieves sound data using pointers, sorts/filtering the data, and writes each processed sound to a `.asm` file at the specified path. The function handles header navigation, data extraction, and file outpu... | def export_all_sounds(path, header_pointer, sound_names, prefix="", is_sfx=True):
sounds = []
labels = []
for sound_name in sound_names:
header = get_pointer(header_pointer + 1, rom[header_pointer])
blobs, sound_labels = dump_sound(header, sound_name, prefix, is_sfx)
sounds.append(blobs)
labels += sound_labe... |
def dump_all_sounds(header_pointer, sound_names, prefix="", is_sfx=True):
blobs = []
for sound_name in sound_names:
header = get_pointer(header_pointer + 1, rom[header_pointer])
blobs += dump_sound(header, sound_name, prefix, is_sfx)[0]
header_pointer += 3
return blobs
def dump_channel(start_address, sound_nam... | This function extracts Pokémon cry sounds from specified memory addresses in a game ROM, aggregates them into a list of audio blobs, sorts and filters the data, then writes the processed sounds to an assembly file ("cries.asm") in the "audio/" directory for further use. | def dump_all_cries():
blobs = dump_all_sounds(0xe91b0, cry_names, "Cry_")
blobs += dump_channel(0xf3134, "Sentret", 8, "Cry_")[0]
blobs += dump_channel(0xf35d3, "Unused", 5, "Cry_")[0]
blobs += dump_channel(0xf35ee, "Unused", 6, "Cry_")[0]
blobs += dump_channel(0xf3609, "Unused", 8, "Cry_")[0]
blobs = sort_and_fi... |
def dump_all_sounds(header_pointer, sound_names, prefix="", is_sfx=True):
blobs = []
for sound_name in sound_names:
header = get_pointer(header_pointer + 1, rom[header_pointer])
blobs += dump_sound(header, sound_name, prefix, is_sfx)[0]
header_pointer += 3
return blobs
def dump_sound(header, sound_name, prefix... | This function extracts and processes sound effect data from a game, splitting them into two categories based on bank boundaries. It dumps sound blobs, sorts/filtering them, then divides the list into 'sfx' and 'sfx_crystal' segments. Finally, it writes these segmented audio data to separate assembly files for organized... | def dump_all_sfx():
blobs = dump_all_sounds(0xe927c, sfx_names, "Sfx_")
blobs += dump_sound(0xf0d5f, "Unused", "Sfx_")[0]
blobs = sort_and_filter(blobs)
for i, (blob, next) in enumerate(zip(blobs, blobs[1:])):
if get_bank(blob["end"]) != get_bank(next["start"]):
sfx = blobs[:i + 1]
sfx_crystal = blobs[i + 1... |
def get_rand_tmp_file_name() -> str:
"""TODO replace
Returns a random file name in /tmp"""
letters = string.ascii_lowercase
rand_name = (''.join(random.choice(letters) for i in range(15)))
return f"/tmp/{rand_name}"
def log_print(
*args: Union[str, bytes],
_print: bool = True,
... | This function writes content to a temporary file, then uses sudo to move it to a specified location, enabling writing to files Python can't access directly. It logs differences if the target file exists or overwrites it, bypassing permission restrictions by leveraging sudo for the file move operation. | def sudo_write_file(content: str, perm_location: str) -> None:
"""Writes file in /tmp and moves it to another location using sudo.
Allows user to write to files that python doesn't have permission
to write to.
Args:
content (str): What will be in the file
perm_location (str): The file t... |
def get_match_df(connection):
match_df = pd.read_sql_query(MATCH_DF_QUERY, connection)
match_df['date'] = match_df['date'].apply(lambda x: datetime.strptime(x, FORMAT_DATE_STR))
match_df['season_date'] = match_df['season'].apply(lambda x: datetime(year=int(x.split('/')[0]), month=1, day=1))
player_att_d... | The code processes sports match and season data by connecting to a database, retrieving match and season statistics, merging them into a comprehensive DataFrame, adding future match information for teams, and saving the processed data as a pickle file for further analysis. | def main():
connection = sqlite3.connect('data/database.sqlite')
# match_df - goals, ratings and betting odds info for each match in a certain league
match_df = get_match_df(connection)
# season_df - wins, league points and season info (total goals for each team)
season_df = get_season_df(connection... |
def wordDocument(speech):
if ("word" in speech or "Word" in speech):
type = "docx"
speak("How should I name the document?")
name = getFileName()
speak("What should I write in it?")
text = getText()
speak("Creating " + name + ".docx...")
createFile(na... | The function attempts to create a file (Word, PDF, or TXT) based on input speech. It prioritizes Word documents, then PDFs, then TXT files if prior attempts fail, returning the first successfully generated file. | def doCreateFile(speech):
if ("file" in speech or "document" in speech):
x = wordDocument(speech)
if (x == None):
x = pdfFile(speech)
if (x == None):
x = txtFile(speech)
return x |
def calc_r0(ABGMRES, A, B, b, x, filter):
if ABGMRES:
r0 = np.asarray(b).reshape(-1) - np.asarray(apply(A, x)).reshape(-1)
r0 = elsa.DataContainer(np.reshape(r0, np.shape(np.asarray(b))), b.getDataDescriptor())
return r0, np.shape(np.asarray(b))
else:
r0 = np.asarray(apply(B, b, ... | This code implements the GMRES (Generalized Minimal Residual) algorithm to solve a linear system Ax = b, using an iterative Krylov subspace approach. It constructs an orthogonal basis via Arnoldi iteration, computes residual norms, and solves a least-squares minimization to approximate the solution. The ABGMRES variant... | def GMRES(A, B, b, x0, nmax_iter, epsilon=None, ABGMRES=True, filter=False):
# --- 1. Instantiate ---
# r0 = b - Ax
r0, r0_shape = calc_r0(ABGMRES=ABGMRES, A=A, B=B, b=b, x=x0, filter=filter)
h = np.zeros((nmax_iter + 1, nmax_iter))
w = [np.zeros(r0_shape[0] * r0_shape[1])] * nmax_iter
e = np.... |
def scalarmult1(scalar, cofactor):
co_cleared = ((cofactor * 5) % 8) * order # cleared main factor
combined = trim(scalar) + co_cleared
return from_edwards(ed_scalarmult(ed_base_1, combined))
def scalarmult2(scalar, cofactor):
co_cleared = (cofactor % 8) * order # cleared main factor
combined ... | The code performs scalar multiplication using five different methods, compares their results, and raises an error if they differ, ensuring consistency across implementations. | def scalarmult(scalar, cofactor):
p1 = scalarmult1(scalar, cofactor)
p2 = scalarmult2(scalar, cofactor)
p3 = scalarmult3(scalar, cofactor)
p4 = scalarmult4(scalar, cofactor)
p5 = scalarmult5(scalar, cofactor)
if p1 != p2 or p1 != p3 or p1 != p4 or p1 != p5:
raise ValueError('Incoherent s... |
def split_hist(heights, bin_edges, high_bin_indices, divisor=1000):
""" Plot a histogram where one or more bins have very large values """
# Make high_bin_indices a list if an int was passed
if isinstance(high_bin_indices, int):
high_bin_indices = [high_bin_indices]
# Create 2-row, 1-col subplot... | This function plots a histogram of input data, clamping outliers to the last bin, and dynamically chooses between a standard or split histogram based on height variability. It adjusts y-axis labels for scalability and applies customizable axis labels. | def plot_hist(data, bins, xlabel=None, ylabel=None, divisor=1000):
fig = plt.figure()
# Make it so that all points beyond the bin range get put in the last bin
data = np.array(data)
data[data > bins[-1]] = bins[-1] - 1e-10
# Get histogram bin heights
heights, _ = np.histogram(data, bins)
# I... |
def MergeAndFilterByPlatform(env, params):
"""Take a dictionary of arguments to lists of values, and, depending on
which platform we are targetting, merge the lists of associated keys.
Merge by combining value lists like so:
{win_foo = [a,b], lin_foo = [c,d], foo = [e], mac_bar = [f], bar = [g] }
... | This function wraps a SCons builder to preprocess and post-process inputs/outputs by merging platform-specific parameters, handling dependencies, adjusting build flags (like CPPDEFINES, LIBS), managing signed binaries, and generating debug symbols. It modifies the environment, processes libraries, and returns the built... | def ExtendComponent(env, component, **kwargs):
"""A wrapper around a scons builder function that preprocesses and post-
processes its inputs and outputs. For example, it merges and filters
certain keyword arguments before appending them to the environments
construction variables. It can build signed ... |
def checkCollision(self, pos):
"""
Check if the bacteria collide with the side of the tube.
Peform either an arching or tangental collision
"""
# coordinates of the position
x = pos[0]
y = pos[1]
if x < 0 and y < 0:
x ... | This code simulates bacterial movement by updating position based on velocity, directional angle, and diffusion. It handles run/tumble dynamics, collision checks, and stochastic processes for rotational diffusion. The method also tracks doubling timers, adjusts movement status, and triggers pattern-specific behaviors (... | def step(self):
"""
Move the bacteria accordingly
"""
# if bacteria have just doubled reset the doubling timer
if self.next_double < self.dt:
self.next_double = np.random.normal(self.doubling_mean, self.doubling_std, 1)
# get the run status
... |
def stepConcentration(self):
"""
Update the concentration grid of the model depending on the current location of agents.
Uses finite difference equations of Ficks law from Franz et al.
"""
#calculate components needed for the discretisation
dx2, dy2 = self.dx * self.dx,... | The main task of the code is to advance the model by one simulation step, including scheduling updates, evaluating concentration fields, handling cell collisions, updating bacterial reproduction, tracking cells, and periodically saving angle distributions and density data. It also increments the tick counter and prints... | def step(self):
"""
Combine methods to do one step of the model
"""
#perform a step
#print('STEP')
#start = time.time()
self.schedule.step()
#end = time.time()
#print(end-start)
#ignore the first tic
if self.ticks > 1:
... |
def display_menu():
"""The display_menu() function displays the menu for the user's options
and prompts user for their choice while validating their input"""
# 1. Display all U.S. States in Alphabetical order along with the
# Capital, State Population, and Flower
# 2. Search for a specific state a... | The main task of the code is to run a menu-driven U.S. states application allowing users to display, search, update population data, and visualize state information via a bar graph. The `main()` function controls the program flow by repeatedly displaying a menu, capturing user choices, and invoking corresponding functi... | def main():
"""The main() function is the start of the program interacting with the user.
All other functions are called in this function to display the menu for the user
to choose an option and perform the corresponding tasks that the user chooses."""
# This menu-driven application allows a user ... |
def display_menu():
"""The display_menu() function displays the menu for the user's options
and prompts user for their choice while validating their input"""
# 1. Population Data
# 2. Housing Data
# 3. Exit Program
print("\nSelect the file you want to analyze:\n") # Prompt
print("1. ... | The main task of the code is to provide a user with a menu-driven interface to analyze CSV datasets (PopChange.csv & Housing.csv) by generating histograms, plots, and statistical insights for selected variables, with options to exit the program. | def main():
"""The main() function is the start of the program interacting with the user.
All other functions are called in this function to display the menu for the user
to choose an option and perform the corresponding tasks that the user chooses."""
# This program allows a user to load one of two C... |
def display_menu():
"""The display_menu() function displays the menu for the user's options
and prompts user for their choice while validating their input"""
# 1. Generate Secure Password
# 2. Calculate and Format a Percentage
# 3. How many days from today until July 4, 2025?
# 4. Use the Law ... | The main task of the code is to serve as a menu-driven application's entry point, allowing users to select from math and security-related functions like password generation, percentage calculation, day counting, law of cosines, and volume calculation. It displays a welcome message, loops through a menu of options, exec... | def main():
"""The main() function is the start of the program interacting with the user.
All other functions are called in this function to display the menu for the user
to choose an option and perform the corresponding tasks that the user chooses."""
# This menu-driven application provides users wit... |
def bytes2matrix(text):
""" Converts a 16-byte array into a 4x4 matrix. """
return [list(text[i:i+4]) for i in range(0, len(text), 4)]
def add_round_key(s, k):
for i in range(4):
for j in range(4):
s[i][j] ^= k[i][j]
def sub_bytes(s):
for i in range(4):
for j in range(4):
... | This method encrypts a plaintext block using AES by applying multiple rounds of substitution, shifting, mixing columns, and adding round keys. It converts plaintext to a matrix, performs initial key addition, iterates through rounds with sub_bytes, shift_rows, mix_columns, and key addition, then finalizes with sub_byte... | def encrypt_block(self, plaintext):
"""
This is a helper method which is used to encrypt the given plaintext. This method is called from
encrypt() to ensure the encryption happens and the ciphertext is returned. This involves 4 steps
1. add_round_key
2.
Args:
- p... |
def bytes2matrix(text):
""" Converts a 16-byte array into a 4x4 matrix. """
return [list(text[i:i+4]) for i in range(0, len(text), 4)]
def add_round_key(s, k):
for i in range(4):
for j in range(4):
s[i][j] ^= k[i][j]
def inv_shift_rows(s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1... | This function decrypts a single block of ciphertext using AES decryption steps. It applies inverse operations (inv_sub_bytes, inv_shift_rows, inv_mix_columns) in reverse order of encryption rounds, combined with round keys from self._key_matrices. The process starts with the last round key, iterates through inverse tra... | def decrypt_block(self, ciphertext):
cipher_state = bytes2matrix(ciphertext)
add_round_key(cipher_state, self._key_matrices[-1])
inv_shift_rows(cipher_state)
inv_sub_bytes(cipher_state)
for i in range(self.n_rounds - 1, 0, -1):
add_round_key(cipher_state, self._key... |
def pad(plaintext):
"""
Pads the given plaintext with PKCS#7 padding to a multiple of 16 bytes.
Note that if the plaintext size is a multiple of 16,
a whole block will be added.
"""
padding_len = 16 - (len(plaintext) % 16)
padding = bytes([padding_len] * padding_len)
return plaintext + p... | The main task of the code is to encrypt plaintext using AES in CBC mode. It pads the input, splits it into blocks, XORs each block with the previous ciphertext block (starting with the IV), encrypts the result, and concatenates the encrypted blocks to produce the final ciphertext. | def encrypt_cbc(self, plaintext, iv):
"""
Encrypts the given plaintext using the given initialization vector (iv).
"""
plaintext = pad(plaintext)
blocks = []
previous = iv
for plaintext_block in split_blocks(plaintext):
block = self.encrypt_block(xor... |
def split_blocks(message, block_size=16):
return [message[i:i+16] for i in range(0, len(message), block_size)]
def xor_bytes(a, b):
""" Returns a new byte array with the elements xor'ed. """
return bytes(i^j for i, j in zip(a, b))
def decrypt_block(self, ciphertext):
cipher_state = bytes2matrix... | The function decrypts AES ciphertext in CBC mode using the provided IV by decrypting each block, XORing it with the previous block (starting with IV), and combining results, then removing padding to retrieve the original plaintext. | def decrypt_cbc(self, ciphertext, iv):
"""
Decrypts the given ciphertext using the given initialization vector (iv).
"""
blocks = []
previous = iv
for ciphertext_block in split_blocks(ciphertext):
# CBC mode decrypt: previous XOR decrypt(ciphertext)
... |
def make_project_folder(self):
current_datetime = datetime.now().strftime("%Y-%m-%d_%H-%M")
self.folder_name = f"{self.project_name}_{current_datetime}"
self.project_path = os.path.join(self.output_path, self.folder_name)
if not os.path.exists(self.project_path):
os.makedir... | This code initializes a project for text analysis by configuring parameters for document preprocessing, embedding generation (using SentenceTransformer), dimensionality reduction (UMAP), and clustering (HDBSCAN). It sets up file paths, text processing rules, sampling options, and model hyperparameters, then preprocesse... | def __init__(
self,
project_name: str,
output_path: str,
documents_path: str = "",
file_path: str = "",
file_type: str = None,
model: str = "all-MiniLM-L6-v2",
embeddings_path: str = "",
reduced_embeddings_path: str = "",
reduced_2D_embeddi... |
def distance_from_tokens(token_pos, token_list):
"""Returns the total manhattan or euclidean distance from the given token to the list of tokens provided"""
total = 0
if token_list != None:
for pos in token_list:
total += manhattan_distance(token_pos, pos)
#total += euclidean... | The function calculates a token's "wellbeing" heuristic on a board by evaluating its distance to victims and predators. It subtracts the token's distance to victims from its distance to predators, adjusting both values by a fixed offset of 8. A lower value indicates better wellbeing, favoring tokens that are farther fr... | def token_value(token_type, token_pos, board_state):
"""Function returns the "wellbeing" of a token which is a part of the heurstic of the whole board.
Defined as [distance to victims - distance to predators]
The smaller this value, the better the "wellbeing" of the token"""
victim_distance = distance_f... |
def token_vps(token_type, token_pos, board_state):
"""Function returns the number of a victims minus the number of predators the token has"""
victim_num = len(get_victims(token_type, board_state))
predator_num = len(get_predators(token_type, board_state))
return predator_num - victim_num
def token_valu... | The function evaluates a board state using multiple heuristics to determine a weighted score, prioritizing enemy defeat, comparing team sizes, assessing token vitality, and proximity to victims. It combines these factors with adjustable weights to guide strategic decisions in a game or simulation. | def eval_func(board_state, w): # sourcery no-metrics
eval = 0
h = h1 = h2 = h3 = h4 = h5 = h6 = h7 = h8 = 0
""" Heuristic to want all enemys defeated"""
if not board_state['s'] and not board_state['r'] and not board_state['p']:
h = -100
""" Heuristic Based on number of total teammates agai... |
def get_token_type(board_state, pos, player):
"""Function gets the token type in the position given"""
for key in board_state:
for tokenpos in board_state[key]:
if tokenpos == pos:
#Check if it is the player's token in case both upper and lower has a token in the grid
... | The function filters a list of moves to identify optimal ones for backward induction by evaluating slide moves based on proximity to victims/predators and throw moves using conditions like target presence, ally positions, and safety. It prioritizes moves that improve player position, reducing computational load by retu... | def filter_good_moves(original_list, board_state, player_type):
"""Function takes a list of moves and filter out the good ones for backward induction algorithm to reduce compute
time"""
if player_type == 'upper':
enemy_type = 'lower'
else:
enemy_type = 'upper'
good_moves = []
f... |
def get_player_moves(game_state, player_type, player_throws):
"""Function gets a list of move that the player with player_type can make"""
moves = []
#Throws
type = ['R','P','S']
temp_board = Board('upper')
throws = temp_board.throw_area(player_throws, player_type)
for throw_pos in throws:
... | The code generates a matrix of heuristic evaluations for all combinations of filtered "good" moves from upper and lower players in a game, using the original game state and predefined weights. It returns the evaluation matrix along with the filtered move lists to aid in selecting the optimal next move with a search dep... | def create_matrix(original_state, upper_throws, lower_throws):
"""Function uses game theory to return the best move to choose next, with the search depth of 1 only"""
#Initialize dummy variables to create new board states and calculate heuristics
empty_board = Board('upper')
dummy = pl.Player('upper')
... |
def upload(args):
s3_client = get_s3_client(args.endpoint_url)
prefix = args.prefix
if prefix and not prefix.endswith('/'):
prefix = f'{prefix}/'
s3_db_filepath = f'{prefix}{DATABASE_FILENAME}'
local_db_filepath = DATABASE_FILENAME
try:
s3_client.head_object(Bucket=args.bucket... | The main task of the code is to create a command-line tool for syncing files with an S3-compatible cloud bucket. It supports uploading/downloading files, debugging operations (e.g., integrity checks, file extraction), and managing local/cloud storage consistency. The script uses argparse to handle commands like 'upload... | def entry():
argparser = argparse.ArgumentParser(
description='Quickly send your files to cloud storage'
)
subparsers = argparser.add_subparsers(
title='command', dest='command', required=True
)
upload_cmd = subparsers.add_parser(
'upload',
help='Upload changed files... |
def set_chrome_option(self):
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) ' \
'Chrome/80.0.3987.132 Safari/537.36'
chrome_opt = webdriver.ChromeOptions()
chrome_opt.add_argument('--no-sandbox')
chrome_opt.add_argument(... | This code's main task is to crawl specified websites (e.g., 'https://www.rgmotorsinc.com/') using Selenium with proxy rotation to avoid detection. It extracts vehicle inventory URLs, handles pagination, processes iframe content, collects vehicle detail page links, and logs results. The goal is to systematically scrape ... | def crawl_func(self):
self.set_chrome_option()
self.not_crawlable_urls = ['https://www.rgmotorsinc.com/']
# columns = ['Type', 'Title', 'VIN', 'Price', 'Mileage', 'Year', 'Make', 'Model', 'Trim']
i = 1
len_not_crawlable_url = len(self.... |
def read_wout(self):
print("Reading boozer file from: ", self.__wout_path)
with netcdf_file(self.__wout_path, "r") as wfile:
for var in wfile.variables:
self._woutdata[var] = wfile.variables[var].data.copy()
def get_coefs(self):
self.n_s = len(self._woutdata["jlist"])... | This code initializes a class to process plasma data from a file, setting up theta and phi grids for coordinate transformations. It reads data, computes coefficients, and calculates Boozer coordinates for plasma analysis in fusion research. | def __init__(self, wout_path, n_th, n_ph):
self.__wout_path = wout_path
self._woutdata = {}
# if (not ispow2(n_th)) or (not ispow2(n_ph)):
# raise ValueError("n_th, n_ph must be powers of 2")
self.n_th = n_th
self.n_ph = n_ph
self.th = np.linspace(0, 2 * np.pi... |
def parse_args():
help_flag = False
profile = None
region = None
verbose = 1
color_flag = 0
argCount = len(sys.argv)
i = 1
while i < argCount:
a = sys.argv[i]
i = i + 1
if a == "--profile":
if i >= argCount:
raise Exception(f"Option par... | (The code retrieves AWS VPC and subnet information using boto3, optionally including NIC details based on verbosity. It processes these resources into structured segments, formats them into a table, and prints the output with optional color coding if the terminal supports it.) | def main():
profile, region, verbose, color_flag, help_flag = parse_args()
if help_flag:
print_help()
return
session = boto3.session.Session(profile_name = profile, region_name = region)
ec2_client = session.client("ec2")
vpcs = fetch_vpc_list(ec2_client)
subnets = fetch_subne... |
def get_unprocessed_granules(event):
all_granules = get_granules(event)
existing_products = database.get_products_for_event(event['event_id'])
processed_granule_names = [product['granules'][0]['granule_name'] for product in existing_products]
return [granule for granule in all_granules if granule['granu... | The code processes an event by retrieving unprocessed granules, submitting jobs for each granule to HyP3, and handling errors by logging exceptions and creating FAILED product records for problematic granules. | def handle_event(hyp3, event):
print(f'processing event: {event["event_id"]}')
granules = get_unprocessed_granules(event)
for granule in granules:
try:
submit_jobs_for_granule(hyp3, event['event_id'], granule)
except GranuleError as e:
print(e.__context__)
... |
def setCandidates(self,usr):
cand = []
for u in usr:
rec = usr[u]
for r in rec:
if r in cand:
continue
cand.append(r)
self.candidates = cand
return
def aggregateAvg(self):
scores = {}
i = 0
... | The code executes an action (0-5) to select an aggregation method, updates the environment state, generates top-10 recommendations, computes user satisfaction and reward, and checks if the episode terminates after 15 timesteps. It returns environment state, termination status, and reward. Your return | def execute(self,actions):
## Check the action is either 0 or 1 -- heater on or off.
#assert actions == 0 or actions == 1
## Increment timestamp
self.timestep += 1
## Update the current_temp
#self.current_temp = self.response(actions)
self.setCandidates(self.us... |
def get_working_collection():
with open('mongo_db.json') as data_file:
data_item = json.load(data_file)
client = MongoClient(data_item["mongo_url"])
test_database = client.get_database(data_item["mongo_database"])
working_collection = test_database.get_collection(data_item["mongo_collection"])
... | The code crawls Reddit subreddits via an API, processes their data, and updates a database with new/updated subreddits. It iterates up to `pages_limit` times, logs errors, and separates subreddits into 'create' and 'update' actions based on existing records in the database. | def crawl_api_endpoint(pages_limit=2):
reddit_api = RedditApi()
pages_limit = pages_limit
last_subreddit_name = None
logging.basicConfig()
logger = logging.getLogger('database')
logger.setLevel(logging.NOTSET)
logger2 = logging.getLogger('crawler')
logger2.setLevel(logging.NOTSET)
w... |
def calculate_mistake_prob(self, word):
"""
Returns the noisy chanel probability of thr word
Args:
word (str): word to find noisy chanel probability
Returns:
(double): noisy chanel probability
"""
candidates_mistake_probs = [] # Tuples of (can... | The function corrects a word using a simple noisy channel model by calculating the probability of each possible correction (candidate) based on mistake probabilities and prior probabilities, then returning the candidate with the highest combined probability along with its value. | def simple_noisy_chanel(self, word):
"""
Returns the correction of the word if simple noisy chanel applied
Args:
word (str): word to fix
Returns:
(tuple): fixed word, probability
"""
candidates_mistake_probs = self.calculate_mistake_prob(word)
... |
def get_all_grams_contains_the_word(self, str_parts, word):
"""
Returns all grams containing the word
Args:
str_parts (list): the sentences seperated to tokens
word (str): the word to find grams with
Returns:
(list): list of grams
"""
... | This function corrects a word in a sentence using a context-based noisy channel model. It identifies n-grams containing the word, calculates error probabilities for candidate corrections, and computes their likelihoods by evaluating context probabilities. The correction with the highest combined probability (error prob... | def context_noisy_chanel(self,str_parts ,word):
"""
Returns the correction of the word if context noisy chanel applied
Args:
str_parts (list): the sentence seperated to tokens
word (str): word to fix
Returns:
(tuple): fixed word, probability
... |
def simple_noisy_chanel(self, word):
"""
Returns the correction of the word if simple noisy chanel applied
Args:
word (str): word to fix
Returns:
(tuple): fixed word, probability
"""
candidates_mistake_probs = self.calculate_mistake_prob(word)
... | This function applies a noisy channel model to correct words in a tokenized sentence. It compares each word's prior probability with a corrected candidate, selecting the higher-probability option based on alpha. It filters out unchanged candidates and returns the most probable corrected word along with the original wor... | def simple_real_words_noisy_chanel(self, str_parts, alpha):
"""
Returns the correction of the word if simple real words noisy chanel applied
Args:
str_parts (list): the sentence sapareted to tokens
alpha (double): probability for the word not to be a wrong word
Re... |
def context_noisy_chanel(self,str_parts ,word):
"""
Returns the correction of the word if context noisy chanel applied
Args:
str_parts (list): the sentence seperated to tokens
word (str): word to fix
Returns:
(tuple): fixed word, probability
... | The function applies a noisy channel model with context to correct words in a tokenized sentence. It calculates probabilities using n-grams and an alpha parameter, comparing them to candidate corrections. It filters valid candidates where the corrected word differs from the original, then returns the highest-probabilit... | def context_real_words_noisy_chanel(self, str_parts, alpha):
"""
Returns the correction of the word if context real words noisy chanel applied
Args:
str_parts (list): the sentence sapareted to tokens
alpha (double): probability for the word not to be a wrong word
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.