dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def xor(a, b):
assert(len(a) == len(b))
return "".join(["0" if a[i] == b[i] else "1" for i in range(len(a))])
def key_expansion(key):
reg = list(key)
tmp = reg[63]
for i in range(63, 0, -1):
reg[i] = reg[i-1]
reg[0] = tmp
reg[9] = xor(reg[9], tmp)
reg[34] = xor(reg[34], tmp)
... | The code performs a block encryption by reversing the input data, applying XOR with a key segment, and iterating through multiple rounds of encryption using key expansion. The process involves reversing data, XOR operations, and repeated key expansion for each round, ultimately returning the transformed data after fina... | def encrypt_block(data):
data = data[::-1]
key = KEY
data = xor(data, key[:45])
key = key_expansion(key)
for i in range(5):
data = round(data, key[:45])
key = key_expansion(key)
data = data[::-1]
return data |
def key_expansion(key):
reg = list(key)
tmp = reg[63]
for i in range(63, 0, -1):
reg[i] = reg[i-1]
reg[0] = tmp
reg[9] = xor(reg[9], tmp)
reg[34] = xor(reg[34], tmp)
reg[61] = xor(reg[61], tmp)
return "".join(reg)
def reverse_round(data, key):
tmp = ""
for i in range(0,45... | The main task of the code is to decrypt a data block using a cryptographic algorithm. It reverses the input data, expands the initial key into multiple subkeys, applies inverse rounds with these keys, performs an XOR operation, and finally reverses the data again to produce the decrypted output. | def decrypt_block(data):
data = data[::-1]
key = KEY
keys = [KEY]
for i in range(5):
key = key_expansion(key)
keys.append(key)
for i in range(5,0,-1):
data = reverse_round(data, keys[i][:45])
data = xor(data, keys[0][:45])
data = data[::-1]
return data |
def create_temp_dir(db):
os.makedirs(TEMP_DIR, exist_ok=True)
db = os.path.join(TEMP_DIR, db)
return db
def create_db(input_dir, db, verbose=False):
foldseek(f"createdb {input_dir} {db}", verbose=verbose)
def db_to_3Di(db, include_amino_acids=False):
names = parse_names(db)
repr_3Di = parse_seqs... | The function converts a database from an input directory into a 3Di format using temporary storage, then cleans up by removing the temporary files. It creates a temporary directory for the database, processes the input data into 3Di structure, and returns the parsed result while optionally including amino acids and con... | def to3Di(input_dir, db="3DiAA", verbose=False, include_amino_acids=False):
db = create_temp_dir(db) # changes db to within the temp directory
create_db(input_dir=input_dir, db=db, verbose=verbose)
parsed = db_to_3Di(db, include_amino_acids=include_amino_acids)
remove_db(db)
return parsed |
def make_pack(self, data, seq_num, ack_num, ack=False, syn = False, fin = False,ad_win = 0):
flags = ""
if(ack):
flags += "1"
else:
flags += "0"
if(syn):
flags += "1"
else:
flags += "0"
if(fin):
... | This code implements a graceful disconnection in a network protocol by sending a FIN-ACK packet, waiting for acknowledgment, and handling timeouts. It sends an encrypted FIN-ACK packet, repeatedly retransmits if no response is received within 1 second, and terminates the connection after 3 seconds of no response. Upon ... | def mrt_disconnect(self, ack_num):
self.on = False
finack = self.make_pack("",0,ack_num,ack=True,fin=True,ad_win = self.window_size)
self.recv.sendto(encrypt(finack),self.sender)
time_last = time.time()
timeout = time.time()
# keep looping incase they did not get the fin... |
def make_pack(self, data, seq_num, ack_num, ack=False, syn = False, fin = False,ad_win = 0):
# flags (ACK, SYN, FIN) --> between
# random number for connection --> between 0-255
# checksum (use hash())
# advertised window
# data
flags = ""
if(ack):
f... | This function implements a three-way handshake to establish a connection with a server. It generates a random connection number, sends a SYN packet, waits for a SYN-ACK response (with timeout handling), extracts server parameters, and sends an ACK to complete the handshake. The process involves packet encryption/decryp... | def mrt_connect(self):
# generate random number for connection
self.conn_num = int(random.random()*1000)
syn = self.make_pack(data="",seq_num=self.next_seq_num,ack_num=0, syn=True)
self.s.sendto(encrypt(syn),self.ip_port)
self.time_last_ack = time.time()
self.next_seq_num... |
def update(self):
# if available window is < packet length
if(time.time() - self.time_last_ack > self.timeout):
self.resend_all()
def make_pack(self, data, seq_num, ack_num, ack=False, syn = False, fin = False,ad_win = 0):
# flags (ACK, SYN, FIN) --> between
# random number ... | The main task of the code is to gracefully terminate a network connection by sending a FIN packet, waiting for the server's FIN-ACK response, and then sending an ACK to complete the disconnection process. It ensures all unacknowledged data is sent first, handles timeout retransmissions, and closes the socket once the c... | def mrt_disconnect(self):
# wait for all things to be sent before disconnecting
while(len(self.unacked) > 0):
self.update()
# generate random number for connection
fin = self.make_pack(data="",seq_num=self.next_seq_num,ack_num=0, fin=True)
self.s.sendto(encrypt(f... |
def get_field(decoded_msg, flags = False, seq = False, ack = False, con_num = False, checksum = False, ad_win = False, data = False):
if flags:
return decoded_msg[0:3]
if seq:
return int(decoded_msg[3:7])
if ack:
return int(decoded_msg[7:11])
if con_nu... | The main task of the code is to process incoming packets by verifying their legitimacy, handling data or FIN messages. For normal data packets with "000" flags, it sends an ACK, updates sequence tracking, and forwards data. For FIN packets with "001" flags, it acknowledges and initiates disconnection. The function mana... | def process_packet(self,recieved_packet):
# check to see if packet is legit or should be ignored
# if is normal data message
if(get_field(recieved_packet,flags=True) == "000"):
# if is the right packet, send ack and update next ack to send
# if is the wrong packet, ignor... |
def mrt_probe(self):
if self.recv:
reading, _, closing = select.select([self.recv],[],[self.recv])
if reading:
return True
return False
def check_packet(self,data):
if get_field(data,con_num=True) == self.conn_num and check_checksum(data):
retu... | The main task of the code is to wait for a probe condition, receive and decrypt a message, validate the packet, and process/return it if valid. It continuously probes until a valid message is received, decrypted, and verified, then processes and returns the packet. | def mrt_recieve1(self):
while not self.mrt_probe():
continue
(x,_,_,sender) = self.recv.recvmsg(2**16)
packet = decrypt(x).decode('utf-8')
if(self.check_packet(packet)):
return self.process_packet(packet) |
def mrt_probe(self):
if self.recv:
reading, _, closing = select.select([self.recv],[],[self.recv])
if reading:
return True
return False
def check_packet(self,data):
if get_field(data,con_num=True) == self.conn_num and check_checksum(data):
retu... | This function waits for a valid packet within a specified timeout. It repeatedly checks a probe status, and if it times out, returns 0. Upon successful probe, it receives and decrypts a message, validates the packet, and processes it if valid. | def mrt_recieve_timeout(self,timeout):
start_time = time.time()
while not self.mrt_probe():
if time.time() - start_time > timeout:
return 0
(x,_,_,sender) = self.recv.recvmsg(2**16)
packet = decrypt(x).decode('utf-8')
if(self.check_packet(packet)):
... |
def integerValidation(requestMessage):
while True:
validInteger = input(requestMessage)
if validInteger.isdigit():
return int(validInteger)
print("Please enter a valid integer.")
def drawSuperPattern(chosen_colors, dimention, all_patterns, win):
for y in range(0,dimention*dim... | Your return
The main task of the code is to create an interactive graphical application that allows users to select a grid size (5x5 or 7x7), choose three colors (with at least two unique), and generate patterns on a canvas. It validates user inputs, manages color selection, and uses a graphical window to display and... | def main():
iteration = 0
chosen_colors=[]
selected_dimention=[]
all_patterns=[]
print("Enter a grid size of either: 5 or 7")
while True:
dimention=integerValidation("Height and Width of the patches >> ")
if dimention==5 or dimention==7:
break
print("Please e... |
def integerValidation(requestMessage):
"""integerValidation validates the integer input if the input is
incorrect it will request an input again. Once successful it will exit
and return.
Args:
requestMessage (string): Contains the input message for the user to
follow.
Returns:
... | Your returnThe code generates and interacts with colored grid patterns. It validates user inputs for grid size (5 or 7) and three colors (with two unique). It creates a graphical window, draws patterns using chosen colors, and allows users to click on squares for selection or press 'd' to delete selected squares, with ... | def main():
iteration = 0
chosen_colors=[]
selected_dimention=[]
all_patterns=[]
# Request the height and width with integer validation.
print("Enter a grid size of either: 5 or 7")
while True:
dimention=integerValidation("Height and Width of the patches >> ")
if dimention==... |
def exit():
sys.exit(0)
def meann(x):
return summ(x) / len(x)
def summ(x):
if type(x) != list:
print('should type x is list!')
exit()
for i in range(len(x)):
if type(x[i]) != int and type(x[i]) != float:
print('should type x is intiger or float!')
exit()
... | The code calculates the sample variance of a list of numbers. It first validates that the input is a list of integers or floats. Then, it computes the squared difference of each element from the mean, sums these values, and divides by the number of elements minus one to return the sample variance. | def varr(x):
if type(x) != list:
print('should type x is list!')
exit()
for i in range(len(x)):
if type(x[i]) != int and type(x[i]) != float:
print('should type x is intiger or float!')
exit()
y = []
for i in range(len(x)):
y.append((x[i] - meann(x... |
def exit():
sys.exit(0)
def meann(x):
return summ(x) / len(x)
def summ(x):
if type(x) != list:
print('should type x is list!')
exit()
for i in range(len(x)):
if type(x[i]) != int and type(x[i]) != float:
print('should type x is intiger or float!')
exit()
... | This function calculates the skewness of a dataset to determine its direction (right, left, or none). It first validates that the input is a list of integers/floats, computes the mean, then calculates cubed and squared deviations from the mean. It sums these values, computes the skewness formula, and returns the result... | def skewness(x):
if type(x) != list:
print('should type x is list!')
exit()
for i in range(len(x)):
if type(x[i]) != int and type(x[i]) != float:
print('should type x is intiger or float!')
exit()
m = meann(x)
y1 = []
y2 = []
for i in range(len(x)... |
def exit():
sys.exit(0)
def meann(x):
return summ(x) / len(x)
def summ(x):
if type(x) != list:
print('should type x is list!')
exit()
for i in range(len(x)):
if type(x[i]) != int and type(x[i]) != float:
print('should type x is intiger or float!')
exit()
... | The code calculates the kurtosis of a given list of numerical data by first validating input types, computing the mean, then applying the formula for excess kurtosis: (sum((x - mean)^4)/n) / (sum((x - mean)^2)/n)^2 - 3, which measures the "tailedness" of the data distribution. | def kurtosis(x):
if type(x) != list:
print('should type x is list!')
exit()
for i in range(len(x)):
if type(x[i]) != int and type(x[i]) != float:
print('should type x is intiger or float!')
exit()
m = meann(x)
y1 = []
y2 = []
for i in range(len(x)... |
def get_cwd():
cwd = '/Users/mahrokh/DECODE/Simulations/London'
return cwd
def get_data_of_a_person(block=5, house_id="MAC004504", crop_years=True, verbose=False):
path = get_cwd()+"/input/halfhourly_dataset/block_"+str(block)+".csv"
data = pd.read_csv(path)
if house_id==[]:
house_id = ... | The main task of the code is to aggregate and average half-hourly energy consumption data from multiple households belonging to a specified ACORN social group (e.g., "ACORN-L"). It filters candidate households, validates their data completeness, processes individual datasets (cleaning, formatting, and aligning timestam... | def get_data_of_acorn_group(group="ACORN-L", num_houses=10, crop_years=True, verbose=False):
path = get_cwd()+"/input/informations_households.csv.xls"
data = pd.read_csv(path)
candidates = data.loc[data.Acorn==group]
# get 1 p
ind_1p=0
while True:
block_name = candidates.file.iloc[ind_1p... |
def get_cwd():
cwd = '/Users/mahrokh/DECODE/Simulations/London'
return cwd
def get_data_of_a_person(block=5, house_id="MAC004504", crop_years=True, verbose=False):
path = get_cwd()+"/input/halfhourly_dataset/block_"+str(block)+".csv"
data = pd.read_csv(path)
if house_id==[]:
house_id = ... | This function aggregates energy consumption data from multiple households across specified blocks. It reads CSV data, processes individual house energy profiles (normalizing, cleaning, and aligning timestamps), and combines them into a single averaged dataset. The output is a DataFrame containing the mean energy consum... | def get_data_of_mixed_group(block=20, num_houses=10, crop_years=True, verbose=False):
path = get_cwd()+"/input/halfhourly_dataset/block_"+str(block)+".csv"
data = pd.read_csv(path)
ids = data.LCLid.unique()
# get 1 p
df = get_data_of_a_person(block=block, house_id=ids[0], verbose=verbose)
df[... |
def get_cwd():
cwd = '/Users/mahrokh/DECODE/Simulations/London'
return cwd
def get_data_of_a_person(block=5, house_id="MAC004504", crop_years=True, verbose=False):
path = get_cwd()+"/input/halfhourly_dataset/block_"+str(block)+".csv"
data = pd.read_csv(path)
if house_id==[]:
house_id = ... | This function aggregates energy consumption data from multiple households in a specified ACORN group (e.g., "ACORN-L") for 2013. It filters candidate households, processes their half-hourly energy data (cleaning, validating, and normalizing), and combines the data into a single DataFrame with averaged energy values. It... | def get_data_of_acorn_group_2013(group="ACORN-L", num_houses=10, crop_years=True, verbose=False):
path = get_cwd()+"/input/informations_households.csv.xls"
data = pd.read_csv(path)
candidates = data.loc[data.Acorn==group]
ys=[]
# get 1 p
ind_1p=0
while True:
block_name = candidates.f... |
def add_module_defs(app):
modules = frappe.get_module_list(app)
for module in modules:
d = frappe.new_doc("Module Def")
d.app_name = app
d.module_name = module
d.save(ignore_permissions=True)
def add_to_installed_apps(app_name, rebuild_website=True):
installed_apps = frappe.get_installed_apps()
if not app_n... | The function installs a Frappe app by syncing its data, handling dependencies, executing pre/post-install hooks, and updating system settings. It checks if the app is already installed, installs required apps, clears cache, syncs fixtures/customizations, sets patches, and ensures proper permissions. The process include... | def install_app(name, verbose=False, set_as_patched=True):
from frappe.model.sync import sync_for
from frappe.modules.utils import sync_customizations
from frappe.utils.fixtures import sync_fixtures
frappe.flags.in_install = name
frappe.flags.ignore_in_install = False
frappe.clear_cache()
app_hooks = frappe.ge... |
def get_range_input(input, length=None, min=0):
ids = []
if length != None and input.lower() == "all":
return range(min, length)
if "-" in input:
content = input.split('-')
first = validate_int(content[0])
second = validate_int(content[1])
if first == None or second =... | This function allows users to edit specific elements in an array (`data`) by inputting IDs (individual or range-based) and setting values (with an offset). It validates inputs, adjusts indices, and updates the array either individually per item or uniformly across selected IDs, returning the modified array. | def edit_array_user(names, data, name, type_name="level", range=False, length=None, item_name=None, offset=0, extra_values=None, all_at_once=True):
individual = True
if range:
ids = get_range_input(coloured_text(f"Enter {name} ids(You can enter &all& to get all, a range e.g &1&-&50&, or ids separate by ... |
def get_version():
path = get_files_path("version.txt")
version = open_file_s(path)
return version
def coloured_text(text, base="#ffffff", new=dark_yellow, chr="&", is_input=False):
color_new = fg(new)
color_base = fg(base)
color_reset = fg("#ffffff")
text_split = text.split(chr)
for i ... | This function checks for updates by comparing the currently installed version of a software with the latest available version. If a newer version exists, it informs the user and provides instructions to update using pip, along with a link to the changelog. | def check_update():
installed_version = get_version()
coloured_text(f"\nYou currently have version &{installed_version}& installed", new=green)
latest_version = get_latest_version()
if not latest_version:
return
coloured_text(f"The latest version available is &{latest_version}&\n", new=green... |
def create_directory_if_not_exist(path: str):
Path(path).mkdir(parents=True, exist_ok=True)
def check_if_module_should_be_in_filtered_graph(module: BTModule, allowed_modules):
if len(allowed_modules) == 0:
return True
path_manager = PathManagerSingleton()
module_path = path_manager.get_relative_... | This function generates a PlantUML package diagram from a module hierarchy, filtering packages and dependencies. It creates a textual UML file with colored nodes/edges to visualize differences between two module graphs if a compare_graph_root is provided. The diagram includes modules, their dependencies, and highlights... | def plantuml_diagram_creator_sub_domains(
root_node,
diagram_name,
packages,
ignore_packages,
compare_graph_root,
root_folder,
path_view,
save_location="./",
):
create_directory_if_not_exist(save_location)
global root_module
root_module = root_folder
diagram_type = "pac... |
def _create_pu_graph(graph: BTGraph, config: dict) -> dict[str, dict[str, PuPackage]]:
bt_packages = graph.get_all_bt_modules_map()
views = {}
for view_name, view in config["views"].items():
pu_package_map: dict[str, PuPackage] = {}
for bt_package in bt_packages.values():
pu_pac... | The function `render_pu` generates PlantUML (PU) diagrams for different views of a graph. It creates PU graph structures, iterates through each view, and optionally prints debug metrics (package and dependency counts) if `MT_DEBUG` is enabled. It then renders the PU diagram for each view, constructs a save path using t... | def render_pu(graph: BTGraph, config: dict):
views = _create_pu_graph(graph, config)
for view_name, pu_package_map in views.items():
if os.getenv("MT_DEBUG"):
dep_count = sum(
len(package.pu_dependency_list) for package in pu_package_map.values()
)
pac... |
def _create_pu_graph(graph: BTGraph, config: dict) -> dict[str, dict[str, PuPackage]]:
bt_packages = graph.get_all_bt_modules_map()
views = {}
for view_name, view in config["views"].items():
pu_package_map: dict[str, PuPackage] = {}
for bt_package in bt_packages.values():
pu_pac... | The function compares two BTGraph objects (local and remote) to identify differences in packages and dependencies. It marks packages as created, deleted, or modified, updates dependency states, and generates a PlantUML diagram highlighting these changes. The result is saved as a file, showing structural differences bet... | def render_diff_pu(local_bt_graph: BTGraph, remote_bt_graph: BTGraph, config: dict):
project_name = config["name"]
local_graph_views = _create_pu_graph(local_bt_graph, config)
remote_graph_views = _create_pu_graph(remote_bt_graph, config)
packages_to_skip_dependency_update = set()
for view_name, lo... |
def load_file():
with open("day5.txt", 'r') as f:
lines = [line.strip() for line in f]
return lines
def get_seat(line):
row = get_row(line)
col = get_col(line)
seat = row*8+col
return seat
def find_empty_seat(seats):
for idx,seat in enumerate(seats):
if idx==0 or idx==len(seats)-1:
continue
seat = seats... | The code processes a file to find the highest seat number (part 1) and identifies an empty seat in a sorted list (part 2). It loads data, extracts seat values, sorts them, and computes results for both tasks. | def run():
lines = load_file()
seats = sorted([get_seat(line) for line in lines])
print('part 1: %s'% max(seats))
print('part 2: %s' % find_empty_seat(seats)) |
def stemmer(message):
stemmer = PorterStemmer()
message_token = nltk.word_tokenize(message)
stemmed_message=[]
for count in range(len(message_token)):
stemmed_message.append(stemmer.stem(message_token[count]))
return stemmed_message
def get_locations(message):
message=re.sub("['\(\)]",""... | The code processes user messages to extract specific information based on context (e.g., locations, dates, times, delays, bookings). It applies stemming, spell-checking, and intent recognition. If no answer is found, it corrects spelling mistakes, confirms with the user, and retries. If still unresolved, it returns Non... | def reasoning(message, context):
message = message.lower()
#stemming
if context == "basic":
answer = stemmer(message)
#Access train stations in the message
if context == "loc":
answer= get_locations(message)
#Get a date from a users message
if context == "date":
... |
def select_room():
print("\n\nSelect what room\n")
for room in rooms:
print(room)
selected_room = input("\ntype the room name\n")
while not rooms.get(selected_room):
print('Invalid Room Name')
selected_room = input("\ntype the room name\n")
print(selected_room + ' has been ... | The main task of the code is to manage RFID operations in a selected room via a menu-driven interface. It allows users to read, write, duplicate, or compare RFID data, switch rooms, or exit. The duplication mode copies content from one RFID card to another, checking tag compatibility and handling read/write operations ... | def main():
room = select_room()
while room:
# modes would be read, write, duplicate, compare
print("\n\n1: read \n2: write\n3: duplicate\n4: compare\n9: change room\nx: Exit")
mode = input("enter a number of what to do\n\n")
valid_selection = False
# readmode
... |
def open_gripper():
global GRIPPER
global GRIPPER_OPEN
pi.set_servo_pulsewidth(GRIPPER, GRIPPER_OPEN)
time.sleep(1)
def go_to_coor(x, y, z):
global ROTATE
global SHOULDER
global ELBOW
a0, a1, a2 = solve(x, y, z)
if a0 != None:
pi.set_servo_pulsewidth(SHOULDER, ang2pulse(SHOULDER, a1))
time.sleep(0.2)
pi... | The code's main task is to pick up a fruit from coordinates (35,240,60) using a gripper, transport it to a lemon lime box at (-30,-40,80), release it, and return to a centered position. The sequence involves opening/closing the gripper, precise movement, waiting periods, and resetting the robot's position. | def lemons():
open_gripper()
go_to_coor(35,240,60) # fruit location (z= 20 for floor, 50 for on mount)
time.sleep(0.3)
close_gripper()
go_to_coor(-30,-40,80) # lemon lime box
open_gripper()
stop_gripper()
time.sleep(0.1)
reset_to_center() |
def open_gripper():
global GRIPPER
global GRIPPER_OPEN
pi.set_servo_pulsewidth(GRIPPER, GRIPPER_OPEN)
time.sleep(1)
def go_to_coor(x, y, z):
global ROTATE
global SHOULDER
global ELBOW
a0, a1, a2 = solve(x, y, z)
if a0 != None:
pi.set_servo_pulsewidth(SHOULDER, ang2pulse(SHOULDER, a1))
time.sleep(0.2)
pi... | The code's main task is to pick up a blueberry from a designated location (35,240,60) using a gripper, transport it to a blueberry box at coordinates (-120,100,150), release it, and return to a central position. It involves opening/closing the gripper, precise movement to target coordinates, and a reset action to cente... | def blueberries():
open_gripper()
go_to_coor(35,240,60) # fruit location (z= 20 for floor, 50 for on mount)
time.sleep(0.3)
close_gripper()
go_to_coor(-120,100,150) #blueberry box coordination
open_gripper()
stop_gripper()
time.sleep(0.1)
reset_to_center() |
def open_gripper():
global GRIPPER
global GRIPPER_OPEN
pi.set_servo_pulsewidth(GRIPPER, GRIPPER_OPEN)
time.sleep(1)
def go_to_coor(x, y, z):
global ROTATE
global SHOULDER
global ELBOW
a0, a1, a2 = solve(x, y, z)
if a0 != None:
pi.set_servo_pulsewidth(SHOULDER, ang2pulse(SHOULDER, a1))
time.sleep(0.2)
pi... | The code's main task is to pick up a raspberry from coordinates (35,240,60) by opening the gripper, moving to the fruit's location, closing the gripper to grasp it, then transporting it to the raspberry box at (20,-10,80). It releases the raspberry by reopening the gripper, stops the mechanism, waits briefly, and final... | def raspberries():
open_gripper()
go_to_coor(35,240,60) # fruit location
time.sleep(0.3)
close_gripper()
go_to_coor(20,-10,80) #raspberry box coordination
open_gripper()
stop_gripper()
time.sleep(0.1)
reset_to_center() |
def open_gripper():
global GRIPPER
global GRIPPER_OPEN
pi.set_servo_pulsewidth(GRIPPER, GRIPPER_OPEN)
time.sleep(1)
def go_to_coor(x, y, z):
global ROTATE
global SHOULDER
global ELBOW
a0, a1, a2 = solve(x, y, z)
if a0 != None:
pi.set_servo_pulsewidth(SHOULDER, ang2pulse(SHOULDER, a1))
time.sleep(0.2)
pi... | The code's main task is to pick up an orange from a specified location (35,240,60) using a gripper, transport it to an oranges box at (50,60,80), release it, and reset the robot to a central position. The process involves opening/closing the gripper, moving to target coordinates, and timing delays for smooth operation. | def oranges():
open_gripper()
go_to_coor(35,240,60) # fruit location (z= 20 for floor, 50 for on mount)
time.sleep(0.3)
close_gripper()
go_to_coor(50,60,80) # oranges box
open_gripper()
stop_gripper()
time.sleep(0.1)
reset_to_center() |
def load_lines(path: str):
with open(path, "r") as file:
return file.readlines()
def parse_game(line: str):
game_number, rounds = get_game_number(line)
return {game_number: parse_rounds(rounds)}
def validate(game: dict[int, list[str, int]]) -> bool:
rounds = list(game.values())[0]
fo... | The code processes each line from 'input.txt', parses it into a game, validates the game, and accumulates valid game keys in a dictionary. Finally, it prints the sum of these valid keys. | def part_one():
path = './input.txt'
valids = {}
for line in load_lines(path):
game = parse_game(line)
if validate(game):
valids.update(game)
print(sum(list(valids.keys()))) |
def load_lines(path: str):
with open(path, "r") as file:
return file.readlines()
def parse_game(line: str):
game_number, rounds = get_game_number(line)
return {game_number: parse_rounds(rounds)}
def set_power(game):
red = 1
green = 1
blue = 1
for g in game:
red = g['r... | The code reads input lines from 'input.txt', processes each line into a game structure, calculates the power of each game's values, sums these powers, and prints the total result. | def part_two():
path = './input.txt'
total = 0
for line in load_lines(path):
game = parse_game(line)
for v in game.values():
total += set_power(v)
print(total) |
def _create_experiments_log_file(filename):
if os.path.exists(filename):
return
open(filename, 'w').write(','.join(EXPERIMENTS_LOG_FILE_HEADER) + '\n')
def test_algorithm_many_times(json_data, algorithm: typing.Callable, start_angle, angle_step):
angle = start_angle
best_res = {}
best_paths ... | The code compares different algorithms across multiple experiments by running each algorithm with specified configurations, modifying parameters as needed, and appending results to a CSV file for analysis. It handles special cases like the 'gtsp' algorithm, adjusts UAV numbers from algorithm names, and logs outcomes fo... | def compare_algorithms(config):
_create_experiments_log_file(config['output_file'])
df = pd.read_csv(config['output_file'])
for experiment in config['experiments']:
for algorithm in config['algorithms']:
if algorithm == 'gtsp':
print(
f"\n\n\n Startin... |
def parse_element(name: str):
return name
def parse_function(function_def: ion.IonPyList):
conds = []
exprs = []
for cond, expr in (function_def[i:i+2] for i in range(0, len(function_def), 2)):
conds.append(cond)
exprs.append(expr)
piecewise = create_piecewise(conds, exprs)
retur... | This function parses ion data from a file descriptor, processing elements, functions, phases, and parameters. It adds parsed entities to a database object (`dbf`), using type-specific handlers for each data category. Elements are registered with species/elements, functions are stored in symbols, phases are structured w... | def read_ion(dbf, fd):
lines = ion.load(fd, single_value=False)
for line in lines:
linetype = line.ion_annotations[0].text.upper()
if linetype == 'ELEMENT':
element = parse_element(line.text)
dbf.species.add(v.Species(element, {element: 1.0}, charge=0))
dbf.el... |
def get_screen_display(self):
if self.image_render:
return climage.convert(f'pyzork/data/maps/{self.image_render}.png',
is_unicode=self.display["use_unicode"],
is_truecolor=self.display["use_truecolor"],
is_256color=self.display["use_256color"],
... | The code renders a game scene by gathering its description, visual elements, and active commands, then displaying them to the user. In debug mode, it prints diagnostic info; otherwise, it clears the screen and shows the scene details along with available commands for interaction. | def set_scene(self, prompt="What will you do?"):
screen_description = self.description
screen_visual = self.get_screen_display()
# Get commands currently valid for scene (always) and current game/player state (changes)
self.active_command_tuples = self.get_active_command_tuples()
... |
def set_resolution(self, resolution: typing.Tuple[int, int]) -> None:
"""
Sets stream resolution based on supported streams
:param resolution: Stream resolution
:return: None
"""
self._set_parameter(cv2.CAP_PROP_FRAME_WIDTH, resolution[0])
self._set_parameter(cv2.... | The main task of the code is to connect to a DIGIT device, initialize its video stream with specified resolution and FPS, and configure lighting settings. It attempts to open a video stream using OpenCV, logs connection status, sets stream parameters, and adjusts RGB intensity if provided, defaulting to maximum brightn... | def connect(
self,
stream=DigitStreams.QVGA_60fps,
lighting: typing.Tuple[int, int, int] = None,
) -> None:
logger.info(f"{self.serial}:Connecting to DIGIT")
try:
self.__dev = cv2.VideoCapture(self.dev_name)
except cv2.error as err:
logger.erro... |
def generate_address():
address = Address(random.choice(names), streetname, random.choice(cities), random.choice(states), random.randint(501, 99950))
return address
def generate_paychecks(amt=100.00):
paychecks = []
# generate GRANT_BONUS
grant_bonus_amt = generate_paycheck("GRANT_BONUS", amount=amt... | The main task of the code is to generate a CEO employee with randomized attributes (address, paychecks, time off, projects), encapsulate them in a Root object, and return the JSON representation of this structure. The function creates an Employee instance, assigns it to a Root container, and outputs the serialized JSON... | def generate_ceo():
employee = Employee("CEO", generate_address(), generate_paychecks(1000.00), generate_timeoff(), generate_projects())
root = Root(employee)
return root.to_json() |
def generate_address():
address = Address(random.choice(names), streetname, random.choice(cities), random.choice(states), random.randint(501, 99950))
return address
def generate_paychecks(amt=100.00):
paychecks = []
# generate GRANT_BONUS
grant_bonus_amt = generate_paycheck("GRANT_BONUS", amount=amt... | The code generates a CTO employee's data structure by creating an Employee object with attributes like title, address, paychecks, time off, and projects, wrapping it in a Root class, and returning its JSON representation. | def generate_cto():
employee = Employee("CTO", generate_address(), generate_paychecks(750.00), generate_timeoff(), generate_projects())
root = Root(employee)
return root.to_json() |
def generate_designation():
return random.choice(designations)
def generate_address():
address = Address(random.choice(names), streetname, random.choice(cities), random.choice(states), random.randint(501, 99950))
return address
def generate_paychecks(amt=100.00):
paychecks = []
# generate GRANT_BONU... | The code generates an employee with attributes like designation, address, paychecks, time off, and projects, encapsulates it in a Root object, and returns its JSON representation. | def generate_employee():
employee = Employee(generate_designation(), generate_address(), generate_paychecks(), generate_timeoff(), generate_projects())
root = Root(employee)
return root.to_json() |
def miniMax(self, Max):
score=self.eval()
if score!=-1:
return score
if Max:
best=-1000000
for i in range(3):
for j in range(3):
if (board[i][j]=='_'):
board[i][j]=player
va... | This function evaluates all possible moves on a 3x3 board by simulating each empty cell as a computer move, then using a selected algorithm (minimax, depth-limited, alpha-beta, etc.) to calculate the move's value. It tracks the best move with the lowest evaluated value, resetting the board after each trial. The main ta... | def findnext(self):
bestnow=1000000
bestmove=[-1,-1]
for i in range(3):
for j in range(3):
if(board[i][j]=='_'):
board[i][j]=computer
# moveval=self.miniMax(True,1)
depth=10
if self.algo==... |
def miniMax(self, Max, depth):
# board=self.board(gridsize)
utility=self.eval()
# score=self.heuristic()
# print("Utility is: ",utility)
if utility!=-1:
return utility
if Max:
best=-1000000
for i in range(self.gridsize):
... | The main task of the code is to determine the optimal next move for a computer player in a grid-based game by evaluating all empty cells. It temporarily places the computer's symbol in each empty cell, uses a specified algorithm (minimax, depth-limited search, or alpha-beta pruning), and selects the move with the lowes... | def findnext(self):
# board=self.board(gridsize)
bestnow=1000000
bestmove=[-1,-1]
for i in range(self.gridsize):
for j in range(self.gridsize):
if(board[i][j]=='_'):
board[i][j]=computer
# moveval=self.miniMax(True,1)
... |
def maximum_likelihood(self, x):
return self.network_B(x)
def uncertainty(self, x):
covariance = self.covariance(x)
return np.sqrt(np.abs(covariance[:, 0, 0]))
def eval_MI(self, x, y=None, loss=None, c=0):
if y is not None:
T_joint = self([x, y]) - c
T_marginal =... | The function evaluates a model's predictions (yhat) and uncertainty (sigma) for input data x. If labels y are provided, it computes joint log probabilities (T_joint), marginal log probabilities (T_marginal), and mutual information (MI) using shuffling and custom evaluation. Returns predictions, uncertainty, and derived... | def eval(self, x, y=None, loss=None, c=0):
yhat = self.maximum_likelihood(x)
sigma = self.uncertainty(x)
if y is not None:
T_joint = self([x, y]) - c
T_marginal = self([x, self.shuffle(y)]) - c
MI = self.eval_MI(x, y, loss, c)
return yhat.numpy(... |
def initHeaders(self):
headers = [
Header((self.WIDTH/2,self.HEIGHT-25),200,100, (255,255,255), "", "centered"),
Header((10,10), 75,50, (25,25,25), "matrix size"),
]
return headers
def initButtons(self):
buttons = [
Button( coordinates=(self.WIDTH-85,1... | The code initializes a matrix rotation visualizer, setting up a 3x3 matrix with gradient color mode, animation controller for rotation, UI headers, buttons, and starts the main loop to display and animate matrix transformations in real-time. | def __init__(self):
self.drawRays = True
self.frame_count = 0
self.headers = self.initHeaders()
self.matrixSize = 3
self.colorMode = "gradient"
self.colorModeIndex = 1
self.matrix = SquareCellMatrix(N = self.matrixSize, cell_size = 50, screen_width = self.WIDT... |
def score_spans_dev(self):
assert self.dev_set != None, "dev set is not loaded yet!"
if self.reranking:
self.dev_logits, self.dev_scores = self.score_passages(self.dev_set)
elif self.bart:
self.dev_logits, self.dev_scores, self.dev_spans = self.score_spans_bart(s... | This function processes development data for a question-answering model. It scores spans if the task is "qa", aggregates answers if enabled, and selects top spans from logits/scores using temperature scaling. For BART models, it directly assigns logits/scores; otherwise, it extracts top spans via extract_top_span, prep... | def top_span_dev(self):
if self.task == "qa":
self.score_spans_dev()
if self.answer_agg:
self.answer_agg_dev()
if self.bart:
self.dev_top_probs = self.dev_logits
self.dev_top_scores = self.dev_scores
else:
self.dev_top_probs, s... |
def score_spans_test(self):
assert self.test_set != None, "test set is not loaded yet!"
if self.reranking:
self.test_logits, self.test_scores = self.score_passages(self.test_set)
elif self.bart:
self.test_logits, self.test_scores, self.test_spans = self.score_spans_bart(... | This function processes test data to determine top spans based on the task and configuration. If the task is "qa", it scores spans. If answer aggregation is enabled, it performs aggregation. For BART models, it directly assigns top probabilities and scores; otherwise, it extracts top spans using logits, scores, and tem... | def top_span_test(self):
if self.task == "qa":
self.score_spans_test()
if self.answer_agg:
self.answer_agg_test()
if self.bart:
self.test_top_probs = self.test_logits
self.test_top_scores = self.test_scores
else:
self.test_top_... |
def score_spans_dev(self):
assert self.dev_set != None, "dev set is not loaded yet!"
if self.reranking:
self.dev_logits, self.dev_scores = self.score_passages(self.dev_set)
elif self.bart:
self.dev_logits, self.dev_scores, self.dev_spans = self.score_spans_bart(s... | The function searches for an optimal temperature parameter by minimizing the negative log-likelihood (NLL) using cross-entropy loss on development data. It iterates through temperature values, computes the cross-entropy between model logits (scaled by temperature) and ground-truth scores, and selects the temperature wi... | def search_temperature_nll(self):
## search temperature by NLL / CE
## this is not suitable for QA because there can be 0/1/>1 correct answers
best_nll = float('inf')
best_temp = -1
temp_values = map(lambda x: round(x / 100 + 0.01, 2), range(1000))
for temp in temp_values... |
def field_no2row_col(self, field_no: int) -> Tuple[int]:
# self.board_width, (field_no-1) % self.board_width
return (field_no-1) // self.board_width, (field_no-1) % self.board_width
def row_col2field_no(self, row: int, col: int) -> int:
return row * self.board_width + col + 1
def can_capture_any... | This function validates and executes a piece move in a board game, checking turn validity, movement direction, capture rules, and promotion. It ensures the move adheres to game constraints, updates the board state, and returns a result indicating success or specific errors like illegal moves, turn mismatches, or captur... | def move_piece(self, from_field: int, to_field: int) -> MoveResult:
if self.continue_capturing_field_no is not None and from_field != self.continue_capturing_field_no:
return MoveResult(MoveError.MUST_USE_SAME_PIECE)
if from_field < 1 or from_field > 32:
return MoveResult(MoveErr... |
def field_no2row_col(self, field_no: int) -> Tuple[int]:
# self.board_width, (field_no-1) % self.board_width
return (field_no-1) // self.board_width, (field_no-1) % self.board_width
def get_piece_color_rc(self, row: int, col: int) -> GamePieceColor:
if row >= 0 and row < self.board_height and co... | This function checks if a game piece at a given position can make any valid move (either a regular move to an adjacent empty space or a capture). It evaluates movement directions based on the piece's color (dark/light) and type (king), considering row parity to determine valid diagonal directions. If no immediate move ... | def can_piece_make_any_move(self, from_field: int) -> bool:
piece = self.fields[from_field]
from_row, from_col = self.field_no2row_col(from_field)
if piece.get_color() == GamePieceColor.DARK or piece.get_type() == GamePieceType.KING:
if from_row % 2 == 0:
# One up lef... |
def read_path_file(self, data_file):
verts = []
self.path_length = 0
df = pd.read_csv(data_file, sep=',', index_col=None, header=0)
self.user_id = df.iloc[0]["user_id"]
cols = [col for col in df]
for index, row in df.iterrows():
verts.append(np.array([float(r... | The code initializes an object by reading a data file to extract vertices, computing metrics, calculating sinuosity and curvature, and printing user ID, scenario number, and computed values. | def __init__(self, data_file):
self.verts = self.read_path_file(data_file)
self.sum_metrics(data_file)
self.sinuosity = self.compute_sinuosity()
print("User: ", self.user_id)
print("Scenario: ", self.scenario_num)
print('Sinuosity:', self.sinuosity)
self.curvature... |
def convert_scannedpdf_to_jpg(self):
input_path = self.source_path+self.source_name
output_path = self.source_path+self.source_name[:self.source_name.rfind(self.dest_type)]
os.makedirs(output_path)
self.JPEG_path = output_path+os.sep+self.source_name+os.sep
pri... | The code's main task is to convert a scanned PDF into a standard PDF by first converting the scanned PDF to JPEG images, then converting those JPEGs back to a PDF format, and finally merging them into a cohesive document. | def execute_pdf_conversion(self):
self.convert_scannedpdf_to_jpg()
self.convert_jpg_to_pdf()
self.merge_pdf() |
def player_move(self,num,check_single=True):
evaltime=0
if num==1:
if not check_single:
player_name="Player 2"
else:
player_name="AI"
i,j=self.obj1.cell_choice(self.cells)
choice=self.player1_choice+" "
elif num==2:
i,j=self.obj1.cell_choice(self.cells)
choice=self.player2_choice+" "
... | The code implements a single-player game loop where the user chooses to go first or not. It alternates between player and computer moves, checks for a win/tie after each move, and displays the result if the game ends. The loop continues until a decisive outcome is reached. | def single_player(self):
choice=input("Do you want to play first?(y/n)").lower()
while(True):
if choice=='y':
self.player_move(1,True)
result=self.game_checker()
if result!='0':#a tie or winning
self.display_result(result)
break
choice='n'
else:
self.player_move(0)
choi... |
def player_move(self,num,check_single=True):
evaltime=0
if num==1:
if not check_single:
player_name="Player 2"
else:
player_name="AI"
i,j=self.obj1.cell_choice(self.cells)
choice=self.player1_choice+" "
elif num==2:
i,j=self.obj1.cell_choice(self.cells)
choice=self.player2_choice+" "
... | The main task of the code is to alternate between two players making moves in a game loop. After each move, it checks the game state. If a win or tie is detected, it displays the result and terminates the loop. Player 1's move includes a flag (False), while Player 2's move does not. The loop continues until a decisive ... | def double_player(self):
while(True):
self.player_move(1,False)
result=self.game_checker()
if result!='0':#not a tie or winning
self.display_result(result)
break
self.player_move(2)
result=self.game_checker()
if result=='0':
continue
else:
self.display_result(result,True)
... |
def create_graph(edges):
graph = {}
vertex_list = []
for edge in edges:
if edge[0] not in vertex_list:
vertex_list.append(edge[0])
graph[edge[0]] = [edge[1]]
else:
neighbours = graph[edge[0]]
neighbours.append(edge[1])
graph[edge[0]... | The main task of the code is to rank reachable items in a graph starting from a given node, compute their highest scores, and return the top 5 items sorted by score (descending) and item identifier (ascending). It constructs a graph, filters item nodes, checks reachability, calculates scores, and outputs the ranked lis... | def ranking_func(edges, weights, start):
graph = create_graph(edges)
all_possible_vertices = []
all_reacheable_vertices = []
for vertices in graph:
if vertices == start:
continue
# include only items
if vertices.find("i") != -1:
all_possible_ver... |
def build_graph(dataset, data, add_inter_layer_edges=True, add_self_loop=True):
"""
Build the input DGL graph
"""
edges, n_entity, n_el, etype, tp = load_dataset(dataset, data)
adj, empty = build_supra_adj(edges, n_el, n_entity, etype, add_self_loop=add_self_loop,
ad... | The function loads and preprocesses graph data, including building a graph structure, encoding labels, splitting data into training/validation/test sets, and handling real/synthetic features (standardization/normalization). It returns the graph, features, labels, indices, and dataset info for graph-based machine learni... | def load_data(root_dir, dataset_name, num_features, train_percentage, test_percentage,
features_distribution='gaussian', add_inter_layer_edges=True, feat_var='fixed',
standardize=True, normz=False):
"""
Load input graph, features, labelse, train indices, validation indices,
test ... |
def parse_args():
parser = argparse.ArgumentParser(description="DeepStream YOLO Dataset Processor")
parser.add_argument("--device", type=str, default="/dev/video0", help="Path to the USB camera device (e.g., /dev/video0)")
parser.add_argument("--framerate", type=str, default="30/1", help="Framerate for the ... | The main task of the code is to execute either dataset accuracy testing or real-time detection based on command-line arguments. If the `--test` flag is enabled, it runs `run_dataset_test` to evaluate performance on a dataset. Otherwise, it triggers `run_real_time_detection` for live object detection, leveraging parsed ... | def main():
args = parse_args()
if args.test:
# Code for testing accuracy with a dataset
run_dataset_test(args)
else:
# Code for real-time detection
run_real_time_detection(args) |
def addMatchLabel(pair, index, clickable):
label = tk.Label(root, text=str(pair))
label.place(x=0, y=(index*20)+30)
this.labelList.append(label)
if(clickable):
label.bind("<Button-1>", lambda x:clickMatch(pair, label))
def makeGraph():
graph = nx.MultiGraph()
nodes = data.getNodes()
... | The function `updatePerfectMatch` toggles a pair's status as a "perfect match" in a dataset, updates the corresponding label in a graph visualization, redraws the network graph, and refreshes the display to reflect the change. It clears the current plot, reconstructs the graph, adjusts labels, and triggers a UI update ... | def updatePerfectMatch(pair, init=False):
if (pair not in data.getNoMatches()):
data.togglePerfectMatch(pair)
index = data.getPerfectMatches().index(pair)
addMatchLabel(pair, index, not init)
plt.clf()
this.G = makeGraph()
nx.draw_networkx(this.G, with_labels=True, fo... |
def read_and_unpack_header(self):
header_raw = self.STDF_IO.read(self.HEADER_SIZE)
header = False
if header_raw:
header = struct.unpack(self.e + 'HBB', header_raw)
rec_name = self.REC_NAME.get((header[1], header[2]), 'oops')
# self.logger.debug('header={}, r... | This function reads a record from an STDF file by parsing its header and body. It returns the record name, header, and parsed body data if valid. If no header is found, it logs the position, closes the file, and returns False. Special handling sets endianness for 'FAR' records based on CPU type. | def read_record(self):
header = self.read_and_unpack_header()
if header:
rec_size = header[0]
# self.logger.debug('BODY start at ={}'.format(self.STDF_IO.tell() ) )
body_raw = self.read_body(rec_size)
# self.logger.debug('BODY end at ={}'.format(self.STDF_... |
def normalized_px():
fx_prices = raw_px()
return 10000*fx_prices/fx_prices.iloc[0,:]
def ew_port_cumret():
return 10000*(1+normalized_px().pct_change().fillna(0).mean(axis=1)).cumprod()
def iv_port_cumret():
weighted_returns = iv_factor_weigths().values.re... | The function `plot_div()` generates a cumulative wealth plot comparing portfolio strategies. It conditionally plots normalized price data and cumulative returns of either an equally weighted portfolio (if blending type is "ew") or both equally weighted and volatility targeting portfolios (otherwise). The plot includes ... | def plot_div():
_, ax = plt.subplots()
if input.blending_type()=="ew":
ax.plot(normalized_px(), alpha=0.15)
ax.plot(ew_port_cumret(), color="black")
else:
ax.plot(normalized_px(), alpha=0.075)
ax... |
def domain_from_template(
self, template: Path, name: str, image_path: str, define: bool = False
) -> libvirt.virDomain:
"""Create a new domain from a given XML template. Defined and Run."""
self.delete_domain_if_exists(name)
map = dict(NAME=name, IMAGE_PATH=image_path, UUID=uuid4())... | This function creates a temporary virtual machine domain using a template, generates a snapshot, and yields control to the caller. After the context is exited, it reverts the domain to the snapshot state and deletes the domain, ensuring cleanup. The domain's name is auto-generated if not provided, with a timeout for st... | def temp_domain_snapshot(
self, name: str = "", timeout: int = 30
) -> libvirt.virDomain:
"""Temporary domain context manager to define a domain and create a snapshot and
revert afterwards"""
name = name if name else str(uuid4())
print(f"{name=}")
domain = self.domain... |
def is_exponential(n):
iteration = math.floor(math.log2(n)) + 1
for i in range(2, iteration):
a_float = n**(1/i)
a_floor = math.floor(a_float)
a_ceil = math.ceil(a_float)
if abs(a_floor - a_float) < abs(a_ceil-a_float):
a = a_floor
else:
a = a_ceil... | This code implements the AKS primality test to determine if a number 'n' is prime or composite. It checks for exponential properties, iterates through potential divisors 'r', verifies co-primality, and applies modular exponentiation conditions. If all tests pass, 'n' is declared prime; otherwise, it is marked composite... | def aks_test(n):
if is_exponential(n):
return 'composite'
r = 2
while r < n:
if math.gcd(n,r) != 1:
return 'composite'
if isPrime(r):
q = find_largest_prime_factor(r-1)
if q >= 4*math.sqrt(r)*math.log(n) and \
fast_mod(n, math.floor(... |
def calculate_heuristic(self, left, right, r, c, direction):
# left is me, right is me
# based on current setup, it is actually possible to do look ahead of this situation by count_open_continuous_piece as well,
# but we will leave that to minimax to handle, or else..."1 step" just becomes too ... | This function updates the heuristic grid (h_grid) for a given cell (r,c) by evaluating the maximum heuristic value based on four directional configurations (horizontal, vertical, diagonal). It checks if the cell is already occupied, computes continuous piece counts in each direction, combines configurations using get_m... | def update_heuristic(self, r, c):
b = self.board
if b.grid[r][c] != 0:
self.h_grid[r][c] = (-1, 0) # if piece already placed, rank = -1
return
# get all direction (configurations, regularized_score)
cs1 = self.calculate_heuristic(self.count_continuous_piece(r, c... |
def notify_my_neighbor(self, r, c):
b = self.board
for i in range(max(r - 4, 0), min(r + 5, b.piece_num)): # update heuristic of each possible piece in the neighborhood
for j in range(max(c - 4, 0), min(c + 5, b.piece_num)):
self.update_heuristic(i, j)
def fetch_optimal_sear... | The function performs a minimax search with pruning to evaluate game positions, recursively exploring optimal moves by simulating board states, updating position lists, and pruning suboptimal branches based on depth, width, and evaluation criteria. It tracks move validity, updates board configurations, and debugs visua... | def minimax(self, search_set, pos_list, conf_list, eval_list, depth, width, is_naive):
# if self.final_pos is not None:
# return
self.cal_count[depth] += len(search_set) # debug
if depth == 0:
for pos in search_set: # append all optimal positions to pos_list and done
... |
def fetch_optimal_search_set(self, pos_list, conf_list, eval_list, depth, width, is_naive):
ret = set()
maxPos = None
maxConf = 'alpha'
maxEval = self.dict['alpha'] # the current maximum configuration we can get at current depth and width
b = self.board
for r in ... | The main task of the code is to determine the optimal move in a board game using a minimax algorithm with alpha-beta pruning. It explores possible moves up to a specified depth, evaluates configurations, and selects the best position from the deepest level. The function restores the original board state, processes eval... | def move_piece_2(self, depth, width, is_naive):
b = self.board
self.power_depth = depth
# self.final_pos = None
origin_grid = deepcopy(b.grid) # deepcopy the current board
origin_h_grid = deepcopy(self.h_grid)
eval_list = [None] * depth
conf_list = [None] * depth... |
def detect(self, image):
"""Detect stars in a given image and return a list of stars as 2d points"""
img = cv2.imread(str(image))
img = np.array(Image.open(image).resize((600, 600)))
if len(img.shape) == 2:
gray = img
else:
gray = cv2.cvtColor(img, cv2.COL... | The code processes two images by detecting stars in each, applying an algorithm with 1000 iterations and a threshold of 22 to identify inliners, drawing the results on both images, and returning the inliners from each image for further analysis or visualization. | def run(self, image1, image2):
"""Run the algorithm on two images"""
print("Running Algorithm")
stars1 = self.detect(image=image1)
stars2 = self.detect(image=image2)
dst_inliner, src_inliners = self.algorithm(
stars1=stars1, stars2=stars2, num_iterations=1000, thresho... |
def detect_nanopi(self, img):
"""
This method detects stars in a given image.
Args:
img (string): The path to the image.
Returns: A list of Object Star.
"""
original_image = Image.open(img)
image = original_image.resize((600, 600))
width, hei... | The code processes two images on a NanoPi board by detecting stars, applying an algorithm to find matching star patterns (with 1000 iterations and a threshold of 22), and visualizing results. It returns the matched star coordinates from both images for alignment or analysis. | def run_nanopi(self, image1, image2):
"""Run the algorithm on two images on nanppi board."""
print("Running Algorithm")
stars1 = self.detect_nanopi(img=image1)
stars2 = self.detect_nanopi(img=image2)
src_stars = self.stars_list_to_array(stars1)
dst_stars = self.stars_lis... |
def stars_list_to_array(self, stars):
"""
This method gets the list of stars as Star objects and converts them to list of point
Args:
stars (list of Star): The list of stars.
Returns: A list of point in 2D. Example: [(x0, y0), (x1, y1)]
"""
list = []
... | The code processes star data from an image and array on a NanoPi board by converting star lists to arrays, applying an algorithm with specified parameters (iterations, threshold) to find inliners, visualizing results on the input image, and returning inlier data if sufficient stars are present; otherwise, it returns em... | def run_nanopi_from_array(self, image1, stars, image_stars):
"""Run the algorithm on one image and array on nanppi board."""
print("Running Algorithm")
stars1 = image_stars
src_stars = self.stars_list_to_array(stars1)
if len(src_stars) > 2:
dst_inliner, src_inliners =... |
def load_data(self, file_path='', dates=None, df=None, num=0):
"""Load the relevant stock data from file, dataframe, or Yahoo!.
Args:
file_path (string): Full path of csv file containing stock price data
for the single period problem.
dates (list): [Start_Date, ... | The code executes a workflow to load data, build a model (CQM or DQM), and solve it based on parameters like risk bounds, return targets, and initial holdings. For CQM, it directly solves the problem; for DQM, it performs a grid search if multiple parameters are specified, then builds and solves the DQM model. The task... | def run(self, min_return=0, max_risk=0, num=0, init_holdings=None):
"""Execute sequence of load_data --> build_model --> solve.
Args:
max_risk (int): Maximum risk for the risk bounding formulation.
min_return (int): Minimum return for the return bounding formulation.
... |
def get_var_color(var):
"""
Takes in the variable name and for the variable to colormap
var A string of the variable name to get the color for
"""
# Check whether taking first or finite differences
if 'd_' in var:
var = var[2:]
# Build dictionary of available colors
var_... | The function `plot_waterfall` generates a 3D waterfall plot visualizing individual profiles from an `Analysis_Group` object, using specified color maps, clustering, and filtering parameters. It processes data frames, handles date formatting, applies clustering algorithms, filters data ranges, and plots profiles with di... | def plot_waterfall(ax, a_group, fig, ax_pos, pp, clr_map=None):
"""
Takes in an Analysis_Group object which has the data and plotting parameters
to produce a subplot of individual profiles in a 3D waterfall layout. Returns
the x and y labels and the subplot title
ax The axis on which ... |
def sort_clusters(df, cluster_numbers, ax=None, order_by='SA', use_PDF=False):
"""
Redoes the cluster labels so they are sorted in some way
df A pandas data frame output from HDBSCAN_
cluster_numbers A list of all the labels for the clusterst in df
ax The axis on which to ... | The function `plot_clusters` visualizes HDBSCAN clusters on an x-y plane (or 3D), plotting data points, noise, centroids, and outliers with customizable markers, colors, and annotations. It handles cluster relabeling, filters data, adds regression lines, box-and-whisker plots, and legends, while respecting parameters l... | def plot_clusters(a_group, ax, pp, df, x_key, y_key, z_key, cl_x_var, cl_y_var, cl_z_var, clr_map, m_pts, m_cls, rel_val, ell, box_and_whisker=True, plot_slopes=False):
"""
Plots the clusters found by HDBSCAN on the x-y plane
ax The axis on which to plot
pp
df A pandas dat... |
def get_axis_labels(pp, var_attr_dicts):
"""
Using the dictionaries of variable attributes, this adds the xlabel and ylabel
attributes to the plot parameters object passed in (this replaced the
`get_axis_label` function)
pp A custom Plot_Parameters object
var_attr_dicts A ... | This code initializes a class to process and filter a dataset for plotting. It stores input parameters, identifies available variables, filters relevant variables and profiles, and prepares filtered data for visualization using specified parameters and titles. | def __init__(self, data_set, profile_filters, plt_params, plot_title=None):
self.data_set = data_set
self.vars_available = list(data_set.arr_of_ds[0].keys())
self.profile_filters = profile_filters
self.plt_params = get_axis_labels(plt_params, data_set.var_attr_dicts)
self.plot_ti... |
def calc_metrics(
pred: torch.Tensor,
target: torch.Tensor,
metrics: dict,
device: torch.device,
num_of_classes: int,
) -> None:
dice_coeff_metric = Dice().to(device)
if num_of_classes == 1:
dice_score = dice_coeff_metric(pred, target)
metrics["dice"] += dice_score.item() * t... | The `eval_run` function evaluates a neural network on a validation/test dataset, computing loss and metrics. It processes batches, calculates loss, updates metrics (e.g., loss, accuracy), and logs images/visualizations if in "test" phase. It handles polar-to-Cartesian coordinate conversion if enabled, tracks image stat... | def eval_run(
net: nn.Module,
loss: nn.Module,
eval_data_loader: DataLoader,
epoch: int,
device: torch.device,
batch_size: int,
epochs: int,
classes: int,
phase: str,
) -> Tuple[dict, int]:
net.eval()
metrics: dict = defaultdict(float)
epoch_samples = 0
image_stats = ... |
def find_related_words(dictionary, lang):
lang_dictionary = {}
for category in dictionary:
for entry in dictionary[category]:
definitions = entry[1]['definitions']
for definition in definitions:
for word in sanitize_list(definition[lang]):
lang... | The main task of the code is to generate a language-specific dictionary by extracting related words, collecting their definitions, adding frequency data, normalizing frequencies, and sorting the entries by frequency. The function processes an input dictionary, filters language-related terms, aggregates definitions, enr... | def create_language_dict(dictionary, lang):
related_words = find_related_words(dictionary, lang)
print("creating a",lang,"specific dictionary...")
d = {}
for i,(word, ids) in enumerate(related_words.items()):
log_percent(i/len(related_words))
definitions = []
for id in ids:
... |
def read_json(freq_path):
with open(freq_path, 'r', encoding='utf-8') as f_json:
freq = json.load(f_json)
print("read",freq_path,"...")
return freq
def convert_to_flat_list(lang, original_list):
flat_list = []
for entry in original_list:
row = []
word = entry[0]
if(wo... | The main task of the code is to process multiple language-specific frequency dictionaries by converting their ordered lists into flat structures and saving them as CSV files. For each language, it extracts "frequency_order" and "random_order" from JSON files, transforms them into lists using `convert_to_flat_list`, and... | def main():
dicts = [
["isv", read_json('json/build/final_frequency_dict.json')],
["be", read_json('json/build/final_frequency_dict_be.json')],
["bg", read_json('json/build/final_frequency_dict_bg.json')],
["cs", read_json('json/build/final_frequency_dict_cs.json')],
["en", r... |
def read_json(freq_path):
with open(freq_path, 'r', encoding='utf-8') as f_json:
freq = json.load(f_json)
print("read",freq_path,"...")
return freq
def create_language_dict(dictionary, lang):
related_words = find_related_words(dictionary, lang)
print("creating a",lang,"specific dictionary...... | The main task of the code is to process a frequency dictionary by iterating through specified language codes, generating language-specific dictionaries for each code, and saving them as separate JSON files. It reads a base JSON file, applies a language-specific transformation, and stores the results in individual files... | def main():
dictionary = read_json('json/build/final_frequency_dict.json')
language_codes = ['en', 'ru', 'be', 'uk', 'pl', 'cs', 'sk', 'bg', 'mk', 'sr', 'hr', 'sl']
for language_code in language_codes:
tmp_dict = create_language_dict(dictionary, language_code)
save_json(tmp_dict, 'jso... |
def preprocess_directory(path, filenames, file_count):
# Set the noise threshold
k = 9
# Preprocess each file in directory
k_grams = {}
max_length = 0
hash_values = {}
preprocessed_files = {}
for i in range(file_count):
preprocessed_files[filenames[i]] = preprocess_code(path, filenames[i])
max_... | The main task of the code is to run the MOSS plagiarism detection system on files in a specified directory, generating fingerprints via the Winnowing algorithm, comparing them to identify similarities, and producing detailed plagiarism reports, originality scores, and insights. It processes all files or a specific file... | def trigger_moss(path, specific_file=None, want_exhaustive_logs=False):
'''
To run MOSS for all the files present in the given path
'''
# Extract all files present in the given path
filenames = os.listdir(path)
file_count = len(filenames)
print(f'Received a batch of {file_count} files')
# Preprocess e... |
def load_data(file_name: str) -> list:
lst = []
with open(file_name) as f:
lines = f.readlines()
for elem in lines:
lst.append(elem.strip())
return lst
def one_star_alg(lst: list, rule: dict) -> int:
ans = 0
passport = ''
passports = []
for elem in lst:
if ele... | The main task is to validate passport data against specified rules. The code loads input data, defines required fields, and applies two algorithms: one for basic validation (1st star) and another for stricter checks (2nd star). Dummy data simulates passports, with rules ensuring all required fields (e.g., byr, hgt) are... | def main():
data = load_data('../input.txt')
dummy_data = ["ecl:gry pid:860033327 eyr:2020 hcl:#fffffd",
"byr:1937 iyr:2017 cid:147 hgt:183cm",
"",
"iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884",
"hcl:#cfa07d byr:1929",
... |
def getRequestFromPhone():
monitor = {'top': 150, 'left': 0, 'width': 395, 'height': 450}
sct = mss()
cv2.namedWindow("Phone", cv2.WINDOW_NORMAL)
cv2.moveWindow("Phone", 500, 500);
question = ""
list_answer = []
while True:
img = np.array(sct.grab(monitor))
img = cv2.cvtCo... | The function `getRequest` retrieves requests based on the input source. It dispatches to specific methods like `getRequestFromPhone` or `getRequestFromCamera` depending on the `source` parameter. For 'test', it uses `getRequestsFromInput` with a predefined question and options. Returns an empty list if the source is un... | def getRequest(source):
if source == 'phone':
return getRequestFromPhone()
elif source == 'camera':
return getRequestFromCamera()
elif source == 'file':
return getRequestFromFile()
elif source == 'test':
return getRequestsFromInput(
'What is the capital of ... |
def saveFile(s, filename='history.txt'):
with open(filename, 'a') as f:
f.write('\n')
f.write(s)
f.write('\n')
f.close()
def getRequest(source):
if source == 'phone':
return getRequestFromPhone()
elif source == 'camera':
return getRequestFromCamera()
el... | The code implements a quiz game that retrieves questions from a source, uses Google search stats to determine an answer, and tracks user accuracy. It displays options, prompts for the correct answer, and logs results if enabled. The main task is to interactively test knowledge with dynamically generated questions and t... | def play_HQ(source='test', save = False):
n_question = 0
n_correct_answer = 0
if save:
saveFile(time.strftime("%a %d %b %Y %H:%M:%S"))
play = prompt.integer('\nNew question : ')
while(play):
s = ""
n_question += 1
list_req = getRequest(source)
if len(l... |
def strategy(self, date, open, high, low, close, volume, vwap):
action = self.ema(close, self.state)
if action == Action.LONG:
self.buy(1, close, date)
self.state = State.LONG
elif action == Action.SHORT:
self.sell(1, close, date)
self.state = Stat... | The code simulates a trading strategy by iterating through historical price data, updating the strategy with each data point, recording valuation changes, and executing trades (sell or buy) based on the current state (LONG/SHORT) at the end of the simulation. It maintains a valuation history and resets the state afterw... | def simulate(self):
for index, row in self.df.iterrows():
date = row["DATE"]
open = row["OPEN"]
high = row["HIGH"]
low = row["LOW"]
close = row["CLOSE"]
volume = row["VOLUME"]
vwap = row["VWAP"]
self.strategy(date, o... |
def click(self, xp_locator, msg=""):
"""
Function to click on the web element
:param xp_locator:
:param msg:
:return:
"""
try:
self.get_web_element(xp_locator)
self.get_web_element(xp_locator).click()
self.step_pass(f"Successful... | The function `click_and_type` automates interacting with a web element by clicking it and typing a specified value. It uses an XPath locator to identify the element, handles exceptions gracefully, and logs success/failure messages with context. The `msg` parameter adds descriptive text to logs for clarity. | def click_and_type(self, xp_locator, value, msg=""):
"""
Function to click and type value in the web element
:param xp_locator:
:param value:
:param msg:
:return:
"""
try:
self.click(xp_locator, msg=msg)
self.send_keys(xp_locator, v... |
def Omegahat(r,a,laux):
"""
Calculates the angular velocity of the sub-Keplerian orbit
(Eq. B39 P1)
:param r: radius of the source
:param a: spin of the black hole
"""
return (a+(1-2/r)*(laux-a))/(PIF(r,a)/(r**2)-(2*a*laux)/r)
def lhat(r,a):
"""
Calculates the rspecific angular momen... | This function calculates the redshift factor for a photon in a circular orbit outside a black hole's ISCO. It uses parameters r (radius), a (spin), lamb (angular momentum), and eta (Carter constant) to compute the redshift via helper functions involving orbital frequencies (OH, OT), radial and tangential velocity compo... | def gDisk(r,a,b,lamb,eta):
"""
Calculates the redshift factor for a photon outside the inner-most stable circular orbit(isco) (assume circular orbit)
(Eq. B13 P1)
:param r: radius of the source
:param a: spin of the black hole
:param lamb: angular momentum
:param eta: Carter constant
:r... |
def lhat(r,a):
"""
Calculates the rspecific angular momentum of the sub-Keplerian flow
(Eq. B44b P1)
:param r: radius of the source
:param a: spin of the black hole
"""
return sub_kep*(r**2+a**2-2*a*np.sqrt(r))/(np.sqrt(r)*(r-2)+a)
def Omegahat(r,a,laux):
"""
Calculates the angular v... | The function calculates the redshift factor for a photon traveling inside the innermost stable circular orbit (ISCO) of a rotating black hole. It uses parameters like black hole spin (a), source radius (r), angular momentum (lamb), and Carter constant (eta) to compute relativistic corrections. The result involves orbit... | def gGas(r,a,b,lamb,eta):
"""
Calculates the redshift factor for a photon inside the isco (assume infalling orbit)
(Eq. B13 P1)
:param r: radius of the source
:param a: spin of the black hole
:param b: sign for the redshift
:param lamb: angular momentum
:param eta: carter constant
:... |
def x0(t):
return(radhs*np.sin(t*velhs))
def y0(t):
return(radhs*np.cos(t*velhs))
def gDisk(r,a,b,lamb,eta):
"""
Calculates the redshift factor for a photon outside the inner-most stable circular orbit(isco) (assume circular orbit)
(Eq. B13 P1)
:param r: radius of the source
:param a: spin o... | The function calculates the relativistic image of a lensed equatorial source near a black hole, incorporating time delays from lensing and geometric effects. It computes brightness using a Gaussian profile modulated by redshift and spin-dependent factors (gDisk/gGas) for regions inside/outside the innermost stable orbi... | def flare_model(grid,mask,redshift_sign,a,rs,th,ts,thetao,rwidth,delta_t):
"""
Calculate the black hole image including the time delay due to lensing and geometric effect
:param grid: alpha and beta grid on the observer plane on which we evaluate the observables
:param mask: mask out the lensing band, ... |
def conserved_quantities(alpha,beta,theta_o,a):
"""
Computes the conserved quantities for a photon landing at (alpha,beta) on the image plane
:param alpha: x coordinate on the image plane (perpendicular to the projected spin axis)
:param beta: y coordinate (parallel to the projected spin axis)
:para... | The function `calculate_observables` computes key observable quantities (source radius, redshift sign, time delay, and angular position) for gravitational lensing or black hole spacetime effects. It processes input grids and masks to evaluate conserved quantities, turning points, angular integrals, and radial integrals... | def calculate_observables(grid,mask,theta_o,a,mbar,distance=1000):
"""
A master function to calculate all observable effects based on all above functions
:param grid: alpha and beta grid on the observer plane on which we evaluate the observables
:param mask: mask out the lensing band, see lb_f.py for de... |
def visit_assign(self):
if not self.register.current().matches(TT_ID):
return Error("SYNTAX ERROR", self.statement, "Expected Variable ID",
self.register.current().position)
id_tok = self.register.current()
if id_tok.data in BUILT_IN_FUNCTIONS.keys():
... | The main task of the code is to parse and process assignment or output statements in a language. It checks for an assignment token, processes the assignment expression, and applies a PEMDAS-based evaluation to binary operations within assignments. If an output token is found, it processes the output statement. Otherwis... | def visit_statement(self):
if self.register.current().matches(TT_ASSIGN):
self.register.advance()
out = self.visit_assign()
if type(out) is AssignNode:
if type(out.value_node) is BinOpNode:
logger.debug("FIX BINOP")
tmp ... |
def domain_analysis(data):
"""Prints the category matches for all libraries."""
tags = {'image' : ['jpg', 'jpeg', 'gif', 'png', 'heif', 'image', 'yuv'],
'pdf' : ['pdf'],
'crypto' : ['crypto', 'encrypt', 'decrypt', 'conceal', 'tls', 'ssl'],
'crypto_small' : ['crypto', 'encrypt... | The code defines a function `start_analyses` that executes four distinct analyses on input data: domain analysis, architecture analysis, library distribution analysis, and interface analysis. Each analysis processes the data to extract specific insights, such as structural characteristics, system design, dependency dis... | def start_analyses(data):
"""Runs the different analyses."""
domain_analysis(data)
architecture_analysis(data)
library_distribution_analysis(data)
interface_analysis(data)
import IPython; IPython.embed() |
def game_over():
return check_winner(HUMAN_PLAYER) or check_winner(AI_PLAYER) or check_draw()
def ai_move():
best_score = -float("Inf")
best_spot = 0
board_spots = list(BOARD.keys())
random.shuffle(board_spots)
for spot in board_spots:
if BOARD[spot] not in "XO":
BOARD[spot]... | The code's main task is to run a game loop where the AI and human players take turns making moves, checking after each move if a player has won or if the game is a draw. If a win or tie is detected, it displays the board and announces the result, then terminates the loop. | def main():
while not game_over():
ai_move()
if check_winner(AI_PLAYER):
print_board(BOARD)
print(f"{AI_PLAYER} wins!")
break
elif check_draw():
print_board(BOARD)
print("Tie!")
break
human_move()
if che... |
def send_new_case_msg(self) -> None:
r = requests.post(self.base_url + "/newcase")
if not r.ok:
self.kill_force()
pass
def send_stroke_msg(self, case: list[list[int], list[int]]) -> str:
data = {"stroke": case}
data = json.dumps(data)
r = requests.post(self.... | The code evaluates a model's performance on a series of test cases by processing strokes, validating guesses, and accumulating scores. It iterates through `n_cases`, sends test cases, retrieves strokes, and compares model guesses against correct answers. Correct guesses add to the total score, while incorrect ones cont... | def evaluate(self, base_url: str) -> float:
self.total_score = 0
self.base_url = base_url
eval = Evaluator(self.directory)
# loop n_cases times
for i in range(self.n):
# we want to send a new test case, so try sending the message x times
self.send_new_ca... |
def safe_input(input_type, message):
"""
Ask for input.
Parameters:
- input_type (string): data type for the input. One of:
- "string"
- "int_positive"
- "float_positive"
Returns:
- value (depends on input_type)
"""
while True:
valu... | This code presents a menu-driven interface for an inventory management system, allowing users to select actions like registering sales, tracking product arrivals, querying inventory, generating reports, or viewing seasonal products. It validates user input to ensure a choice between 1-8, then executes the corresponding... | def main():
print("""
Select an action
1. Register sale
2. Register product arrival
3. Query inventory data
4. Most sold items
5. Employees with most sales
6. Generate sales report
7. Show only seasonal products
8. Customer satisfaction form
""")
while True:
action = safe_input('int_positive', 'Action... |
def get_modal(modal_id, close_id, save_id, heading):
return html.Div([
dbc.Modal([
dbc.ModalBody([
html.P(heading, className="modal_headings"),
modal_content(modal_id)]),
dbc.ModalFooter([
dbc.Button("Close", id=close_id, color="light",... | The code creates a Dash HTML layout for a pipeline interface, featuring a sidebar, topbar, and main content area with modals for editing titles and configuring analysis steps like data format, quality control, alignment, and variant calling. It includes interactive elements such as buttons, input fields, and dynamicall... | def create_layout():
return html.Div([
html.Div([
sidebar.create_layout(),
], className="screen_division_left"),
html.Div([
topbar.create_layout(),
html.Div([
html.Div([
html.Div([
html.P("Analysi... |
def linearity(self):
rainbow_statistic, rainbow_p_value = self.linear_rainbow(self.model)
return rainbow_statistic, rainbow_p_value
def homoscedasticity(self):
y = self.data[self.target]
y_hat = self.model.predict()
fig, ax = plt.subplots()
ax.set(xlabel="Predic... | The code performs diagnostic checks on a statistical model by calculating linearity (rainbow statistic/p-value), homoscedasticity (Lagrange multiplier/F-stat p-values), sum of squared residuals, and multicollinearity (VIF). Results are compiled into a structured DataFrame, displayed as a Markdown table, and accompanied... | def check(self):
rainbow_statistic, rainbow_p_value = self.linearity()
lagrange_multiplier_pvalue, f_stat_p_value = self.homoscedasticity()
ss = self.sum_squared_residuals(self.model.model.endog, self.model.predict())
self.results = pd.DataFrame([[rainbow_statistic, rainbow_p_value, la... |
def scan_angle_and_distance_step(self, scan_step_angle):
min_angle = 0
while min_angle >= -70 + scan_step_angle: # scan angle range [-70, 70]
min_angle -= scan_step_angle
angle_distance_list = []
cur_angle = min_angle
while cur_angle <= -min_angle:
... | The code scans angular and distance data, converts valid points to coordinates, fills gaps between nearby points, and updates a map with obstacles, then adds clearance to the map. | def scan(self):
angle_dist_list = self.scan_angle_and_distance_step(5)
for i in range(len(angle_dist_list)):
angle = angle_dist_list[i][0]
distance = angle_dist_list[i][1]
if distance > 0:
xPos, yPos = self.convert_coordinate(angle, di... |
def CreateSubstrings(m, text):
"""
Description
-----------
Given a text = y_1, y_2, ..., y_n it returns a list with m
strings y1, y2,.., ym where:
y1 = y_1, y_m+1, y_2m+1, ...
y2 = y_2, y_m+2, y_2m+2, ...
.
.
.
ym = y_m, y_2m, y_3m, ...
Parameters
----------
m :... | The function determines the likely length of a keyword used in encrypting a text by analyzing the index of coincidence (IOC) for substrings created by splitting the text into groups of characters spaced by each possible length from 1 to k. It calculates the average IOC for each group, compares it to the expected IOC of... | def GuessKeywordLegth(k, text):
"""
Description
-----------
Using the index of coincidence for each value from 1 to k
it tries to find the length of the keyword used to encrypt
Parameters
----------
k : int
The biggest guess value for the key length
text : string
The... |
def generate_address(self):
public, private = rsa.newkeys(512)
public_key = public.save_pkcs1()
private_key = private.save_pkcs1()
return self.get_address_from_public(public_key), private_key
def create_genesis_block(self):
print("===== Create genesis block...")
new_blo... | The code simulates a blockchain process by generating a cryptographic address and private key, creating a genesis block, and entering a loop to initialize, sign, and add transactions to the blockchain. It then mines a block, checks the address's balance, and adjusts mining difficulty. The main task is to demonstrate a ... | def start(self):
address, private = self.generate_address()
self.create_genesis_block()
while True:
# Step1: initialize a transaction
transaction = self.initialize_transaction({
'sender': address,
'receiver': 'super-smurf',
... |
def create_genesis_block(self):
print("===== Create genesis block...")
new_block = Block.from_dict({
'previous_hash': 'Hello First Block!',
'difficulty': self.difficulty,
'miner': 'super-smurf',
'miner_rewards': self.miner_rewards
})
new_... | The code initializes a miner by generating its address and private key, creates a genesis block, and enters an infinite loop to continuously mine new blocks using the miner's address while dynamically adjusting the mining difficulty. | def start(self):
address, private = generate_address()
print(f'Miner address: {address}')
print(f'Miner private: {private}')
self.create_genesis_block()
while True:
self.mine_block(address)
self.adjust_difficulty() |
def __make_X_and_y(self):
"""Makes X and y for training."""
# Make the basic X and y
X_train, y_train = make_X_and_y(
days=self.input_days,
repeats=self.training_repeats,
scale_inputs=self.scale_inputs,
scale_targets=self.scale_targets,
... | The code trains an ensemble of models by preparing training data, modifying features, setting up early stopping, creating a loss function, saving models in a directory, and generating training statistics for each ensemble member. | def train(self):
"""Train all the ensemble members, save them in models/ensemble/<ensemble_name>
and print out some stats about the training."""
# Make the basic X and y
X_train, y_train = self.__make_X_and_y()
# Filter channels and add static features if necessary
X_tra... |
def deconstruct_image(img,height,width,k):
"""
Break image into kxk blocks
return:
img: a COPY of that image in the form of n x k**2 vectors (n=number of blocks)
"""
print("Deconstructing image into blocks")
if (((height % k) != 0) or ((width % k) != 0) or (k == 0)):
raise TypeError("Yo, hold on, you can'... | The main task of the code is to evaluate image recovery quality using varying numbers of sensed pixels (S) for compressed sensing. It corrupts image blocks, applies recovery algorithms with regularization parameters, compares unfiltered vs. median-filtered results, and generates plots showing recovery quality (MSE) tre... | def main(filename,k,subfolder):
if subfolder[0] != '/':
raise ValueError("Subdir folder must start with '/'")
print("Entered main function....")
print("\n*************************")
img_original = imgRead(filename) # load image
savedir = os.getcwd() + subfolder
imgSave(savedir,filename,'unbothered',img=img_... |
def tokenize_function(examples, tokenizer, dataset):
if dataset in ["sst2", "cola"]:
return tokenizer(
examples["sentence"],
padding="max_length",
truncation=True,
return_tensors="pt",
)
elif dataset == "mnli":
return tokenizer(
... | The code sets up a federated learning framework for sequence classification using transformer models (DistilBERT, RoBERTa, BERT, T5) on GLUE benchmark datasets. It loads models/tokenizers, prepares datasets (with MNLI handling), tokenizes data, splits for federated learning (k-shot or standard), trains the global model... | def main(args):
if args.model == "distilbert":
model_name = "distilbert-base-uncased"
tokenizer = DistilBertTokenizerFast.from_pretrained(model_name)
elif args.model == "roberta":
model_name = "roberta-base"
tokenizer = RobertaTokenizerFast.from_pretrained(model_name)
elif ar... |
def show_settings(self, stacked_widget_index):
if not self.settingsDialog.isVisible():
self.settingsDialog.show()
else:
self.settingsDialog.hide()
def resizeEvent(self, event=None):
return
def modify_comic_view(self, key_pressed=None):
if key_pressed:
... | This code initializes a GUI application's main window, setting up UI components, toolbars, status bars, and connecting event handlers. It loads settings, configures the library, initializes database, and prepares interactive elements like bookmarks, formatting options, and keyboard shortcuts for document navigation and... | def __init__(self):
super(MainUI, self).__init__()
self.setupUi(self)
# Set window icon
self.setWindowIcon(
QtGui.QIcon(':/images/Lector.png'))
# Central Widget - Make borders disappear
self.centralWidget().layout().setContentsMargins(0, 0, 0, 0)
sel... |
def parse_split_chapters(self, chapters_with_split_content):
# For split chapters, get the whole chapter first, then split
# between ids using their anchors, then "heal" the resultant text
# by creating a BeautifulSoup object. Write its str to the content
for i in chapters_with_split_con... | The main task of the code is to parse and organize an EPUB file's content by extracting chapters from the OPF spine, mapping them to the manifest, adjusting the table of contents (TOC) order, handling split chapters with anchors, parsing their content, and inserting the cover image. It ensures chapters are correctly or... | def generate_content(self):
# Find all the chapters mentioned in the opf spine
# These are simply ids that correspond to the actual item
# as mentioned in the manifest - which is a comprehensive
# list of files
try:
# Multiple chapters
chapters_in_spine = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.