dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def gen_prompt(form):
text_prompt = form["text_prompt"]
song_title = form["song_title"]
genres = form["genres"]
lang = form["lang"]
lyrics = form["lyrics"]
prompt = f"Title: {song_title}\nLanguage: {lang}\nGenres: {genres}\nIdea: {text_prompt}\n\nLyrics:\n{lyrics}"
return prompt
def generate... | The code handles song creation via a web form. On POST requests, it generates a song using a text prompt from the form, downloads the generated song, and redirects to the index page. If not a POST request, it renders the 'create_song.html' template for user input. | def create_song():
if request.method == "POST":
text_prompt = gen_prompt(request.form)
song_url, song_info = generate_song(text_prompt)
if song_url:
download_song(song_url, song_info)
return redirect(url_for("index"))
return render_template("create_song.html") |
def update_queue(queue):
songlist = get_songs_list()
new = set(songlist).difference(set(queue))
rem = set(queue).difference(set(songlist))
for r in rem: queue.remove(r)
return list(new), queue
def log_queue(queue, curr=None):
with open(TRACKQUEUE, "w") as fil:
fil.write(str(datetime.now(... | This function processes a song queue by prioritizing and playing tracks sequentially. It updates the queue dynamically, announces the next song using a TTS speaker, handles playback with error recovery, and manages interruptions. The loop continues until the queue is exhausted, returning -1 if empty, or exiting when al... | def playQueue(queue, speaker=None):
k = 0
while True:
priority, queue = update_queue(queue)
# Add new songs to queue with priority
if len(priority)>0:
queue = queue[:k]+priority+queue[k:]
log_queue(queue, curr=k)
if len(queue) == 0:
print("Queue ... |
def make_model_path(model_name):
'''
Creates the model folder for the specified model name
params:
model_name: str
The name of the model to get the path for
return:
str
The path to the model folder
'''
path = get_model_path(model_name)
i... | The main task of the code is to train a Variational Autoencoder (VAE) on a given dataset using customizable hyperparameters, including activation functions, hidden/latent layer sizes, loss terms (MSE and KLD), and training settings (epochs, batch size, learning rate). It handles model loading/saving, validation, loggin... | def train_net(net_name, dataset, **kwargs):
'''
The network training loop
params:
net_name: str
The name of the network to train
dataset: PatientDataSet
The dataset to train on
**kwargs:
activations: tuple (default = ('tanh', 'selu', 'tanh', 'tan... |
def run_test_mode(self):
config.run_mode = 'test'
for test_episode in range(config.number_of_episode_per_intermediate_test):
self.play_tic_tac_toe(test_episode, "both_greedy")
self.play_tic_tac_toe(test_episode, "first_player_random")
self.play_tic_tac_toe(test_episod... | The code trains a model over a specified number of episodes, alternating between training and intermediate testing phases. It logs results after each episode and saves the final trained models. | def start(self):
for train_episode in range(1, config.total_train_episode + 1):
if train_episode % config.intermediate_test_frequency == 0:
self.run_test_mode()
else:
self.run_train_mode(train_episode)
self.log_outputs(train_episode)
... |
def find_arrow(self, frame):
"""
Find the position of the arrow, knowing that it is red
"""
mask = cv2.inRange(frame, np.array([0, 0, 100]), np.array([100, 100, 255]))
opening = cv2.morphologyEx(
mask, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5... | The code processes video frames sequentially to analyze object and arrow positions, computes their movement, updates an equation, and writes the results to an output video, concluding with solving the equation and displaying the final frame. | def process(self):
"""
Process frames one by one to analyze
"""
if self.cap is None or self.out is None:
raise NameError('Use this function inside a with statement.')
current_frame = 0
while self.cap.isOpened():
# Capture frame by frame
... |
def login_user(login, email, password, scopes=DEFAULT_SCOPES):
secret_file = 'masto_bot/{0}.secret'.format(login)
mastodon = create_app(login, secret_file, scopes)
mastodon.log_in(
username=login,
password=password,
to_file=secret_file,
scopes=scopes
)
return mastodon
def reset_toots(mastodon... | The code initializes or resets Mastodon user accounts based on YAML configurations. It reads settings from `mastobotconfig` and `bootstrapconfig`, sets up API endpoints, and creates a directory. It logs in an admin user, checks existing users, and processes each configured user to either log in (if existing) or registe... | def main(mastobotconfig, bootstrapconfig, reset):
global API_URL, MEDIAPATH
with open(mastobotconfig) as f:
mastobotconfig_dict = yaml.safe_load(f)
MEDIAPATH = mastobotconfig_dict.get('mediapath', MEDIAPATH)
API_URL = "https://{0}".format(mastobotconfig_dict['server_name'])
with open(bootstrapconfig) a... |
def fetch_content(url):
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 12.0; rv:94.0) Gecko/20100101 Firefox/94.0"
}
try:
r = requests.get(url, headers=headers, timeout=3)
except Exception as e:
print(f"URL FAILURE: {url}")
return None
return r.text... | The main task of the code is to retrieve and extract structured metadata and boiled-down text content from a given website URL. It fetches webpage HTML, checks for errors, extracts metadata, processes the HTML to extract key text, and returns both results as a tuple. | def get_text_from_website(url):
html_doc = fetch_content(url)
if html_doc == None:
return "", ""
meta = meta_from_website(html_doc, url)
boiled_content = boil_html(html_doc)
return meta, boiled_content |
def firstContext():
return 0
def init():
global test
test = False
def control_code(terminate, ic, cx):
if terminate:
return True, ic
else:
r = randint(0, 1)
if r == 1:
terminate, ic = contextSwitch(ic, cx)
if terminate is True:
return True, ic... | The main task of the code is to generate a sequence of bit permutations by iteratively applying random transformations to a set of boolean variables (x1-x4), controlled by a `control_code` function. The process runs for `k+1` iterations (default k=2), starting with an initial context, and outputs the resulting permutat... | def main(k=2):
cx, n, temp = 0, k, 0
g_ic, output = list(), list()
while cx <= k:
if 0 <= cx <= n:
ic = firstContext()
if ic == 0:
init()
terminate = False
if cx == 0:
x1, x2, x3, x4 = False, False, False, False
... |
def firstContext(t, tk_list):
if t in tk_list and t == 1:
return 0
else:
return 1
def init():
global test
test = False
def control_code(terminate, cx, k, t, tk_list, temp):
if terminate:
return True, temp
else:
r = randint(0, 1)
if r == 1:
term... | The main task of the code is to generate bit permutations using a context-based control mechanism. It iterates through a range, applies random bit permutations based on a threshold value $ k $, and collects the results in an output list. The process checks termination conditions, modifies bit sequences through swaps, a... | def main(k=2):
goal, terminate = False, False
n = 3
tk_list = [1, 2]
g_cx, output = list(), list()
temp = 0
for i in range(1, n):
t = i
if 0 < t <= n:
cx = firstContext(t, tk_list)
if cx <= k:
if cx == 0:
init()
... |
def Turn2String(self,State,count):
if count == 1:
s = ''
for i in State:
for j in i:
s += str(j)
return s
if count == 2:
s = ''
for i in State:
for j in i:
s += str(j) + " "
return s
def Check_GoalState(self,Current_Node):
Path = []
temp = 0
if self.Turn2String(C... | This code performs Breadth-First Search (BFS) to solve a 8-puzzle problem. It takes a 3x3 input matrix, initializes a queue with the starting state, and iteratively explores all possible moves by generating new puzzle states. It checks if the current state matches the goal, tracks computational time, and outputs succes... | def bfs(self):
print('Enter the Input Matrix (Values from 0-8)')
Input_Value = np.array([[int(j) for j in input().split()] for i in range(3)])
global ID
global Nodes
Initial_Time = time.time()
Node_Stack = collections.deque()
Initial_Node = Puzzle(Input_Value,ID,0)
Node_Stack.append(Initial_Node)
Tag... |
def isvalid(Cordinates,p):
Z1 = p[0].contains_point(Cordinates)
Z2 = p[1].contains_point(Cordinates)
Z3 = p[2].contains_point(Cordinates)
Z4 = p[3].contains_point(Cordinates)
Z5 = p[4].contains_point(Cordinates)
Z6 = p[5].contains_point(Cordinates)
Z7 = p[6].contains_point(Cordinates)
Z... | The code implements the A* algorithm to find a collision-free path from a start point to a goal point in a 2D workspace, considering obstacles. It validates input points, uses heuristics for pathfinding, explores nodes, and updates the optimal path. Once a path is found, it visualizes the trajectory, calculates motor v... | def Astar_algo(StartPoints, GoalPoints, p):
start_time = time.time()
plt.plot(StartPoints[0], StartPoints[1], 'rx')
plt.plot(GoalPoints[0], GoalPoints[1], 'rx')
Check1 = isvalid(StartPoints,p)
Check2 = isvalid(GoalPoints,p)
if Check1 == True or Check2 == True or StartPoints[0] > 1110 or Start... |
def check_rect(self, point):
if (point[0] >= self.rect[0][0]) & (point[0] <= self.rect[1][0]) & (point[1] >= self.rect[0][1]) & (point[1] <= self.rect[1][1]) :
return True
else:
return False
def ObstacleCircle(self, point):
if math.sqrt((point[0] - ((self.cir[0] + self.ci... | The code checks if a given point lies within any obstacle (rectangles or circles) by evaluating multiple collision detection methods. It returns `True` if the point is inside any obstacle, otherwise `False`, serving as a collision check in path planning or robotics navigation systems. | def space_obs(self, point):
#checking the point if it's in the obstacle
if self.check_rect(point) or self.ObstacleCircle(point) or self.ObstacleCirclec2(point) or self.ObstacleCirclec3(point) or self.check_rect2(point) or self.check_rect3(point) or self.check_rect4(point) or self.check_rect5(point) or s... |
def newnode(self, check):
PointList = []
#print check
if (check[1] - 1 >= 0):
PointList.append((check[0], check[1] - 1))
if (check[1] + 1 < 250):
PointList.append((check[0], check[1] + 1))
if (check[0] - 1 >= 0):
PointList.append((check[0] - 1,... | This code implements a Breadth-First Search (BFS) algorithm to find a path from a starting point to an endpoint in a grid, avoiding obstacles. It uses a queue to explore valid neighboring nodes, marks visited nodes, and visualizes the search process with Pygame by drawing paths. The algorithm tracks node information an... | def imp_bfs(self, point, epoint):
start_time = time.time()
self.sp = point
closed_point = []
queue = []
self.node_info = {}
current_point = point
while(current_point != epoint):
newnode = self.newnode(current_point)
node_valid = [c for c in... |
def purge_processing_queue(self):
"""Move all items from the processing queue to the work queue"""
queue_has_items = True
while queue_has_items:
key = self.redis.rpoplpush(self.processing_queue, self.queue)
queue_has_items = key is not None
if queue_has_items:... | (The code processes Redis keys from a queue by retrieving a hash, attempting to consume it, handling errors, and updating queue states. If processing succeeds, it logs the time and removes the key; if not, it retries after a delay. The function also manages empty queues by waiting before retrying.) | def consume(self):
"""Find a redis key and process it"""
start = timeit.default_timer()
# Purge the processing queue in case of stranded keys
self.purge_processing_queue()
redis_hash = self.get_redis_hash()
if redis_hash is not None: # popped something off the queue
... |
def x_axis_value():
global xval
temp = varx.get()
options = ["Pitch","Yaw","Cpy", "Cpp", "Cpt","Cps","Cpts"]
xval = options.index(temp)
return xval
def y_axis_value():
global yval
temp = vary.get()
options = ["Pitch","Yaw","Cpy", "Cpp", "Cpt","Cps","Cpts"]
yval = options.index(temp)
... | The code processes input data to generate a plot by retrieving x and y axis values and passing them to a plotting function. | def execute(data):
x = x_axis_value()
y = y_axis_value()
plotdata(data,x,y) |
def get_quat(self):
with self.model.model_lock:
quat=copy.deepcopy(self.model.quat)
pass
return quat
def vec_apply_rot(rot,vec):
# Apply rotation by conjugation operation p'=qpq^-1
rotnorm = rot/np.linalg.norm(rot)
vecquat = np.array((0.0,vec[0],vec[1],vec[2]),dtype=... | This code creates a GUI with matplotlib to visualize 3D orientation vectors and interactive sliders for adjusting rotation/forward commands. It sets up subplots for different coordinate planes, initializes sliders for control inputs, and uses a timer for continuous updates. The main task is to provide real-time orienta... | def interactor(self):
# This MUST be called from the main thread because the main thread is the ONLY one allowed to do GUI/matplotlib stuff!
try:
orientation = self.get_quat()
# Frontward direction is y
self.world_vec_frontward=vec_apply_rot(orientation,np.array((0... |
def save_image_batch_to_disk(tensor, output_dir, file_names, img_shape=None,arg=None):
os.makedirs(output_dir,exist_ok=True)
if not arg.is_testing:
assert len(tensor.shape) == 4, tensor.shape
for tensor_image, file_name in zip(tensor, file_names):
image_vis = tgm.utils.tensor_to_ima... | The code defines a main function for training and testing a neural network model (likely for image segmentation or edge detection). It sets up training parameters, loads datasets, initializes the model (DexiNet), handles GPU/CPU device allocation, and performs training with Adam optimizer. It also includes testing func... | def main():
# Testing settings
DATASET_NAME= ['BIPED','BSDS','BSDS300','CID','DCD','MULTICUE',
'PASCAL','NYUD','CLASSIC'] # 8
TEST_DATA = DATASET_NAME[8]
data_inf = dataset_info(TEST_DATA)
# training settings
parser = argparse.ArgumentParser(description='Training application.... |
def get_hash_from_python() -> str:
return get_hash(get_python())
def save_hash_if_not_exists(hash: Optional[str] = None) -> str:
if hash is None:
hash = get_hash_from_python()
if not is_hash_in_table(hash):
python = get_python()
insert_row({"hash": hash, "python": python}, TABLE)
... | The code generates a short shareable URL and HTML embed code using a user-provided or automatically generated hash. It captures input, validates the hash, stores it if new, retrieves the short URL and embed code, then displays the URL and expands to show the embed code. | def get_short_url_button():
custom_hash = st.text_input("Custom Hash").strip()
if st.button("Get shareable url"):
if custom_hash:
hash = custom_hash
else:
hash = get_hash_from_python()
save_hash_if_not_exists(hash)
url = get_short_url_from_hash(hash)
... |
def rank(self):
if self.check_RF():
return 9
elif self.check_SF():
return 8
elif self.check_four():
return 7
elif self.check_FH():
return 6
elif self.check_flush():
return 5
elif self.check_S():
retur... | This function compares two poker hands to determine which is stronger. It first checks their ranks, returning -1/1 based on rank hierarchy. For tied ranks, it compares specific card values (e.g., 5th card for rank 8/4, pairs for rank 2/1) and uses `check_highest_card` as a tiebreaker. Returns 0 for ties, with logic var... | def compare_hand(self, hand):
if hand.rank() > self.rank():
return -1
elif hand.rank() < self.rank():
return 1
elif hand.rank() == self.rank():
if self.rank() == 8 or self.rank() == 4:
if hand.delt_cards[4].value > self.delt_cards[4].value:
... |
def scatmatr(structure,lam,NSinFi,pol):
#treat the multilayer as coherent and calculates the scattering matrix, T and R
#calculates interfaces matrices
intmatrix=[]
for i in range(len(structure)-1):
N1=structure[i][1]
N2=structure[i+1][1]
rough=structure[i+1][3]
CosFi1=CosFi(... | The code calculates modified scattering matrices for a mixed coherent/incoherent multilayer structure by dividing it into coherent segments and incoherent layers. It processes each coherent block using `scatmatr` and `modmatr`, appends incoherent layer matrices with phase shifts, and returns a list of combined scatteri... | def incohescatmatr(structure,lam,NSinFi,pol):
#for a mixed coherent/incoherent multilayer calculates the modified scattering matrices
#the original multilayer is divided in coherent layers/incoherent layer/coherent layers ....
#example: c is for coeherent, i for incoherent, / is the interface
#original multilayer /1c/2... |
def incohescatmatr(structure,lam,NSinFi,pol):
#for a mixed coherent/incoherent multilayer calculates the modified scattering matrices
#the original multilayer is divided in coherent layers/incoherent layer/coherent layers ....
#example: c is for coeherent, i for incoherent, / is the interface
#original multilayer /1c/2... | The code calculates the modified scattering matrix (S), transmission (T), and reflection (R) coefficients for a multilayer structure, combining coherent and incoherent effects. It computes the matrix product of individual layer matrices in reverse order, derives T and R from S, and adjusts T using refractive indices an... | def globscatmatr(structure,lam,NSinFi,pol):
#for a mixed coherent/incoherent multilayer return the modified scattering matrix, T and R
GS=incohescatmatr(structure,lam,NSinFi,pol)
#calculates the matrix list product
S=np.identity(2)
for i in range(len(GS)-1,-1,-1):
S=MATRIXMULT(GS[i],S)
R=S[... |
def PhaseShift(d,N,NSinFi,lam):#compute phase shift
beta = 2*np.pi*d*N*CosFi(NSinFi,N)/lam
test = beta.imag < -50#avoid overflow
b=test*beta.imag
beta=beta-b*(1j)-(50j)*test
test = beta.imag > 50#avoid overflow
b=test*beta.imag
beta=beta-b*(1j)+(50j)*test
return beta
def CosFi(N1SinFi1,N... | The code computes the energy flux in a specific layer of a layered structure, considering both coherent and incoherent layers. It uses scattering matrices, phase shifts, and polarization effects to calculate flux contributions from left and right interfaces, returning the total energy flux at position x in layer j. | def EFLUX(structure, lam, NSinFi, j, x, pol):
#compute Energy Flux in layer j at relative position x (0<=x<=1)
N0=structure[0][1]
N=structure[j][1]
d=structure[j][0]
beta=PhaseShift(d,N,NSinFi,lam)*(1-x)
cosFi=CosFi(NSinFi,N)
cosFi0=CosFi(NSinFi,N0)
#compute T
S,T,R=globscatmatr(structur... |
def forwardStep(self):
self.params['Z1'] = (torch.matmul(self.params['W1'], self.params['Z0'].T) + self.params['B1'][:, None]).T
self.params['A1'] = self.sigmoid(self.params['Z1'])
self.params['Z2'] = (torch.matmul(self.params['A1'], self.params['W2'].T).T + self.params['B2'][:, None]).T
... | The code trains a neural network over multiple epochs using mini-batch gradient descent. It normalizes input images, computes forward passes, calculates mean squared error loss between predicted and target outputs, performs backpropagation, updates model parameters via an optimizer, and tracks training accuracy per epo... | def trainNetwork(self):
for epoch in range(self.epochs):
for idx, (image, label) in self.trainSet:
print('Epoch', epoch + 1, ': Batch', idx + 1, ',', round(idx / (60000/self.batchSize) * 100, 2), '% done', end='\r')
self.params['Z0'] = image.resize(sel... |
def forwardStep(self):
self.params['Z1'] = np.dot(self.params['W1'], self.params['Z0'].T).T + self.params['B1']
self.params['A1'] = self.sigmoid(self.params['Z1'])
self.params['Z2'] = (np.dot(self.params['A1'], self.params['W2'].T) + self.params['B2']).T
self.params['A2'] = self.sigmoid(... | This code trains a neural network by iterating over epochs, shuffling training data, normalizing inputs, performing forward and backward propagation for each batch, updating parameters, and computing accuracy after each epoch. | def trainNetwork(self):
for epoch in range(self.epochs):
shuffle = np.random.permutation(len(self.trainSet))
self.trainSet = self.trainSet[shuffle]
self.trainLabels = self.trainLabels[shuffle]
for sample, label, index in zip(self.trainSet, self.trainLabels, range... |
def login(self):
try:
is_authenticated = self.api.is_authenticated()
if is_authenticated:
LOG.info("Already authenticated")
return True
if self.api.login_with_cookie():
LOG.info("Logged in with cookies.")
return ... | This method routes requests based on the 'action' parameter in self.params. It first checks login status, then processes actions like listing pages, structure, seasons, videos, or searches by calling corresponding methods. If no params exist, it defaults to listing pages. Invalid actions raise errors. | def route(self):
if not self.login():
return
if self.params:
action = self.params["action"]
param = self.params.get("param", None)
if action == self.ACTION_PAGE:
self.list_page_content(param)
elif action == self.ACTION_STRUCTU... |
def _get_xml_root(xml_file):
"""
Get the root of the XML tree.
:param xml_file: The name of the XML file.
:return: The root of the XML tree.
"""
try:
tree = eT.parse(xml_file)
return tree.getroot()
except FileNotFoundError:
return _create_xml_root(xml_file)
def _crea... | The code saves a book's data into an XML file by appending a new `<book>` element with an incremented position value. It retrieves the XML root, calculates the next available position, updates the book's position, creates a book element, adds it to the root, and saves the updated XML structure. | def save_book_to_xml(book: Book, xml_file):
"""
Save a book to an XML file.
:param book: Dictionary containing book information.
:param xml_file: The name of the XML file.
"""
root = _get_xml_root(xml_file)
pos = len(root.findall(ELEMENT_NAME)) + 1 # increase the pos
book.set_pos(pos)
... |
def _get_xml_root(xml_file):
"""
Get the root of the XML tree.
:param xml_file: The name of the XML file.
:return: The root of the XML tree.
"""
try:
tree = eT.parse(xml_file)
return tree.getroot()
except FileNotFoundError:
return _create_xml_root(xml_file)
def _crea... | The main task of the code is to reset an XML file by replacing its content with a new list of books. It clears the existing XML structure, assigns each book a sequential position, creates corresponding XML elements, and saves the updated XML tree. This function ensures the XML file accurately reflects the provided book... | def set_list_to_xml(book_list, xml_file):
"""
Resets the XML file based on the provided book list.
:param book_list: The list of books.
:param xml_file: The name of the XML file.
"""
root = _get_xml_root(xml_file)
root.clear()
for index, book in enumerate(book_list):
book.set_po... |
def clear(fast=False, lol=False):
os.system("cls" if os.name == "nt" else "clear")
if fast:
display_ansi_art(random_ans_file)
print(introduction)
else:
display_ansi_art(random_ans_file)
sprint(introduction, 0.005)
def pexit():
sprint(f"\n{red} May t... | The code provides a menu-driven interface for selecting injection methods (Thread/Process or Callback), loading corresponding modules, modifying module files with user-provided URLs or shellcode paths, and compiling the modified modules into Windows executables using Go. It handles argument parsing, module selection, f... | def main():
parser = ArgumentParser()
parser.add_argument("-o", "--option", help="Sephiros [Default : null]")
args = parser.parse_args()
option = args.option
clear(lol=True)
while True:
print(f"\n{info}1-Thread/Process Injection ")
prin... |
def forward(self):
"""Run forward pass; called by both functions <optimize_parameters> and <test>."""
self.fake_B = self.netG(self.real_A)
def backward_D(self):
"""Calculate GAN loss for the discriminator"""
# Fake; stop backprop to the generator by detaching fake_B
fake_B = self... | This function optimizes parameters of a GAN's generator (G) and discriminator (D). It first computes fake images via G, updates D by calculating gradients from real/fake data, then freezes D's gradients to optimize G. The process involves zeroing optimizers, backpropagating losses, and updating weights, ensuring D is i... | def optimize_parameters(self):
self.forward() # compute fake images: G(A)
# update D
# self.netD.train()
self.set_requires_grad(self.netD, True) # enable backprop for D
self.optimizer_D.zero_grad() # set D's gradients to zero
self.backward_D() ... |
def _swap(self,i,inx):
self._data[i], self._data[inx] = self._data[inx],self._data[i]# swap the values
# swap the indices
self._data[i]._index = i
self._dict[self._data[i]._value] = self._data[i]._index
self._data[inx]._index = inx
self._dict[self._data[inx]._value] = sel... | This method removes an element at a specified index from a heap, validating the index first. If the index is the last element, it directly removes it. Otherwise, it swaps the element with the last one, removes the last element, and adjusts the heap via _upheap or _downheap to maintain heap properties. | def remove(self,inx): # removing any index from the heap
if not (0 <= inx < len(self) ):
raise ValueError( "Invalid locator" )# key value does not exists
if inx == len(self) - 1: # if last index is to be pop out then remove its index and value form the heap
self._dict.pop(self.... |
def IP1(self, message):
permutedMessage = ''
P_i = [58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19,... | The code's main task is to encrypt and decrypt plaintext using a key matrix through multiple iterations. It applies permutations (IP1, inversePermutation), rounds with keys, and swapping. The encryption process repeats rounds with keyMatrix elements, while decryption reverses the key order. The method prints both ciphe... | def encrypt(self, plainText, keyInput, iterations):
self.plainText = plainText
keys = key()
keyMatrix = keys.generatekeys(keyInput)
for j in range(iterations):
self.plainText = self.IP1(self.plainText)
for i in range(len(keyMatrix)):
self.plainText... |
def _setup_train(self):
self.epochs = 5
self.lr = 0.001
params = list(self.textclassTask.parameters())
self.optimizer = torch.optim.Adam(params, lr=self.lr)
self.loss = nn.CrossEntropyLoss()
def _getdata(self, op="train"):
if op == "train":
self.train_iter = s... | The main task of the code is to train a multi-task model (encoder, position task, dependency parsing task, and text classification task) using a training dataset, evaluate it on a validation set during training, and save the best model based on validation accuracy. It resumes training from a checkpoint if available, pe... | def train(self):
self._setup_train()
self._getdata("train")
iter2, best_valid_acc = self._load_model("train")
print("train batch len = {} | valid batch len = {}".format(len(self.train_iter), len(self.valid_iter)))
if best_valid_acc == -1:
iter2, best_valid_acc = 0, 0... |
def _setup_train(self):
self.epochs = 5
self.lr = 0.001
params = list(self.encoder.parameters()) + list(self.posTask.parameters())
self.optimizer = torch.optim.Adam(params, lr=self.lr)
self.loss = nn.NLLLoss()
def _getdata(self, op="train"):
if op == "train":
... | The code trains a model with an encoder and position task, iterating over training data in batches. It tracks training accuracy, validates periodically, and saves the best model based on validation accuracy. The loop runs for a specified number of epochs, updating model parameters via backpropagation and optimizing wit... | def train(self):
self._setup_train()
self._getdata("train")
iter, best_valid_acc = self._load_Model("train")
print("train batch = {} | valid batch len = {}".format(len(self.train_iter), len(self.valid_iter)))
for epoch in range(iter, self.epochs):
train_acc = 0.
... |
def scale_train(self, df_train):
nsamples, ntimesteps, nfeatures = df_train.shape
# reshape to use sklearn scaler
df_train_rs = df_train.copy().reshape((nsamples, ntimesteps * nfeatures))
# fit scaler
scaler = MinMaxScaler(feature_range=(-1, 1))
self.sca... | The main task of the code is to train an LSTM model multiple times (self.n_repeat) on scaled time-series data, evaluate its performance using RMSE metrics for each training epoch, and collect historical results. It splits input-output pairs (X, y), trains the model iteratively with reset states, and compares prediction... | def train_lstm(self, train_data, train_data_raw):
train = self.scale_train(train_data)
train_raw = train_data_raw.copy()
assert (train.shape == train_raw.shape)
X, y = train[:, :(self.n_in), :], train[:, (self.n_in):, :]
hist = []
for j in range(self.n_repeat):
... |
def scale_train(self, df_train):
nsamples, ntimesteps, nfeatures = df_train.shape
# reshape to use sklearn scaler
df_train_rs = df_train.copy().reshape((nsamples, ntimesteps * nfeatures))
# fit scaler
scaler = MinMaxScaler(feature_range=(-1, 1))
self.sca... | This code trains and validates an LSTM model multiple times (n_repeat) using scaled training data and separate validation data. It iteratively builds the model, trains it for n_epoch epochs, evaluates performance on both training and validation sets using RMSE, and retains the model with the lowest validation RMSE. The... | def train_and_validate_lstm(self, train, train_raw,
valid, valid_raw):
train = self.scale_train(train)
train_raw = train_raw.copy()
X, y = train[:, :(self.n_in), :], train[:, (self.n_in):, :]
# Training and evaluating
hist =... |
def split_data_into_sets(images_count, class_count):
if not tf.gfile.Exists(DIRECTORY_IMAGES):
print("Cannot find image directory named: " + DIRECTORY_IMAGES)
return None
sets = {}
directories = [x[0] for x in tf.gfile.Walk(DIRECTORY_IMAGES)]
is_root_dir = True
for directory in direc... | The main task of the code is to train a neural network model using precomputed bottleneck features from images, splitting data into training, validation, and testing sets. It builds a final classification layer, trains the model with periodic validation, evaluates test accuracy, and saves the trained graph and labels. ... | def run_model(images_count, class_count, graph, bottleneck_tensor, image_data_tensor, resized_image_tensor):
#Split the images to training, testing and validation sets
data_sets = split_data_into_sets(images_count, class_count)
sess = tf.Session()
store_bottleneck_values(sess, data_sets, image_data_te... |
def is_nga_file_update_needed(self):
git_date = self.get_nga_latest_remote_git_update_date()
local_file_path = Constants.NGA_ZIP_FILE_PATH
if local_file_path.exists():
creation_date, altered_date = get_file_creation_date(str(local_file_path))
if git_date > creation_date... | The main task of the code is to check if the NGA ZIP file exists, prompt the user to replace it if needed, download the ZIP file if missing or updated, and then extract it to create/replace the database. It ensures the latest data is obtained and processed, handling both update and initial download scenarios with user ... | def download_zip_if_needed(self):
if Constants.NGA_ZIP_FILE_PATH.exists():
self.is_nga_file_update_needed()
if input("Remove and replace the existing file? yes/no ").lower() == "yes":
if Constants.NGA_ZIP_FILE_PATH.exists():
Constants.NGA_ZIP_FILE_PATH... |
def render(self):
#to render a single frame
self.raisim_dll._render()
'''
r(t) = w_base_pos * r_base_pos(t) +
w_base_lin_vel * r_base_lin_vel(t) +
w_end_eff_co * r_end_eff_co(t) +
w_base_rpy *r_base_rpy(t) +
w_base_angulat_vel * r_base_angulat_vel
... | The code resets the robot's position to a default stance, initializes the step counter, and applies a predefined set of joint angles (nominal_stance_action) to generate the initial state. It also triggers rendering if enabled and interacts with a DLL for simulation reset. | def reset(self):
#b_h - the bot will be rest at 0,0,b_h with the default stance joint angles
b_h = self.c_Float_3()
for i in range(3):
b_h[i] = self.base_init_pos[i]
print('reset')
#reset ithstep
self.ith_step = -1
self.raisim_dll._rst(b_h)
#display the reset if required
... |
def kernel9(img, x, y):
return([(kx,ky) for (kx,ky) in [
((x-1),(y-1)),(x,(y-1)),((x+1),(y-1)),
((x-1),y),(x,y),((x+1),y),
((x-1),(y+1)),(x,(y+1)),((x+1),(y+1))
] if((kx in range(img.width)) and (ky in range(img.height)))])
def kernel21(img, x, y):
return([(kx,ky) for... | The function generates a pixel value by applying a specified kernel (k9, k21, k35) to the image at coordinates (x,y), then passes the result along with environment parameters (env), and other variables (m, s) to a `generateValue` function to compute the final pixel value. | def generatePixel(img, env, x, y, k, m, s):
if(k == "k9"): adjacent = kernel9(img, x, y)
elif(k == "k21"): adjacent = kernel21(img, x, y)
elif(k == "k35"): adjacent = kernel35(img, x, y)
else: adjacent = kernel9(img, x, y)
return(generateValue(img, env, adjacent, m, s)) |
def select_dict_field(item):
selection = show_and_select(item)
for count, field in enumerate(item):
if count == selection:
return field, item[field]
def edit_field(field):
new_value = ""
if isinstance(field[1], str):
new_value = input('Enter A New Value For "{}"\n'.format(fie... | The main task of the code is to modify a specific field in a selected dictionary item within a list of items. It selects a field from the item, edits it, updates the item with the edited field, and replaces the original item in the list with the modified version, finally returning the updated list of items. | def modify_selected_item(items, selected_item):
print(selected_item)
selected_field = select_dict_field(selected_item)
print(selected_field)
edited_field = edit_field(selected_field)
edited_item = save_field_to_item(edited_field, selected_item)
items = save_item_to_items(edited_item, items)
... |
def show_and_select(items):
for count, item in enumerate(items):
print("[{}] {}".format(count + 1, show_entry(item)))
selection = int(custom_input("Input Int To Select\n", len(items)))
if isinstance(items, list):
return items[selection - 1]
else:
return selection - 1
def modify_s... | The main task of the code is to recursively allow user interaction for modifying nested items. It repeatedly lets the user select an item, either modifying it directly or diving into its content if it exists. The process continues until the user confirms they are done, after which the updated items are returned. | def interact_modify(items):
done = False
while not done:
selected_item = show_and_select(items)
if 'content' in selected_item:
interact_modify(selected_item['content'])
else:
items = modify_selected_item(items, selected_item)
done = not show_confirm_done()... |
def interact_modify(items):
done = False
while not done:
selected_item = show_and_select(items)
if 'content' in selected_item:
interact_modify(selected_item['content'])
else:
items = modify_selected_item(items, selected_item)
done = not show_confirm_done()... | The main task of the code is to process a dataset by modifying items, balancing them based on specified keys (default: 'chance'), ungrouping the items, and saving the final processed data to a file. | def interact_main(filename, items, keys=['chance']):
items = interact_modify(items)
items = interact_balance(items, keys=keys)
grouper.ungroup(items)
interact_save(items, filename) |
def _acc(self, dt):
new = self.acc_fun(dt)
if self.cruise_control_on and new > self.target_velocity and not self.v_input_received:
self._velocity = self.target_velocity
else:
self._velocity = min(float(self.top_speed), new)
def _dec(self, dt):
delta = dt * max(se... | The code calculates velocity by deciding between acceleration, deceleration, or braking based on conditions. If acceleration is needed, it calls `_acc(dt)`; otherwise, it decelerates via `_dec(dt)` and applies braking via `_brake(dt)` if cruise control is active and braking is required. | def calc_velocity(self, dt):
if self.is_acc or self.should_acc:
self._acc(dt)
else:
self._dec(dt)
if self.cruise_control_on and self.should_brake:
self._brake(dt) |
def rotate(self, dt, v):
self._rotation += v * dt * (self._velocity / self.top_speed * 5)
self.bound_rotation()
self.image = pygame.transform.rotate(self.orig_image, 360.0 - self._rotation)
self.rect = self.image.get_rect()
self.update_rect()
def calc_velocity(self, dt):
... | The code updates the object's state by processing a time step `dt`, including updating the front wheel and sensor, rotating based on wheel rotation, calculating velocity, resetting acceleration/input flags, and executing movement. | def update(self, dt):
self.front_wheel.update(dt)
self.sensor.update(dt)
self.rotate(dt, self.front_wheel.rotation)
self.calc_velocity(dt)
self.is_acc = False
self.v_input_received = False
self.move(dt) |
def new_incident(incident_type, user, passwd):
incident = {
"incident_type": incident_type,
"user": user,
"pass": passwd,
"scan_type": None,
"proto": None
}
return incident
def log_plaintext(packet, incident, user, p... | The function logs network incidents by recording details like source IP, user, and password. It checks if an incident exists for the IP; if not, it creates a new one. Depending on the incident type ("plaintext" or "scan"), it calls respective logging functions to handle the packet data, ensuring structured logging for ... | def log(packet, incident_type, user, passwd, scan_type):
ip = packet[IP].src
if ip not in incidents_log:
incidents_log[ip] = new_incident(incident_type, user, passwd)
incident = incidents_log[ip]
if incident_type == "plaintext":
log_plai... |
def parse_userpass(userpass):
userpass = userpass.group(1)
userpass = userpass.lstrip("Authorization: Basic ")
userpass = userpass.rstrip("\\r\\n")
userpass = base64.b64decode(userpass)
return str(userpass)
def get_http_user(userpass):
user_regex = re.compile(r"b'(.*?)\:"... | This function extracts HTTP Basic Authentication credentials from a network payload. It searches for 'Authorization: Basic' patterns, parses the encoded username/password, and logs them if found. The regex matches the Authorization header, decodes the credentials, and handles exceptions by printing errors. | def grab_pass_http(packet, payload):
try:
user = None
passwd = None
incident_type = "plaintext"
userpass = None
if "Authorization: Basic" in payload:
userpass_regex = re.compile(r'''(
... |
def get_min_point(self):
self.open_list = sorted(self.open_list, key=lambda point: point.cal_F())
return self.open_list[0]
def get_surround_points(self, point):
surround_points = []
x = point.X - 1
while x <= point.X + 1:
z = point.Z - 1
while z <= point.... | This code implements a pathfinding algorithm, likely A*, to find a route from a start point to an end point. It uses open and closed lists to track explored and unexplored nodes, checks neighboring points, and updates paths based on heuristic evaluations. If the end point is reached, it returns the path; otherwise, it ... | def find_path(self, start_p, end_p):
if start_p.X == end_p.X and start_p.Z == end_p.Z:
return [start_p]
self.open_list.append(start_p)
while len(self.open_list) > 0:
temp_start = self.get_min_point()
self.open_list.pop(0)
self.close_list.append(... |
def get_trainable_data(data_path, target):
df = read_df(data_path, 2)
train_df = get_train_df(df, target)
dv = DictVectorizer()
train_dict = train_df.to_dict(orient='records')
X = dv.fit_transform(train_dict)
y = df[target]
# missing values -> 0
y.fillna(0, inplace=True)
# we are... | This code's main task is to train and evaluate an XGBoost model for predicting flight delays (DEP_DELAY) using a dataset. It sets up MLflow tracking, loads data, splits it into training/validation/test sets, performs hyperparameter tuning via train_model_search, and trains the optimal XGBoost model using DMatrix format... | def main_flow(data_path = 'data/2018.csv'):
MLFLOW_TRACKING_URI = "http://127.0.0.1:5000"
mlflow.set_tracking_uri(MLFLOW_TRACKING_URI)
# mlflow.set_tracking_uri("sqlite:///mlflow.db")
mlflow.set_experiment("flight-delay-experiment")
target = ['DEP_DELAY']
X_train, y_train, X_val, y_v... |
def init_placeholder(self):
# encoder_inputs: word indices [batch_size, max_time_steps]
self.encoder_inputs = tf.placeholder(dtype=tf.int32, shape=(None, self.max_sent_len), name="encoder_inputs")
self.encoder_inputs_length = tf.placeholder(dtype=tf.int32, shape=(None, ), name="encder_inputs_len... | The code constructs a neural network model by initializing placeholders, building an encoder and decoder with provided embeddings, and merging all TensorFlow summaries for monitoring training progress. | def build_model(self, init_embed, decoder_init_embed):
print("building model...")
self.init_placeholder()
self.build_encoder(init_embed)
self.build_decoder(decoder_init_embed)
self.summary_op = tf.summary.merge_all() |
def scan(args):
from kyofu.util import show_proceed_prompt
name = args.library_name
overwrite = args.overwrite_song
path_hint = args.path_hint
library = Library.get_by_name(name)
if not path_hint:
if not show_proceed_prompt('Full scan may take very long time. Continue?'):
r... | The code updates a music library by scanning for file changes, updating existing songs or adding new ones using metadata. It checks for existing songs by path, updates them if found, or imports new entries otherwise. The process ensures the library's data aligns with file changes, using a session to commit updates. | def update(args):
from kyofu.metadata import load_metadata
from kyofu import session, logger
name = args.library_name
library = Library.get_by_name(name)
if len(library.song) == 0:
logger.info(f'No song in library. try full scan: library={library}')
return scan(args)
for path ... |
def clipPoint(self, point: QPoint, xmax, ymax):
x = point.x()
if x > xmax:
x = xmax
elif x < 0:
x = 0
y = point.y()
if y > ymax:
y = ymax
elif y < 0:
y = 0
return QPoint(x, y)
def snap(self, rect: QRect):
r... | This method handles mouse release events to manage graphical shapes. It creates a rectangle from mouse points, checks the selected tool type, and updates the shapes list by either adding new shapes (if non-overlapping) or removing intersecting ones. The logic varies based on the selected tool (e.g., delete, add specifi... | def mouseReleaseEvent(self, event):
print("Point 3")
if event.button() & Qt.LeftButton:
rect = QRect(self.clipPoint(self.begin, self.xmax, self.ymax), self.clipPoint(
self.destination, self.xmax, self.ymax))
rect = self.snap(rect)
# Delete shapes in ... |
def D_lambda(img_fake, img_lm, block_size=32, p=1):
"""Spectral distortion
img_fake, generated HRMS
img_lm, LRMS"""
assert img_fake.ndim == img_lm.ndim == 3, 'Images must be 3D!'
H_f, W_f, C_f = img_fake.shape
H_r, W_r, C_r = img_lm.shape
assert C_f == C_r, 'Fake and lm should have the same ... | The code calculates three no-reference evaluation metrics for image quality: D_lambda (spectral distortion), D_s (spatial distortion), and qnr (quality index without reference), using input images 'pred' (predicted), 'pan' (panchromatic), and 'hs' (high spectral/hyperspectral). It returns these metrics as a list for as... | def no_ref_evaluate(pred, pan, hs):
#no reference metrics
c_D_lambda = D_lambda(pred, hs)
c_D_s = D_s(pred, hs, pan)
c_qnr = qnr(pred, hs, pan)
return [c_D_lambda, c_D_s, c_qnr] |
def setInputLen(self, x):
self.n = len(x)
def dlp(self, x):
num = int(x, 2)
ans = ((self.g)%(self.p))**(num)
#print("giving binstring = ",ans%(self.p) )
return self.binstring(ans%(self.p))
def msb(self, x):
if int(x,2) <= (self.p-1)/2:
return "1"
else:... | The main task of the code is to process an input string `s` by first setting its length, then applying two operations: `dlp(s)` and `msb(s)`, and returning the sum of their results. The function combines the outcomes of these operations to produce a final output. | def prg_1(self, s):
self.setInputLen(s)
ans = self.dlp(s)
ans = ans + self.msb(s)
return ans |
def detectStart(self):
'''
get the start location from the original source
searching for red squares
'''
redFilter = copy.copy(self.originalImage)
redFilter = cv.cvtColor(redFilter[:,:,:3], cv.COLOR_BGR2HSV)
maskRed1 = cv.inRange(redFilter, (0, 70, 50), (10, 255, 255))
maskRed2 = cv.inRange(redFilter, (... | This code loads an image from a file, detects a starting point and waypoints, then uses these to identify a track. The main task is image-based path or track detection in a robotic or autonomous system. | def load(self, filename):
self.originalImage = cv.imread(filename, cv.IMREAD_UNCHANGED)
rf = self.detectStart()
gf = self.detectWaypoints()
self.detectTrack(rf, gf) |
def load_data():
return load_with_schema(HolocraftData.from_json)
def ensure_upload_playlists(youtube: api.Resource, data: HolocraftData):
for channel_id in chain(
map(lambda member_info: member_info.channel_id, data.members.values()),
data.clippers,
):
if channel_id not in data.uplo... | The main task of the code is to use a YouTube API key to update playlists, source streams, and clips data by interacting with YouTube's API, then save the updated data, notify clients, and report quota usage and HTML fetch statistics. | def main():
api_key = sys.argv[1]
youtube = api.build("youtube", "v3", developerKey=api_key)
# Load existing data
data = load_data()
# Do update
ensure_upload_playlists(youtube, data)
update_source_streams(youtube, data)
update_clips(youtube, data)
# Write out
write_data(data)... |
def read_asset(PDF_FILE):
"""
Read the PDF file and return the text
"""
logger.debug(f"Reading file from {PDF_FILE}...")
file = open(PDF_FILE, 'rb')
pdf_reader = PyPDF2.PdfReader(file)
txt = []
for pages in pdf_reader.pages:
txt.append(pages.extract_text())
logger.debug("All ... | The main task of the code is to process a Bible PDF file by reading and splitting its text into pages, rejoining fragmented verses, generating thematic maps, and normalizing theme names (e.g., correcting "confu sion" to "confusion" and "everlasting life" to "eternity") for consistent categorization. The function return... | def process(pdf_file=PDF_FILE):
file = read_asset(PDF_FILE)
logger.debug("File read successfully...")
pages = process_text(file)
logger.debug("All pages successfully processed...")
pages = rejoin_text(pages)
logger.debug("All incomplete verses fixed...")
bible_maps = create_map(pages)
lo... |
def getOpentDB(category, difficulty, nrQuestions = 1): # Andre
''' With a set number of questions, category and difficulty level
outputs the questions with that criteria '''
import html
import json
import random
### Check if the number of questions is valid, more than 0 and less than 50
... | This function retrieves questions based on category, difficulty, and source (e.g., OpentDB, Birthday). It calls specific data-fetching functions, handles errors by returning structured error messages, and resets tokens if necessary. The result is a dictionary containing question details or error information. | def getQuestion(category, difficulty, nrQuestions = 1, qSource = "OpentDB"): # Andre
''' Given a category, diffculty as strings and number
of questions as integer return a dictionary with
type, question, possible answers and correct answer '''
if (qSource == "OpentDB"):
questionSet = ge... |
def minusvec(v1,v2):
return [a-b for a, b in zip(v1, v2)]
def dot(v1,v2):
return sum([a*b for a,b in zip(v1, v2)])
def calNormalVec(self,p):
return unitvec(minusvec(p, self.center)) | This code calculates if a ray intersects a sphere, computes intersection parameters (time 't', point 'p', normal 'N'), and returns a hit record if the intersection occurs at t > 0. It uses quadratic equation solving with ray-sphere intersection math, storing results in a hit_record object for rendering purposes. | def hit(self,rayy):
ori=rayy.getori()
ocvec=minusvec(ori,self.center)
CC=dot(ocvec,ocvec)-self.rad**2
#
d=rayy.getdir()
BB=2*dot(d,ocvec)
#
AA=1
judge=False
t=0
p=0
N=0
delta=BB**2-4*AA*CC
if delta>=0:
... |
def calLightVec(p):
return unitvec(minusvec(lightsource, p))
def creatvec(x,y,z):
vec=[]
vec.append(x)
vec.append(y)
vec.append(z)
return vec
def vecscale(vec,scale):
return [x*scale for x in vec]
def dot(v1,v2):
return sum([a*b for a,b in zip(v1, v2)])
def calkdvec(kd,vec):
xx=vec[0... | The code calculates diffuse shading at a hit point by checking if a light ray is occluded by any object in the scene. If unoccluded, it computes the diffuse component using the surface normal, light direction, and material's diffuse coefficient. If occluded, it returns black. | def shading(record,hitable_list):
hit_record=record.gethit_record()
p=hit_record[1]
L=calLightVec(p)
myray=ray(p,L)
judge=False
for k in range(len(hitable_list)):
if judge==False:
mysphere=hitable_list[k]
judge,myrecord=mysphere.hit(myray)
fin=[]
if j... |
def calLightVec(rayy,tt,source):
return unitvec(minusvec(source, rayy.point_at_parameter(tt)))
def calNormalVec(rayy,tt):
return unitvec(minusvec(rayy.point_at_parameter(tt), center))
def creatvec(x,y,z):
vec=[]
vec.append(x)
vec.append(y)
vec.append(z)
return vec
def vecscale(vec,scale):
... | The main task of the code is to compute a color intensity based on light and surface normal vectors. It calculates the light direction (L) and surface normal (N), then uses their dot product to determine the lighting contribution. The result is a scaled intensity vector (I) multiplied by the maximum of 0 and the dot pr... | def colormodel3(rayy,tt,source):
L=calLightVec(rayy,tt,source)
N=calNormalVec(rayy,tt)
I=creatvec(1,1,1) #light intensity
return vecscale(I,max(0,dot(N,L))) |
def swLookAt(self,eyex,eyey,eyez,atx,aty,atz,upx,upy,upz):
fx=atx-eyex
fy=aty-eyey
fz=atz-eyez
f=[]
f.append(fx)
f.append(fy)
f.append(fz)
f=np.array(f)
f=self.normal(f)
up=[]
up.append(upx)
up.append(upy)
up.append(upz)
up=np.array(up)
up=self.normal(up)
s=np.cross(f, up)
s=s... | The code renders a 3D scene by configuring OpenGL matrices: STEP2 sets the camera view using a custom `swLookAt` matrix based on `self.theta`, while STEP3 defines a perspective projection with `swPerspective`. It then draws a grid, a tetrahedron, and invokes `addnew()` to complete the rendering pipeline. | def display(self):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
if self.STEP2:
glMatrixMode(GL_MODELVIEW)
glLoadMatrixf(self.swLookAt(10 * cos(self.theta), -10 * sin(self.theta), 10, 0, 0, 0, 0, 0, 1))
####################
#glLoadIdentity()
#gluLookAt(10*cos(self.theta), -10*sin(self.theta), ... |
def background(rayy):
#for background color
unit_direction=rayy.getdir()
t=(unit_direction[1]+1)*0.5
tem1=vecscale([1,1,1],(1-t))
tem2=vecscale([0.5,0.7,1],t)
fin=addvec(tem1,tem2)
return fin
def shading(record,hitable_list):
hit_record=record.gethit_record()
p=hit_record[1]
... | This code implements ray tracing to compute the color of a ray by checking intersections with objects in a scene. It calculates shading, handles reflections and refractions using Fresnel equations, and combines results recursively with depth limits. The function returns the final color after considering all lighting an... | def trace(rayy,hitable_list,depth):
fin=[]
if depth>max_step:
fin=background(rayy)
else:
intersect=-1
closest=math.inf
best_record=0
#hit_reclist=[]
for i in range(len(hitable_list)):
mysphere=hitable_list[i]
judge,myrec=mysphere.hit(r... |
def background(rayy):
#for background color
unit_direction=rayy.getdir()
t=(unit_direction[1]+1)*0.5
tem1=vecscale([1,1,1],(1-t))
tem2=vecscale([0.5,0.7,1],t)
fin=addvec(tem1,tem2)
return fin
def hit_sphere(rayy):
#
ocvec=minusvec(origin,center)
CC=dot(ocvec,ocvec)-rad**2
#... | The function determines the color of a ray based on the specified model. It checks if the ray intersects a sphere, applies different shading models (e.g., red, normal, shading variants) with light sources, or returns a background color if no intersection occurs. For the 'bonus' model, it handles dual sphere intersectio... | def color(rayy,model):
if model!='bonus':
if model=='skybox':
fin=background(rayy)
else:
#to see if ray hit sphere
judge, tt=hit_sphere(rayy)
if judge:
##if hit, decide which color
if model=='red':
fi... |
def creatvec(x,y,z):
vec=[]
vec.append(x)
vec.append(y)
vec.append(z)
return vec
def generategamma():
return (random.random()+1)
def addvec(v1,v2):
return [a+b for a,b in zip(v1, v2)]
def vecscale(vec,scale):
return [x*scale for x in vec]
def minusvec(v1,v2):
return [a-b for a, b in ... | The code generates a 3D scene with multiple spheres (different sizes, colors, and reflective properties), then renders a PPM image by tracing rays from each pixel to calculate color based on object intersections, saving the result to a file. | def main():
##############################################################
f = open(f"test.ppm", "w")
f.write("P3\n")
f.write(f"{width} {height}\n255\n")
############################################
hitable_list=[]
hitable_list.append(sphere(creatvec(0,-100.5,-2),100))
hitable_list.appe... |
def addvec(v1,v2):
return [a+b for a,b in zip(v1, v2)]
def vecscale(vec,scale):
return [x*scale for x in vec]
def minusvec(v1,v2):
return [a-b for a, b in zip(v1, v2)]
def color(rayy,model):
if model!='bonus':
if model=='skybox':
fin=background(rayy)
else:
#to see... | This function generates a 2D image representation of a 3D model by iterating over each pixel, calculating the color using ray tracing principles, and writing the result to a file. It creates rays from the origin to each pixel's position, computes the color based on the model, and outputs the generated image with a comp... | def mywindow(f,model):
for j in range(height,0,-1):
for i in range(width):
u=float(i/width)
v=float(j/height)
tem=addvec(vecscale(horizontal,u),vecscale(vertical,v))
uvcenter=addvec(lower_left_corner,tem)
r1=ray(origin,minusvec(uvcenter,origin))
... |
def createTables(cur):
command = '''CREATE TABLE IF NOT EXISTS Boards (
board_id INTEGER PRIMARY KEY,
name TEXT)'''
cur.execute(command)
command = '''
CREATE TABLE IF NOT EXISTS Threads (
thread_id Integer primary key,
topic Text,
html_path Text,
posts Text,
parent_bid Integer,
op_date Text,
html_content B... | The code downloads topics from a specified board using a SQLite database. It validates command-line arguments, connects to the database, creates tables, adds the board, retrieves topics, and downloads them, printing a completion message. | def main():
if len(sys.argv) != 3:
print("Usage: python download.py <db_name> <board_id>")
return
path = sys.argv[1]
boardId = sys.argv[2]
dbExists = os.path.exists(path)
con = sql.connect(path)
with con:
cur = con.cursor()
createTables(cur)
addBoards(cur)
getAllTopics(boardId, con)
#addFromFolder(con... |
def full2short(self, config):
for kwargs in [config, self.CONFIG]:
if kwargs.__contains__("line_spacing_height"):
kwargs["lsh"] = kwargs.pop("line_spacing_height")
if kwargs.__contains__("text2color"):
kwargs["t2c"] = kwargs.pop("text2color")
i... | This code initializes a text-based SVG object by processing input text, replacing tabs with spaces, generating an SVG file, adjusting path data, applying color configurations, and scaling the object for rendering. | def __init__(self, text, **config):
self.full2short(config)
digest_config(self, config)
text_without_tabs = text
if text.find("\t") != -1:
text_without_tabs = text.replace("\t", " " * self.tab_width)
self.text = text_without_tabs
self.lsh = self.size if self.l... |
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def setup(args):
# Prepare model
config = CONFIGS[args.model_type]
config.split = args.split
config.slide_step = args.slide_s... | This code defines a main function for training a Vision Transformer (ViT) model. It parses command-line arguments for data paths, model configurations, training hyperparameters, and distributed settings. The function initializes device settings, logging, random seeds, loads or creates the model, and executes the traini... | def main():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument("--name", required=True,
help="Name of this run. Used for monitoring.")
parser.add_argument('--data_root', type=str, default='./dataset')
parser.add_argument("--model_type", choices=["ViT... |
def wait_for(cycles):
print(f'Waiting for {cycles} cycles')
for i in range(cycles):
yield from tick()
def store_number(dut, number_to_store, location):
yield from wait_storage_available(dut)
print(f'Storing { number_to_store} in location { location}.')
# Load a number into storage
yield ... | The code simulates a system where numbers are stored in designated memory locations, calculates their average, and verifies correctness. It tests three scenarios with varying numbers, ensuring stored values match expectations and calculated averages (stored in location 4) are accurate. Exceptions are raised for mismatc... | def simulation_story(dut):
print('Starting simulation')
# Lets give a few cycles to allow the board to startup
yield from wait_for(5)
# Store numbers
yield from store_number(dut, 5, location=1)
yield from store_number(dut, 7, location=2)
yield from store_number(dut, 9, location=4)
# T... |
def exploration_decision(self, state: tuple[tuple[int]], uninvestigated: list[int]):
benefits = self.environment.benefits
costs = self.environment.costs
employed = list(state[0])
not_employed = list(state[1])
probabilities = self.get_probabilities(state)
probabilities[employed] = -1.0
pro... | The code implements a reinforcement learning algorithm to select the next technique to investigate. It explores techniques by simulating trajectories, updating state-action values based on probabilities, costs, and benefits, and iteratively refining decisions through dynamic programming. The function returns the chosen... | def next_technique(self, employed: list[int], not_employed: list[int]):
# root state
root_employed = tuple(sorted(employed))
root_not_employed = tuple(sorted(not_employed))
root_uninvestigated = [t for t in range(len(self.environment.benefits)) if t not in root_employed and t not in root_not_employed]
... |
def printGreeting():
print("This program will solve mazes using a recursive search.")
print("Running maze search...")
print("Results: ",end="")
def processCommandLineArgs():
arguments=sys.argv
#Try to read the file, return none if it is invalid amount
try:
textFile=arguments[1]
s... | The main task of the code is to solve a maze by reading user-provided parameters, loading a maze file, and finding a valid path from a specified start to end point. It processes command-line arguments, validates inputs, reads the maze data, executes a search algorithm, and outputs either the solution path or an error m... | def main():
#Greets user and reads in maze file/associated arguments
printGreeting()
processed=[]
processed=processCommandLineArgs()
#Throws errors based on the problem the user is causing
if(processed==(None,None,None)):
print("Invalid number of parameters you silly billy")
retu... |
def evaluation_road(traci, detectorset, number_lane, capacity):
"""
laneInfo = LaneInfo(number_lane=11, capacity=66.6)
vehicleCount = VehicleCounter(traci)
vehicleCount.getVehicleCountInDetector(NS_DETECTOR + WE_DETECTOR)
densityClass = get_level_of_service(vehicleCount, laneInfo)
print(f"DANH G... | The code dynamically adjusts traffic light programs in a SUMO simulation based on real-time traffic density evaluations. It uses detectors to assess congestion levels (NS/WE directions), categorizes them into classes (A-F), and applies adaptive control strategies—modifying cycle times or green durations—via TraCI. The ... | def run_with_new_program():
traci.switch("sim1")
# traci.edge.getLastStepVehicelNumber: lay all vehicle tren 1 edge
# traci.lanearea.getLastStepVehicleNumber: count vehicle tren 1 detector
"""execute the TraCI control loop"""
step = 1
count_reset = 0
NS_DETECTOR = ["e2det_-695446623#0_1", "... |
def find_column_one(user:list)->list:
'''Finds the first column in this method which contains minterms and corresponding binary'''
first=[]
for i in range(len(user)):
for j in range(i+1,len(user)):
dashed=dashing(str(bin(user[i])[2:].zfill(4)),str(bin(user[j])[2:].zfill(4)))
... | The main task of the code is to implement the Quine-McCluskey algorithm for minimizing Boolean expressions in Sum of Products (SOP) form. It processes input minterms through steps like grouping terms, identifying prime implicants, and applying Petrick's method to determine the minimal essential prime implicants, ultima... | def quine_mc_clausky():
'''Takes minterms as input and gives minimized SOP solution'''
# user= [int(i) for i in input("Enter the minterms: ").strip().split()]
user=[0, 1, 2, 5, 6, 7, 8, 9, 10, 14]
# print(user)
print("*"*100)
print("*"*100)
print("\nThe first column is:::")
zero_print(us... |
def cost_func(self, point,target):
return self.current_cost + self.heuristics_func(point,target)
def get_path(self,target):
path = []
self.VISITED.reverse()
for item in self.VISITED:
x,y = target[0]-item[0], target[1]-item[1]
d = abs(x)+abs(y)
if(d < 2... | This code implements a pathfinding algorithm using a priority queue (OPEN) to search for the shortest path from a start point to an end point in a grid, while avoiding collisions with another agent (agent2). It uses a cost function to prioritize nodes and expands valid paths, returning the found path or 0 if no path ex... | def search(self,start,end,agent2_loc):
self.OPEN.put((self.cost_func(start,end),start))
while not self.OPEN.empty():
point = self.OPEN.get()[1]
self.VISITED.append(point)
if(point == end):
return self.get_path(end)
self.expand(point,agent2_... |
def randomize_order(self):
ordtype = 2 # limit order
leverage = 1 # spot leverage is 1
side = choice(self.order_sides) # pick random side
price = self.decim(round(self.mid_price, self.price_precision))
qty = self.decim(round(self.qty, self.qty_precision))
if len(self.... | The main task of the code is to execute three sequential operations—randomizing order data, updating orders, and randomly canceling orders—each followed by a delay determined by `self.sleep`, likely to simulate asynchronous processing or rate-limiting in a task automation context. | def main(self):
self.randomize_order()
sleep(self.sleep)
self.update_orders()
sleep(self.sleep)
self.random_cancel()
sleep(self.sleep) |
def create_default_folders(self):
''''''
print('checking files')
# checking config file
if not os.path.exists(self.config_file):
cf = open(self.config_file, 'w')
cf.close()
print(self.config_file, 'created')
# cheching techdir
... | This code initializes an object by setting a working directory path (defaulting to a subdirectory if none is provided), creating necessary folders, configuring file paths for tech files and settings, initializing a library dictionary, and loading technology files and configuration data to prepare the environment for SR... | def __init__(self, path='') -> None:
super().__init__()
if path:
self.path = path
else:
self.path = os.getcwd() + '/sram_gereator_work_directory'
os.makedirs(self.path, exist_ok=True)
self.config_file = self.path + '/.sram_generator.config'
sel... |
def loading_config(path: Path, base_config: BaseConfig, arguments) -> Iterable[Config]:
for p in (path if isinstance(path, list) else [path]):
for file_location in glob.glob(p, recursive=True):
with open(file_location, 'r') as config_file:
log.debug("Loading config", file_locatio... | The code automates AWS CloudFormation deployments by parsing command-line arguments for config files, base configs, and deployment options (e.g., parallel execution, dry-run, deletion). It loads configurations, deploys or deletes stacks based on flags, and supports concurrency, debugging, and cleanup of deprecated stac... | def main():
parser = argparse.ArgumentParser(description='Automate CloudFormation deployments')
parser.add_argument('-c', '--config', required=True, help='Config file or multiple files when using a pattern', nargs='+')
parser.add_argument('-b', '--base', help='Base configs file to use')
parser.add_argum... |
def FinalVictoryDance(self):
try:
deb("game won #2",str(self.gameMyLove));
SFX(self.ArtWork['SFX_FinalVictory']);
splash.do_My_Splash(artj(self.ArtWork['FinalVictory']),5,True,(self.scr['W'])/4,(self.scr['H'])/4,(self.scr['W'])/2,(self.scr['H'])/2);
#msg="\n";
#msg+="\n";
#splash.do_My_Te... | The code executes a victory sequence when the game is won, playing a victory sound, displaying a splash screen, loading a grid file, updating the user's position in the puzzle, and rendering visual elements. It first checks if a specific condition (`self.gameMyLove > 0`) is met, triggering an alternative victory animat... | def VictoryDance(self):
try:
if self.gameMyLove > 0: self.FinalVictoryDance(); return
deb("game won",str(self.gameMyLove));
SFX(self.ArtWork['SFX_Victory']);
##splash.do_My_Splash(self.iDuckShot3,1);
splash.do_My_Splash(artp(self.ArtWork['Victory']),3,True,(self.scr['W']-580)/2,(self.scr['H']-1... |
def setupArtWork(self):
self.ArtWork['Wall']='f_purple';
self.ArtWork['Path']='blank1';
self.ArtWork['Door']='door01';
self.ArtWork['Key']='key01';
self.ArtWork['Life']='life03';
self.ArtWork['SuperLife']='life02';
self.ArtWork['MonsterR']='npc07';
self.ArtWork['Monster0']='npc0R';
self.ArtWor... | The code initializes a visual/game interface by setting up artwork, screen dimensions, maze visualization parameters, and animation settings. It loads game data, creates grid structures, and prepares page items for display, likely for an interactive application or game with predefined visual and animation configuration... | def __init__(self):
self.setupArtWork();
self.SizeSetup();
##
self.Fanart=(xbmc.translatePath(Config.fanart)); self.b1=artp("black1"); self.current=0; self.content=[]; self.scr={}; self.scr['L']=0; self.scr['T']=0; self.scr['W']=1280; self.scr['H']=720;
##
self.MazeVisW=self.WH; self.MazeVisH=self.WH;
... |
def write_config(atchem2_path, initial_concs={}, spec_constrain={},
spec_constant={}, env_constrain={}, photo_constant = {},
photo_constrain = {},
env_vals = {"TEMP":"298", "PRESS":"1013", "RH":"50",
"H2O":"CALC", "DEC":"CALC", "BLHEIGHT"... | The function configures, builds, and runs an AtChem2 model with specified instantaneous species concentration injections. It iterates over ordered injection times, adjusts initial concentrations, runs simulations, stitches outputs, and handles NOx ratio preservation. The task involves creating temporary directories, mo... | def _write_build_run_injections(injection_dict, atchem2_path, mech_path, day,
month, year, t_start, t_end, step_size,
initial_concs, spec_constrain,
spec_constant, env_constrain, photo_constant,
... |
def write_config(atchem2_path, initial_concs={}, spec_constrain={},
spec_constant={}, env_constrain={}, photo_constant = {},
photo_constrain = {},
env_vals = {"TEMP":"298", "PRESS":"1013", "RH":"50",
"H2O":"CALC", "DEC":"CALC", "BLHEIGHT"... | This function configures, builds, and runs an AtChem2 atmospheric chemistry model with a NOx constraint, allowing NO and NO2 to vary freely. It iterates over time steps, adjusting initial concentrations to maintain specified NOx levels, building temporary model copies, executing simulations, and aggregating outputs int... | def _write_build_run_nox_constraint(nox_dict, atchem2_path, mech_path, day,
month, year, t_start, t_end, step_size,
initial_concs, spec_constrain,
spec_constant, env_constrain, photo_constant,
... |
def _write_build_run_injections(injection_dict, atchem2_path, mech_path, day,
month, year, t_start, t_end, step_size,
initial_concs, spec_constrain,
spec_constant, env_constrain, photo_constant,
... | The function `write_build_run` automates the configuration, building, and execution of an AtChem2 atmospheric chemistry model. It handles three modes: standard simulations with default parameters, simulations with species injections (mimicking chamber experiments), and experimental NOx concentration constraints. The fu... | def write_build_run(atchem2_path, mech_path, day, month, year, t_start, t_end,
step_size,initial_concs={}, spec_constrain={},
spec_constant={}, env_constrain={}, photo_constant={},
photo_constrain={},
env_vals = {"TEMP":"298", "PRESS":"... |
def request_tree(self,link):
header = self.__rotate_header.fetch_header()
res = req.get(link,headers=header)
tree = html.fromstring(html=res.text)
return tree
def get_each_page_item_links(self,tree):
expression = "//div[contains(@class,'list-dir-even')]/div[@class='row']//div[@cl... | The code initiates web scraping by iterating through paginated URLs, extracting item links, and using multithreading to scrape data from each link concurrently. It converts relative URLs to absolute ones, manages threads for parallel processing, and ensures all threads complete before ending the scraping process. | def start_scraping(self):
"""
Runs the scraper
"""
print("\n\nstarting scraping ! Please wait for it to end ! \n\n")
currentUrl = "https://www.raise.sg/directory/directories/default.html"
while currentUrl:
tree = sel... |
def checkCheck(board, castleData):
#Returns who is in check, -1 Black, 1 White, 0 None
whiteKingPos = []
blackKingPos = []
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == 6:
whiteKingPos = [i,j]
if board[i][j] == -6:
... | The function determines if a checkmate occurs by checking if the side under attack (white or black) has any legal moves to escape. It scans the board for the king's position, evaluates all possible moves for the attacking side's pieces, and returns 1 (white checkmate), -1 (black checkmate), or 0 (no checkmate) based on... | def checkmateCheck(board, castleData):
checkData = checkCheck(board, castleData)
if checkData != 0:
whiteKingPos = []
blackKingPos = []
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == 6:
whiteKingPos = [i,j]
... |
def findMoves(board, name, x, y, castleData):
possibleMoves = [] #x, y, Kill
color = 0
if name > 0:
color = 1
else:
color = -1
if name == 1:
#White Pawn
if y == 6:
if x in range(0,8) and y-2 in range(0,8):
if board[x][y-2] == 0 and board[x... | This function handles chess piece selection and movement based on user input. It calculates board coordinates, updates the game state by selecting/moving pieces, manages castling data, checks for check/checkmate, and returns updated board, turn, and game status. | def choosePosition(pos, newBoard, newSelectedPiece, newTurn, newPossibleMoves, newInCheck, newCastleData):
x = -1
y = -1
for i in range(0,8):
if pos[0] in range(i*100, i*100 + 100):
x = i
if pos[1] in range(i*100, i*100 + 100):
y = i
board = copy.deepcopy(newBoar... |
def open_stand():
#pyautogui.rightClick()
pydirectinput.rightClick()
time.sleep(0.1)
#reset_mouse()
stand_image = pyautogui.locateOnScreen('./images/brewing_stand_label.png', region=(0, 40, 800, 640))
if stand_image is not None:
print("Brewing stand found!")
reset_mouse()
... | This code automates a game's brewing process by alternating between serving ingredients and dropping potions on a brewing stand. It retrieves coordinates and ingredients, handles errors, moves the mouse, and uses image detection to reset the screen, repeating cycles to complete brewing tasks while managing game interac... | def alternate_bs(nw_with_drop):
#prepare ingredients
open_stand()
nw_coords, ingredient1, ingredient2, ingredient3 = get_ingredients()
exit_bs()
coords = [nw_coords, ingredient1, ingredient2, ingredient3]
if nw_coords == -1 or ingredient1 == -1 or ingredient2 == -1 or ingredient3 == -1:
... |
def create_numba_list(py_list):
numba_list = List()
for item in py_list:
numba_list.append(item)
return numba_list
def run(df, df_length, n, labels, n_labels, headers, start_index, end_index):
"""
fastest way to do this is to just create a numpy matrix of results ie a dataframe
append ev... | The code generates a classification report with precision, recall, and F1 scores for each class, using bootstrap sampling (n iterations) to compute confidence intervals at a specified confidence level (e.g., 95%). It handles binary/multiclass data, returns results as a dictionary or sorted DataFrame, and includes sampl... | def classification_report(
label,
predicted,
n=1000,
confidence_level=95,
as_dict=False,
sort_by_sample_size=False,
):
"""
n: number of bootstrap iterations
confidence_level: 90, 95, etc., between 1 & 100
as_dict: return a nested dictionary
sorted: return the Pandas dataframe... |
def _submit_carousel_grade(self, data):
"""
submit user interaction with carousel's result
:return: (dict)
"""
# User needs to attempt all assessments
if self.assessment_completed and self.has_passed:
data['max_value'] = 1.0
logging.info("Submittin... | The main task of the code is to log and process student responses by determining the appropriate grading method (carousel or summative) based on the 'last_slide' flag, combining results with a base response, and returning a JSON-formatted output for analytics. | def submit_student_response(self, data, suffix=''): # pylint: disable=unused-argument
"""
Publish data for analytics purposes
"""
logging.info("User submitted response :{}".format(data))
response = self._submit_carousel_grade(data) if data.get('last_slide', False
... |
def get_random_vertex(self):
random_key = random.choice(list(self.vertices.keys()))
return self.vertices[random_key]
def add_edge(self, vertex1, vertex2):
self.adjacency_list[vertex1.id].append(vertex2.id)
self.adjacency_list[vertex2.id].append(vertex1.id)
def get_connected_components(se... | The main task of the code is to randomly add edges between vertices in a graph, ensuring no duplicate edges, and then check if the graph remains disconnected. If multiple connected components exist, it attempts to connect them. The function enhances graph connectivity by introducing randomness in edge creation and addr... | def randomly_add_edges(self):
num_edges = random.randint(0, len(self.vertices) - 1)
for _ in range(num_edges):
v1 = self.get_random_vertex()
v2 = self.get_random_vertex()
if v1.id != v2.id and v2.id not in self.adjacency_list[v1.id]:
self.add_edge(v1, ... |
def _generate_rooms(self):
num_of_rooms = random.randint(1, 4)
for i in range(num_of_rooms):
room = Room(i)
counter = 0
while not self._is_allowed_location(room):
room.generate()
if counter >= 50:
return
... | The code generates a dungeon-like structure by creating rooms, connecting them with random edges, consolidating room tiles into a unified map, generating paths between rooms, and adding items and enemies to populate the environment. | def generate(self):
self._generate_rooms()
self.randomly_add_edges()
for key, room in self.vertices.items():
self.tiles.update(room.tiles)
for coords, tile in room.tiles.items():
x, y = coords[0], coords[1]
self._generate_paths()
self._add_... |
def get_positions(self, card, game_state):
characters_in_room = [q for q in game_state['character_cards'] if q['position'] == card['position']]
number_of_characters_in_room = len(characters_in_room)
available_rooms = []
available_rooms.append(self.get_adjacent_positions(card['position'],... | The main task of the code is to generate all possible actions for a game by evaluating active character cards' colors and positions. For each card, it creates decision options with color, position, and computed values. Grey cards include additional power indices, while the 'fantom' flag determines whether to use a spec... | def get_possible_actions(self, game_state, fantom=False):
active_cards = game_state['active character_cards']
actions = []
# Get all possible colors
for card in active_cards:
# Character node
color = card['color']
... |
def hit(self, zombie):
if(self.checkCollisionZombieHead(zombie)):
self.headshot_sound.play()
zombie.decreaseHeath(100)
return "headshot"
elif not self.checkCollisionZombie(zombie):
return "miss"
else:
zombie.decreaseHeath(50)
return "hit"
def drawBackground(self):
# b... | This code runs a game loop that handles input events, processes collisions with zombies, updates scores, and renders game elements. It toggles fullscreen mode on F11, plays bullet sounds on mouse clicks, checks hit detection, updates hit animations, and displays scores and crosshairs. The loop maintains FPS, updates th... | def run(self):
while self.running:
self.clock.tick(self.FPS)
self.current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_F11:
... |
def _get_base(self, str_id: str) -> RawIOBase:
files: list[str] = [
f"{str_id}_{name}.cysp"
for name in [
"CHARA_BASE",
"DEAR",
"NO_WEAPON",
"POSING",
"RACE",
"RUN_JUMP",
"SMIL... | The main task of this code is to generate a skeleton buffer for a unit by combining data from multiple files. It calculates a base unit ID, retrieves motion type information, constructs file paths for skeleton data, reads and merges binary data from these files into a BytesIO buffer, updates animation counts, and retur... | def get_skeleton_buffer(self, unit_id: int) -> BufferedReader | None:
base_unit_id = str(unit_id // 100) + "01"
if (unit := self.unit_data.get(base_unit_id)) is None:
for unit in self.unit_data.values():
if unit.get("prefab_id") == base_unit_id:
break
... |
def run_elegant(settings):
PF = execute_elegant(settings)
return PF
def fingerprint(keyed_data, digest_size=16):
"""
Creates a cryptographic fingerprint from keyed data.
Used JSON dumps to form strings, and the blake2b algorithm to hash.
"""
h = blake2b(digest_size=16)
for key in... | (The code evaluates a simulation by running 'elegant' with given settings, saves the results to an HDF5 file named using a settings-based fingerprint, computes a merit value via 'merit1', attaches the file path to the output, and returns this combined result.) | def evaluate_elegant(settings, a=1):
PF = run_elegant(settings)
fnameh5 = 'elegant_sim_' + fingerprint(settings) + '.h5'
PF.write(H5_SAVE+fnameh5)
output = merit1(PF)
output['archive']=H5_SAVE+fnameh5
return output |
def get_all_boolean_combinations(number):
return list(itertools.product([True,False], repeat = number))
def build_query_string(prefix_string, parameter_name_list = None, parameter_value_list = None, parameter_is_set_list = None):
query_string = prefix_string + "?"
is_first_parameter = True
if parameter... | This function tests all boolean parameter combinations by generating queries, validating responses, and ensuring filtered data matches expected results through comparison with manually filtered datasets. | def check_all_parameter_combinations(REQUEST_URL, parameter_name_list, parameter_values):
combinations = get_all_boolean_combinations(len(parameter_name_list))
for parameter_set_combination in combinations:
query_string = build_query_string(REQUEST_URL, parameter_name_list, parameter_values, parameter_... |
def _print_clause(self, clause):
print(
" ".join(str(self._literal_to_int(literal))
for literal in clause) + " 0",
file=self.cnf_file,
)
def _print_clauses(self, clauses):
for clause in clauses:
self._print_clause(clause)
def _get_aux_clau... | The code converts a logical formula into a SAT solver-compatible format by introducing auxiliary variables for equivalences ("a<->b") and nested logical operations. It processes each clause, expands nested expressions using helper variables, and prints clauses to a file. It tracks variable mappings, handles disjunction... | def write(self, formula):
"""Adds helper variables for all occurences of "a2<->a1" """
self.count = itertools.count(start=1)
self.vars_to_numbers = dict()
aux_iff_vars = set()
logging.debug("Writing minisat input file")
# We omit specifying the number of vars and clause... |
def detectifLatLong(inputA):
values = inputA.replace(" ","").split(",")
#print(values)
if len(values) == 2:
isFloat1 = True
try:
float(values[0])
except:
isFloat1 = False
isFloat2 = True
try:
float(values[1])
except:
... | The code calculates walking directions between two locations using Google Maps API, ensuring accessibility (e.g., sidewalks). It processes route steps, checks for obstacles, and generates detailed JSON data with coordinates, bearings, elevation changes, and detour handling. It integrates MongoDB and Excel data for univ... | def calculateDirections(exists, college, startaddy, endaddy, latExt, longExt, latExt2, longExt2):
if exists:
stringINPUTSTART = startaddy
stringINPUTEND = endaddy
baseLink = "https://maps.googleapis.com/maps/api/directions/json?"
if detectifLatLong(stringINPUTSTART):
lat,... |
def get_sketch_setting(dataset):
if dataset == 'icvl':
return [(0, 1), (1, 2), (2, 3), (0, 4), (4, 5), (5, 6),
(0, 7), (7, 8), (8, 9), (0, 10), (10, 11), (11, 12),
(0, 13), (13, 14), (14, 15)]
elif dataset == 'nyu': # select_joints = [0, 3, 6, 9, 12, 15, 18, 21, 24, 25, 2... | The function `draw_pose` visualizes skeletal pose data by drawing joints and connecting lines on an image, using dataset-specific color schemes. It optionally annotates joint angles if `return_angles` is True, overlays labels on the image, and returns the modified image with the pose sketch. | def draw_pose(points,dataset,img=None,return_angles=False,points3d=None):
# if not img:
# img = np.zeros((480,640))
sketch = get_sketch_setting(dataset)
jt_color = get_joint_color(dataset)
line_color = get_sketch_color(dataset)
if return_angles:
# points = points if not points3d else p... |
def advect_temp_salt_enthalpy(state):
"""
integrate temperature and salinity and diagnose sources of dynamic enthalpy
"""
vs = state.variables
settings = state.settings
vs.dtemp = advect_temperature(state).dtemp
vs.dsalt = advect_salinity(state).dsalt
if settings.enable_conserve_energy... | The code integrates temperature and salinity dynamics by computing advection tendencies, applying horizontal and vertical diffusion (including isopycnal and biharmonic mixing), diagnosing dynamic enthalpy sources, updating the equation of state, and calculating surface density fluxes and dissipation terms, all based on... | def thermodynamics(state):
"""
integrate temperature and salinity and diagnose sources of dynamic enthalpy
"""
"""
Advection tendencies for temperature, salinity and dynamic enthalpy
"""
vs = state.variables
settings = state.settings
vs.update(advect_temp_salt_enthalpy(state))
... |
def make_starting_orgs_list() -> list:
""" Makes list of orgs from STARTING_ORGS string.
Adds '_' after the 'HH' prefix (turns 'HH123456' into 'HH_123456).
Called by make_csv_from_fmpro_json() """
target_orgs: list = []
for org_id in STARTING_ORGS.split():
updated_org_id: str = f'%s_... | The code processes a JSON file to extract and validate organizational data, filters it based on predefined target organizations, sorts the results by 'Organization ID', and writes the validated data into a TSV file, ensuring consistency and correctness through multiple validation checks. | def make_csv_from_fmpro_json( input_path: str ) -> None:
## make target orgs-list ----------------------------------------
# target_orgs: list = STARTING_ORGS.split()
target_orgs: list = make_starting_orgs_list()
sorted_target_orgs: list = sorted( target_orgs )
## load json file --------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.