content
stringlengths
22
815k
id
int64
0
4.91M
def render_template(template, defaults): """Render script template to string""" if not isinstance(template, Template): filename = template.format(**defaults) template = Template(filename=filename) return template.format(**defaults)
15,500
def get_hash(string): """ FNV1a hash algo. Generates a (signed) 64-bit FNV1a hash. See http://www.isthe.com/chongo/tech/comp/fnv/index.html for math-y details. """ encoded_trimmed_string = string.strip().encode('utf8') assert isinstance(encoded_trimmed_string, bytes) i64 = FNV1_64A_INIT ...
15,501
def load_seq_sizes(def_vars): """Load sequence sizes.""" seq1_sizes, seq2_sizes = {}, {} if def_vars.get("SEQ1_LEN"): seq1_sizes = read_chrom_sizes(def_vars.get("SEQ1_LEN")) elif def_vars.get("SEQ1_CTGLEN"): seq1_sizes = read_chrom_sizes(def_vars.get("SEQ1_CTGLEN")) else: cle...
15,502
def extract_source(source_path: Path) -> (Path, Optional[str]): """Extract the source archive, return the extracted path and optionally the commit hash stored inside.""" extracted_path = source_path.with_name(source_path.stem) commit_hash = None # Determine the source archive type before extracting it ...
15,503
def correct_distribution (lines): """ Balance the distribution of angles Define an ideal value of samples per bin. If the count per bin is greated than the the average, then randomly remove the items only for that bin """ angles = np.float32(np.array(lines)[:, 3]) num_bins = 21 hist...
15,504
def numDockedWindows(): """ Determine the amount of docked windows (i.e. visible on all desktops). return - Number of windows. """ stdout = runCommand(COMMAND_LIST_WINDOWS) result = -2 # first two windows are actually not windows and don't count for i in iter(stdout.splitlines()): if i...
15,505
def get_logger(name, level='DEBUG', ext_logger=None): """ retrieves a logger with colored logs installed Args: name: string used to describe logger names level: log level to use ext_logger: External logger object, if not create a new one. Returns: log: instance of a log...
15,506
def train(): """ Configuring, training, evaluating and making predictions on gathered data within our model rules. """ # retrieving processed data, ready to pipe into Tensorflow Estimators genomes, groups = _preprocess_data(db.all()) # first 1000 genomes/groups for training train_x = {'geno...
15,507
def get_value(hive, key_name, value_name): """ >>> get_value( ... HKEY_LOCAL_MACHINE, ... "SOFTWARE/Microsoft/Windows/CurrentVersion/Explorer/StartMenu", ... "Type") [1, 'group'] >>> get_value( ... HKEY_CURRENT_USER, ... "Software\\Microsoft\\Windows\\CurrentVersion\\...
15,508
def addScore(appId: str, scoreName: str, value: int, userId: str, checksum: str=Header(None), db=Depends(Database)): """ Add user score to leaderboard """ validateParameters(appId=appId, scoreName=scoreName, value=value, userId=userId, checksum=checksum) with db.trans...
15,509
def has_affect(builtin: str) -> bool: """Return `True` if the given builtin can affect accessed attributes.""" if builtin not in PYTHON_BUILTINS: raise ValueError(f"'{builtin}' is not a Python builtin") return builtin in PYTHON_ATTR_BUILTINS
15,510
def get_plot_for_different_k_values(similarity, model_name): """ This function plots points after applying a cluster method for k=3,4,5,6. Furthermore prints silhouette score for each k :param similarity: Contains our dataset (The similarity of RIPE monitors) :return: A list containing silhouette score ...
15,511
def main(): """Profiles various versions of LCA.""" nshort = 6 tshort = 2 nmed = 3 tmed = 6 nlong = 1 # Setup variables for inference numDict = int(2048) numBatch = int(128) dataSize = int(256) dictsIn = np.random.randn(numDict,dataSize) # LCA requires that dictiona...
15,512
def RandomBrightness(image, delta, seed=None): """Adjust the brightness of RGB or Grayscale images. Tips: delta extreme value in the interval [-1, 1], >1 to white, <-1 to black. a suitable interval is [-0.5, 0.5]. 0 means pixel value no change. Args: image: Tensor or arr...
15,513
async def volume(ctx, volume: float): """Sets the volume of the bot, (0-2).""" server = ctx.message.server.id players[server].volume = volume
15,514
def fetch_rfc(number): """ RFC fetcher >>> fetch_rfc("1234") (u'https://tools.ietf.org/html/rfc1234', 'Tunneling IPX traffic through IP networks') """ url = "https://tools.ietf.org/html/rfc%s" % (number, ) xml, dummy_response = fetch_and_parse_xml(url) title = xml.xpath('string(//meta[@...
15,515
def samefile(path1, path2, user=None): """ Return :obj:`True` if both path arguments refer to the same path. """ def tr(p): return abspath(normpath(realpath(p)), user=user) return tr(path1) == tr(path2)
15,516
def get_list_coord(G, o, d): """Get the list of intermediate coordinates between nodes o and d (inclusive). Arguments: G {networkx} -- Graph o {int} -- origin id d {int} -- destination id Returns: list -- E.g.: [(x1, y1), (x2, y2)] """ edge_data = G.get_edge_da...
15,517
def todays_date(): """ Returns today's date in YYYYMMDD format. """ now = datetime.datetime.now() date_str = "{0}{1}{2}".format(now.year, now.strftime('%m').zfill(2), now.strftime('%d').zfill(2)) return date_str
15,518
def kl_divergence(p_probs, q_probs): """"KL (p || q)""" kl_div = p_probs * np.log(p_probs / q_probs) return np.sum(kl_div[np.isfinite(kl_div)])
15,519
def _dbize(ec, org, rxn, cof, all_smiles): """Place data into MongoDB.""" #Connect to mongodb. client = MongoClient() db = client.BrendaDB ec_collection = db.ec_pages rxn_collection = db.rxn_pages cpd_collection = db.cpd_pages #Build dictionary of reactions and organisms r_o_dict = {} for k,...
15,520
def colors_to_main(colors, main_colors): """ Mapping image colors to main colors and count pixels :param: colors: all colors in image :param: main_colors: input main colors (blue, green, yellow, purple, pink, red, orange, brown, silver, white, gray, black) :return: colors """ ...
15,521
def await_lock(lock): """ Wait for a lock without blocking the main (Qt) thread. See await_future() for more details. """ elapsed = 0 # total time elapsed waiting for the lock interval = 0.02 # the interval (in seconds) between acquire attempts timeout = 60.0 # the total time...
15,522
def get_arg_value_wrapper( decorator_func: t.Callable[[ArgValGetter], Decorator], name_or_pos: Argument, func: t.Callable[[t.Any], t.Any] = None, ) -> Decorator: """ Call `decorator_func` with the value of the arg at the given name/position. `decorator_func` must accept a callable as a paramete...
15,523
def delete_index(c, core, server=DEFAULT_SOLR_URL): """ Delete index data. """ client = SolrClient(core=core, base_url=server) client.delete_all_index()
15,524
def yaml_request(request: quart.local.LocalProxy) -> bool: """Given a request, return True if it contains a YAML request body""" return request.content_type in ( "text/vnd.yaml", "text/yaml", "text/x-yaml", "application/vnd.yaml", "application/x-yaml", "applicatio...
15,525
def validatePath(path): """ Returns the validated path. :param path: string or unicode - Path to format .. note:: Only useful if you are coding for both Linux and Windows for fixing slash problems. e.g. Corrects 'Z://something' -> 'Z:' Example:: fpath = xbmc.validatePath(somepath...
15,526
def fancy_scatter(x, y, values=None, bins=60, names=['x', 'y'], marg=False, marg_perc=15, nbins=[3, 3]): """ Scatter plot of paramters with number desnity contours overlaid. Marginalized 1D distributions also plotted. Make sure that the data is appropriately cleaned before using this ...
15,527
def add_dingbot(dingbot_id=None, *args, **kwargs): """Add a dingbot config with interactive input""" home = os.path.expanduser('~') configfp = os.path.join(home, '.easydingbot') if os.path.exists(configfp): with open(configfp) as f: config_dict = json.load(f) if 'default' in ...
15,528
def get_raster_availability(layer, bbox=None): """retrieve metadata for raster tiles that cover the given bounding box for the specified data layer. Parameters ---------- layer : str dataset layer name. (see get_available_layers for list) bbox : (sequence of float|str) bounding ...
15,529
def absolute_error(observed, modeled): """Calculate the absolute error between two arrays. :param observed: Array of observed data :type observed: numpy.ndarray :param modeled: Array of modeled data :type modeled: numpy.ndarray :rtype: numpy.ndarray """ error = observed - modeled r...
15,530
def prepare_tempdir(suffix: Optional[str] = None) -> str: """Preapres a temprary directory, and returns the path to it. f"_{version}" will be used as the suffix of this directory, if provided. """ suffix = "_" + suffix if suffix else None dir_str = mkdtemp(suffix, "warsawgtfs_") return dir_str
15,531
def parse_number(string): """ Retrieve a number from the string. Parameters ---------- string : str the string to parse Returns ------- number : float the number contained in the string """ num_str = string.split(None, 1)[0] number = float(num_str) retur...
15,532
def catch_exception(func): """ Decorator that catches exception and exits the code if needed """ def exit_if_failed(*args, **kwargs): try: result = func(*args, **kwargs) except (NonZeroExitCodeException, GitLogParsingException) as exception: Logger.error(exception...
15,533
def _coord_byval(coord): """ Turns a COORD object into a c_long. This will cause it to be passed by value instead of by reference. (That is what I think at least.) When runing ``ptipython`` is run (only with IPython), we often got the following error:: Error in 'SetConsoleCursorPosition'. ...
15,534
def create_tables(cur, conn): """ Creates all tables in Redshift. cur and conn and the curson and connection from the psycopg2 API to the redshift DB. """ for q in sql_q.create_table_queries: print('executing query: {}'.format(q)) cur.execute(q) conn.commit()
15,535
def _list_flows(output_format='dict', **kwargs) -> Union[Dict, pd.DataFrame]: """ Perform the api call that return a list of all flows. Parameters ---------- output_format: str, optional (default='dict') The parameter decides the format of the output. - If 'dict' the output is a dic...
15,536
def main(argv): """Entry point.""" try: argv = FLAGS(argv) except gflags.FlagsError, e: print '{}\nUsage: {} ARGS\n{}'.format(e, sys.argv[0], FLAGS) sys.exit(1) with open(FLAGS.definition_file, 'r') as def_file: if FLAGS.struct_file: def_file.seek(0) output = StructBasedOutput(FLAGS...
15,537
def _take_many_sparse_from_tensors_map(sparse_map_op, sparse_handles, rank=None, name=None): """Read `SparseTensors` from a `SparseTensorsMap` and concatenate them. The input `sparse_handles` must b...
15,538
def rts_smooth(kalman_filter, state_count=None): """ Compute the Rauch-Tung-Striebel smoothed state estimates and estimate covariances for a Kalman filter. Args: kalman_filter (KalmanFilter): Filter whose smoothed states should be returned state_count (int or None): Number o...
15,539
def play_episode(args, sess, env, qnet, e): """ Actually plays a single game and performs updates once we have enough experiences. :param args: parser.parse_args :param sess: tf.Session() :param env: gym.make() :param qnet: class which holds the NN to play and update. :param e: chance of...
15,540
def to_categorical(y, num_columns): """Returns one-hot encoded Variable""" y_cat = np.zeros((y.shape[0], num_columns)) y_cat[range(y.shape[0]), y.astype(int)] = 1.0 return Variable(FloatTensor(y_cat))
15,541
def suppress_vtk_warnings(): """A context manager to suppress VTK warnings. This is handy when trying to find something dynamically with VTK. **Example** with supress_vtk_warnings(): x = tvtk.VolumeRayCastMapper() """ try: obj = vtk.vtkObject() obj.GlobalWarningDisplay...
15,542
def npi_provider_extension(source): """ Add non empty fields in NPI Record to NPI Extension in Practitioner Profile :param source: :return: profile['extension'] {} """ extn = {} for key, value in source.items(): if isinstance(value, str): if value == "": ...
15,543
def extract_light_positions_for_rays(ray_batch, scene_info, light_pos): """Extract light positions for a batch of rays. Args: ray_batch: [R, M] tf.float32. scene_info: Dict. light_pos: Light position. Returns: light_positions: [R, 3] tf.float32. """ ray_sids = extract_slice_from_ray_batch( ...
15,544
def user_choice(): """ takes input from the user and performs the tasks accordingly """ userchoice = """ Enter 1 for solving available problems. Enter 2 for giving your own sudoku problem. ...
15,545
def cdf(x, c, loc=0, scale=1): """Return the cdf :param x: :type x: :param c: :type c: :param loc: :type loc: :param scale: :type scale: :return: :rtype: """ x = (x - loc) / scale try: c = round(c, 15) x = np.log(1 - c * x) / c return 1.0 /...
15,546
def solve_eq(preswet, func): """Solve the peicewise-linear stability of a parcel INPUTS: variables from the most ascent of a parcel preswet: pressure func : piecewise linear function to solve (tw-te) OUTPUTS: solutions: zeros of the function (tw-te) stability: indication of the stability...
15,547
def load_dict(file_name): """ Reads JSON or YAML file into a dictionary """ if file_name.lower().endswith(".json"): with open(file_name) as _f: return json.load(_f) with open(file_name) as _f: return yaml.full_load(_f)
15,548
def test_two(caplog, no_job_dirs): """Test with two artifacts in one job. :param caplog: pytest extension fixture. :param str no_job_dirs: Test with --no-job-dirs. """ jobs_artifacts = [('spfxkimxcj6faq57', 'artifacts.py', 12479), ('spfxkimxcj6faq57', 'README.rst', 1270)] config = dict(always_j...
15,549
def get_next_number(num, proxies='', auth=''): """ Returns the next number in the chain """ url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php' res = requests.get('{0}?nothing={1}'.format(url, num), proxies=proxies, auth=auth) dat = res.content pattern = re.compile(r'next nothing is (\d+)') match = ...
15,550
def gzip_str(g_str): """ Transform string to GZIP coding Args: g_str (str): string of data Returns: GZIP bytes data """ compressed_str = io.BytesIO() with gzip.GzipFile(fileobj=compressed_str, mode="w") as file_out: file_out.write((json.dumps(g_str).encode())) b...
15,551
def test_cli_argparser_raises_no_exceptions(): """An invalid keyword to ArgumentParser was causing an exception in Python 3.""" with pytest.raises(SystemExit): parse_args(None)
15,552
def get_summoner_spells(): """ https://developer.riotgames.com/api/methods#!/968/3327 Returns: SummonerSpellList: all the summoner spells """ request = "{version}/summoner-spells".format(version=cassiopeia.dto.requests.api_versions["staticdata"]) params = {"tags": "all"} if _locale...
15,553
def run_expr(expr, vranges): """ Evaluate expr for every value of free variables given by vranges and return the tensor of results. TODO(yzhliu): move to utils """ def _compute_body(*us): vmap = {v: u + r.min for (v, r), u in zip(vranges.items(), us)} return tir.stmt_functor.substitu...
15,554
def test_update_quotas_1st_time_using_name(host): """Configurate tenant quotas and verify it works properly at the first time""" update_quotas(host, name=tenant, instances=12, cores=10, ram=128) verify_updated_quotas(host, name=tenant, instances=12, cores=10, ram=128)
15,555
def cache_cleanup(dry_run: bool = False) -> list: """Perform cleanup in the scraper cache directory. Returns list of deleted directories. :param dry_run: in case of value True - DRY RUN MODE is on and no cleanup will be done. :return: list of deleted directories """ log.debug("cache_cleanup(): clean...
15,556
def solve_covariance(u) -> np.ndarray: """Solve covariance matrix from moments Parameters ---------- u : List[np.ndarray] List of moments as defined by the ``get_moments()`` method call of a BayesPy node object. """ cov = u[1] - np.outer(u[0], u[0]) return cov if cov.shape ...
15,557
def graph_multiple(input_list): """visualize measured height""" fig_stem = "__".join([pathlib.Path(i).stem.strip("_height")[:10] for i in input_list]) fig_name = pathlib.Path(pathlib.Path.cwd() / "cv2" / "{0}.png".format(fig_stem)) pyplot.rcParams["xtick.direction"] = "in" pyplot.rcParams["ytick.direction"] ...
15,558
def interact_ids(*columns: Array) -> Array: """Create interactions of ID columns.""" interacted = columns[0].flatten().astype(np.object) if len(columns) > 1: interacted[:] = list(zip(*columns)) return interacted
15,559
def _get_depthwise(): """ We ask the user to input a value for depthwise. Depthwise is an integer hyperparameter that is used in the mobilenet-like model. Please refer to famous_cnn submodule or to mobilenets paper # Default: 1 """ depth = '' while depth not in ['avg', 'max']: ...
15,560
def LoadPartitionConfig(filename): """Loads a partition tables configuration file into a Python object. Args: filename: Filename to load into object Returns: Object containing disk layout configuration """ valid_keys = set(('_comment', 'metadata', 'layouts', 'parent')) valid_layout_keys = set(( ...
15,561
def get_own(): """Returns the instance on which the caller is running. Returns a boto.ec2.instance.Instance object augmented by tag attributes. IMPORTANT: This method will raise an exception if the network fails. Don't forget to catch it early because we must recover from this, fast. Also, it will...
15,562
def create_report( name: str, description: str, published: datetime, author: Identity, object_refs: List[_DomainObject], external_references: List[ExternalReference], object_marking_refs: List[MarkingDefinition], report_status: int, report_type: str, confidence_level: int, la...
15,563
def get_curve_points( road: Road, center: np.ndarray, road_end: np.ndarray, placement_offset: float, is_end: bool, ) -> list[np.ndarray]: """ :param road: road segment :param center: road intersection point :param road_end: end point of the road segment :param placement_offset: o...
15,564
def default_inputs_folder_at_judge(receiver): """ When a receiver is added to a task and `receiver.send_to_judge` is checked, this function will be used to automatically set the name of the folder with inputs at judge server. When this function is called SubmitReceiver object is created but is not saved...
15,565
def remove_extension(string): """ Removes the extention from a string, as well as the directories. This function may fail if more than one . is in the file, such as ".tar.gz" Args: string: (string): either a path or a filename that for a specific file, with extension. (e.g. /usr/di...
15,566
def _theme_static(path): """ Serve arbitrary files. """ return static_app.static(path, 'theme')
15,567
def create_link(link: schemas.Link, db: Session = Depends(get_db)): """Create link """ # Check if the target already exists db_link = crud.get_link_by_target(db=db, target=link.target) if db_link: raise HTTPException(status_code=400, detail="link already registered") response = crud.cre...
15,568
def encode_rsa_public_key(key): """ Encode an RSA public key into PKCS#1 DER-encoded format. :param PublicKey key: RSA public key :rtype: bytes """ return RSAPublicKey({ 'modulus': int.from_bytes(key[Attribute.MODULUS], byteorder='big'), 'public_exponent': int.from_bytes(key[Att...
15,569
def is_block_valid(new_block, old_block): """ simple verify if the block is valid. """ if old_block["Index"] + 1 != new_block["Index"]: return False if old_block["Hash"] != new_block["PrevHash"]: return False if caculate_hash(new_block) != new_block["Hash"]: ret...
15,570
def add_get_parameter(url, key, value): """ Utility method to add an HTTP request parameter to a GET request """ if '?' in url: return url + "&%s" % urllib.urlencode([(key, value)]) else: return url + "?%s" % urllib.urlencode([(key, value)])
15,571
def get_simple_match(text): """Returns a word instance in the dictionary, selected by a simplified String match""" # Try to find a matching word try: result = word.get(word.normalized_text == text) return result except peewee.DoesNotExist: return None
15,572
def validate_value_is_unique(attribute: models.Attribute, value: models.AttributeValue): """Check if the attribute value is unique within the attribute it belongs to.""" duplicated_values = attribute.values.exclude(pk=value.pk).filter(slug=value.slug) if duplicated_values.exists(): raise ValidationE...
15,573
async def test_in_zone_works_for_passive_zones(hass): """Test working in passive zones.""" latitude = 32.880600 longitude = -117.237561 assert await setup.async_setup_component( hass, zone.DOMAIN, { "zone": [ { "name": "Passive Zone...
15,574
def ipv_plot_df(points_df, sample_frac=1, marker='circle_2d', size=0.2, **kwargs): """Plot vertices in a dataframe using ipyvolume.""" if sample_frac < 1: xyz = random_sample(points_df, len(points_df), sample_frac) else: xyz = dict(x=points_df['x'].values, y=points_df['y'].values, z=points_d...
15,575
def exec_command_stdout(*command_args, **kwargs): """ Capture and return the standard output of the command specified by the passed positional arguments, optionally configured by the passed keyword arguments. Unlike the legacy `exec_command()` and `exec_command_all()` functions, this modern fun...
15,576
def admin_login(): """ This function is used to show the admin login page :return: admin_login.html """ return render_template("admin_login.html")
15,577
def input_file_location(message): """ This function performs basic quality control of user input. It calls for a filepath with a pre-specified message. The function then checks if the given filepath leads to an actual existing file. If no file exists at the given location, the function will ...
15,578
def delete_tag( access_key: str, url: str, owner: str, dataset: str, *, tag: str, ) -> None: """Execute the OpenAPI `DELETE /v2/datasets/{owner}/{dataset}/tags/{tag}`. Arguments: access_key: User's access key. url: The URL of the graviti website. owner: The owner...
15,579
def test_copy_globals(): """ Checks that a restored function does not refer to the same globals dictionary, but a copy of it. Therefore it cannot reassign global values. """ global_var_writer(10) assert global_var_reader() == 10 assert global_var == 10 reader = Function.from_object(glo...
15,580
def check_dfs(): """ This function checks if the dfs is running """ process = subprocess.Popen("jps", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = process.communicate() results = str(stdout) flag = 0 if results.find("NameNode") > -1: flag += 1 ...
15,581
def create_contact(): """ Get a contact form submission """ data = request.get_json(force=True) contact = ContactDAO.create(**data) return jsonify(contact.to_dict())
15,582
def smartSum(x, key, value): """ create a new page in x if key is not a page of x otherwise add value to x[key] """ if key not in list(x.keys()): x[key] = value else: x[key] += value
15,583
def make_my_tuple_video(LOGGER, image, width, height, frames, codec, metric, target, subsampling, param, uuid=None): """ make unique tuple for unique directory, primary key in DB, etc. """ (filepath, tempfilename) = os.path.split(image) filename, extension = os.path.splitext(tempfilename) my_tuple =...
15,584
def separate_sets( hand: DefaultDict[int, int], huro_count: int, koutsu_first: bool = True ) -> Tuple[List[Tile], List[List[Tile]], Tile]: """Helper function for seperating player's remaining hands into sets. It should either be 14, 11, 8, 5, or 2 tiles. The arg koutsu_first would change the priority fo...
15,585
def units(legal_codes): """ Return sorted list of the unique units for the given dictionaries representing legal_codes """ return sorted(set(lc["unit"] for lc in legal_codes))
15,586
def resize_terms(terms1, terms2, patterns_to_pgS, use_inv): """ Resize the terms to ensure that the probabilities are the same on both sides. This is necessary to maintain the null hypothesis that D = 0 under no introgression. Inputs: terms1 --- a set of patterns to count and add to each other to de...
15,587
def get_network_list(): """Get a list of networks. --- tags: - network """ return jsonify([ network.to_json(include_id=True) for network in manager.cu_list_networks() ])
15,588
def bfixpix(data, badmask, n=4, retdat=False): """Replace pixels flagged as nonzero in a bad-pixel mask with the average of their nearest four good neighboring pixels. :INPUTS: data : numpy array (two-dimensional) badmask : numpy array (same shape as data) :OPTIONAL_INPUTS: n : int ...
15,589
def handle_create_cfn_stack(stack_name: str, url: str, s3_bucket: str, cfn_client, runner_role: str = ''): """ Creates a cfn stack for use in testing. Will wait until stack is finished being created to exit. :param stack_name: Name of the stack :param url: CFN Template URL ...
15,590
def less(): """ Render LESS files to CSS. """ for path in glob('%s/less/*.less' % env.static_path): filename = os.path.split(path)[-1] name = os.path.splitext(filename)[0] out_path = '%s/www/css/%s.less.css' % (env.static_path, name) try: local('node_modules/...
15,591
def parse_discount(element): """Given an HTML element, parse and return the discount.""" try: # Remove any non integer characters from the HTML element discount = re.sub("\D", "", element) except AttributeError: discount = "0" return discount
15,592
def read_files(allVCFs): """ Load all vcfs and count their number of entries """ # call exists in which files call_lookup = defaultdict(list) # total number of calls in a file file_abscnt = defaultdict(float) for vcfn in allVCFs: v = parse_vcf(vcfn) # disallow intra vcf d...
15,593
def parse_dat_file(dat_file): """ Parse a complete dat file. dat files are transposed wrt the rest of the data formats here. In addition, they only contain integer fields, so we can use np.loadtxt. First 6 columns are ignored. Note: must have a bims and info file to process completely. Para...
15,594
def test_env(monkeypatch, tmp_path): """Test that the environment variable is respected""" data_dir = tmp_path / "envpath" data_dir.mkdir() monkeypatch.setenv("PPX_DATA_DIR", str(data_dir)) ppx.set_data_dir() proj = ppx.MassiveProject(MSVID) out_path = Path(data_dir, MSVID) assert proj....
15,595
def parse_cmd_arguments(mode='split_audioset', default=False, argv=None): """Parse command-line arguments. Args: mode (str): The mode of the experiment. default (optional): If True, command-line arguments will be ignored and only the default values will be parsed. argv (opt...
15,596
def get_number_packets_start_end(trace, features): """ Gets the number of incoming & outcoming packets in the first and last 30 packets """ first = trace[:30] last = trace[-30:] packets_in, packets_out = counts_in_out_packets(first) features.append(packets_in) features.append(packets_o...
15,597
def emails(): """A strategy for generating email addresses as unicode strings. The address format is specific in :rfc:`5322#section-3.4.1`. Values shrink towards shorter local-parts and host domains. This strategy is useful for generating "user data" for tests, as mishandling of email addresses is ...
15,598
def next_whole_token( wordpiece_subtokens, initial_tokenizer, subword_tokenizer): """Greedily reconstitutes a whole token from a WordPiece list. This function assumes that the wordpiece subtokens were constructed correctly from a correctly subtokenized CuBERT tokenizer, but the sequence may be trun...
15,599