content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _reset() -> str:
"""Internal function returning ANSI escape sequence to reset all colors and boldness"""
return '\033[0m' | e5bb60a83f104d920a1c3c5be85365eba82d6b7d | 81,908 |
def create_tf(b, a):
"""
Creates a transfer function given vectors of values for the numerator, b[i], and
denominator, a[i],
b[0]*s**n + b[1]*s**(n-1) + ... + b[n]
f(s) = --------------------------------------
a[0]*s**m + a[1]*s**(m-1) + ... + a[m]
Arguments:
b... | b169f6e313f7bcd07bc19f3145b0f14a57791b1a | 81,910 |
def get_playlist(target_playlist, playlists):
"""
Searches for a playlist named `target_playlist` in the list `playlists`.
:param target_playlist:
:param playlists:
:return:
"""
for playlist in playlists:
if playlist['name'] == target_playlist:
return playlist | 1adf8c94e497519baede0d42476d1dfc92f4f1a9 | 81,911 |
import secrets
def _create_salt() -> str:
"""Create random salt."""
salt = secrets.token_hex(8)
return salt | 0ef07248ad8815b722285e15d2d6a702609a1498 | 81,914 |
def uniq_vals_incommon(list1, list2):
"""find unique values in common between two lists"""
return list(set([x for x in list1 if x in list2])) | 0dc53c8e4bcca14972e43f5ecff8d7d643ef9104 | 81,923 |
def _merge_jsonb_objects(column: str) -> str:
"""
This function returns SQL that merges the top-level keys of the
a JSONB column, taking the newest available non-null value.
"""
return f"""{column} = COALESCE(
jsonb_strip_nulls(old.{column})
|| jsonb_strip_nulls(EXCLUDED.{col... | 4d0f05d0d701217f7929721f6ef500fcb23d1d1b | 81,924 |
def should_perform_aggr_query(hesabi_body):
"""
this function specifies if we should go for agg field from sources or not
:param hesabi_body:
:return:
"""
if "agg_field" in hesabi_body:
return True
return False | a7f4c326ff517ab670316435a7fd8669a920cb5e | 81,935 |
import torch
def rotate_vec_by_axisangle(vec, aa_vec):
"""
This function rotates a 3D vector @vec by the direction and angle represented by @aa_vec.
See https://stackoverflow.com/questions/32485772/how-do-axis-angle-rotation-vectors-work-and-how-do-they-compare-to-rotation-matr
for more information.
... | 8ab749d7c26a94dfd9c0da80334c69e0e46702a2 | 81,938 |
import torch
def batch_pdist(X, Y, device=None):
""" Computes all the pairwise distances.
Parameters
----------
X : torch.tensor
shape [c, n, d]
Y : torch.tensor
shape [c, m, d] or [1, m, d]
Returns
-------
torch.tensor
output has shape [c, n, m]. The entry at... | 2d0801aa4abe6d2fe740d65f9f6f75645b6dde4f | 81,942 |
def subset(d, keys=()):
""" Return a copy of dict over a subset of keys and values. """
return dict([(k, d[k]) for k in keys if k in d]) | 51e4190ca40d8b6cb924e6c30a720f0231ba85e8 | 81,945 |
def get_physnets_for_node(task):
"""Return the set of physical networks for a node.
Returns the set of physical networks associated with a node's ports. The
physical network None is excluded from the set.
:param task: a TaskManager instance
:returns: A set of physical networks.
"""
return ... | 2e97b347661ab407b2609f142c937184e0fa36f1 | 81,946 |
def is_item_visible(item):
"""Returns true if the item is visible."""
for attr in ['is_deleted', 'is_archived', 'in_history', 'checked']:
if item[attr] == 1:
return False
return True | 3ac9d18cb70b29ab6d6dc39916d89f0cdc2a035c | 81,950 |
from datetime import datetime
import pytz
def _datetime_from_query(ts):
"""Converts the above arbitrary format back to a datetime object, complete
with a time zone. `ts` should be a string, straight out of the query.
Returns None if `ts` is missing or junk.
"""
if not ts:
return None
... | c0bfb96973c2c009bd60b3a48e12a5c2d271bcaa | 81,951 |
def PEM_split(cert_pem):
"""Split a certificate / certificate chain in PEM format into multiple
PEM certificates. This is useful for extracting the last / root PEM cert
in a chain for example. Will return a list of strings with each string
being an individual PEM certificate (including its '-----BEGIN... | 3872e7a971d2c0262add850f680732839e933d5c | 81,952 |
def _round(value: float, places=2) -> str:
"""Rounds a value to the given number of decimal places."""
fstring = "{:.%gg}" % places # pylint: disable=consider-using-f-string
return fstring.format(value) | 7c57e4c59d6cd3b6a435aa3988ec685a1551b87c | 81,953 |
import inspect
def find_people(person_module):
"""
Returns the functions prefixed with `get` from a module.
"""
functions = inspect.getmembers(person_module, predicate=inspect.isfunction)
people_functions = filter(lambda x: x[0].startswith('get'), functions)
persons = []
for _, function i... | c3b957051fc75acc5bd208a36d2882164e8564cd | 81,954 |
import csv
def parse_csv(path):
"""Read in the way that dict[algorithm][world_size] --> list"""
results = dict()
with open(path) as csvfile:
iterator = csv.reader(csvfile, delimiter=',')
for row in iterator:
print(row)
algorithm, world_size, object_size, mean, std =... | ae69b2ed43d150e20f52c6c5e729980c19a58e93 | 81,955 |
def get_any_index(lst, *values):
"""Returns the index of (the first of) a set of values in lst."""
for value in values:
try:
return lst.index(value)
except ValueError:
pass | 1676d18ac4f9968a3ffae44ef4b786242cc2f509 | 81,956 |
def prompt_string(msg):
"""Prompts the user for a value.
@param msg: Message to display to user.
@return: User's input or None.
"""
return input("\n%s: " % msg).strip(" \n") or None | 39c1d8cdadbdb760bdc7933f1520e613e8f817b6 | 81,958 |
from typing import List
def rgb_to_cielab(rgb: List[int]) -> List[int]:
"""
Convert from RGB to CIELab color space.
Arguments:
rgb: Iterable of length 3 with integer values between 0 and 255
Returns:
A list with 3 integer scaled values of CIELab.
References:
- https://gi... | 2c2b1250613a93526944e31f2572c24ee8e50c88 | 81,970 |
def bytes_to_size_string(b: int) -> str:
"""Convert a number in bytes to a sensible unit."""
kb = 1024
mb = kb * 1024
gb = mb * 1024
tb = gb * 1024
if b > tb:
return "%0.2fTiB" % (b / float(tb))
if b > gb:
return "%0.2fGiB" % (b / float(gb))
if b > mb:
return "%... | 9ad3a2adb5438206b5365483210d9a230d19f9eb | 81,973 |
import colorsys
def hsv_to_rgb(hsv):
"""
Converts the given HSV tuple to RGB values
:param hsv: The input HSV tuple ((h, s, v) ranging from 0.0 to 1.0)
:return: The converted RGB tuple ((r, g, b) ranging from 0 to 255)
"""
return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(hsv[0], hsv[1]... | 10fd66d9b9da75802c79e6f69d6e63ddce17c472 | 81,977 |
def sylvester(number: int) -> int:
"""
:param number: nth number to calculate in the sequence
:return: the nth number in Sylvester's sequence
>>> sylvester(8)
113423713055421844361000443
>>> sylvester(-1)
Traceback (most recent call last):
...
ValueError: The input value of [n=-1] ... | c9d6a4af29fc3b4ef4de145673caab8ea643355c | 81,983 |
import torch
def get_spacer_tensor(template: torch.Tensor, length: int) -> torch.Tensor:
"""Get a tensor of zeros."""
shape = template.shape[:-1] + (length,)
return torch.zeros(
shape,
dtype=torch.float32,
device=template.device,
) | e1ba4793d4667e547489894724ba15127cb25530 | 81,984 |
from typing import Any
def size(obj: Any) -> int:
"""Return the length of an array or string."""
try:
return len(obj)
except TypeError:
return 0 | 71f9c01e4b9bd614df5bf839ef37c30ec1ec0752 | 81,990 |
def slicify(slc, dim):
"""
Force a slice to have defined start, stop, and step from a known dim.
Start and stop will always be positive. Step may be negative.
There is an exception where a negative step overflows the stop needs to have
the default value set to -1. This is the only case of a negativ... | 06c7a4e3f5a371e5bbacb4f6a41c51041567fa08 | 82,001 |
def pad_floats(n):
"""
Formats numbers to two decimal places
:param n: number to be formatted
:return: formatted number
"""
return float("{:.2f}".format(n)) | 377fe965b6d8891c76b47ffa1cd2da099f893c3b | 82,003 |
def flatten(x):
""" flatten(): turns nested list or tuple into single list """
result = []
if isinstance(x, str):
result = x
else:
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, str):
result.extend(flatten(el))
else:
... | 2afbad9dc45711ac1cba96a377dd5e212d262c52 | 82,006 |
import time
def validate_counter(counter):
"""
Validates a counter ensuring it's in a sliding window.
Window is +/- 12 hours (43200 seconds)
"""
currentTime = int(time.time())
return (currentTime-43200) <= counter <= (currentTime+43200) | 7f7866c3f1f038bbe87ffdce4f05bb385f72d030 | 82,009 |
def is_list_type(value):
"""
判断value是否列表类型,兼容python2、python3
:param value: 输入值
:type value: any
:returns: 判断结果
:rtype: bool
"""
return isinstance(value, (list, set, tuple)) | 3d858858d1ec3042f9318c9ca524197ad980bcf9 | 82,011 |
def _target_ads_in_campaign_to_user_list(
client, customer_id, campaign_id, user_list_resource_name
):
"""Creates a campaign criterion that targets a user list with a campaign.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a str client customer ID used to create an cam... | 28944ade1b3d2d3e94fc39bf1fffc1887d8be868 | 82,012 |
import re
def get_text_refs(url):
"""Return the parsed out text reference dict from an URL."""
text_refs = {'URL': url}
match = re.match(r'https://www.ncbi.nlm.nih.gov/pubmed/(\d+)', url)
if match:
text_refs['PMID'] = match.groups()[0]
match = re.match(r'https://www.ncbi.nlm.nih.gov/pmc/ar... | f24cdec70775d10e707aa8ae693dfe5a977fee93 | 82,013 |
def remove_invariant_features(dataset):
"""Returns a new dataset with all invariant features removed.
"""
return dataset[:, dataset.samples.std(axis=0).nonzero()[0]] | 42e931d1b64813beef3481d9f909b423b08a0d55 | 82,018 |
def ravel_multiple_indices(ixs, shape):
"""
"Flattens" multiple 2D input indices into indices on the flattened matrix, similar to np.ravel_multi_index.
Does the same as ravel_index but for multiple indices at once.
Parameters
----------
ixs: array of ints shape (n, 2)
The array of n indi... | 06d1078abaa8203f19680544ea5cc5b811618c54 | 82,020 |
def export_url(url):
"""
Get the 'Special:Export' XML version url of an article
"""
page = url.split("/")[-1]
return ("http://en.wikinews.org/w/index.php?title=Special:Export"
"&action=submit&pages={}".format(page)) | e1e22896c2641865354a8a8c4ba82dcd59118da3 | 82,025 |
def delta_time(ind):
"""Create a function to return the delta time from a product-specific block."""
def inner(seq):
return seq[ind] >> 5
return inner | 288d2fd1e677640f5166e77b77c5b015b4c15b61 | 82,037 |
import re
def represents_float(text):
"""
This function return True if the given param (string or float) represents a float
:Example:
>>> represents_float("1.0")
True
>>> represents_float("1")
False
>>> represents_float("a")
False
>>> repres... | ab3f5b39800e84e79421f2b8fbf9c57ad07cb1a3 | 82,042 |
def get_comments(events, comments=None):
"""
Pick comments and pull-request review comments out of a list of events.
Args:
events: a list of (event_type str, event_body dict, timestamp).
comments_prev: the previous output of this function.
Returns:
comments: a list of dict(author... | f3b412cb36463b523fc2d9c67554b856eeb1489e | 82,043 |
def applyReplacements(symbol_list):
"""
Apply the rules associated with each symbol to the symbols in
`symbol_list`. Symbols with no defined rule are returned as-is.
The elements of `symbol_list` must be subclasses of Symbol.
Returns a tuple of (`replaced`, `new_symbol_list`) where `replaced` is
... | 8482dd8a5afc00f156b090289a09a615d6385b00 | 82,044 |
def errorMessage(err, location = None):
"""
Generate a standard error message.
Parameters
----------
err : str
The error message.
location : str, optional
Where the error happens. E.g. CTL.funcs.funcs.errorMessage
Returns
-------
str
The generated error ... | fbc1c0cee3de8d165cb4f2512e5f830cedaa0c27 | 82,047 |
def _NormalizePath(path):
"""Returns the normalized path of the given one.
Normalization include:
* Convert '\\' to '/'
* Convert '\\\\' to '/'
* Resolve '../' and './'
Example:
'..\\a/../b/./c/test.cc' --> 'b/c/test.cc'
"""
path = path.replace('\\', '/')
path = path.replace('//', '/')
filtered... | ed6cd73f1c59eeef4d55121a99bb29c2e569a6da | 82,049 |
def arcsecs2radians (seconds:float) ->float:
"""convert arcseconds to radians.
"""
radians = seconds * 0.000004848
return radians | 50c5884bf4bb2fb559faede58f7a023259ba5dde | 82,050 |
def coerce_to_list(val):
"""
For parameters that can take either a single string or a list of strings,
this function will ensure that the result is a list containing the passed
values.
"""
if val:
if not isinstance(val, (list, tuple)):
val = [val]
else:
val = []
... | a26e881eea0de2b7e0a029e6a56f2f9a9f9449af | 82,051 |
def xyxy2xywh(bbox_xyxy):
"""
Args:
bbox_xyxy: [xim, yxim, xmax, ymax]
Ruturns:
bbox_xywh: [x, y, w, h]
"""
xim, yxim, xmax, ymax = bbox_xyxy
return [xim, yxim, xmax-xim, ymax-yxim] | 7a533a64cede8a0a4a073e547099087d906f8ef0 | 82,061 |
def train_test_split(data, test_len):
"""
Train/ Test split
:param data: (np.array) Sequence to split
:param test_len: (int) length of test sequence
:return: np.array, np.array: train sequence, test sequence
"""
# print("[DataProcessor] Train/Test split")
if test_len == 0:
return... | 9a21e22934a6b48974ff121542ff2061115fde78 | 82,063 |
def check_numeric_type(array):
"""
Check if an array contains only numeric values. Accepted formats: int64, int32, float64, float32
Args:
array: array-like, shape=(n_samples, n_features)
Returns:
boolean, True if the array is one of accepted types.
"""
is_numeric = array.dtype... | 803e5c4fe7349aa165f197ade735ed5cb37f1604 | 82,064 |
def exponentiate(base, exp, p):
"""
uses the square and multiply algorithm to
get (base^exp)%p
:param base: base of the exponentiation
:param exp: power that the base is being raised to
:param p: prime modulus
:returns: (base^exp) mod p
"""
e = "{0:b}".format(exp) # bitstring of... | 48b656a62b819e71c2135918c63e5b1445feebb9 | 82,067 |
def get_stack_name(stack_formatted):
"""
Get the stack name (eg. HDP) from formatted string that may contain stack version (eg. HDP-2.6.1.0-123)
"""
if stack_formatted is None:
return None
if '-' not in stack_formatted:
return stack_formatted
return stack_formatted.split('-')[0] | 59e9fc45ceea1e032036b8098cf36dc4acf25d0f | 82,070 |
import copy
def nonuniform_mutation(random, candidate, args):
"""Return the mutants produced by nonuniform mutation on the candidates.
The function performs nonuniform mutation as specified in
(Michalewicz, "Genetic Algorithms + Data Structures = Evolution
Programs," Springer, 1996). This function al... | c002fc2faeaa9a2e1a2d270158a0535814d2bf15 | 82,071 |
def get_outbound_layers(layer):
"""Return outbound layers.
Parameters
----------
layer: Keras.layers
A Keras layer.
Returns
-------
: list[Keras.layers]
List of outbound layers.
"""
try:
# noinspection PyProtectedMember
outbound_nodes = layer._out... | c38c4f49e6abd4ddf445e32bbeac0320a409bece | 82,075 |
def calc_gb_size(num_rows, row_size):
"""Calculate the size of table in GB
given row size and number of rows in bytes"""
total_byte = row_size * num_rows
total_gb = ((total_byte / 1024) / 1024) / 1024
return total_gb | 98768350c15ed87527e6a29dc95ed13c49bd6a25 | 82,076 |
def maybe_get(obj, i):
"""
:param obj: object
:param i: the index
:return: the i-th item if the `obj` instantiates the __getitem__ function
"""
return obj[i] if hasattr(obj, "__getitem__") else obj | 701535c1401bf5fcf4f4c1ced9bacd6558f479e2 | 82,081 |
def get_index_name(app_id, namespace, name):
""" Gets the internal index name.
Args:
app_id: A str, the application identifier.
namespace: A str, the application namespace.
name: A str, the index name.
Returns:
A str, the internal name of the index.
"""
return '{}_{}_{}'.format(app_id, namesp... | b7f5dc80a8a0b649d7d0009d34ab9da4f432b54f | 82,084 |
def pad_lines_after_first(prefix, s):
"""Apply a prefix to each line in s after the first."""
return ('\n' + prefix).join(s.splitlines()) | 2c990180ad4e6d276b1a18e934406f5ab89d73fd | 82,085 |
import copy
def merge_dict(original_data, new_data):
"""
Merge two dictionaries.
Merge the content of a `new` dictionary into another, `original` dictionary.
A new dictionary with the merged content is created. Values are preserved
and a ValueError is raised if incompatible content is encounte... | 71d8e19d9d5e7f640a741dd8a815e0f9ad324588 | 82,086 |
def quote(text):
"""Change " to \\"."""
try:
return text.replace('"', '\\"')
except TypeError:
return text | cd3018062985a08923122028552d9b1e9f68b1f5 | 82,090 |
def check_return_code(error_message, expected_code=0):
"""Create a callable to verify the return code of a response.
To be used with the :meth:`run` function. The callable will raise an
:class:`AssertionError` if the return code of the response is different from the
given one.
Args:
error_... | 17302dad9f2d46ca4dbef16429595c5b7107f6ca | 82,091 |
import base64
def encode(data: bytes) -> str:
"""Encode data to base64url (RFC 4648) text
:param data: Raw data
:returns: Base64-encoded data
:raises TypeError: if `data` is not a bytes instance
>>> encode(b'test')
'dGVzdA'
"""
if not isinstance(data, bytes):
raise TypeError... | 88d361a8ab4429119fdb03e57a2054d04491d150 | 82,094 |
import base64
import binascii
def _decode_telegram_base64(string):
"""
Decodes a url-safe base64-encoded string into its bytes
by first adding the stripped necessary padding characters.
This is the way Telegram shares binary data as strings,
such as Bot API-style file IDs or invite links.
Re... | faae09c4fbb3430681f83037ac4ac653ce54b87f | 82,098 |
def to_product(product_tuple):
"""Parse a tuple into valid 'Product' object.
Args:
product_tuple: Tuple containing StockCode, Description, Quantity and UnitPrice.
Returns:
Product (dictionary).
"""
return {
'id': str(product_tuple[0]),
'description': str(product_tup... | 52b01932a58791bfea44ae47ca1b23acaa437744 | 82,100 |
from typing import List
from typing import Union
import hashlib
def integer_seed(objs: List[Union[str, int]]) -> int:
"""Reproducibly and readably generate a seed value, from strings and integers.
"""
assert isinstance(objs, list), isinstance(objs, tuple)
h = hashlib.sha256()
for obj in objs:
if isinsta... | 2397c74e7455f66cad07dcc9745c69639cf7b750 | 82,102 |
import re
def _remove_redundant_parts(word: str) -> str:
"""
This function removes redundant parts in a given Neo-Assyrian word in ORACC.
:param word: A given word
:return: The given word after removing redundant parts
"""
word = re.sub(r"lu₂[a-z]*", "lu₂", word)
return re.sub(r"@?v|\\[a-... | 1650c7c2d339a4945910480c519ea1176af1da14 | 82,107 |
import hashlib
def partition(example, num_buckets):
""" Partition examples into multiple buckets """
def determine_hash(input_bytes):
m = hashlib.blake2b(input_bytes, digest_size=4)
address = 0
for i, b in enumerate(m.digest()):
address += b * (2 ** (i * 8))
return address
address = deter... | b005c81a07b9975356ed04753db157211f3214b4 | 82,108 |
import math
def acos(theNumber):
"""Returns math.acos(theNumber)."""
return math.acos(theNumber) | 254ebf05c850f220a35ce21a7a03ab61edc2804b | 82,112 |
def gene_synonyms(ncrna):
"""
Find all gene synonyms, if they exist.
"""
gene = ncrna.get("gene", {})
synonyms = gene.get("synonyms", [])
if "symbol" in gene:
synonyms.append(gene["symbol"])
return synonyms | 95c1759f86831e23f097c1a6d5525380e8dab51b | 82,115 |
def ms2min_sec(ms: int):
"""Convert milliseconds to 'minutes:seconds'."""
min_sec = f'{int(ms / 60000):02d}:{int(ms / 1000) % 60:02d}'
return min_sec | 0d08ba003223e0f5e36e01c14f40a96328154f99 | 82,117 |
from datetime import datetime
def date2jd(date):
"""
Convert datetime object to JD"
Args:
date (datetime.datetime): date to convert
Returns:
float: Julian date
"""
jd_td = date - datetime(2000, 1, 1, 12, 0, 0)
jd = 2451545.0 + jd_td.days + jd_td.seconds/86400.0
retur... | a5033fb2b1a4d9295127329eec541c389837cdcc | 82,118 |
def jaccard(r_tokens: list, s_tokens: list) -> float:
"""Computes jaccard similarity.
JAC(r, s) = |r ∩ s| / |r ∪ s|
Parameters
----------
r_tokens : list
First token list.
s_tokens : list
Second token list.
Returns
-------
Jaccard similarity of r and s.
"""
... | 427bd308e153cf6781ada6ba45f4bdd0b8f73220 | 82,120 |
def rank_zero_method(f):
"""Decorator that executes f only if the passed experiment has rank 0. This
is used with distributed data parallel to train on multiple nodes."""
def inner(self, experiment):
if experiment.rank != 0:
return
return f(self, experiment)
return inner | e4ee6d55898de8ae5667bd4e483e3f084bdcbacd | 82,121 |
def extract_files_to_lint(file_diffs):
"""Grab only files out of a list of FileDiffs that have a ACMRT status."""
if not file_diffs:
return []
lint_files = [f.name for f in file_diffs if f.status in b'ACMRT']
return lint_files | 3594bd942f132f7c815df3423eaef6c0de882588 | 82,123 |
from typing import Mapping
from typing import Any
from typing import Iterable
from typing import Dict
import itertools
def _combinations_of_selections(selections: Mapping[str, Any]) -> Iterable[Dict[str, Any]]:
"""Find all permutations of combinations of selections.
This is useful for passing the selections ... | 8d71d519e7183aaf66d286fda6e4e79dc842bb96 | 82,125 |
def cropFrequencies(frequencies, Z, freqmin=0, freqmax=None):
"""
Trim out all data points below the X-axis
Parameters
----------
frequencies : np.ndarray
Array of frequencies
Z : np.ndarray of complex numbers
Array of complex impedances
freqmin : float
Minimum freq... | d289c55bca938f377c31feacb102c47ecb615d5e | 82,126 |
from typing import Union
def is_inet_address(addr: Union[tuple[str, int], str]) -> bool:
"""Check whether addr is of type tuple[str, int]."""
return (
isinstance(addr, tuple)
and len(addr) == 2
and isinstance(addr[0], str)
and isinstance(addr[1], int)
) | 825c0e0f71d8e0165d93b0915074e8f4ef68c4ce | 82,129 |
from typing import Counter
def get_word_freqs(captions):
""" Calculates word frequencies
:param captions: list of captions
"""
word_freqs = Counter()
for caption in captions:
word_freqs.update(list(filter(None, caption.split(' '))))
return word_freqs | 43fe7bd3ac85955da9efa3f88009bb4397b24a4e | 82,132 |
def _is_windows(repository_ctx):
"""Returns true if the host OS is Windows."""
return repository_ctx.os.name.startswith("windows") | 4101d53a6cfaee74688d10b3902f5665d8362aa5 | 82,135 |
def is_engine_in_list(engines_list, engine_class):
"""Checks if engine in the list
:param list engines_list: list of engines
:param engine_class: engine class
:returns: True if engine in the list
False if engine not in the list
"""
engines = filter(
lambda engine: isinsta... | e3299c5dc84f881b10b2a3767ac869724b249da1 | 82,143 |
import hashlib
def CalculateHash(file_path):
"""Calculates and returns the hash of the file at file_path."""
sha1 = hashlib.sha1()
with open(file_path, 'rb') as f:
while True:
# Read in 1mb chunks, so it doesn't all have to be loaded into memory.
chunk = f.read(1024 * 1024)
if not chunk:
... | 5c3b9a13aab3e607d9b4f34277c57fbec2b86ed2 | 82,147 |
import torch
def _normalize_images(images):
"""
Given a tensor of images, uses the torchvision
normalization method to convert floating point data to integers. See reference
at: https://pytorch.org/docs/stable/_modules/torchvision/utils.html#save_image
The function uses the normalization from mak... | bf3737fc9ac64f3bf8454f2626806f0bffb57361 | 82,151 |
def getGrayDiff(img,currentPoint,tmpPoint):
"""This function does gray difference between two points.
Parameters
----------
img : numpy array
Array containing the image data.
currentPoint : numpy array
Array containing the position of one seed point.
tmpPoint : numpy array
... | 9191501fe16775067521092366b3a39f75ec0254 | 82,153 |
def gen_explicit_map_nn_maxpool2d(params_pt, args_pt):
"""
Generate explicit_map for nn.MaxPool2d.
Args:
params_pt (dict): Params for APIPt.
args_pt (dict): Args for APIPt.
Returns:
dict, map between frames.
"""
if 'padding' in args_pt:
padding = args_pt['paddin... | 23e9ccc1f415aa73de8a123a15466537eb002d29 | 82,155 |
def wrap(text, line_length):
"""Wrap a string to a specified line length.
Args:
text: The string to wrap.
line_length: The line length in characters.
Returns:
A wrapped string.
Raises:
ValueError: If line_length is not positive.
"""
# DON'T DO THIS:
# assert l... | 170e9fff91d4ee79e342efee1ee5c8dabbab6070 | 82,156 |
def _imag_1d_func(x, func):
"""Return imag part of a 1d function."""
return func(x).imag | bc5d4eb810f56ca0e9131980f85c34794d91076a | 82,157 |
def Dist(p1,p2):
"""
Euclidean distance between 2 points
"""
x1, y1 = p1
x2, y2 = p2
return (((x1-x2)*(x1-x2)) + ((y1-y2)*(y1-y2)))**0.5 | 974f397515cf1ce37e925cb60a435a557b94bfaf | 82,159 |
def cross(a, b):
"""Cross product between a 3-vector or a 2-vector"""
assert len(a) == len(b), 'Vector dimensions should be equal'
if len(a) == 3:
return (
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0])
elif len(a) == 2:
... | c3ae97b472560f7704310fff8b163b0572e68859 | 82,165 |
import itertools
def nth(iterable, n):
"""Returns the nth item from iterable."""
try:
return iterable[n]
except TypeError:
try:
return next(itertools.islice(iterable, n, None))
except StopIteration:
raise IndexError('index out of range') | 6ca5f1aa0f78607a9f0d31b43fe9ec5cd8a30623 | 82,167 |
def rgb_xyz(rgb):
"""
Convert tuple from the sRGB color space to the CIE XYZ color space.
The XYZ output is determined using D65 illuminate with a 2° observer angle.
https://en.wikipedia.org/wiki/Illuminant_D65
sRGB (standard Red Green Blue): https://en.wikipedia.org/wiki/SRGB
CIE XYZ: https://en.wikipedia.org/... | 7f7146a7a91c1574c96f13539e51aaf373919451 | 82,168 |
def identity_transform(memory, image_key):
"""Simple function to return the image at "image_key" in the memory.
Args:
memory (dictionnary): memory dict.
image_key (string): image key.
Returns:
np.array: the image.
"""
return memory[image_key] | 149203758798e5cee189179326e12faaf2eeaf20 | 82,170 |
def strip_byte_order_mark(text):
"""Return text with byte order mark (BOM) removed."""
try:
return text.encode('utf-8').decode('utf-8-sig')
except UnicodeError:
return text | 9f7734cd9b07312ab35fff4473bf8acdb6991718 | 82,179 |
def get_blockname_from_block_id(lookup_dict: dict, block_id: str) -> str:
"""
Pycifrw makes datablock names all lower case. When I make up a pd+block_id from a dataname, sometimes the user has a
case-dependent reference somewhere in their CIF, and so I can't find the datablock. This looks in my lookup dicti... | f7489588181c9a51f8ece8649fda26a1e6b8afa2 | 82,180 |
def sub_print(stream_id, data, state, log):
"""!@brief Default stream data callback. Prints data.
@param stream_id data stream id
@param data data to be printed
@param log logging object
"""
log.info("[{}]: {}".format(stream_id, data))
return state | 61865e31f04a1f52561b72c1dae78f1d2bf8437f | 82,181 |
def flatten(categories):
"""Flatten incoming categories list
>>> flatten({'name':'test'})
[{'name': 'test', 'parent': None}]
>>> flatten({'name': 'Category 8', 'children': [{'name': 'Category 22'}, {'name': 'Category 23'}]})
[{'name': 'Category 8', 'parent': None}, {'name': 'Category 22', 'parent':... | 018e068af6203736d7f70623dd2d24be12e2ea06 | 82,189 |
def lca(node1, node2):
""" Returns least common ancestor of {node1, node2}. """
nodes = sorted(
[(node1.uid, node1), (node2.uid, node2)],
key=lambda x: -x[0]
)
while nodes[0][0] != nodes[1][0]:
lower_node = nodes[1][1]
par = lower_node.parent
assert par is not No... | f9b210be7366ebbc700b0efbf3eee892f30dcc8e | 82,192 |
import bisect
def find_ge(a, x):
"""Find leftmost item greater than or equal to x"""
i = bisect.bisect_left(a, x)
if i != len(a):
return i
raise ValueError | 36c87a92d3beaa6ef54935be3ea830cac4a530c8 | 82,194 |
def sort_python_measurement_files(folder):
"""Sort a folder of measurement data by order of measurements.
This doesn't strictly preserve measurement order but rather groups files by
measurement type in the experiment order.
Parameters
----------
folder : pathlib.Path
Folder of data to ... | 3c6ecabfd198d033a784c16b4b751e325d77fc35 | 82,196 |
def identify_technique(target, obstype, slit, grating, wavmode, roi):
"""Identify whether is Imaging or Spectroscopic data
Args:
target (str): Target name as in the keyword `OBJECT` this is useful in
Automated aquisition mode, such as AEON.
obstype (str): Observation type as in `OBSTYPE... | 07e825692cc1bee9580383651ac76ef6bb5c3f92 | 82,198 |
def c200_to_v200(c200=1., rs=1.0, H0=73):
"""get C200
H0 in km/s/Mpc
rs in Mpc
c200 is dimensionless
Return V in km/s
"""
return 10. * c200 * rs * H0 | 87b7d5f78f1b14cb3f83f34a1c5d18ffd912308a | 82,202 |
def gen_podcast_episode_id(podcast_episode_obj):
"""
Generates the Elasticsearch document id for a Podcast
Args:
podcast_episode_obj (PodcastEpisode): The PodcastEpisode object
Returns:
str: The Elasticsearch document id for this object
"""
return "podcast_ep_{}".format(podcast... | cd6a76e61bd761d93545af88a248dd097e6689ca | 82,205 |
import pathlib
def get_full_img_path(img_root_path, csv_path):
"""Merge csv root path and image name."""
root_dir = pathlib.Path(csv_path).parent
img_path = root_dir / pathlib.Path(img_root_path)
return str(img_path) | 582c86466cfd886099b34736c40d440195434396 | 82,206 |
def find_identifier(qualifiers):
"""Finds an identifier from a dictionary of feature qualifiers.
This function selects for the following fields in decreasing order:
protein_id, locus_tag, ID and Gene. This should cover most cases where CDS
features do not have protein ID's.
Args:
qualifier... | d2f7cdaaa1b7907f7846100704d05d9558d5c123 | 82,210 |
def find_user(user_name, source):
"""
Search for a user by name on the given object
"""
name = user_name.lower()
for user in source.users:
if user.nickname.lower() == name:
return user
return None | f08dee7d5ea3a0667ce4aafefb3ab99cf73fb459 | 82,219 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.