dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def rotatedScrambles(scramble): from copy import copy scrambles = [scramble] rots = {'z':zScramble,'y':yScramble} reverse = [[]] for posDr in [['z'],['y'],['y','z'],['z','y'],['z','y','z']]: tempScramble = copy(scramble) tempReverse = [] for rot in posDr: tempScra...
This code solves a Rubik's Cube scramble by decomposing it into Edge Orientation (EO), DR (Drain) substep, DR step, and final solution phases. It processes multiple axis orientations, applies pruning parameters to optimize steps, and returns detailed solutions with move sequences and lengths for each orientation.
def solveScrambleAllDRAxisExtraDRStep(scramble,fromEOToDRPrune,fromDRPrune): print("Scramble:",scramble) scramble = scramble.split(' ') scrambleList,reversing = rotatedScrambles(scramble) solution_texts = [] for scramble,rev in zip(scrambleList,reversing): resDic = {} resDic["So...
def query_graph(self,query): try: result = None callback = self.client.submitAsync(query) for result in callback.result(): print(result) self.print_status_attributes(callback.result()) return result except Exception as e: ...
The main task of the code is to add or update a vertex in a Cosmos Gremlin graph database. It checks if a vertex with specific properties (RUN_ID, PIPELINE_STEP_NAME) already exists. If it does, the vertex is updated by removing the EXPERIMENT_NAME property. If not, a new vertex is created using the provided label and ...
def add_vertex(self, label, properties,run_id,pipeline_step_name): try: query = "g.V().hasLabel('amlrun').has('RUN_ID', '"+run_id+"').has('PIPELINE_STEP_NAME', '"+pipeline_step_name+"').values('id')" documentIds = self.query_graph(query) if documentIds: docume...
def get_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("userpass", type=str) parser.add_argument("organization", type=str) parser.add_argument("project_name", type=str) parser.add_argument("repository_id", type=str) parser.add_argument("commit_id", type=str)...
The main task of the code is to retrieve files from a specific commit in a repository, prepare them into a structured DataFrame, and execute sorting operations based on parameters like `break_pipeline` and `commit_risk_limit`. It processes file paths, organizes data, and applies sorting logic to analyze or transform th...
def main(): args = get_args() # Get commit files commit_file_paths = get_files( args.organization, args.project_name, args.repository_id, args.commit_id ) # Prepare Sorts files_df = prepare_sorts(args.repo_local_url, commit_file_paths) # Execute Sorts execute_sorts(files_df, a...
def check_parser_errors(parser): if not parser.errors: return logging.error("Parser has errors.") for err in parser.errors: logging.error(f"Parser error: {err}") pytest.fail() def infix_expression_test(exp, left, operator, right): assert isinstance(exp, ast.InfixExpression) lite...
This test verifies the correct parsing of an if-expression without an else clause. It checks that the input "if (x < y) {x}" is parsed into an AST with an IfExpression containing a condition (x < y) and a single consequence statement (x), confirming the parser handles such expressions accurately.
def test_if_expression(): input_str = "if (x < y) {x}" lexer = Lexer(input_str) parser = Parser(lexer) program = parser.parse_program() check_parser_errors(parser) assert ( len(program.statements) == 1 ), f"Program has not enough statements. {len(program.statements)=}" stmt = pr...
def check_parser_errors(parser): if not parser.errors: return logging.error("Parser has errors.") for err in parser.errors: logging.error(f"Parser error: {err}") pytest.fail() def literal_expression_test(exp, expected): if isinstance(expected, bool): boolean_literal_test(exp...
This test function verifies that a parser correctly handles function literals by checking if the input string "fn(x, y) { x + y; }" is parsed into a valid FunctionLiteral with two parameters ("x" and "y") and a body containing an addition expression "x + y". It ensures the parser generates the correct AST structure wit...
def test_function_literal(): input_str = "fn(x, y) { x + y; }" lexer = Lexer(input_str) parser = Parser(lexer) program = parser.parse_program() check_parser_errors(parser) assert ( len(program.statements) == 1 ), f"Program has not enough statements. {len(program.statements)=}" ...
def check_parser_errors(parser): if not parser.errors: return logging.error("Parser has errors.") for err in parser.errors: logging.error(f"Parser error: {err}") pytest.fail() def identifier_test(exp, value): assert isinstance(exp, ast.Identifier) assert exp.value == value a...
This test verifies that a parser correctly handles a function call expression with multiple arguments, including infix expressions, within an expression statement. It checks the parsed structure has the correct function name "add", three arguments, and validates each argument's type and value, ensuring proper parsing o...
def test_call_expression(): input = "add(1, 2 * 3, 4 + 5);" lexer = Lexer(input) parser = Parser(lexer) program = parser.parse_program() check_parser_errors(parser) assert ( len(program.statements) == 1 ), f"Program has not enough statements. {len(program.statements)=}" stmt = p...
def skip_whitespace(self) -> None: """ Skip whitespace characters in the input string. This method advances the read position until a non-whitespace character is encountered. Examples: >>> lex = Lexer(" let x = 5;") >>> lex.skip_whitespace() >>> lex...
The main task of the code is to tokenize input characters into meaningful tokens (e.g., operators, identifiers, integers) by checking fixed mappings, handling multi-character operators like '=='/!=' via lookahead, and classifying letters/digits into keywords/identifiers/integers, while skipping whitespace and returning...
def get_next_token(self) -> Token: """ Get the next token from the input string. Returns: Token: The next token. Examples: >>> lex = Lexer('=+(){},;') >>> lex.get_next_token() Token(type=<TokenType.Equal: '='>, literal='=') """ ...
def next_token(self) -> None: self.current_token = self.peek_token self.peek_token = self.lexer.get_next_token() def parse_expression( self, precedence: Precedence ) -> ast.Expression | None: if self.current_token.type not in self.prefix_parse_funcs: self.no_prefix_error(...
The function parses an expression enclosed in parentheses. It advances the token parser, parses an expression with the lowest precedence, checks for a closing parenthesis, and returns the parsed expression if valid; otherwise, returns None.
def parse_grouped_expression(self) -> ast.Expression | None: self.next_token() exp = self.parse_expression(Precedence.LOWEST) if not self.expect_peek(TokenType.RPAREN): return None return exp
def peek_token_is(self, type) -> bool: return self.peek_token.type == type def next_token(self) -> None: self.current_token = self.peek_token self.peek_token = self.lexer.get_next_token() def parse_expression( self, precedence: Precedence ) -> ast.Expression | None: if self.c...
This function parses function call arguments by collecting expressions between parentheses, handling commas, and returning them as a list of AST nodes.
def parse_call_arguments(self) -> list[ast.Expression]: args: list[ast.Expression] = [] if self.peek_token_is(TokenType.RPAREN): self.next_token() return args self.next_token() args.append(self.parse_expression(Precedence.LOWEST)) while self.peek_token_...
def current_precedence(self) -> Precedence: return token_type_to_precedence(self.current_token.type) def next_token(self) -> None: self.current_token = self.peek_token self.peek_token = self.lexer.get_next_token() def parse_expression( self, precedence: Precedence ) -> ast.Expression...
This code parses an infix expression by creating an AST node with the current token as the operator, then parsing the right-hand side of the expression using the current precedence level to ensure correct operator precedence handling in the abstract syntax tree.
def parse_infix_expression(self, left: ast.Expression) -> ast.Expression: expression = ast.InfixExpression( token=self.current_token, operator=self.current_token.literal, left=left, ) precedence = self.current_precedence() self.next_token() ex...
def expect_peek(self, type) -> bool: if self.peek_token_is(type): self.next_token() return True self.peek_error(type) return False def next_token(self) -> None: self.current_token = self.peek_token self.peek_token = self.lexer.get_next_token() def parse_ex...
This code parses a "let" statement in an abstract syntax tree (AST) by reading an identifier, checking for an assignment operator, parsing an expression as the value, and returning the constructed AST node. It handles token validation and skips optional semicolons, returning None if required tokens are missing.
def parse_let_statement(self) -> ast.LetStatement: stmt = ast.LetStatement(token=self.current_token) if not self.expect_peek(TokenType.IDENT): return None stmt.name = ast.Identifier( token=self.current_token, value=self.current_token.literal ) if not se...
def next_token(self) -> None: self.current_token = self.peek_token self.peek_token = self.lexer.get_next_token() def parse_expression( self, precedence: Precedence ) -> ast.Expression | None: if self.current_token.type not in self.prefix_parse_funcs: self.no_prefix_error(...
The code parses a return statement, creating an AST node, parsing the return value expression, handling an optional semicolon, and returning the constructed ReturnStatement AST node.
def parse_return_statement(self) -> ast.ReturnStatement: stmt = ast.ReturnStatement(token=self.current_token) self.next_token() stmt.return_value = self.parse_expression(Precedence.LOWEST) if self.peek_token_is(TokenType.SEMICOLON): self.next_token() return stmt
def parse_expression( self, precedence: Precedence ) -> ast.Expression | None: if self.current_token.type not in self.prefix_parse_funcs: self.no_prefix_error(self.current_token.type) return None prefix = self.prefix_parse_funcs[self.current_token.type] left...
The function parses an expression statement, creating an AST node with the current token and parsing an expression with the lowest precedence. It optionally consumes a semicolon if present, then returns the constructed expression statement AST node.
def parse_expression_statement(self) -> ast.ExpressionStatement: stmt = ast.ExpressionStatement(token=self.current_token) stmt.expression = self.parse_expression(Precedence.LOWEST) if self.peek_token_is(TokenType.SEMICOLON): self.next_token() return stmt
def parse_let_statement(self) -> ast.LetStatement: stmt = ast.LetStatement(token=self.current_token) if not self.expect_peek(TokenType.IDENT): return None stmt.name = ast.Identifier( token=self.current_token, value=self.current_token.literal ) if not se...
This function parses a statement by identifying the current token type and delegating to specialized parsing methods. If the token is 'LET', it parses a variable declaration; if 'RETURN', it parses a return statement; otherwise, it parses an expression as a statement. The result is an abstract syntax tree (AST) node re...
def parse_statement(self) -> ast.Statement: match self.current_token.type: case TokenType.LET: return self.parse_let_statement() case TokenType.RETURN: return self.parse_return_statement() case _: return self.parse_expression_st...
def expect_peek(self, type) -> bool: if self.peek_token_is(type): self.next_token() return True self.peek_error(type) return False def next_token(self) -> None: self.current_token = self.peek_token self.peek_token = self.lexer.get_next_token() def parse_ex...
The code parses an `if` expression into an abstract syntax tree (AST). It creates an `IfExpression` node, validates parentheses, parses the condition, and reads the consequence block. If an `else` clause is present, it parses the alternative block. The method returns the constructed AST node or `None` if parsing fails ...
def parse_if_expression(self) -> ast.Expression: expression = ast.IfExpression(token=self.current_token) if not self.expect_peek(TokenType.LPAREN): return None self.next_token() expression.condition = self.parse_expression(Precedence.LOWEST) if not self.expect_peek...
def expect_peek(self, type) -> bool: if self.peek_token_is(type): self.next_token() return True self.peek_error(type) return False def parse_function_parameters(self) -> list[ast.Identifier]: identifiers: list[ast.Identifier] = [] if self.peek_token_is(To...
This method parses a function literal into an AST node by creating a FunctionLiteral object, validating expected tokens (parentheses and curly braces), parsing parameters and body, and returning the constructed AST or None if token validation fails.
def parse_function_literal(self) -> ast.Expression: func = ast.FunctionLiteral(token=self.current_token, parameters=[]) if not self.expect_peek(TokenType.LPAREN): return None func.parameters = self.parse_function_parameters() if not self.expect_peek(TokenType.LSQUIRLY): ...
def load_model(self, model_path): model_path = model_path.replace('\\', '/') model = tf.keras.models.load_model(model_path, compile=False) basename = os.path.basename(model_path) if basename.endswith('_cd.h5'): val_found = False for i in range(len(basename) - 1, 0...
This code initializes a time series prediction model for stock data, setting parameters like ticker, date ranges, hyperparameters (learning rate, time step), and model type (LSTM). It loads or builds a neural network model, splits data into training/validation sets, and prepares inputs/outputs for training. The main ta...
def __init__(self, ticker, start_date, end_date, interval='1d', lr=0.001, time_step=14, batch_size=32, future_step=7, model_type='lstm', validation_ra...
def plot_train_validation_data(self, train_data, validation_data): len_train = len(train_data) len_validation = len(validation_data) len_sum = len_train + len_validation padded_train_data = train_data.tolist() + [None for _ in range(len_sum - len_train)] padded_validation_data = ...
The code trains a neural network model using custom data, performing batch-wise gradient computation with Adam optimizer. It shuffles training data, iteratively updates the model, and saves checkpoints every 2000 iterations with filenames incorporating validation metrics (MAPE/MAE). Training stops at max iterations, fo...
def fit(self): print(f'\ntrain on {len(self.train_x)} samples. train_x.shape : {self.train_x.shape}') print(f'validate on {len(self.validation_x)} samples. validation_x.shape : {self.validation_x.shape} ') self.plot_train_validation_data(self.train_data, self.validation_data) self.model....
def __clear_buffers(self): """Clears the input and output buffers""" try: self._port.reset_input_buffer() self._port.reset_output_buffer() except AttributeError: # pySerial 2. self._port.flushInput() self._port.flushOutput() def __writ...
The main task of the code is to synchronize with a Lua-based NodeMCU device by sending auto-baud trigger characters, clearing buffers, executing a Lua print command, and verifying the expected response to establish communication. It handles timeouts by raising an exception if synchronization fails, ensuring the device ...
def __sync(): """Get in sync with LUA (this assumes that NodeMCU gets reset by the previous two lines)""" log.debug('getting in sync with LUA') self.__clear_buffers() try: self.__writeln('UUUUUUUUUUUU') # Send enough characters for auto-baud ...
def __exchange(self, output, timeout=None): """Write output to the port and wait for response Expects a str as input""" if not isinstance(output, str): raise TypeError("output should be a str") self.__writeln(output) self._port.flush() return self.__expect(tim...
This function downloads a file from a remote device to RAM by sending a request, validating responses, and receiving data in chunks. It handles error checking, acknowledges receipt, and concatenates data chunks into a byte string for return.
def download_file(self, filename): """Download a file from device to RAM Return 'bytes' of the full content """ validate.remotePath(filename) res = self.__exchange('send("{filename}")'.format(filename=filename)) if ('unexpected' in res) or ('stdin' in res): lo...
def __writeln(self, output): """write, with linefeed""" self.__write(output + '\n') def __expect(self, exp='> ', timeout=None): """will wait for exp to be returned from nodemcu or timeout. Will use utils.ENCODING for encoding if not bytes. """ timeout_before = self._port....
The code verifies if a local file matches a remote file by comparing their checksums or raw content. It supports 'raw' (direct content comparison), 'sha1' (SHA1 hash comparison), or 'none' (no verification). If verification fails, it logs an error and raises a VerificationError.
def verify_file(self, local, remote, verify='none'): """Tries to verify if local has same checksum as remote. Valid options for verify is 'raw', 'sha1' or 'none' """ # get the local file contents self.__writeln(';') self.__expect('> ') content = from_file(loca...
def file_list(self): """list files on the device""" log.info('Listing files') res = self.__exchange(LIST_FILES) res = res.split('\r\n') # skip first and last lines res = res[1:-1] files = [] for line in res: files.append(line.split('\t')) ...
The code's main task is to back up all files from a device to a specified directory. It logs the backup process, retrieves a list of files, prepares the device, and iteratively reads each file, saving it to the provided path with the same filename, ensuring a complete copy of all device files.
def backup(self, path): """Backup all files from the device""" log.info('Backing up in '+path) # List file to backup files = self.file_list() # then download each of then self.prepare() for f in files: self.read_file(f[0], os.path.join(path, f[0]))
def __writeln(self, output): """write, with linefeed""" self.__write(output + '\n') def __expect(self, exp='> ', timeout=None): """will wait for exp to be returned from nodemcu or timeout. Will use utils.ENCODING for encoding if not bytes. """ timeout_before = self._port....
This function uploads a file to a remote device via a transfer protocol by splitting the file into 128-byte chunks, sending each chunk with acknowledgment checks, and verifying the transfer. It handles destination path validation, sends the filename, transfers data in blocks, and includes verification if specified.
def write_file(self, path, destination='', verify='none'): """Uploads a file to the remote device using the transfer protocol""" filename = os.path.basename(path) if not destination: destination = filename validate.remotePath(destination) log.info('Transferring %s as...
def __parse_both_fighter_from_soup(soup): elements = soup.findAll('a', 'b-fight-details__person-link') return elements[0].attrs['href'].strip().split('/')[-1], elements[1].attrs['href'].strip().split('/')[-1] def __parse_winner_from_soup(soup): elements = soup.findAll('div', 'b-fight-details__person') f...
This function crawls and persists detailed data about a specific fight (given by fight_id), including fighter IDs, bout outcomes, weight class, and round-specific statistics. It extracts information from HTML using helper functions, stores fight and fighter data, and returns the parsed fight details for further process...
def crawl_fight_with_id(fight_id: str): LOG = logging.getLogger(__name__) LOG.debug(f'Crawling fight {fight_id}...') soup = util.get_soup(URL_FIGHT + fight_id) fight = Fight(id=fight_id) fighter1, fighter2 = __parse_both_fighter_from_soup(soup) crawl_fighter_with_id(fighter1) crawl_fight...
def search_field(self,query): fild_lis = self.sep_fields(query) for i in fild_lis: pseudo_query = self.tok(i[1]) for w in pseudo_query: docs = self.ret_pos(w) if(len(docs)>0): idf = math.log2(total_docs/len(docs)) ...
The main task of the code is to process a list of search queries by iterating through them, determining if each query is a field-based query (split by colon) or a normal query, executing corresponding search methods (search_field or search_normal), and collecting results into a document dictionary before writing the ou...
def search(self): for i in self.queries: self.start = datetime.now() temp = i.split(":") if(len(temp)>1): # field query self.search_field(i.lower()) else: # normal query self.search_normal(i.lower()) ...
def _defaults(): default = { "padding": 5, "message_colour": (255, 255, 255), "outline_colour": (0, 0, 0), "background_colour": (0, 0, 0), "hold_time": 2.0, "step_time": 0.075 } return default def get_text_from_web(): global connected_to_wifi if not co...
This code displays and scrolls text on a screen, adjusting brightness via buttons. It fetches new text every 30 seconds, manages scrolling states (pre-scroll, scrolling, post-scroll), calculates text width for proper shifting, and updates the display with dynamic text and background color.
def display_text(initial_text="", initial_brightness=0.5, setup_values=_defaults()): last_time = time.ticks_ms() last_request = int(time.time()) message_text = initial_text shift = 0 state = STATE_PRE_SCROLL gu.set_brightness(initial_brightness) # set the font graphics.set_font("bitmap...
def redraw_display_if_reqd(): global clock, year, month, day, wd, hour, minute, second, last_second, old_secs, time_chgd, ptm, vol_set if time_chgd: rtc.datetime((year,month,day,wd,hour,minute,second,0)) time.sleep(0.1) tm = time.time() + (utc_offset * 3600) tm_local = time.localtim...
The function `sync_time()` connects to a WiFi network, synchronizes the device's real-time clock (RTC) with an NTP server, and handles connection errors. It checks WiFi availability, establishes a connection, waits for success, syncs time via `ntptime.settime()`, and disconnects. If synchronization fails, it logs error...
def sync_time(): global wlan, tone_a, tone_b if not do_sync: return if not wifi_available: return TAG="sync_time(): " msg_shown = False # Start connection wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(WIFI_SSID, WIFI_PASSWORD) # Wait for con...
def my_dev(): if my_debug: global dev_dict TAG= "my_dev(): " dev_lst = ['sysname', 'nodename', 'release', 'version', 'machine'] dev_dict = {} s_tpl = os.uname() le = len(s_tpl) for i in range(le): dev_dict[dev_lst[i]] = s_tpl[i] if my_debug: print(TAG+f"dev_d...
The code's main task is to configure and synchronize a device's RTC with an NTP server, monitor hardware inputs (buttons) for adjusting time, brightness, and volume, display dynamic information including countdowns, and manage periodic updates. It initializes device details, handles user interactions via switches, and ...
def main(): global dev_dict, clr_idx, tone_a, tone_b, vol_set, vol TAG="main(): " my_dev() # fill dev_dict with os.uname() keys and values if len(dev_dict) > 0: k = dev_dict.keys() if 'machine' in k: print(TAG+f"This script is running on a \'{dev_dict['machine']}\'") ...
def model_from_checkpoint_path(checkpoints_path): from .models.all_models import model_from_name assert (os.path.isfile(checkpoints_path+"_config.json") ), "Checkpoint not found." model_config = json.loads( open(checkpoints_path+"_config.json", "r").read()) latest_weights = find_lat...
The main task of the code is to process a video using a segmentation model, predicting and visualizing each frame's segmentation results. It reads video input, applies the model to each frame, overlays predictions with specified colors, and either displays the output in real-time or saves it to a file. The function han...
def predict_video(model=None, inp=None, output=None, checkpoints_path=None, display=False, overlay_img=True, class_names=None, show_legends=False, colors=class_colors, prediction_width=None, prediction_height=None): if model is None and (checkpoints_path is not...
def get_release_scans(release_file): scan_lines = urllib.request.urlopen(release_file) scans = [] for scan_line in scan_lines: scan_id = scan_line.decode('utf8').rstrip('\n') scans.append(scan_id) return scans def download_scan(scan_id, out_dir, bucket, unzip=False): print('Downloadi...
The main task of the code is to download EDINA public data releases, either specific scan IDs or full train/test sets, based on user input. It validates scan IDs against predefined lists, organizes downloads into designated directories, and handles unzipping. The script uses command-line arguments to specify output pat...
def main(): parser = argparse.ArgumentParser(description='Downloads EDINA public data release.') parser.add_argument('-o', '--out_dir', required=True, help='directory in which to download') parser.add_argument('--id', help='specific scan id to download') parser.add_argument('--split', help='download the...
def LoadData(datasetname='MNIST', limit=100): print("LOADING DATASETS") print("-------------------") transform = TransformData() print("LOADING TRAINING DATA") dataset = GNNBenchmarkDataset('data', datasetname, split="train", transform=transform) if limit>0: dataset = dataset[:limit] origina...
This function loads and preprocesses a graph dataset (e.g., MNIST) for training, handling both original and converted data formats. It checks for pre-saved pickle files, loads target labels, truncates data based on a limit, applies transformations, and returns processed datasets along with targets. Options include norm...
def LoadTrain(datasetname='MNIST', skipLine=True, limit=0, doNormalize = False): if (not os.path.exists('data/train/target_data.pkl') or (not os.path.exists('data/train/converted_dataset.pkl') and not skipLine)): LoadData(datasetname,limit) file_name = 'data/train/target_data.pkl' with open(file_name, '...
def LoadData(datasetname='MNIST', limit=100): print("LOADING DATASETS") print("-------------------") transform = TransformData() print("LOADING TRAINING DATA") dataset = GNNBenchmarkDataset('data', datasetname, split="train", transform=transform) if limit>0: dataset = dataset[:limit] origina...
The function `LoadVal` loads and preprocesses validation data from a specified dataset (e.g., MNIST), optionally limiting data size and applying normalization. It retrieves target labels from a pickle file, loads the dataset using `GNNBenchmarkDataset`, and preprocesses it. If `skipLine` is False, it also loads a prepr...
def LoadVal(datasetname='MNIST', skipLine=True, limit=0, doNormalize = False): if not os.path.exists('data/val/target_data.pkl'): LoadData(datasetname, limit) file_name = 'data/val/target_data.pkl' with open(file_name, 'rb') as file: print(file_name, " loaded") target = pickle.load(file...
def LoadData(datasetname='MNIST', limit=100): print("LOADING DATASETS") print("-------------------") transform = TransformData() print("LOADING TRAINING DATA") dataset = GNNBenchmarkDataset('data', datasetname, split="train", transform=transform) if limit>0: dataset = dataset[:limit] origina...
This function loads and preprocesses a test dataset for graph neural networks. It retrieves target labels from a pickle file, loads the dataset using GNNBenchmarkDataset, applies transformations, and optionally normalizes data. If specified, it also loads a preprocessed converted dataset. The function returns the proce...
def LoadTest(datasetname='MNIST', limit=0, skipLine=True, doNormalize = False): if not os.path.exists('data/test/target_data.pkl'): LoadData(datasetname) file_name = 'data/test/target_data.pkl' with open(file_name, 'rb') as file: print(file_name, " loaded") target = pickle.load(file) ...
def add_sidebar(): st.sidebar.header("Cell Nuclei Measurement") data=get_clean_data() slider_labels=[ ('Radius(mean)','radius_mean'), ('Texture(mean)','texture_mean'), ('Perimeter(mean)','perimeter_mean'), ('Area(mean)','area_mean'), ('Smoothness(mean)','smo...
The code creates a Streamlit web app for breast cancer prediction. It configures the page layout, collects user input via a sidebar, displays a radar chart visualizing input data, and shows prediction results. The app aims to diagnose breast cancer using tissue sample data through interactive visualization and machine ...
def main(): st.set_page_config( page_title='Breast Cancer Predictor', page_icon=':female-doctor:', layout='wide', initial_sidebar_state='expanded' ) input_data=add_sidebar() with st.container(): st.title('Breast Cancer Predictor') st.wr...
def q_posterior(self, log_x_start, log_x_t, t): # q(xt-1 | xt, x0) = q(xt | xt-1, x0) * q(xt-1 | x0) / q(xt | x0) # where q(xt | xt-1, x0) = q(xt | xt-1). t_minus_1 = t - 1 t_minus_1 = torch.where(t_minus_1 < 0, torch.zeros_like(t_minus_1), t_minus_1) log_EV_qxtmin_x0 = self.q_p...
This function computes a loss for a probabilistic model by combining KL divergence between true and predicted distributions with decoder negative log likelihood, weighted by a time-step mask. It returns the loss and reconstructed values for training or evaluation.
def compute_Lt(self, log_x_start, log_x_t, t, cond_con, detach_mean=False): log_true_prob = self.q_posterior( log_x_start=log_x_start, log_x_t=log_x_t, t=t) log_model_prob, log_x_recon = self.p_pred(log_x=log_x_t, t=t, cond_con=cond_con) if detach_mean: log_model_prob =...
def _get_num_train_samples(self): """ returns number of train samples (training set size) """ return integer_floor(self._get_num_samples()*self.train_ratio) def _get_num_test_samples(self): """ returns number of test samples (test set size) """ ...
The code defines the `__repr__` method to return a string representation of an object, including its class name and the counts of training samples, test samples, and labels. This aids in debugging by providing a concise summary of the object's state.
def __repr__(self): return self.__class__.__name__ + \ f"(n_train_samples: {self._get_num_train_samples()}, " \ f"n_test_samples: {self._get_num_test_samples()}, " \ f"n_labels: {self.get_num_labels()})"
def move_dest(start, to): return [(start[0] + i * move_vectors[to % N_VECTORS][0], start[1] + i * move_vectors[to % N_VECTORS][1]) for i in range(1, to // N_VECTORS + 2)] def can_eat(start, to): global desk piece = desk[start[0]][start[1]] if not piece: return False, [] if piece ...
This function handles a move in a board game, validating if a piece can move or capture based on rules. It checks for empty cells, correct piece color, valid move paths, and backward movement restrictions. If valid, it updates the board state, manages piece transformations (e.g., king promotion), and adjusts game state...
def move(start, to): global desk, restricted piece = desk[start[0]][start[1]] dest = move_dest(start, to)[-1] after_dest = move_dest(dest, to % N_VECTORS)[-1] if not piece: print('Empty cell') return False if (piece - white_move) % 2 == 1: print('Wrong color') ret...
def recommendSongs(self): print('Obtaining the recommended choices..........') for ss in self.init_song_strings: r = spootify.search(ss,limit=1)['tracks']['items'][0] self.ResultsOfSearch.append({ 'id':r['id'], 'artists':[i['name'] ...
This code initializes a playlist object with a name and three songs, setting up data structures to store song recommendations, features, and transformed data. It triggers methods to recommend songs, extract features, transform data, build a song list, and preview results, likely for a music recommendation or analysis s...
def __init__(self, playlistName, song1, song2, song3): self.name = playlistName List_Of_Songs.playlists[self.name] = self self.init_song_strings = [] self.ResultsOfSearch = [] self.RecommendedIdsOfTracks = [] self.trax = [] self.df = None self.playlist ...
def startMicrophone(self): self.speech_service.setAudioExpression(False) # Disable audio expression self.speech_service.setVisualExpression(False) # Disable visual expression self.audio_recorder.stopMicrophonesRecording() # Stop any previous recording self.audio_recorder.startMicrophones...
This code handles touch events on a body part (specifically the head) by starting/stoping a microphone and processing speech-to-text when the head is touched/released. It disconnects from the touch event to prevent repetition, processes audio input upon release, then reconnects to continue listening for future touches....
def onTouched(self, strVarName, bodyValues): # Disconnect to the event when talking, to avoid repetitions self.touch.signal.disconnect(self.id) touchedBodies = [] for partValues in bodyValues: if partValues[0] == "Head": if partValues[1]: # If touched ...
def convertGCode(self, gcode_layers): self._clearValues() current_path = [] current_position = self._position(0, 0, 0, 0, [0]) for gcode_layer in gcode_layers: for line in gcode_layer.split("\n"): G = self._getInt(line, "G") if G is not None: ...
The main task of the code is to convert G-code paths into an STL mesh by generating 3D vertices for each path using a specified tube shape (rectangular or diamond), then writing the resulting mesh data to a binary STL file stream. It processes each path, calculates line width, constructs vertices via shape-specific fun...
def write_stl(self, stream): tube_type = "rectangular" #tube_type = "diamond" num_vertices = { "diamond": 16, "rectangular": 12} tube_function = { "diamond": self._generateTubeVerticesDiamond, "rectangular": self._generateTubeVerticesRecta...
def convertGCode(self, gcode_layers): self._clearValues() current_path = [] current_position = self._position(0, 0, 0, 0, [0]) for gcode_layer in gcode_layers: for line in gcode_layer.split("\n"): G = self._getInt(line, "G") if G is not None: ...
This function converts G-code paths from a 3D printing scene into OpenSCAD code, writing it to a stream. It retrieves active build plate data, checks for G-code, adjusts parameters like line width and layer thickness, and generates SCAD shapes (cube/cylinder) with offsets. The output represents 3D printable geometry in...
def write_scad(self, stream, shape = "cube"): active_build_plate = Application.getInstance().getMultiBuildPlateModel().activeBuildPlate scene = Application.getInstance().getController().getScene() if not hasattr(scene, "gcode_dict"): return False gcode_dict = getattr(scene, "...
def convertGCode(self, gcode_layers): self._clearValues() current_path = [] current_position = self._position(0, 0, 0, 0, [0]) for gcode_layer in gcode_layers: for line in gcode_layer.split("\n"): G = self._getInt(line, "G") if G is not None: ...
This code converts GCode data from a 3D printing scene into CSV format by extracting active build plate paths, calculating line widths, and writing position/size details to a stream. It retrieves scene data, processes GCode paths, computes line dimensions, and outputs structured CSV lines with positional and dimensiona...
def write_csv(self, stream): active_build_plate = Application.getInstance().getMultiBuildPlateModel().activeBuildPlate scene = Application.getInstance().getController().getScene() if not hasattr(scene, "gcode_dict"): return False gcode_dict = getattr(scene, "gcode_dict") ...
def selectSplittingAttribute(self, D, A, threshold): # uses information gain gains = dict.fromkeys(A, 0) for a in A: gains[a] = self.findBestSplit(D, a)[1] best = max(gains, key=gains.get) if gains[best] > threshold: return best else: return N...
The code implements the C4.5 decision tree algorithm to recursively construct a classification tree. It checks termination conditions (pure class labels or no attributes left), selects the optimal splitting attribute, and builds child nodes by recursively applying the algorithm to subsets of data. The tree nodes store ...
def C45(self, D, A, og_D, threshold, parent_val=None, parent_var=None, sign=None): T = {} class_labels_counts = D.iloc[:,-1].value_counts().to_dict() c = max(class_labels_counts, key=class_labels_counts.get) # Step 1: check termination conditions if len(class_labels_counts.keys(...
def getEnv(name): return environ[name] def updateOrinsert(param) : try: query(""" INSERT INTO cm_ai_model( APP_ID, `INPUT`, UPD_TMS ) VALUES( '""" + g...
This function saves a TensorFlow model using `tf.saved_model.simple_save` to a directory specified by environment variables, removes any existing files in the target directory, and updates records with input keys. It handles exceptions during directory removal and performs a push operation after saving.
def simple_save(sess, inputs, outputs): path = getEnv("GIT_REPO_PATH") l = list(inputs.keys()) try: shutil.rmtree(path + "/" + getEnv("PRJ_ID") + '/model/' + getEnv("APP_VER")) except OSError: pass tf.saved_model.simple_save(sess, path + "/" + getEnv("PRJ_...
def cohesion_alignment(self,bL): if len(bL)<2: return([self.p,[0,0]]) else: sbL=sorted(bL,key=self.dist2) if len(sbL)>7:sbL=sbL[:6] p=array([0.0,0.0]) v=array([0.0,0.0]) for b in sbL: p=p+b.p ...
This code computes an agent's next velocity and position using a combination of cohesion, separation, following, and escape forces. It applies these forces via a dot product with parameters, normalizes velocity to a maximum limit, updates position with time step dt, and stores the new position. The main task is simulat...
def np(self,bL,dt,t): x=self.cohesion_alignment(bL) forces=[x[0],x[1],self.Separation(bL),self.follow(t),self.escape(bL)] self.next_v=dot(self.prameters,forces) self.next_v=self.max_v*self.next_v#/norm(self.next_v) self.next_p=self.p+array(self.v)*dt ...
def hunt(self,bL): if self.hanger > 0: return([0,0]) else: #find the closest target target=bL[1] for b in bL: if b.name!=self.name: if self.dist2(target)>self.dist2(b): target=copy(b) ...
This code calculates an agent's next velocity and position by combining forces from hunting, separation, and flight behaviors. It adjusts forces based on a 'hanger' state, scales them using parameters, normalizes velocity, and updates the agent's position for simulation. Force vectors are logged for visualization.
def np(self,bL,dt,t): global scale hunting=self.hunt(bL) fly=self.fly(t) if self.hanger>0: hunting=array([0,0]) else: pass fly=array([0,0]) self.hanger -= dt forces=[hunting,self.separation(bL),fly] self.next_v...
def lastest_block(self): return (self.latest_nth_block(1)) def get_chain_data(self): # Update/Get chain data from mongo DB get_block_index = 1 print(f"[*] Need to load {count_rawdata()} blocks.") while(get_block_index < count_rawdata()): print(f"[*] Loading Block {get_block_index}") ...
The main task of the code is to mine new blocks in a blockchain system. It checks for slow mode (with a 3-second delay), synchronizes the blockchain by comparing the latest block's hash with the database, and triggers proof-of-work mining if no blocks are received. The loop runs twice, ensuring chain updates and mining...
def run_miningBlock(self): for num in range(2): if len(sys.argv) == 4: print("[**] Slow mode on: sleeping 3 seconds when mining new block...") time.sleep(3) # Update chain if it is not synchronized if (self.lastest_block().current_hash != get_latestblock_fromDB()["current_hash...
def minimumFind(count): minV=count[0] minIndex=0 for i in range(0,len(count)): if(count[i]<minV): minV=count[i] minIndex=i return minV,minIndex def genWord3gramVec(w1,w2,triCount,biCount): predict=['','','','',''] count=[0,0,0,0,0] minV=0 minIndex=0 fo...
This function predicts the next word(s) following a 3-word sequence (w1, w2, w3) using 4-gram frequency data (quadCount). It identifies the most frequent 4-gram matches, then falls back to 3-grams (triCount) and 2-grams (biCount) if no 4-gram matches exist. The output is a list of predicted words based on these n-gram ...
def genWord4gramVec(w1,w2,w3,quadCount,triCount,biCount): predict=['','','','',''] count=[0,0,0,0,0] minV=0 minIndex=0 for k,v in quadCount.items(): if(k[0]==w1 and k[1]==w2 and k[2]==w3): if(v>minV): count[minIndex]=v predict[minIndex]=k[3] ...
def initialize(self, data): self.room_group_name = data self.who_am_i = self.get_who_am_i() async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) game_session = GameSessionModel.get_ongoing_session_by_url(self.roo...
This code handles incoming messages in a WebSocket consumer. It parses JSON data to determine the message type, then triggers corresponding actions: initializing a session, terminating it via timeout or kill command, or processing game messages. The core task is routing and responding to different message types in a re...
def receive(self, text_data): data_json = json.loads(text_data) message = data_json.get('message', '') message_type = data_json.get('type', '') if message_type == 'initialize': self.initialize(message) elif message_type == 'kill_session' or self.is_timeout(): ...
def get_CIFAR10(opts): modified_indicies = None data_tr = datasets.CIFAR10(opts.path + '/CIFAR10', train=True, download=True) data_te = datasets.CIFAR10(opts.path + '/CIFAR10', train=False, download=True) X_tr = data_tr.data Y_tr = np.array(data_tr.targets) X_tr, Y_tr, modified_indicies = add_mo...
The code defines a function `get_dataset` that retrieves specific datasets based on the input name. It acts as a factory method, returning different dataset loaders (`get_CIFAR10`, `get_SVHN`, `get_KMNIST`) depending on the provided name parameter, while passing additional configuration options (`opts`) to each respect...
def get_dataset(name, opts): if name == 'CIFAR10': return get_CIFAR10(opts) elif name == 'SVHN': return get_SVHN(opts) elif name == 'KMNIST': return get_KMNIST(opts)
def compute_distributions(range_checkpoint): distributions = {checkpoint: (generate_random_discrete_distribution(size+1), generate_random_discrete_distribution(size+1)) for size, checkpoint in enumerate(range_checkpoint)} return distributions def plot_distances_between_n...
This code visualizes the evolution of policy sampling distributions versus max-ent Nash equilibria during training. It allows users to select self-play algorithms (Naive SP, Full History SP, Iterated Nash Response) and training checkpoints. The code computes and plots distance metrics between distributions, compares sp...
def exploration_view(results_dir): name = 'Evolution of policy sampling distribution VS Nash averaging' st.write(f'# {name}') selfplay_choice = st.sidebar.radio('Select Self-Play algorithm', ('Naive SP', 'Full History SP', 'Iterated Nash Response')) st.write('##...
def initialize_agent(task): # Config defined in paper config = dict() config['discount'] = 0.99 config['use_gae'] = True config['use_cuda'] = False config['gae_tau'] = 0.95 config['entropy_weight'] = 0.01 config['gradient_clip'] = 5 config['optimization_epochs'] = 10 config['mini...
This code implements a multi-agent reinforcement learning approach for the Rock-Paper-Scissors environment. It generates self-play trajectories using a NaiveSelfPlay scheme, computes basis trajectories, merges them, and analyzes action patterns through t-SNE embeddings to visualize learned strategies. The process invol...
def main(): task = generate_task('RockPaperScissors-v0', EnvType.MULTIAGENT_SIMULTANEOUS_ACTION) print('Initializing agent') agent = initialize_agent(task) print('Computing SP-induced trajectories') training_trajectories = compute_sp_training_trajectories( task=task, agent=agent, ...
def plot_basis_only(embedding, ax): basis_embedding = embedding[:3000] # HACK: we know the first 3000 points are the basis plot_basis_scatter(basis_embedding, ax) return ax def plot_basis_and_first_episodes(embedding, ax): plot_basis_scatter(embedding[:3000], ax) first_500_eps = embedding[3000:3500...
The main task of the code is to generate and visualize embeddings by creating three distinct plots: a basis-only scatter plot, a plot combining the basis with first episodes, and a plot showing the basis, episodes, and trajectory evolution. The code loads embedding data, uses matplotlib for visualization, and saves the...
def main(embedding, save): embedding = pickle.load(open(args.embedding, 'rb')) # Create matplotlib figure fig = plt.figure() ax = fig.add_subplot(111) ax.axis('off') ax = plot_basis_only(embedding, ax) if save: plt.savefig('rirrps_basis_scatter_plot.pdf', format='pdf', dpi=1000, tr...
def getXMLpath(self, doexit = True, dowrite = False): etcpath = "/etc/" XMLpath = "" # first look in etc if os.path.isfile(os.path.join(etcpath,XML_FILENAME)): XMLpath = os.path.join(etcpath,XML_FILENAME) if dowrite and not os.access(XMLpath, os.W_OK): ...
The code initializes a database dictionary and checks if an XML path exists. If not, it creates and retrieves an XML file; otherwise, it directly retrieves the existing XML. The main task is to manage XML file creation and retrieval based on path validation during object initialization.
def __init__(self): self.db = {} if not self.getXMLpath(False): # only create xml if super user, otherwise keep empty self.createXML() self.getXML() else: self.getXML()
def updateOrder_add(self, orderMap, depth, side, orderNum, price, qty): # get existing price level or add new one pxLevel = None pxIdx, found = self.findPrice(depth, side, price) if found: pxLevel = depth[pxIdx] else: depth.insert(pxIdx, PriceLevel(side, p...
The code updates market depth data by processing order ticks. It selects the appropriate buy/sell depth and order map based on the tick's side, then executes an add, modify, or delete operation on the order book using corresponding methods. The function handles order updates by adjusting quantity, price, or removing or...
def updateOrder(self, tick): """ Update market depth based on ORDER tick """ depth = self.buyDepth if tick.side == "BUY" else self.sellDepth orderMap = self.buyOrderMap if tick.side == "BUY" else self.sellOrderMap # if tick.orderNum == '62179824': # print('Stop') if t...
def is_bra(string: str) -> bool: global parser_idx return string[parser_idx] in bra_list def atom_number(string: str) -> "defaultdict[str, int]": # atom_number: { atom, natural_number } res: defaultdict[str, int] = defaultdict(int) while True: atom_str = atom(string) ...
The code parses a string containing bracketed expressions, extracting atom numbers and natural numbers, multiplying them, and replacing bracketed segments with the result. It iteratively processes nested brackets, updating the string until all brackets are removed, then returns the final atom counts as a defaultdict. Y...
def nests(string: str) -> "defaultdict[str, int]": global parser_idx # Get the index of the last bra parser_idx = max([string.rfind(bra) for bra in bra_list]) while parser_idx != -1 and parser_idx < len(string): start_idx = parser_idx # Check bra if no...
def check_brackets(string: str) -> None: re_brackets = re.compile(r"[\(\)\[\]\{\}]") brackets_dict = {bra_list[idx]: ket_list[idx] for idx in range(len(bra_list))} check_brackets = list() brackets = re_brackets.findall(string) for c in brackets: if c in bra_list: ...
The main task of the code is to parse a chemical formula string into a dictionary mapping elements to their respective counts, handling nested brackets, numbers, and validating the input's structure and characters.
def molecule(string: str): global parser_idx check_brackets(string) check_invalid_characters(string) string = parse_head_number(string) elem_num = nests(string) retval: dict[str, int] = dict() for key in elem_num: retval[key] = elem_num[key] re...
def change_state_by_char(string, pointer, state, lexeme): global Nodes current_char = string[pointer] next_state = 0 pointer_move = 0 token_found = False error = "" temp_lexeme = "" if is_valid(current_char): next_state = check_edges(current_char, state) # print(next_stat...
This function tokenizes input by processing characters through state transitions, updating the symbol table, handling line increments for newlines, and returning the next token (e.g., ID, EOF) or error messages. It tracks position (pointer), line numbers, and lexer states, using helper functions to determine token name...
def get_next_token(): global pointer global line global state global input_file global symbol_list temp_lexeme = "" token_name = "" return_state = [] while True: #print(pointer, input_file[pointer], state) return_state = change_state_by_char(input_file, pointer, stat...
def change_state_by_char(string, pointer, state, lexeme): global Nodes current_char = string[pointer] next_state = 0 pointer_move = 0 token_found = False error = "" temp_lexeme = "" if is_valid(current_char): next_state = check_edges(current_char, state) # print(next_stat...
The main task of the code is to tokenize input text by processing characters using a state machine. It identifies lexemes, handles line tracking, error reporting, and symbol table updates. The function returns the next token as "(token_name, lexeme)", manages EOF, unclosed comments, and invalid inputs, while updating g...
def get_next_token(): global pointer global line global state global input_file global symbol_list temp_lexeme = "" token_name = "" return_state = [] while True: #print(pointer, input_file[pointer], state) return_state = change_state_by_char(input_file, pointer, stat...
def _listing_xml(directory): """Function to create list of athlete data from rio PDF file XML. Args: directory: Name of directory containing data Returns: data: List of dicts of data """ # Initialize key variables profiles = [] regex_date = re.compile(r'^.*?>([0-9]+ [A-Z]+...
The main task of the code is to process athlete profiles from XML and HTML files in specified directories, combine and deduplicate them, then save the unique profiles as a YAML file. It accepts command-line arguments for input/output directories, processes data via helper functions, and outputs the count of profiles an...
def main(): """Main Function. Process Fina XML file """ # Initialize key variables profiles = [] ts_start = int(time.time()) # Get CLI arguments parser = argparse.ArgumentParser() parser.add_argument( '-f', '--fina_directory', help='Name of directory containing FIN...
def events(self, stage=None): """Get all event information. Args: stage: Round of event Returns: data: List of dicts with information """ # Get data data = [] # Get sesssions sessions = self.sessions() for session in se...
The function `allresults` retrieves and aggregates results for all events, optionally filtered by a specified stage. It collects event IDs, fetches results for each, combines them into a list, sorts the data using `results_csv_sorter`, and returns the sorted list of dictionaries containing event information.
def allresults(self, stage=None): """Get results for all events. Args: stage: Round of event Returns: data: List of dicts with information """ # Initialize key variables event_ids = [] _data = [] # Get results for each event ...
def results(self, event_id): """Get results for an event. Args: event_id: Event ID number Returns: data: List of dicts with information """ # Initialize key variables data = [] # Get athlete data for event athletes = self.athlet...
This function generates structured data for CSV output by aggregating event details, participant vitals, and calculated metrics like BMI and swimming speed. It processes event results, filters out invalid entries, and compiles information into a list of dictionaries containing meet details, athlete data, and performanc...
def results_csv(self, _event_id): """Get results for an event. Args: _event_id: Event ID number Returns: data: List of dicts with information """ # Initialize key variables event_id = str(_event_id) participants = self.results(event_id) ...
def events(self, stage=None): """Get all event information. Args: stage: Round of event Returns: data: List of dicts with information """ # Get data data = [] # Get sesssions sessions = self.sessions() for session in se...
The function aggregates results from all events by iterating through each event's ID, collecting their CSV data, and returning a sorted list of combined results. It filters events by the specified 'stage' parameter, sorts event IDs, and merges individual event results into a single sorted dataset for output.
def allresults_csv(self, stage=None): """Get results for all events. Args: stage: Round of event Returns: data: List of lists with information """ # Initialize key variables event_ids = [] _data = [] # Get results for each event...
def topic_analysis_embeddings(analyzer, subgraph, **settings): """ Rerun topic analysis based on embeddings """ subgraph_df = analyzer.df[analyzer.df.id.isin(subgraph.nodes)] embeddings = preprocess_embeddings( subgraph, # Dataframe cannot be hashed, so use tuples of columns ...
This function performs topic clustering on a subgraph using specified methods (e.g., embeddings, DBSCAN, Louvain, LDA), returning a dictionary mapping PMIDs to cluster IDs. It delegates to specialized analysis functions based on the chosen method and parameters, enabling flexible text clustering for scientific document...
def topic_analysis(analyzer, subgraph, method, **method_params): """ Returns partition - dictionary {pmid (str): cluster (int)} """ if method == 'embeddings': return topic_analysis_embeddings(analyzer, subgraph, **method_params) if method == 'dbscan': return topic_analysis_dbscan(ana...
def binaryToDict(self, inputBinary): # tempJSON = inputBinary.decode() return pickle.loads(inputBinary) def messageReceived(self, connectionPort, dataDict): if self.connections[connectionPort]["dh"].getSharedKey(): print("Message from",self.connections[connectionPort]["name"],"-",dec...
This function continuously receives UDP packets, converts the binary data into a dictionary, and routes the data to appropriate handlers based on its type ("message" or "key") by calling either messageReceived or keyReceived methods with the received port and data dictionary.
def receiveThreadFunction(self): while True: data, recvAddress = self.sock.recvfrom(4096) dataDict = self.binaryToDict(data) recvPort = recvAddress[1] # routing request appropriatly if dataDict["type"]=="message": self.messageReceived(r...
def enemy_generation(self, count, last_x_pos): if self.is_game_start == True: for i in range(0, count): self.x_pos = last_x_pos + random.randint( last_x_pos - 20, last_x_pos + 40 ) last_x_pos += 80 self.y_pos = 10 - ...
This code initializes a game's main components, including player, enemies, coins, road backgrounds, score tracking, UI elements, and game state variables. It sets up Pygame window, loads assets, positions objects, and prepares for game loop execution with collision detection and user interaction handling.
def __init__(self): # constructor and self is a reference of object # for enemy self.score = 0 self.x_pos = 0 self.y_pos = 0 self.count = 30 # for coin self.coin_count = 0 self.coin_x_pos = 0 self.coin_y_pos = 0 self.c_count = 50 ...
def energy_from_series(series, params): return series.sum() / samples_per_hour(params) def force_split_active_area(active_area_series, n): ind = active_area_series.index borders = np.linspace(0, len(ind), n + 1).astype(np.int32) borders[-1] = len(ind) if len(set(borders)) != n + 1: return No...
The function generates and evaluates possible splits of an active area time series. It converts the series to a specified frequency, calculates a maximum number of splits based on energy thresholds, iterates through potential splits (1 to max_n), evaluates each split's quality using a rating function, and returns a lis...
def get_rated_active_area_splits(active_area_series, params): active_area_series = active_area_series.asfreq(params["frequency_string"]) rated_splits = [] max_n = min( 10, int(energy_from_series(active_area_series, params) / params["energy_min"]) + 1, ) for n in range(1, max_n): ...
def detect_active_areas_unfiltered( input_series, window_size=12, greater_than=0, narrow=True ): active_mask = input_series > greater_than temp = active_mask.rolling(window_size, center=True).sum() temp = (temp > 0) & (np.isfinite(input_series)) temp = temp.astype("int8").diff() areas = grouper(...
This function identifies active operational periods in a machine's time-series data by filtering segments where power exceeds thresholds. It processes daily data, detects candidate intervals using a sliding window, verifies energy content, and refines results using rated power splits to return valid active area start/e...
def detect_active_areas(machine_series, params): if machine_series.index.freq is None: raise ValueError( "machine_series.index.freq must not be None (to guarantee that there are no holes)" ) machine_series_i_indexed = machine_series.reset_index(drop=True) all_active_areas = [] ...
def __readfile(self, filename): with open(filename, 'r') as sql_file: sqlContent = sql_file.read() return sqlContent.replace('\n', '').split(';') def __typeify(self, line): if 'NewTable' in line[:15]: return 1 def __tableBuilder(self, line): stringBuilder = 'CREAT...
The code processes each line of the input file, checks if the line is of type 1 using `__typeify`, and if so, constructs a new SQL table with `__tableBuilder` and adds it to the collection via `__addTable`, effectively parsing and storing structured data from the file.
def __addin(self, ADD_File): lines = self.__readfile(ADD_File) for line in lines: if self.__typeify(line) == 1: newTable = SQL_Table.SQL_Table( self.__tableBuilder(line) ) self.__addTable(newTable)
def __readin(self, SQL_File): content = self.__readfile(SQL_File) self.tables = [] self.tablenames = {} tablenames = [] for line in content: if 'drop table' in line.lower(): tablenames.apppend()#__nameExtractDT(line)) print('did not wri...
The code initializes a class instance with a name and input object, processes SQLF and ADDF files to populate table data, and uses helper methods to read and validate tables, setting up internal structures for managing database tables and their relationships.
def __init__(self, name, inputObject): self.name = name self.tablenames = {} self.tables = [] if inputObject.getSQLF(): self.droppedtablenames = self.__readin(inputObject.getSQLF()) self.__checkTables() if inputObject.getADDF(): self.__addin(i...
def padding(num, target_length): """ Padding left for number to make it's string format length reaches the target length. This is mainly used to construct valid hex color number in R,G,B position. Example, if the given num is a hex number 0xf and the target length is 2, then the padding result is 0...
The function generates random base colors and their lighter variations, returning a 2D list of hex color codes. It first creates a base color using min/max parameters, then generates `eutmux_base_color_total` base colors and `eutmux_light_color_total` lighter shades for each, ensuring color range constraints. The outpu...
def random_color( min_color=0, max_color=231, eutmux_base_color_total=7, eutmux_light_color_total=24, ): """ Generate random color hex codes. Firstly, it will generate random integer from min_color (0-(255 - eutmux_light_color_total - 1)) to max_color (0-(255 - eutmux_light_color_total)). ...
def _get_soup(cls, url=None, html=None, request_args=None): request_args = request_args or {} if html: return BeautifulSoup(html, 'lxml') headers = dict(cls.request_headers) if url: headers['Host'] = urlparse(url).netloc user_headers = request_args.pop(...
The `get_result` method retrieves similar and exact data from a webpage using either a URL or HTML input. It generates a BeautifulSoup object, then applies learned rules to extract results via `get_result_similar` and `get_result_exact`. The `grouped` parameter determines output structure, returning rule-organized dict...
def get_result(self, url=None, html=None, request_args=None, grouped=False): """ Gets similar and exact results based on the previously learned rules. Parameters: ---------- url: str, optional URL of the target web page. You should either pass url or html or both. ...
def _get_soup(cls, url=None, html=None, request_args=None): request_args = request_args or {} if html: return BeautifulSoup(html, 'lxml') headers = dict(cls.request_headers) if url: headers['Host'] = urlparse(url).netloc user_headers = request_args.pop(...
The code automatically generates scraping rules (stack_list) to extract specified content (wanted_list) from a web page, using either a URL or provided HTML. It processes each target, builds extraction rules, and returns unique results if all targets are successfully scraped, or None otherwise.
def build(self, url=None, wanted_list=None, html=None, request_args=None, update=False): """ Automatically constructs a set of rules to scrape the specified target[s] from a web page. The rules are represented as stack_list. Parameters: ---------- url: str, optional ...
def empty_warehouse(self): for bin_ in self.warehouse.bins: bin_.product = None bin_.occupation = 0 def init_warehouse(self): if init_bins := self.config.get('init_bins'): for bin_, bin_content in init_bins.items(): product = Product(bin_content['produ...
The main task of the code is to initialize a new episode by configuring parameters, resetting the warehouse environment, setting planned positions, updating the next order, and returning the current state. It prepares the simulation for a new sequence of actions by clearing previous data, applying configuration setting...
def episode_start(self, config): self.config = config print('Intializing episode...') print('Config:', self.config) self.empty_warehouse() self.init_warehouse() self.init_planned_pos() self.set_next_po() self.update_state() return self.state
def episode_start(self, config): self.config = config print('Intializing episode...') print('Config:', self.config) self.empty_warehouse() self.init_warehouse() self.init_planned_pos() self.set_next_po() self.update_state() return self.state def ep...
The code dispatches events by routing them to specific handler methods based on their type. It checks the `event_type` of `next_event` and calls corresponding functions like `episode_start`, `episode_step`, or `episode_finish`. If the event is `IDLE`, it prints "Idling" and returns. For unrecognized event types, it rai...
def dispatch_event(self, next_event): if next_event.event_type == BonsaiEventType.EPISODE_START: return self.episode_start(next_event.event_content) elif next_event.event_type == BonsaiEventType.EPISODE_STEP: return self.episode_step(next_event.event_content) elif next_ev...
def is_board_full(self) -> bool: """ Checks if a board is full. Used to end the game :return: True if either dice count is 9 """ p1_dice_count: int = 0 p2_dice_count: int = 0 for p1_column, p2_column in zip(self.p1_dice_list_group, self.p2_dice_list_group): ...
The function `perform_easy_ai_turn` makes an "easy" AI opponent select a random available column to place a piece, but only if the AI timer is sufficiently high and the board isn't full. It avoids immediate actions, updates game state variables, and resets a debounce timer to prevent rapid inputs.
def perform_easy_ai_turn(self) -> None: """ The logic used for an "easy" AI opponent. The AI checks what columns have an open spot and randomly selects one of them. """ if self.ai_timer < 2 or self.is_board_full(): return self.set_turn_values() self.fi...
def is_board_full(self) -> bool: """ Checks if a board is full. Used to end the game :return: True if either dice count is 9 """ p1_dice_count: int = 0 p2_dice_count: int = 0 for p1_column, p2_column in zip(self.p1_dice_list_group, self.p2_dice_list_group): ...
The method `perform_hard_ai_turn` evaluates available columns for a "hard" AI opponent, prioritizes empty columns, calculates potential moves using a tier list, selects the optimal column, and updates the game state by finalizing the turn and resetting the debounce timer.
def perform_hard_ai_turn(self) -> None: """ The logic used for a "hard" AI opponent. The AI checks what columns have an open spot and selects the best spot. """ if self.ai_timer < 2 or self.is_board_full(): return self.set_turn_values() self.first_turn...
def perform_hard_ai_turn(self) -> None: """ The logic used for a "hard" AI opponent. The AI checks what columns have an open spot and selects the best spot. """ if self.ai_timer < 2 or self.is_board_full(): return self.set_turn_values() self.first_turn...
This method updates game logic by handling timers, dice animations, AI behavior based on difficulty, dice movement, score calculation, and visual updates. It alternates between player turns, triggers AI actions (Easy/Hard), filters dice, calculates scores, and adjusts multiplier colors for real-time game progression.
def on_update(self, delta_time): """ All the logic to move, and the game logic goes here. """ self.mouse_debounce_timer += delta_time self.ai_timer += delta_time if self.current_turn: self.p1_current_dice.roll_dice_animation(delta_time) else: ...
def introEvents(self) -> None: for event in pygame.event.get(): if event.type == pygame.QUIT: self.__running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.__gamestate = "playing" def introUpdate(self) -...
This code defines a game loop that runs while the game is active. It checks the current game state and executes corresponding event-handling, update, and drawing functions for intro, playing, or gameover states. It maintains a consistent frame rate using a clock and exits the game when the loop ends.
def run(self) -> None: while self.__running: if self.__gamestate == "intro_screen": self.introEvents() self.introUpdate() self.introDraw() elif self.__gamestate == "playing": self.playingEvents() self.playing...
def setTarget(self, player_grid_pos: Vector2) -> Vector2: if self.__personality == "speedy" or self.__personality == "slow": return player_grid_pos elif self.__personality == "scared": if player_grid_pos.x > NUM_COLUMNS//2: if player_grid_pos.y > NUM_ROWS//2: ...
This code updates an enemy's position by setting a target toward the player, moving the enemy pixel-by-pixel in its direction at a set speed, checking if movement timing is appropriate, and updating grid coordinates based on pixel position adjusted for screen buffer and cell dimensions.
def updateEnemy(self, walls: list, player_grid_pos: Vector2) -> None: self.__target = self.setTarget(player_grid_pos) if self.__target != self.__grid_pos: self.__pix_pos += self.__direction * self.__speed if self.isTimeToMove(): self.move(walls, player_grid_pos) ...
def set_default_dir(self, default_dir: str) -> None: if (path := self.get_dir_path(default_dir)) is None: if default_dir in ["git_root", "git"]: raise ValueError("Git repository is not found.") raise ValueError(f"Invalid default_dir: {default_dir}") self._default_...
The code initializes and configures directory-related attributes in a data class. It sets up `_default_dir`, `_search_dir_list`, and `_non_dot_dir_list` using setter methods, ensuring proper directory structure configuration post-object creation.
def __post_init__(self) -> None: """Post initialization.""" self._default_dir: Path self._search_dir_list: list[Path] self._non_dot_dir_list: list[Path] self.set_default_dir(self.default_dir) self.set_search_dir_list(self.search_dir_list) self.set_non_dot_dir_list...
def _send(self, msg): """ Send something (anything) to the IRC server. """ print('Sending: %s\r\n' % msg) self.sock.send(('%s\r\n' % msg).encode()) def on_connect(self): """ Called once we have connected to and identified with the server. Mainly joins the ...
This code parses an IRC message line by extracting the command and prefix, then delegates processing to specific handlers based on the command, such as handling nickname conflicts, connection events, name lists, pings, errors, kicks, joins, and private messages.
def parse(self, line): if not line: # empty line; this should throw up an error. return line = line.strip('\r\n') tokens = line.split(' ') if tokens[0].startswith(':'): prefix = tokens.pop(0)[1:].strip(':') else: prefix = '' ...
def get_forum_and_reviews(filename): with open(filename, 'r') as f: obj = json.load(f) return obj['forums'], obj['reviews'] def basov_original(review_text): sentences = get_sentence_lists(review_text) edges = [] for sentence in sentences: selected_words = [w for w in sentence if w not in STOPWORDS] ...
The main task of the code is to process reviews from a conference (e.g., ICLR 2019) by analyzing text using two methods: `basov_original` and `basov_sentence`. It prints the most frequent terms/phrases (edges and sentences) from each review, stopping at the first occurrence of a frequency count equal to 1. The code use...
def main(): forum_map, reviews = get_forum_and_reviews('iclr2019_reviews.json') for review_id, review_text in tqdm.tqdm(reviews.items()): b_edges = basov_original(review_text) b_sentence = basov_sentence(review_text) print("ORIGINAL") for k, v in b_edges.most_common(): if v == 1: break...
def get_action(self, observation, evaluation=False): if observation.ndim == 1: observation = observation[None] # add the batch dimension try: x = torch.from_numpy(observation).float().to(self.device) except: x = observation action_dist, _ = self.policy.forward(x) ...
The main task of the code is to perform a single training iteration for a reinforcement learning agent. It interacts with the environment, collects experiences, updates the policy when sufficient data is accumulated, and adjusts the policy's exploration parameter (standard deviation) based on the episode ratio. The fun...
def train_iteration(self,ratio_of_episodes): # Run actual training reward_sum, episode_length, num_updates = 0, 0, 0 done = False # Reset the environment and observe the initial state # observation, _ = self.env.reset(seed=self.seed) observation, _ = self.env.r...
def merge(dict1, dict2): for k, v in dict2.items(): if k in dict1: _v = dict1[k] if isinstance(_v, dict) or isinstance(_v, Dict): merge(_v, v) else: dict1[k] = v else: dict1[k] = v def save(self, report=True): if...
This function updates a nested log structure by processing input heads and keyword arguments. It navigates through hierarchical Dicts, creates new entries if needed, merges provided data into the log, and optionally saves changes. The core task is to dynamically update a structured log with specified IDs, heads, and pa...
def update(self, *heads, ids=None, save=False, **kwargs): if ids is None: if self.new_log is None: return self.update(*heads, ids=self.log_id, save=save, **kwargs) else: log = self.new_log else: if self.change is None: s...
def make_boards(board_data): """ Take the board data and compose into 5x5 arrays """ # [[''], ['22 13 17 11 0'], [' 8 2 23 4 24'], ['21 9 14 16 7'], [' 6 10 3 18 5'], [' 1 12 20 15 19'], [''], [' 3 15 0 2 22'], [' 9 18 13 17 5'], ['19 8 7 25 23'], ['20 11 10 24 4'], ['14 21 16 12 6'], ['']...
The code simulates a Bingo game by parsing input numbers and boards, marking numbers on boards, tracking winning boards, and calculating the score of the last winning board. It processes input data, creates boards, iterates through numbers to mark them, identifies the final winning board, and computes its score using t...
def play(input): numbers, *board_data = input numbers = numbers.split(",") make_boards(board_data) print("boards: 🍌") print(boards) for count, number in enumerate(numbers): mark_boards(number) winning_board_idx, winning_num = winning_boards[-1] calc_score(boards[int(winning_boar...
def get_accuracy(y_pred, y_true): """Calculate the accuracy of the predicted labels. y_pred: list predicted labels y_true: list of corresponding true labels """ true_pos, false_pos, true_neg, false_neg = get_confusion_matrix(y_pred, y_true) if true_pos + false_pos + true_neg + false_neg == 0: ...
The code defines a function `evaluate` that calculates and prints precision, recall, F-score, and accuracy by comparing predicted labels (`y_pred`) with true labels (`y_true`), using helper functions for metric computations. It formats results as percentages with four decimal places for readability.
def evaluate(y_pred, y_true): """Calculate precision, recall, and f-score of the predicted labels and print out the results. y_pred: list predicted labels y_true: list of corresponding true labels """ accuracy = get_accuracy(y_pred, y_true) precision = get_precision(y_pred, y_true) recal...
def load_file(data_file): """Load in the words and labels from the given file.""" words = [] labels = [] with open(data_file, 'rt', encoding="utf8") as f: i = 0 for line in f: if i > 0: line_split = line[:-1].split("\t") words.append(line_split...
The code trains and evaluates multiple machine learning classifiers (Naive Bayes, Logistic Regression, Random Forest, SVM, Decision Tree) on text data using features like word length, frequency, syllables, and synsets. It assesses model performance on training and development datasets, with specific error analysis for ...
def my_classifier(training_file, development_file, counts): """Train a classifier using length, frequency, syllables, and synsets features.""" words_train, labels_train = load_file(training_file) words_dev, labels_dev = load_file(development_file) models = [] models.append(('Naive Bayes', GaussianN...
def load_file(data_file): """Load in the words and labels from the given file.""" words = [] labels = [] with open(data_file, 'rt', encoding="utf8") as f: i = 0 for line in f: if i > 0: line_split = line[:-1].split("\t") words.append(line_split...
The main task of the code is to train an SVM classifier by combining training and development data, extract features using provided counts, test the model on the test file, and save predicted labels. It loads data, merges training/development sets, trains the SVM with features, applies the model to test data, and outpu...
def my_best_classifier(training_file, development_file, test_file, counts): """Train a SVM classifier using combined training and development file and testing on test file.""" # Load training and development data words_train, labels_train = load_file(training_file) words_dev, labels_dev = load_file(deve...
def naive_bayes(training_file, development_file, counts): """Train a Naive Bayes classifier using length and frequency features. Print out evaluation results on the training and development data. """ words_train, labels_train = load_file(training_file) words_dev, labels_dev = load_file(developme...
The code defines a function `classifiers` that runs three machine learning models—Naive Bayes, Logistic Regression, and a custom classifier—on provided training and development datasets. It uses a `counts` parameter, likely containing feature statistics, to train and evaluate each model. The function prints headers for...
def classifiers(training_file, development_file, counts): print("\n========== Classifiers ===========\n") print("Naive Bayes") print("-----------") naive_bayes(training_file, development_file, counts) print("\nLogistic Regression") print("-----------") logistic_regression(training_file, de...
def tree_construction(args): char = args.pop() node = Node(char) if char == "-": node.push_left(tree_construction(args)) elif operator(char): node.push_left(tree_construction(args)) node.push_right(tree_construction(args)) return node def operator(char): return char in ...
This code converts a logical formula into conjunctive normal form (CNF), then uses the MiniSAT solver to check its validity. It processes input arguments, constructs a syntax tree, eliminates implications and negations, outputs the CNF formula, writes it to a file in DIMACS format, and determines validity based on the ...
def main(): args = sys.argv[1] args = args.replace(" ", "") args = list(args) args.reverse() root = Node(args.pop()) if root.char == "-": root.push_left(tree_construction(args)) elif operator(root.char): root.push_left(tree_construction(args)) root.push_right(tree_c...
def __post(self, path, parameter_json=None, files= None): result_json = {} if not self.__token: if not self.__get_token(): raise src_missing_token('Missing token') try: headers = {"Accept": "application/json", 'Authorization': f'to...
This function creates a new user with configurable details like username, password, name, contact info, and login method. It validates PKI login rules, processes rights as a list, and assigns groups/roles if provided. The user is created via a POST request, and group/role assignments are made sequentially. If any step ...
def create_user(self, username, password, firstName=None, lastName=None, phone=None, email=None, loginMethod=1, pkiFilterRule=None, rights=None, fixedVpnAddress=None, groupId=None, roleId=None): """ Create a new user Args: username (String): User name password (String): ...
def __get(self, path): result_json = {} if not self.__token: if not self.__get_token(): raise src_missing_token('Missing token') try: headers = {"Accept": "application/json", 'Authorization': f'token {self.__token}'} re...
The main task of the code is to retrieve detailed information about a specific user by fetching data such as activation status, groups, and roles, then compiling them into a JSON object. The function uses the provided user_id to get base details, checks activation status, and appends associated groups and roles if avai...
def __get_user_details(self, user_id): """ Get details about a specific user Args: user_id (Integer): Id of a specific user Returns: Json: Result """ temp_user = self.__get(GET_USER_DETAIL.format(user_id))['data'] temp_user['user_id'] = u...
def __get_token(self): """ Retrieve token from server Returns: Json: Result """ json = {'username': self.username, 'password':self.password} path = TOKEN_PATH request_result = None try: headers = {"Accept": "application/json"} ...
This code initializes a connection to the SINEMA RC Server by configuring communication parameters, handling authentication, disabling SSL certificate verification if specified, creating a session, retrieving an API token, and fetching system information like DNS and IP addresses.
def __init__(self, address, port=443, username='admin', password='admin', timeout=500, verify_certificate=False): """Create new object for communication to SINEMA RC Server. API License is needed Args: address (String): IP-Address or DNS name of the Server port (int, optional): ...
def create_device_subnet(self, deviceId, name, ipAddress, subnetMask, natMode, virtualIp=None): """ Assign a subnet to a device Args: deviceId (integer): Id of the device name (string): Name of the subnet ipAddress (string): IPv4-Address of the subnet ...
This method assigns a subnet to a specified device by creating a subnet with parameters like IP address, subnet mask, and NAT mode. It checks if the operation succeeds, raises an error if not, and then associates the subnet with a group or node if those parameters are provided. The main task is to configure device subn...
def __assign_device_subnet(self, subnet_parameter, device_id): """ Assign a subnet to a device Args: subnet_parameter (Json): Json with subnet parameter device_id (Integer): Device id Raises: src_wrong_usage: Raise error if server doesn't allow this ...
def __post(self, path, parameter_json=None, files= None): result_json = {} if not self.__token: if not self.__get_token(): raise src_missing_token('Missing token') try: headers = {"Accept": "application/json", 'Authorization': f'to...
The main task of the code is to create a new VPN device with configurable parameters, validate input types, map them to numeric values, send a POST request to create the device, and optionally configure OpenVPN settings, groups, and subnets. It returns device details and CLI commands if requested, handling errors for i...
def create_device(self, name, password, type, connectionType, vendor=None, smsGatewayProvider=None, gsmNumber=None, senderId=None, location=None, comment=None, fixedVpnAddress=None, defaultGateway=None, openvpn_parameter=None, groupId=None, subnet_parameter=None, get_running_cli=False): ""...
def fit_two_gaussian(ch,spec,guess=[5000,112,6,900,123,12],lower=77,upper=185): errfunc = lambda p, x, y, y_err: (two_gaussian(x, *p) - y)/y_err lower = int(lower) upper = int(upper) spec_err = np.sqrt(spec) spec_err[spec_err==0]=1 p_out = optimize.leastsq(errfunc, guess[:], args=(ch[lower:upper...
The code fits the Fe Ka X-ray peak in a given spectrum using two Gaussian functions, estimates the Full Width at Half Maximum (FWHM) of the peak, and returns the FWHM value along with its uncertainty. It identifies the peak position, performs the Gaussian fit, converts channel positions to energy, calculates the FWHM u...
def fit_fe_spectrum(ch,spec): # expects SoLEXS binning and Fe Ka in range of 60 to 120 ene_peak = [5.89e3,6.49e3] fe_ka_guess_ch = ch[np.argmax(spec[60:120]) + 60] fe_ka_guess_a = np.max(spec[60:120]) fit_results,err_fit_results = fit_two_gaussian(ch,spec,guess=[fe_ka_guess_a,fe_ka_guess_ch,3,fe_ka_gue...
def _draw_buttons(self): for button in self.buttons: button.draw() def _draw_maze(self): y = self.maze_start_y for line in self.maze.grid: x = self.maze_start_x for tile in line: if tile == '#': rect = pygame.Rect(x, y, 20,...
The main task of the code is to render visual elements by calling methods that draw buttons, mazes, messages, paths, and objects, likely for a graphical interface or game scene.
def _draw(self): self._draw_buttons() self._draw_maze() self._draw_message() self._draw_paths() self._draw_objects()
def _is_valid(self, position: tuple) -> bool: ''' Returns True if a position is within the maze boundaries and not a wall ''' if position[0] < self.maze_start_x or position[0] > self.maze_end_x: return False if position[1] < self.maze_start_y or position[1] >...
This code manages a main event loop for a maze-solving application, updating the UI with incremental progress, handling user input for setting start/goal positions and buttons, and rendering the final path once solving completes, while maintaining a 30 FPS display update.
def _display(self): ''' Main event loop ''' run = True while run: self.window.fill(BLACK) # Incrementally add search progress with any frame tick so it doesn't overwhelm the user if self.progress_queue: if len(self.progress) !=...
def mean(self): """Calculates mean of self.poly""" mu = self.moment(order=1) return sympy.simplify(mu) def var(self): """Calculates variance of self.poly""" var = self.moment(order=2) - (self.moment(order=1) ** 2) return sympy.simplify(var) def moment(self, order: int): ...
The code calculates the skewness of a polynomial distribution using the third moment, mean, and variance. It applies the formula: (third moment - 3*mean*variance - mean³) / (variance^(3/2)), then simplifies the result symbolically using Sympy.
def skew(self): """Calculates skewness of self.poly""" mean = self.mean() var = self.var() skew = (self.moment(order=3) - (3 * mean * var) - (mean ** 3)) / (sympy.sqrt(var) ** 3) return sympy.simplify(skew)