dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def cleanTheString(strings): #bersihkan dokumen terlebih dahulu dengan regex # print(strings) #hapus unicode strings = re.sub(r'[^\x00-\x7F]+', ' ', strings) #hapus mentions strings = re.sub(r'@\w+', '', strings) #lowercase the string strings = strings.lower() #hapus punctuation (tit...
The main task of the code is to process a search query by cleaning and vectorizing it, then retrieve and combine results from internal and external documents. It sorts the results by relevance, extracts term vectors, and returns the sorted results along with query words and combined vectors for further analysis or rank...
def mainSearch(searchQuery, externalDoc=""): #ubah queries menjadi vektor terlebih dahulu #bersihkan query, lakukan stemming, filtering (hapus stopwords) cleaned_query, _ = cleanTheString(searchQuery) vector_query = [i[1] for i in cleaned_query] query_words = [i[0] for i in cleaned_query] ...
def __select_source(self): typer.echo("Select photo source") for number, source in photo_sources.items(): typer.echo(f"[{number}] {source}") source_number = int(typer.prompt("Your choice?")) if source_number in photo_sources: self.photo_source = source_number ...
The main task of the code is to import a photo by selecting a source, sending it via an API, and handling responses. It checks for a photo source, retrieves an API response, and prints success with the URL if the status is 200/201, or an error message otherwise, recursively restarting the process on failure.
def run_photo_import(self): typer.echo("PHOTO IMPORT UTILITY") if not self.photo_source: self.__select_source() api_post_response = self.__get_api_response() if api_post_response.status_code in (200, 201): typer.echo(f"Photo added\n" f"url: {api_post_response.json...
def create_b2(): """ Create the b2 Branches instance. """ int_txt = ('You walk into the village and wander past the huts.\n' 'You open the door to one and notice a group ' 'of sand monsters.\n' 'You try to shut the door but it is too late, they have ' ...
The main task of the code is to create a "Branches" instance representing a desert scenario with narrative text, choices (a/b/c), and three story-exit routes (b2/b3/b4), appending descriptive exit texts for each option.
def create_b1(): """ Create the b1 Branches instance. """ int_txt = ('You emerge into...a desert!\n' 'Sandy dunes stretch for miles in every direction.\n' 'You start walking. It is really hot and you quickly tire.\n' 'As you ascend a dune you see a village of...
def find_human(self): for organism in self.organisms[1:]: if organism.name == "Human": return organism return None def next_round(self): self.sort() tmp = self.count i = 1 while i <= tmp: if self.organisms[i].ifAlive: ...
This function handles the "next round" action in a game. It checks if a human player exists and whether their move is valid. If no human is present or their move is legal, it triggers the next round; otherwise, it alerts the user of an illegal move.
def next_round_pressed(self, button): tmp = self.find_human() if tmp == None: self.next_round() else: if self.if_human_move(tmp): self.next_round() else: print("Illegal move with human. Choose different direction.")
def divide_chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n] def tprint(text): clock = datetime.timedelta(seconds=time.time() - t0) print(f'[{clock}] {text}') def process_chunk_of_images(chunk): global yolo_score_matrix global retina_score_matrix chunk_data = p_map(process_si...
The code processes images by generating coordinate grids, splitting them into chunks, and analyzing each chunk using object detection models (YOLOv5 and RetinaNet). It saves score matrices as NumPy files, visualizes results with heatmaps, and logs runtime. Final outputs include score matrices, plots, and a debug log.
def process_images(): jobs = [] for x in range(-w // 2, bg_w - (w // 2), 10): for y in range(-h // 2, bg_h - (h // 2) - 1, 10): jobs.append((x, y)) logging.debug('Splitting coords into chunks') chunks = list(divide_chunks(jobs, chunk_size)) tprint('Coords split into chunks') ...
def ONNkomandoa(id_berogailu): try: bueltan = __berogailuEgoeraAldatu(id_berogailu, True) except ErroreaEskaeran: raise ErroreaEskaeran(11) # Err ONN. Ez dago ID hori duen berogailurik return bueltan def OFFkomandoa(id_berogailu): try: bueltan = __berogailuEgoeraAldatu(id_berog...
The main task of the code is to create a UDP server that receives commands (e.g., ONN, OFF, NAM), processes them by calling specific functions, handles errors by reverting device states, and sends ASCII-encoded responses back to the sender. It maintains a backup of device states for error recovery and supports command ...
def main(): # Sortu socketa eta esleitu helbide bat. global berogailuak, listaBK s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('', PORT)) while True: # Jaso mezu bat eta erantzun datu berdinekin. mezua, bez_helb = s.recvfrom(1024) # Jasotako mezua ASCII format...
def check_witness(inputs): for txin in inputs: if 'witness' in txin: return True return False def encode_version(version): ''' Encode the version field of a transaction. ''' return version.to_bytes(4, 'little') def encode_txin(inputs): ''' Encode each transaction input. ''' r...
The function `encode_tx` serializes a transaction object into hexadecimal byte-code by encoding its version, inputs, outputs, locktime, and optional witness data. It checks for witness presence in inputs, appends a witness flag if needed, and sequentially encodes each component. The final byte string is returned as a h...
def encode_tx(obj, **kwargs): ''' Serialize a transaction into byte-code. ''' version = obj.get('version', 1) inputs = obj.get('vin', []) outputs = obj.get('vout', []) locktime = obj.get('locktime', 0) # Check if witness data exists in inputs. has_witness = check_witness(inputs) # Enc...
def encode_version(version): ''' Encode the version field of a transaction. ''' return version.to_bytes(4, 'little') def hash_prevouts(inputs, anypay): ''' Combine all input prevout fields, then return a digest. ''' if anypay: return b'0' * 32 raw_prev = b'' for txin in input...
This function generates a message digest for signing a BIP143 Segwit transaction by concatenating transaction version, input data (prevouts, sequence), specific input details (txid, vout, sequence), redemption script, input value, outputs, locktime, and sighash flag, then applying hash256. It handles script formats, si...
def encode_sighash(obj, txin_idx, txin_value, script, **kwargs): ''' Generate the message digest that is used to sign a BIP143 Segwit transaction. ''' version = obj.get('version', 1) inputs = obj.get('vin', []) outputs = obj.get('vout', []) locktime = obj.get('locktime', 0) sigha...
def check_balance(api_key, api_secret): urlstem = '/api/v3/account' parameters = { 'recvWindow': 20000, 'timestamp': current_timestamp() } balance_raw = json.loads(api_get_signed(urlstem, parameters, api_key, api_secret)) balance = defaultdict(dict) for coin in balance_raw['balances']: balance[coin['as...
This code monitors cryptocurrency prices in real-time via WebSocket, detects arbitrage opportunities, executes trades based on predefined thresholds, and visualizes USDT balance changes. It connects to Binance, updates price data, checks for profitable trades, manages active opportunities, and adjusts balances dynamica...
def market_monitor(cryptosofinterest, queryfrequency, tradefrequency, balance, trading_fee, trading_ratio, arb_threshold, arbs_checking, tradeinprogress, exchange_info, api_key, api_secret): import time import datetime import websocket import ssl balance = check_balance(api_key, api_secret) firstpass = True tim...
def get_sections_local(specs): with open(specs["config"], 'r') as f: lines = f.readlines() if specs["search"] == ["ACL Values"]: return lines return get_sections(lines) def get_sections_remote(specs): client = paramiko.SSHClient() client.set_missing_host_key_policy(parami...
The code parses a configuration by determining if sections are sourced locally or remotely, then searches for specified items in those sections, compiling results into a dictionary for return.
def parse_config(specs): if specs["local"]: sections = get_sections_local(specs) else: sections = get_sections_remote(specs) results = {} for item in specs["search"]: results[item] = get_results(item, sections) return results
def transform_odometry_child_frame(msg, target_frame, tf_buffer): """Transform the child frame of the odom message to the target frame.""" target_pose = transform_pose_child_frame( msg.pose.pose, target_frame, msg.child_frame_id, tf_buffer, msg.header.stamp) target_twist = transform_twist_c...
The main task of the code is to compare an odometry message with ground truth data by calculating pose and twist errors. It adjusts the ground truth for the odometry's child frame using a transform buffer if applicable, then returns combined error values from poseError and twistError functions to assess odometry accura...
def odometryError(odom, ground_truth, tf_buffer): """Compare the odometry message to the ground truth message""" if odom.child_frame_id != "": twist_ground_truth = transform_odometry_child_frame( ground_truth, odom.child_frame_id, tf_buffer) else: twist_ground_truth = ground_trut...
def PureLiteral(clauses): if clauses == -1: return -1, [] pureList = [] pureLiterals = [] occ = NumOccurences(clauses) for i, j in occ.items(): if -i not in occ: pureLiterals.append(i) for pure in pureLiterals: clauses = EliminateClause(clauses, pure) p...
This function solves a SAT problem using backtracking with optimizations: it removes pure literals, applies unit propagation, checks for failed literals, selects a variable heuristically, and recursively tries assignments until a solution is found or all possibilities are exhausted.
def BacktrackingCore(varlist, clauses): clauses, pureVars = PureLiteral(clauses) clauses, unitVars = UnitPropagation(clauses) if clauses != -1: clauses, failedVars = FailedLiteral(clauses) varlist += (unitVars + pureVars + failedVars) else: varlist = (unitVars + pureVars + failed...
def open_DB(self): """ will open DB file and put value in: self.conn (need DB file name) and self.cursor """ self.conn = sqlite3.connect('driveApp.db') self.current = self.conn.cursor() def close_DB(self): self.conn.close() def get_user_name(self, id): """returns the name of the ...
The code retrieves a student's profile data (email, address, phone, birthdate, and teacher info) from a database using their ID, formats it into a pipe-separated string, and returns it.
def get_student_profile(self, id): """returns the needed data for student's profile by id.""" self.open_DB() sql = "SELECT email, address, phoneNumber, birthdate, teacherId \nFROM Students \nWHERE Id='%s';" % id print(sql) self.current.execute(sql) data = self.current.fet...
def open_DB(self): """ will open DB file and put value in: self.conn (need DB file name) and self.cursor """ self.conn = sqlite3.connect('driveApp.db') self.current = self.conn.cursor() def get_user_name(self, id): """returns the name of the user by his id""" if self.check_value_...
This code retrieves a user's notifications from a database, sorts them by sending time (latest first), and returns them as a formatted string containing sender details, content, status, and timestamps.
def get_notifications(self, receiverId): """returns all the user's notifications' data : the sender, the content, status, sendingTime""" self.open_DB() sql = "SELECT senderId, content, status, sendingTime, type \nFROM Notifications \nWHERE receiverId='%s';" % receiverId print(sql) ...
def msg(self, Message): """ Print out the specified message if the print_messages flag is set. """ if (self.print_messages == True): print(Message) def get_curr_room(self): """ Get the current room that the player is in. """ return(se...
This function maps string actions to corresponding method calls, executing tasks like moving directions, shooting, picking up gold, or exiting. It logs actions and returns results from methods or False for unknown commands.
def action_wrapper(self, ActionStr): """ Wrap up the actions as strings. """ self.msg("ActionWrapper: {}".format(ActionStr)) if (ActionStr == "GetRoom"): return(self.get_curr_room()) elif (ActionStr == "PickupGold"): return(self.pickup_g...
def addItem(event, context): global foodName # global foodNum foodItem = event['request']['intent']['slots']['Food']['value'] if foodName[0] == None: foodName[0] = foodItem else: foodName.append(foodItem) # try: # foodNumber = event['request']['intent']['slots']['Numbe...
The code defines an intent router function that directs user intents to specific handlers. It checks the intent name from the event and routes it to functions like addItem, Done, cancel_intent, help_intent, or stop_intent based on predefined conditions, enabling differentiated responses for various user requests in an ...
def intent_router(event, context): intent = event['request']['intent']['name'] # Custom Intents # Intent that is always accessible after phase 1 is completed if intent == "ingredients": return addItem(event, context) elif intent == "done": return Done(event, context) elif intent...
def on_launch(event, context): # Initialize Values Here # ChefAlexaTable.put_item( # Item={ # 'ID': 0, # 'Ingredient': [] # } # ) # build_SSML(str(req_email)) # get_perm() # access_token= event['context']['System']['user']['accessToken'] return build_S...
This code defines an AWS Lambda handler for an Alexa skill, routing incoming requests based on their type: LaunchRequest triggers on_launch, IntentRequest uses intent_router for intent handling, and SessionEndedRequest invokes on_Exit. The main task is to process and direct Alexa interaction events to appropriate funct...
def lambda_handler(event, context): if event['request']['type'] == "LaunchRequest": return on_launch(event, context) elif event['request']['type'] == "IntentRequest": return intent_router(event, context) elif event['request']['type'] == "SessionEndedRequest": return on_Exit(event, co...
def _check_download_dir(link, download_dir, hashes): # type: (Link, str, Optional[Hashes]) -> Optional[str] """ Check download_dir for previously downloaded file with correct hash If a correct file is found return its path else None """ download_path = os.path.join(download_dir, link.filename) ...
The main task of the code is to download and unpack a file from a given URL into a specified location. It checks if the file already exists in a provided download directory, otherwise downloads it to a temporary directory, unpacks it, and optionally copies the file to the download directory. The function ensures the ar...
def unpack_http_url( link, # type: Link location, # type: str download_dir=None, # type: Optional[str] session=None, # type: Optional[PipSession] hashes=None, # type: Optional[Hashes] progress_bar="on" # type: str ): # type: (...) -> None if session is None: raise TypeError...
def unpack_vcs_link(link, location): # type: (Link, str) -> None vcs_backend = _get_used_vcs_backend(link) assert vcs_backend is not None vcs_backend.unpack(location, url=hide_url(link.url)) def unpack_file_url( link, # type: Link location, # type: str download_dir=None, # type: Optional[...
The function `unpack_url` unpacks a given link (VCS, file, or HTTP) into a specified location. It handles VCS links by exporting to the location or download_dir, processes file URLs with hash verification, and manages HTTP URLs using a session. Parameters include location, download_dir, session, hashes for validation, ...
def unpack_url( link, # type: Link location, # type: str download_dir=None, # type: Optional[str] session=None, # type: Optional[PipSession] hashes=None, # type: Optional[Hashes] progress_bar="on" # type: str ): # type: (...) -> None """Unpack link. If link is a VCS link: ...
def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Sampling-Theory_Illustrator")) self.slider_label.setText(_translate("MainWindow", " Move the Slider To change the Value of FMax for Sampling")) self.H...
This code sets up a GUI interface for a signal processing application using PyQt. It creates a main window with two tabs: one for visualizing received signals with adjustable parameters, and another for generating custom signals through input fields, plotting, and manipulation. The interface includes sliders, checkboxe...
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(920, 595) Mainicon = QtGui.QIcon() Mainicon.addPixmap(QtGui.QPixmap("wicon.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(Mainicon) self.centralwidget = QtWidgets...
def openFileNameDialog(self): options=QtWidgets.QFileDialog.Options() files=QtWidgets.QFileDialog.getOpenFileName(self,'Open only txt or CSV or xls',os.getenv('HOME'), "csv(*.csv);; text(*.txt) ;; xls(*.xls)",options = options) if files: ...
The code defines an `on_click` method that handles button clicks in a PyQt5 application. It opens three file dialogs, stores selected filenames in `list_files`, and reads data from the first three files if their names are non-empty. Specifically, it calls `read_data1()`, `read_data2()`, and `read_data3()` for the first...
def on_click(self): print('PyQt5 button click') self.openFileNameDialog() self.openFileNameDialog() self.openFileNameDialog() fname=list_files[0] if (fname[0] != ''): self.read_data1() else: pass fname=list_files[1] if (fnam...
def collect_baselines(self, steps): self.move_to(0,0) l1, l2 = self.collect_sound(steps=steps) return np.array([np.mean(l1), np.mean(l2)]) def collect_sound(self, steps=1): cmd = str.encode('read {} \n'.format(steps)) data = self.write_read(cmd) data = data.split(";")[:-1...
The main task of the code is to adjust collected sound data by subtracting baseline values and visualize the result. It retrieves baseline data, collects sound samples, applies offset corrections, and plots the processed data.
def test(self): shifts = self.collect_baselines(1000) l, r = self.collect_sound(step=100) l = l - shifts[0] r = r - shifts[1] self.plot_data(range(100), l, r)
def collect_baselines(self, steps): self.move_to(0,0) l1, l2 = self.collect_sound(steps=steps) return np.array([np.mean(l1), np.mean(l2)]) def collect_data(self, sep, shifts): xs = np.arange(-30,31,sep) ys = np.arange(-30,31,sep) data = [] for i,x in enumerate(xs...
The main task of the code is to collect baseline data, prompt user input via a metronome trigger, gather sensor data with a fixed separation parameter, save the acquired data to a file using NumPy, and visualize the data. The function orchestrates data collection, user interaction, storage, and visualization for experi...
def collect_and_save_data(self, save_path): sep=5 shifts = self.collect_baselines(200) input("\nTURN ON METRONOME! HIT ENTER TO CONTINUE.\n") data = self.collect_data(sep, shifts) np.savez(save_path, data=data) self.visualize_data(save_path,sep)
def download_and_unzip_countries(): destination = data_files["admin_0_countries_unzipped_filepath"] if destination is not None and destination.exists(): logger.info(f"countries shapefile already unzipped to {destination}") return countries_110m_url = "https://naciscdn.org/naturalearth/110m/c...
The main task of the code is to download and prepare geographical data, including countries, OSM data in feather format, and seas data. It verifies data readiness and raises an error if preparation fails, ensuring all required datasets are correctly downloaded and processed for subsequent use.
def download_and_prepare_data(): download_and_unzip_countries() get_osm_in_feather_form() download_unzip_and_prepare_seas_feather() if not data_ready(): raise RuntimeError("Data not ready even though it should be.")
def data_ready() -> bool: for data_file_key in data_files_needed: filepath_raw = data_files[data_file_key] if filepath_raw is None: logger.debug(f"Did not find {data_file_key}, value is None") return False filepath_obj = Path(filepath_raw) if not filepath_obj....
The main task of the code is to load and combine bad landing area data from two sources (OSM and SEAS), align their coordinate reference systems (CRS), and return a unified GeoSeries containing all geometries. It first checks if data is ready, downloads/prepares it if needed, loads both datasets, ensures they share the...
def load_bad_landing_data() -> gpd.GeoSeries: if not data_ready(): logger.info("Data not ready. Getting files now") download_and_prepare_data() logger.info("Data ready") from_osm_polys = load_osm_bad_landing_data() from_seas_polys = load_seas_bad_landing_data() shared_crs = from_...
def load_bad_landing_data() -> gpd.GeoSeries: if not data_ready(): logger.info("Data not ready. Getting files now") download_and_prepare_data() logger.info("Data ready") from_osm_polys = load_osm_bad_landing_data() from_seas_polys = load_seas_bad_landing_data() shared_crs = from_...
The main task of the code is to load and reproject bad landing geospatial data into a specified coordinate reference system (processing_crs), generate spatial indexes for the data in that CRS, and load Finland's geospatial data. The function initializes spatial indexes for the specified CRS and stores Finland's geospat...
def load_data(self): self.bad_landing_gs = load_bad_landing_data().to_crs(processing_crs) sindex_crs = {processing_crs} # Initialize spatial index for crs in sindex_crs: self.save_bad_landing_sindex(crs) self.finland_gs = get_finland_gs()
def path_to_goal(self): start_x = -8.0 start_y = -2.0 goal_x = 4.5 goal_y = 9.0 slope = (goal_y - start_y) / (goal_x - start_x) # angle = 180.0 * np.arctan(slope) / 3.14 # print(slope,angle) slope = np.arctan(slope) return slope def goal_seek(self): err = target_slope*0.09 # print(yaw) if self...
This callback function updates the robot's position and orientation from sensor data, converts quaternion to Euler angles, calculates the target slope for navigation, and executes either goal-seeking or wall-seeking behavior based on the current mode.
def odom_callback(self,data): self.robot_pos = [data.pose.pose.position.x,data.pose.pose.position.y] global roll, pitch, yaw,target_slope orientation_q = data.pose.pose.orientation orientation_list = [orientation_q.x, orientation_q.y, orientation_q.z, orientation_q.w] (roll, pitch, yaw) = euler_from_quaternio...
def extract_gigs(): gigs_file = root / "gigs.xml" gigs_root = et.ElementTree(file=gigs_file) bands = {} venues = {} gigs = [] found_gigs = 0 relevant_gigs = 0 bands_xml = gigs_root.findall(".//table[@name='tempgig']/records/record") for gig_xml in bands_xml: found_gigs = foun...
The main task of the code is to generate HTML pages for bands, venues, and an index of gigs by extracting data from `extract_gigs()`, printing template/destination paths, and calling functions to build individual pages for each band and venue, along with an aggregated index page of all gigs.
def build_all(): bands, venues, gigs = extract_gigs() print(templates_path) print(destination_base) build_index_page(gigs) for band in bands: build_band_page(band, bands[band], gigs) for venue in venues: build_venue_page(venue, venues[venue], gigs)
def get_data(data): L=len(data) ratio=math.floor(3/4*L) train_data=data val_data=data[ratio:,] if args.model_type=='electra': #the data tuples are the exactly the same as in bert train_data_pairs=create_bert_tuples(train_data,seq_length, .15) val_data_pairs=create_bert_tuple...
The code trains a machine learning model (ELECTRA, Transformer, BERT, or generic) on given data, validating after each epoch. It splits data into training and validation sets, iterates over 1000 epochs, and uses model-specific training functions. After each epoch, it evaluates validation loss, updates the best model if...
def train(data, model, discriminator=None): print("in train") data=data #create train and val data #get_data handles the cases of full_transformer, encoder bert style, or encoder train_data, val_data = get_data(data) epochs=1000 #min_loss=float('inf') if args.model_type=='electra': ...
def events(self): for event in pg.event.get(): if ( event.type == pg.QUIT or event.type == pg.KEYDOWN and event.key == pg.K_q ): self.running = False def move(self, action) -> None: """ Moves player according...
The code defines a `step` method that processes an action by updating the environment state, triggering events, and moving the agent. It calculates the reward and determines if the episode is done, then returns the new state, reward, and done status. This is typical in reinforcement learning environments for agent inte...
def step(self, action): self.n_frames_threshold += 1 self.events() self.move(action) reward, done = self.get_reward() state = self.get_state() return state, reward, done
def convert_file(file_path): # if no needed - stay .wav new_path = file_path if file_path.endswith('.flac'): # convert from .flac new_path = convert_flac(file_path) if file_path.endswith('.webm'): # convert from .webm new_path = convert_webm(file_path) return new_pat...
The main task of the code is to process an audio file using a specified machine learning model (YOLO or classification) to compute a score-per-second (SPS) metric. It converts and prepares the audio, segments it into 500ms clips, runs predictions with the model, calculates SPS by dividing the prediction count by audio ...
def main(file_path,model_name,threshold=0.25): sps = 0 # convert file format audio_file = convert_file(file_path) # change fr,channels such that model can read it new_full_path = change_file_properties(audio_file) # cut the file to 500ms each and run model destination_path = cut_files_to_fo...
def build_generator_matrix(n, k, generator_polynomial): rows = [] for i in range(n - k, n): row = np.zeros(n) row[i] = 1 _, remainder = divide_mod2(row, generator_polynomial) row[:len(remainder)] = remainder # x^i - x^i mod g(x) rows.append(row) return np.vstack(rows...
The code implements a cyclic error-correcting code with parameters n=7, k=3, and maximum burst length b=2. It constructs generator and parity-check matrices, defines encoder/decoder functions, and tests their correctness using sample input data. The task focuses on validating cyclic code encoding/decoding processes for...
def plain_cyclic(): n, k = 7, 3 generator = [1, 0, 1, 1, 1] b = 2 # max burst length gen_matrix = build_generator_matrix(n, k, generator) par_check_matrix = build_parity_check_matrix(n, k, generator) encoder = lambda data_blocks: encode(data_blocks, gen_matrix) decoder = lambda transmitted...
def build_parity_check_matrix(n, k, generator_polynomial): rows = [np.identity(n - k)] for i in range(n - k, n): dividend = [0] * (i + 1) dividend[-1] = 1 _, remainder = divide_mod2(dividend, generator_polynomial) # x^i mod g(x) rows.append(remainder) return np.vstack(rows...
The code implements a Reed-Solomon decoding algorithm (RDS) to detect and correct burst errors up to 5 bits in a shortened (341, 331) code. It encodes UTF-8 data blocks, introduces burst errors, decodes using a tailored parity-check matrix, and verifies error correction accuracy through assertions and trials. The proce...
def rds(): # original code is (341, 331), shortened (26, 16) # yeah, so we have to pretend that inputs are from 341-dimensional space with initial positions zeroed out # i.e. multiplied by x^325 or sth b = 5 k_0 = 16 n_0 = 26 n = 341 k = n - (n_0 - k_0) pm = build_parity_check_matrix...
def _synchronize(self, bit_arr): i = 0 while i < len(bit_arr) - 26 and not self.in_sync: syndrome = np.matmul(bit_arr[i:i + 26], pc_matrix) % 2 offset_word = lookup_syndrome(syndrome) self.prev_offset_words[self.current_offset] = offset_word if offset_wor...
The main task of the code is to decode a bit array into data groups by synchronizing with known patterns, shifting to align data, decoding full groups, and storing leftover bits for future rounds. It combines previous and current bits, handles synchronization loss, and recursively decodes remaining bits, returning the ...
def decode(self, bit_arr): # steps: # 1. SYNC: find 2 consecutive syndromes corresponding to known offset words in correct order # 2. SHIFT: shift to beginning of the next group (might not be in bit_arr!) # 3. DECODE: decode as many groups as can fit bit_arr (accumulate decoding er...
def train_batch(self, batch,n, epoch): if epoch > self.startfrom: loss, losses, ans_logit = self.forward(batch) loss = loss / self.grad_accumulation if args.multiGPU: loss = loss.mean() losses = losses.mean(0) loss.backward() ...
The main task of the code is to train a multimodal model (combining text and vision components) with distributed data parallelism. It initializes a custom optimizer (BertAdam), manages parameter freezing/unfreezing for pre-trained layers, processes dataset folds with distributed samplers, and logs training losses. The ...
def train(self, train_dataset, valid_dataset, args): if args.gpu == 0: print("Finished creating distributed parellel") # Optimizer from models.optimization import BertAdam batch_per_epoch = 13960*10 #len(train_dataloader) t_total = int(batch_per_epoch * args...
def staffList(self): try: f = open('config/staff.json', 'r') try: data = json.load(f) return data['users'] except Exception as e: return False except Exception as e: return False def command_list(self): ...
The code dynamically loads and registers Discord bot commands with cooldown management, authorization checks, and error handling. It sets up cooldown resets for staff members, processes command errors (e.g., cooldowns, unauthorized access), and loads command modules from files. It validates user inputs, enforces role-b...
def add_commands(self, commandName='dth'): @self.bot.before_invoke async def resetCooldown(ctx): # enable cooldown resets for staff members if (self.config['enable-reset-cooldowns']): staff = self.staffList() userInfo = user(ctx) i...
def update_map_matrix(self, x, y, value): """ Updates the value of a cell in the map matrix. """ self.map_matrix[y][x] = value def clear_screen_and_display(self): """ Clears the screen and displays the current state of the maze. """ os.system('cls' if os.n...
The code's main task is to start a maze navigation game, allowing the player to move using arrow keys. It updates the game state, checks for valid moves, deducts lives on wall collisions, resets position upon losing all lives, and ends the game when the player reaches the exit or exhausts all lives, displaying appropri...
def play(self): """ Starts the game and allows the player to navigate through the maze. """ px, py = self.start_pos is_playing = True key_action_map = { readchar.key.UP: (0, -1), readchar.key.DOWN: (0, 1), readchar.key.LEFT: (-1, 0), ...
def findCandidatePairs(self, read): myList = self.hashRead(read) candidatePairs = {} for x in myList: #for every value of the sub-vector of signature for val in self.sigTable[x]: #for every segment in the list if val[0] == 1: #if the segment is in reference (ID = 1) ...
The code identifies the optimal matching index for a given RNA read by first evaluating candidate pairs. If no valid match is found (res = -1), it reverses the RNA read, re-evaluates candidates, and returns the maximum count index from either process.
def FindMatchingIndex(self, read): candidates = self.findCandidatePairs(read) res = self.FindMaxCount(candidates) if(res == -1): candidates = self.findCandidatePairs(oppositeRNA(read)) res = self.FindMaxCount(candidates) return res
def findCandidatePairs(self, read): myList = self.hashRead(read) candidatePairs = {} for x in myList: #for every value of the sub-vector of signature for val in self.sigTable[x]: #for every segment in the list if val[0] == 1: #if the segment is in reference (ID = 1) ...
The code identifies the best matching index for a given RNA read by first checking candidate pairs from the original read. If no valid match is found (res = -1), it processes the opposite RNA strand, finds new candidates, and returns the result from FindMaxCount, ensuring a match is identified either from the original ...
def FindMatchingIndex(self, read): candidates = self.findCandidatePairs(read) res = self.FindMaxCount(candidates) if(res == -1): candidates = self.findCandidatePairs(oppositeRNA(read)) res = self.FindMaxCount(candidates) return res
def _looking_around(self): """ :return: surrounding agents, possible moving positions and obstacles to observe the surrounding environments """ # the list of objects surrounding an agent, 5x5 range, exclude the center where the agent is standing surrounding_agents = self....
The main task of the code is to guide an agent's movement in a simulated environment by detecting surrounding agents, fire hazards, and exits. It updates perceptual memory of fire locations, exchanges information with other agents, and uses pathfinding algorithms to navigate towards a goal exit while avoiding obstacles...
def step(self): # Remember the previous position temp_last_pos = self.pos # First, an agent should look around for the surrounding agents & possible moving positions. surrounding_agents, possible_steps, contacting_objects = self._looking_around() for surrounding_agent in surrou...
def _update_ost_fill_level_dict(self): if self.local_mode: self.ost_fill_level_dict.clear() for i in range(self.num_osts): ost_idx = str(i) fill_level = random.randint(40, 60) self.ost_fill_level_dict[ost_idx] = fill_level els...
The code's main task is to manage and execute tasks between source and target OSTs (Object Storage Targets) by processing input files, monitoring OST states, and dynamically assigning tasks to available OST pairs. It maintains caches, updates system states, and periodically reloads data while handling task queues and r...
def run(self): logging.info("%s active!", self._name) try: task_xml_info = TaskXmlReader.read_task_definition(self.task_file, self.task_name) logging.debug("Loaded task information from XML: %s.%s", task_xml_info.class_module, task_xml_info.class_na...
def _divide_boundary_evenly(self): """ Divide the boundary evenly by the arc length s. s=1 for divide how :return: s values for startpoint, midpoint, endpoint and arclength for each element. """ num_elements = self.N_init if not isinstance(num_elements, int) or nu...
This method generates detailed boundary element data for Boundary Element Method (BEM) calculations. It creates an array storing 13 parameters per element, including coordinates, normal/tangent vectors, curvature, and segment endpoints. The boundary is divided evenly for 'even' element type, with vector-supported shape...
def _generate_boundary_elements(self): """ Generate detailed information of boundary element used for BEM according to the shape and N_init. Notice: This method is only executable for shapes with vector-supported methods. Rewrite this method or do not inherit this class for boundary sha...
def _set_params(self, size_params): """ Set the parameters for the cavity. :param size_params: """ self.R, self.d = size_params def _compute_perimeter(self): return self.find_s_for_theta(2 * pi) def _generate_boundary_elements(self): """ Generate detailed ...
This code initializes a polar-coordinate-based cavity structure by setting parameters, calculating perimeter, generating boundary elements, adjusting the center, and determining the actual number of elements (N) based on the generated boundary elements.
def __init__(self, size_params, N_elements, element_type='even', center=(0, 0)): """ Initialize the SingleCavityPolar defined in polar system. :param size_params: Tuple. Size parameters to define the cavity. :param N_elements: Number of boundary elements :param center: Center of ...
def optimal_weights(n_points, er, cov): target_rs = np.linspace(er.min(), er.max(), n_points) weights = [minimize_vol(target_return, er, cov) for target_return in target_rs] return weights def portfolio_returns(weights, returns): return weights.T @ returns def portfolio_vol(weights, covmat): return ...
The function `plot_ef` generates and visualizes the **multi-asset efficient frontier** by calculating optimal portfolio weights, returns, and volatilities across `n_points`. It plots the frontier as a line graph of volatility vs. returns. Optional parameters allow adding key points: the **global minimum variance portfo...
def plot_ef(n_points, er, cov, riskfree_rate=0 ,show_cml=False,show_ew=False,show_gmv=False): """ Plots the multi-asset efficient frontier """ weights = optimal_weights(n_points, er, cov) rets = [portfolio_returns(w, er) for w in weights] vols = [portfolio_vol(w, cov) for w in weights] ef = ...
def listcreator(self,l): self.l2 = [] for i in l: self.l2.append(list(self.jsonvals[i]["SLOTS"].keys())) return self.l2 def timetable(self,l,ind = 0): if ind == len(l): return True else: course = l[ind] lorp = 'P' if cou...
The main task of the code is to generate and display a timetable by processing input data through `listcreator` and `timetable` methods. It sets the schedule using `set_sch`, checks validity via `self.t`, and prints the schedule if valid. If invalid, it prompts the user to try different subjects.
def final_generation(self): self.l2 = self.listcreator(self.l) self.t = self.timetable(self.l) self.set_sch(self.final_alloted) #self.print_sch(self.schedule) if self.t: self.print_sch(self.schedule) else: print('not possible try different set of s...
def listcreator(self,l): self.l2 = [] for i in l: self.l2.append(list(self.jsonvals[i]["SLOTS"].keys())) return self.l2 def timetable(self,l,ind = 0): if ind == len(l): return True else: course = l[ind] lorp = 'P' if cou...
The code generates a timetable by creating a list (`self.l2`), generating a timetable (`self.t`), setting the schedule (`self.set_sch`), and printing it if valid. If invalid, it prompts the user to try different subjects. The method returns after handling these steps.
def final_generation(self): self.l2 = self.listcreator(self.l) self.t = self.timetable(self.l) self.set_sch(self.final_alloted) #self.print_sch(self.schedule) if self.t: self.print_sch(self.schedule) else: print('not possible try different set of s...
def my_leq(left_side: int, right_side: int) -> bool: """Returns whether an integer is lesser-than or equal to another.""" return left_side <= right_side def my_mul(multiplier: int, multiplicand: int) -> int: """Calculates the product of two integers.""" product = 0 while my_leq(1, multiplicand): ...
The code computes the bitwise AND of two integers by iteratively checking each bit, using arithmetic operations to simulate bit manipulation. It processes each bit from least to most significant, calculates the AND for each pair of bits, and accumulates the result by shifting and adding. The loop continues until both i...
def my_and(arg1: int, arg2: int) -> int: """Calculates the bitwise and of two integers.""" result = 0 temp = 1 while my_leq(1, my_mul(arg1, arg2)): # we look at the first bit of a and b by checking if the number is odd or even # for this we use the modulo operator (a mod 2 and b mod 2) ...
def my_leq(left_side: int, right_side: int) -> bool: """Returns whether an integer is lesser-than or equal to another.""" return left_side <= right_side def my_add(augend: int, addend: int) -> int: """Calculates the sum of two integers.""" return my_sub(augend, my_sub(0, addend)) def my_mod(dividend: in...
The code computes the bitwise inclusive OR of two integers by iteratively checking each bit position, adding the corresponding power of two to the result if either bit is set, and shifting the operands right until all bits are processed.
def my_or(arg1: int, arg2: int) -> int: """Calculates the bitwise inclusive or of two integers.""" result = 0 temp = 1 while my_leq(1, my_add(arg1, arg2)): if my_leq(1, my_add(my_mod(arg1, 2), my_mod(arg2, 2))): result = my_add(result, temp) temp = my_mul(temp, 2) arg...
def my_leq(left_side: int, right_side: int) -> bool: """Returns whether an integer is lesser-than or equal to another.""" return left_side <= right_side def my_add(augend: int, addend: int) -> int: """Calculates the sum of two integers.""" return my_sub(augend, my_sub(0, addend)) def my_mod(dividend: in...
The code computes the bitwise XOR of two integers by iteratively checking each bit, using arithmetic operations to simulate the XOR logic. It processes each bit pair, constructs the result by adding the appropriate power of 2 based on the XOR outcome, and shifts bits right until all positions are evaluated.
def my_xor(arg1: int, arg2: int) -> int: """Calculates the bitwise exclusive or of two integers.""" result = 0 temp = 1 while my_leq(1, my_add(arg1, arg2)): temp2 = my_add(my_mod(arg1, 2), my_mod(arg2, 2)) if my_leq(temp2, 1): result = my_add(result, my_mul(temp2, temp)) ...
def my_and(arg1: int, arg2: int) -> int: """Calculates the bitwise and of two integers.""" result = 0 temp = 1 while my_leq(1, my_mul(arg1, arg2)): # we look at the first bit of a and b by checking if the number is odd or even # for this we use the modulo operator (a mod 2 and b mod 2) ...
The code tests the correctness of custom logic functions `my_and`, `my_or`, and `my_xor` by comparing their outputs with Python's built-in bitwise operators (`&`, `|`, `^`) for given integer inputs.
def test(arg1: int, arg2: int) -> None: """Tests the logic operations.""" assert arg1 & arg2 == my_and(arg1, arg2) assert arg1 | arg2 == my_or(arg1, arg2) assert arg1 ^ arg2 == my_xor(arg1, arg2)
def lista_de_codigos_productos(): codigos=[] if len(productos)==0: codigos=[] else: [codigos.append(producto["codigo"]) for producto in productos if "codigo" in producto] return sorted(codigos,reverse=True) def posicion_de_codigo_ordenado_decre_de_productos(...
La función realiza una compra verificando si hay stock suficiente para un producto específico. Si la cantidad solicitada es menor o igual al stock disponible, actualiza el stock y registra la venta; de lo contrario, lanza un error indicando la falta de stock.
def realizar_compra(codigo_producto, cantidad): global ventas lista_de_codigos = lista_de_codigos_productos() posicion=posicion_de_codigo_ordenado_decre_de_productos(codigo_producto) if hay_stock(codigo_producto) and cantidad <= productos[posicion]["stock"]: ...
def reset_dimensions(self): self.length = 3.3 * self.scale self.width = 2. * self.scale self.height = 1.5 * self.scale self.wheel_radius = 0.57 * self.scale self.wheel_width = 0.48 * self.scale self.wheel_offset = 0.2 * self.scale self.wheel_base = 1.9 * self.scal...
This code initializes a class instance by setting up references to game settings, screen, statistics, and workspace objects. It calculates an offset based on map position and settings, then calls methods to reset dimensions, motion parameters, and positions, preparing the object for game operations.
def __init__(self, settings, screen, game_stats, workspace, scale=39): self.settings = settings self.screen = screen self.game_stats = game_stats self.workspace = workspace self.scale = scale self.R_view = self.workspace.R_view self.offset = self.workspace.map_po...
def box_to_matrix(box): """Converts a box tuple (in [Lx, Ly, Lz, xy, xz, yz] order with HOOMD meanings) into a box matrix""" (Lx, Ly, Lz, xy, xz, yz) = box return np.array([[Lx, xy*Ly, xz*Lz], [0, Ly, yz*Lz], [0, 0, Lz]], dtype=np.float64) def wrap(b...
This method rescales a system's coordinates and box to ensure the shortest distance between any two points equals the specified value 'l'. It calculates the current minimum distance (from box vectors or pairwise positions), then scales all coordinates and the box by the ratio of 'l' to this minimum distance, returning ...
def rescale_shortest_distance(self, l): """Rescale the system to have the given shortest distance between points The box and all coordinates are scaled by an appropriate factor to produce a system with the given shortest distance between any two points. This method is currently N^2 in t...
def load(image_file): image = tf.io.read_file(image_file) image = tf.image.decode_jpeg(image) w = tf.shape(image)[1] w = w // 2 real_image = image[:, :w, :] input_image = image[:, w:, :] input_image = tf.cast(input_image, tf.float32) real_image = tf.cast(real_image, tf.float32) return input_image,...
The main task of the code is to load an image file, apply random jittering to both input and real images for data augmentation, normalize the images to standardize pixel values, and return the processed input and real image pairs for training a machine learning model, likely in a generative adversarial network (GAN) co...
def load_image_train(image_file): input_image, real_image = load(image_file) input_image, real_image = random_jitter(input_image, real_image) input_image, real_image = normalize(input_image, real_image) return input_image, real_image
def oblate_pertubations(pos): ''' Calculates the Pertubations from the Effects of Oblateness of Earth through J2 Model. J2 Perturbations: Pg 664 HD Curtis Parameters: ----------- pos: array This initializes the position state variable. Output: ...
The function `f2` computes the instantaneous derivative of velocity (acceleration) by combining gravitational acceleration from a central body, oblate perturbations, and drag effects (if enabled). It takes position (`pos`) and velocity (`vel`) as inputs, applies the gravitational term `(-MU/|pos|³ * pos)`, adds oblate ...
def f2(pos,vel): '''Differential Equation - Function: d(x2) = -u . x1 P P ----- ------- + oblate + drag , x1 = r, x2 = v dt (x1)^3 Parameters: ----------- pos: array This initializes the position ...
def RK4_a(pos,vel,h): """ To Calculate Value of (a) of RK-4: v_a = f(v_x). """ v_ax, v_ay = np.zeros(3), np.zeros(3) v_ax = f1(pos,vel) v_ay = f2(pos,vel) return v_ax,v_ay def RK4_b(pos,vel,v_ax,v_ay,h): """ To Calculate Value of (b) of RK-4: v_b = f(v_x + (h/2)v_a) """ ...
The code propagates a satellite's position and velocity over a specified time using the RK-4 method, integrating state variables with optional drag perturbations. It iteratively computes intermediate acceleration terms (a, b, c, d) and updates the state vectors via weighted averaging. The function returns the final pro...
def propagate(pos,vel, time, h_step_size = 1, drag=False): """Propogate the State Variables. The Propogator here uses the initial State Vectors and RK - 4 to approximate the subsequent system of State Variables. RK - 4: X(n+1) = X(n) + h (a + 2*b + 2*c + d) ...
def load_known_cases(): with open("oyez/case_summaries.json") as handle: known_summaries = json.load(handle) known_map = { (summary["term"], summary["docket_number"]): summary for summary in known_summaries } return (known_summaries, known_map) def find_missing(known_map, years):...
The main task of the code is to identify cases updated on the server but missing locally, fetch their details and transcripts, and update the local case summaries with successfully retrieved entries. It loads existing summaries, detects gaps using specified years, retrieves missing data, and writes updated summaries to...
def main(): """ Find any cases that the server is updated with but we don't have locally and fetch the case info and transcripts for them. For all cases this is succesful for, also update case_summaries """ (known_summaries, known_map) = load_known_cases() missing_summaries = find_missing(kn...
def create_output_directory(self, analysis): if analysis == 'blast_analysis': dirs = [ self.parameters.blast_out, self.parameters.seq_path, ] for directory in dirs: if os.path.exists(directory): shutil.rmt...
The code executes different bioinformatics analyses based on parameters: BLAST, HMM, BUSCO, or full analysis. It creates output directories, processes sequences, and retrieves lineage data for each analysis type. The main task is to manage and execute multi-step analysis pipelines for gene similarity, hidden Markov mod...
def run(self): if self.parameters.blast_analysis: self.parameters.seq_dicio = { 'out_blastp.6': ['', 'Multiple species'] } self.create_output_directory(analysis='blast_analysis') self.get_similar_genes() if self.parameters.hmm_analy...
def read_features(dir_path): mydic = {} key = set() to_remove = [] for path in os.listdir(dir_path): if(os.path.isfile(os.path.join(dir_path, path))): file_with_extension = os.path.splitext(path) file_name = file_with_extension[0] file_extension = file_with_...
The code generates a secured biometric template by transforming minutiae points using geometric operations. It reads features from a database, processes each minutiae point relative to singular points, applies rotation and translation adjustments, and saves the modified coordinates. The algorithm reduces intra-subject ...
def generate_secured_template(database = "Database"): dic, key = read_features(database) key = sorted(key) s0, p0, q0, r0 = read_keyset() for a in key: minutiae = a + "_m" singular = a + "_s" minutiae_list = dic[minutiae] singular_list = dic[singular] n = len(m...
def _find_current_patch_index(self): return self._find_patch_index(self.current_patch) def _get_differential_revision_in_patch(self, patch_index): prev_patch = None if patch_index > 0: prev_patch = self._stack[patch_index - 1] for commit in self._commits_in_reverse(self._sta...
This function generates and executes an 'arc diff' command to create/update a differential revision in Phabricator. It checks the current patch index, handles edge cases (untracked branch, bottom of stack), constructs the command with appropriate options (--create, --update, --edit) based on patch relationships, and ru...
def arc_diff(self, edit_diff): current_patch_index = self._find_current_patch_index() if current_patch_index < 0: print('Cannot diff: current branch not tracked in gack') elif current_patch_index == 0: print('Cannot diff bottom of stack! gack push first') else: ...
def _generate_agents(self): list_of_agents = [] for number in range(self.num_agents): # agents are initially generated neutral and # their scepticism follows a normal distribution around the average scepticism level list_of_agents.append(agent.Agent(opinion=0, ...
The main task of the code is to initialize a multi-agent simulation environment with specified parameters such as agent types, connectivity structure, and communication protocols. It creates agent entities, establishes inter-agent connections, detects and resolves isolated agents, and configures protocols for informati...
def __init__(self, num_agents, num_liars, num_experts, num_connections, cluster_distance, num_news, num_steps, connectivity_type, communication_protocol="random", ...
def converged(self): if all([agent.convinced for agent in self.agent_list]): return True else: return False def all_contacted(self): # assume all agents have been contacted all_contacted = True for agent_index, agent in enumerate(self.agent_list): ...
The main task of the code is to simulate a multi-agent communication process, tracking convergence or full contact conditions. It iterates through steps, executes a communication protocol, and records results in a DataFrame if stepwise output is enabled. The simulation stops early if convergence or full contact is achi...
def run_simulation(self, verbose=False, stepwise=False): final_step = 0 skip_step = 10 # how often to print with step-wise run_results_df = pd.DataFrame() # to decrease the number of lines in the csvs we count only the steps in which agents actually communicated successful_steps...
def loadlines(root, checkvalid=True): if is_dict(root): lines = [] with open(root, 'r') as f: # files = [line.rstrip().split()[-1] for line in f.readlines()] files = [line.rstrip().split() for line in f.readlines()] if checkvalid: files = [topath(l...
The function builds a dataset based on tuning mode and repetition settings. If not tuning, it loads the base training dataset. For meta-tuning, it either repeats the meta dataset or constructs a dynamic few-shot dataset using train data and metadata, scaling by repetition factors. The task involves conditional dataset ...
def build_dataset(dataopt): # Base training dataset if not cfg.tuning: return loadlines(dataopt['train']) # Meta tuning dataset if cfg.repeat == 1: return loadlines(dataopt['meta']) else: if 'dynamic' not in dataopt or int(dataopt['dynamic']) == 0: return loadlin...
def highlight_text(text, offset, uniq_spans): """ Given a string and the annotations which fall within this string, highlights the concepts. """ # index of break, type of break (n = nothing) breaks = [(0, "n"), (len(text), "n")] for span in uniq_spans: breaks.append((span.start - of...
The function processes a sentence by identifying annotations related to chemical and disease entities, highlights them in the text, extracts their names, and wraps the text in a span tag if both entity types are present. It returns the extracted names and formatted text.
def process_sentence(chem, dise, sentence): spans = [annot for annot in sentence.annotations if not {chem, dise}.isdisjoint(annot.uid.uid)] form_text = highlight_text(sentence.text, sentence.start, spans) names = grab_names(spans) if len(set(v.stype for v in spans)) == 2: form_text = add_simp...
def list_files( self, folder_id: str, folders_only: bool = False, next_page_token: str = None ): """list all items within a folder""" q = f"parents = '{folder_id}'" if folders_only: q += " and mimeType = 'application/vnd.google-apps.folder'" return ( ...
This function moves all files or folders from a specified source folder to a destination folder, with an option to move only folders. It handles pagination for large datasets, logs the total number of moved items, and updates the file locations accordingly.
def move_all_content_location( self, old_folder: str, new_folder: str, folders_only=False ): """ "Moves" all files in one folder to another folder. :param old_folder: folder to move from :param new_folder: folder to move to :param folders_only: only move folders (i.e...
def Story(): global topic global points global turns turns=0 print("The stories to play with are:\n") print("""1. Sleeping Beauty.\n2. The Golden Egg.\n3. Max's Encounter with the Aliens.\n4. The Lion and the Mouse.\n5. Boy who Cried Wolf\n6. The Bear and the Two Friends. 7. Count Wisely.\n8. Ex...
This code presents a menu-driven Mad Libs game launcher. It displays four options: Story, Collective Nouns, Proverbs, and Exit. Based on user input, it sets global variables and invokes corresponding game functions. The loop continues until the user selects "Exit," which terminates the program with a farewell message.
def Mmain(): global choice global topic con=True while con: time.sleep(2) print("The subgames available are:\n") print("1. Mad Libs for Stories.\n2. Mad Libs for Collective Nouns.\n3. Mad Libs for Proverbs.\n4. Exit\n") op=input("Enter your choice:") if op=="1": ...
def random_board(board): ran_list = [] new_board = [] queens_list =[] new_board = copy.deepcopy(board) for i, value in enumerate(board): ran_list.append(random.randint(0,len(board)-1)) for i, value in enumerate(ran_list): queens_list.append((value,i)) new_board[value][i...
This code implements a parallelized search algorithm to solve a board configuration problem (likely N-Queens) by iteratively generating random boards, evaluating available moves, updating queen positions, and checking for solutions. It uses shared variables for inter-process communication, restarting when repeated stat...
def loop(board,return_dict,num,quit,foundit,full_board): all_tries = [] count = 0 num = 1 queens_list = [] board,queens_list = random_board(full_board) print_current_try(queens_list) while not quit.is_set(): start_time = time.time() curr_try = print_current_tr...
def get_input(): return [line.strip() for line in open("../input/day3", "r")] def part_1(data): gamma, epsilon = get_gamma_epsilon(data) return int(gamma, 2) * int(epsilon, 2) def part_2(data): """ Need to recalculate gamma and epsilon after each filtering """ o2_list = [d for d in data] ...
The code's main task is to retrieve input data using `get_input()`, process it with two functions `part_1` and `part_2`, and return their results. It separates the problem into two parts, solving each sequentially and combining their outputs as the final solution.
def solve(): data = get_input() return part_1(data), part_2(data)
def open_image(): filepath = filedialog.askopenfilename() image = Image.open(filepath) photo = ImageTk.PhotoImage(image) label = tk.Label(image=photo) label.image = photo # keep a reference! label.pack() return image def registernaor(image, num_shares): print("Please select a point in t...
The code registers a user by splitting an original image into a specified number of shares using a secret sharing algorithm. It prompts the user for the number of shares, processes the image with `registernaor()` to generate share coordinates (x, y), and stores these shares with `addxynum()` for later retrieval or reco...
def register(): original_image = open_image() r = 99 tolerance = 15 # Ask the user for the number of shares num_shares = simpledialog.askinteger("Input", "Enter the number of shares:",parent=root) # Register the user x, y = registernaor(original_image, num_shares) addxynum(x,y,num_shar...
def placeholder(self): """Initialize the placeholders for the visible units""" self.vu = tf.placeholder(shape=[None, self.Nvisible], dtype="float32") def data_pipeline(self): """Define the data pipeline""" # placeholder for the batch_size self.batch_size = tf.placeholder(tf.int6...
The code generates a computational graph for an RBM model by initializing placeholders, data pipelines, and network parameters, setting up Gibbs sampling for visible unit sampling, defining a loss function, and configuring an Adam optimizer with batch-size-adjusted learning rate.
def generate_graph(self): """Call the different RBM modules to generate the computational graph""" log.info("Creating the computational graph") self.placeholder() # create the visible units placeholder self.data_pipeline() # data_pipeline self.init_parameters() # initialize ...
def time(self): """Time a particular section of the code - call this once to set the state somewhere in the code, then call it again to return the elapsed time since last call. Call again to set the time and so on... Returns: float: if timer started time in seconds since the...
The main task of the code is to train a generative model using Gibbs sampling and gradient-based parameter updates. It processes training and test user/affinity matrices, constructs a computational graph, performs iterative model training over epochs, tracks RMSE and precision metrics, and returns the total training ti...
def fit(self, xtr, xtst): """Fit method Training in generative models takes place in two steps: 1) Gibbs sampling 2) Gradient evaluation and parameters update This estimate is later used in the weight update step by minimizing the distance between the model and the emp...
def maxSingularValue(L): from scipy.sparse.linalg import svds #maximum value of singular value decompositon # u, s, vt = svds(L, k=1) return s[0] def gradmat(Nin): Bxy = sparse.lil_matrix((2*Nin*Nin, Nin*Nin),dtype=np.float32) #x,y# x = np.arange(Nin) y = np.arange(Nin) x2 = (x.repea...
The code performs PSF deconvolution on an observed image using the Primal-Dual splitting method, incorporating regularization, iteration control, and cost analysis. It loads input matrices, computes hyperparameters, executes the deconvolution algorithm, and outputs the reconstructed image along with optional cost funct...
def main(): import argparse parser = argparse.ArgumentParser( description='Perform PSF deconvolution via Primal-Dual splitting' ) parser.add_argument("--psfmat", type=str, default='psf.mat', help="A: Observation matrix") parser.add_argument("--obsimg", type=str, default='obs.raw', help="Y: O...
def check_winner(self, player): for i in range(3): if all(self.board[i][j] == player for j in range(3)) or all( self.board[j][i] == player for j in range(3) ): self.game_over = True return True if all(self.board[i][i] == player for...
The main task of the code is to determine the game's outcome by checking if the player ("X") or AI ("O") has won, or if the game ended in a draw due to a full board, then displaying the corresponding result message.
def check_game_state(self): if self.check_winner("X"): self.show_message(f"{self.player_name} wins!") elif self.check_winner("O"): self.show_message("AI wins!") elif self.is_board_full(): self.show_message("It's a draw!")
def check_winner(self, player): for i in range(3): if all(self.board[i][j] == player for j in range(3)) or all( self.board[j][i] == player for j in range(3) ): self.game_over = True return True if all(self.board[i][i] == player for...
The code handles a player's move in a game by placing their symbol on the board if the cell is empty and the game isn't over. It updates the UI, checks for a win or draw, and switches players if needed, ensuring proper game state transitions and user feedback.
def make_move(self, row, col): if not self.game_over and self.board[row][col] == " ": self.board[row][col] = self.current_player self.buttons[row][col].config(text=self.current_player, state="disabled") if self.check_winner(self.current_player): self.show_mes...
def get_ai_move_minimax(self, available_moves): best_val = float("-inf") best_move = None for move in available_moves: row, col = move self.board[row][col] = "O" eval = self.minimax(0, False) self.board[row][col] = " " if eval > best_...
The code's main task is to handle the AI's move in a Tic-Tac-Toe game by selecting an optimal or random move based on the AI level, updating the game board with "O", disabling the corresponding button, and checking the game state. It identifies available moves on a 3x3 grid, uses Minimax for "Hard" difficulty, or choos...
def make_ai_move(self): if not self.game_over: available_moves = [(i, j) for i in range(3) for j in range(3) if self.board[i][j] == " "] if self.ai_level == "Hard": move = self.get_ai_move_minimax(available_moves) else: move = self.get_random_m...
def create_menu(self): menu_bar = tk.Menu(self.root) self.root.config(menu=menu_bar) menu_bar.add_command(label="Main Menu", command=self.func) menu_bar.add_command(label="Player vs AI", command=self.func1) menu_bar.add_command(label="Reset", command=self.reset_game) menu...
This code initializes a Tic Tac Toe game GUI by setting up the root window, player names, game board, and UI components. It configures the window title, initializes an empty 3x3 board, sets the starting player ("X"), and prepares menus and boards. The `get_player_names()` method likely prompts users to input names for ...
def __init__(self, root): self.root = root self.root.title("Tic Tac Toe") self.player_names = {"X": "", "O": ""} self.current_player = "X" self.board = [[" " for _ in range(3)] for _ in range(3)] self.game_over = False self.create_menu() self.create_board_...
def data_users(): return data_db_user def list_user(data=data_users(), isBack=False, isPwd=False): view.text_in_line(liner='-') if isPwd: print(f" {'No.':<5}{'Username':<15}{'Password':<15}{'Role':<15}") else: print(f" {'No.':<5}{'Username':<15}{'Role':<15}") view.text_in_line(li...
This function allows users to select a user by number or username, validates input, handles recall scenarios, and uses fuzzy matching to find partial username matches. It ensures valid selection, recurses on invalid inputs, and prepares the selected user data for an update process.
def update_user(data=data_users(), isRecall=False): ratio = 80 user_selected = [] key = '' admin.header('Update User', 'Menu') list_user(data) if isRecall: key = input(' Pilih User [No] : ') back_to_menu(key) if not key.isnumeric(): print() vi...
def wash(self): self.run() def drain(self): self.run() def spin(self): self.run()
The code defines a `control_center` method that checks the value of `self.selected` and executes corresponding operations: `wash()`, `drain()`, or `spin()` based on the selected mode, acting as a dispatcher to route tasks to appropriate methods.
def control_center(self): if self.selected == "wash": self.wash() elif self.selected == "drain": self.drain() elif self.selected == "spin": self.spin()
def get_all_users(): """Gets all users currently on 'user.txt' and return all users as a list.""" with open("user.txt", "r") as f: # Reading from 'users.txt'. users = f.readlines() return users def get_all_tasks(): """Gets all tasks currently on 'tasks.txt' and return all tasks as a list.""...
The main task of the code is to generate a detailed user report, calculating metrics like total tasks, completion rates, and overdue task percentages for each user, then appending this structured data to 'user_overview.txt'. It processes all users and tasks, computes statistics, and formats the output in a user-friendl...
def create_user_overview(): """Creates a report about all details for each user, and appends it to 'user_overview.txt'.""" all_users = get_all_users() # Getting all current users. all_tasks = get_all_tasks() # Getting all current tasks. initiate_user_overview() # Writes header for user_overview. ...
def get_user_tasks(current_username): """Gets all tasks for a specific user and returns them as a list.""" all_tasks = get_all_tasks() # Getting all current tasks. my_tasks = [] # Declaring empty list to hold user's tasks. for task in all_tasks: # Looping through all tasks to get user's tasks and ap...
The code retrieves and displays all tasks for the current user in a formatted manner, showing task details like title, assignee, dates, and completion status. It allows the user to select a task and edit it if it's incomplete. The function uses task splitting and indexing to manage data, ensuring user-friendly output a...
def view_mine(current_username): """Prints all tasks for current user in a user-friendly format.""" my_tasks = get_user_tasks(current_username) # Getting all tasks for specific user and looping through them. for task in my_tasks: split_task = task.split(",") # Split line by "," to get hold of det...
def make_square(img): x, y, _ = img.shape size = max(x, y) new_img = np.zeros((size, size, 3), dtype=np.uint8) ax,ay = (size - img.shape[1])//2,(size - img.shape[0])//2 new_img[ay:img.shape[0]+ay,ax:ax+img.shape[1]] = img # Pad the new_img array with edge pixel values # Apply feathering eff...
This function processes camera frames by applying rotations, undistortion, blurring, and filters to each camera's image. It detects image points, triangulates them into 3D world coordinates, locates objects, applies Kalman filtering for tracking, and sends real-time object data via sockets and serial communication to d...
def _camera_read(self): frames, _ = self.cameras.read() for i in range(0, self.num_cameras): frames[i] = np.rot90(frames[i], k=self.camera_params[i]["rotation"]) frames[i] = make_square(frames[i]) frames[i] = cv.undistort(frames[i], self.get_camera_params(i)["intrins...
def advance(self): cur_char = self.source[self.current] self.current += 1 return cur_char def handle_string(self): while self.peek() != '"' and not self.is_at_end(): if self.peek() == "\n": self.line += 1 self.advance() if self.is_at_end()...
The main task of the code is to scan and identify tokens from input. It processes characters, handling strings, whitespace, newlines, numbers, and identifiers, delegating to specific methods based on the current character. It skips whitespace, tracks line numbers, and raises exceptions for unrecognized characters.
def scan_token(self): char = self.advance() match char: case '"': self.handle_string() case " " | "\t": pass case "\n": self.line += 1 case _: if char.isdigit(): self.handl...
def _handle_input(self): for event in pygame.event.get(): if event.type == pygame.QUIT or ( event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE ): quit() if event.type == pygame.KEYDOWN and self.snake and not self. direction_chage_fl...
The main task of the code is to run a game loop that continuously handles user input, processes game logic, and renders the game state while `self.play_again` remains `True`. The loop repeats these steps until `play_again` is set to `False`, effectively controlling the game's runtime.
def main_loop(self): while self.play_again == True: self._handle_input() self._process_game_logic() self._draw()
def atmospheric_density(state): """ Calculate the astmospheric density in kg/(m^3). This is based on temperature, pressure, and humidity. See also Picard, A., R. S. Davis, M. Glaser, and K. Fujii. "Revised formula for the density of moist air (CIPM-2007)." Metrologia. 45 (2008): 149-155. Ent...
The function calculates atmospheric dynamic viscosity by combining dry air and water vapor viscosities using temperature, humidity, and pressure data. It first checks for necessary state variables, computes dry air viscosity, then incorporates water vapor viscosity if humidity is present. The final viscosity is derived...
def atmospheric_viscosity(state): """ Calculate the astmospheric dynamic viscosity in kg/(m*s). This is based on temperature and humidity. I've used a relatively simple equation to combine the viscosities of dry air and water vapor, as listed in Melling, Adrian, Stefan Noppenberger, Martin Still, a...
def atmospheric_density(state): """ Calculate the astmospheric density in kg/(m^3). This is based on temperature, pressure, and humidity. See also Picard, A., R. S. Davis, M. Glaser, and K. Fujii. "Revised formula for the density of moist air (CIPM-2007)." Metrologia. 45 (2008): 149-155. Ent...
This function calculates the coefficient of drag (Cd) using Reynolds number (Re), Mach number (Mn), and atmospheric parameters. It accepts a state dictionary or direct Re/Mn inputs, computes Re/Mn from state data if needed, selects a drag calculation method (default: Miller), and returns Cd. It handles extrapolation wa...
def coefficient_of_drag(state=None, density=None, reynolds=None, mach=None, only_in_range=False): """ Calculate the coefficient of drag. This is based off of the Reynolds number, Mach number, and possibly other factors. Enter: state: a dictionary of the current state. See comm...
def sqrdSoundVel(temp_i, temp_e): return boltzmann/(beta*mu) * (temp_i/iMMW + temp_e/eMMW) def a_aux(x): k1 = sp.kn(1, x) k2 = sp.kn(2, x) k3 = sp.kn(3, x) result = np.where(k2 > 0.0, x*(0.25*(3.0*k3+k1)/k2-1.0), 1.5053) return result def aux_der(x): return - da_aux(1.0/x) / (x*x)
This function computes a complex physics-related quantity using input parameters transformed through exponential functions and derived coefficients. It calculates terms involving temperature ratios, Mach numbers, and auxiliary functions to return a combined result based on plasma dynamics or fluid mechanics principles.
def Den_r(logr, logTi, logTe, logv, j): Ti = np.exp(logTi) TiR = Ti*iMMW Te = np.exp(logTe) TeR = Te*eMMW te = boltzmann*TeR/(electronMass*cLight2) v = -np.exp(logv) cs2 = sqrdSoundVel(TiR, TeR) vnorm = v/cLight cs2norm = cs2/cLight2 machNumber2 = vnorm*vnorm / cs2norm in...
def magField(r, temp_i, temp_e, radialVel): return np.sqrt((1.0-beta)*massDensity(r, temp_i, temp_e, radialVel)*sqrdSoundVel(temp_i, temp_e)*8.0*np.pi) def eDens(r, temp_i, temp_e, radialVel): return massDensity(r, temp_i, temp_e, radialVel)/(eMMW*mu) def Iprim(x): return 4.0505/np.power(x, 1.0/6.0) * (1.0+...
The code computes a synchrotron radiation parameter using electron density, magnetic field, and temperature terms, involving modified Bessel functions and thermal effects to determine a radiation intensity component.
def xiSync(nu, r, temp_i, temp_e, v): theta = boltzmann*temp_e/(electronMass*cLight2) nu0 = electronCharge*magField(r, temp_i, temp_e, v)/(2.0*np.pi*electronMass*cLight) xM = 2.0*nu/(3.0*nu0*theta*theta) k2 = sp.kn(2, 1.0/theta) k2 = np.where(k2 > 0, k2, 1.0e100) return 4.43e-30*4.0*np.pi*eDens(...
def qee(r, temp_i, temp_e, v): theta = boltzmann*temp_e/(electronMass*cLight2) ne = eDens(r, temp_i, temp_e, v) return ne*ne*cLight*re*re*const.alpha*electronMass*cLight2 * \ np.where(theta < 1.0, 20.0/(9.0*np.sqrt(np.pi)) * (44.0-3.0*np.pi*np.pi) * np.power(theta, 1.5)*(1.0+1.1*the...
The function calculates the total bremsstrahlung emission coefficient by summing contributions from free-free (qee) and bound-free (qei) processes, then multiplying by a temperature-dependent exponential factor and the Gaunt factor to account for radiative efficiency at a given frequency.
def xiBremss(nu, r, temp_i, temp_e, v): qBremss = qee(r, temp_i, temp_e, v)+qei(r, temp_i, temp_e, v) return qBremss*np.exp(-planck*nu/(boltzmann*temp_e))*(planck/(boltzmann*temp_e))*gaunt(nu, temp_e)
def xiBremss(nu, r, temp_i, temp_e, v): qBremss = qee(r, temp_i, temp_e, v)+qei(r, temp_i, temp_e, v) return qBremss*np.exp(-planck*nu/(boltzmann*temp_e))*(planck/(boltzmann*temp_e))*gaunt(nu, temp_e) def xiSync(nu, r, temp_i, temp_e, v): theta = boltzmann*temp_e/(electronMass*cLight2) nu0 = electronCha...
The function calculates the opacity `kappa` by comparing blackbody radiation `bnu` with combined emission terms `xi` (bremsstrahlung and synchrotron). It returns `xi/bnu` if `bnu` exceeds 1% of `xi` times the height function, otherwise 50.0, representing a conditional opacity threshold.
def kappa(nu, r, temp_i, temp_e, v): bnu = 4.0*np.pi*blackbody_nu(nu, temp_e).value xi = xiBremss(nu, r, temp_i, temp_e, v)+xiSync(nu, r, temp_i, temp_e, v) return np.where(bnu > 1.0e-2*xi*height(r, temp_i, temp_e), xi/bnu, 50.0)
def eDens(r, temp_i, temp_e, radialVel): return massDensity(r, temp_i, temp_e, radialVel)/(eMMW*mu) def height(r, temp_i, temp_e): return np.sqrt(sqrdSoundVel(temp_i, temp_e))/keplAngVel(r) def SSD_temp(radius): """Disk surface temperature""" return np.power(SSD_qPlus(radius)/stefanBoltzmann,0.25) def ...
The code calculates the total radiative flux from an accretion disk by integrating over a frequency range (nuMin to nuMax) using an iterative method. It combines contributions from bremsstrahlung and synchrotron radiation, incorporating blackbody intensities, electron density, and Thomson scattering. The sum accounts f...
def qminus_dermer_fast(r, tempi, tempe, v): nuMin = 1.0e6 nuMax = 1.0e21 iter = 30 paso = np.power(nuMax/nuMin, 1.0/float(iter-1)) sum = 0.0 nu = nuMin theta = boltzmann*tempe/(electronMass*cLight2) ne = eDens(r, tempi, tempe, v) h = height(r, tempi, tempe) temp_SSD = np.where(r...
def eDens(r, temp_i, temp_e, radialVel): return massDensity(r, temp_i, temp_e, radialVel)/(eMMW*mu) def height(r, temp_i, temp_e): return np.sqrt(sqrdSoundVel(temp_i, temp_e))/keplAngVel(r) def xiBremss(nu, r, temp_i, temp_e, v): qBremss = qee(r, temp_i, temp_e, v)+qei(r, temp_i, temp_e, v) return qBrem...
This code calculates the total emitted flux from synchrotron and bremsstrahlung radiation processes in a plasma, integrating over a frequency range from 1e6 to 1e21 Hz. It computes optical depth (tau_es), blackbody radiation (bnu), and emission coefficients (xi), then accumulates the flux contribution (fluxx) weighted ...
def qminus_esin_fast(r, tempi, tempe, v): nuMin = 1.0e6 nuMax = 1.0e21 iter = 30 paso = np.power(nuMax/nuMin, 1.0/float(iter-1)) sum = 0.0 nu = nuMin theta = boltzmann*tempe/(electronMass*cLight2) ne = eDens(r, tempi, tempe, v) h = height(r, tempi, tempe) k_es = ne*thomson t...
def ResNet18_backbone(inputs): x = Conv2D(64, (7, 7), strides=2, padding='valid')(inputs) x = BatchNormalization()(x) x = Activation('relu')(x) x = MaxPooling2D((3, 3), strides=2)(x) b1 = res_block(x, n_filters=64, stride=1) b2 = res_block(b1, n_filters=128, stride=2) b3 = res_block(b2, n_f...
The code defines a neural network model named ShelfNet for image segmentation. It uses a ResNet18 backbone to extract features, applies 1×1 convolutions to adjust dimensions, and employs a decoder-encoder structure with skip connections and transpose convolutions to upscale features. The model outputs a 3-channel segme...
def ShelfNet(): # Inputs inputs = Input(shape=(224, 224, 3,)) # Backbone b1, b2, b3, b4 = ResNet18_backbone(inputs) f_input = b4 # 1 - 1*1 Convs b1 = conv1x1_block(b1, n_filters=64) b2 = conv1x1_block(b2, n_filters=128) b3 = conv1x1_block(b3, n_filters=256) b4 = conv1x1_block(b...
def insert_ticket(): train_results = select_from_table("train") for row in train_results: train_number = row[0] train_seats_left = row[4] # TODO : SKIP IF TICKET EXISTS OR TRAIN HAS NO SEATS LEFT if does_ticket_exist(train_number) or train_seats_left <= 0: continue ...
The main task of the code is to refresh GUI tables by connecting to an SQLite3 database, fetching data from "train", "ticket_info", and "transaction_details" tables, and populating corresponding UI elements with the retrieved records. The function executes `insert_ticket()` to handle ticket data before updating the tab...
def RefreshTables(self): #Connect to SqLite3 database and fill GUI table with data insert_ticket() write_to_table(self.ui.tableWidget_2, select_from_table("train", "Id", 0)) write_to_table(self.ui.tableWidget, select_from_table("ticket_info", "Id", 0)) write_to_table(self.ui.tab...
def buy_ticket(index): table = select_from_table("ticket_info", "Id", index).fetchone() fname = FirstName lname = LastName adress = Address phone = Phone username = UserName price = table[5] ticketid = table[0] execute_command( "INSERT INTO transaction_details ('Fname' , 'Ln...
The code's main task is to purchase a ticket using an index from a spin box, update a transaction details table with database data, and refresh UI tables. It retrieves the index, triggers the buy_ticket function, fetches transaction data, writes it to a table widget, and refreshes all tables for real-time updates.
def BuyTicket(self): index = int(self.ui.spinBox.text()) buy_ticket(index) write_to_table(self.ui.tableWidget_3, select_from_table("transaction_details")) self.RefreshTables()
def remove_ticket(index): transaction_table = select_from_table("transaction_details", "Id", index).fetchone() ticket_table = select_from_table("ticket_info", "Id", transaction_table[7]).fetchone() train_id = ticket_table[6] train_info = select_from_table("train", "Id", train_id).fetchone() train_se...
The main task of the code is to cancel a ticket by retrieving its index from a spin box, removing it via `remove_ticket()`, updating the transaction details table with refreshed data from the database, and refreshing UI tables to reflect changes.
def CancelTicket(self): index = int(self.ui.spinBox_2.text()) remove_ticket(index) write_to_table(self.ui.tableWidget_3, select_from_table("transaction_details")) self.RefreshTables()
def calc_ab(zi, Mi, **cosmo): """ Calculate growth rate indices a_tilde and b_tilde Parameters ---------- zi : float Redshift Mi : float Halo mass at redshift 'zi' cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, ...
The code calculates the concentration parameter (c) and related cosmological quantities (sigma, nu, formation redshift) for dark matter halos of given mass M at redshift z. It uses numerical optimization to solve for c, computes mass variance (sigma), dimensionless fluctuation (nu), and formation redshift (zf) using co...
def COM(z, M, **cosmo): """ Calculate concentration for halo of mass 'M' at redshift 'z' Parameters ---------- z : float / numpy array Redshift to find concentration of halo M : float / numpy array Halo mass at redshift 'z'. Must be same size as 'z' cosmo : dict Dictiona...
def _checkinput(zi, Mi, z=False, verbose=None): """ Check and convert any input scalar or array to numpy array """ # How many halo redshifts provided? zi = np.array(zi, ndmin=1, dtype=float) # How many halo masses provided? Mi = np.array(Mi, ndmin=1, dtype=float) # Check the input sizes for zi...
The code computes halo properties (concentration-mass relation and accretion history) using cosmological parameters and redshift inputs, based on Correa et al. (2015). It processes halo mass ($M_i$) and redshift ($z_i$) inputs, calculates either concentration ($c$), mass variance ($\sigma$), or accretion rates ($dM/dt$...
def run(cosmology, zi=0, Mi=1e12, z=False, com=True, mah=True, filename=None, verbose=None, retcosmo=None): """ Run commah code on halo of mass 'Mi' at redshift 'zi' with accretion and profile history at higher redshifts 'z' This is based on Correa et al. (2015a,b,c) Parameters ----...
def loadImages(self): pieces = ['2', '1'] for piece in pieces: if piece == '2': self.IMAGES[piece] = p.transform.scale(p.image.load('images/'+'bW'+'.png'), (self.SQ_SIZE, self.SQ_SIZE)) else: self.IMAGES[piece] = p.transform.scale(p.image.load('ima...
The main task of the code is to run a "Wolves Eat Sheep" game loop, handling user and AI moves alternately, updating the game state, rendering the game on screen, and checking for a win condition. It initializes Pygame, processes events, manages turn-based gameplay between player and AI, tracks moves, and displays resu...
def main(self): p.init() screen = p.display.set_mode((self.WIDTH, self.HEIGHT)) clock = p.time.Clock() screen.fill(p.Color('white')) gs = WES_Engine.WES_State() moveMade = True # True for wolf and False for Sheep self.loadImages() # only load images once before t...
def _initialize_population(self, pop_size, num_models): ''' Initializes the population for the genetic algorithm. pop_size: size of the population num_models: number of models in the ensemble returns population: random weight initialization for the ensemble ''' ...
This function implements a genetic algorithm to optimize ensemble model weights. It initializes a population, iterates through generations (5 total), calculates fitness scores, selects parents, performs crossover/mutation (10% mutation rate), and replaces the population with offspring. The best weights from each genera...
def _genetic_algorithm(self, optimizer, save_dir, resume=False): ''' Runs the genetic algorithm to optimize ensemble weights optimizer: optimizer to use for model parameter updates. ''' # Hyperparameters for genetic algorithm mutation_rate = 0.1 num_generations =...
def pilConversion(rgbPilImage): open_cv_image = np.array(rgbPilImage) # Convert RGB to BGR return open_cv_image[:, :, ::-1].copy() def getMaskMaterialFocus(material): templateImage = material.renderImage() materialMask = addBackgroundToRawMaterial(material).getchannel("A") borderMask = Image.eva...
The function compares a target image (targetRGB) with a material's template image, using a mask to focus on specific regions. It calculates and returns the confidence level of the match, optionally adjusting sensitivity via a threshold.
def matchMasked(targetRGB, material, threshold=None): targetImage = pilConversion(targetRGB) templateImage = material.renderImage() mask = getMaskMaterialFocus(material) alpha = pilToMask(mask) matchImage, confidence = findMatches(targetImage, pilConversion(templateImage.convert("RGB")), mask=alph...