content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_selec(tab, selec_tab, name_selec='name', thresh_selec='thresh', op_selec='op', type_selec='type', sel_tag_col='sel'): """ fonction to set a select flag (column) to tab data Parameters --------------- tab: astropy table data to process selec_tab: astropy table tab of selecti...
169db78e0d32b549573cc8642fa22dbecb8c1322
660,364
def get_pairs(word): """ Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char pairs = set(pairs) ...
a2e88c2c9a74bb6715a99e99813cfde7cea8789d
660,365
def make_pure_python(obj): """ Take dict object which can include either dict or numpy scalars or Python scalars, and convert to pure Python. """ if isinstance(obj, dict): for key, val in obj.items(): obj[key] = make_pure_python(val) return obj elif hasattr(obj, 'item...
740c4d8c3bbc9a5f9a460079dd07b1d1581e8010
660,371
def app_config(app_config): """Customize application configuration.""" app_config[ 'FILES_REST_STORAGE_FACTORY'] = 'invenio_s3.s3fs_storage_factory' app_config['S3_ENDPOINT_URL'] = None app_config['S3_ACCESS_KEY_ID'] = 'test' app_config['S3_SECRECT_ACCESS_KEY'] = 'test' return app_config
af0054a6242b6ff065e726fa59813a657f5c6552
660,373
def filter_images(piclists): """ Filter the image lists to remove the "False" and "path=None" items :param piclists: A list of list of Picture_infos namedtuple :return: The same lists, but filtered """ for i, piclist in enumerate(piclists): piclist = [j for j in piclist if type(j) != boo...
2701ff1122878e7db50a47fc54de7b8fba816e92
660,374
from pathlib import Path def get_path_as_str(path: Path) -> str: """ Get the given path as a string. :param path: a Path :return: a str """ return str(path)
632188289c8f3bd679ea7d18feb69edc9f24d5cd
660,376
def _build_name_index_tuples(name, index_max): """return list of tuples [(N, 'nameN')] of the size indexMax""" def build_name(tup): return tup[1] + str(tup[0]) names = index_max * [name] names = map(build_name, enumerate(names)) return list(enumerate(names))
4d8b5b9b8ca49d0c4bc2a51abc07da0fc4b1cc16
660,378
from string import punctuation from unicodedata import category, normalize def standardize(ds): """Remove interpunctuation and whitespaces from a string.""" ss = ''.join(s for s in normalize('NFD', ''.join(ds.split())) if category(s) != 'Mn') manually = (('“', '"'), ('”', '"'), ("(TM)", "...
3eca58c98a8755985c9d39edba631c62654c86d6
660,383
from pathlib import Path def ed_append(filename, string): """ appends string to the end of the file. If the file does not exist, a new file is created with the given file name. The function returns the number of characters written to the file. :param filename: file to be manipulated :param str...
da9f9964794c55483ee0a549e810d9df9bef6567
660,387
import re def filter_data_genes(counts, filter_genes): """ Filter the input matrix of counts to keep only the genes given as input. :param counts: matrix of counts (genes as columns) :param filter_genes: list of genes to keep :return: the filtered matrix of counts """ genes_to_keep = l...
2d30aacb40e12d9dd7d3f7d1bcf7b078c9a8d6fb
660,393
def get_next_super_layer(layer_dependency_graph, super_nodes, current_layer): """ Return the immediate next super layer of current layer. :param layer_dependency_graph: dependency graph of the model :param super_nodes: list of all super nodes :param current_layer: the layer whose next super layer n...
d7a0e606c10974510d0d250d15d26537f8440494
660,396
import torch def batchify_image(input): """Promotes the input tensor (an image or a batch of images) to a 4D tensor with three channels, if it is not already. Strips alpha channels if present. """ if input.ndim == 2: input = input[None] if input.ndim == 3: input = input[None] ...
f59a0e31ecf3bc490992f6d164b59975dfe8067b
660,399
def is_position_valid(position, password): """Check if position is valid for password.""" return 0 <= position < len(password) and password[position] is None
217960f4b4e25dd4e35856787055712462d6eb10
660,403
import unicodedata def remove_diacritics(raw_text: str) -> str: """ >>> raw_text = "Montréal, über, 12.89, Mère, Françoise, noël, 889, اِس, اُس" >>> remove_diacritics(raw_text) 'Montreal, uber, 12.89, Mere, Francoise, noel, 889, اس, اس' """ nfkd_form = unicodedata.normalize("NFKD", raw_text) ...
fe80736ef58d829f4511576d94e096814cd79857
660,405
def xl_col_to_name(col, col_abs=False): """Convert a zero indexed column cell reference to a string. Args: col: The cell column. Int. col_abs: Optional flag to make the column absolute. Bool. Returns: Column style string. """ col_num = col if col_num < 0: rais...
11ebb0e82847e5a1cddeace375a5a0cc3f30bf1b
660,410
import six import re def check_if_error_message_equal(formatted_msg, unformatted_msg): """ Helper assertion for testing that a formatted error message matches the expected unformatted version of that error. """ # Replace all `{}` style substitutions with `.*` so that we can run a regex # on th...
6f6550fe899121921372ca8a0a76f1289623f052
660,412
import re def check_url_protocol(url): """Ensures a given url has the http:// protocl.""" if re.compile('http://').match(url) == None: url = 'http://' + url return url else: return url
10b7346a82a7126cef2cb7af6eab5004b3a74ed5
660,413
import re def is_doi(str): """ check if a string is a valid DOI @param str: str to check @type str: str @return: True if DOI @rtype: bool """ doi_regex = re.compile('\\b(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])\S)+)\\b') return True if doi_regex.match(str) else False
03d48d6d9fc6a6f3bd7ec48ecacb6279e76bef22
660,416
def compute_jaccard_similarity_score(x, y): """ Jaccard Similarity J (A,B) = | Intersection (A,B) | / | Union (A,B) | """ intersection_cardinality = len(set(x).intersection(set(y))) union_cardinality = len(set(x).union(set(y))) return intersection_cardinality / float(union_cardinality)
b58e2d8ede4fbbf46493cb976e15c54fd4858693
660,418
def format_polygon_line(indiviual_points): """ Given a list of coordinates [lat1, long1, lat2, long2, lat3, long3, ...], create a string with longitude latitude couples separated by commas, and enclosed in parentheses, ex: '(long1 lat1, long2 lat2, long3 lat3, ...)' :param indiviual_points: a list o...
d793c183c3222583d157689b900563c56751868d
660,422
def get_image_uri(region_name): """Return object detection algorithm image URI for the given AWS region""" account_id = { "us-east-1": "811284229777", "us-east-2": "825641698319", "us-west-2": "433757028032", "eu-west-1": "685385470294", "eu-central-1": "813361260812", ...
4e50dacf12aac8d157f094a510b7f6ec45261fb0
660,424
def removeSpacesAndTabs(data): """ Remove all tabs and spaces. >>> removeSpacesAndTabs("a Sting With Spaces") 'aStingWithSpaces' >>> removeSpacesAndTabs("a\tSting\tWith\tTabs") 'aStingWithTabs' """ return data.replace(" ", "").replace("\t", "")
6a9263990cfac06fade6c5b69b1c44f93a8f3cbf
660,425
def sort_string(text: str) -> str: """Sort string punctuation, lowercase and then uppercase.""" return ''.join(sorted([x for x in text], key=str.swapcase))
2d1094d3f620b5486ec2ac09ddb0705c1e50128f
660,426
def strip_matching(from_str, char): """Strip a char from either side of the string if it occurs on both.""" if not char: return from_str clen = len(char) if from_str.startswith(char) and from_str.endswith(char): return from_str[clen:-clen] return from_str
9e5f5340e2ffde51d4fe8ed524561c99e0a22dcd
660,430
def find_all_starts(seq): """Find the starting index of all start codons in a lowercase seq""" # Initialize array of indices of start codons starts = [] # Find index of first start codon (remember, find() returns -1 if not found) i = seq.find('atg') # Keep looking for subsequence incrementing ...
cc60a6b0622a326e6ff1b90775d138cd901cdb92
660,436
def ns_to_ms(nanos, rounding=True, decimals=3): """ Converts nanoseconds to milliseconds, with optional rounding. :param nanos: A numeric value of nano seconds :param rounding: Whether to apply rounding (default is 3 decimal places) :param decimals: The amount of decimal places to round to :ret...
fe341d092682de76124871229cd793d11a39d9c8
660,440
def decompose_valuefmt(valuefmt): """Returns a tuple of string parts extracted from valuefmt, and a tuple of format characters.""" formats = [] parts = valuefmt.split('%') i = 1 while i < len(parts): if parts[i].startswith('s') or parts[i].startswith('d'): formats.append(part...
2cdb518ad95f694f56d339f4597e1afb338aa9e5
660,442
import platform def is_linux() -> bool: """ :return: True if running on Linux. False otherwise. """ return platform.system().lower() == 'linux'
2126de6751fdaf27eab606eef54230690270e4bf
660,443
def refractive_index_broadband_vapour(sigma): """ Parameters ---------- sigma : {float, numpy.array}, unit=µm-1 vacuum wavenumber, that is the reciprocal of the vacuum wavelength Returns ------- n_ws : {float, numpy.array} refractive index for standard moist air at sea leve...
c721b8e30d3afb2d7c629baed717cd8c32c6ac45
660,444
def clean_brackets( string, brackets=(("(", ")"),), ): """Removes matching brackets from the outside of a string Only supports single-character brackets """ while len(string) > 1 and (string[0], string[-1]) in brackets: string = string[1:-1] return string
d6cb7575ec0a8f4cad4c3fa859d998bc6d483d99
660,445
def remove_sound_descriptions(subs): """ Removes phrases that are enclosed with square brackets in the subtitles, for example [KNOCKING ON DOOR] :param subs: :return: """ for sub in subs: if '[' in sub.text and ']' in sub.text: t = sub.text sub.text = t[:t.index('...
c02d9550d7320fd9478f381302515b0af4b50e32
660,449
def stringOfList(list, sep=" "): """ Convert a list of items to a string of items, separated by sep """ result = "" for it in list: result += sep + str(it) return result
bdfcc06c1f2633383c9571941c774de22ee62ae3
660,453
def get_keys_from_osm_json(osm_json): """ Obtain all keys from queried OSM results, and do not include repeated elements. Parameters ---------- osm_json : JSON Returns ------- List """ osm_keys = [] for element in osm_json['elements']: keys = list(element["tags"].k...
c07f20798c732ba3cd7615eb5e849ff4e59bf069
660,455
from typing import List def _reGlue(words: List[str]) -> str: """Helper function to turn a list of words into a string""" ret = "" for i in range(len(words)): ret += words[i] + " " ret = ret.strip() return ret
05e62307550e48fe1e7f387b4b5b618edd83e986
660,456
from typing import MutableMapping from contextlib import suppress def delete_recursive_dictionary_keys(dct_to_change: MutableMapping, list_of_keys_to_remove: list) -> MutableMapping: """ Removes the specified keys from the specified dict. Args: dct_to_change: Dictionary to modify list_of_k...
e73f19521edcbcdbb21b2ced1911aea55d5af5ca
660,458
def generate_community_tags_scores(database, community): """ This function generates the most important terms that describe a community of similar documents, alongside their pagerank and in-degree scores. """ # Get all intersecting nodes of the speficied community, # ranked by their in-degree (...
c7623fdbad3389ec5c3dbf55c6758036c7cfce03
660,460
import re def _remove_assignment_id(s): """Remove the trailing (xxxxx) from a Canvas assignment name.""" return re.sub(r" +\(\d+\)$", "", s)
766f37c0530f3bbc03a0545a30902edf888d1422
660,462
from typing import List def find_common_name_for_boxes(boxes: List[str]) -> str: """ A brute-force solution for finding two boxes where the difference in box names is limited to a single character. Returns the common characters in the box names. The algorithm just loops through the boxes and comp...
abc9600ac07074f8da5612d12155512586892ba1
660,463
import torch def f1_loss(y_true: torch.Tensor, y_pred: torch.Tensor, is_training=False) -> torch.Tensor: """ Calculate F1 score. Can work with gpu tensors FROM https://gist.github.com/SuperShinyEyes/dcc68a08ff8b615442e3bc6a9b55a354 The original implementation is written by Michal Haltuf on Kaggle. ...
8a1270992bd63e4f84eb8f8e7f0f9633ec12e744
660,464
def bounding_box(patches): """ Return the bounding box of the given patches """ mins = [float('inf'), float('inf')] maxs = [-float('inf'), -float('inf')] for patch in patches: shape = patches[patch]['shape'] min_pos = [min(shape.bbox[i], shape.bbox[i + 2]) for i in range(2)] ...
e93c01a11a69a1649e66211975e93ead079bec44
660,465
def distance_between_notes(first_note, second_note): """ returns distance between two notes, as a number of half-tones""" notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] first_index = notes.index(first_note) second_index = notes.index(second_note) distance = second_index - ...
7461e2b78a8c3eaed31ea872a64c212a0a5df9f3
660,466
def is_window_in_area(window, area): """ Checks if a window is within an area. To determine whether a window is within an area it checks if the x and y of the window are within that area. This means a window can "hang out" of an area but still be considered to be in the area. Args: win...
9bc3c841176042169221cd8cde0127a808ad0498
660,469
import re def get_year_from_cmip(filename): """ Given a file name, assuming its a cmip file, return the start and end year """ p = r'\d{6}-\d{6}\.nc' s = re.search(pattern=p, string=filename) if not s: raise ValueError("unable to match file years for {}".format(filename)) start, e...
863c404708463f04fdfea8e269c39cbded413aaa
660,471
import math def _doy_fraction(doy): """Fraction of the DOY in the year (Eq. 50) Parameters ---------- doy : scalar or array_like of shape(M, ) Day of year. Returns ------- array_like DOY fraction [radians]. """ return doy * (2.0 * math.pi / 365)
96019f7c2f132f52ad4e98b101dd2220cac93aaf
660,475
def split_grads_by_size(threshold_size, device_grads): """Break gradients into two sets according to tensor size. Args: threshold_size: int size cutoff for small vs large tensor. device_grads: List of lists of (gradient, variable) tuples. The outer list is over devices, the inner list is over indi...
2e182650be07b1ce2bfe6cc3ee4b34c9915160f7
660,477
def module_cache_path(ctx): """Returns the Clang module cache path to use for this rule.""" return ctx.genfiles_dir.path + "/_objc_module_cache"
62468fb1ea68626a86611c8b3190fa8da3390dd7
660,481
def parse_volume_bindings(volumes): """ Parse volumes into a dict. :param volumes: list of strings :return: dict """ def parse_volume(v): if ':' in v: parts = v.split(':') if len(parts) > 2: hp, cp, ro = parts[0], parts[1], parts[2] ...
34a72defb428e109ac400b6ff31681dd6e16a9c5
660,483
def _get_totals_row(slocgroup): """Returns the row for TOTALS.""" totallines = slocgroup.totallines def average(key): total = totallines(key) return total / len(slocgroup.filenamesToSlocInfos) return ['TOTALS', totallines('code'), average('codeperc'), totallines...
380dfda71574ed08f5f5c1379e352987346ca8f0
660,484
def read_relative_operator_basenames(task): """ Read list of relative operators basenames. Returns: (list) : list of relative operators basenames """ relative_operator_filename = "relative_operators.dat" # read list of unit tensors relative_operator_stream = open(relative_operator_fil...
3a558d7dfd81ef1abcb83b62ceae5c34ef17a6a1
660,485
from typing import Sequence from typing import List def averaged_knots_constrained( n: int, p: int, t: Sequence[float]) -> List[float]: """ Returns an averaged knot vector from parametrization vector `t` for a constrained B-spline. Args: n: count of control points - 1 p: degree ...
7dfd08fd8b0d332e992ca4a837b8b43516ac264b
660,486
from typing import Callable from typing import Tuple from typing import Any from typing import Dict from warnings import warn def format_errwarn(func: Callable[[], Tuple[Any, Dict, Dict]]): """ Wraps a function returning some result with dictionaries for errors and warnings, then formats those errors and ...
d8dd854ca3ce3a45c07432a51a69ff78758a3da9
660,488
def create_fold_names(model_name:str, n_splits=5) -> list: """ List comprehension that creates the folder names. Parameters ---------- `model_name` : `str`\n Model name. `n_splits` : `int`, `optional`\n Number of splits used for kfold cross validation, by default 5 Returns ...
b7aff7da2c759daa5ed5600246be3ee3073da722
660,490
import logging def parse_time_window(timewindow): """ Args: timewindow (str, optional): time window for plot. Must be in format: 'YYYY-MM-DD:YYYY-MM-DD' Returns: list:str containing starting and ending times """ return_list = [] try: parts = timewindow.split(":") ...
b1d115a7f26f34b28106043a35ceff700a638c88
660,492
def ValidJsIdentifier(x): """Returns True if x is valid javascript identifier.""" # This is just an approximation if not x: return False nodash = x.replace('_', 'a') return nodash.isalnum() and nodash[0].isalpha()
101c3f48d0d9a134e2a01f6aeb198e2122cf5519
660,493
def _SnakeToCamelString(field_name): """Change a snake_case string into a camelCase string. Args: field_name: str, the string to be transformed. Returns: str, the transformed string. """ parts = field_name.split('_') if not parts: return field_name # Handle field_name with leading '_'s by c...
4499203fb763b74c6fcc93d9d8611c6b08641fc6
660,495
def _latest_report_info_dir(bucket): """Returns a GCS URL to the latest report info for the given bucket.""" return 'gs://{0}/latest_report_info/'.format(bucket)
172fe8d1b8ad038c95b9ec9f629f59d17b5bacb7
660,499
def parse_dir(save_dir): """Parses the save directory to get only the directory (without the file name) to save the pictures to :param save_dir: save directory string :return: save directory string without the file name """ dir_list = save_dir.split('/') dir = '' if len(dir_list) == 1: ...
d40ff6ff03859654210bce5ed67d33f25e07a467
660,502
def coordinate_of_sequence(sequence): """ ___0__1__2__3__4__ 4| 1 2 3 4 5 3| 6 7 8 9 10 2| 11 12 13 14 15 1| 16 17 18 19 20 0| 21 22 23 24 25 """ y = 4 - ((sequence - 1) // 5) x = (sequence - 1) % 5 return x, y
3f6a81a9eb0a2e1fe9e4d68fd212b7914ea700be
660,505
def _mod_name_key(typ): """Return a (__module__, __name__) tuple for a type. Used as key in Formatter.deferred_printers. """ module = getattr(typ, '__module__', None) name = getattr(typ, '__name__', None) return (module, name)
6c8b63bee7e0342f1c48295123d4be2caa55f537
660,506
def normalize_query_param(query_param): """Normalize query parameter to lower case""" return query_param.lower() if query_param else None
9bb21d79b774c5d5ff735c7b2ff46739d1c9e3c8
660,510
def y_n_to_bool(str_arg): """Convert Rinnai YN to Bool""" if str_arg == "Y": return True return False
225e5948f642a07b09516ffcd9e80b675d8c3b8a
660,515
def signature_for_type_name(type_name): """Determine the JNI signature for a given single data type. This means a one character representation for primitives, and an L<class name>; representation for classes (including String). """ if type_name == "void": return "V" elif type_name == ...
3a9a230b2386c4c83b50e6f9919e7683734f0ce4
660,516
import pytz from datetime import datetime def convert_unix_ts(timestamp, timezone = "Europe/Berlin"): """Utility function to help converting flespi utc unix time output to human readable. Parameters: ----------- timestamp: int Unix time generated py flespi platform. timezone: str ...
0f869f311e41b26cc897c2c63611b9a09e4ddcb2
660,519
import json def dump_args(args: tuple, kwargs: dict) -> str: """Util to make hashable function arguments.""" return json.dumps(args) + json.dumps(kwargs, sort_keys=True)
0dc013159bfc7896a1c2c4b723e7ecbf16acc9e4
660,523
import click def _call_in_source(dag, method_name, message, kwargs=None): """ Execute method on each task.source in dag, passing kwargs """ kwargs = kwargs or {} files = [] results = [] for task in dag.values(): try: method = getattr(task.source, method_name) e...
fe1ad53e19e8aaa1265d27124d2d56eb61c689c0
660,526
import itertools def unpack_fields(fields): """ Flattens the given fields object into a flat list of fields. Parameters ---------- fields : (list | dict) List or dict that can contain nested tuples and None as values and column names as keys (dict). Returns ------- li...
bee277f4665ac4a43baeb37a6289558e1b4c101f
660,534
import re def _sanitize_query(query: str) -> str: """ Remove some invalid characters from the query Parameters ---------- query : str A search query to be sanitized Returns ------- str A sanitized query """ query = re.sub(r'\s+', ' ', query) return query
130a5dbb9fd835809f68b039f40db4961a2d6ba9
660,535
from typing import Tuple from typing import List def _get_lie_algebra(segment_sign: Tuple[int, int, int], radius: float) -> List[Tuple[float, float, float]]: """ Gets the Lie algebra for an arcline path. :param segment_sign: Tuple of signs for each segment in the arcline path. :pa...
791fb523f33652f6a5d8362e34b9ea582a7620e6
660,542
def rst_link_filter(text, url): """Jinja2 filter creating RST link >>> rst_link_filter("bla", "https://somewhere") "`bla <https://somewhere>`_" """ if url: return "`{} <{}>`_".format(text, url) return text
01fe0f88518611abbec3abd2f93d0cb4439cd225
660,545
def update_show_clade_defining(switches_value): """Update ``show_clade_defining`` variable in dcc.Store. This should be set to True when the clade defining mutations switch is switched on, and False when it is turned off. It is None at application launch. :param switches_value: ``[1]`` if the clad...
2905ec5ac8579b250df30c5f8bd629f1b7701965
660,546
def get_sum(path, tree): """ Returns the sum of all the numbers in the path for the given tree. """ pathsum = 0 for i, row in enumerate(tree): pathsum += row[path[i]] return pathsum
018cc24c6a1dc20cd9dbf5b0db6e3b20e257c7e6
660,551
def hash_shard(word): """Assign data to servers using Python's built-in hash() function.""" return 'server%d' % (hash(word) % 4)
ab333bba1f93909369f6935786a268bbda984e9e
660,552
def push_row(matrix, row): """Pushes row with index row to the bottom of the matrix, and shifts all other rows up""" return [matrix[i] for i in range(len(matrix)) if i != row] + [matrix[row]]
f2b9b4d2a2e199c7ac66ab817931323d218ded5a
660,554
import collections def are_lists_equal(list1, list2): """ Checks whether two lists are equal (contain exactly the same elements). Using Counter data structure allows duplicates to be considered i.e. [1, 1, 2] != [1, 2]. :param list1: the first list. :param list2: the second list. :return: tru...
cc3c1e3cee5f41361dfdd65f2ebcacc07b7540d6
660,559
def read_installer(myinstaller, log): """ reads the text of the current installer script and returns it as a string """ log.info(f"Reading current installer from {myinstaller}...") with open(myinstaller, "r") as f: text = f.read() log.info(f"\t=> found {len(text)} characters") return...
d063beb7def5ccd8ef2b6de64be297e541e59753
660,561
def requires_reload(action, plugins): """ Returns True if ANY of the plugins require a page reload when action is taking place. """ return any(p.get_plugin_class_instance().requires_reload(action) for p in plugins)
5cf26e1e22dc62f6b1280a7d5f664f30ee220e94
660,562
from typing import Union from pathlib import Path def file_variations( filename: Union[str, Path], # The original filename to use as a base. extensions: list, ) -> list: # list of Paths """Create a variation of file names. Generate a list of variations on a filename by replacing the extension with ...
b8f1953b7b59791ac1c2650aa959fef39ce53f1e
660,569
def compile(self): """Compile TokenNode.""" return "%s" % self.tok
09f6878ef1d8b41e8a811853a795884364e20626
660,581
def to_sorted_subfloats(float_string): """Convert string of floats into sorted list of floats. This function will first remove the "TSH" and turn the string of floats into the list of floats and sort them from smaller to larger. Args: float_string (str): A string begin with "TSH" and followed ...
7764b648449c4ca79a8fe9aecd8a1b3b73acee1c
660,587
def get_hash(example): """Get hash of content field.""" return {"hash": hash(example["content"])}
79e404ad99d87dd1151f4bd88ffba112ade82f4f
660,590
def f2odds(f): """Convert fraction B117 to odds ratio B117/other.""" return f/(1-f)
2dcf0b3516691b7c353ab80fedb19689c17791fb
660,591
def scale_between(minval, maxval, numStops): """ Scale a min and max value to equal interval domain with numStops discrete values """ scale = [] if numStops < 2: return [minval, maxval] elif maxval < minval: raise ValueError() else: domain = maxval - minval ...
4e21d0ed391776ad5ba85dad189b0ae46dfbf0ec
660,592
def progress_bar_width(p): """Compute progress bar width.""" p = int(p) return 15.0 + p * 0.85
1ea83fdc3d87a4b52920d1b94f3c2e08dc063b9e
660,595
def binomial_coefficient(n: int, k: int) -> int: """ Since Here we Find the Binomial Coefficient: https://en.wikipedia.org/wiki/Binomial_coefficient C(n,k) = n! / k!(n-k)! :param n: 2 times of Number of nodes :param k: Number of nodes :return: Integer Value >>> binomial_coefficient(4, ...
6925e0cdeec9e982d3349576b043994bd7794fbf
660,600
def _files(*paths): """Files for PyDoIt (It doesn't allow pathlib2, only str or pathlib).""" return [str(x) for x in paths]
48ce9ce052283024ac800ea5f1199fa0ca77aded
660,603
def read_article(article_location): """ Read article's filtered context. :param article_location: The article's file location. :type article_location: str :return: The context of file. :rtype: str """ article_text = '' with open(article_location, 'r', encoding='utf-8') as file: ...
788bd30ff778cdc2bd93372d0b073fb95e1797d4
660,604
def ndim(x): """Returns the number of exes in a tensor, as an integer.""" dims = x.get_shape()._dims if dims is not None: return len(dims) return None
a654a17081663d091acd761e61c3bccc06b801cf
660,608
def _slice(index, i, nneighbors, lim): """ A partir de l'indice `index`, renvoie les `nneighbors` indices suivants dans la dimension `i` (y compris `index`, qui est le premier élément de la liste). Si certains des indices calculés sont supérieurs à `lim` dans la dimension `i`, renvoie une liste...
afb34b36d1c5217ee2be89e5ef738b62099f1ea6
660,610
def pivotFlip(string, pivot): """Reverses a string past a pivot index.""" flip = list(string[pivot:]) flip.reverse() return string[:pivot]+''.join(flip)
1e00ea9526e6484e7072763cb7b1b55708261426
660,613
def det(x): """ Return the determinant of ``x``. EXAMPLES:: sage: M = MatrixSpace(QQ,3,3) sage: A = M([1,2,3,4,5,6,7,8,9]) sage: det(A) 0 """ return x.det()
8e74bb3c1f8c99ea25b4868690813b11ac47087f
660,614
def fields_sort_key_factory(fields, field_order): """Return a function to sort `fields` by the `field_order`.""" raw_field_order = [x[0] for x in fields] def key(key): name, field = key try: return field_order.index(name) except ValueError: return 100000 + ra...
5aae7150aa34d1fe9aafe943ef62b054a3bcf83d
660,620
import itertools def unique_dashes(n): """Build an arbitrarily long list of unique dash styles for lines. Parameters ---------- n : int Number of unique dash specs to generate. Returns ------- dashes : list of strings or tuples Valid arguments for the ``dashes`` parameter...
dfa88e1aa3b7c34cacdab3455947e59760e69891
660,622
import uuid def generate_id() -> str: """ Generate an uuid to be used as id """ return str(uuid.uuid4())
51fdc5edc567457e6f7fce9acf39619f0ab45da1
660,625
def count_user(data_list): """ Function count the users. Args: data_list: The data list that is doing to be iterable. Returns: A list with the count value of each user type. """ customer = 0 subscriber = 0 for i in range(len(data_list)): if data_list[i][5] ...
ccd4218efe017c4bebe332c9a258de61f03ec097
660,631
import base64 def encode_access_id(token_str: str, replica: str) -> str: """ Encode a given token as an access ID using URL-safe base64 without padding. Standard base64 pads the result with equal signs (`=`). Those would need to be URL-encoded when used in the query portion of a URL: >>> base64....
0e927008f5346eaff01741918ef8ac50c9bfd40b
660,633
def expand_suggested_responses(instrument, lookups, *responses): """ Maps any {'_suggested_response': pk} values to the SuggestedResponse by that id, as long as it is present in the ``lookups`` dict. """ values = [] for response in responses: data = response # Assume raw passthrough by...
06fce35c585716142489bcaf55339cabc36be9b6
660,634
import fsspec from typing import Optional from typing import Set from typing import List def _get_objects_in_path( fs: fsspec.AbstractFileSystem, path: str, target_type: Optional[str] = None, extensions: Optional[Set[str]] = None ) -> List[str]: """Get all objects of a specific typ...
73c05da142ac04637e992f6871b6fad851d8b9a2
660,636
def get_property_by_name(pif, name): """Get a property by name""" return next((x for x in pif.properties if x.name == name), None)
b3800921adb2d2275bede664f0f1697b6def2b72
660,637
def _scale(column, new_range): """ Scale list of values to a given range (the original range is assumed to be [min(column), max(column)]). """ old_range = (column.min(), column.max()) return (((column - old_range[0]) * (new_range[1] - new_range[0])) / (old_range[1] - old_range[0])) + new_range[0]
dd612904ac21eff845b62d13a6831a9ecd02c542
660,641
def dominance(counts): """Dominance = 1 - Simpson's index, sum of squares of probs. Briefly, gives probability that two species sampled are the same.""" freqs = counts/float(counts.sum()) return (freqs*freqs).sum()
5027b5476027006028453e4ceb6309faa76fb2c7
660,645