content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_tl_num_size(val: int) -> int:
"""
Calculate the length of a TL variable.
:param val: an integer standing for Type or Length.
:return: The length of var.
"""
if val <= 0xFC:
return 1
elif val <= 0xFFFF:
return 3
elif val <= 0xFFFFFFFF:
return 5
else:
... | 4a11da075f57d98b2956e7932adf0cc9a14645a7 | 27,712 |
def dict2yaml(yaml_dict: dict) -> str:
"""
Convert the YAML dict into the YAML front matter string.
Parameters
----------
yaml_dict : dict
Dict made from the YAML front matter.
Returns
-------
str
YAML front matter into string.
"""
yaml_text = "---\n"
for i ... | b2bfd40ad5f45f2725384a9de12fbfcc0d7fe9d1 | 27,715 |
def remove_rectangle(rlist, u_low, u):
"""
Function to remove non-optimal rectangle
from the list of rectangles
Parameters
----------
rlist : list
List of rectangles.
u_low : list
Lower bound of the rectangle to remove.
u : list
Upper bound of the rectangle to re... | 4353fc9bb1187b565abcb5932465940ada6ad678 | 27,717 |
def lcp(s1, s2):
"""Return the length of the longest common prefix
between strings `s1` and `s2`."""
comp = 0
for i in range(min(len(s1), len(s2))):
if s1[i] != s2[i]:
break
comp += 1
return comp | dae5fbe70e9684f7e9a336adbd4e74d874dd52f5 | 27,718 |
import torch
def pr(x, y):
""" Metrics calculation from: https://en.wikipedia.org/wiki/Confusion_matrix
Returns precision, recall, specificity and f1 (in that order)
"""
tp = ((x == y) * (x == 1)).sum().to(torch.float32)
tn = ((x == y) * (x == 0)).sum().to(torch.float32)
fp = ((x != y) * (... | b2095585e3283b8c301c992ea241158c612b4d3b | 27,719 |
import re
def _strip_ken_suffix(name):
"""
>>> _strip_ken_suffix('Akita ken')
'Akita'
>>> _strip_ken_suffix('Akita-ken')
'Akita'
>>> _strip_ken_suffix('Akita Prefecture')
'Akita'
"""
return re.sub(r'[- ](ken|prefecture)', '', name, flags=re.IGNORECASE) | 736dae9f335d5a22e3faace4e947ec02798d3fa2 | 27,721 |
from typing import OrderedDict
import six
def BuildFullMapUpdate(clear, remove_keys, set_entries, initial_entries,
entry_cls, env_builder):
"""Builds the patch environment for an environment update.
To be used when BuildPartialUpdate cannot be used due to lack of support for
field masks ... | dd43cfe6db69076c61a211d9534f0a5624f76246 | 27,722 |
def exception_match(x, y):
"""Check the relation between two given exception `x`, `y`:
- `x` equals to `y`
- `x` is a subclass/instance of `y`
Note that `BaseException` should be considered.
e.g. `GeneratorExit` is a subclass of `BaseException` but which is not a
subclass of `Exception`, and i... | 6ea965c70c9980834a4b31baac802b5bad295e2a | 27,728 |
import math
def trunc(value, decimals=0):
"""Truncates values after a number of decimal points
:param value: number to truncate
:type value: float
:param decimals: number of decimals points to keep
:type decimals: int
:return: truncated float
:rtype: float
"""
step = 10 ** decimal... | fda9289eae3274b7c8cb1bd172032fc3c0e7f8f0 | 27,730 |
def identifier_to_label(identifier):
"""Tries to convert an identifier to a more human readable text label.
Replaces underscores by spaces and may do other tweaks.
"""
txt = identifier.replace("_", " ")
txt = txt.replace(" id", "ID")
txt = dict(url="URL").get(txt, txt)
txt = txt[0].upper() +... | 8dbbac38e4e0408354128bf8da0dabbf72d785ae | 27,734 |
def standings_to_str(standings):
"""Format standings list as string. Use enumerate()
index value both to display place. Ties receive the
same place value.
Format: "<place>. <team name> (<points>)\n"
Parameters:
standings (list): team standings
Returns:
str: formatted string re... | be19aff13a20c0c421bf4b58a8f309d36ab9d973 | 27,737 |
def getGameFromCharacter(cname: str) -> str:
"""Return a query to get games with equal Ryu Number to a character.
The query will retrieve the title and Ryu Number of a game whose Ryu
Number is exactly equal to the Ryu Number of the character whose name is
passed. This is used primarily for path-f... | 22e6a5702f69d3d7ca391add6144c8e19734c5a9 | 27,738 |
def is_valid_cidr_netmask(cidr_netmask: str) -> bool:
"""
This function will check that the netmask given in
parameter is a correct mask for IPv4 IP address.
Using to verify a netmask in CIDR (/24) format.
:param cidr_netmask: Netmask to check
:return bool: True if the netmask is valid
"""
... | 3e63d4cf2e9d748977230f7b9c26bf6e1440d313 | 27,739 |
from typing import List
def clean_authors(authors_list: List[str], sign: str) -> List[str]:
"""
Cleans a list of author names by splliting them based on a given sign.
Args:
authors_list (:obj:`List[str]`):
A list of author names.
sign (:obj:`str`):
Sign that separ... | 65d7e625d0e7e98f95c3e2ae4877d5d744518686 | 27,741 |
def _get_crash_key(crash_result):
"""Return a unique identifier for a crash."""
return f'{crash_result.crash_type}:{crash_result.crash_state}' | 0f2472bf984440bb27cd94e1e3fb132529b4fad1 | 27,742 |
def midpoint(A, B):
""" calculates the midpoint between 2 points"""
return (A[0]+B[0])/2, (A[1]+B[1])/2, (A[2]+B[2])/2; | d9895cfed02a86b3a0b9117ff6e697d69c173a96 | 27,743 |
from typing import List
def filter_stacktrace(stacktrace: List[str]) -> List[str]:
"""Removes those frames from a formatted stacktrace that are located
within the DHParser-code."""
n = 0
for n, frame in enumerate(stacktrace):
i = frame.find('"')
k = frame.find('"', i + 1)
if fr... | ac92251eadc4f53c3a2f14e7386c38ee2aa70e17 | 27,744 |
def avg(iter, key=None, percent=0.0):
"""
自定义求平均值
:param iter:
:param key:
:param percent: 去除百分比(将列表中的最大最小值去掉一定后再计算平均值)
:return:
"""
nlen = len(iter)
if nlen == 0:
return 0
# 要去除的数据
del_num = int(nlen * percent / 2)
if del_num >= nlen:
return 0
new_it... | 6305c908d4726412843b5fa936daf04e313096de | 27,748 |
from typing import List
def is_course_section_row(row_cols: List, time_index: int) -> bool:
"""Determines if a row in a course table contains data for a course section.
:param row_cols: A row in a course table.
:param time_index: The column index where the time data is possibly stored.
:return: True ... | 640c92bf289d0b9734912140d6624ce639c05e39 | 27,752 |
def readline(string):
"""
read a line from string
"""
x = ""
i = 0
while i < len(string):
if string[i] != "\n":
x += string[i]
i += 1
else:
return x + "\n"
return x | 67a081e2cba9e791ebcf3d60e42222a89d7c5429 | 27,753 |
import hashlib
def _hashdigest(message, salt):
""" Compute the hexadecimal digest of a message using the SHA256 algorithm."""
processor = hashlib.sha256()
processor.update(salt.encode("utf8"))
processor.update(message.encode("utf8"))
return processor.hexdigest() | 2c9c5886d72700826da11a62f4cc9c82c2078090 | 27,757 |
def inv_permutation(permutation):
"""Get the inverse of a permutation. Used to invert a transposition for example.
Args:
permutation (list or tuple): permutation to invert.
Returns:
list
"""
inverse = [0] * len(permutation)
for i, p in enumerate(permutation):
inverse[p]... | ab75f150d9df12d6bbec64fbe4744d962b9de1c6 | 27,760 |
def parent_user_password(db, parent_user):
"""Creates a parent website user with a password."""
user = parent_user
user.set_password('password')
user.save()
return user | 56718190793179034d5cce86e5bc6060c8d5d5a2 | 27,761 |
def _get_val_list(obj, path_list, reverse=False):
"""Extract values from nested objects by attribute names.
Objects contain attributes which are named references to objects. This will descend
down a tree of nested objects, starting at the given object, following the given
path.
Args:
obj: ob... | b66c7242db6c02340a2b8b2d92d842894990891b | 27,764 |
def remove_all_None(a_list):
"""Remove all None values from a list."""
# type: (list) -> list
return [item for item in a_list if item is not None] | 15eaeb7ef0208f3cd5519534bf155c62da88d3d5 | 27,765 |
def _get_ids(records, key):
"""Utility method to extract list of Ids from Bulk API insert/query result.
Args:
records (:obj:`list`): List of records from a Bulk API insert or SOQL query.
key (:obj:`str`): Key to extract - 'Id' for queries or 'id' for inserted data.
Returns:
(:obj:`... | 2fe90c06a7458af49db87d2ee01350e065920113 | 27,766 |
def get_params_for_component(params, component):
"""
Returns a dictionary of all params for one component defined
in params in the form component__param: value
e.g.
>> params = {"vec__min_df": 1, "clf__probability": True}
>> get_params_for_component(params, "vec")
{"min_df": 1}
"""
... | aefee29c848fecab432efc74acd3d1bcaf80e539 | 27,773 |
import re
def try_include(line):
"""
Checks to see if the given line is an include. If so return the
included filename, otherwise None.
"""
match = re.match('^#include\s*[<"]?(.*)[>"]?$', line)
return match.group(1) if match else None | f30c885ffa783f78f5a71dc1906ac6e158226361 | 27,775 |
from typing import Dict
from pathlib import Path
import json
def get_config() -> Dict:
"""Load config file from disk as python dict and return it. File is
expected to exist on the same path as this source file.
"""
with open(
Path(Path(__file__).parent, "config.json").resolve(),
"r",
... | 68a0a11ddfea137b1ede61686df630e1d9735c21 | 27,777 |
def get_filename_without_extension(filename):
"""
Returns the name of the 'filename', removing any extension. Here, an extension is indicated by a *dot*,
e.g. 'file.txt' where 'file' denotes the name and 'txt' is the extension.
If multiple extensions exist, only the last one is removed. In case no exte... | 7359be82706b1aa041c3559293db8e8cfe49f157 | 27,779 |
def make_variable_batch_size(num_inputs, onnx_model):
"""
Changes the input batch dimension to a string, which makes it variable.
Tensorflow interpretes this as the "?" shape.
`num_inputs` must be specified because `onnx_model.graph.input` is a list
of inputs of all layers and not just model inputs.... | e503ea83cac31c33fff0cee6909e7f6640acf4b5 | 27,781 |
def power(x, n):
"""
计算幂的递归算法 x^n = x * x^(n-1)
时间复杂度 O(n)
:param x:
:param n:
:return:
"""
if n == 0:
return 1
else:
return x*power(x, n-1) | 5772fc4ccd1e392f7e8cff4a6068b4cf21989312 | 27,789 |
def filter_list(values, excludes):
"""
Filter a list of values excluding all elements from excludes parameters and return the new list.
Arguments:
values : list
excludes : list
Returns:
list
"""
return list(x for x in values if x not in excludes) | 68f25fe3afd4faebeefde7639a2b3d5885255e6a | 27,796 |
def _process_scopes(scopes):
"""Parse a scopes list into a set of all scopes and a set of sufficient scope sets.
scopes: A list of strings, each of which is a space-separated list of scopes.
Examples: ['scope1']
['scope1', 'scope2']
['scope1', 'scope2 scope3']
Retu... | 85fa5d8f761358225343f75e1c1dfa531e661eb3 | 27,797 |
import hashlib
def tagged_hash_init(tag: str, data: bytes = b""):
"""Prepares a tagged hash function to digest extra data"""
hashtag = hashlib.sha256(tag.encode()).digest()
h = hashlib.sha256(hashtag + hashtag + data)
return h | 955cc9fe6082d56663b9cd3531b0bb75aa2af472 | 27,798 |
import math
def GsoAzimuth(fss_lat, fss_lon, sat_lon):
"""Computes the azimuth angle from earth station toward GSO satellite.
Based on Appendix D of FCC 05-56.
Inputs:
fss_lat: Latitude of earth station (degrees)
fss_lon: Longitude of earth station (degrees)
sat_lon: Longitude of satellite (... | f8761e3529f75a02d90369b5f8aa353f22bbc599 | 27,808 |
def read_file(path):
"""Read file."""
with open(path) as _file:
return _file.read() | bed1e255478c6d43d84240e1c1969aa3c1bc21f3 | 27,813 |
def constrain(val, min_val, max_val):
"""
Method to constrain values to between the min_val and max_val.
Keyword arguments:
val -- The unconstrained value
min_val -- The lowest allowed value
max_val -- The highest allowed value
"""
return min(max_val, max(min_val, val)) | 655cc16ad425b6ca308d3edbd2881a3923ef195e | 27,814 |
from typing import Counter
def small_class(raw_data, labels, threshold=20):
"""Removes samples and classes for classes that have less than
`threshold` number of samples."""
counts = Counter(labels)
data, n_labels = [], []
for i, l in enumerate(labels):
if counts[l] >= threshold:
... | cf80bd67ccc3d69baf0b71f226c8b56ef5b80e7c | 27,818 |
def rescale_size(size, scale, return_scale=False):
"""
Compute the new size to be rescaled to.
Args:
size (tuple[int]): The original size in the form of
``(width, height)``.
scale (int | tuple[int]): The scaling factor or the maximum size. If
it is a number, the imag... | 4baa26011ab191c4adca963c5ad7b6e63941b740 | 27,820 |
def compose(f, g):
"""Function composition.
``compose(f, g) -> f . g``
>>> add_2 = lambda a: a + 2
>>> mul_5 = lambda a: a * 5
>>> mul_5_add_2 = compose(add_2, mul_5)
>>> mul_5_add_2(1)
7
>>> add_2_mul_5 = compose(mul_5, add_2)
>>> add_2_mul_5(1)
15
"""
# pylint: disabl... | 053c1c6db1517a10ef0580268abb709441a71333 | 27,822 |
def keynat(string):
"""
A natural sort helper function for sort() and sorted()
without using regular expressions or exceptions.
>>> items = ('Z', 'a', '10th', '1st', '9')
>>> sorted(items)
['10th', '1st', '9', 'Z', 'a']
>>> sorted(items, key=keynat)
['1st', '9', '10th', 'a', 'Z']
... | fa8a1e52ae97ff78cecab0afe1050142fd12d18a | 27,826 |
def format_address(address):
"""Remove non alphanumeric/whitespace characers from restaurant address
but allows for commas
"""
return ''.join(chr for chr in address if chr.isalnum()
or chr.isspace() or chr == ",") | 6cb191b6672744dfedb570fa1e85f85876fa2895 | 27,832 |
import pickle
def load_pickled_data(path):
"""Load in a pickled data file
Args
----
path (str) : path to the file to read
Returns
-------
the data object
"""
with open(path, "rb") as f:
data = pickle.load(f)
return data | 18a4c352d14762c4b52dc205336a49a2c88cfbc1 | 27,833 |
def get_outputs(lst, uses, seen):
"""Return the list of nodes whose values are required beyond this segment.
Arguments:
lst: list of nodes (the segment)
uses: dict mapping each node to its uses (globally)
seen: set of nodes that are part of the segment
"""
outputs = []
for ... | 03d6c859bb70aa5ce868b9c71ff7ce6092d52604 | 27,837 |
def get_matches_metadata(infile):
"""
Reads match IDs and metadata from a filename.
Args:
infile: Filename where match IDs and metadata are stored (string).
Returns:
List of dicts with IDs and metadata for each match.
"""
out = []
with open(infile, "r") as file:
lines... | c9b70b40ea0c1ada0af0b6b9c6fbb7e3d95d83e5 | 27,844 |
def lmParamToPoint(a, c):
""" Return the coordinates of a landmark from its line parameters.
Wall landmarks are characterized by the point corresponding to the
intersection of the wall line and its perpendicular passing through the
origin (0, 0). The wall line is characterized by a vector (a, c) such a... | 6b98613216f1287ed9b25f1345ea0a18aa0fc90b | 27,847 |
from typing import Any
from typing import Callable
def pipe(in_: Any, *args: Callable[[Any], Any]) -> Any:
"""Basic pipe functionality
Example usage:
>>> pipe(
... [True, False, 1, 3],
... all,
... lambda x: "It's true" if x else "They lie"
... )
'They lie'
"""
for func... | 8eff195886ec9daf8391532cb21dc61182462c34 | 27,848 |
from re import X
def label_data(frame, model):
"""Predict cluster label for each tract"""
frame["cluster"] = model.predict(X)
ix = ["geoid", "state_abbr", "logrecno", "geo_label", "cluster"]
return frame.reset_index().set_index(ix) | 7a27a0722394b90aba237a821be3d2a5730403c0 | 27,856 |
def rel_2_pil(rel_coords, w, h):
"""Scales up the relative coordinates to x1, y1, x2, y2"""
x1, x2, y1, y2 = rel_coords
return [int(x) for x in [x1 * w, y1 * h, x2 * w, y2 * h]] | f619f4a0920db503401abdd0cfd86b61116c4992 | 27,858 |
import time
def datetime_format(epoch):
"""
Convert a unix epoch in a formatted date/time string
"""
datetime_fmt = '%Y-%m-%dT%H:%M:%SZ'
return time.strftime(datetime_fmt, time.gmtime(epoch)) | e45f7874bebdbe99a1e17e5eb41c5c92e15a96b3 | 27,859 |
def count_genes_in_pathway(pathways_gene_sets, genes):
"""Calculate how many of the genes are associated to each pathway gene set.
:param dict pathways_gene_sets: pathways and their gene sets
:param set genes: genes queried
:rtype: dict
"""
return {
pathway: len(gene_set.intersection(ge... | bb3859c9a6b8c17448a6cbcc3a85fc315abbab31 | 27,861 |
import unittest
import inspect
def AbstractTestCase(name, cls):
"""Support tests for abstract base classes.
To be used as base class when defining test cases for abstract
class implementations. cls will be bound to the attribute `name`
in the returned base class. This allows tests in the subclass to
... | 66641e3c9d805946880ac8dfc41827f51986f6aa | 27,863 |
import itertools
def flat_map(visitor, collection):
"""Flat map operation where returned iterables are flatted.
Args:
visitor: Function to apply.
collection: The collection over which to apply the function.
Returns:
Flattened results of applying visitor to the collection.
"""
... | 5501e4adc18ca8b45081df4158bcd47491743f29 | 27,868 |
def hex_sans_prefix(number):
"""Generates a hexadecimal string from a base-10 number without the standard '0x' prefix."""
return hex(number)[2:] | 6faaec36b2b3d419e48b39f36c1593297710a0a4 | 27,869 |
def curly_bracket_to_img_link(cb):
"""
Takes the curly-bracket notation for some mana type
and creates the appropriate image html tag.
"""
file_safe_name = cb[1:-1].replace('/', '_').replace(' ', '_')
ext = 'png' if 'Phyrexian' in file_safe_name or file_safe_name in ('C', 'E') else 'gif'
ret... | 99a1a7ebf6318d2fbc9c2c24035e5115829b6feb | 27,872 |
def name_options(options, base_name):
"""Construct a dictionary that has a name entry if options has name_postfix"""
postfix = options.get("name_postfix")
if postfix is not None:
return { "name": base_name + str(postfix) }
return {} | c5db1619fa951298743e28c78b8f62165b5d09de | 27,876 |
def first_index(keys, key_part):
"""Find first item in iterable containing part of the string
Parameters
----------
keys : Iterable[str]
Iterable with strings to search through
key_part : str
String to look for
Returns
-------
int
Returns index of first element ... | 45b41954e795ee5f110a30096aa74ea91f8e6399 | 27,879 |
def _calc_shape(original_shape, stride, kernel_size):
"""
Helper function that calculate image height and width after convolution.
"""
shape = [(original_shape[0] - kernel_size) // stride + 1,
(original_shape[1] - kernel_size) // stride + 1]
return shape | 46a40efec8c7163ead92425f9a884981e6a4a8bc | 27,880 |
def needs_column_encoding(mode):
"""
Returns True, if an encoding mode needs a column word embedding vector, otherwise False
"""
return mode in ["one-hot-column-centroid",
"unary-column-centroid",
"unary-column-partial",
"unary-random-dim"] | d5642d03628357508be87e227c5a9edf8e65da2d | 27,881 |
import json
def decode_frame(frame, tags=None):
""" Extract tag values from frame
:param frame: bytes or str object
:param tags: specific tags to extract from frame
:return: dictionary of values
"""
# extract string and convert to JSON dict
framebytes = frame if isinstance(frame, bytes) e... | 1e239c380c7050ff536aa7bfc1cd0b0a01959f39 | 27,884 |
import textwrap
def construct_using_clause(metarels, join_hint, index_hint):
"""
Create a Cypher query clause that gives the planner hints to speed up the query
Parameters
----------
metarels : a metarels or MetaPath object
the metapath to create the clause for
join_hint : 'midpoint',... | 61c4dc58782aeb1bc31affb7ec2c74361eac8089 | 27,889 |
from typing import List
import torch
def import_smallsemi_format(lines: List[str]) -> torch.Tensor:
"""
imports lines in a format used by ``smallsemi`` `GAP package`.
Format description:
* filename is of a form ``data[n].gl``, :math:`1<=n<=7`
* lines are separated by a pair of symbols ``\\r\\n``
... | 2ca9708944379633162f6ef9b4df3357bca77e80 | 27,891 |
import re
def load_tolerances(fname):
""" Load a dictionary with custom RMS limits.
Dict keys are file (base)names, values are RMS limits to compare.
"""
regexp = r'(?P<name>\w+\.png)\s+(?P<tol>[0-9\.]+)'
dct = {}
with open(fname, 'r') as f:
for line in f:
... | 60af52ec49cadfdb5d0f23b6fa5618e7cc64b4c2 | 27,897 |
def is_list(input_check):
"""
helper function to check if the given
parameter is a list
"""
return isinstance(input_check, list) | 9ff5767c862a110d58587cccb641a04532c1a1a5 | 27,899 |
import re
def is_valid_hostname(hostname):
"""
Check if the parameter is a valid hostname.
:type hostname: str or bytearray
:param hostname: string to check
:rtype: boolean
"""
try:
if not isinstance(hostname, str):
hostname = hostname.decode('ascii', 'strict')
exc... | 31f16d1c648a230de3eb0f3158be42e0841db5a4 | 27,901 |
def _mgmtalgomac(rack, chassis, slot, idx, prefix=2):
""" Returns the string representation of an algorithmic mac address """
return "%02x:%02x:%02x:%02x:%02x:%02x" % (prefix, rack >> 8, rack & 0xFF, chassis, slot, idx << 4) | ea90898d50d5946abb6e0d6c678e876aa8b5f8cf | 27,902 |
def _model_insert_new_function_name(model):
"""Returns the name of the function to insert a new model object into the database"""
return '{}_insert_new'.format(model.get_table_name()) | bd3079813b266a4e792ea323ab59eb3ef377159e | 27,905 |
def create_dataverse_url(base_url, identifier):
"""Creates URL of Dataverse.
Example: https://data.aussda.at/dataverse/autnes
Parameters
----------
base_url : str
Base URL of Dataverse instance
identifier : str
Can either be a dataverse id (long), a dataverse alias (more
... | 8dcaacf58c7ca8b601ed2543f8d8de20bbcbc8a2 | 27,906 |
def isinsetf(s):
"""
Returns a function which tests whether an element is in a set `s`.
Examples
--------
>>> colors = ['red', 'green', 'blue']
>>> f = isinsetf(colors)
>>> map(f, ['yellow', 'green'])
[False, True]
"""
s = set(s)
return lambda e: e in s | 492f5381a66ef42670e5dd229c41a5481290114a | 27,910 |
import math
def f(n):
"""
Define f(n) as the sum of the digit factorials for given number n.
For example:
f(342) = 3! + 4! + 2! = 32
:param n: number
:return: sum digit factorial
"""
return sum(math.factorial(int(ch)) for ch in str(n)) | 334ca97a936876d79643cad70994c3da8cbee98e | 27,914 |
def createc_fbz(stm):
"""
Function returning Createc channel feedback z value
Parameters
----------
stm : createc.CreatecWin32
Createc instance
Returns
-------
value : str
"""
# from createc.Createc_pyCOM import CreatecWin32
# stm = CreatecWin32()
return stm.... | affda33fd1050fdf865544cfc66e3899788fccc2 | 27,922 |
def similar(x,y):
"""
function that checks for the similarity between the words of
two strings.
:param x: first string
:param y: second string
:return: returns a float number which is the result of the
division of the length of the intersection between the two strings'
wor... | 92edaf8ebcedcbfbb1adf2b87c8d00f159b3ccc8 | 27,923 |
from datetime import datetime
def convert_time(ts):
"""converts timestamps from time.time() into reasonable string format"""
return datetime.fromtimestamp(ts).strftime("%Y-%m-%d::%H:%M:%S") | 195124dac4c4c145c397fe8e4fd10d3ab3d6700f | 27,926 |
def get_nr_to_check(selection, line_scores):
"""
Gets the number of checks the annotators should do given a selection and a line_score
:param selection: selection of the lines to check
:param line_scores: the lines with the given score
:return: the number of checks that still need to be performed
... | 4560a1f6a8ab3671b73513e6eab193dd5300ec82 | 27,930 |
def read_pair_align(read1, read2):
""" Extract read pair locations as a fragment oriented in increasing chromosome coordinates
:param read1: read #1 of pair in pysam AlignedSegment format
:param read2: read #2 of pair in pysam AlignedSegment format
:return 4-item array in the following format: [fragA-s... | f9d1476330a8cf1c9e836654d67a8bcda9e18eb7 | 27,933 |
def getaxeslist(pidevice, axes):
"""Return list of 'axes'.
@type pidevice : pipython.gcscommands.GCSCommands
@param axes : Axis as string or list of them or None for all axes.
@return : List of axes from 'axes' or all axes or empty list.
"""
axes = pidevice.axes if axes is None else axes
if ... | 6a01538eb46a7f19efcc2bfb737bf1945ec4db52 | 27,942 |
import mimetypes
def is_html(path: str) -> bool:
"""
Determine whether a file is an HTML file or not.
:param path: the path to the file
:return: True or False
"""
(mime_type, _) = mimetypes.guess_type(path)
return mime_type in ('application/xhtml+xml', 'text/html') | bfd570f19c78447adf2ab28b2d94f1119922b97d | 27,945 |
def _next_set(args):
"""
Deterministically take one element from a set of sets
"""
# no dupes, deterministic order, larger sets first
items = sorted(list(map(frozenset, args)), key=lambda x: -len(x))
return items[0], set(items[1:]) | 37d1fdf1796d2b0b455f638bc8e03de030d668f0 | 27,951 |
def _get_figure_size(numaxes):
"""
Return the default figure size.
Width: 8 units
Height: 3 units for every subplot or max 9 units
Return
------
(width, height)
The figure size in inches.
"""
figure_width = 8
figure_height = max(6, min(numaxes * 3, 10))
return (figur... | bb6f3a08b974cac2d5da2b69eac8653e9b41411e | 27,957 |
def _simpsons_inner(f, a, f_a, b, f_b):
"""Calculate the inner term of the adaptive Simpson's method.
Parameters
----------
f : callable
Function to integrate.
a, b : float
Lower and upper bounds of the interval.
f_a, f_b : float
Values of `f` at `a` and `b`.
Return... | e0e9170b8030f8f5c2f66927b91b034d9cd4a82f | 27,958 |
def upload_to_dict(upload):
"""Creates a Python dict for an Upload database entity.
This is an admin-only function that exposes more database information than
the method on Upload.
"""
return dict(
id=upload.id,
flake=upload.flake,
filename=upload.filename,
mimetype=... | c6fdc5b53dbbc1fa28e64fb574c5a3919f5e780e | 27,963 |
def wrong_adjunction(left, right, cup):
""" Wrong adjunction error. """
return "There is no {0}({2}, {3}) in a rigid category. "\
"Maybe you meant {1}({2}, {3})?".format(
"Cup" if cup else "Cap", "Cap" if cup else "Cup", left, right) | 263684e737a3212a1d44fcd88ba719fc9f1c07a1 | 27,965 |
def magnify_contents(contents, features):
"""
Create additional features in each entry by replicating some column
of the original data. In order for the colums to differ from the
original data append a suffix different for each new additional
artificial column.
"""
magnified_contents = []
... | ec2a43cdb280da74b44a6fec96d0708c90d03f18 | 27,978 |
def binary_search(arr, first, last, element):
"""
Function to search an element in a given sorted list.
The function returns the index of the first occurrence of an element in the list.
If the element is not present, it returns -1.
Arguments
arr : list of elements
first : position of the fir... | d006f751bf13efe04d55ab72e166ea279bef9d3d | 27,979 |
def _as_list(arr):
"""Force being a list, ignore if already is."""
if isinstance(arr, list):
return arr
return [arr] | 3af09d6aae798be53d4f99fb63f17a3fd8e0f3ed | 27,980 |
def right_digit(x):
"""Returns the right most digit of x"""
return int(x%10) | 3f52393e9241714839e97a41f858753485cc5c89 | 27,983 |
import random
def generate_string(length: int) -> str:
"""Generates a random string of a given lentgh."""
symbols: str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
final_string: str = ""
for i in range(length):
final_string += symbols[random.randint(0, len(symbols) - 1)]
... | 9e6d4cbccf52f8abb6adf462a9a37b384a707ca3 | 27,985 |
def is_number(n):
"""
Return True if the value can be parsed as a float.
"""
try:
float(n)
return True
except ValueError as _:
return False | d9a2f8e4893b7379c2dcabf24f7f5f731423a753 | 27,987 |
from pathlib import Path
def create_flag_file(filepath: str) -> str:
"""
Create a flag file in order to avoid concurrent build of same previews
:param filepath: file to protect
:return: flag file path
"""
flag_file_path = "{}_flag".format(filepath)
Path(flag_file_path).touch()
return f... | 80ad8e181574600fcb1b9ded6e5c64c3c0d5b457 | 27,996 |
def _get_range_clause(column, value, bucket_interval):
"""Returns an SQL clause specifying that column is in the range
specified by value. Uses bucket_interval to avoid potentially
ambiguous ranges such as 1.0B-1.9B, which really means [1B, 2B).
"""
if value[0] == '-':
# avoid minus sign wit... | 7b0e9da8fa1ac9365e93ccd1137d519f08dadbed | 28,000 |
def createStructuringElement(radius=1, neighborhood="8N"):
"""Create a structuring element function based on the neighborhood and the radius.
Args:
radius (integer): The radius of the structuring element excluding the center pixel.
neighborhood (string): 4N or 8N neighborhood definition around... | f99601729155fb6993a63a6317454d9359c4fd69 | 28,008 |
def get_id_update(update: dict) -> int:
"""Функция для получения номера обновления.
Описание - получает номер обновления из полученного словаря
Parameters
----------
update : dict
словарь, который содержит текущий ответ от сервера телеграм
Returns
-------
update['update_id'] :... | 68672ff86cda83a11d557ff25f1a206bd1e974b3 | 28,010 |
def extract_some_key_val(dct, keys):
"""
Gets a sub-set of a :py:obj:`dict`.
:param dct: Source dictionary.
:type dct: :py:obj:`dict`
:param keys: List of subset keys, which to extract from ``dct``.
:type keys: :py:obj:`list` or any iterable.
:rtype: :py:obj:`dict`
"""
edct = {}
... | 80dff136ada8cfd754e1a02423e7eef364223a48 | 28,013 |
def ddiff_pf_contact(phi):
""" Double derivative of phase field contact. """
return -3.*phi/2. | 53150d05e6c2b6399da503b87c6ff83f2585483b | 28,018 |
def removeSpaces(string):
"""Returns a new string with spaces removed from the original string
>>> string = '1 173'
>>> removeSpaces(string)
'1173'
"""
return ''.join([char for char in string if char != ' ']) | ce00687c43ce521c14b578105bd9412c31b9817a | 28,019 |
from typing import Any
def do_nothing_collate(batch: Any) -> Any:
"""
Returns the batch as is (with out any collation
Args:
batch: input batch (typically a sequence, mapping or mixture of those).
Returns:
Any: the batch as given to this function
"""
return batch | 45cd76fb2ab1e4ad11053041a70ae9eb9c1948ec | 28,020 |
def _load_table_data(table_file):
"""Load additional data from a csv table file.
Args:
table_file: Path to the csv file.
Returns:
header: a list of headers in the table.
data: 2d array of data in the table.
"""
with open(table_file, encoding="utf-8") as f:
lines = f... | c1f1ee84c2f04a613616897b897a01ee2364b98c | 28,030 |
def backlog_color(backlog):
"""Return pyplot color for queue backlog."""
if backlog < 5:
return 'g'
if backlog > 24:
return 'r'
return 'y' | 551413b28c9c9736ea19e63c740f9c28613784ee | 28,032 |
import requests
def get_url_content(url):
"""
返回url对应网页的内容,用于分析和提取有价值的内容
:param url: 网页地址
:return: url对应的网页html内容
"""
return requests.get(url).text | 07f2e7ce8c365e601fd7ed4329f04e6ae56e214f | 28,035 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.