dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def create_box_encoder( model_filename, input_name="images", output_name="features", batch_size=32 ): with tf.io.gfile.GFile(model_filename, "rb") as f: graph_def = tf.compat.v1.GraphDef() graph_def.ParseFromString(f.read()) with tf.Graph().as_default() as graph: tf.import_graph_def(...
The code processes a video to detect, track, and extract preprocessed facial frames. It uses a face detection model (retina) and a deep learning tracker (MARS) to identify and follow faces across frames. For each tracked face, it samples and resizes frames to a fixed size, organizing them into a 5D tensor for machine l...
def extract_preprocessed_frames_multiface(video_path): frame_size = (224, 224) max_cosine_distance = 0.7 nn_budget = None model_filename = "mars-small128.pb" encoder = create_box_encoder(model_filename, batch_size=1) metric = nn_matching.NearestNeighborDistanceMetric( "cosine", max_cosin...
def _dwt(sig: np.ndarray, level: int = 4) -> List[np.ndarray]: # Only detail coefficients are returned, thus lowest 2**level-th frequencies are discarded. _, *details = pywt.wavedec(sig, 'db4', mode='per', level=level) return details def _segment(sig: np.ndarray, win_length: int, hop_length: int) -> np.nda...
The function estimates tempo (BPM) of segments in a time-series signal using auto-correlation of a cascaded DWT filter bank. It processes the input signal with specified window/hop lengths, downsamples via DWT, segments coefficients, and converts each segment to BPM within [min_bpm, 2*min_bpm].
def tempo_series(sig: np.ndarray, fs: float, win_length: int = None, hop_length: int = None, dwt_level: int = 4, min_bpm: int = 80) -> np.ndarray: ''' Estimate the tempo (bpm) of the segments of a time-series signal. Uses auto-correlation of a cascaded DWT filter bank. :param sig: (1-...
def cate_entropy(df,attr,y): ''' calculate and return categorical entropy of attribute 'attr' of data 'df' ''' a=df[[attr,y]].value_counts().to_dict() # print(a) b=df[attr].value_counts().to_dict() # print(b) c=df[y].unique() a_key = a.keys() e = sum(b[i]/df.shape[0]*sum(-a[(i,j)]/b[i]*math.log(a[(i...
The function identifies the optimal attribute for splitting data in a decision tree by calculating and comparing information entropy. It evaluates each feature (categorical or numerical), computes entropy using dedicated functions, and selects the attribute with the minimum entropy as the best split point for subsequen...
def best_split_measure(df,y): attr_list = df.drop(y,axis=1).columns.tolist() # assign initial best split attribute and entropy best_split_attr = attr_list[0] best_split_entropy = 0 if df[best_split_attr].dtype=='O': best_split_entropy = cate_entropy(df,best_split_attr,y) else : nume_...
def minor_major_class(df,y): ''' return minority class and majority class of the data ''' d = df[y].value_counts().to_dict() d_key = list(d.keys()) all_equal = True for k in d_key[1:]: if d[d_key[0]] != d[k]: all_equal = False break if all_equal: return d_key[0], d_key[1] return...
The function identifies the best split value for a feature in a dataset by focusing on the minority class. It filters minority instances, removes outliers using inner fences, defines the minority range, and computes the optimal split within this range to balance class distribution.
def MCE(dat,col,y): ''' Find subset of instances within the minority range and return best split value ''' # counts = dat[y].value_counts().to_dict() # minor = min(counts, key=counts.get) minor, major = minor_major_class(dat,y) minor_df = dat[dat[y]==minor] # create set of minority insta...
def class_iden(df,y): """ Identify majority class and minority class for binary class data Parameters ---------- data : dataframe an input dataframe class_col : str a class column of data Returns: minor_class : a minority class of data major_class : a ...
The function performs quartile-pattern bootstrapping to generate balanced synthetic samples for imbalanced datasets. It identifies minority and majority classes, partitions the minority data into groups, and combines bootstrapped samples from lower partitions with direct samples from upper partitions and majority data....
def QPBT(data,class_col, s_size, b_size, npartition=4, normalize_method=None): ''' Quartile-pattern bootstrapping. ''' # define minor class and major class min_class, maj_class = class_iden(data, class_col) col_name = data.columns.values.tolist() # create bootstrap collection bootstrap_collection = [] ...
def stop_criteria(df,y): ''' stopping criteria condition for recursive partitioning ''' stop = False c = df[y].unique() if(len(c)==1): stop = True return stop def best_split_measure(df,y): attr_list = df.drop(y,axis=1).columns.tolist() # assign initial best split attribute and ...
This function implements a recursive partitioning algorithm to build a decision tree. It recursively splits data based on the best feature (categorical or numerical) and threshold, creating child nodes. Stopping criteria include reaching max depth, uniform class labels, or no remaining features. It handles feature sele...
def RPA(node,df,y,max_depth = 7, max_features = None): ''' recursive partitioning algorithm for building decision tree ''' # return leaf node if there is only 1 distinct value in class column if stop_criteria(df,y) == True: c = df[y].unique()[0] node.name = c return # return leaf node if tree r...
def cate_entropy(df,attr,y): ''' calculate and return categorical entropy of attribute 'attr' of data 'df' ''' a=df[[attr,y]].value_counts().to_dict() # print(a) b=df[attr].value_counts().to_dict() # print(b) c=df[y].unique() a_key = a.keys() e = sum(b[i]/df.shape[0]*sum(-a[(i,j)]/b[i]*math.log(a[(i...
The function identifies the best attribute for splitting in a decision tree using the Minimum Cross-Entropy (MCE) criterion. It calculates entropy for each feature (categorical or numerical) and selects the attribute with the lowest entropy as the optimal split. Numerical features use MCE to determine the best split va...
def MCE_best_split_measure(df,y): ''' find best split measure of data 'df' ''' attr_list = df.drop(y,axis=1).columns # assign initial best split attribute and entropy best_split_attr = attr_list[0] best_split_entropy = 0 if df[best_split_attr].dtypes=='O': best_split_entropy = cate...
def stop_criteria(df,y): ''' stopping criteria condition for recursive partitioning ''' stop = False c = df[y].unique() if(len(c)==1): stop = True return stop def MCE_best_split_measure(df,y): ''' find best split measure of data 'df' ''' attr_list = df.drop(y,axis=1).co...
The code builds a Minority Condensation Decision Tree (MCDT) by recursively partitioning data based on selected features. It checks stopping criteria (e.g., single class, max depth), drops redundant columns, selects features, determines optimal splits, and creates child nodes for categorical or numerical splits. Leaf n...
def MCDT(node,df,y,max_depth = 7, max_features = None): ''' Build and return Minority condensation decision tree ''' # return leaf node if there is only 1 distinct value in class column if stop_criteria(df,y) == True: c = df[y].unique()[0] node.name = c return # return leaf no...
def crossObstacle(self,x1,x2,y1,y2): obs=self.obstacles.copy() while(len(obs)>0): rectang=obs.pop(0) for i in range(0,101): for i in range(0,101): u=i/100 x=x1*u + x2*(1-u) y=y1*u + y2*(1-u) ...
The function connects two nodes by checking if a path between them crosses an obstacle. If it does, it removes the second node and returns False; otherwise, it adds an edge between the nodes and returns True.
def connect(self,n1,n2): (x1,y1) = (self.x[n1], self.y[n1]) (x2,y2) = (self.x[n2], self.y[n2]) if self.crossObstacle(x1,x2,y1,y2): self.remove_node(n2) return False else: self.add_edge(n1,n2) return True
def number_of_nodes(self): return len(self.x) def sample_envir(self): x=int(random.uniform(0,self.mapw)) y=int(random.uniform(0,self.maph)) return x,y def add_node(self,n,x,y): self.x.insert(n,x) self.y.append(y) def isFree(self): n = self.number_of_nodes() - 1 ...
This code expands a Rapidly-exploring Random Tree (RRT) or RRT* by adding nodes to the tree. It samples a new node, checks if it's collision-free, connects it to the nearest existing node, and optionally rewires connections in RRT* to optimize paths. The function returns updated node coordinates and parent relationship...
def expand(self,type): n=self.number_of_nodes() x,y=self.sample_envir() self.add_node(n,x,y) if self.isFree(): xnearest=self.nearest(n) self.step(xnearest,n) if type=='rrt-star': if self.goalFlag: self.c...
def number_of_nodes(self): return len(self.x) def add_node(self,n,x,y): self.x.insert(n,x) self.y.append(y) def nearest(self,n): dmin=self.distance(0,n) nnear=0 for i in range(n): if self.distance(i,n) < dmin: dmin=self.distance(i,n) ...
This function extends a Rapidly-exploring Random Tree (RRT) or RRT* by adding a new node toward a goal position. It identifies the nearest existing node, moves toward it, and connects the nodes. For RRT*, it checks if the goal is reached, connects the new node, finds neighboring nodes, and rewires the tree for optimal ...
def bias(self,ngoal,type): n=self.number_of_nodes() self.add_node(n,ngoal[0],ngoal[1]) nnear=self.nearest(n) self.step(nnear,n) if type=='rrt-star': if self.goalFlag: self.connect(nnear,n) return self.x, self.y, self.parent ...
def vectorize(film, allGenres): vector = [] # 1. normalise the year; apply weight yearNorm = YEAR_NORMS[film['year']] * YEAR_WEIGHT vector.append(yearNorm) # 2. normalise imdbRating imdbRatingNorm = (film['imdbRating'] - MIN_IMDB_RATING) / DIFF_IMDB_RATING vector.append(imdbRatingNorm) #...
The code initializes user and film data by reading CSV/JSON files, filtering movies, normalizing attributes, vectorizing films, and generating a user profile for recommendations. It computes weighted averages of user-rated films, creates a normalized vector space, and prepares data for subsequent recommendation generat...
def initRec(): global VECTOR_LENGTH global profileChanges # init profileChanges vector for i in range(0, TOTAL_RECS): profileChanges.append(np.zeros(VECTOR_LENGTH)) # read in the file and append to list data structure try: myFilmDataList = [] with open("../data/ratings....
def get_ip(proxy=False): request_arg = ["http://api.ipify.org/"] if proxy: request_arg += [proxy] response = send_request(*request_arg) if not response: return False return response["response"] def check(proxies): global force_ssl_support, protocols, proxy_judges if force_...
This script parses command-line arguments to check proxy servers for functionality. It supports input via direct list, file, or automatic fetching from spys.me. Proxies are tested against specified protocols (HTTP, HTTPS, SOCKS4/5), with options to enforce SSL, output valid proxies to a file, generate proxychains confi...
def main(): parser = LocalParser( description="Proxies checker in Python.", add_help=False) parser._positionals.title = "Positional arguments" parser._optionals.title = "Optional arguments" parser.add_argument("-h", "--help", action="help", help="Show this help message.")...
def _convert_train_codes_to_labels(self) -> None: """Converts singleton code to novel label.""" # Count the codes in the training set code_counts = Counter([code_span.code for code_span in self.train]) # Convert codes that appear only once to "novel" bucket for code_span in self....
The main task of the code is to prepare a dataset for training by converting code spans to labels, merging duplicate data points, creating a labeler, and initializing a vectorizer with specified features (span text, context, previous questions). It ensures novel spans are labeled, handles data deduplication, and sets u...
def prepare( self, span_text: bool, left_context: bool, right_context: bool, previous_question: bool, previous_question_number: bool, ) -> None: assert not self.is_prepared, "Dataset is already prepared" # Convert codes to labels # NOTE: This t...
def check_snapshot_exist(self, vbox_name, snapshot_name=None): snapshots = self.get_snapshot_lsit(vbox_name) if not snapshots: return False if snapshot_name in snapshots: return True return False def check_vbox_running(self, vbox_name): out, err ...
This function reverts a VirtualBox virtual machine (vbox_name) to a specified snapshot (snapsnot_name). If no snapshot name is provided, it uses a default. It checks if the snapshot exists, powers off the VM if running, restores the snapshot via VBox Manager, and restarts the VM on success. Errors like missing snapshot...
def revertsnapsnot_vbox(self, vbox_name, snapsnot_name=None): if not snapsnot_name: snapsnot_name = self.default_snapshot if not self.check_snapshot_exist(vbox_name, snapsnot_name): RevertMachineFailed(b'No target Snapshot') if self.check_vbox_running(vbox_name)...
def logging(self): f=open("Task4Log.txt","w+") for i in self.logHistory: f.write("=> %s\r\n" %(i)) f.close() def perform_interpolation(self,degree): self.logHistory.append("Performing interpolation") self.logging() """plots the interpolation of each chunk""" ...
The main task of the code is to perform linear interpolation by calculating extrapolation parameters, generating a LaTeX equation for the interpolated data, logging the process, and handling potential errors. It checks the extrapolation coefficient, computes a maximum length, executes interpolation, writes residuals, a...
def linearInterpolate(self): self.logHistory.append("Linear interpolation was called") self.logging() if self.ExtrapolationCoef ==0: print("Please check the extrapolation slider as there mush be an error in its code lines") else: self.maxLength=int(self.Extrapolat...
def logging(self): f=open("Task4Log.txt","w+") for i in self.logHistory: f.write("=> %s\r\n" %(i)) f.close() def perform_interpolation(self,degree): self.logHistory.append("Performing interpolation") self.logging() """plots the interpolation of each chunk""" ...
This code performs polynomial interpolation by checking the extrapolation coefficient, calculating interpolation parameters, generating a LaTeX equation for the polynomial, logging results, and handling errors. It uses the interpolation order, coefficients, and residuals to create a mathematical model for data approxim...
def polyInterpolate(self): self.logHistory.append("Polynomial interpolation was called") self.logging() if self.ExtrapolationCoef ==0: print("Please check the extrapolation slider as there mush be an error in its code lines") else: self.maxLength=int(self.Extrapol...
def linearInterpolate(self): self.logHistory.append("Linear interpolation was called") self.logging() if self.ExtrapolationCoef ==0: print("Please check the extrapolation slider as there mush be an error in its code lines") else: self.maxLength=int(self.Extrapolat...
The main task of the code is to set the chunk order based on user selection from a combobox, trigger linear or polynomial interpolation depending on the selected radio button, and log the action. It converts the combobox index to an integer, checks the interpolation type flag, executes corresponding interpolation metho...
def setChunkOrder(self): self.Chunkorder= int(self.ChunkNumberComboBox.currentIndex())+1 if( self.PolynomialInterpRadioBtn.isChecked() or self.LinearInterpRadioBtn.isChecked): if(self.interpolationTypeFlag ==0): self.linearInterpolate() elif(self.interpolationType...
def logging(self): f=open("Task4Log.txt","w+") for i in self.logHistory: f.write("=> %s\r\n" %(i)) f.close() def linearInterpolate(self): self.logHistory.append("Linear interpolation was called") self.logging() if self.ExtrapolationCoef ==0: print(...
The function `interpolationPrep` determines the interpolation method based on the input value `val`. If `val` is 0, it sets the interpolation type to linear and calls `linearInterpolate`; if 1, it sets the type to polynomial and calls `polyInterpolate`. For other values, it prompts the user to select a valid option fro...
def interpolationPrep(self, val): self.logHistory.append("The interpolationPrep function was called") self.logging() if val == 0: self.interpolationTypeFlag =0 self.linearInterpolate() elif val ==1: self.interpolationTypeFlag =1 self.polyIn...
def ChooseOrderComboBoxEdit(self): self.ChooseOrderComboBox.clear() self.lcdOrder.display(self.InterpolationOrder) for j in np.arange(1,self.InterpolationOrder+1): self.ChooseOrderComboBox.addItem(str("Order # " +str(j))) self.ErrorOptionsEnabling(self.axis,self.type) def po...
This method sets the interpolation order to the provided value, updates the UI combo box, and triggers either polynomial interpolation or preparation based on the interpolation type flag.
def InterpolationOrdersetting(self, val): self.InterpolationOrder=val self.ChooseOrderComboBoxEdit() if self.interpolationTypeFlag ==1: self.polyInterpolate() else: self.interpolationPrep(0)
def logging(self): f=open("Task4Log.txt","w+") for i in self.logHistory: f.write("=> %s\r\n" %(i)) f.close() def ChooseOrderComboBoxEdit(self): self.ChooseOrderComboBox.clear() self.lcdOrder.display(self.InterpolationOrder) for j in np.arange(1,self.Interpolat...
This method sets the interpolation order by updating the instance variable, logs the change, triggers a UI update, and conditionally executes either polynomial interpolation or preparation based on the interpolation type flag.
def InterpolationOrdersetting(self, val): self.logHistory.append("Interpolation order setting was made") self.logging() self.InterpolationOrder=val self.ChooseOrderComboBoxEdit() if self.interpolationTypeFlag ==1: self.polyInterpolate() else: self....
def get_filings(c: Company) -> List[Usd]: filings:List[Usd] = None if not hasattr(c, 'facts') or not hasattr(c.facts, 'dei'): return filings if hasattr(c.facts.dei, 'EntityPublicFloat'): units = c.facts.dei.EntityPublicFloat.units if hasattr(units, 'USD'): filings = uni...
This function parses SEC company JSON data, extracts key attributes, calculates statistical metrics from associated filings, and creates a graph node in the database representing the company. It also links the company node to individual filing records if available.
def import_company(company_json:bytes, db:Graph, trace=False) -> Node: """ Parse SEC Company JSON """ c: Company = json.loads(company_json, object_hook=lambda d: SimpleNamespace(**d)) if not hasattr(c, 'entityName'): if trace: print('Company is missing entityName attribute.'...
def get_vbo(self): vertex_data = self.get_vertex_data() vbo = self.ctx.buffer(vertex_data) return vbo def get_shader_program(self, shader_name): with open(f'shaders/{shader_name}.vert') as file: vertex_shader = file.read() with open(f'shaders/{shader_name}.frag') as f...
This code initializes a 3D rendering component by setting up OpenGL resources, including a vertex buffer object (VBO), shader program for a cube, vertex array object (VAO), and model matrix. It also calls an `on_init()` method for additional setup, using the provided application context (`app`) to configure rendering p...
def __init__(self, app): self.app = app self.ctx = app.ctx self.vbo = self.get_vbo() self.shader_program = self.get_shader_program('cube') self.vao = self.get_vao() self.m_model = self.get_model_matrix() self.on_init()
def getLayoutProbabilities(difficulty): if difficulty == 1: option1Probability = 3/4 option2Probability = 1/8 option3Probability = 1/16 option4Probability = 1/16 elif difficulty == 2: option1Probability = 1/4 option2Probability = 1/4 option3Probability = ...
The code generates a layer of game objects (drones and bombs) based on difficulty settings, using probabilistic decisions to add drones, bombs, or specialized bomb-drone combinations. It ensures at least one standalone drone for playability, separates objects into distinct lists, and returns them for game layer constru...
def buildLayer(app, difficulty, layer, n): totalList = [] mustHaveDroneCounter = 1 dronelist = [] bomblist = [] option1Probability, option2Probability, option3Probability, option4Probability = getLayoutProbabilities(difficulty) cx = random.uniform(app.width/(n*2.5), app.width/(n*2)) ...
def process_event(self, event): self.current_screen.process_event(event) def set_current_screen(self, screen_name): self.current_screen = self.screens[screen_name] self.current_screen.set_player(self.player) self.current_screen.refresh_screen() def reset_player(self): init_positi...
This code manages a game loop by processing events, updating the current screen, and handling state transitions. It checks if the game is running, dead, or in victory state, updating accordingly. If running, it processes events like quitting, updates the screen, draws it, and changes states if needed. If dead, it reset...
def tick(self): if self.state == game_states.RUNNING: for event in pg.event.get(): if event.type == pg.QUIT: self.complete = True self.process_event(event) new_screen = self.current_screen.update() if new_screen: ...
def load_truck_packages(truck1, truck2, truck3): # Manually Load Packages to truck method list1 = [1, 2, 5, 7, 10, 13, 14, 15, 16, 19, 20, 29, 33, 34, 37, 39] list2 = [3, 6, 8, 11, 12, 18, 23, 25, 27, 30, 31, 35, 36, 38, 40] list3 = [4, 9, 17, 21, 22, 24, 26, 28, 32] truck1.packages = list1 truc...
The main task of the code is to manage a package delivery system by loading data (packages, distances, addresses) into data structures, initializing truck objects with specific parameters, assigning packages to trucks, delivering packages using distance calculations, and optionally displaying delivery metrics like time...
def main(): # Main method # Hash table instance p_hash_table = HashTable.HashTable() # Distance List instance distance_data = [] # Address List instance address_data = [] # Load Packages to Hash Table CSVReader.load_package_data('CSV/Package Table.csv', p_hash_table) # Load Dis...
def remove_extraneous_pars(line): if check_openpar(line[0]) and check_closepar(line[-1]) and validpars(line[1:-1]): line = line[1:-1] return line def check_openpar(char): return char == par[0] def endpar(line,idx): count = 0 for i in range(idx,len(line)): if check_openpar(line[i]): ...
This function parses a mathematical expression string into terms (substrings representing variables, numbers, or parentheticals) and operators. It identifies parentheses, atoms (non-operator sequences), and operators, returning lists of term ranges and individual operators for further processing in an expression evalua...
def get_terms_ops(line): line = remove_extraneous_pars(line) terms = [] ops = [] i = 0 while i < len(line): if check_openpar(line[i]): idx = i i = endpar(line,i) + 1 terms.append([idx,i]) continue elif notop(line[i]): atomen...
def check_and(char): return char == ampersand def check_openpar(char): return char == par[0] def check_closepar(char): return char == par[1] def check_or(char): return char == disjunction def untilop(line,i): while i < len(line) and notop(line[i]): i += 1 return i
This function splits a given input string into segments based on logical operators ('and', 'or') and parentheses, ensuring proper handling of nested parentheses. It iterates through the string, identifying operator positions and splitting the string at these points while avoiding splits inside unmatched parentheses. Th...
def separate_into_sentences(line): lines = [] latest = [] i = 0 while i < len(line): if check_and(line[i]): lines.append(latest) latest = [] elif not check_openpar(line[i]) and not check_closepar(line[i]) and not check_or(line[i]): op = untilop(line,i)...
def check_openpar(char): return char == par[0] def remove_extraneous_pars(line): if check_openpar(line[0]) and check_closepar(line[-1]) and validpars(line[1:-1]): line = line[1:-1] return line def get_terms_ops(line): line = remove_extraneous_pars(line) terms = [] ops = [] i = 0 ...
The function `combine_ors` combines two logical expressions (`t1` and `t2`) using disjunction (OR) and conjunction (AND) operations, handling nested parentheses and structural complexities. It ensures proper parenthesization, swaps operands if needed, and recursively combines terms while respecting operator precedence....
def combine_ors(t1,t2): if not check_openpar(t1[0]) and not check_openpar(t2[0]): return t1 + disjunction + t2 t1 = remove_extraneous_pars(t1) t2 = remove_extraneous_pars(t2) terms1,ops1 = get_terms_ops(t1) terms2,ops2 = get_terms_ops(t2) if len(get_terms_ops(t2)[0]) == 1 or check_or(ops...
def recurse_pars(line,fxn_to_recurse): i = 0 lenline = len(line) while i < lenline: if check_openpar(line[i]): idx = i + 1 i = endpar(line,i) line,i,lenline = replace_get_endidx(line,idx,i,fxn_to_recurse(line[idx:i])) continue i += 1 return...
The main task of the code is to recursively identify and parenthesize consecutive "and" operations in a logical expression. It processes the input line, extracts terms and operators, iterates backward through operators, and wraps subexpressions between "and" operators in parentheses to enforce proper grouping. This ens...
def group_ands(line): line = recurse_pars(line,group_ands) terms,ops = get_terms_ops(line) for i in range(len(ops) - 1,-1,-1): if check_and(ops[i]): line,_,_ = replace_get_endidx(line,terms[i][0],terms[i + 1][1],parenthesize(line[terms[i][0]:terms[i + 1][1]])) return line
def recurse_pars(line,fxn_to_recurse): i = 0 lenline = len(line) while i < lenline: if check_openpar(line[i]): idx = i + 1 i = endpar(line,i) line,i,lenline = replace_get_endidx(line,idx,i,fxn_to_recurse(line[idx:i])) continue i += 1 return...
The function `groupsof2` processes a logical expression string by grouping terms connected by `AND` operations first, enclosing each `AND`-linked pair in parentheses. If remaining operations are `OR`, it similarly groups them. It recursively parses the input, identifies terms and operators, and iteratively replaces sub...
def groupsof2(line): line = recurse_pars(line,groupsof2) terms,ops = get_terms_ops(line) if len(terms) == 2: return line numands = 0 for i in range(len(ops) - 1,-1,-1): # going in backwards order to not deal with weird indexing if check_and(ops[i]): line,_,_ = replace_get...
def recurse_pars(line,fxn_to_recurse): i = 0 lenline = len(line) while i < lenline: if check_openpar(line[i]): idx = i + 1 i = endpar(line,i) line,i,lenline = replace_get_endidx(line,idx,i,fxn_to_recurse(line[idx:i])) continue i += 1 return...
This code processes a logical expression by replacing each occurrence of the equivalence symbol 'iff' with a logically equivalent conjunction of implications. It recursively handles nested structures, splits the expression around 'iff', transforms sub-expressions using negation and disjunction, and recombines them with...
def remove_iffs(line): iffs = line.count(iff) # assume only top level <=> if iffs != 0: line = recurse_pars(line,remove_iffs) alastidx = 0 for i in range(iffs): alastidx = line.index(iff,alastidx + len(iff)) if alastidx != 0 else line.index(iff) a = line[:alastidx] b = No...
def recurse_pars(line,fxn_to_recurse): i = 0 lenline = len(line) while i < lenline: if check_openpar(line[i]): idx = i + 1 i = endpar(line,i) line,i,lenline = replace_get_endidx(line,idx,i,fxn_to_recurse(line[idx:i])) continue i += 1 return...
The code processes a logical expression string to replace top-level "if" statements (represented by "=>" and "<=") with equivalent logical forms using negation and disjunction. It iteratively identifies the earliest occurrence of "=>" or "<=", applies parenthesization rules, and substitutes the implication with a negat...
def remove_ifs(line): totalifs = line.count(ifthen[0]) + line.count(ifthen[1]) # assume only top level ifs if totalifs != 0: line = recurse_pars(line,remove_ifs) totalifs = line.count(ifthen[0]) + line.count(ifthen[1]) # assume only top level ifs alastidx = 0 for i in range(totalifs): ...
def notop(char): # dont need to check for iffs and ifs bc already gotten rid of and we consider ! part of the literals if check_and(char): return False if check_or(char): return False return True def check_openpar(char): return char == par[0] def endpar(line,idx): count = 0 for i...
This function recursively processes a logical expression string to apply negations, handling parentheses and atomic elements. It traverses the input line, identifying operations, negations, and parentheses, then replaces sub-expressions with their negated forms or transformed values, ensuring proper syntax and structur...
def negate(line): i = 0 lenline = len(line) while i < lenline: if notop(line[i]): if check_openpar(line[i]): epidx = endpar(line,i) line,i,lenline = replace_get_endidx(line,i,epidx + 1,check_parenthesize(negate(line[i + 1:epidx]))) elif check_n...
def remove_extraneous_pars(line): if check_openpar(line[0]) and check_closepar(line[-1]) and validpars(line[1:-1]): line = line[1:-1] return line def recurse_pars(line,fxn_to_recurse): i = 0 lenline = len(line) while i < lenline: if check_openpar(line[i]): idx = i + 1 ...
The main task of the code is to apply De Morgan's Law to a logical expression, transforming AND operations into OR operations (and vice versa) while adjusting parentheses and removing extraneous ones. It recursively processes nested expressions, splits terms and operators, checks for valid structures, and recombines te...
def demorgan(line): line = remove_extraneous_pars(recurse_pars(line,demorgan)) terms,op = get_terms_ops(line) if len(terms) > 2: return line op = op[0] left = line[terms[0][0]:terms[0][1]] right = line[terms[1][0]:terms[1][1]] if check_and(op): # next few lines are probably o...
def check_negation(char): return char == negation def check_openpar(char): return char == par[0] def endpar(line,idx): count = 0 for i in range(idx,len(line)): if check_openpar(line[i]): count += 1 elif check_closepar(line[i]): count -= 1 if count == 0...
This function processes a string to propagate negations through parenthesized expressions. It iterates through the string, identifying negations followed by open parentheses. For each match, it locates the corresponding closing parenthesis, replaces the enclosed expression with its negated version wrapped in parenthese...
def propagatenegations(line): i = 0 lenline = len(line) while i < lenline: if check_negation(line[i]) and check_openpar(line[i + 1]): epidx = endpar(line,i) line,i,lenline = replace_get_endidx(line,i,epidx + 1,check_parenthesize(negate(line[i + 2:epidx]))) continu...
def get_args(): args = parse_args() filename = args.filename if args.filename else raw_input("Please enter the name of the text file: ") N = args.num_lists if args.num_lists else raw_input("Please enter the desired number of lists: ") F = args.num_inbetween if args.num_inbetween else raw_input("Please e...
The main task of the code is to process a text file containing experimental data, generate randomized lists using Latin square and LCM constraints, and output a CSV file for a Turk interface. It reads input parameters, validates configurations, creates randomized trial sequences, and exports results in a structured for...
def main(): filename, N, F, Y, seed = get_args() if seed is not None: random.seed(seed) FNAME = filename.split("/")[-1] FNAME = FNAME.split(".")[0] print() print("Processing the text file...") print() print("-------") with codecs.open(filename, encoding="utf-8") as ...
def check_collision(board, score, piece, row, col, quintris): return col+len(piece[0]) > quintris.BOARD_WIDTH or row+len(piece) > quintris.BOARD_HEIGHT \ or any( [ any( [ (c != " " and board[i_r+row][col+i_c] != " ") for (i_c, c) in enumerate(r) ] ) for (i_r, r) in enumerate(piece) ] ) def display_board...
The code evaluates possible Tetris moves by generating valid commands for a given piece, calculating scores for each, and selecting the optimal move. It uses a cost function to assess board states, considers future piece placements via Expectimax (though incomplete), and returns the command with the lowest score. Metri...
def evaluator(self, quintris, board, piece, ): ''' - Successor function that calls the game_commands_generator that returns the list of all possible commands that lead the piece to non-redundant states. - ''' # METRICS : #score_mtx = [[1*r if board[r][c] == 'x' else 0 for c in range...
def check_collision(board, score, piece, row, col, quintris): return col+len(piece[0]) > quintris.BOARD_WIDTH or row+len(piece) > quintris.BOARD_HEIGHT \ or any( [ any( [ (c != " " and board[i_r+row][col+i_c] != " ") for (i_c, c) in enumerate(r) ] ) for (i_r, r) in enumerate(piece) ] ) def animated_game...
The code evaluates the best move for a Tetris piece by analyzing the board's filled cells (score_mtx) and open spaces (open_space_mtx). It calculates row-wise scores and open space percentages, determines the collision row for the piece, generates possible game commands, and selects the optimal move using `animated_get...
def animated_evaluator(self, quintris, board, piece, ): score_mtx = [[1*r if board[r][c] == 'x' else 0 for c in range(len(board[0]))] for r in range(len(board)) ] open_space_mtx = [[1 if board[r][c] != 'x' else 0 for c in range(len(board[0]))] for r in range(len(board)) ] summed_up = [sum(arr) for arr in sc...
def move(self, dt): distance = 0 new_speed = 0 distance = (self.speed * dt) + (0.5 * GRAVITY * dt * dt) new_speed = self.speed + (GRAVITY * dt) self.rect.centery += distance self.speed = new_speed if self.rect.top < 0: self.rect.top = 0 ...
This code updates a bird's state in a game when it's alive, incrementing its lifespan, moving it, handling jumps based on pipes, drawing it, and checking collision/status with pipes to manage gameplay.
def update(self, dt, pipes): if self.state == BIRD_ALIVE: self.time_lived += dt self.move(dt) self.jump(pipes) self.draw() self.check_status(pipes)
def convert_adj_linkedlist(A): pn = A.shape[0] A_link = [] for i in range(pn): A_i_neighbor = [] for j in range(pn): if A[i, j] == 1: A_i_neighbor.append(j) A_link.append(A_i_neighbor) return A_link def extract_nonshared_edge(A, faces): A_single = ...
The function fills holes in a 3D mesh by identifying valid loops (circles) in the adjacency matrix, projecting points onto these loops, and adding new triangular faces to close gaps. It uses criteria like minimum non-shared edges and projection counts to determine which loops to fill, updating the adjacency matrix and ...
def fill_holes(faces, skel_p, input_p, A_init, A_recon, max_loop_len=9, min_nonshared_e=3, min_proj_v=3): A_loop_link = convert_adj_linkedlist(A_init) A_fill = copy.copy(A_init) f_init_num = len(faces) cir_id = 0 tmp_faces = copy.copy(faces) f2c_id = [] all_circles = [] # extract all l...
def extract_skel_face(A): pn = A.shape[0] faces = [] for i in range(pn): for j in range(i, pn): for k in range(j, pn): check1, check2, check3 = False, False, False if A[i, j] == 1 or A[j, i] == 1: check1 = True if A[i, k...
The function generates a mesh (faces and edges) from input points and skeletal structures, refining initial mesh parameters (A_init) towards final ones (A_final) using hole-filling and boundary refinement. It processes each batch element, handling exceptions by falling back to simpler edge extraction, and returns struc...
def generate_skel_mesh(input_xyz, skel_xyz, A_init, A_final): batch_size = skel_xyz.size()[0] input_xyz_np = input_xyz.detach().cpu().numpy() skel_xyz_np = skel_xyz.detach().cpu().numpy() A_init_np = A_init.detach().cpu().numpy() A_final_np = A_final.detach().cpu().numpy() A_mesh_np = np.zeros_l...
def do_crop(self, img): if self.crop_mode == 'random': return self.do_random_crop(img) elif self.crop_mode == 'additional': return self.do_additional_crop(img) elif self.crop_mode == 'original': return img def do_mixup(self, img, label, alpha=1.): idx ...
This function loads and preprocesses audio data by cropping, applying optional augmentations (mixup, gain, freqmask), normalizing, and reshaping the input image, then returns the processed data along with its corresponding label.
def __getitem__(self, index): img = np.load("{}.npy".format(self.X[index][:-4])) img = self.do_crop(img) label = self.y[index].astype(np.float32) if self.mixup and np.random.random() < 0.5: img, label = self.do_mixup(img, label) if self.gain and np.random.random() < ...
def do_scaling(self, snd, interpolate='Nearest'): scale = np.power(self.scaling, random.uniform(-1, 1)) output_size = int(len(snd) * scale) ref = np.arange(output_size) / scale if interpolate == 'Linear': ref1 = ref.astype(np.int32) ref2 = np.minimum(ref1+1, len(s...
This code loads an audio file, applies preprocessing steps like scaling, padding, cropping, mixup augmentation, gain adjustment, and normalization, then returns the processed audio tensor and corresponding label for a machine learning model training or evaluation.
def __getitem__(self, index): _, snd = wavfile.read("{}".format(self.X[index])) label = self.y[index].astype(np.float32) if self.scaling!=-1: snd = self.do_scaling(snd) snd = self.do_padding(snd) snd = self.do_crop(snd) if self.mixup: snd, label = ...
def _check_no_venv_in_workdir(self, workdir, project_name, venvname="venv"): venvdir_dst = workdir / venvname if venvdir_dst.exists(): print(f'The activate proxy inside "{venvdir_dst}" exis...
The main task of the code is to create a Python virtual environment for a specified project, ensuring no existing environment conflicts in the working directory. It first checks for existing environments, then creates a centralized virtual environment, and finally establishes a "proxied" environment within the project'...
def create_venv(self, project_name, workdir, system_site_packages=False): """ Parameters ---------- project_name: str The project name for which the virtual enviroment is created. This will be the virtual environment name in the folder where all the vi...
def draw_menu(WIN): text = font1.render("About the game", True, WHITE) WIN.blit(BUTTON, (-25, -20)) WIN.blit(text, (0, 0)) text1 = font1.render("Game levels", True, WHITE) WIN.blit(BUTTON, (175, -20)) WIN.blit(text1, (215, 0)) def draw_about_the_game(WIN): lines = [ "The purpose of t...
This code displays a game menu with a "START GAME" button and other options. It waits for a mouse click: if the "START GAME" button is pressed, it returns True to signal a game restart; otherwise, it navigates to "About the Game" or "Levels" sections based on mouse position. The loop runs at 30 FPS, updating the screen...
def start(WIN): # Wait for a mouse click while True: WIN.blit(END_BACKGROUND, (0, 0)) # Draw a button draw_menu(WIN) rendered_text = pygame.font.SysFont('Comic Sans MS', 50).render("START GAME", True, WHITE) WIN.blit(rendered_text, (WIDTH // 2 - 170, HEIGHT // 2 - 20)) ...
def dsn_names(): return {t[0] for t in dsn_vars()} def dsn_resource(n): return { "name": dsn_var(n, "JNDI_NAME"), "attrs": { "auth": "Container", "type": "javax.sql.DataSource", "url": dsn_var(n, "JDBC_URL"), "username": dsn_var(n, "USER"), ...
The function `dsn_opts` generates Tomcat resource configurations and links by iterating over names from `dsn_names()`, creating lists of resources and links using list comprehensions. It returns a dictionary with keys `"tomcat_resources"` and `"tomcat_resource_links"`, each mapping to dynamically generated lists of res...
def dsn_opts(): names = dsn_names() return { "tomcat_resources": [dsn_resource(n) for n in names], "tomcat_resource_links": [dsn_link(n) for n in names], }
def env(k, default=""): return os.environ.get(k, default) def ssl_opts(): if env("ENABLE_SSL") == "yes": return {"tomcat_self_signed": "yes", "tomcat_ssl_enabled": "yes"} return {} def dsn_opts(): names = dsn_names() return { "tomcat_resources": [dsn_resource(n) for n in names], ...
The code generates a YAML configuration file containing Tomcat-related variables, including environment settings, system identifiers (user/group IDs), SSL options, and connection parameters. It aggregates environment variables with defaults, combines memory arguments, and writes the structured data to the provided file...
def go(fp): with fp: vars = { "tomcat_censor_ansible_output": env("CENSOR_ANSIBLE_OUTPUT", "yes"), "tomcat_memory_args": " ".join( [env("TOMCAT_MEMORY_ARGS"), env("TOMCAT_EXTRA_ARGS")] ), "tomcat_java_home": env("JAVA_HOME"), "tomca...
def getFileReader(self, filePath): """ Get an iterator used to get each row in a CSV or XLSX file """ if f'.{FILE_TYPE_CSV}' in filePath: self.file = open(filePath, encoding="utf8") self.fileType = FILE_TYPE_CSV return csv.reader(self.file) elif f'.{F...
This code initializes a data processing object by reading a file, extracting headers, selecting specific columns, and preparing data according to parameters like returnColumns, default data types, and row limits. It processes file input, filters data, and structures output as dictionaries or other formats, with error h...
def __init__(self, filePath, returnColumns = None, defaultHeaders=None, defaultDataTypes=None, rowDataType=ROW_TYPE_DICT, noneStrings=DEFAULT_NONE_STRINGS, noneExceptions=None, rowLimit=None): self.defaultHeaders = defaultHeaders self.defaultDataTypes = defaultDataTypes self.rowDataType = rowDat...
def command_parser() -> argparse.ArgumentParser: """ Parse command line arguments Returns: parsed arguments """ parser = argparse.ArgumentParser( prog="Testplan generator", description="Generating json files used as testplan" ) parser.add_argument("maxResults", type=int) ...
The main task of the code is to parse command-line arguments, validate a video category ID against available categories, generate search results using specified parameters, and save the results as JSON files in a designated output directory.
def main(): args, unknown = command_parser() api_args = vars(args) dest = api_args.pop("outputDirectory") categories = assignable_categories( hl=args.relevanceLanguage, region_code=args.regionCode ) category_id = int(args.videoCategoryId) # check if category id is assignable if...
def path(self, *path): """Utility to join paths including the bucket and prefix""" path = list(filter(None, path)) path = self.unprefix(path) items = [self.prefix_] + path return self.delimiter.join(items) def isfile(self, path): path_ = self.path(path) # FileNotF...
This code removes a file or directory from an S3 storage system. It checks if the path points to a file or directory, logs debug information, and uses `self.fs.rm()` to delete files directly or recursively remove directories by appending a delimiter and setting `recursive=True` for nested contents.
def rm(self, path): path_ = self.path(path) self.log.debug("S3contents.S3FS: Removing: `%s`", path_) if self.isfile(path): self.log.debug("S3contents.S3FS: Removing file: `%s`", path_) self.fs.rm(path_) elif self.isdir(path): self.log.debug("S3contents...
def mkdir(self, path): path_ = self.path(path, self.dir_keep_file) self.log.debug("S3contents.S3FS: Making dir: `%s`", path_) self.fs.touch(path_) def ls(self, path=""): path_ = self.path(path) self.log.debug("S3contents.S3FS.ls: Listing directory: `%s`", path_) files = s...
The main task of the code is to initialize an S3 bucket by creating a directory, listing its contents, and checking if it's a directory. If an "AccessDenied" error occurs, it logs an error message suggesting an IAM policy for access and exits. Otherwise, it re-raises other exceptions to handle them externally.
def init(self): try: self.mkdir("") self.ls("") self.isdir("") except ClientError as ex: if "AccessDenied" in str(ex): policy = SAMPLE_ACCESS_POLICY.format( bucket=os.path.join(self.bucket, self.prefix) )...
def path(self, *path): """Utility to join paths including the bucket and prefix""" path = list(filter(None, path)) path = self.unprefix(path) items = [self.prefix_] + path return self.delimiter.join(items) def isdir(self, path): path_ = self.path(path) # FileNotFo...
This code implements a recursive copy operation for files and directories in an S3 filesystem. It converts paths, logs the operation, checks if the source is a directory or file, and recursively copies directory contents while creating the target directory structure. For files, it directly copies using the underlying f...
def cp(self, old_path, new_path): old_path_, new_path_ = self.path(old_path), self.path(new_path) self.log.debug("S3contents.S3FS: Coping `%s` to `%s`", old_path_, new_path_) if self.isdir(old_path): old_dir_path, new_dir_path = old_path, new_path for obj in self.ls(old_...
def print_green(*args, **kwargs): """Prints green text to terminal""" print(colorama.Fore.GREEN, end='') print(*args, **kwargs) print(colorama.Style.RESET_ALL, end='') def _load_data(self, data_dir, word_tokens, pristine_input, pristine_output, batch_size, seq_length, seq_step): ...
The main task of the code is to train a sequence model using provided data and hyperparameters. It loads training/validation data, builds a neural network with specified layers and dimensions, and trains it for a given number of epochs. The function includes timing measurements for data loading, model construction, and...
def train(self, data_dir, word_tokens, pristine_input, pristine_output, batch_size, seq_length, seq_step, embedding_size, rnn_size, num_layers, num_epochs, live_sample): """Train the model""" print_green('Loading data...') load_start = time.time() x, y, x_val,...
def im_fit(im): """Fit image to window.""" w, h = im.size ratio = get_fit_ratio(w, h) if ratio != 1.0: # NOSONAR im = im.resize((int(w * ratio), int(h * ratio)), APP.quality) return im def im_scale(im): """Scale image.""" im_w, im_h = im.size ratio = APP.im_scale * get_fit_ratio...
The function `im_resize` resizes and displays an image based on `APP`'s attributes (fit, scale, transpose). It copies the image, applies transformations, and shows the result. If looping is enabled and the image has multiple frames, it cycles through frames, manages animation timing, and restarts the loop. The function...
def im_resize(loop=False): """Resize image.""" if not (hasattr(APP, "im") and APP.im): return im = APP.im.copy() # Loses im.format! if APP.fit: im = im_fit(APP.im) if APP.im_scale != 1: im = im_scale(APP.im) if APP.transpose_type != -1: LOG.debug("Transposing...
def info_hide(): """Hide info overlay.""" info_set("") CANVAS.lower(CANVAS.text_bg) CANVAS.lower(CANVAS.text) scrollbars_set() def info_set(msg: str): """Change info text.""" APP.showing = msg CANVAS.itemconfig(CANVAS.text, text=msg) # type: ignore info_bg_update() def info_show(): ...
(The function `help_toggle` toggles the visibility of a help message in an application. If the help is already visible, it hides it; otherwise, it generates a formatted help message from function bindings, excluding specific functions. It processes key bindings, normalizes their names, appends function documentation, a...
def help_toggle(event=None): """Toggle help.""" if APP.showing == "help": info_hide() else: lines = [] for fun, keys in BINDS: if fun in (drag_begin, drag_end, resize_handler): continue lines.append( ( "" ...
def info_set(msg: str): """Change info text.""" APP.showing = msg CANVAS.itemconfig(CANVAS.text, text=msg) # type: ignore info_bg_update() def info_show(): """Show info overlay.""" CANVAS.lift(CANVAS.text_bg) CANVAS.lift(CANVAS.text) scrollbars_set() def info_hide(): """Hide info ov...
The function toggles an info overlay by checking the current state of `APP.showing`. If it's empty or "help", it updates the info content, logs the text, and displays the overlay while temporarily changing the cursor to "watch". If not, it hides the info. The function manages dynamic info display based on application s...
def info_toggle(event=None): """Toggle info overlay.""" if APP.showing in ("", "help"): CANVAS.config(cursor="watch") info_set( APP.title()[: -len(" - " + TITLE)] + info_get(APP.im, APP.info, APP.paths[APP.i_path]) ) LOG.debug("Showing info:\n%s", CANVAS.i...
def info_bg_update(): """Update info overlay.""" x1, y1, x2, y2 = CANVAS.bbox(CANVAS.text) CANVAS.text_bg_tkim = ImageTk.PhotoImage( # type: ignore Image.new("RGBA", (x2 - x1, y2 - y1), "#000a") ) CANVAS.itemconfig(CANVAS.text_bg, image=CANVAS.text_bg_tkim) # type: ignore CANVAS.coords...
This code handles Tk window resize events by updating UI elements (text wrap, canvas dimensions, scrollbars) to match the new window size, ensuring layout adjustments and image resizing when the window geometry changes.
def resize_handler(event=None): """Handle Tk resize event.""" new_size = APP.winfo_geometry().split("+", maxsplit=1)[0] if APP.s_geo == new_size: return APP.w = APP.winfo_width() APP.h = APP.winfo_height() ERROR_OVERLAY.config(wraplength=APP.w) TOAST.config(wraplength=APP.w) CANV...
def log(text: str, origin: str): if debugging_enabled: print("[" + origin + "] " + text) def validate_position(): position_validity = True log("WIP", "main.validate_position()") if not position_validity: recover_position()
The main task of the code is to control a robot to drive forward by a specified distance, handle obstacle detection by logging sensor data into a database, retry on failures with a limit, and update the robot's position. It sends commands to a server, processes responses, and manages data storage and error handling dur...
def drive_forward(mm: int): server.send_text(mapping1_connection, "drive_forward") server.send_text(mapping1_connection, str(mm)) response = server.receive_text(mapping1_connection) if response == "ok": # TODO calculate new position print("") elif response == "objectNearby": ...
def log(text: str, origin: str): if debugging_enabled: print("[" + origin + "] " + text) def start(): db_operations.connect() db_operations.clean() # TODO only clean in specific situations db_operations.setup_database() log('[server/main.py] database ready', "main.start()") ev3_connect_...
The code's main task is to initialize a system by starting processes, validating position, measuring the current location, and planning to create a map (marked as TODO). It logs status updates at each stage and concludes by shutting down the system. The sequence includes starting operations, readiness checks, position ...
def run(): log('starting...', "main.run()") start() log('ready', "main.run()") validate_position() measure_at_current_location() # TODO create the map log('shutdown', "main.run()") stop()
def initialize_checkpoint_manager(self): """ Initialize checkpoints and restore if possible. """ checkpoint_path = "./checkpoints/" if self.use_cloud: checkpoint_path = os.path.join( "gs://", self.cloud_bucket, self.name, "checkpoints" ) ...
The code trains a neural network model (likely a GAN) using training data (`train_x`, `train_y`) for a specified number of epochs. It shuffles data, processes batches, and executes `train_step` to update generator and discriminator losses. It tracks losses, generates training/test images, and saves checkpoints every 5 ...
def train( self, train_x, train_y, test_x=None, test_y=None, epochs=10, checkpoints=True, on_epoch_end=None, ): """ Train the networks. """ print(f"x examples: {len(train_x)}, y examples: {len(train_y)}") if che...
def config_environment( self, cell: Cell, count: int, ) -> List[Tuple[int, int]]: result: List[Tuple[int, int]] = [] for _ in range(count): while True: x, y = (randint(0, self.n_rows - 1), randint(0, self.n_columns - 1)) if self.mat...
The main task of the code is to randomize the positions of babies and robots on a grid while resetting the environment. It initializes a new matrix with free cells, places barnyards, obstacles, and dirt, then repositions each baby (avoiding occupied cells) and robot to random free spots, adjusting baby positions if the...
def randomize(self): old_matrix = self.matrix self.matrix = [ [Cell.Free for _ in range(self.n_columns)] for _ in range(self.n_rows) ] (x, y), *_ = self.config_environment(Cell.Barnyard, 1) self.config_barnyard(x, y, self.n_babies - 1) self.config_environment(...
def config_environment( self, cell: Cell, count: int, ) -> List[Tuple[int, int]]: result: List[Tuple[int, int]] = [] for _ in range(count): while True: x, y = (randint(0, self.n_rows - 1), randint(0, self.n_columns - 1)) if self.mat...
This code initializes a grid-based simulation environment with specified numbers of robots, babies, obstacles, and dirts. It creates a 2D matrix, configures cell types, places agents using provided creators, and tracks free cells and time. The setup includes barnyard, obstacles, dirty cells, and agent placement to esta...
def __init__( self, n_rows: int, n_columns: int, n_robots: int, n_babies: int, n_obstacles: int, n_dirts: int, random_time: int, dirt_probability: float, robot_creator: Callable[[int, int], RobotAgent], baby_creator: Callable[[int, ...
def KeyGen(size=8): #generate prime numbers p,q with same size p=generatePrime(size) q=generatePrime(size) if p == q: raise ValueError('p, q cannot be ==') #calculate n = pq & phi = (p-1)(q-1) n = p * q phi = (p - 1) * (q - 1) #select random integer 1<e<phi ==>gcd(e,phi)=1 e = ra...
The main task of the code is to demonstrate hybrid encryption using AES and RSA. It generates RSA keys, creates an AES symmetric key, encrypts a message with AES, then encrypts the AES key with RSA. During decryption, it decrypts the AES key using RSA's private key and uses it to decrypt the AES-encrypted message, show...
def main(): print("encrypt and decrypt with AES and RSA") print("******************************************************************") #Generate key print("Generating RSA public and Privite keys") pub,pri=KeyGen() #2. Generates symmetric key for data encapsulation scheme. print(...
def publish_job_analytics(self, chart): job_config = self.get_job_config(chart.chart_id) if job_config is None: job_config = self.job_config_template(chart) else: y_axis_label = chart.label_mapping.get(chart.y_axis_label) y_axis_label = y_axis_label i...
The main task of the code is to publish a report by validating user permissions, checking the chart's status, generating a query, and retrying the publishing process (via `publish_job_analytics` and `publish_report_portal`) up to 5 times if failures occur. If successful, it updates the chart status to "PUBLISHED" and r...
def publish_report(self, slice_id=None): form_data = json.loads(request.form.get("form_data")) user_id = g.user.get_id() if g.user else None slice_id = form_data.get("sliceId") slc = db.session.query(Slice).filter_by(id=slice_id).one_or_none() if not security_manager.can_access(...
def cross_ref_users_table(): entered_cred = get_login_creds() users = pd.read_csv('UsersTable.csv') output = "Wrong Password" count_iter = 0 for id, password in zip(users['Login ID'], users['Password']): if check_id(entered_cred, id): if check_password(entered_cred, password): ...
The main task of the code is to handle user login with up to three attempts, allowing registration if requested during failed attempts, and triggering password recovery via email if all attempts are exhausted. It checks user credentials, offers registration, and provides a recovery option based on user input.
def login(): for i in range(3): print("Attempt ", i+1) if cross_ref_users_table(): print(f'Login Successful') return True else: print("Login Unsuccessful") register_ft_user_key = input("Do you wish to register (Y/n)?") if check_yes(...
def load_img(img_name): img = ~mpimg.imread(img_name) img = np.delete(img, 2, 2) img = np.delete(img, 1, 2) img = img.squeeze() img = clear_noise(img) return img def split_img(img): n = 0 between_nums = False height, width = img.shape # [White start, Number start, Number end, Whi...
The function processes an image containing digits by splitting it into individual digits, predicting each digit's value and accuracy, and returning a combined numeric result (1-3 digits) along with the product of prediction accuracies. It handles partial digit detection by saving images of detected digits and calculati...
def get_results(img_name): full_img = load_img(img_name) digits = list(split_img(full_img)) if digits[0] is None: return None, None elif digits[1] is None: plt.imsave('img1.jpg', digits[0], cmap=plt.cm.binary) dig_1, accuracy_1 = predict(digits[0]) return dig_1, round(ac...
def setup_directories(self) -> None: self.sprite_directory = os.path.join("sprites") self.state_directory = os.path.join("states") self.tilemap_directory = os.path.join("tilemaps") # Assets self.asset_directory = os.path.join("assets") self.font_directory = os.path.join(s...
The main task of the code is to initialize and start a new game by setting up necessary directories, loading the initial game state, and entering the game loop to begin gameplay.
def new(self): """Starting a new game""" self.setup_directories() self.load_first_state() self.game_loop()
def is_train_test_file_exists(self) -> bool: try: logging.info("Checking if training and testing file is available") is_train_file_exist = False is_test_file_exist = False train_file_path = self.data_ingestion_artifact.train_file_path test_file_path ...
The main task of the code is to validate data by checking the existence of train/test files, verifying the dataset schema, and detecting data drift. If successful, it generates a `DataValidationArtifact` with file paths, validation status, and a success message, logging the result. On failure, it raises an exception.
def initiate_data_validation(self) -> DataValidationArtifact: try: self.is_train_test_file_exists() self.validate_dataset_schema() self.is_data_drift_found() data_validation_artifact = DataValidationArtifact( schema_file_path=self.data_validation...
def __addEntryLog(self, uid): # insert into database date = input("Enter the date for your current entry (mm/dd/yyyy): ") weight = float(input("Enter your weight for your current entry (in lbs): ")) self.cursor.execute( "INSERT INTO EntryLogs (uid, date, weight) VALUES (?, ?, ?);", (uid, datetime.strpti...
This function displays a user menu for health data management, allowing actions like adding entries, graphing progress, estimating weight loss, tracking calories, and accessing help. It loops until the user selects "Quit" (option 6), fetching the username from the database first.
def __mainMenu(self, uid): self.cursor.execute("SELECT username FROM Users WHERE uid=?;", (uid)) username = self.cursor.fetchall()[0][0] flag = True # run continuous loop on main menu until user quits while flag: print("\nHello %s!" % username) print("What would you like to do next? (enter a number)\n"...
def __newUser(self): print("\nHello new user.\nPlease provide us with the following information:") username = self.__username() pwd = self.__password() name = input("Name: ") sex = input("Sex (M/F): ") height = input("Height (in inches): ") # convert user's birthday to datetime format birthday = input...
This code initializes a WeightLoss Manager application by presenting a startup menu allowing users to create a new account or load existing progress. It validates user credentials for existing accounts, retrieves a valid UID, and directs users to the main menu. The class sets up UI formatting, date display, and handles...
def __init__(self): WeightLossDB.__init__(self) # a bottom border for command-line text-prompts in UI self.border = "-------------------------------------------------" # the format for displaying dates to the user self.USformat = "%m/%d/%Y" # start WeightLoss program print("\nWelcome to WeightLoss Ma...
def create_csv(): """ Create a new csv files :return: None """ users_exists = os.path.exists('users.csv') passwords_exists = os.path.exists('passwords.csv') if not users_exists and not passwords_exists: print('Creating new csv files') users_data = pd.DataFrame(columns=['uuid'...
The code defines a main function for a password manager application. It initializes a CSV file, creates a PasswordManager instance, displays a home screen, and processes user input to navigate the main menu, handling password management tasks like storage and retrieval.
def main(): tprint('Password Manager') warnings.simplefilter(action='ignore') create_csv() pm = PasswordManager() home() choice = input('Enter your choice: ') mainMenu(pm, choice)
def offer_split(self, player): while True: try: response = input(f"{player.name}, Do you want to Split? (yes/no): ").strip().lower() if response not in ["yes", "no"]: raise ValueError(INVALID_ANSWER_MESSAGE) if response...
The `play_round` method manages player turns in a game, handling splitting, doubling down, and regular play for each active player, then proceeds to the host's turn.
def play_round(self): # Players' turns for player in self.active_players: # Check and offer double down if player.can_split() and self.offer_split(player): for hand_index in range(len(player.hands)): print(f"Playing hand {hand_index + 1} for {p...
def get_power(self): return self._get_node(SysPower) == '1' def get_name(self): return self._get_node(SysInfoFriendlyname) def get_volume(self): return round(float(self._get_node(SysAudioVolume)) / VOLUME_STEPS, 2) def get_mute(self): return self._get_node(SysAudioMute) == '1' def get_so...
The main task of the code is to return a dictionary containing the current state of an object by aggregating values from multiple instance methods, such as power, name, volume, mute status, sources, MAC address, media metadata, and playback state. This provides a consolidated snapshot of the object's attributes for ext...
def get_state(self): return { 'power': self.get_power(), 'name': self.get_name(), 'volume': self.get_volume(), 'mute': self.get_mute(), 'sources': self.get_sources(), 'mac_address': self.get_mac_address(), 'artist': self...
def locateItem(): xpath_list, class_list, id_list, name_list = ["//a[contains(@class, 'template')]", "//article[contains(@class, 'product-card')]", "//a[contains(@href, 'add_to_cart')]", "//a[contains(@href, 'shop')]", "//a[contains(@class, 'product')]", "//li[contains(@class, 'product')]", "//a[contains(@class, 'p...
This function adds a specified number of products to a cart by locating products, clicking them, and interacting with add-to-cart buttons. It includes delays, error handling, and verification. Returns True if successful, False otherwise.
def addItem(numberOfProductsUserWants): time.sleep(3) for i in range(0, numberOfProductsUserWants): time.sleep(2) products = locateItem() if products != "" and len(products) > numberOfProductsUserWants: products[i+1].click() else: print("Cannot find produc...
def get_style_image_features(image, style_transfer_vgg, num_style_layers): preprocessed_style_image = preprocess_image(image) outputs = style_transfer_vgg(preprocessed_style_image) style_outputs = outputs[:num_style_layers] return [gram_matrix(style_layer) for style_layer in style_outputs] def get_conte...
The main task of the code is to perform neural style transfer by optimizing a generated image to combine the style of a given style image with the content of a content image. It uses a pre-trained VGG model to extract style and content features, iteratively updates the generated image via gradient descent (using specif...
def fit_style_transfer( style_image, content_image, style_weight=1e-2, content_weight=1e-4, optimizer="adam", learning_rate=0.001, epochs=1, steps_per_epoch=1, var_weight=None, vgg_model=None, num_style_layers=None, num_content_layers=None): assert vgg_model is not None and num_style_layers...
def update_distance_vector(self, src_server_id): try: for dest_server_id in self.list_of_servers: if src_server_id == dest_server_id: # don't need to find cost to myself (src_server) continue # prepare to find least cost to des...
The code listens for UDP packets on a specified server IP and port. It processes incoming messages to detect crash notifications, updating the distance vector by setting crashed server costs to infinity and adjusting neighbor routes. For non-crash messages, it increments packet counters, parses updates, and adjusts the...
def listen(self, server_ip, server_port, exit_event): # create a UDP socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_socket.bind((server_ip, server_port)) while not exit_event.is_set(): readable, _, _ = select.select([server_socket], [], [], 1) ...
def _reward(self, action: Action) -> float: """ The reward is defined to foster driving at high speed, on the rightmost lanes, and to avoid collisions. :param action: the last action performed :return: the corresponding reward """ #modifications rewards_2 = tuple...
The code executes an action in a simulated environment, updates the environment state, computes the reward, checks termination/truncation conditions, and returns observation, reward, termination status, truncation status, and additional info. It handles rendering and adjusts the reward based on a configuration paramete...
def step(self, action: Action) -> Tuple[Observation, float, float, bool, dict]: """ Perform an action and step the environment dynamics. The action is executed by the ego-vehicle, and all other vehicles on the road performs their default behaviour for several simulation timesteps until ...
def image_capture(self, image_pipe, maini_pipe, repeatRate): global estop if debug: print("Image Capture Starting") pipeContents = [] if not estop: while maini_pipe.poll(): #Empty pipe pipeContents.append(maini_pipe.recv()) for i i...
The main task of the code is to validate user inputs for a test setup, ensuring parameters like test duration, voltage/current values, and image capture rate are within acceptable ranges. If valid, it disables the start button, initializes hardware processes (power supply, pressure sensor, image capture), and triggers ...
def validateTest(self): global psen_script, image_script, power_script, q, radioVar, testRunning, maini_pipe testRunning = True if debug: print("validating") try: testMin = float(EntTime[0].get()) imageOn = bool(var3.get()) print(imageOn) ...
def preTestCountDown(self, i): global estop if i > 0 and estop == False: #Countdown Started self.BtnPreStart.config(text = str(i)) i -= 1 self.testWait = root.after(1000, lambda: self.preTestCountDown(i)) elif estop: #Cancled by Estop root.after_ca...
This code validates input parameters for a gas control system, checks hardware readiness, initializes multiplexer processes, configures GPIO relays, and starts a pre-test procedure with safety limits and error handling. It ensures gas flow, calibration settings, file names, and USB connectivity meet requirements before...
def preTest(self): global multi, q limitList = [0]*4 try: gasFlow = float(EntFlow[0].get()) #add similiar proportional control calcuations to powerValue if gasFlow > 131 or gasFlow < 0: func.message("Warning","Gas Flow Rate must not exceed 131 SCCM and mus...
def share_info(): """Only for display purpose""" os.system("cls") print("%" * 50) print(" " * 20 + "Now live ! ") print("%" * 50) print("\n\n") print( f"Stop: {STOP}, Absolut stop: {ABSOLUT_STOP}, Margin time: {MARGIN_TIME}, Take profit: {TAKE_PROFIT}" ) print( f"Wa...
The code automates Binance trading by analyzing cryptocurrency pairs, using historical data to identify trading opportunities. It either loads precomputed data (QUICK_MODE) or fetches real-time BTC pairs and calculates their means. The main loop continuously selects pairs for trading, executes trades, tracks cumulative...
def main(): # for Binance API client = Client(config.API_KEY, config.API_SECRET, tld="com") # for sending message to user # browser = connect() # only for display purpose share_info() # set up if QUICK_MODE: with open("save.json", "r") as file: means = json.load(f...
def run_steps(env, W1, W2, b1, b2, do_render): observation = env.reset() fpb = [] for step_num in range(10000): obs_vector = np.expand_dims(a=observation, axis=1).reshape(-1, 1) A1, A2 = forward_prop(W1, b1, W2, b2, obs_vector) probs_of_up_or_down = A2 # throws in some rando...
The function `run_episode` executes multiple episodes in a batch, collects discounted rewards, normalizes rewards across episodes, performs backpropagation to compute gradients, updates neural network parameters (W1, b1, W2, b2), and returns the updated parameters along with step counts per episode. It trains the model...
def run_episode(env, W1, b1, W2, b2, do_render, episode_batch_size): all_steps = [] episode_bags = [] for episode_number in range(episode_batch_size): #number of episodes per mini batch episode_bag = run_steps(env, W1, W2, b1, b2, do_render if episode_number == 0 else False) all_steps.append...
def resnet50(inputs, scope, training): with tf.variable_scope(scope): layer = conv_bn_relu(inputs, 64, 7, 2, 'conv1', training) with tf.variable_scope('block1'): for unit in range(2): layer = bottleneck(layer, 256, 1, 'unit%d' % (unit+1), training) layer = bottleneck(layer, 256, 2, 'unit3...
The code processes an input image using a ResNet50 backbone to extract features, then iteratively generates heatmaps (hmaps), depth maps (dmaps), and length maps (lmaps) through a stack of neural networks. For each stack layer, features are updated by concatenating outputs of previous layers, enabling progressive refin...
def detnet(img, n_stack, training): features = resnet50(img, 'resnet', training) pos_tile = get_pose_tile(tf.shape(img)[0]) features = tf.concat([features, pos_tile], -1) hmaps = [] dmaps = [] lmaps = [] for i in range(n_stack): hmap = net_2d(features, training, 'hmap_%d' % i, 21) features = tf.c...
def clearscreen(): prompt('cls||clear') def delay(times, sleeptime = 0.4, char = '.'): for i in range(times): sleep(sleeptime) print(char, end='', flush=True) def admin_workflow(): admin_functions = [insert_med, display_bills, display_meds, search_med, update_med, delete_med] while True: clearscreen() print...
The code authenticates an admin user by checking a hardcoded username ('admin') and password ('1234'). If valid, it triggers an admin workflow with a green checkmark animation; otherwise, it displays an error and returns to the previous screen after a delay.
def login_admin(): clearscreen() print('\n\n') WRONG_CREDS = False usr = input('Enter username: ') if usr == 'admin': pwd = input('Enter password: ') if pwd == '1234': print('✅ Credentials verified! Logging in ', end='') delay(8, sleeptime=0.15, char='🟩') admin_workflow() else: WRONG_CREDS = Tru...
def parse_destination(self, frame): result, self.dest = self.fixup_address(frame[0:7]) return result def parse_source(self, frame): result, self.source = self.fixup_address(frame[7:14]) return result def parse_repeaters(self, frame): pos = 14 while True: more, repeater = self.fixup_address(frame[p...
This code parses a network frame by sequentially extracting destination, source, repeaters (if present), type, and information fields. It adjusts the parsing position dynamically based on frame structure, ensuring accurate data extraction from the provided byte frame.
def parse(self, frame): self.parse_destination(frame) has_repeaters = self.parse_source(frame) pos = 14 if has_repeaters: pos = self.parse_repeaters(frame) if pos >= len(frame): return pos = self.parse_type(frame, pos) self.parse_info(frame, pos + 1)
def find_winner(self): # strategy: go through each column, each row, then the diagonals # if every symbol is the same, we have a winner # check each column for c in range(self.cols): winner = self.check_column_for_winner(c) if winner != '': return...
This code initializes a customizable Tic Tac Toe game with multiple players, setting up a grid-based board, handling user input for turn order, and executing a game loop until a winner is determined. It validates player counts, populates the board with numbered positions, and alternates turns between players while chec...
def __init__(self, cols, rows, num_players): self.cols = cols self.rows = rows self.num_players = num_players if self.num_players > len(self.PLAYER_SYMBOLS): raise ValueError(f'{num_players} is greater than maximum of {len(self.PLAYER_SYMBOLS)} players.') # initializ...
def reduce(self, threshold: float = 0, variables: bool = False, word_black_list=[]): """ Merge either on words or on variables. Should merge on variable only after `self.make_state_generic` has been called. """ count_function = self.count_word if variables == True: ...
The code fits an automaton by pruning and simplifying it using frequency thresholds and a blacklist. It reduces states, removes low-frequency transitions, simplifies chains, merges groups, and applies min_freq filtering to optimize the automaton's structure while excluding specified words.
def fit(self, threshold: float = 0.2, min_freq: float = 0, word_black_list=[]): """Fit the automaton Parameters ---------- threshold : float The frequency threshold, each pattern should have a frequency higher than this threshold min_freq: float T...
def parse_brand(rowId, rowData): # find brand index = rowData.find('brand:') if (index > -1): index = index + len('brand:') commaIndex = rowData.find(',', index, len(rowData)) brand_val = rowData[index: commaIndex] if (len(brand_val) < 25): brand_val = brand_val.s...
This function parses raw data into structured fields (brand, style, color, size, material) by calling specific parsing functions, converts rowData to lowercase, and stores the result in a dictionary `rowDict` under the given `rowId`. The material field is temporarily left empty, and size handling for lists is commented...
def parseRowData(rowId, rowData): rowData = rowData.lower() # rowIds = [8528, 11726] # for id in rowIds: # if (rowId == id): # printRowData(rowId, rowData) brand_val = parse_brand(rowId, rowData) style_val = parse_style(rowId, rowData) color_val = pa...
def get_formatted_task_date(date): task_date = datetime.strptime(date, '%m/%d/%Y %I:%M:%S %p') return "{}/{}".format(task_date.month, task_date.day) def is_new_project(row, projects_time): return not row["Project"] in projects_time def create_new_project(row, projects_time): projects_time[row["Project"]...
The code reads a CSV file, processes each row to extract and format task dates, and aggregates time data into a dictionary where each key is a project. It checks if a project is new, creates an entry if so, and adds the formatted task time. The final dictionary maps projects to their aggregated time entries.
def read_data_to_dict(input_csv): projects_time = {} with open(input_csv, 'r') as file: reader = csv.DictReader(file) for row in reader: task_date = get_formatted_task_date(row["Start Date"]) if is_new_project(row, projects_time): create_new_project(row, p...
def login_facebook(self, username, password): # fb_un = self.extra.get('fb_un') # fb_pw = self.extra.get('fb_pw') # if fb_un is None or fb_pw is None: # self.logger.debug('No facebook account login info, please supply them.') # return False if not self.s.driver.cu...
The main task of the code is to automate clicking on ads to earn points within a browser session, managing parameters like maximum clicks, duration, and error handling. It initializes browser sessions, handles Facebook login if credentials are provided, processes ads, tracks click counts, and performs cashout/daily che...
def ameb_emu(self, max_click=None, duration=None, skip=None, close=False, cashout=True): click = 0 c_handle = None ads = None skip = skip or '' new = True start = True newargs = None _refresh = False while True: try: if ...
def __capture(self, args): return self.__execute(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def __print_cmd(self, args): if self.verbose > 1: MercurialCPPCheckRunner.eprint(colored(join_args(args), 'blue')) def __execute(self, args, stdout=None, stderr=None): self.__print_...
This function analyzes a file in a Mercurial repository by comparing its content across two revisions (left and right). It retrieves file versions using `hg cat`, applies diffs with `hg diff` and `patch`, runs static analysis via `cppcheck` on both versions, and filters out issues present in the left revision from the ...
def analyse_file(self, i, f, s, tmpdir, leftrev, rightrev, leftrev_args, rightrev_args, range_args): src = os.path.join(self.hg_root, f) if rightrev is None and not os.path.exists(src): MercurialCPPCheckRunner.eprint('%s does not exist, skipping' % src) return [] fwd = o...
def image_exists(prefix, name): docker = DOCKER name = name.strip() if prefix: proc = runs("{docker} inspect {prefix}/{name}".format(**locals())) else: proc = runs("{docker} inspect {name}".format(**locals())) if proc.rc: logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,...
This test verifies the CentOS 7.3.1611 Docker image's ability to install packages via a local repository mirror. It creates a CentOS repo container, configures a test container to use this local mirror, installs python-docker-py, then cleans up. The test ensures proper network configuration and package installation fun...
def test_1073_centos(self): prefix = PREFIX docker = DOCKER repo_image = "centos-repo:7.3.1611" box1_image = "centos:7.3.1611" if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test") if not image_exists(prefix, repo_image): self.skipTest("have no " + repo_...
def image_exists(prefix, name): docker = DOCKER name = name.strip() if prefix: proc = runs("{docker} inspect {prefix}/{name}".format(**locals())) else: proc = runs("{docker} inspect {name}".format(**locals())) if proc.rc: logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,...
This test case verifies the CentOS 7.4.1708 Docker image's ability to install packages via a local repository mirror. It creates a CentOS repo container, configures a test container to use this mirror, installs python-docker-py, then cleans up containers. The test ensures proper Docker setup, network configuration, and...
def test_1074_centos(self): prefix = PREFIX docker = DOCKER repo_image = "centos-repo:7.4.1708" box1_image = "centos:7.4.1708" if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test") if not image_exists(prefix, repo_image): self.skipTest("have no " + repo_...
def image_exists(prefix, name): docker = DOCKER name = name.strip() if prefix: proc = runs("{docker} inspect {prefix}/{name}".format(**locals())) else: proc = runs("{docker} inspect {name}".format(**locals())) if proc.rc: logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,...
This test verifies the functionality of a CentOS 7.5.1804 Docker image by setting up a local repository container, configuring a test container to use it via host IP, installing python-docker-py, and ensuring proper network configuration and package installation. It skips if Docker is unavailable or the required image ...
def test_1075_centos(self): prefix = PREFIX docker = DOCKER repo_image = "centos-repo:7.5.1804" box1_image = "centos:7.5.1804" if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test") if not image_exists(prefix, repo_image): self.skipTest("have no " + repo_...
def image_exists(prefix, name): docker = DOCKER name = name.strip() if prefix: proc = runs("{docker} inspect {prefix}/{name}".format(**locals())) else: proc = runs("{docker} inspect {name}".format(**locals())) if proc.rc: logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,...
This test verifies CentOS 7.6.1810 Docker image functionality by setting up a local repository container, configuring host overrides for mirror access, and testing package installation. It creates two containers: one as a CentOS repo mirror and another to install python-docker-py, ensuring proper network configuration ...
def test_1076_centos(self): prefix = PREFIX repo_image = "centos-repo:7.6.1810" box1_image = "centos:7.6.1810" if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test") if not image_exists(prefix, repo_image): self.skipTest("have no " + repo_image) sx____("{...
def image_exists(prefix, name): docker = DOCKER name = name.strip() if prefix: proc = runs("{docker} inspect {prefix}/{name}".format(**locals())) else: proc = runs("{docker} inspect {name}".format(**locals())) if proc.rc: logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,...
This test case verifies the CentOS 7.7.1908 Docker image's ability to install packages via a local yum repository. It creates a CentOS repo container, configures a test container to use it as a mirror, installs python-docker-py, and ensures the process completes successfully. The test checks both container setup and pa...
def test_1077_centos(self): prefix = PREFIX docker = DOCKER repo_image = "centos-repo:7.7.1908" box1_image = "centos:7.7.1908" if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test") if not image_exists(prefix, repo_image): self.skipTest("have no " + repo_...
def image_exists(prefix, name): docker = DOCKER name = name.strip() if prefix: proc = runs("{docker} inspect {prefix}/{name}".format(**locals())) else: proc = runs("{docker} inspect {name}".format(**locals())) if proc.rc: logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,...
This test verifies CentOS 7.9.2009 Docker image functionality by creating a local repository container, configuring a test container to use it via host override, installing python-docker-py, and validating operations. It ensures proper container setup, network configuration, package installation, and cleanup.
def test_1079_centos(self): prefix = PREFIX docker = DOCKER repo_image = "centos-repo:7.9.2009" box1_image = "centos:7.9.2009" if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test") if not image_exists(prefix, repo_image): self.skipTest("have no " + repo_...
def image_exists(prefix, name): docker = DOCKER name = name.strip() if prefix: proc = runs("{docker} inspect {prefix}/{name}".format(**locals())) else: proc = runs("{docker} inspect {name}".format(**locals())) if proc.rc: logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,...
This test verifies the installation of python2-numpy on a CentOS 8 Docker container using a local CentOS repository mirror. It ensures Docker is running, creates a repository container, configures host resolution, spins up a CentOS 8 test container, installs the package, and cleans up resources.
def test_1080_centos(self): prefix = PREFIX docker = DOCKER repo_image = "centos-repo:8.0.1905" box1_image = "centos:8" if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test") if not image_exists(prefix, repo_image): self.skipTest("have no " + repo_image) ...
def image_exists(prefix, name): docker = DOCKER name = name.strip() if prefix: proc = runs("{docker} inspect {prefix}/{name}".format(**locals())) else: proc = runs("{docker} inspect {name}".format(**locals())) if proc.rc: logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,...
This test case verifies the installation of python2-numpy in a CentOS 8.1.1911 Docker container using a local CentOS repository mirror. It sets up Docker containers for the repository and test environment, configures network hosting, installs the package, and ensures proper cleanup by removing containers after testing.
def test_1081_centos(self): prefix = PREFIX docker = DOCKER repo_image = "centos-repo:8.1.1911" box1_image = "centos:8.1.1911" if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test") if not image_exists(prefix, repo_image): self.skipTest("have no " + repo_...
def image_exists(prefix, name): docker = DOCKER name = name.strip() if prefix: proc = runs("{docker} inspect {prefix}/{name}".format(**locals())) else: proc = runs("{docker} inspect {name}".format(**locals())) if proc.rc: logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,...
This test verifies CentOS 8.3.2011 image functionality by creating two Docker containers: a CentOS repository container and a test container. It configures network host mapping for the repository, installs python2-numpy in the test container, and ensures proper container lifecycle management through creation, execution...
def test_1083_centos(self): prefix = PREFIX docker = DOCKER repo_image = "centos-repo:8.3.2011" box1_image = "centos:8.3.2011" if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test") if not image_exists(prefix, repo_image): self.skipTest("have no " + repo_...