content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def ensure_tuple(tuple_or_mixed, *, cls=tuple): """ If it's not a tuple, let's make a tuple of one item. Otherwise, not changed. :param tuple_or_mixed: :return: tuple """ if isinstance(tuple_or_mixed, cls): return tuple_or_mixed if tuple_or_mixed is None: return tuple...
d7d6ca13a86391f4777da2716d5d9e4fe242698e
663,452
def _interp_evaluate(coefficients, t0, t1, t): """Evaluate polynomial interpolation at the given time point. Args: coefficients: list of Tensor coefficients as created by `interp_fit`. t0: scalar float64 Tensor giving the start of the interval. t1: scalar float64 Tensor giving the end of...
600cc5e39b8859f9e1a65e49e609030f09f88eec
663,453
import json def write_json(file_path, json_obj): """Write JSON string. # Arguments file_path: `str`<br/> the absolute path to the JSON string. json_obj: `dict`<br/> a dictionary # Returns flag : bool True if saved successfully False...
3f212d2271e3b29e68d64510974b4ad1c50f7a99
663,456
def broken_6(n): """ What comes in: A positive integer n. What goes out: Returns the sum: 1 + 1/2 + 1/3 + ... + 1/n. Side effects: None. """ total = 0 for k in range(1, n + 1): total = total + 1 / k return total
17e86195d68c531c63f748f91ec39dc04414b01e
663,465
def fantasy_pros_column_reindex(df): """Adds columns that are missing from Fantasy Pros tables and reorders columns Some tables are missing stats (no passing stats for RBs) so this will fill in the gaps and have '0' as the value for any missing column :param df: cleaned dataframe object resul...
cb846d31d9d6952650cab17cf6528d06ad9a0198
663,466
def no_comment_row(x_str): """ Tests if the row doesn't start as a comment line. """ return x_str[0] != "#"
798580a7dffaa22d17c389108d02050fedaebb51
663,467
def density(w, **kwargs): """Compute density of a sparse vector. Parameters ---------- w : array-like The sparse vector. Returns ------- float The density of w, between 0 and 1. """ if hasattr(w, "toarray"): d = float(w.nnz) / (w.shape[0] * w.shape[1]) e...
7fdd1c81cab679be8ac326aa86045cf6188fa60e
663,468
def id_from_uri(uri: str) -> str: """Get the item ID from URI address.""" return uri.rstrip("/").split("/")[-1]
e568df78c9c1b2a46501d4300d705b48467584a1
663,469
def gen_model(model_name, image_tag, timeout, num_of_workers): """ Generates the Sagemaker model that will be loaded to the endpoint instances. """ model = { "SagemakerModel": { "Type": "AWS::SageMaker::Model", "Properties": { "ModelName": model_name, ...
9cac78d8c864edce7aabef5e4d86c51827a3c31c
663,471
import pickle def unpickle(file): """Unpickle something (in this case tf-id).""" with open(file, "rb") as source: return pickle.load(source)
b1fe2af493a642155d1558b506682adf2e02a034
663,473
def lammps_copy_files(job): """Check if the submission scripts have been copied over for the job.""" return job.isfile("submit.pbs")
9d801d379155f02b93389252fd3352712f55fb2c
663,476
def encode_count_header(count): """ Generate a header for a count HEAD response. """ return { "X-Total-Count": count, }
43cb0ae99f696e10e0240364e5dc8067783084eb
663,478
def round_up(n: int, div: int): """Round up to the nearest multiplier of div.""" return ((n + div - 1) // div) * div
7ade722fa1354d67e4a7b4df453ae545c8b78135
663,479
import math def arc_chord_length(radius: float, sagitta: float) -> float: """Returns the chord length for an arc defined by `radius` and the `sagitta`_. Args: radius: arc radius sagitta: distance from the center of the arc to the center of its base """ return 2.0 * math.sqrt(2.0 ...
a174476f1c28db0c2b37c8a6fa0f7660d899c578
663,485
def num_coeffs(l): """The number of coefficients (i.e. different "order" terms) at a given degree, l 2*l + 1 """ return 2*l + 1
6b927b31402e1328f86a87e8e10d4e80df7d6ee5
663,490
from typing import Dict from typing import AnyStr from typing import Any def update_dictionary_keys_with_prefixes(input_dict: Dict[AnyStr, Any], prefix: AnyStr): """Adds a prefix to the keys of a dictionary.""" output_dict = dict((prefix + key, value) for (key, value) in input_dict.items()) return output_...
530d806de5a839318729f14c2e1c57a173509ed8
663,491
def div2D(v1,v2): """Elementwise division of vector v1 by v2""" return (v1[0] / v2[0], v1[1] / v2[1])
59415639346e89c5aed230caea807e8662c2f1ff
663,492
def get_visual_selection(lines, start, end): """Split an arbitrary selection of text between lines Args: lines (list): Lines of text to be processed start (tuple): Coordinates of the start of a selection in format (line, char) end (tuple): Coordinates of the en...
56936f17a5d23455a8df4f99519d02cf700697aa
663,495
def default_collate(batch): """ Default collate function, used for ParlAIDataset and StreamDataset """ new_batch = [] for b in batch: idx = b[0] if type(b[1]) is list: ep = b[1][0] else: ep = b[1] new_batch.append((idx, ep)) return new_...
acb5292ef117e7668a3d377ef0df4e3fc069f376
663,499
def user_says_yes(message=""): """Check if user input is either 'y' or 'n'. Returns a boolean.""" while True: choice = input(message).lower() if choice == "y": choice = True break elif choice == "n": choice = False break else: ...
b5ac454facc1ae7496b42c06fbe73776cae8bfca
663,502
def makespan(sol={}): """Returns the makespan of a solution (model 1's objective function).""" return sol["makespan"]
22e5ec2e2457032f1a653bbafb08f213c54f8eda
663,508
from typing import Tuple def printable_field_location_split(location: str) -> Tuple[str, str]: """Return split field location. If top-level, location is returned as unquoted "top-level". If not top-level, location is returned as quoted location. Examples: (1) field1[idx].foo => 'foo', 'field1[id...
100a05ed2188a4a21d783835591d04588f93a947
663,509
def replace_string_chars(s1, pos, s2): """ Replace characters in a string at the specified string position (index). @param s1: Input string for replacement. @param pos: Input string index of replace. @param s2: - Replacement string. @return: New resulting string. """ len2 = len(s2) i...
3544fd1d8b608efd0b6ec3a177ccb9c54356a8f7
663,510
def path_as_0_moves(path): """ Takes the path which is a list of Position objects and outputs it as a string of rlud directions to match output desired by Rosetta Code task. """ strpath = "" for p in path: if p.directiontomoveto != None: strpath += p.directiontomove...
6423f7c4c46fc79cd38cdddb3d367411ef9a05d4
663,515
import ast def _to_dict(contents): """Parse |contents| as a dict, returning None on failure or if it's not a dict.""" try: result = ast.literal_eval(contents) if isinstance(result, dict): return result except (ValueError, TypeError): pass return None
4e9acba2e247c72dc7927e37087415e5606d6b73
663,516
import click from typing import Union from typing import Any from typing import List from typing import Tuple from pathlib import Path def validate_path_pair( ctx: click.core.Context, param: Union[click.core.Option, click.core.Parameter], value: Any, ) -> List[Tuple[Path, Path]]: """ Validate a pa...
d6267479828546e395e6691b2495b807ca24e79a
663,524
def indent(*args) -> str: """Return joined string representations of objects with indented lines.""" text = '\n'.join(str(arg) for arg in args) return '\n'.join( (' ' + line if line else line) for line in text.splitlines() if line )[2:]
957dec3b0dd73931681414bfa16b30a92349e50d
663,525
def get_f_min(f_max, cents_per_value, v_min, v_max): """ This function takes in a y value max and min, a maximum frequency and a y scale parameter in units of cents/y value, and returns the minimum frequency that fits to such a scale. Cents are a logarithmic unit of tone intervals (https://en.wikipedia.org/...
c2e92d0f2aa63f8553d85d9fb0bdcf79156deff1
663,533
def dup_strip(f): """ Remove leading zeros from ``f`` in ``K[x]``. Examples ======== >>> from sympy.polys.densebasic import dup_strip >>> dup_strip([0, 0, 1, 2, 3, 0]) [1, 2, 3, 0] """ if not f or f[0]: return f i = 0 for cf in f: if cf: brea...
f72a3e78ea14f42e61118502eff981ed98250eae
663,534
def column_to_list(data, index): """Return a list with values of a specific column from another list Args: data: The list from where the data will be extracted index: The index of the column to extract the values Returns: List with values of a specific column """ column_list = [] ...
95a953b8da13ae04e755a2755ec6feebc447bd20
663,540
import itertools import operator def group_versions(versions): """Group versions by `major.minor` releases. Example: >>> group_versions([ Version(1, 0, 0), Version(2, 0, 0, 'rc1'), Version(2, 0, 0), Version(2, 1, 0), ]) ...
2d047c2650a11e96329a3dec870a9904d98d5c18
663,541
def metacalibration_names(names): """ Generate the metacalibrated variants of the inputs names, that is, variants with _1p, _1m, _2p, and _2m on the end of each name. """ suffices = ['1p', '1m', '2p', '2m'] out = [] for name in names: out += [name + '_' + s for s in suffices] ...
1c1783db3dbd82239ccb2052b79280f7bde4a5b2
663,549
def getNamespaceUnversioned(string: str): """getNamespaceUnversioned Gives namespace of a type string, version NOT included :param string: :type string: str """ if '#' in string: string = string.rsplit('#', 1)[1] return string.split('.', 1)[0]
942ca50f3168124fd6935ac97a069a8519e0559a
663,557
def MultiplyTwoNumbers(a,b): """ multiplying two numbers input: a,b - two numbers output: returns multiplication """ c = a*b return c
ee083b6133de4e2c8da434b937dd801d074ae31b
663,561
def days_since(t1, t2): """ Returns the number of days between two timestamps. :param t1: Time one. :param t2: Time two. """ timedelta = t1 - t2 return timedelta.days
9ed73a98fcb2dcde9f3317b7785bfc1bd074a23f
663,564
import re def substitute(line, regex, class_): """Generate a span and put it in the line per the regex.""" result = re.search(regex, line) if result: for match in result.groups(): line = line.replace( match, '<span class="{}">{}</span>'.format(class_, match), 1 ...
a5c96b3550371c085cfff21c0e7bb128642793b1
663,570
def ceildiv(a, b): """Divides with ceil. E.g., `5 / 2 = 2.5`, `ceildiv(5, 2) = 3`. Args: a (int): Dividend integer. b (int): Divisor integer. Returns: int: Ceil quotient. """ return -(-a // b)
2fb7849ac6ad823e4259672d29cc96b9bfef3d3f
663,571
def flatten(lst): """Flatten a 2D array.""" return [item for sublist in lst for item in sublist]
74dac38eff7b7eec3254dbc2fa49287f25552ad8
663,572
def lcfa_pattern(tmp_path): """Fixture to mock pattern for LCFA files.""" return str(tmp_path / "lcfa-fake" / "lcfa-fake-{year}{month}{day}{hour}{minute}{second}-" "{end_hour}{end_minute}{end_second}.nc")
6a2ca379692fc61f6a17ff3198a7cbe2a09b1181
663,574
def leverage(balance_df): """Checks if the leverage exposure was reduced since previous year Explanation of Leverage: https://www.investopedia.com/terms/l/leverage.asp balance_df = Balance Sheet of the specified company """ # current year assets_curr = balance_df.iloc[balance_df.index.get_l...
2e528e959bade3f3de875429eb1a1289c8a77d52
663,575
def get_progress(context, scope): """ Returns the number of calls to callbacks registered in the specified `scope`. """ return context.get("progress", {}).get(scope)
cd0f827c3bf1f548a51dce992949b804d6b97aba
663,579
def fread(path): """Reads a file.""" with open(path, 'r') as file: return file.read()
4c80975e324286e0b95298fc8c12c8670c6b60ed
663,580
def Multiply_by_number(matrix_1, number): # умножение матрицы на число """ Функция, которая умножает матрицу на число :params matrix_1: матрица :params matrix_2: число, на которое необходимо умножить матрицу :return matrix_out: матрица, как результат """ matrix_out = [] for...
a62c8b08be1d6947176a622d1eae059f31e29907
663,582
def filter_products(queryset, user): """ Restrict the queryset to products the given user has access to. A staff user is allowed to access all Products. A non-staff user is only allowed access to a product if they are in at least one stock record's partner user list. """ if user.is_staff: ...
6189b05e41f2408d85bd22a850b3eea36d26f744
663,588
from typing import Any def arg_dict_creator(string: Any): """Creates a Dict from a CSV string. Args: string(str): CSV string - formatted as 'field1:value1,field2:value2'. Returns: Dict from string representation. """ if not string: return None split_string = string.s...
7c0d5d2b02a3a0cca7bf1f2dbf0946aabb7a5aea
663,589
def create_dicts_by_chain(keys_chain: list): """ Create nested dicts by keys chain >>> create_dicts_by_chain(['some', 'keys']) {'some': {'keys': {}}} """ result = {} current_dict = result for key in keys_chain: current_dict[key] = {} current_dict = current_dict[key] r...
03ab93fbe62a59e539fd150ab1277c4377fd6739
663,590
def load_collection(path): """Loads tsv collection into a dict of key: doc id, value: doc text.""" collection = {} with open(path) as f: for i, line in enumerate(f): doc_id, doc_text = line.rstrip().split('\t') collection[doc_id] = doc_text.replace('\n', ' ') if i % 1000000 == 0: pri...
3813b229560e11959d135de1be62659aed8b06af
663,594
def sampleIdsFromNode(node, cladeTops=()): """Return a list of IDs of all samples found under node.""" kids = node.get('children') if (kids): sampleIds = [] for kid in kids: if (kid not in cladeTops): sampleIds += sampleIdsFromNode(kid, cladeTops) else: ...
7832e7916d917cb1e4fe848a6094516c2dc1c913
663,596
def dense_flops(in_neurons, out_neurons): """Compute the number of multiply-adds used by a Dense (Linear) layer""" return in_neurons * out_neurons
e9f35b2f1d7cad7c8e47f75983f806881d293ffa
663,606
def calc_beats(data, rpeak_locs, metrics): """Returns the times when R-peaks occur Args: data (2D numpy array): contains two columns with time and ECG data rpeak_locs (1D numpy array): contains locations of R-peaks metrics (dict): dictionary containing the metrics calculated ...
6491e104d85bb251430f752b780e5f7a1c82bac0
663,614
def majority_vote(votes, minimum_count=3): """Determine the label voted for by the majority Given a list of binary votes we compute the preferred label based on a simple majority vote if there are atleast `minimum_count` votes. Returns the binary label or `None` if there are not enough votes "...
c90e04df5b6f11272e55f9f667ccc5af9568e23d
663,615
def pluralize(n, text, suffix='s'): # type: (int, str, str) -> str """Pluralize term when n is greater than one.""" if n != 1: return text + suffix return text
4c186689474f4b761070214a074cfa3cf91d005d
663,616
def shortest_path_tree(g, s, d): """Reconstruct shortest-path tree rooted at vertex s, given distance map d. Return tree as a map from each reachable vertex v (other than s) to the edge e=(u,v) that is used to reach v from its parent u in the tree. """ tree = {} for v in d: if v is not s: for e in...
f2bf948469b601a8074f5837f1dd52f8f926fa25
663,617
def decodeImage(imageMatrix, bitPlane): """ Method to decode the text inside the image to a text string. Parameters ---------- imageMatrix : list A list of ints with the matrix of pixels of the image to be modified bitPlane : int The...
b98cfc69eba9b56ff6d287f423820a33edc5f875
663,622
def set_blast_min_length(config): """Set minimum sequence length for running blast searches.""" return config["settings"].get("blast_min_length", 1000)
7fe865731fb0de1dd4e45a6bdf4a4fbcdb84b7d5
663,626
def local_name(url): """Generate a local filename from a remote URL.""" # We assume that the remote url is separated by / and that the file name # is the final part of the url return url.split('/')[-1]
70feaa769d6a85ac4c89ecef400d9af2dd100f6d
663,628
def readlines(fil=None,raw=False): """ Read in all lines of a file. Parameters ---------- file : str The name of the file to load. raw : bool, optional, default is false Do not trim \n off the ends of the lines. Returns ------- lines : list The list ...
4557a9b3ada9d42932c711723eb089814f2820aa
663,629
def normalize_commit_message(commit_message): """ Return a tuple of title and body from the commit message """ split_commit_message = commit_message.split("\n") title = split_commit_message[0] body = "\n".join(split_commit_message[1:]) return title, body.lstrip("\n")
c93d05b16a8dcc02b030e6e5b2f6b05aaac5232b
663,631
import json def load_task(json_file): """Opens a task json file and returns its contents""" try: with open(json_file, 'r') as jinput: raw_input = json.load(jinput) except FileNotFoundError as e: print(f'\n\nError, file not found: {json_file}', end='\n\n') return re...
0499178a0b28caddc4e8689b5109d7a2b5af09e9
663,638
def FilterSet(df, annotSet="", annotSetArr=[], annotSetCompare="=", limit=0, negate=False): """Provide the ability to filter a Dataframe of AQAnnotations based on the value in the annotSet field. Args: df: Dataframe of AQAnnotations that will be filtered by the specified annotation set. annotSet: String to...
e56f7fb5aba3efeba231a03f1be3817550ae7b4a
663,639
import json def load_dictionary_from_json_file(json_file_path): """ Loads a dictionary from file at json_file_path, returns the dictionary. """ with open(json_file_path, 'r') as json_file: return json.load(json_file)
ad03c556b8cc0ddddcea88b17fe739b5ef43806e
663,645
def getBlockZone(p, aSearch, tBlock, blockSize): """ Retrieves the block searched in the anchor search area to be compared with the macroblock tBlock in the current frame :param p: x,y coordinates of macroblock center from current frame :param aSearch: anchor search area image :param tBlock: macrobl...
1317c4816ca4c14de3adb34dcbddb97cea8be08a
663,647
def prefix_absolute_path_references(text, base_url): """Adds base_url to absolute-path references. Markdown links in descriptions may be absolute-path references. These won’t work when the spec is not hosted at the root, such as https://spec.matrix.org/latest/ This turns all `[foo](/bar)` found in ...
15c5cc435f23a888a725066eba8405d1d438ce9d
663,650
def find (possible): """Returns `(key, index)` such that `possible[key] = [ index ]`.""" for name, values in possible.items(): if len(values) == 1: return name, values[0]
6fb98eb6baf4756210f0e8fa38783a3498cf3093
663,651
def construct_raid_bdev(client, name, strip_size, raid_level, base_bdevs): """Construct pooled device Args: name: user defined raid bdev name strip_size: strip size of raid bdev in KB, supported values like 8, 16, 32, 64, 128, 256, 512, 1024 etc raid_level: raid level of raid bdev, supp...
ad9a09c100e836cf5d7f4c2593e1e838ed8bea2c
663,653
def fit_pattern(pattern, word): """ Checks if given word fits to the pattern """ if len(pattern) != len(word): return False for i in range(len(pattern)): if pattern[i] != '.' and pattern[i] != word[i]: return False return True
d6e06eb9fbf6c015fca3a691436aa973d91025b3
663,655
import json def deserialize_json_response(byte_content): """Deserializes byte content that is a JSON encoding. Args: byte_content: The byte content of a response. Returns: The deserialized python object decoded from JSON. """ return json.loads(byte_content.decode("utf-8"))
98cf4284c0904ba31f82e1f39e848a3158a49b7c
663,658
def get_ttl(seconds=None, minutes=None, hours=None, days=None, weeks=None): """ Get ttl in seconds calculated from the arguments. Arguments: seconds (int | None): Number of seconds to include in the ttl. minutes (int | None): Number of minutes to include in the ttl. hours (int | Non...
e1ce7725cb3253275bd3d23be39a0b8180df5e73
663,659
def potential_cloud_shadow_layer(nir, swir1, water): """Find low NIR/SWIR1 that is not classified as water This differs from the Zhu Woodcock algorithm but produces decent results without requiring a flood-fill Parameters ---------- nir: ndarray swir1: ndarray water: ndarray Outpu...
8ef78fe9048ccac2ecc2dc1b12250eb424c083d2
663,660
import csv def readCSVIntoList(link): """ Reads CSV to list using 'csv.reader()' Params: link (String) - contains link to the file Returns: tweets_list (List) - containing the tweets in vector form (m x 1) """ tweets_file = csv...
9d0afe32a127930869cdc4b91e99d93488f210f2
663,669
from typing import Mapping def _turn_iterable_to_mapping_from_attribute(attribute, obj, optional=False): """ Given ``obj`` which is either something that is an instance of ``Mapping`` or an iterable, return something that implements ``Mapping`` from ``getattr(o, attribute)`` to the value of the items ...
d1b3eeea07c48c73b97e6f93759e983f9aa262ba
663,674
import functools import warnings def deprecated(f): """Prints a deprecation warning when called.""" @functools.wraps(f) def wrapper(*args,**kw): warnings.warn_explicit("calling deprecated function %s"%f.__name__, category=DeprecationWarning, ...
2cbf070c902f026acb0df61fcd17f65191139d55
663,675
def loan_principal(a: float, i: float, n: float) -> float: """ Calculates the loan principal given annuity payment, interest rate and number of payments :param a: annuity payment :param i: monthly nominal interest rate :param n: number of payments :return: loan principal """ numerator = ...
dc5a991a6fc0d6ed9e5e3fd3138a0ed8c9d13fe0
663,679
import string import random def id_generator(size=6, chars=string.ascii_uppercase + string.digits): """Random string generator. Original code from: http://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python Parameters ---------- size : i...
b501dda1c9514671c6a944ee5d61785da51ace08
663,680
from typing import AsyncIterable from typing import AsyncIterator from typing import NoReturn def empty() -> AsyncIterable[None]: """ Returns an asynchronous iterable that yields zero values. """ class Empty(AsyncIterator[None]): def __aiter__(self) -> AsyncIterator[None]: return ...
f6789e6c62a6713929f589493c41aad6bff6667c
663,682
def topHat(r,A0=0.2): """Top-hat beam profile as used in Ref. [1]. Args: r (numpy array, ndim=1): Equispaced 1D grid for radial coordinate. A0 (float): Top hat width (default: 0.2). Returns: f (numpy array, ndim=1): Top-hat beam profile. """...
5bb8a71daf3150d45b6120ce9be692e03e4f4e23
663,685
def npv_converter(sensitivity, specificity, prevalence): """Generates the Negative Predictive Value from designated Sensitivity, Specificity, and Prevalence. Returns negative predictive value sensitivity: -sensitivity of the criteria specificity: -specificity of the criteria preval...
7e4199ebdf967650595afcc0b3cfd6c01520b333
663,687
def convert_error_code(error_code): """Convert error code from the format returned by pywin32 to the format that Microsoft documents everything in.""" return error_code % 2 ** 32
40197987e46fab5082b7ccad308edbefd472b852
663,692
def simplify_polyphen(polyphen_list): """ Takes list of polyphen score/label pairs (e.g. ['probably_damaging(0.968)', 'benign(0.402)']) Returns worst (worst label and highest score) - in this case, 'probably_damaging(0.968)' """ max_score = 0 max_label = 'unknown' for polyphen in polyphen_li...
c31334c0526beed5c3506fb121f3b0e4a3fe51ee
663,695
def snake_to_camel(value: str, *, uppercase_first: bool = False) -> str: """ Convert a string from snake_case to camelCase """ result = "".join(x.capitalize() or "_" for x in value.split("_")) if uppercase_first: return result return result[0].lower() + result[1:]
6b5498e997b7a5408e55ef6a8921ffe2df37cd84
663,696
def _expt__CMORvar(self): """Return set of CMORvar item identifiers for CMORvars requested for this experiment""" cmv = set() for u in self._get__requestItem(): ri = self._inx.uid[u] rl = self._inx.uid[ri.rlid] for i in rl._get__CMORvar(): cmv.add(i) return cmv
db40213a4aee047321a6e19647e04228c2c9f084
663,697
def extract_name_email (txt): """ Extracts the name and email from RFC-2822 encoded email address. For eg. "Jeff Jeff <jeff.jeff@gmail.com>" returns ("Jeff Jeff", "jeff.jeff@gmail.com") """ if "<" in txt and ">" in txt: name, email = txt.split("<") return name[:-1], email[:-...
5226ab6c7fd9cfd3047e6a512f076f1e22a05f8c
663,705
def is_key_valid(key): """Returns True if a Cloud Datastore key is complete. A key is complete if its last element has either an id or a name. """ if not key.path: return False return key.path[-1].HasField('id') or key.path[-1].HasField('name')
019318b00c8843946dbd36b67570f19cbaed137d
663,706
def preprocess( text, min_token_len=2, irrelevant_pos=["ADV", "PRON", "CCONJ", "PUNCT", "PART", "DET", "ADP", "SPACE"], ): """ Given text, min_token_len, and irrelevant_pos carry out preprocessing of the text and return a preprocessed string. Parameters ------------- text : (str) ...
e36a622f748cb3f6900eda3f3e4d5ef8dbf44952
663,707
import datetime def convertto_iso_format(dt_obj: datetime.datetime): """Takes a given datetime object and returns the timestamp in ISO format as a string. Examples: >>> now = get_epoch_time()\n >>> now\n 1636559940.508071 >>> now_as_dt_obj = convertfrom_epoch_time( no...
3034ad46411438efb2abb3848cfaa12e18983aca
663,708
def process_question(question): """Process the question to make it canonical.""" return question.strip(" ").strip("?").lower() + "?"
0372540179cb1680b7b66b140bb6eb92d2eae9c4
663,713
import functools import operator def solution(resources, args): """Problem 8 - Version 1 Go through the entire 1000-digit number and calculate the product of each digit in the specified numbers of digits, then find the maximum. Parameters: resources The 1000-digit number ar...
f18b72d9f71491afa79cd7a12641376f937acd37
663,715
from typing import get_origin from typing import Union from typing import get_args def get_possible_types(t): """ Given a type or a Union of types, returns a list of the actual types """ if get_origin(t) == Union: return get_args(t) else: return [t]
e172de92d9dd76b77eaec821d39d84089328b3c6
663,717
import string import re def split(s): """Split string s by whitespace characters.""" whitespace_lst = [re.escape(ws) for ws in string.whitespace] pattern = re.compile('|'.join(whitespace_lst)) return pattern.split(s)
1d911d49776851350aac83532d434b7b9ccb11ba
663,718
def sort_dict(d, reverse=True): """Return the dictionary sorted by value.""" return dict(sorted(d.items(), key=lambda item: item[1], reverse=reverse))
55a17c1c1b828aa6f72410c9d9bc08d3838ce905
663,725
def reduceWith(reducer, seed, iterable): """ reduceWith takes reducer as first argument, computes a reduction over iterable. Think foldl from Haskell. reducer is (b -> a -> b) Seed is b iterable is [a] reduceWith is (b -> a -> b) -> b -> [a] -> b """ accumulation = seed for value...
edc217ce3a53521e872ad04b461d6ecad9f549d2
663,726
import re def process_mac_ip_pairs(tshark_output): """ Process output from the tshark command with MAC-IP pairs and return parsed array of dictionaries. :param tshark_output: output obtained by running tshark command :return: array of dictionaries with parsed MAC-IP pairs """ # Remove white s...
c95c493b1630c1a9cbcefb2f42703095eb96bf1c
663,727
def remove_duplicates_retain_order(seq): """Code credited to https://stackoverflow.com/a/480227. Args: seq (list): Any list of any datatype. Returns: list: The list in same order but only first occurence of all duplicates retained. """ seen = set() seen_add = seen.add return([x for x in seq if not (x in se...
a928c63a53ddd032ebcafc3d958d4e8efe313844
663,732
from typing import Any import re def get_MD(tag_bytes: bytes, no_tag: Any = None) -> str: """Extract the MD tag from a raw BAM alignment bytestring Parameters ---------- tag_bytes : bytes a bytestring containing bam formatted tag elements no_tag : Any r...
f12b9ac78ba8ed77f26219500dd28a0464b52a90
663,733
def choose(n, k): """ Binomial coefficients Return the n!/((n-k)!k!) Arguments: n -- Integer k -- Integer Returns: The bionomial coefficient n choose k Example: >>> choose(6,2) 15 """ ntok = 1 for t in range(min(k, n - k)): ntok = ntok * (n...
62b80dd620bf10e9058aedfebc32dfdfa34f0ae5
663,734
def indices_of_nouns(tokens): """Return indices of tokens that are nouns""" return [i for i, (_, pos) in enumerate(tokens) if pos.startswith('N')]
d8f3bf620a4272aba3948ce9c82a767e197afdaa
663,737
import math def _lockfile_create_retries(timeout_sec): """Invert the lockfile-create --retry option. The --retry option specifies how many times to retry. Each retry takes an additional five seconds, starting at 0, so --retry 1 takes 5 seconds, --retry 2 takes 15 (5 + 10), and so on. So: timeout_sec =...
f34148d2d9bdb7e994081411fcccd1e55d4ce878
663,738
def AlignMatches(matches): """ Tallys up each dif's song id frequency and returns the song id with highest count diff Args: matches: list of tuples containing (song id, relative offset) matched from known song Returns: songId (int) """ diffMap = {} largestCount = 0 song...
d6caf440fc374845b72266e8fbef5bc45658cbf1
663,744
import platform def is_os(*args): """Check if current OS is in args Returns: bool """ return platform.system() in args
9643493d93dd13f3b5b6785c25a19f80bde081e9
663,745
def elaborateanswer(question): """ Give an elaborate, realitisc and Michael-Palin-like answer to the question `question`. Examples: --------- >>> elaborateanswer("Do you have some cheddar?") 'No.' >>> elaborateanswer("The camembert is indeed runny.") '<Nods.>' """ if questio...
15dd965ee0d74fe222603227535b8961da0d1883
663,747