content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def seglength(pyccd_result, ordinal, series_start): """ The number of days since the beginning of the segment that the ordinal intersects with. The days between and around segments identified through the change detection process comprise valid segments for this. This why we need to know when the act...
a3d73ebd9d2725dd27662ebfd69c0c70395833cf
572,371
import re def normalize_ark_string(ark_string): """ Reconsitutues the hypens in the UUID portion of the ARK string. The ARK spec requires hyphens to be insignificant. Assumes that the ARK string contains the optional / after 'ark:', that the NAAN is 5 characters long, and that the shoulder is pre...
b9cdd9d11b0534c85b0ad6dc467ca1127bb733c3
572,372
def gen_related(*related): """Generate section with list of related objects""" fmt = '<li>{}: <a href="/{}?{}">{}</a>' data = [fmt.format(r[0], r[0], '&'.join(['='.join(e) for e in r[1]]), r[2]) for r in related] return '<h2>Related objects</h2><...
21ee8d0b74f546ad0c324aa515b6b372db00807f
572,375
def get_scf_variables(**kwargs): """Return a dict of variables required for an SCF calculation.""" variables = dict( prtden = 1, prtvxc = 1, tolvrs = kwargs.get('tolvrs', 1e-10), ecut = kwargs.get('ecut'), ) return variables
b2d3b029b1422515115690af7030dd5466c70b8d
572,378
def compose_retries(*can_retry_funcs): """ Compose other can_retry functions into a single function that calls each of the passed can_retry function in the sequence and returns True only if all of them return True :return: a function that accepts a :class:`Failure` and returns ``True`` only...
cca86efa5499846abe514aaaa97da20d917ea8a4
572,379
import pickle def load_data(filename): """Load data from pickle file Parameters ---------- filename: str Path to file Returns ------- data: list or dict Loaded file. """ return pickle.load(open(filename, "rb"), encoding='latin1')
f3b119e4b756669e8ffa9dc297f14891a48c6455
572,381
import torch import math def compute_particle_xyz_from_internal(particle_1_xyz, particle_2_xyz, particle_3_xyz, bond, angle, dihedral): """ Compute the Cartesian coordinate of a particle based on i...
9a3b59d5c29a0c8ac9c5f498925698b8ab29bd16
572,388
def _get_attribute(element, attrname): """ Get attribute from an element. Wrapper over Element.attrib, as this doesn't fallback to the element namespace if the attribute is qnamed and the requested attribute name is not. Ex: <ns:elem attr1="value1" ns:attr2="value2"/> _get_att...
0aefddaeee265616d0c6725015c8f0ddb8e5921a
572,395
import copy def _normalize_data_to_send(info): """Cleans up the data to send to the cloud service. Args: info (dict): the data to send Returns: dict: the info object, cleaned. """ # Remove the parts of the data that are unbounded in size. info = copy.deepcopy(info) for key ...
9e329d0173c20ba8082e2b228e60ed45284f1dfc
572,400
def _find_child_node(node, name): """Return child with given name from parent node""" for c in node.children: if c.frame.get("name") == name: return c return None
455148bb38225fe3e83c182503c48b7189fb3eed
572,401
def to_list(sql_results): """ Transform the results from mysql query (tuple) to list """ ret = list() for tup in sql_results: if len(tup) == 1: ret.append(tup[0]) else: ret.append(list(tup)) return ret
59d3dd7bac7cae08ccb80fd24924b9a24751280b
572,402
def unroot_schema(schema: dict): """ Modify a json-schema dictionary to make it not root. Parameters ---------- schema: dict """ terms = ("required", "properties", "type", "additionalProperties", "title", "description") return {k: v for k, v in schema.items() if k in terms}
58b30b9c1013fc2a06cf7c97286bc1282399db20
572,403
def get_time_group_max(time_group): """Return dictionary with max values for each time group.""" dict_time_max = {'year': 5000, # dummy large value for year since unbounded ... 'season': 4, 'quarter': 4, 'month': 12, ...
23413dca869c4a70d145c89e74985f38b72d0fa8
572,412
def nest_contains_list(nest): """Whether the nest contains list. Args: nest (nest): a nest structure Returns: bool: True if nest contains one or more list """ if isinstance(nest, list): return True elif isinstance(nest, tuple): for item in nest: if ne...
39459f822e0cb31a2fb1f28c225352b025c8f1c3
572,413
from typing import List import re def find_expected_outputs(snippet: str) -> List[str]: """Finds expected output lines within a snippet. Expected output must be annotated with a leading '# prints'. Lines below '# prints' must start with '# ' or be just '#' and not indent any more than that in order t...
b9a5993d5a5a17c0fe1e6737e5b4ec0f9f214d82
572,417
def create_author(conn, author): """ Create a new author into the authorScopus table :param conn: :param author: :return: author id """ sql = ''' INSERT INTO authorScopus(id,givenname,surname,initials,orcid) VALUES(?,?,?,?,?) ''' cur = conn.cursor() cur.execute(sql, author) return cur.lastrowid
16407bbe36db59ef6464792aa18bba0ca4028b59
572,419
def findValue(tags, tag_name, label_name=None, label_type=None): """ This is a small helper that is used to pull out values from a tag given the value of the tags class or id attribute. See the example. Parameters: ----------- tag_name : str Tag name or type,...
6d1f150b63b54aa6e22a7aac594865e8329ab5de
572,420
def _get_channel_num(port_grp): """ Return a channel number given a port group. The lowest value port number in the group is returned. No checks are made to insure that all ports are in the same chassis. Args: port_group: (tuple or list of str representing port numbers of the form 'n' ...
8c57577208c3f5e670bf5f132e5961c271be6176
572,422
def get_affected_enduse(strategy_vars, name): """Get all defined affected enduses of a scenario variable Arguments --------- strategy_vars : dict Dict with all defined strategy variables name : str Name of variable to get Returns ------- enduses : list AFfected ...
30675c28f615b0e91c1884e858fa449371c235d5
572,425
import requests def get_source_code(url): """Get the source code of the given webpage as a text in English Args: url (str): The URL to get a source code from Returns: str: The text from the response body in English (if possible) """ return requests.get(url, headers={"Accept-Lang...
fce2a7eb439386686f9aabbf8de7389846514c63
572,429
import re def replaceURL(text, replace): """ Replaces url address with "url" """ text = re.sub('((www\.[^\s]+)|(https?://[^\s]+))',replace,text) text = re.sub(r'#([^\s]+)', r'\1', text) return text
3118d3c6e4680065856e5ec84a2415df65130526
572,434
import torch def kl_div_to_std_normal(mu, logvar): """Compute element-wise KL(q(z) || N(0, 1)) where q(z) is a normal parameterized by mu, logvar. Parameters ---------- mu : :obj:`torch.Tensor` mean parameter of shape (n_frames, n_dims) logvar log variance parameter of shape (n_fr...
e0450e4c821ee3f89c4dd48a0d54aea5d572b467
572,436
def f_to_c(degrees): """ Convert degrees fahrenheit to degrees celcius """ return (degrees - 32) * 5/9
73e74f81cc7b106f9575476057c29ad8035365c8
572,437
import pytz def dout(obj): """ Helper function to ensure that we're always printing internal datetime objects in a fully qualified UTC timezone. This will let 'None' values pass through untouched. """ if obj is None: return if obj.tzinfo: return obj.astimezone(pytz.UTC).iso...
f2c9e76a31a5588a90388d5cbab74477db868a2a
572,438
from datetime import datetime def structured_data_datetime(dt): """ Formats datetime object to structured data compatible datetime string. """ if dt.time(): return datetime.strftime(dt, "%Y-%m-%dT%H:%M") return datetime.strftime(dt, "%Y-%m-%d")
acab0ce0fd32280ce722c00da4b73ce2f18c3716
572,439
def cladistic(tree, taxa): """Determines the cladistic property of the given taxon set. Parameters ---------- tree : skbio.TreeNode tree for taxa comparison taxa : iterable of str taxon names Returns ------- str 'uni' if input taxon is a single tip in given tree...
6040b759a210779dd291b2d29da8944e5467cdbf
572,442
import re def extract(regularE : str, init : str, stop : str, string : str): """ regularE: RE to catch string init: First string to replace stop: Last string to replace string: String to apply the RE With a regular expression and init and stop to replace,...
4466f2a0a7377d634554a231b5b79c2778bc3f30
572,444
import re def parseVersionFromLine(version_str): """Given a string containing a dotted integer version, parse out integers and return as tuple.""" version = re.search(r'(\d+\.\d+\.\d+)', version_str) if not version: return (0,0,0) return tuple(map(int, version.group(1).split(".")))
89917953ccd05219542ce75a90e70b92fbe2d2ab
572,445
def first(thing): """ FIRST thing if the input is a word, outputs the first character of the word. If the input is a list, outputs the first member of the list. If the input is an array, outputs the origin of the array (that is, the INDEX OF the first member of the array). """ return th...
4538d8dd442442a1663bbe18b95bb24e2edc7d3b
572,446
def bottleneck_param(scope, base_depth=64, kernel_size=3, num_units=3, stride=2, rate=1): """ Generate parameters for each stage in a res-net. :param scope: string, the name of the stage(bottleneck), e.g, "b...
e59bc85dfa2cb11bd4e1e5bfb810eb66f94d2a25
572,447
def obj_index_getter(key): """Get a callable that extracts a key form an object.""" return lambda obj: ( getattr(obj, "__getitem__", None) or getattr(obj, "__getattribute__") )(key)
465f5fb6401e8d619bdee4eda69cb6ba385a68dc
572,448
import requests from bs4 import BeautifulSoup def get_page(url): """ Gets the particular webpage to parse. """ r = requests.get(url) html_content = r.text soup = BeautifulSoup(html_content, 'lxml') return soup
77a547d1d12327817e0d4d341164d82e256cd30d
572,449
from typing import Tuple def decode_length(b: bytes) -> Tuple[int, int]: """ Decodes a shortvec-encoded length from the provided bytes :param b: The provided bytes :return: The length decoded from the provided bytes and how many bytes it used. """ offset = 0 length = 0 while offset < le...
051f28ca178667b4a913a6691dda4c835b38d34f
572,454
def bitVector2num(bitVec: list): """Convert a bit list to a number. The list is assumed to be in "MSB-at-index-0" ordering. Args: bitVec (list): The bit list that we want to convert to a number. Returns: Integer value of input bit vector. """ bitStr = ''.join(str(b) for b...
99764755eb2fde7977f17867fbb90ab259ad0f3d
572,455
def dictionary_based_metrics(metrics): """ Higher order function creating a result type and collection function from the given metrics. Args: metrics (iterable): Sequence of callable metrics, each accepting the algorithm state as parameter and returning the measured valu...
e4e893cd95d3aec5b6e3de7e1c47f7ca1c1122ae
572,462
def sign(value): """ Returns the sign of the given value :param value: float :return: -1 of the value is negative; 1 if the value is positive; 0 if the value is zero """ return value and (1, -1)[value < 0]
f975dd2516b120b69ab3ce5553bfe79f671fcdc2
572,464
def IsSameFile(changed_src_file_path, file_path_in_log): """Guesses if the two files are the same. Args: changed_src_file_path (str): Full path of a file committed to git repo. file_path_in_log (str): Path of a file appearing in a failure log. It might not be a full path. Returns: True if th...
a3a95f3acaeb62a57c9d1fb6a247e90ad7f27941
572,466
def df_without_columns(df, cols_to_remove): """ Returns a copy of the input dataframe, without specified columns. :param df: the input DataFrame :param cols_to_remove: list or set of columns to remove :return: a copy of the input dataframe, without specified columns. """ df_sub = df[list(s...
492c13040da3f4663157cc5741927349a3df3bac
572,469
def round_list(raw_list, decimals=4): """ Return the same list with each item rounded off. Args: raw_list: float list decimals: how many decimal points to round to Returns: the rounded list """ return [round(item, decimals) for item in raw_list]
b23223e582e5bcb0c72ce1507dd48d0fa004e129
572,470
def get_roles(decoded_token): """Get roles declared in the input token Note: returns both the realm roles and client roles Args: decoded_token (dict): The user's decoded bearer token Returns: list[str]: List of role names """ # Extract realm scoped roles try: # Se...
b585872e02993841b16a10e029a18884974625eb
572,471
def compare_adf_stat_with_critical_values(result): """ Function compares the t-stat with adfuller critcial values (1%) and returnsm true or false depending on if the t-stat >= adfuller critical value :result (dict_items) Output from adfuller test :return (bool) """ tstat = abs(next(i...
3f40d725b6ced7fd57b8cbd24e8178c372078755
572,472
from typing import List def get_paired(words: List[str]) -> List[str]: """ Pair each word with the next one with a white space. :param words: a list of words :return: a list of strings, where each one is a concatenation of two neighboring original words. """ if len(words) > 1: return [...
fbfaa297dc798d940e5d1a55dd15213d008571e7
572,481
import re def _clean_order(order): """ Takes something like (1 1 0)(0 1 1) and returns a arma order, sarma order tuple. Also accepts (1 1 0) and return arma order and (0, 0, 0) """ order = re.findall(r"\([0-9 ]*?\)", order) def clean(x): return tuple(map(int, re.sub("[()]", "", x).spl...
0a7284dc41b8b376533340ea2b18aff07c7eafd4
572,487
def text_length(text): """ Get text length """ text = text.decode('utf-8') return len(text)
bafac64c628665425fede7fde144c334b9d0b80d
572,488
def decay_function(value, epoch, reduction_rate): """ Applies to the input value monothonical decay. Parameters ---------- value : int, float epoch : int Current training iteration (epoch). reduction_rate : int The larger the value the slower decay Returns -------...
e001a8f0bead9117a5462e0155e8e48a221ff2a9
572,490
def contains_an_even_digit(n: int) -> bool: """ Return True if n contains an even digit. >>> contains_an_even_digit(0) True >>> contains_an_even_digit(975317933) False >>> contains_an_even_digit(-245679) True """ return any(digit in "02468" for digit in str(n))
78eb8764f7f361c428ca6d980a595d646bf862ee
572,492
def hamming_distance(s1, s2) -> int: """Return the Hamming distance between equal-length sequences.""" if len(s1) != len(s2): raise ValueError('Unequal lengths of input objects') return sum((x != y) for x, y in zip(s1, s2))
f1bf4b7b54374eee579aa71c39e3fa4a7600250c
572,493
def _row_norm(df): """ >>> df = pd.DataFrame({ ... 'cell-1': {'a':8, 'b':1, 'c': 7}, ... 'cell-2': {'a':1, 'b':1, 'c': 1}, ... 'cell-3': {'a':10, 'b':1, 'c': 10} ... }) >>> _row_norm(df) cell-1 cell-2 cell-3 a 0.8 0.1 1.0 b 1.0 1.0 1.0 c ...
096e03b189d206417524a1baafc32ffadc4f8e6b
572,494
def transition_model(corpus, page, damping_factor): """ Return a probability distribution over which page to visit next, given a current page. With probability `damping_factor`, choose a link at random linked to by `page`. With probability `1 - damping_factor`, choose a link at random chosen fr...
457f1cbd3a1b35033943eef81b570ab745440a6d
572,495
def done_or_not(board): """Check if Sudoku board is valid or not. Keyword arguments: board -- Sudoku board as a list[list_lines] Return "Finished!" if the board is valid, otherwise return "Try again!". """ for x in range(9): if ( # Rows len(set(board[x])) < 9 or...
937e1693a3678131cc6308a6e10df3d96fc8833f
572,502
def from_db(v): """dB to linear """ return 10**(float(v)/10.0)
1ef07367cb2dc6e2cf8900606763b353803a25df
572,504
import requests import json def search_entities(entities, language="en"): """ Search for item ID and property ID on Wikidata. Take entities dictionary, search on Wikidata for the lemmas of the item and the property through an API call to wbsearchentities. Parameters: entities (dict): diction...
b44392ae4159e16cefce8d1b5b2e775aa416a394
572,505
def infinite_slope(vector_one, vector_two): """Check if provided vectors for line imply an infinite slope""" return(vector_one[0] == vector_two[0])
29b42035b84f9f9cf651f5ddd3b9c18f75a8d500
572,508
def accuracy(logits, targets, padding_idx=None): """ logits: (batch_size, max_len, vocab_size) targets: (batch_size, max_len) """ _, preds = logits.max(dim=2) trues = (preds == targets).float() if padding_idx is not None: weights = targets.ne(padding_idx).float() acc = (weigh...
4698b4ab850ef417156f4870e733fae574ab981c
572,509
import math def _get_distance(pos1, pos2): """ Returns distance between two points Params : pos1 : tuple in (x,y) format pos2 : tuple in (x,y) format """ return math.sqrt((pos2[0]-pos1[0])**2 + (pos2[1]-pos1[1])**2)
aac00ed10c2e627a2a67e08b09ab1b957655bd13
572,511
def overlap(r1, r2, construct=range): """ Overlap of two ranges. For two ranges *r1* and *r2* return the normalized range corresponding to the intersection ot the sets (of consecutive integers) corresponding to *r1* and *r2* Return a normalized result, which is either None, or an object constr...
9047cb8ac6d5cf6a3f5982f11702f68b6111ae16
572,515
import re def get_value(str2search, filename): """Return the float value corresponding to the first occurence of 'str2search' in 'filename'.""" file = open(filename, 'r', encoding='latin-1') value = None for line in file: if str2search in line: value = re.findall(r"\d+\.\d+", line...
808768a94b93b1a5efd564e42278d47cc6b2be14
572,519
def get_primary_dep(config, dep_tasks): """Find the dependent task to inherit attributes from. If ``primary-dependency`` is defined in ``kind.yml`` and is a string, then find the first dep with that task kind and return it. If it is defined and is a list, the first kind in that list with a matching dep ...
607cd6829c66027fecba9d4caeb93bb4c44bc287
572,520
def hello(name: str = "World") -> str: """Provide a name, return a greeting.""" return f"Hello, {name}!"
2aaf9dbc29cdc4584253ee3fa74efb49dadc1aa2
572,521
import requests def read_url(url: str) -> str: """ Return url contents. :param url: URL for request :return: return response content string """ cal_data = requests.get(url).text return cal_data
efe617722ddde37b2ba5e39eca3d3bdfa311f015
572,525
def _swapxy(data): """Helper function to swap x and y coordinates""" return [(y, x) for (x, y) in data]
cfa759a702ca8e8d50779b459326df9d0b4ecb5a
572,527
def get_pp_grid(cv, vals): """ Return a point that gives a particular CV, when the collective variables are defined through a grid. Parameters ---------- cv : array The target cv. vals : list A list of the line vectors defining the CV. Returns ------- pp : array ...
f9920bff735671413c7a143a14642b4ccd8f400f
572,541
from urllib.parse import urljoin, urlsplit def make_absolutizing_url_mutator(baseurl): """Return a function that makes relative URLs absolute. Parameters ---------- baseurl : string, absolute URL The absolute URL with which to combine relative URLs Returns ------- A mutator funct...
b0068a6fdc9784a3322b24f1835edb480f81a19d
572,542
def load_frame_counts(fpath): """Load mapping from URIs to frame counts from ``fpath``. The file is expected to be in the format of a Kaldi ``utt2num_frames`` file; that is, two space-delimited columns: - URI - frame count """ frame_counts = {} with open(fpath, 'r') as f: for l...
9010b1058db3c94733919425d8e56203d06284ad
572,550
import string def tamper(payload, **kwargs): """ Converts all characters in a given payload to overlong UTF8 (not processing already encoded) (e.g. SELECT -> %C1%93%C1%85%C1%8C%C1%85%C1%83%C1%94) Reference: * https://www.acunetix.com/vulnerabilities/unicode-transformation-issues/ * https:...
ead1a99a6a8a528a4fd93b42961d7afa2f59b6be
572,551
def getPopScores(population, fitness=False): """ Returns a list of population scores Example: >>> lst = Interaction.getPopScores(population) :param population: population object (:class:`GPopulation.GPopulation`) :param fitness: if is True, the fitness score will be used, otherwise, the raw. :rty...
337c5e5af6e24a3694cf16306596288815bc3ac9
572,554
import netrc def get_credentials_from_netrc(*, hostname, netrc_file=None): """Fetch username and password stored on netrc file, for accessing a service.""" credentials = netrc.netrc(file=netrc_file).authenticators(hostname) if credentials is None: return None, None return credentials[0], cred...
69c94e800e5b35b0de32feb60bbd042cbc18b694
572,557
def get_Sigma_powerlaw_params(param_dict): """ Extract and return parameters from dictionary for powerlaw form """ rScale = param_dict['rScale'] rc = param_dict['rc'] sScale = param_dict['sScale'] sigma = param_dict['sigma'] return rScale, rc, sScale, sigma
36912793721a11121b5ef0fcdd44d9185d3ccdfc
572,558
def rivers_with_station(stations): #sam """ Function that returns a set of names of rivers that have an associated monitoring station. """ List_of_rivers =set() #initialate a new empty set for s in stations: #loop in side the sta...
4cf5c3d055b281d1e3c93a0e404a6b70eca88875
572,560
def bs (link): """ Replace \\ with \\\\ because RST wants it that way. """ # phpdomain does not grok leading backslashes link = link.lstrip ('\\') return link.replace ('\\', '\\\\')
d0865b317def34621d1a00b7c56f313925724ef7
572,561
from typing import Iterable def dictify_chunk_size(shape, chunk_size): """ Given chunk_size which may be a tuple or dict, return a dict type all the same. :param shape: tensor's shape :param chunk_size: if dict provided, it's dimension id to chunk size; if provided, it's the ch...
e80f16df01cf01803c1160c1cf6a2094a54f6efb
572,563
from typing import Union from typing import Sequence from typing import Tuple def _validate_inputs( reference_corpus: Union[Sequence[str], Sequence[Sequence[str]]], hypothesis_corpus: Union[str, Sequence[str]], ) -> Tuple[Sequence[Sequence[str]], Sequence[str]]: """Check and update (if needed) the format ...
c92c428fa55c7e8902a1f96d1f6663a7d372c86a
572,564
def dict_clean(input_dict): """Removes empty dictionary keys from a dictionary and returns a cleaned up dictionary. Empty meaning an empty list, string or dict or a None value. Args: input_dict (dict):The input dictionary. Returns: dict: The cleaned dictionary """ stripped_dict...
bb390a81351af6c2c8b0188a09d82eb9021646fd
572,565
def doms(u, v): """Return -1 if u dominates v, 1 if v dominates u and 0 otherwise. u dominates v if all(u <= v) and any(u < v), i.e., in minimisation sense. """ assert len(u) == len(v) sg = 0 for ui, vi in zip(u, v): if ui == vi: continue s = -1 if ui < vi else 1 ...
90ad910f76e6c68b3bf41608ce4a503ecf503c09
572,570
def map_to_2D_dict(mapping_data): """ Converts mapping file to 2D dictionary INPUT: mapping_data -- a tab delimited string from the opened mapping file OUTPUT: D2 -- a two dimensional dictionary where each sample ID is keyed to a dictionary of meta data containing heade...
6bae110f1e6cc960968afaf4744ef59ecca5f2fb
572,573
def to_curl(request, headers="simple", print_it=True): """ Get a curl string from a python request. :param request: a requests.models.Response or a requests.models.Response.request object :param headers: headers to include in the curl request (the "-H" args). Specified by a {header_n...
3e91e07418e4e1edaaf8acf483e80675972ef9b0
572,576
def get_fasta_ids(fasta): """Get the IDS from a FASTA file.""" idset = set() with fasta.open() as fasta_fh: for line in fasta_fh: if line.startswith(">"): idset.add(line.split()[0][1:]) return list(idset)
13ae4543546cb5b6cb8794bc415ccda6344cf2d1
572,578
def per_capita_TED(sum_12_mo): """Calculates final Peak Hour Excessive Delay number. Args: sum_12_mo, the integer sum of all TED values. Returns: A value for Peak Hour Excessive Delay per capita. """ print(sum_12_mo) pop_PDX = 1577456 return sum_12_mo / pop_PDX
3b084908a0caf3da2a425d9805bda78a04b6ee54
572,584
def get_plant_states(plant_ids, pudl_out): """ Determine what set of states a given set of EIA plant IDs are within. If you only want to select data about a particular set of power plants from the EPA CEMS data, this is useful for identifying which patitions of the Parquet dataset you will need to ...
f9d7c0f8e80fe15cc6a678aa0ff5dfdb7c51d3b5
572,585
def p_observe_errors(_1, _2, _3, state): """ Calculate the error between the redemption and market price. """ error = (state["pid_state"].redemption_price - state["market_price"]) return {"error_star": error}
b0b102695cc25c32860aa9bbb83c6141c09bcc07
572,587
def xor(a, b): """XOR two byte sequences together.""" return bytes(za ^ zb for za, zb in zip(a, b))
b72b70b8b03daca129321a24f9abc41093abd85a
572,590
import requests def extract_text(file): """ Extracts text from file using Tika Server. Args: file: File bytes object. Returns: dict: Tika response dictionary. """ tika_response = requests.put( url=f'http://127.0.0.1:80/tika', data=file, headers={ ...
dbc8d2cda9693d6e04e0599e0b85a4528ecd1d1d
572,591
def map_trigger(library, session, trigger_source, trigger_destination, mode): """Map the specified trigger source line to the specified destination line. Corresponds to viMapTrigger function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identif...
123129994ce24ea641d7dc863c0cf91393ef7d4c
572,592
def _mobius(p, q): """ Applies the mobius transformation that fixes the line from q to the origin and sends q to the origin to the point p. Parameters ---------- p : list of floats, length 2 The coordinate we are applying this transformation to. q : list of floats, length 2 The ...
190296816b2bc9403fdfcb362862c6e062502914
572,597
def first_upper_case(words): """ Set First character of each word to UPPER case. """ return [w.capitalize() for w in words]
9d945a86afcaee2c828c53beba748520561da6cc
572,600
import yaml def load_config(config_file): """Convert YAML file into Python Object.""" config_text = config_file.read_text() config = yaml.safe_load(config_text) return config
b5c2cf4c5aa36067a1f10ef4ba86df41f363cfb7
572,602
from typing import Iterable from typing import Dict from typing import OrderedDict def create_schema_baseline(statements: Iterable[Dict]) -> Dict: """Function for getting the baseline schema configuration based on create schema statements :param List[Dict] statements: The statements upon which to base the co...
5df92f04c56b4bd1b19723314f934f9863e9870c
572,605
from typing import Set from typing import Dict def scaffold_overlap(indices_1: Set[int], indices_2: Set[int], index_to_scaffold: Dict[int, str]) -> float: """ Computes the proportion of indices in indices_2 which have a scaffold in indices_1. :param indices_1: A ...
f2bedb31fd9a8990358ba779366388809e30ba74
572,607
def subset(df, items, axis=1): """ Constructs a dataframe is a subset to the items, by row or column. Parameters ---------- df: pd.DataFrame items: list columns if axis = 1 indices if axis = 0 axis: int 0 - rows 1 - columns Returns ------- pd.DataFrame """ if axis == ...
f6ad0496b26d34d967659e79a97920c6ff6f94b1
572,609
def any_of(*args): """Return regex that matches any of the input regex patterns. The returned value is equivalent to writing:: r'(<arg1>|<arg2>|...)' """ return "({})".format("|".join(args))
b6c2537b27e7ab9e5a99b6030e384cb363fd3a45
572,610
from typing import Any def is_not_empty(obj: Any) -> bool: """Determine if object is not None and is length is > 0 :param obj: object :return: if object is not None and length is > 0 """ return obj is not None and len(obj) > 0
88550fc9b8ea4c8cfcebb440dc1b414994353a41
572,612
def _is_bimolecular(reaction): """ Determines if a reaction is bimolecular """ reactants = reaction[0] isbimol = bool(len(reactants) == 2) return isbimol
59ff1196b28dbecaed4b703302e1e3a527c0a684
572,616
def rgb2int(rgb_tuple): """Return the int number of a color from (r,g,b), with 0<r<1 etc.""" rgb = (int(rgb_tuple[0] * 255), int(rgb_tuple[1] * 255), int(rgb_tuple[2] * 255)) return 65536 * rgb[0] + 256 * rgb[1] + rgb[2]
63694ba06b720fc6c84305cb0aa8cdc6d4befbfe
572,618
import torch import math def cauchy_icdf(p, loc, scale): """ Compute the componentwise inverse cdf of a cauchy with mean as loc and variance as scale. Parameters ---------- p: float(s) Probability value in [0,1] loc: float(s) The mean of the distri...
e8f1a2125326ac1ad2df56278a1348f0cd94433a
572,619
def standardize_punctuation(text: str) -> str: """Standardizes punctuation in the text. Args: text: Input text. Returns: Punctuation-standardized text. """ text = text.replace("’", "'") text = text.replace("`", "'") text = text.replace("“", '"') text = text.replace("”",...
2bd142fe27e9846b5b4c3840d96b55bf4c83b4f9
572,637
def flatten(numbers): """ Flatten the read count dictionary into arrays for curve fitting. :param numbers: defaultdict(list) - read counts :return: list, list - list of allele numbers and list of corresponding read counts """ x = [] y = [] for k, v in numbers.items(): y.extend(v)...
2a34def1b23858154a23fb288670182b0da44282
572,640
def merge_deps(old, new): """ Merge two dependency lists. The lists are partially ordered, with all dependents coming after the items they depend on, but otherwise order doesn't matter. The merged list preserves the partial ordering. So if old and new both include the item "c", then all items that...
a51c754c91952aca190cf27e060326286d81b687
572,643
def make_into_set(iter_of_dict): """ Convenience function that turns an iterator of dicts into a set of frozenset of the dict items. """ return set(frozenset(dict_.items()) for dict_ in iter_of_dict)
2fffec3f644f942aed932f18902b84c5d0e123d9
572,646
from pathlib import Path def readbytes(path): """Read file contents and return as |bytes|. .. versionchanged:: 2.1 `path` can now be |Path| or |str|. Previously, it had to be |str|. Parameters ---------- path |str| or |Path| -- Path to file to be opened. Returns ------...
d1df92f04474542b80924c6747433732edd98357
572,647
def convert_chrome_cookie(cookie): """Convert a cookie from Chrome to a CookieJar format type""" return { 'name': cookie['name'], 'value': cookie['value'], 'domain': cookie['domain'], 'path': cookie['path'], 'secure': cookie['secure'], 'expires': int(cookie['expir...
47565be83b22e55ddcd63a7f755948f617578621
572,650