dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def _get_yaml_file(self, uri: str) -> Dict:
data = "".join(get_file(self.ls, uri))
try:
return ruamel.yaml.safe_load(data)
except ruamel.yaml.YAMLError as e:
logger.error(f"Error while parsing {uri}: {e}")
return {}
def _update_context(self, filename: str):
... | This function loads a YAML configuration file from the specified path, recursively merges it with default configurations listed in the file, and returns the combined configuration data. It handles inheritance by resolving default files, merging their contents into the primary config using deep updates, and updating the... | def load_yaml_config(self, config_path: str) -> Dict:
logger.info("Loading config from: {}".format(config_path))
data = self._get_yaml_file(config_path)
# Recursively load default file (config inheritance)
result: Dict = {}
if "defaults" in data:
base_folder = "/".jo... |
def get_country_links(countries_wiki_url):
"""
given a url to the wikipedia page listing all
countries in the world, return a dictionary mapping
country names to links to their respective wikipedia
pages.
:param countries_wiki_url: link
:return: name (str) -> link dict (str)
"""
# ge... | The main task of the code is to build an ontology from country data retrieved from Wikipedia. It fetches country links, extracts detailed information for each country, constructs an ontology using this data, and serializes it into NT format, saving the result to the specified output path. | def main_build_ontology(out_path):
# get links to country wikipedia pages
country_links = get_country_links(COUNTRY_WIKI_URL)
# get details about each country
country_data = {}
for country, link in country_links.items():
print('working on: ', country)
full_link = WIKIPEDIA_BASE_URL ... |
def get_country_infobox(country_link):
res = requests.get(country_link)
page = html.fromstring(res.content)
info_box = page.xpath("//table[contains(@class, 'infobox')][1]")
assert (len(info_box) > 0)
return info_box[0]
def get_country_president(infobox):
"""
extract president name, wiki link... | The code extracts country information from a Wikipedia page, including leaders (prime minister/president), area, population, government types, and capital city. It uses helper functions to parse data from an infobox, handles missing fields with `None`, and returns a structured dictionary. The function also logs errors ... | def get_country_info(country_link, with_prime, with_presi):
"""
return dict of information about country, including:
- prime minister name + link to wiki page + bday
- president name + link to wiki page + bday
- area of country
- population
- types of government (can match a number of types)... |
def get_country_links(countries_wiki_url):
"""
given a url to the wikipedia page listing all
countries in the world, return a dictionary mapping
country names to links to their respective wikipedia
pages.
:param countries_wiki_url: link
:return: name (str) -> link dict (str)
"""
# ge... | The main task of the code is to scrape and process country-related data from Wikipedia. It retrieves country links, identifies nations with presidents and prime ministers, extracts detailed country information, saves the data in a pickle file, and constructs an ontology serialized to a file. The workflow involves web s... | def main():
# get links to country wikipedia pages
country_links = get_country_links(COUNTRY_WIKI_URL)
# get lists of contries with prime ministers and presidents
with_presi = get_countries_with_presidents()
with_prime = get_countries_with_primes()
# get details about each country
country_... |
def filterBySafeDistance(self, poses, target):
filtered = []
for pose in poses:
if utils.separation(pose, target) <= self.safeDistance:
filtered.append(pose)
return filtered
def chooseTheBestPose(self, poses, bans=[]):
if len(poses) == 0 or len(bans) == 0:
... | This method identifies safe target positions by first filtering out nearby obstacles (meanies) within a safe distance from the current position, then selecting the optimal pose from candidate positions that avoids these filtered obstacles. | def targetPoseToAvoidMeanies(self):
self.allMeaniesToAvoid = self.filterBySafeDistance(
self.allMeanies, self.currentPose)
self.targetPose = self.chooseTheBestPose(
self.candidatePoses(self.currentPose), self.allMeaniesToAvoid) |
def targetPoseToAvoidMeanies(self):
self.allMeaniesToAvoid = self.filterBySafeDistance(
self.allMeanies, self.currentPose)
self.targetPose = self.chooseTheBestPose(
self.candidatePoses(self.currentPose), self.allMeaniesToAvoid)
def direction(self, bans=[]):
# If not at th... | The code's main task is to determine Tallon's movement direction in a game by prioritizing avoiding obstacles (meanies, pits) and moving toward bonuses. It retrieves game elements' positions, checks for threats, and calculates direction: avoiding meanies if present, moving toward the nearest bonus if available, or self... | def makeMove(self):
# This is the function you need to define
# For now we have a placeholder, which always moves Tallon
# directly towards any existing bonuses. It ignores Meanies
# and pits.
#
# Get the location of the Bonuses.
self.allBonuses = self.gameWorld.... |
def masking(path):
try:
imgGray = cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2GRAY)
faces = detector(imgGray)
predictor = dlib.shape_predictor(lendmark_path)
for face in faces:
# x1, y1 = face.left(), face.top()
# x2, y2 = face.right(), face.bottom()
... | The function `homomorphic` processes an image by applying a masking operation, saving the modified image to a specified path, and conditionally invoking additional functions (`morfologi` or `face_detector`) based on input parameters (`Hello`, `Hello_`). It handles different modes of processing, including saving the ima... | def homomorphic(path, subject, Hello, Hello_=False, path_save_homomorpic=path_save_homomorpic):
try:
if (Hello == 1 & Hello_ == 2):
masking(path)
img = cv2.imread(path)
# logging.info("Berhasil Melakukan filtering HomomorphicFilter")
path_save_homomorpic += su... |
def extract_information(user_input):
print("Processing input:", user_input) # To see exactly what is being processed
doc = nlp(user_input)
matcher = Matcher(nlp.vocab)
print("Recognized entities and their labels:")
for ent in doc.ents:
print(f"{ent.text} ({ent.label_})")
food_preferenc... | The function generates a concise UK travel itinerary based on user preferences, validating location, gathering activities/meals/hotels, and summarizing details for GPT response. It checks for sufficient activities, adjusts location formatting, and structures a 1200-character summary including hobbies, meal options, act... | def chat_gpt(messages):
user_input = messages
location, intent = extract_information(user_input)
print(intent)
if intent == 'plan_trip':
# Proceed with location-specific logic for travel-related inquiries
if location:
if is_location_in_uk(location):
location +... |
def load_data() -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Load data from parquet files."""
if config.local_validation:
train = pd.read_parquet(config.validation_path + config.train_file)
test = pd.read_parquet(config.validation_path + config.test_file)
else:
train = pd.read_parquet(co... | The main task is to generate product recommendation candidates using covisitation data (clicks, carts-orders, buy2buy) and top item lists, then compute validation scores. The code initializes tracking with Neptune, loads data/models, builds a word2vec index, and evaluates candidate predictions against test data for rec... | def main(cfg: DictConfig) -> None:
global config, run
config = cfg
run = neptune.init_run(
name=config.name,
description=config.description,
tags=list(config.tags),
)
run["config"] = config
data, test = load_data()
top_clicks, top_orders = get_top_clicks_orders(test)
... |
def load_data() -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Load data from parquet files."""
if config.local_validation:
train = pd.read_parquet(config.validation_path + config.train_file)
test = pd.read_parquet(config.validation_path + config.test_file)
else:
train = pd.read_parquet(co... | The main task of the code is to generate recommendation candidates using covisitation data (clicks, carts-orders, buy2buy) and a pre-trained model. It loads test data, top interaction statistics, and covisitation matrices, then invokes `generate_candidates` to produce item recommendations based on user behavior pattern... | def main(cfg: DictConfig) -> None:
global config, run
config = cfg
data, test = load_data()
top_clicks, top_orders = get_top_clicks_orders(test)
covisit_clicks = load_combined_covisitation(type="clicks")
covisit_carts_orders = load_combined_covisitation(type="carts-orders")
covisits_buy2buy ... |
def check(self, token_type):
if self.is_at_end():
return False
return self.peek().token_type == token_type
def advance(self):
if not self.is_at_end():
self.current += 1
return self.previous()
def error(self, duck_token, message):
if duck_token.token_type =... | The code's main task is to consume a token of a specified type. It checks if the current token matches `token_type` using `self.check()`. If valid, it advances to the next token and returns it; otherwise, it raises an error with the provided `message`. This is commonly used in parsers to validate and progress through t... | def consume(self, token_type, message):
if self.check(token_type):
return self.advance()
raise self.error(message) |
def advance(self):
self.current += 1
return self.source[self.current - 1]
def add_duck_token(self, token_type):
duck_text = self.source[self.start:self.current]
duck_token = DuckToken(token_type, duck_text, self.line)
self.duck_tokens.append(duck_token)
def error(self, duck_text,... | This function scans and classifies characters into tokens. It identifies punctuation marks (., ?, !), ignores whitespace (space, tab, carriage return), increments line count for newlines, and handles unexpected characters by raising errors or processing identifiers. | def scan_duck_token(self):
c = self.advance()
match c:
case ".":
self.add_duck_token("PUNCTUATION")
case "?":
self.add_duck_token("PUNCTUATION")
case "!":
self.add_duck_token("PUNCTUATION")
case " ":
... |
def match(self, *token_types):
for token_type in token_types:
if self.check(token_type):
self.advance()
return True
return False
def consume(self, token_type, message):
if self.check(token_type):
return self.advance()
raise self.err... | The method `expression` parses a "Quack" expression by checking for the token "QUACK", followed by punctuation, another "QUACK", and final punctuation. If valid, it constructs and returns a `DuckExpression` with the two punctuation values. If invalid, it raises an error expecting a "Quack" structure. Your return | def expression(self):
if self.match("QUACK"):
left = self.consume("PUNCTUATION", "Expect: punctuation after 'Quack'.")
self.consume("QUACK", "Expect: 'Quack' after punctuation.")
right = self.consume("PUNCTUATION", "Expect: punctation after 'Quack'.")
return DuckE... |
def hint(self, message):
"""Show the message in the hint box."""
time_prefix = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S.%f")
time_prefix = time_prefix[:-3] + "$ "
message = time_prefix + message
self.textBrowser_hint.append(message)
def update_image_choices(self):
... | This method enables the "Choose Folder" button, updates UI elements with loaded data, filters available tasks, sets the default task in a combo box, restores the task state, and clears data loaders after all data is successfully loaded. | def on_all_data_loaded(self):
"""Callback when all the data is loaded."""
self.pushButton_choose_folder.setEnabled(True)
self.pushButton_choose_folder.setText("Choose Folder")
self.hint("All folders loaded!")
self.update_image_choices()
self.update_element_choices()
... |
def update_element_choices(self):
"""Update the element choices."""
if (self.comboBox_left.currentText() == "") or (
self.comboBox_right.currentText() == ""
):
return
left = self._data_container[self.comboBox_left.currentText()]
right = self._data_containe... | The code defines a callback method `on_left_changed` that updates element choices, triggers a left/right change event, and updates the left output when the left image is modified. | def on_left_changed(self):
"""Callback when the left image is changed."""
self.update_element_choices()
self.left_or_right_changed()
self.update_left_out() |
def data_loader(dataset, batch_size, random_seed, valid_size=0.1, test_size=0.1):
"""
Creates training, validation and testing pytorch dataloaders to be used for training.
:param dataset: raw dataset in ndarray format
:param batch_size: batch_size
:param random_seed: for reproducible results
:pa... | The main task of the code is to train a neural network model using specified hyperparameters, evaluate its performance on test data, and save the best model. It loads a dataset, initializes a three-layer classifier, uses SGD with optimized learning rate and momentum, trains for 100 epochs, tracks loss curves, computes ... | def train_save_model():
"""
Used to be the main function. Instantiates a model, trains it with the provided hyper parameters,
evaluates it and saves it. This function has been used to save our best model
"""
data_path = "ROI_dataset.dat"
# Parameters
EPOCH_NUMBER = 100
batch_size = 16
... |
def split_data(dataset, valid_size = 0.2, test_size = 0.2):
'''
Splits the input data into three datasets.
The output datasets are as following: the first one for training,
the next one for validation, and the last one for testing.
The output also converts the data in tensors and separate... | The code trains a neural network using optimal hyperparameters from a grid search on a dataset, evaluates its performance on validation and test sets, and saves the trained model. It loads data, splits into training/validation/test sets, initializes a MultiRegression model with SGD optimizer, trains over 100 epochs, tr... | def save_main_model():
'''
Former main function to solve the given problem.
Trains a neural network on the training set with the best hyperparameters
given by the grid search in order to create a model.
Computes interesting metrics on the validation set and the testing set
with the final... |
def split_data(dataset, valid_size = 0.2, test_size = 0.2):
'''
Splits the input data into three datasets.
The output datasets are as following: the first one for training,
the next one for validation, and the last one for testing.
The output also converts the data in tensors and separate... | The code performs a grid search to optimize the learning rate and momentum hyperparameters for a neural network. It trains the model on the training data for a specified number of epochs, evaluates performance using mean squared error (MSE) on the validation set, and retains the hyperparameter combination yielding the ... | def grid_search(epochs = 100, batch_size = 25):
'''
Performs a grid search to tune the learning rate and the momentum.
For a given number of epochs and of batch_size, the function will return
the best set of parameters and the best MSE.
'''
dataset = np.loadtxt("FM_dataset.dat")
# Set s... |
def create_ax(self,fig):
ax = Axes3D(fig)
self.config_ax(ax)
return ax
def config_ax(self, ax):
ax.set_xlim3d(-1000,1000)
ax.set_ylim3d(-1000,1000)
ax.set_zlim3d(-1000,1000)
ax.set_aspect('equal', 'box')
def plot_conf(self, ax, angular_positions):
conf=sel... | This function animates the transition of a robotic configuration from an initial angle to an end angle over 100 frames. It clears and updates the plot for each frame, interpolating angles linearly. If provided, it visualizes a predicted position as a scatter point. The animation pauses briefly between frames to display... | def animate(self, angle_init,angle_end, ax = None, predicted_pos=None):
T=100;
if (ax==None):
fig = plt.figure()
ax = self.create_ax(fig)
for t in range(T):
ax.clear()
self.config_ax(ax)
self.plot_conf(ax,angle_init + t/T * (a... |
def load_config(root: str = ".") -> ConfigParser:
"""Load configuration from file."""
config = ConfigParser()
config.read_dict(DEFAULT_CONFIG)
config.read(os.path.join(root, CONFIG_FILE_NAME))
return config
def _load_service_context(config: ConfigParser) -> ServiceContext:
"""Internal function t... | This function loads an existing index file based on configuration settings. It determines the index type (VectorStoreIndex, SimpleKeywordTableIndex) from the config, attempts to load it from storage, and creates a new index with default storage if loading fails. The index is returned after handling configuration, servi... | def load_index(root: str = ".") -> BaseIndex[Any]:
"""Load existing index file."""
config = load_config(root)
service_context = _load_service_context(config)
# Index type
index_type: Type
if config["index"]["type"] == "default" or config["index"]["type"] == "vector":
index_type = Vector... |
def draw_navigation_buttons(current_slide, total_slides):
next_button_rect = pygame.Rect(WIDTH - 150, HEIGHT - 70, 120, 50)
prev_button_rect = pygame.Rect(30, HEIGHT - 70, 120, 50)
action = None
if current_slide < total_slides - 1:
if draw_button(next_button_rect, "Next"):
action = ... | This code presents a gesture tutorial using Pygame, displaying slides with text/images, allowing navigation, and tracking user gesture practice (catcher/target) success counts. It initializes slides, handles user input for navigation, detects gestures, updates counters, and displays progress until the tutorial conclude... | def main():
clock = pygame.time.Clock()
slides = [
Slide(text="Invisible Bruin Gesture Tutorial", image_path='/Users/johannabai/Desktop/Team-6/tutorial_media/cover.jpeg', image_size=(869, 512)),
Slide(text="Time to practice doing gestures!"),
Slide(text="Catcher Gesture", image_path='/Us... |
def train(self):
for epoch in range(self.current_epoch, self.config.max_epoch):
self.current_epoch = epoch
start = datetime.now()
self.train_one_epoch()
val_loss = self.validate(start)
self.scheduler.step(val_loss)
self.save_checkpoint()
... | The code executes cross-validation experiments by iterating through predefined data folds, training a model on each fold, evaluating it, and aggregating results. It loads data for each fold, trains the model, tests using the best checkpoint, and logs execution time. After all folds, it collects prediction files, comput... | def run(self):
if self.config.mode == 'test':
pass
elif self.config.mode == 'cross-validation':
# cross valid experiments data split root.
self.cross_fold = glob(os.path.join(self.config.CV_ROOT, 'fold*'))
self.cross_fold.sort()
st... |
def get_opt(args=None):
parser = argparse.ArgumentParser(description="High Background event finder")
parser.add_argument("--start",
help='Start date')
parser.add_argument("--data-root",
default="/proj/sot/ska/data/aca_hi_bgd_mon",
help=... | The main task of the code is to monitor for high background (HI BGD) events in observational data, update an archive file with detected events, generate reports, and notify users via email. It loads existing event records, filters invalid entries, fetches new events from a specified start time, logs warnings for signif... | def main():
"""
Review kadi dwells for new high background events, update a text file table of
those events, make reports, and notify via email as needed.
"""
global logger
opt = get_opt()
logger = pyyaks.logger.get_logger(level=opt.log_level)
EVENT_ARCHIVE = os.path.join(opt.data_root... |
def calc_all(self):
self.generate_expect()
return None
def generate_densities(self, density0=None, output_type='numpy'):
if density0 is None:
density0 = self.density0
if density0 is None:
raise Exception('No initial density given')
if self.kdshmap_list... | (This code initializes a quantum dynamics simulation object, setting up parameters for time evolution with noise. It computes propagators, generates time-dependent states/densities, and handles tasks like error calculation, expectation values, or filter functions based on the specified 'goal'. The class manages both ti... | def __init__(self,
H: Union[list, q.qobj.Qobj],
t_list_sub: np.ndarray,
minimal_step: float,
noise_ops: Union[list, q.qobj.Qobj],
f_list: Union[list, np.ndarray],
Sf_list: Union[list, np.ndarray],
dens... |
def generate_path(q0, q1):
x, y, phi = change_of_basis(q0, q1)
paths = []
paths = CSC(x, y, phi, paths)
paths = CCC(x, y, phi, paths)
paths = CCCC(x, y, phi, paths)
paths = CCSC(x, y, phi, paths)
paths = CSCC(x, y, phi, paths)
paths = CCSCC(x, y, phi, paths)
return paths
def genera... | The function `reeds_shepp_path_planning` computes the optimal path between a start and goal configuration (positions and orientations) using Reeds-Shepp curves. It generates candidate paths, sorts them by length, and selects the shortest path with minimal maneuvers. If multiple paths have similar lengths, the one with ... | def reeds_shepp_path_planning(sx, sy, syaw, gx, gy, gyaw):
'''
Given start and end points, returns the best - optimal path
:param sx:
:param sy:
:param syaw:
:param gx:
:param gy:
:param gyaw:
:return:
'''
q0 = [sx, sy, syaw]
q1 = [gx, gy, gyaw]
paths = generate_... |
def generate_path(q0, q1):
x, y, phi = change_of_basis(q0, q1)
paths = []
paths = CSC(x, y, phi, paths)
paths = CCC(x, y, phi, paths)
paths = CCCC(x, y, phi, paths)
paths = CCSC(x, y, phi, paths)
paths = CSCC(x, y, phi, paths)
paths = CCSCC(x, y, phi, paths)
return paths
def genera... | The function `reeds_shepp_path_planningq` computes the optimal Reeds-Shepp path between a start and end point, considering both path length and maneuver complexity. It generates candidate paths, sorts them by length, and selects the shortest valid path. If two paths are nearly equal in length, the one with fewer maneuv... | def reeds_shepp_path_planningq(q0, q1):
'''
Given start and end points, returns the best - optimal path
# q0 = [sx, sy, syaw]
# q1 = [gx, gy, gyaw]
:return:
'''
# q0 = [sx, sy, syaw]
# q1 = [gx, gy, gyaw]
paths = generate_path(q0, q1)
if not paths:
# print(... |
def getParamsFromTakesData(takes_data, cm):
indx = 0
for line in takes_data:
if ( lib.DEBUG == True):
print("Index =" + str(indx))
if (line != '\n'):
line_in = ' '.join(line.split())
if (line_in != ""):
paramValList = line_in.split('=')
... | The main task of the code is to manage a GUI-driven workflow for processing 3D vision data, offering options to configure parameters, run/harvest data, spread files, manage settings, view results, and exit. It handles input/output directories, takes data, and user interactions via menus, logging operations and executin... | def main_loop(input_location, output_location, lord_takes_location,remote_location,config_param,nuc_param):
snbrnumber = ""
current_dir = ""
choice_prev = []
takes_data = []
takes_data = lib.create_takes_data(lord_takes_location)
if (lib.DEBUG == True):
current_dir = "/".join(__... |
def stop_test_processing(state):
running_time = lib.get_running_time()
line_out = "Running time : " + str(running_time) + " sec"
print(line_out)
logger.info(line_out)
if (lib.DEBUG == True):
stop_time = round(time.time(), 4)
lib.send_run_time_command("end", stop_time, "TimeEnd... | The main task of the code is to parse command-line arguments for input/output directories and configuration files, load JSON parameters, and either launch a GUI or execute a system manager process. It processes flags like `-i`, `-o`, `-l` for directories, `-g` for GUI mode, and `-h` for help. Configuration files (`DEVI... | def main(argv):
input_dir = ''
output_dir = ''
lord_dir = ''
opts = ''
config_param = []
nuc_param = []
run_gui_mode = False
program_name = sys.argv[0]
try:
opts, args = getopt.getopt(argv, "ghi:o:l:", ["idir=", "odir=","dfgfile="])
except getopt.GetoptError:
line... |
def go_to_joint_state(self, angles):
joint_goal = self.move_group.get_current_joint_values()
joint_goal[0] = angles[0]
joint_goal[1] = angles[1]
joint_goal[2] = angles[2]
joint_goal[3] = angles[3]
joint_goal[4] = angles[4]
joint_goal[5] = angles[5]
# The go command can be called with jo... | The code controls a robotic arm to perform object pickup and placement tasks. It moves the end-effector to predefined positions, uses vision data for navigation, manipulates objects via a vacuum gripper, and handles multiple items through user inputs. Key steps include Cartesian path planning, joint state control, and ... | def top(self, amount_top):
self.amount_top = amount_top
print(self.amount_top)
print("Look location")
goal = [-1.2366639760050704, -3.3107352079934733, -1.8473003610545498, 0.445423184989181, -1.5702576591461013, 2.806662295774252]
self.go_to_joint_state(goal)
input("next") #after ... |
def trigger_intent(intent, session):
""" Gets the values from the session and prepares the speech to reply to the
user.
"""
card_type = 'Simple'
card_title = intent['name']
session_attributes = {}
should_end_session = True
if 'value' in intent['slots']['dataone']:
dataone = inte... | The code handles user intents by logging request/session details, dispatching to specific intent handlers (e.g., "TriggerIntent"), and managing built-in intents like Help/Cancel/Stop. It raises an error for unrecognized intents. | def on_intent(intent_request, session):
""" Called when the user specifies an intent for this skill """
print("on_intent requestId=" + intent_request['requestId'] +
", sessionId=" + session['sessionId'])
intent = intent_request['intent']
intent_name = intent_request['intent']['name']
# ... |
def on_session_started(session_started_request, session):
""" Called when the session starts """
print("on_session_started requestId=" + session_started_request['requestId']
+ ", sessionId=" + session['sessionId'])
def on_launch(launch_request, session):
""" Called when the user launches the skil... | The code routes incoming Alexa requests to appropriate handlers based on request type (Launch, Intent, Session End) after validating the application ID to ensure the request originates from the authorized skill. | def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
print("event.session.application.applicationId=" +
event['session']['application']['applicationId'])
"... |
def spawn(self, count):
for i in range(0, count):
c = randint(1, 4)
if c == 1:
s = randint(1, 2)
if s == 1:
self.spawnPlane("Red", "Big")
else:
self.spawnPlane("Red", "Small")
elif c == 2:... | This code manages enemy spawning in waves by incrementing a timer, spawning enemies when the timer exceeds a delay, tracking wave progression, updating player score based on wave number, and adjusting spawn limits. It also updates enemy behavior and removes dead enemies. | def update(self, delta, player):
self.spawnTimer += delta
if self.spawnTimer > self.spawnDelay:
self.spawn(randint(1, self.maxSpawns))
self.spawnTimer = 0
self.spawnCount += 1
if self.spawnCount >= self.spawnsPerWave:
self.spawnCount = 0
... |
def create_demand_perm():
matchings = np.random.permutation(total_num_servers)
if demand_type == "big_small":
demands = 100*np.ones(total_num_servers)
for i in range(0, total_num_servers, int(k/2)):
demands[i] += (int(k/2)-1)*900
else:
demands = 1000*np.ones(total_num_servers)
return (matchings, demand... | The main task of the code is to generate demand permutations using `create_demand_perm()`, then create an INI configuration file and routes file based on these permutations via `create_ini_file()` and `create_routes_file()`, respectively. | def main():
matchings_demands = create_demand_perm()
create_ini_file(matchings_demands)
create_routes_file(matchings_demands) |
def infonce_lower_bound(scores):
nll = scores.diag().mean() - scores.logsumexp(dim=1)
# Alternative implementation:
# nll = -tf.nn.sparse_softmax_cross_entropy_with_logits(logits=scores, labels=tf.range(batch_size))
mi = torch.tensor(scores.size(0)).float().log() + nll
mi = mi.mean()
return mi
d... | This function estimates mutual information between tensors x and y using variational lower bounds. It employs a specified estimator (e.g., InfoNCE, NWJ, TUBA) and a critic function to compute pairwise scores. Optional baselines and parameters refine the estimate. The method returns a scalar mutual information value, le... | def estimate_mutual_information(estimator, x, y, critic_fn,
baseline_fn=None, alpha_logit=None, **kwargs):
"""Estimate variational lower bounds on mutual information.
Args:
estimator: string specifying estimator, one of:
'nwj', 'infonce', 'tuba', 'js', 'interpolated'
... |
def get_input(self):
return input()
def buy(self):
print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino:\n")
n = self.get_input()
if n == "back":
return
if n == "1":
self.make_coffee(16, 250, 0, 1, 4)
if n == "2":
sel... | This code manages a coffee machine's operations via a command-line interface, allowing users to perform actions like buying coffee, filling supplies, taking money, checking machine status, or exiting. It runs a loop that repeatedly prompts for input and executes corresponding methods until the user selects 'exit' | def coffee_mode(self):
running = True
while running:
print("Write action (buy, fill, take, remaining, exit):\n")
action = self.get_input()
if action == "buy":
print()
self.buy()
print()
if action == "fill":
... |
def paint_shader(self,genomes):
improved = False
theBestCopy = []
error_results = []
# for genome in genomes:
self.shader_painter.load_texture_from_array(self.img)
for genome in genomes:
translations,rotations,colors,brush_size = self.decode_for_shader(genome... | This function evolves genomes through iterative improvement by evaluating error scores, mutating genomes when no improvement is detected, and returning optimized genomes after final processing. It uses a loop to refine genomes until convergence, then applies a final mutation and selects the best genome. | def epoch(self,epoch,genomes,population):
improved = False
# errorScores = self.paint(genomes)
while not improved:
if self.shader:
errorScores,improved = self.paint_shader(genomes)
else:
errorScores,improved = self.paint(genomes)
... |
def get_local_datetime(iso_date: str):
return datetime.strptime(iso_date, '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc).astimezone(tz=None)
def get_fresh_aggregate_stats(aggregation_types: List[AggregationType]) -> AggregrateStats:
return AggregrateStats(
total_pages=0,
aggregations={
... | The function aggregates incident data by day, counting occurrences of specified aggregation types (e.g., incident categories) for each date within a given date range. It initializes daily statistics, updates counts based on incident attributes, fills gaps for missing dates, and optionally limits custom incident type co... | def get_stats_by_day(
incidents: List[Dict],
start_date: str,
end_date: str,
aggregation_types: List[AggregationType],
max_incident_types: int,
incident_type_extraction_technique: ExtractionTechnique
) -> Dict[str, AggregrateStats]:
incidents_by_day: Dict[str, AggregrateStats] = {}
for ... |
def getDbConfig () :
return {
'database': os.getenv('PG_DB', 'postgres'),
'user': os.getenv('PG_USER', 'postgres'),
'password': os.getenv('PG_PASSWORD', ''),
'host': os.getenv('PG_HOST', 'localhost'),
'port': int(os.getenv('PG_PORT', '5432')),
}
def prepareDatabase (c... | The main task of the code is to connect to a PostgreSQL database using configuration details, prepare the database structure, import data from a CSV file ('worldcities.csv') into the database, and then close the database connection. It retrieves database settings, establishes a connection, executes preparatory steps, l... | def main () :
dbConf = getDbConfig()
dbConnection = pg.connect(**dbConf)
prepareDatabase(dbConnection)
fromCsvToDatabase('./worldcities.csv', dbConnection)
dbConnection.close() |
def build_upload_tab(tab1):
with tab1:
st.write("Upload Videos to the Database")
folder_path = st.text_input("Enter the video folder path")
if st.button("Upload"):
folder = os.listdir(folder_path)
bar = st.progress(0)
# threads = []
for video... | The code defines a Streamlit web app for video search, creating three tabs: "Upload" for video uploads, "Search" for text-based video queries, and "Database" for managing stored videos. The main function initializes the app's title, description, and tab structure, delegating tab-specific logic to separate functions. It... | def main():
st.title("Video Search App")
st.write("Welcome to the Video Search App." +
" You can search for videos using text queries.")
tab1, tab2, tab3 = st.tabs(["Upload", "Search", "Database"])
build_upload_tab(tab1)
build_search_tab(tab2)
build_data_tab(tab3)
return |
def get_final_charge(data):
natoms = get_nbas(data)
key = "charges: old"
natoms = get_nbas(data)
charge_data = get_lines(data, key, natoms + 1, return_index=False)[-1]
screen_charge = float(charge_data[1:][0].split()[2])
final_charges = [float(i.split()[3]) for i in charge_data[1:][1:]]
... | The code constructs a crystal structure object from input data by assembling lattice parameters, atomic species, fractional coordinates, and charge properties into a `Structure` instance, using charge data derived from the input. | def make_structure(data):
screen_charge, charge_dict = get_final_charge(data)
return Structure(lattice=get_lattice(data),
species=get_z(data, get_nbas(data)),
coords=get_atomicpos(data, frac=True),
coords_are_cartesian=False,
c... |
def make_iterations(data):
'''
make an iteration object to hold information
'''
iterations = []
for i in range(get_iter(data)):
dummy = DotMap()
dummy.niter = i
iterations.append(dummy)
return iterations
def get_nbas(data):
'''
Extract number of atoms
'''
... | The function `get_charges` extracts and organizes charge-related data (old, new, screened, RMS, and difference charges) for each iteration from input data. It processes atomic species and iterates through charge information lines, structuring results into a `DotMap` for each iteration. If no iterations are provided, it... | def get_charges(data, iterations=None):
'''
get charge data for each iterations
'''
if iterations is None:
iterations = make_iterations(data)
for j in range(len(iterations)):
iter_i = iterations[j].niter
key = "charges: old"
natoms = get_nbas(data)
iter_... |
def get_data(fname="output"):
try:
with open(fname, 'r') as f:
data = f.read()
return data
except IOError:
print("file not found")
def make_iterations(data):
'''
make an iteration object to hold information
'''
iterations = []
for i in range(get_iter(data)... | The code initializes a class to process simulation data from an output file, extracting structural information, energy values (like HF and HK energies), and band gap data from the last iteration of calculations. It sets up atomic species, structure, and iteration-based energy and band data for analysis. | def __init__(self, output_file="output"):
self.fname = output_file
self.data = get_data(self.fname)
self.iterations = make_iterations(self.data)
# self.natoms=get_nbas(self.data)
# self.nbas=self.natoms
#---finding and setting up structure
self.species = get_spec... |
def factorization_list(largest_num):
"""
Prime factorize every number up to the largest number
and return a list of each prime factorization
input = 5
output = [ {2:1}, {3:1}, {2:2}, {5,1} ]
"""
prime_list = []
for i in range(2,largest_num+1):
prime_dict = greatest_power(prime_... | The code calculates the least common multiple (LCM) of numbers 1 to 20 by determining the highest prime exponents in their factorizations. It first generates prime factors for numbers up to 20, identifies maximum exponents for each prime, then multiplies these primes raised to their highest exponents to compute the LCM... | def main():
print("jese")
top_check = 20
#prime_list = prime_factorization(top_check,[])
#greatest_power(prime_list)
fact_list = factorization_list(top_check)
final_dict = highest_exponent(fact_list)
print(multiply_primes(final_dict)) |
def get_frequent_item_sets(self, minSupport):
self.apriori(minSupport)
toRetItems = []
for key, value in self.largeSet.items():
toRetItems.extend([(tuple(item), self.getSupport(item)) for item in value])
return toRetItems
def get_arules(self, minConfidence):
toRetRule... | The code initializes an object to mine frequent itemsets and association rules from transaction data. It first identifies frequent itemsets using a minimum support threshold, then generates association rules based on a minimum confidence threshold. Finally, it prints the results, combining both frequent itemsets and de... | def __init__(self, minSupport, minConfidence):
items = self.get_frequent_item_sets(minSupport)
rules = self.get_arules(minConfidence)
self.printResults(items, rules) |
def routeLengthGeoJSON(route):
route_length = 0
for section in route:
route_length += routeLength(section['coordinates'])
return route_length
def centerMapByPoints(gps_points):
return [51.5225776,-0.1214206]
def createPopup(idx,point):
title = point['properties']['title']
address = poin... | The code generates an interactive map using folium, plotting GPS points from ordered_features as markers, overlaying a red route (nn_route), and GeoJSON segments from geometry. It calculates and displays route lengths, saves the map as an HTML file, and opens it in a browser for visualization. | def generateMap(ordered_features,nn_route,geometry):
routeLengthOpenRoute = routeLengthGeoJSON(geometry)
# Create a map centered at a specific location
map_center = centerMapByPoints(gps_points=ordered_features) # Replace latitude and longitude with your GPS data
map_zoom = 13 # Adjust the zoom level ... |
def gaussian_pyramid(image, levels):
"""
Builds a Gaussian pyramid for an image with the given number of levels, then return it.
Inputs:
image: a numpy array (i.e., image) to make the pyramid from
levels: how many levels to make in the gaussian pyramid
Returns:
An array of images... | The main task of the code is to refine an initial displacement between two images (H and I) using an iterative Lucas-Kanade method on a Gaussian pyramid with multiple levels. It builds pyramids for both images, scales the initial displacement to the coarsest level, and iteratively computes and accumulates refined displ... | def pyramid_lucas_kanade(H, I, initial_d, levels, steps):
"""Given images H and I, and an initial displacement that roughly aligns H
to I when applied to H, run Iterative Lucas Kanade on a pyramid of the
images with the given number of levels to compute the refined
displacement."""
initial_d = np.a... |
def pyramid_lucas_kanade(H, I, initial_d, levels, steps):
"""Given images H and I, and an initial displacement that roughly aligns H
to I when applied to H, run Iterative Lucas Kanade on a pyramid of the
images with the given number of levels to compute the refined
displacement."""
initial_d = np.a... | The code refines initial displacements between consecutive images using Pyramid Iterative Lucas Kanade (PILK) to align them, then constructs a mosaic panorama. If displacements aren't provided, it computes them iteratively, saves the results, and calculates the panorama's dimensions and starting position. Finally, it s... | def mosaic(images, initial_displacements, load_displacements_from):
"""Given a list of N images taken in clockwise order and corresponding
initial X/Y displacements of shape (N,2), refine the displacements and
build a mosaic.
initial_displacement[i] gives the translation that should be appiled to
i... |
def cal_max_speed(self, frame, CC, CS, sm, clu11_speed, controls):
limit_speed, road_limit_speed, left_dist, first_started, max_speed_log = road_speed_limiter_get_max_speed(CS, controls.v_cruise_kph)
self.cal_curve_speed(sm, clu11_speed * CV.KPH_TO_MS, frame)
if self.slow_on_curves and self.curve_speed >=... | The code updates cruise control parameters by calculating road speed limits, managing state transitions between stock and custom control, and sending CAN messages for adaptive cruise control. It adjusts target speeds, handles button inputs, and manages timers for system resets and signal transmission, ensuring complian... | def update(self, enabled, can_sends, packer, CC, CS, frame, apply_accel, controls):
clu11_speed = CS.clu11["CF_Clu_Vanz"]
road_limit_speed, left_dist, max_speed_log = self.cal_max_speed(frame, CC, CS, controls.sm, clu11_speed, controls)
CC.sccSmoother.roadLimitSpeed = road_limit_speed
CC.sccSmoother.ro... |
def generate_result_string(result):
resultstring = ""
# dont take more than 3 results, exclude results if there are more than 3
if len(result) > 3:
result = result[:3]
if len(result) == 1:
if any(char.isalpha() for char in result[0]):
resultstring = "Only one vanity phone n... | The code processes a phone number from an event, extracts its last 10 digits, checks DynamoDB for existing records, updates timestamps if found, or generates results by converting the number to text, sorting combinations, selecting top unique entries, and storing them. It returns the top 5 results as a formatted string... | def lambda_handler(event, context):
logger.info("Received event: %s", event)
try:
number = event['Details']['ContactData']['CustomerEndpoint']['Address']
# get the last 10 digits of the number
number = number[-10:]
existing_item = table.get_item(Key={'callerNumber': number})
... |
def check_keydown_events(self,event):
""""responding to key presses"""
if event.key == pygame.K_RIGHT:
self.spaceShip.moving_right = True
elif event.key == pygame.K_LEFT:
self.spaceShip.moving_left = True
# pressing q to exit
elif event.key == pygame.K_q:
... | The function `_check_events` processes keyboard and mouse events in a Pygame application. It exits the game on the QUIT event, delegates key presses to `check_keydown_events`, key releases to `check_keyup_events`, and mouse clicks to `check_play_button` with the mouse position. It centralizes event handling to manage u... | def _check_events(self):
""""Respond to keyboard and mouse events"""
for event in pygame.event.get():
# exits the game
if event.type == pygame.QUIT:
sys.exit()
# Key is pressed
elif event.type == pygame.KEYDOWN:
self.check_k... |
def check_fleet_edges(self):
for alien in self.aliens.sprites():
if alien.check_edges():
self.change_fleet_direction()
break
def spaceShip_hit(self):
if self.stats.spaceShips_left > 0:
self.stats.spaceShips_left -= 1
self.sb.prep_spaceS... | The code updates alien positions by first checking fleet edges, then updating their movement. It detects collisions between aliens and the spaceship, triggering a hit response if detected. Finally, it checks if any aliens have reached the bottom of the screen, likely for game-over logic. The function manages alien beha... | def update_aliens(self):
"""checks edges first and then updates position"""
self.check_fleet_edges()
self.aliens.update()
# Looking for alien and spaceship collision
if pygame.sprite.spritecollideany(self.spaceShip, self.aliens):
self.spaceShip_hit()
self.che... |
def _check_events(self):
""""Respond to keyboard and mouse events"""
for event in pygame.event.get():
# exits the game
if event.type == pygame.QUIT:
sys.exit()
# Key is pressed
elif event.type == pygame.KEYDOWN:
self.check_k... | The code runs a game loop that continuously checks for events, updates game elements (spaceship, bullets, aliens) if the game is active, and updates the screen to render the current game state. | def run(self):
while True:
# checking for the events
self._check_events()
if self.stats.game_active:
self.spaceShip.update()
self.update_bullets()
self.update_aliens()
self._update_screen() |
def execute_search(query, indexer, preprocessor, rel_songs):
"""
Checks, which type of search has to be done.
Executes the search and returns the resulting, relevant doc_ids and tfs for those
:param query: The query which should be searched for (str)
:param indexer: Class instance for the created in... | The function `execute_queries_and_save_results` processes a search query using boolean or TF-IDF methods, combines results with popularity scores (if configured), scales scores for clarity, and returns ranked document IDs with scores. It logs timestamps, saves results to a CSV (if enabled), and generates evaluation dat... | def execute_queries_and_save_results(query, indexer, preprocessor, config, SongModel, ArtistModel, rel_songs,
query_num = None):
"""
Function to execute search and return results
:param query: Query that should be searched (str)
:param indexer: Class instance for the... |
def generate_keys(request, username):
the_user = User.objects.get(username=username).pk
key1 = key_pair1.objects.get(user= the_user)
key2 = key_pair2.objects.get(user= the_user)
prime_list = primesInRange(17,2000)
p = random.choice(prime_list)
prime_list = primesInRange(2001,5000)
q = ra... | The main task of the code is to validate a 4-digit OTP received via POST request, create a new user account with stored session data (username, email, password), authenticate the user, initialize account components (balance, notifications, key pairs), and redirect to the home page upon successful OTP verification. If O... | def OTP(request):
if request.method == "POST":
# OTP VALUE
val1 = request.POST['val1']
val2 = request.POST['val2']
val3 = request.POST['val3']
val4 = request.POST['val4']
OTP_receive = str(val1) + str(val2) + str(val3) + str(val4)
# SESSION VALUES
us... |
def cross(v1, v2):
return V3(
v1.y * v2.z - v1.z * v2.y,
v1.z * v2.x - v1.x * v2.z,
v1.x * v2.y - v1.y * v2.x,
)
def sub(v0, v1):
"""
Input: 2 size 3 vectors
Output: Size 3 vector with the per element substraction
"""
return V3(v0.x - v1.x, v0.y - v1.y, v0.z -... | The code loads a 3D model from an .obj file, applies scaling and translation to vertices, calculates face normals, computes lighting intensity based on a directional light, and renders triangles with grayscale shading. It handles both triangular and quadrilateral faces by splitting quads into two triangles, using cross... | def load(self, filename='default.obj', translate=[0,0], scale=[1,1]):
model = Obj(filename)
light = V3(0, 0, 1)
for face in model.faces:
vcount = len(face)
if vcount == 3:
face1 = face[0][0] - 1
face2 = face[1][0] - 1
fac... |
def check_is_user_banned(self, temp_username=None):
if temp_username:
for row in users_db_ws.iter_rows(users_db_ws.min_row, users_db_ws.max_row + 1):
for cell in row:
if str(cell.value) == temp_username:
temp_user_row = str(cell.row)
... | The main task of the code is to handle user login authentication, including checking banned status, managing failed login attempts (banning after 3 failures), allowing password recovery, and validating credentials. It ensures users are banned if they exceed attempt limits, logs actions, and provides a session-quit mech... | def loginPage(self):
while True:
if self.failed_attempted >= 3 and self.username != '':
users_db_ws['H' + self.user_row].value = 'T'
users_db.save('Users.xlsx')
add_record(self.username, 'banned', '3 failed attempts',
'User B... |
def get_joint_prior_matrix(prior_R, prior_H):
"""
Given priors in P(R) and P(H)
Get a joint belief matrix for P(H,R)
"""
joint_prior_matrix = np.array([
[prior_H*prior_R, (1-prior_H)*prior_R],
[prior_H*(1-prior_R), (1-prior_H)*(1-prior_R)],
])
return joint_prior_matrix
def get_rational_posterior_matrix_give... | The code computes and visualizes the diagnosticity of three models (Simple, Rational, BIASR) when updating beliefs with confirmatory (M1 = [1,1,1,1,1]) and disconfirmatory (M2 = [0,0,0,0,0]) evidence. It plots diagnosticity values over 6 observations and compares their for/against ratios, illustrating how each model's ... | def plot_selection_sources(prob_H, prob_R, prob_true_R, prob_true_not_R,):
"""
Compute diagnosticity of two sources, one for and one against
"""
fig = plt.figure()
M1 = [1,1,1,1,1]
rational_joint_prob_matrix = get_joint_prior_matrix(prob_R, prob_H)
indy_joint_prob_matrix = get_joint_prior_matrix(prob_R, prob... |
def get_joint_prior_matrix(prior_R, prior_H):
"""
Given priors in P(R) and P(H)
Get a joint belief matrix for P(H,R)
"""
joint_prior_matrix = np.array([
[prior_H*prior_R, (1-prior_H)*prior_R],
[prior_H*(1-prior_R), (1-prior_H)*(1-prior_R)],
])
return joint_prior_matrix
def get_diagnosticity_of_question(prob... | The code tests the diagnosticity and expected information gain of a question using predefined probabilities (prob_R=0.8, prob_H=0.8) and a joint prior matrix. It calculates diagnosticity (diag) and information gain (info) by comparing true probabilities (prob_true_R=0.75, prob_true_not_R=0.5) with the joint distributio... | def test_information_gain():
prob_R = 0.8
prob_H = 0.8
joint_prob_matrix = get_joint_prior_matrix(prob_R, prob_H)
diag = get_diagnosticity_of_question(prob_true_R=0.75, prob_true_not_R=0.5, joint_prob_matrix=joint_prob_matrix)
print("Diag is ", diag)
information = get_expected_information_gain_of_source(prob_t... |
def plot_biased_assimilation_and_evaluation_joint_distribution(prob_H, prob_R, prob_true_R, prob_true_not_R, M=[1,1,1,1,1]):
fig_width, fig_height = plt.gcf().get_size_inches()
fig = plt.figure(figsize=(fig_width*1.5, fig_height*1.5), constrained_layout=True)
rational_joint_prob_matrix = get_joint_prior_matrix(pr... | The main task of the code is to generate visualizations of cognitive bias simulations, including biased assimilation, evaluation, attitude polarization, and belief perseverance. It uses predefined probability parameters to plot joint distributions, attitude dynamics, and source selection effects under varying condition... | def plot_all_simulations():
prob_H = 0.8
prob_R = 0.5
prob_true_R = 0.75
prob_true_not_R = 0.5
plot_biased_assimilation_and_evaluation_joint_distribution(prob_H=prob_H, prob_R=prob_R, prob_true_R=prob_true_R, prob_true_not_R=prob_true_not_R, M=[1,1,1,1,1])
plot_biased_assimilation_and_evaluation_joint_distribut... |
def get_joint_prior_two_sources(prior_H, prior_R_a, prior_R_b):
joint_prior_tensor = np.empty(shape=(2,2,2))
p_H = [1-prior_H, prior_H]
p_R_a = [1-prior_R_a, prior_R_a]
p_R_b = [1-prior_R_b, prior_R_b]
for H in [0,1]:
for R_a in [0,1]:
for R_b in [0,1]:
joint_prior_tensor[H, R_a, R_b] = p_H[H] * p_R_a... | This function replicates Bayesian updating of joint probability distributions (H, R) across three models—rational, independent, and simple—using repeated data updates. It initializes priors with given probabilities, iterates through data points, and applies model-specific posterior updates. The results show how each mo... | def replicate_biased_evaluation_and_assimilation():
"""
Replicate the results from one source using the two source machinery
"""
prob_H = 0.8
prob_R = 0.5
rational_joint_prob = get_joint_prior_two_sources(prob_H, prob_R, prob_R)
indy_joint_prob = get_joint_prior_two_sources(prob_H, prob_R, prob_R)
simple_join... |
def get_entropy(joint_prob_dist):
prob_H = np.sum(joint_prob_dist, axis=(1,2))
entropy = 0
for H in [0,1]:
if prob_H[H] != 0:
entropy += - prob_H[H] * np.log(prob_H[H])
return entropy
def get_prob_D_rational(prior, D, source):
unnormed_posterior = get_unnormed_posterior_rational(prior, D, source)
return ... | This function calculates the expected information gain by comparing the current entropy of a joint probability distribution with the expected entropy after updating the distribution based on the specified update type (rational, indy, or simple). It iterates over possible states (D=0,1), computes posterior distributions... | def get_expected_information_gain(joint_prob_dist, update_type="rational", source="A"):
current_entropy = get_entropy(joint_prob_dist)
expected_entropy = 0
prob_R = 0.5
for D in [0,1]:
if update_type == "rational":
prob_D = get_prob_D_rational(joint_prob_dist, D, source)
posterior_given_D = get_posteri... |
def get_prob_D_rational(prior, D, source):
unnormed_posterior = get_unnormed_posterior_rational(prior, D, source)
return np.sum(unnormed_posterior)
def get_unnormed_posterior_rational(prior, D, source):
likelihood = get_likelihood_tensor(D=D, D_from=source)
return np.multiply(prior, likelihood)
def get_prob_D_i... | The function calculates the diagnosticity of a question by evaluating the absolute log of likelihood ratios for two hypotheses (0 and 1) under specified update types (rational, indy, simple). It computes these ratios using joint probability distributions and unnormalized posteriors, weights them by the probability of e... | def get_diagnosticity_of_question(joint_prob_dist, update_type="rational", source="A"):
diagnosticity_of_question = 0
for D in [0, 1]:
if update_type == "rational":
prob_D = get_prob_D_rational(joint_prob_dist, D, source)
unnormed_posterior = get_unnormed_posterior_rational(joint_prob_dist, D, source)
el... |
def get_joint_prior_two_sources(prior_H, prior_R_a, prior_R_b):
joint_prior_tensor = np.empty(shape=(2,2,2))
p_H = [1-prior_H, prior_H]
p_R_a = [1-prior_R_a, prior_R_a]
p_R_b = [1-prior_R_b, prior_R_b]
for H in [0,1]:
for R_a in [0,1]:
for R_b in [0,1]:
joint_prior_tensor[H, R_a, R_b] = p_H[H] * p_R_a... | The code computes and visualizes the expected information gain of two sources (for and against) under three models: simple, rational, and BIASR. It updates joint probability distributions iteratively based on message sequences, plots gain trends over observations, and compares for/against gain ratios across models. The... | def plot_selection_sources_with_information_gain(prob_H=0.8, prob_R=0.5):
"""
Compute exected information gain of two sources, one for and one against
"""
fig = plt.figure()
M = [1,0] * 5
sources = ["A", "B"] * 5
rational_joint_prob = get_joint_prior_two_sources(prob_H, prob_R, prob_R)
indy_joint_prob = get_... |
def get_joint_prior_two_sources(prior_H, prior_R_a, prior_R_b):
joint_prior_tensor = np.empty(shape=(2,2,2))
p_H = [1-prior_H, prior_H]
p_R_a = [1-prior_R_a, prior_R_a]
p_R_b = [1-prior_R_b, prior_R_b]
for H in [0,1]:
for R_a in [0,1]:
for R_b in [0,1]:
joint_prior_tensor[H, R_a, R_b] = p_H[H] * p_R_a... | This code computes and visualizes the diagnosticity of three different models (Simple, Rational, BIASR) for selecting sources (for/against) under varying observations. It calculates expected information gain, updates joint probabilities iteratively, and plots diagnosticity trends and their ratios across 6 observations,... | def plot_selection_sources_with_diagnosticity(prob_H=0.8, prob_R=0.5):
"""
Compute exected information gain of two sources, one for and one against
"""
fig = plt.figure()
M = [1,0] * 5
sources = ["A", "B"] * 5
rational_joint_prob = get_joint_prior_two_sources(prob_H, prob_R, prob_R)
indy_joint_prob = get_joi... |
def get_circ_K_2d(shannon, area):
return np.sqrt(4. * np.pi * shannon / area)
def circ_eig_problem_2d(quad_rules, K):
D = circ_kernel_matrix_2d(quad_rules, K)
Wt = np.diag(np.sqrt(quad_rules["weights"]))#using the square root makes the problem symmetric for better conditioning
w,Vt = linalg.eigh(np.dot(... | The function computes Slepian functions (optimal concentration functions) at specified points (xp, yp) using quadrature rules and a given Shannon number. It constructs a kernel matrix, solves an eigenvalue problem, filters eigenvalues/vectors, and evaluates the functions via matrix operations involving quadrature weigh... | def compute_slepians_at_points(quad_rules, shannon, xp, yp):
K = get_circ_K_2d(shannon,quad_rules["area"])
w, V = circ_eig_problem_2d(quad_rules, K)
w = w[:2*shannon]
V = V[:,:2*shannon]
abcissa = quad_rules["abcissa"]
x = abcissa[:,0]
y = abcissa[:,1]
xx, xxp = np.meshgrid(x, xp, indexi... |
def _get_storage_stores() -> Any:
global _classes
if _classes is not None:
return _classes
class CollectionStore(BaseModel):
"""Collection store."""
__tablename__ = "langchain_storage_collection"
name = sqlalchemy.Column(sqlalchemy.String)
cmetadata = sqlalchemy.Co... | The code initializes a store by retrieving ItemStore and CollectionStore classes, assigning them to instance attributes, and creating necessary tables and collections if they don't exist. The __post_init__ method ensures the storage infrastructure is properly set up for data operations. | def __post_init__(
self,
) -> None:
"""Initialize the store."""
ItemStore, CollectionStore = _get_storage_stores()
self.CollectionStore = CollectionStore
self.ItemStore = ItemStore
self.__create_tables_if_not_exists()
self.__create_collection() |
def clean_main_button(self):
if len(self.main_button) > 0:
for main_button in list(self.main_button.keys()):
self.main_button[main_button].remove()
del self.main_button[main_button]
self.main_button = {}
def add_trade_ui(self):
resources_num = len(self... | This function changes the game board's interface type (e.g., "Roll", "Operate", "Trade") by removing existing buttons and adding new ones specific to the type. It handles UI updates for different game states, including error messages with optional back buttons, and resets to initial state if an invalid type is provided... | def change_board_type(self, type, message = "Error", back_button = True):
resources_num = len(self.resources)
segment_num = resources_num * 2
if (type == "Roll"):
self.type = "Roll"
self.clean_main_button()
self.main_button["Roll"] = ImgButton(self, self.Butto... |
def searchByState(state: str) -> pd.core.frame.DataFrame:
df = extractSalesTaxData()
state = clean_state_name(state)
df = df[df["state"].str.contains(state, case=False)]
return df
def searchByZipcode(zipcode: int | str) -> pd.core.frame.DataFrame:
df = searchByState(clean_state_name(stateName(zipcod... | The function `searchTaxData` retrieves sales tax data by accepting a state or zipcode as input. If a state is provided, it fetches data via `searchByState`; if a zipcode is given, it uses `searchByZipcode`. If neither is specified, it returns all extracted sales tax data using `extractSalesTaxData`. | def searchTaxData(state: str = None, zipcode: int | str = None) -> pd.core.frame.DataFrame:
if state:
return searchByState(state)
elif zipcode:
return searchByZipcode(zipcode)
else:
return extractSalesTaxData() |
def get_operation_default_http_response_code(sop: swagger.Operation) -> int:
# TODO: the _first_ response in the spec is obviously not the default
return 200 if 200 in sop.responses else (list(sop.responses.keys())[0])
def attempt_model_name_from_schema(schema: Schema) -> Optional[str]:
if schema.title:
... | The function `extract_default_response_type` determines the default HTTP response type for an API operation. It retrieves the default response code from the operation, inspects its schema, and returns a tuple with the response code and an `ArgumentType` object. If the schema is inline, it derives a name; if it's a refe... | def extract_default_response_type(namespace: NamespacePath) -> tuple[int, ArgumentType]:
resp_code = get_operation_default_http_response_code(sop)
response = sop.responses[resp_code]
if response.schema:
if isinstance(response.schema, Schema):
name = attempt_model_name... |
def miller_rabin(n: int):
t = 50
k, s = get_r(n)
for i in range(1, t):
a = random.randint(2, n - 2)
y = calculate_mod(a, k, n)
if y != 1 and y != (n - 1):
j = 1
while j <= s - 1 and y != (n - 1):
y = (y ** 2) % n
if y == 1: retu... | The code implements Pollard's Rho algorithm to find a non-trivial divisor of a composite integer $ n $. It uses a probabilistic approach with a random walk defined by $ x_{k+1} = (x_k^2 + c) \mod n $, computes the GCD of differences in the sequence, and returns a proper divisor if found. If $ n $ is prime, it returns $... | def pollard_rho(n: int, c=5):
if n == 1:
return 1
if n % 2 == 0:
return 2
if n == 3:
return 3
if miller_rabin(n):
return n
a = random.randint(2, n)
b = a
while True:
a = (a ** 2 + c) % n
b = (b ** 2 + c) % n
b = (b ** 2 + c) % n
... |
def query_state(self):
# name, pop, income, rent, house
url = f"https://api.census.gov/data/2019/acs/acs5?get=NAME,B01003_001E,B19013_001E,B25064_001E,B25107_001E&for=place:*&in=state:{self.abbr}&key={self.census_api}"
response = requests.get(url).json()
response.pop(0)
cityname ... | The main task of the code is to compile a dictionary of statistical data by calling various methods to retrieve values like population, murder rate, car theft rate, and COVID deaths, then returning this structured data. | def get_answer(self):
answer = {}
answer["Population"] = self.query_state()
answer["State Population"] = self.state_pop
answer["Murder Rate"] = self.query_murder()
answer["Car Theft Rate"] = self.query_car_theft()
answer["Covid Deaths"] = self.query_covid()
return... |
def generate_interrupt_buttons(self):
global interrupt_tuple
global interrupt_required
target = interrupt_tuple.target
blanket_return = interrupt_tuple.postreturn
first_interrupt = adlibdict[target]["interrupt"]["first interrupt"]
for item in adlibdict[target]["... | This function generates UI buttons dynamically based on the `condict` data structure. It checks global flags to either display interrupt buttons, create FunkyButtons from point lists, or recursively update the display and re-call itself. The logic handles nested data, updates the UI with templated strings, and adds dis... | def generate_buttons(self):
global key
global interrupt_required
self.ids.player_responses.clear_widgets()
if interrupt_required:
self.generate_interrupt_buttons()
elif type(condict[key]["points"]) == list:
for item in condict[key]["points"]:
... |
def stiffness_matrix(): # Fourth step of the process which calculates the element stiffness matrices for all the elements
global range_x_temp, range_y_temp, no_of_elements, mx, my, element, xst, yst, J, J_inv, J_det, XT, XT_trans, Ke, K, K_temp, N1, N2, N3, N4, ST, k_small, s, t, k
j = 0
i = 0
for h in range(no_of_... | The main task of the code is to gather temperature boundary conditions from the user for a thermal problem. It prompts the user to specify boundary types (temperature, convection, heat flux, or heat generation) and assigns numerical values to selected edges. The function stores inputs in variables and recursively calls... | def boundary_conditions(): # Sixth step of the process that gathers temperature boundary conditions from the user. Not yet implemented.
print ("""Here you will specify the boundary conditions for the problem.
Temperature will assume the unit of Kelvin, heat flux will assume the unit of W/m2, conveciton coefficient wi... |
def worker_init(self):
for worker_id in range(self.num_workers):
# mp.set_start_method("spawn")
sampling_policy = self.old_policy.to(torch.device("cpu"))
p = mp_torch.Process(
target=worker,
args=(
worker_id,
... | The code trains a reinforcement learning policy using PPO-like algorithms, collecting experience via single/multi-worker setups, optimizing parameters with Adam, updating the policy through gradient descent, and saving checkpoints based on reward performance. It handles data collection, loss computation, parameter anne... | def train(self):
single_worker = self.num_workers == 1
if not single_worker:
self.worker_init()
try:
max_reward = 0
optimizer = torch.optim.Adam(self.policy.parameters(), lr=self.LR, eps=1e-5)
reward_plot = []
for _ in tqdm(range(self.E... |
def writeIt(self, array):
if self.debug:
print(binascii.hexlify(array))
return self.uart.write(array)
def padString(self, string, num, startNum):
reply = bytearray(string, "UTF-8")
reply = reply[:self.max_packet_size]
exp = __num_bits(len(reply) - 1)
reply = r... | The main task of the code is to configure a system mode by writing structured data components—such as name, RAW/percent/SI ranges, symbol, and function maps—into a format using helper methods like `padString`, `buildRange`, and `buildFunctMap`. The `setupMode` function processes input parameters (`mode` and `num`) to g... | def setupMode(self, mode, num):
self.writeIt(self.padString(mode[0], num, NAME)) # write name
self.writeIt(self.buildRange(mode[2], num, RAW)) # write RAW range
self.writeIt(self.buildRange(mode[3], num, Pct)) # write Percent range
self.writeIt(self.buildRange(mode[4], num, SI)) # wr... |
def init(self):
self.write_tx_pin(0, 450)
self.write_tx_pin(1, 0)
self.fast_uart()
self.writeIt(b"\x04")
def writeIt(self, array):
if self.debug:
print(binascii.hexlify(array))
return self.uart.write(array)
def setType(self, sensorType):
return self.ad... | This code initializes a sensor connection by configuring the sensor ID, setting communication modes, sending setup commands, and establishing a connection with a hub. It clears UART buffers, sends configuration data, waits for acknowledgments, and sets up periodic callbacks for data handling. The process confirms succe... | def initialize(self):
self.connected = False
# self.send_timer = machine.Timer(-1) # default is 200 ms
# self.period=int(1000/self.freq)
self.init()
utime.sleep_ms(10)
# empty read buffer
self.uart.read()
self.writeIt(
self.setType(self.sensor... |
def initialize(self):
self.connected = False
# self.send_timer = machine.Timer(-1) # default is 200 ms
# self.period=int(1000/self.freq)
self.init()
utime.sleep_ms(10)
# empty read buffer
self.uart.read()
self.writeIt(
self.setType(self.sensor... | This function manages heartbeat communication with a hub, reinitializing the port if no response is received within a timeout. It processes incoming data bytes, responding to heartbeat signals, mode change commands, and data packets with checksum validation. Upon receiving a NACK, it sends predefined payloads. For mode... | def heartbeat(self):
if (utime.ticks_ms() - self.last_nack) > HEARTBEAT_PERIOD:
# Reinitalize the port, have not heard from the hub in a while.
self.last_nack = utime.ticks_ms()
self.initialize()
b = self.readchar() # Read in any heartbeat or command bytes
i... |
def calculate_loss_and_accuracy(self,batch_labels,epsilon=1e-20):
'''
This function will calculate the loss in the current epoch
give the labels and the output activation.
'''
#Retreiving the outptut of network from cache
net_output=self.actv_cache["A"+str(self.nlayers)]
... | This code performs gradient checking by comparing analytically computed gradients with numerically approximated gradients using finite differences. It perturbs each model parameter by ±ε, calculates the loss for both perturbations, and computes the numerical gradient. The relative difference between analytical and nume... | def __gradient_check(self,batch_input,batch_labels,epsilon=1e-5):
'''
This function will check the gradient calculated by the network
and calculating the gradient numerically by finite difference
method. This is only for testing purpose and will be switched
off during testing.
... |
def count_sequences(infile, sequence_type):
if sequence_type == "fasta":
if infile.endswith(".gz"):
cmd = ["zgrep", "-c", "^>", infile]
else:
cmd = ["grep", "-c", "^>", infile]
elif sequence_type == "fastq":
if infile.endswith(".gz"):
cmd = ["zgrep", "... | This code processes sequence files (FASTA/FASTQ) to generate quality control statistics, including sequence length distribution, GC content, ambiguity counts, and nucleotide base distribution. It validates input files, calculates metrics, and outputs results to specified files or STDOUT, with options for fast mode, seq... | def main(args):
parser = OptionParser(usage=usage)
parser.add_option(
"-i", "--input", dest="input", default=None, help="Input sequence file"
)
parser.add_option(
"-o",
"--output",
dest="output",
default="summary.out",
help="Output stats file, if not calle... |
def img_preprocessing(image: Image, side: str):
# Adjust pixels intensities if needed:
if 'WindowWidth' in image.dcm:
image_array = apply_voi_lut(image.dcm.pixel_array, image.dcm)
else:
image_array = image.dcm.pixel_array
# Resize image to the same pixel spacing.
if cfg.normalize_pi... | The code processes medical images to extract and store Regions of Interest (ROIs) for lesions and normal tissue, along with Full-Field Digital Mammography (FFDM) images. It crops lesion ROIs, adjusts bounding boxes for right-side images, saves patches with metadata, generates non-overlapping normal ROIs, and stores the... | def store_rois_and_ffdm(
lesions_subtypes: dict, lesions_metadata: dict,
client: str, episode: str, scanner: str, side: str, view: str,
image: omidb.image.Image, csv_path: str, copied_count: stats,
extra_size: int = 50, n_normal_bbox: int = None
):
output_path = os.path.dirname(csv_path)
base_pa... |
def initialize_csv(csv_path: str, type_csv: str):
columns = [
'client', 'subtype', 'episode', 'img_id', 'filename', 'side', 'view', 'manufacturer',
'breast_bbox', 'bbox_roi', 'extra_size', 'acquisition_date', 'patient_age_dcm',
'dist_src_det', 'dist_src_pat', 'pixel_spacing', 'implant'
]... | The code processes medical imaging data from a database to generate CSV files containing lesion and normal case information. It filters images based on manufacturer, view type, laterality, and presence of lesions, then stores metadata and regions of interest (ROIs) in CSV files. The function tracks processed cases and ... | def generate_database(db: omidb.DB, csv_name: str, output_path: str):
# Keep the count of the cases processed
overall = stats(0, 0, 0, 0)
copied_count = stats(0, 0, 0, 0)
# Read some specific configs
extra_size = cfg.extra_size
n_normal_bbox = cfg.n_normal_bbox
allowed_episode_types = cfg.a... |
def _check_fleet_edges(self):
"""Respond appropriately if the fleet hits one of the edges"""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
"""Respond to the ship being hit by an alien"""
if self.stats.ship_left > 0:
# Decremen... | The function updates alien positions, checks for collisions with the player's ship, and verifies if aliens reach the screen's bottom. It triggers responses for collisions and edge conditions, ensuring game mechanics like ship damage or game over states are activated when necessary. | def _update_aliens(self):
"""Check if the fleet is at an edge, then update"""
self._check_fleet_edges()
self.aliens.update()
# Look for alien-ship collisions
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
# Look for aliens hitting the bottom of the screen
self._check_alie... |
def _check_events(self):
"""Respond to keypresses and mouse"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _update_bullets(self... | The code runs the game's main loop, continuously checking for input events, updating the ship's position, bullets, and alien movements if the game is active, then redrawing the screen to reflect changes, creating a real-time interactive gaming experience. | def run_game(self):
""" Start the main loop for the game"""
while True:
# Watch for keyboard and mouse movements
self._check_events()
if self.stats.game_active:
# Move the ship
self.ship.update()
# Update the bullets
self._update_bullets()
# Update the aliens
self._update_aliens(... |
def gotoNewScanline(self):
self.move(Movement(self.scanlineDescentDirection, 1))
def moveFurthest(self, dir = None):
if dir is None:
farthest = self.findWalls(farthest=True)
else:
farthest = [Movement(dir, self.disToWallInDir(dir))]
#print("Last dir", self.lastMov... | The main task of the code is to complete a new scanline by moving to the next scanline, advancing furthest in the direction opposite to the last scanline's movement, and updating the recorded direction of the last scanline for future reference. | def completeNewScanline(self):
self.gotoNewScanline()
self.moveFurthest(self.oppLastScanlineDirection)
self.updateLastScanlineDirection() |
def _get_soup_from_url(self, url):
response = self._get(url)
html = response.content
return BeautifulSoup(html, "html.parser")
def _get_lesson_player(self, content):
iframe = content.find("iframe", {"class": "vhi-iframe"})
if iframe is None:
raise NoPlayerException
... | This function retrieves a lesson's video content by fetching its web page, parsing HTML to extract a video player element, identifying the master video source, and returning its content for further processing. | def _get_lesson_file(self, lesson: Lesson):
url = f"https://{self.host}/pl/teach/control/lesson/view?id={lesson.id}&editMode=0"
soup = self._get_soup_from_url(url)
player = self._get_lesson_player(soup)
master = self._get_player_master(player)
return master.content |
def readFromJSON(data):
global endState
global start
global alphabets
for key,value in data.items(): ##filling nfa
if type(value) is dict:
if len(key)==2:
index=int(key[-1])
else:
index=int... | The main task of the code is to convert a Non-Deterministic Finite Automaton (NFA) from a JSON file into a Deterministic Finite Automaton (DFA) using epsilon transitions. It initializes the NFA structure, processes the input JSON data, executes the NFA-to-DFA conversion algorithm, and outputs the resulting DFA to a fil... | def main():
global stack
global nfa
global endState
global start
epsilon_set=set()
que=[]#list of sets
regex="[a-zA-Z0-9]"
myFile=open('./Test Cases/#1/nfa.json')
data=json.load(myFile)
for i in range(len(data)-1): ##initializing nfa with empty states
nfa.append(state... |
def generate_buttons():
for i in range(size + 1): # actually runs for the number of square
start_x = i * skip
for e in range(size + 1):
start_y = e * skip
button_list.append(Button((start_x, start_y), (i, e)))
def draw_grid():
win.fill(background_color)
for w in rang... | The code initializes a grid structure, manages a game loop with rendering and input handling, and cleans up resources. It creates a 2D list for the grid, continuously renders the grid and objects, processes user inputs, and maintains a fixed frame rate using Pygame. The loop runs until the 'run' flag is set to False, e... | def main():
for _ in range(0, int(width / skip)):
out = []
for _ in range(0, int(width / skip)):
out.append("")
area.append(out)
generate_buttons()
global run
run = True
while run:
# time_start = time.time()
draw_grid()
if not area[0][0] ==... |
def ResetPUSH(self): # Reset the PUSH relay
print('Resetting PUSH relay...')
self.OpenSocket('RELAY1=0')
def OpenSocket(self,MESSAGE): # Connect to uSwitch
print(MESSAGE)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((self.TCP_IP,self.TCP_PORT))
s.setbloc... | The main task of the code is to open a pod bay door by activating two relays (RELAY0 and RELAY1) and resetting a push mechanism. It prints a message, triggers relay commands to initiate the door movement, and schedules a timed reset to complete the operation. This function likely controls physical hardware, such as mec... | def Up(self): # Move door up
self.ResetPUSH()
print('Opening the pod bay door...')
for i in range(0,2):
self.OpenSocket('RELAY{0}=1'.format(i))
self.TimedResetPUSH() |
def ResetPUSH(self): # Reset the PUSH relay
print('Resetting PUSH relay...')
self.OpenSocket('RELAY1=0')
def OpenSocket(self,MESSAGE): # Connect to uSwitch
print(MESSAGE)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((self.TCP_IP,self.TCP_PORT))
s.setbloc... | The code's main task is to close a pod bay door by activating relays. It resets a push mechanism, prints a status message, sequentially opens two relays (RELAY0 and RELAY1) to initiate door movement, then triggers a timed reset of the push mechanism to ensure safe operation. | def Down(self): # Move door down
self.ResetPUSH()
print('Closing the pod bay door...')
for i in range(0,2):
self.OpenSocket('RELAY{0}={0}'.format(i))
self.TimedResetPUSH() |
def get_train_test(self):
self.train_source = source_int_text[self.batch_size:]
self.train_target = target_int_text[self.batch_size:]
valid_source = source_int_text[:self.batch_size]
valid_target = target_int_text[:self.batch_size]
(self.valid_sources_batch, self.valid_targets_ba... | The main task of the code is to train a neural network model using TensorFlow. It initializes the session, runs training loops over epochs and batches, computes loss, evaluates training and validation accuracy periodically, and saves the trained model after completion. | def train_network(self):
with tf.Session(graph=self.train_graph) as sess:
sess.run(tf.global_variables_initializer())
self.get_train_test()
for epoch_i in range(self.epochs):
for batch_i, (source_batch, target_batch, sources_lengths, targets_lengths) in enumer... |
def generate_unique_logpath(logdir, raw_run_name):
i = 1
while(True):
run_name = raw_run_name + "_" + str(i)
log_path = os.path.join(logdir, run_name)
if not os.path.isdir(log_path):
return log_path
i = i + 1
def train(model, train_set, criterion, optimizer, train_los... | The main task of the code is to train a model using contrastive loss on a given dataset, save the best model checkpoint during training, plot training/validation losses, load the best model, and evaluate its performance on training, test, and benchmark datasets, reporting loss and AUC/AUPRC metrics for each. | def main_one_iter(model, train_set, test_set, out_file, idx, epoch):
tensorboard_log = generate_unique_logpath(tensorboard_dir, "tensorboard_log")
batch_size = 32
best_model = os.path.join(model_dir, "best_model" + str(idx)+ ".pt")
model_checkpoint = ModelCheckpoint(best_model, model)
criterion = Co... |
def setup(self):
print('Starting CCS811 Read')
self.configure_ccs811()
result = self.get_base_line()
print("baseline for this sensor: 0x")
if result < 0x100:
print('0')
if result < 0x10:
print('0')
print(result)
def data_available... | The code continuously monitors sensor data by checking for availability, reads and prints CO2 and tVOC values when data is present, handles errors if detected, and repeats this process every second to ensure real-time monitoring and error reporting. | def run(self):
self.setup()
while True:
if self.data_available():
self.read_logorithm_results()
print("CO2[%d] tVOC[%d]" % (self.CO2, self.tVOC))
elif self.check_for_error():
self.print_error()
time.sleep(1) |
def localTag(k, questions, prev_sentence):
code, em, strong, li, k = cleanSentence(k)
taged = pos_tag(word_tokenize(k))
allTags = [x[1] for x in taged]
tags = [0] * MAGIC
start = 0
while start < len(taged) and taged[start][1] == taged[start][0]:
start += 1
if (start < len(taged) and ... | The main task of the code is to process answer sentences by generating cleaned versions and associated tag vectors using the `localTag` function. It then computes embeddings for the cleaned answers and combines them with the input question embedding and tag vectors via the `combine` function, returning both the cleaned... | def calInput(question_embedding, question_sentences, answer_sentences):
cleaned_answer_sentences = []
localTags = []
for index, i in enumerate(answer_sentences):
if index == 0:
prev = ''
else:
prev = answer_sentences[index - 1]
tag_vector, cleaned_sentence = l... |
def _setBoard(self):
self.b = Board(self.rows, self.cols)
self.b.prepareBoard()
def _setPlayer(self):
self.p = Player()
def _prepareTurnsDict(self):
for x in self.p.players:
self.playerPositions[x] = {
"currentPos": 0
}
def _playTurns(self):
... | The main task of the code is to initialize a game by setting up the game board, player configurations, preparing a turn order dictionary, and initiating the sequence of turns to start gameplay. | def initGame(self):
self._setBoard()
self._setPlayer()
self._prepareTurnsDict()
self._playTurns() |
def _createBoardArray(self):
counter = 1
for row in range(self.rows):
arr = []
for col in range(self.cols):
arr.append(counter)
counter += 1
self.board.append(arr)
return self.board
def _setSnakes(self):
total = self.row... | The main task of the code is to initialize and configure a game board by creating its structure, placing snakes and ladders, and printing their positions. It orchestrates board creation, snake placement, ladder placement, and visualization to set up a functional Snakes and Ladders game environment. | def prepareBoard(self):
self._createBoardArray()
self._setSnakes()
self._setLadders()
self._printSnakeAndLadders() |
def detect_participant_id(self):
participant_id = None
with open(self.filename, 'r', encoding='utf-8', errors="ignore") as f:
for line in f:
if re.search(r'@Participants:', line):
participant_id = re.search(r'[0-9]+', line).group(0)
assert particip... | This code initializes an object by parsing a file to extract participant ID, detect primary/secondary languages, parse utterances, count linguistic types/tokens, and calculate total duration from the last utterance's end time. It sets attributes for filename, participant ID, language pairs, utterance list, token statis... | def __init__(self, cha_file_path):
self.filename = cha_file_path
self.participant_id = self.detect_participant_id()
langs = self.detect_languages()
self.main_lang = langs[0]
self.secondary_lang = None if len(langs) < 2 else langs[1]
self.utterances = self.parse_utterances... |
def syntax_aware_split(x: str, sep: str) -> list[str]:
"""
Split a string by `sep` accounting for literals.
TODO: write a more idiomatic version.
"""
groups: list[list[str]] = []
cur: list[str] = []
in_paren = False
m = len(sep)
i = 0
while i < len(x):
try:
... | The code parses a grammar file into a dictionary by reading each line, splitting it into a symbol and rule using a special separator, handling errors, and returning the resulting grammar dictionary. | def parse_grammar(input_file: Path) -> Grammar:
grammar = {}
with open(input_file) as fp:
lines = [x.strip() for x in fp]
for i, line in enumerate(lines, start=1):
try:
sym, rule = map(
lambda x: x.strip(), syntax_aware_split(line, sep=Special.DEF)
)... |
def create_socket():
try:
global host
global port
global s
host = ""
port = 9985
s = socket.socket()
except socket.error as msg:
print("socket creation failure: " + str(msg))
def bind_socket():
try:
global host
global port
globa... | The main task of the code is to initialize a server socket by creating a socket, binding it to a specific port, and waiting for incoming client connections through the accept_socket() function, forming the foundational setup for a network server application. | def main():
create_socket()
bind_socket()
accept_socket() |
def _download_and_unzip(download_folder_path, unzipped_folder_path):
"""download and unzip Geofabrik shapefiles to the designated folder.
Parameters:
global variables
Returns:
None
"""
start = time.time()
print("=====================================================================... | The main task of the code is to create a structured local database of Geofabrik shapefiles within a specified folder path. It downloads, unzips, reorganizes, and combines shapefiles according to a user-defined label hierarchy, ensuring the file system matches this structure. The function also handles updates by deletin... | def build(database_folder_path):
"""builds a local database of Geofabrik shapefiles in designated folder path.
The file system follows the structure in the user-specified label hierarchy.
Parameters:
database_folder_path (file path): the local file path to store Geofabrik shapefiles
Returns:
... |
def solveEO(c,e):
if not checkEO(e):
return []
else:
moves = ["R","R'","R2","U","U'","U2","F","F'","F2","D","D2","D'","L","L2","L'","B","B2","B'"]
q = deque([(c,e,[])])
visited = set()
while q:
c,e,l = q.popleft()
for move in moves:
... | This code solves a Rubik's cube scramble by decomposing it into four stages: EO (edge orientation), DR (double layer), HTR (hidden triple reduction), and final solving. It applies each stage's solution sequentially to the cube state, tracking transformations via predefined move functions, and outputs the combined solut... | def solveScramble(scramble):
starte = 407901468851537952
startc = 247132686368
print(scramble)
scramble = scramble.split(' ')
for move in scramble:
startc,starte = mdic[move](startc,starte)
eoSol = solveEO(startc,starte)
print("EO:",end='\t')
for move in eoSol:
print(mov... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.