content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _check_hashes(x, y, datatype):
"""MPI reduction op to check if code hashes differ across ranks."""
if x == y:
return x
return False | 5e0b04eaec06b69858b73645613968cceaedd60e | 657,242 |
import traceback
def fixFilename(info, filename):
"""For binary packages we need to refer to /libnn, /binnn and /uidnn where nn is 32 or 64. For
noarch packages we need to use /lib??, /bin?? to get the no arch dependent scripts and files"""
try:
if info['arch'] == 'noarch':
filename = ... | 06b2419bea666a77c43ed07aec3d1586d290aff2 | 657,243 |
import os
def is_leaf(folder):
"""Determine whether folder does not contain any subfolders.
Parameters
----------
folder : str
Folder to be checked for being a leaf.
Returns
-------
bool
True if folder is leaf (does not contain any subfolders),
False otherwise.
... | 282e11550bd94b9458fdc4ee3750d872bc9c9953 | 657,244 |
import textwrap
def _value_type_to_string() -> str:
"""
Generate the function to convert Json::ValueType to a string.
:return: generated code
"""
return textwrap.dedent(
'''\
/**
* converts a JSON value type to a human-readable string representation.
*
*... | 66fc09b2e44146b4f9412bbbfd186586a523f91c | 657,246 |
import numpy as np
def remove_outliers(data):
"""Remove outliers using boxplot algorithm
>>> from text_models.utils import remove_outliers
>>> _ = remove_outliers([0.2, 3.0, 2, 2.5, 5.4, 3.2])
"""
data = np.atleast_1d(data)
q1 = np.quantile(data, q=0.25)
q3 = np.quantile(data, q=0.75)
... | 3001a8717d0338ac53427a3955800242d1380df8 | 657,247 |
def rectangles_collide(x1, y1, w1, h1, x2, y2, w2, h2):
"""
Return whether or not two rectangles collide.
Arguments:
- ``x1`` -- The horizontal position of the first rectangle.
- ``y1`` -- The vertical position of the first rectangle.
- ``w1`` -- The width of the first rectangle.
- ``h1`` ... | 0d9a6a7b87a454bb242480ce48277ed623816410 | 657,248 |
def give_action_choose_probability_new(episodes, episode, model):
"""
This method gives probability of choosing action according to the episode number and total number of episode.
:param episodes: total number of episodes
:param episode: current running episode
:param model: model number
:return... | cb8daca110946c2f2403d93f25b6f6b669e11e02 | 657,250 |
async def startlist() -> dict:
"""Create a mock startlist object."""
return {
"id": "startlist_1",
"event_id": "event_1",
"no_of_contestants": 8,
"start_entries": ["11", "22", "33", "44", "55", "66", "77", "88"],
} | 6130f79ff308db5dde05af5af02ea4c6d1e7a87e | 657,251 |
def spancmb(class_=None, **kwargs):
""" span combinator
because class is a reserved keyword in python, class_ is the first arg
kwargs keys may be any html global attribute """
cdict = {'class': class_} # put class first (sign the siren song or python preserving key order)
cdict.update(kwarg... | 6a524e035781052ff92b61a35c71faff2bd54b93 | 657,252 |
import inspect
def doc_property(name, prop):
"""
return markdown formatted documentation for a class property
Argument(s):
- name(str)
- prop(property)
Returns:
- list
"""
docstr = inspect.getdoc(prop.fget)
return ["- {} (`{}`): {}".format(name, "@property", docstr)] | 0f4498ab75e32cc1705a5ab99aaa6025e23ace41 | 657,253 |
def node_below_adjacent_elements(node, surface):
"""
node_below_adjacent_elements determines if a node is below any element adjacent to it in the surface.
Consider the following layout:
*-*-*-* Here, the nodes are shown as * and node (0,0) as X. Elements are shown as o and neighboring
|O|O|o| ele... | 71d0e2765f57095fae713e7afd8df108a3dfb490 | 657,254 |
import torch
def sample_pdf(rays, weights, N_importance, det=False, eps=1e-5):
"""
Sample @N_importance samples from @bins with distribution defined by @weights.
from https://github.com/sxyu/pixel-nerf/blob/master/src/render/nerf.py#L120
Inputs:
rays: (N_rays, N_samples_+1) where N_samples_ is... | 5de002923147003787262be60fe0f4f34352579c | 657,255 |
def special_sylvester(a, b):
"""Solves the eqation `A @ X + X @ A = B` for a positive definite `A`."""
s, v = a.symeig(eigenvectors=True)
d = s.unsqueeze(-1)
d = d + d.transpose(-2, -1)
vt = v.transpose(-2, -1)
c = vt @ b @ v
return v @ (c / d) @ vt | 57982779f51846d11b6c9f1ae4bf09e14abcd80e | 657,256 |
import copy
def on_threads_context(f, context):
""" helper函数,用于为OnThreads转换context。
参数f为过滤函数,当一个线程应该包含在context中时返回True
返回更新后的context """
target_threads = set()
for f_thread in context['free-threads']:
if f(f_thread):
target_threads.add(f_thread)
ctx = copy.deepcopy(context)... | bb40262d10e674b314ed74a96169ae349cd706f4 | 657,257 |
def fixer(client, operation):
"""
A method decorator to fix boto3 arguments. If the arguments come from a custom resource notification,
they must be converted from strings to the expected types.
:param client: service client name
:param operation: operation name
:return: wrapped function
""... | 6aef804dea70595e6b2f4cd210bf1915f5510371 | 657,258 |
def base_to_integer(base_number, base_string):
"""
Converts baseX integer to base10 integer (where X is the length of base_string, say X for '0123' is 4),
for example: 21646C726F77202C6F6C6C6548 (base16) to 2645608968347327576478451524936 (Which is 'Hello, world!'),
does not account for negative numbers... | 92f7061c834fd291c07325b6f661a24c17ff06c3 | 657,259 |
def skipElement(inFile, currentLine):
"""
Skips an element in the template file, based on finding an end tag that matches the start tag on the next readline().
"""
theLine = inFile.readline()
if (theLine == ''):
print("\nError! The skipElement function reached the end of the file unexpectedly.")
prin... | d96d5e3ca3773f5331b0265c8ef613a7e15ba728 | 657,260 |
import json
def write_vault_secret(client, vault_key, vault_secret):
"""Get password from vault"""
url = client.base_url + vault_key
data = {"value": vault_secret}
response = client.conn.post(url, data=json.dumps(data))
if response.status_code == 204:
return True | 69948af636c2421e21d199352cef26f19f96a020 | 657,262 |
import string
def strip_punctuation(text):
"""
Remove all punctuation from text
:param text: raw headline
:return: parsed headline
"""
if text is None:
text = ""
return text.translate(str.maketrans('', '', string.punctuation)) | 7ad47c0f8cfb9df27ad00c5ec018eed63b84881b | 657,263 |
def read_fragments_data(in_file):
"""Read gene: fragments file."""
ret = {}
f = open(in_file, "r")
for line in f:
line_data = line.rstrip().split("\t")
gene = line_data[0]
chain_str = line_data[1]
# chains = [int(x) for x in line_data.split(",") if x != ""]
# actu... | 21b0ed9191c99d32f5b6b77052a6079b4119939b | 657,264 |
def _rhyme(word_a, word_b, phonemes_func):
"""Return whether two words form a rhyme.
This function is just a general version and the shorthands available in the
same module should be used instead, except a custom function for extracting
phonemes is to be used.
:param word_a: first word.
:param... | 8264302ee25b8823b5ab0741af636ef51a107272 | 657,265 |
def getTexte():
"""
Shakespeare Sonnet 2
:return: test_sentence
"""
test_sentence = """When forty winters shall besiege thy brow,
And dig deep trenches in thy beauty's field,
Thy youth's proud livery so gazed on now,
Will be a totter'd weed of small worth held:
Then being asked, wher... | 7bfe44a09afa6939da5b8b32ded0a1a35a98f56d | 657,266 |
import os
def list_files_in_directory(directory, fullpath=False, extensions=None):
"""This function lists just the files in a directory, not sub-directories.
Parameters
----------
directory : :obj:`str`
The directory to search for files.
fullpath : :obj:`bool`, optional
Specifies ... | 17267689f1b94e22368ec3b82b1add3cf6170872 | 657,267 |
import requests
def get_access_token(app_id, app_secret, redirect_uri, code):
"""
This method gets the access token that helps you get
user details from facebook. The code argument is
retrieved from the url after the user has accepted
the permissions of your app from facebook
:param app_id:
... | 16525f4ff3ea1573be8f9cb6bb2532e95398569c | 657,268 |
def pagination_ruler(limit, total, offset):
"""
This function returns a list of pagination links according to the given
definitions.
"""
ruler = []
current_index = 0
for ndx, item in enumerate(range(0, total+limit, limit)):
page = int((item/limit)) + 1
if page < 1:
... | 49e25f354c7a48214e18862f1706422107b02350 | 657,269 |
import re
def remove_br_in_ul(content):
"""
Get rid of <br> inside <ul> lists
>>> remove_br_in_ul('<ul><li>abc<br></li></ul>')
'<ul><li>abc</li></ul>'
"""
_re_content_in_pre = re.compile(r"<ul>(.*?)</ul>", re.DOTALL)
return re.sub(_re_content_in_pre, lambda match: match.group().replace('<... | 3091c78b71523b05584c26c071165185104408b3 | 657,270 |
def type_label(stage, bin):
"""Label"""
return 2 | d6f64fceed24011d33fa360872fd2c2fdeb62691 | 657,271 |
def traditional_constants_basal_equation(tdd):
""" Traditional basal equation with constants from ACE consensus """
a = 0.5
return a * tdd | ec66d8de28c81bd915d74e0bafdbee69f2892b57 | 657,273 |
def _(acc, short_account_names=False, **kwargs):
"""Return a ledger-cli alike representation of the account"""
# ignore "dummy" accounts
if acc.type is None or acc.parent is None:
return ""
if acc.commodity.mnemonic == "template":
return ""
if short_account_names:
res = "acc... | 78c688fcb9581ebe590321ba4c688f3515c5fcd9 | 657,275 |
import os
def collect_vendored_files():
"""Provides robot_interactive_console.robot."""
VENDORED_ROOT = os.path.dirname(os.path.abspath(__file__))
VENDORED_ROOT = os.path.join(VENDORED_ROOT, "robotframework_interactive")
ret = []
for dir_, _, files in os.walk(VENDORED_ROOT):
for file_name... | 5858d274de76147f4f1200f05663ea038ce0e8c4 | 657,276 |
import pathlib
from typing import Dict
def table_files(sql_file: pathlib.Path) -> Dict[str, str]:
"""
Associates the name of an output file to its SQL table, by reading the
snb-load.sql script
"""
results = {}
with open(sql_file, "r", encoding="utf-8") as in_fd:
for line in in_fd:
... | b6ac2f2030bf12f2121322829b68bb196b850c0f | 657,277 |
def argToInt(value):
""" Given a size or addresse of the type passed in args (ie 512KB or 1MB) then return the value in bytes.
In case of neither KB or MB was specified, 0x prefix can be used.
"""
for letter, multiplier in [("k", 1024), ("m", 1024 * 1024), ("kb", 1024), ("mb", 1024 * 1024), ]:
i... | 089d1d674b249d8ddb24432cce8df013bb9c8abb | 657,278 |
def col_dict_to_set(df, col, key):
"""Create a set from the values of the dictionaries given a key
Args:
df(pd.Dataframe): dataframe
col(str): column containing list of dictionaries
key(str): key to extract from the dictionaries
Returns:
A pandas Dataf... | 351aeeacdfe8c8230472f5e97b6497af69e1e42e | 657,279 |
from click.testing import CliRunner
def cli_runner(request):
"""A command line runner for click applications"""
return CliRunner() | b78936eaf5af430d08aee599b76f8679820122e7 | 657,280 |
def median(pool):
"""
Returns median of sample. From: http://wiki.python.org/moin/SimplePrograms
"""
copy = sorted(pool)
size = len(copy)
if size % 2 == 1:
idx = int((size - 1) / 2)
return copy[idx]
else:
idx1 = int(size/2) - 1
idx2 = int(size/2)
retur... | bfc1c63d09b1796d4509efab4cd52d4719567d78 | 657,281 |
import statistics
def estimate_epsilon(subsample_preds_algo1, classlist, subsample_preds_algo2=None):
"""
Input: - predictions on test subset by ML algorithm 1
- list of N classes
- OPTIONAL: predictions on test subset by ML algorithm 2, if a second one is leveraged
Output: a 3xN ... | 637d0289633de297cf82846fb827613c3592749a | 657,282 |
def _tensor_name_base(full_tensor_name):
"""Removes the device assignment code from a tensor.
e.g. _tensor_name_base("foo:3") => "foo"
Args:
full_tensor_name: A tensor name that is annotated with a device placement
(this is what tensor flow introspection gives).
Returns:
A name without any devic... | e8f524d5d17f1c6d47f29f7af19f6bffbb851f71 | 657,283 |
from typing import NamedTuple
def _to_dict(conf: NamedTuple):
"""Convert nested named tuple to dict."""
d = conf._asdict()
for k in conf._fields:
el = getattr(conf, k)
if hasattr(el, '_asdict'):
d[k] = _to_dict(el)
return d | 1ef32f61b3903ace12c80de78df934a50d6d14e1 | 657,284 |
import requests
import json
def vaultPutBulk(url, params, body, sessionId):
"""
Make an HTTP PUT request to Vault.
:param url: the URL to PUT
:param params: query parameters
:param body: update body
:param sessionId: vault sessionId
:return: responseStr: JSON response string from Vault A... | 8c8ddac049e4cbffced3af596ae7034e7692811c | 657,285 |
from pathlib import Path
def pathRes(p: Path):
"""Finds min length path for a file"""
p = Path(p)
return min((f(p) for f in (Path.absolute, lambda p: p.absolute().relative_to(Path(".").absolute())))) | 299da14adbb51508d11df112710503c9675eb124 | 657,286 |
import pkg_resources
def cerf_regions_raster():
"""Return the cerf regions raster file."""
return pkg_resources.resource_filename('cerf', 'data/cerf_conus_states_albers_1km.tif') | 283b2ced62e677af5d7dc076322fdde140fb686a | 657,288 |
import torch
def to_one_hot_vector(num_class, label):
""" Converts a label to a one hot vector
:param num_class: number of object classes
:param label: integer label values
:return: a vector of the length num_class containing a 1 at position label, and 0 otherwise
"""
return torch.nn.function... | 3ae1559db4d1a0f5174381ac2e70fc8df1f91aa1 | 657,289 |
def flatten_lists(l):
"""
https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists
"""
return [item for sublist in l for item in sublist] | cd79907d147cf11bada31463c559e344d50762ea | 657,290 |
def convert_dataset_into_spacy(df):
"""
Convert a dataset into the spacy tokens
:param df: dataframe
:return: list of converted entities
"""
data = []
for index, row in df.iterrows():
tokens, concepts = row["tokens"], row["concepts"]
entities = []
total_words = 0
... | ab6b9e12ad7753fa4b1df6779b977b733fb31566 | 657,291 |
def bswsa_should_halt(_seq, _stream, values, _context, _loaded_fields):
"""Halting function for :attr:`BasicStructWithSentinelArray.numbers`."""
if values and values[-1] == 0:
# Hit sentinel, remove it from the end of the array.
del values[-1]
return True
return False | 89bfb45266199b21052faa089dde194c9345cc95 | 657,292 |
import torch
def get_R_torch(angles):
"""Get rotation matrix R along verticle axis from the angle
Args:
angles (tensor[N]): In radian
Returns:
Rs (tensor[N, 3, 3])
"""
cs, ss = torch.cos(angles), torch.sin(angles)
zeros = torch.zeros(len(cs), device=angles.device)
ones = ... | 8b8ac6767444b7b561df98e930d55b1919203001 | 657,293 |
def fancy_join(lst, sep=", ", final_sep=" and "):
"""
Join a list using a different separator for the final element
"""
if len(lst) > 2:
head, tail = lst[:-1], lst[-1]
lst = [sep.join(head), tail]
return final_sep.join(lst) | 70a796fed566947cb2b26873a71b7e31a499bda1 | 657,294 |
import hashlib
def sha1_encoding(data: str) -> str:
"""
使用sha1加密算法,返回加密后str
:param data: 需编码内容
:return: data:str
"""
return hashlib.sha1(data.encode(encoding='UTF-8')).hexdigest() | 5c54924e70169207ece6ad5f690e1abc50aab906 | 657,295 |
import torch
def gate_sequence_product(U_list, n_qubits, left_to_right=True):
"""
Calculate the overall unitary matrix for a given list of unitary operations.
return: Unitary matrix corresponding to U_list.
"""
U_overall = torch.eye(2 ** n_qubits, 2 ** n_qubits) + 0j
for U in U_list:
i... | 2f5421a75495a16a823f967cdb06fc7b9d7d2ebb | 657,296 |
def path_to_calib_file(ctypedir, ctype, ofname) :
"""Returns path to file wirh calibration constants in the calib store.
e.g. /some-path/calib/Jungfrau::CalibV1/CxiEndstation.0:Jungfrau.0/pedestals/9-end.data
See parameters description in :py:meth:`history_record`.
"""
return '%s/%s/%s' % (cty... | 6b30ddc8bd693ffc2895321c14f12a227886111f | 657,297 |
from datetime import datetime
def datetime_fromisoformat(dts):
"""
Take an ISO format datetime string and return a datetime type.
The datetime.fromisoformat method was new in Python 3.7. This replacement
works on 3.6.9, which the author is still has on some machines.
It may work on older versions,... | f03072f65b585db88a33ec932c2d277c33e0b93f | 657,298 |
def add(x, y):
"""
加法
:param x:
:param y:
:return:
"""
return str(x + y) | b01feec46ed2c3c333cefc809f2f8f996354acc6 | 657,299 |
import yaml
def load_yaml(file_path):
"""Load a yaml file as a Python dictionary.
Args:
file_path: the absolute or relative path to the yaml file.
Returns:
the contents of the yaml file, as a Python dictionary.
"""
return yaml.load(open(file_path, "r"), Loader=yaml.Loader) | 4957d93dba11cdfb28ddb6caec545bd7590f4fa4 | 657,300 |
def capitalize(s):
"""
Capitalize the first char of a string, without
affecting the rest of the string.
This differs from `str.capitalize` since the latter
also lowercases the rest of the string.
"""
if not s:
return s
return ''.join([s[0].upper(), s[1:]]) | 5f07a8f3be64b4370827ae5ae94f67e2fafc2974 | 657,301 |
def fire_entity(entity_dict, key_ordering, data, expected_length=750):
"""
Applies transformation functions specified by the entity dictionary (first
param) to the user-supplied data (second param). If no user data is
supplied for the given field in the entity dictionary, then the default
value for ... | 40034e4b441c09c1f0ba4df5fb0020a71f5efa73 | 657,302 |
def SetTitleFromStub(obj, i, j, numrows, numcols, section, more, custom):
"""Copy the first row label outermost element and set as table title
The target table may need to have a title, which will be replaced."""
rowtext = more.rowlabelarray.GetValueAt(0,1)
more.pt.SetTitleText(rowtext)
mo... | 06ce2b6a304cb74949a7af5f1d1686d87e6ba74c | 657,303 |
def get_normalized_list(input_str):
""" Returns the comma-separated input string as a normalized list. """
items = input_str.split(",")
total = 0.0
for item in items:
total += float(item)
temp_total = 0
for index, item in enumerate(items):
temp_total += float(item)
items[... | fcf89ca6dd0d03dd09f6927cde599f12084689e0 | 657,304 |
def shorten(s, l, index=-1, token="..", token_length=None):
"""Return given string truncated to given length.
>>> shorten('bonjour', 10)
'bonjour'
>>> shorten('bonjour tout le monde', 10)
'bonjour ..'
>>> shorten('bonjour tout le monde', 10, index=4)
'bonj..onde'
>>> shorten('bonjour... | f34c730ccdf5b43fa9927d652f48bf8b5369e8e8 | 657,305 |
import asyncio
import functools
async def sync_to_async_view(func, *args, **kwargs):
""" Asgiref function is unstable, so use simple executor."""
return await asyncio.get_event_loop().run_in_executor(
None, functools.partial(func, *args, **kwargs)) | c53922b42ee3bea0fd36c4a02b1e8503eba21fbb | 657,306 |
def cpf_is_digits(value):
"""
This function receives the Brazilian CPF and returns True if it contains only digits or False if not.
:param value: A string with the number of Brazilian CPF
:return: True or False
"""
if value.isdigit():
return True
else:
return False | 84c3fca2c97ba84e892c9cbcc669c3b9c34c17a0 | 657,307 |
import hashlib
def _build_hash(target, meta_type):
"""Builds hash from target data and meta_type"""
digest = hashlib.sha1(target.encode('ascii')).hexdigest() # nosec
return meta_type + digest | a12c2f37ecbb7e95fe880febf030139acc5f3a29 | 657,308 |
import six
def key_by_value_dict(in_dict, value):
""" Reverse dictionary lookup.
Args:
in_dict (dict): Input dict.
value: Lookup value.
Returns:
Key in ``in_dict`` containing ``value`` if found.
>>> key_by_value_dict({'key1': 42, 'key2': 'forty-two'},... | 1a93146e6cd6a9ce6244ca19f7069a8c09f70bec | 657,309 |
def get_next_same_type_sibling(element):
"""
:type element: BeautifulSoup or Tag
:rtype: list[Tag]
"""
parent = element.parent
found_self = False
for x in parent.find_all(name=element.name):
if x.parent == element.parent:
if x == element:
found_self = True
elif found_self:
return x
return Non... | cbc621cb0305073df0ee99183aa926618086ed68 | 657,310 |
def moyenne_trois_nb(a : float, b : float, c : float) -> float:
"""Retourne la moyenne arithmétique des trois nombres a, b et c.
"""
return (a + b + c) / 3.0 | e86f22f5ef9fbee2420cd11341272f6e8c54d895 | 657,311 |
from functools import reduce
def solve(n, ar):
"""
Return the sum of the elements in array, ar of size n.
This is the same problem as "Simple Array Sum" but the twist is that the
elements of the array are in the order of 10^10. In python, however, values
are autocast to whatever type/size they nee... | bae2fe96f0d05962cec6f9d45fffd3fcce0dc037 | 657,312 |
def bin_to_dec(bin_str):
"""Convert a string of bits to decimal."""
result = 0
for i, bit in enumerate(bin_str[::-1]):
result += int(bit) * 2**i
return result | f49a9f0ee25e886111407bd20688567ee7e9a16f | 657,313 |
def purge_spikes_beyond_tracking(spike_train, tracking_ts, full_purge=True):
"""
Parameters
----------
spike_train : np.ndarray
Spike times in seconds.
tracking_ts : np.ndarray (2, )
The start and end of tracking relative to sessions start.
full_purge : bool
Remove spikes... | 9cb7c2618b642206fed88693bb4ed5326cc5ee7e | 657,315 |
def reverse_table(tab):
"""
Reverse a table
Parameters
table of numbers
Returns reversed table
"""
for i in range(len(tab)//2):
list_len = len(tab)
tmp = tab[i]
endid = list_len - i - 1
tab[i] = tab[list_len - 1]
tab[i] = tab[endid]... | 9b8c2a0b572fc3d9ef7b56cb83f7762643e60bfa | 657,316 |
def is_same_width(w1, w2):
"""Return true if is the same width of images else return false"""
if w1 == w2:
return True
return False | da6d23828de1eb35878dea4f9db0c676d01cc0c2 | 657,317 |
import re
def loadtxt(value):
"""
Load text from file or string.
Examples
--------
>>> loadtxt(value="temp/text.txt")
:param value: <str> could be a text or a path to text file.
:return: <str> Text from input or file.
"""
if re.match(r'^(([a-zA-Z]:)|((\\|/){1,2}\w+)\$?)((\\|/)... | a0da58e7b72c587e7c33e0ea7366ae6714cf123c | 657,319 |
def apply_antialiasing(kernel, kernel_width, scale_factor,
antialiasing):
"""
Antialiasing is "stretching" the field of view according to the scale
factor (only for downscaling). This is produces the low-pass filtering.
This requires modifying both the interpolation (st... | 96e2417722532634aba8a8ea85e4c30140dbf855 | 657,320 |
def pts_to_mm(pts) -> float:
"""
ptsからmmに変換します
ページサイズの計算方法
Page sizeの単位は、ptsです。例えば、横幅が420 ptsだと、420 pts / 72 (pts/inch) * 25.4 (mm/inch) = 148 mmでA5となります
※ 72 (pts/inch) * 25.4 (mm/inch) ≒ 0.352778
:param pts:
:return:
"""
return float(pts) * 0.352778 | 1699f6030619cfd5371487ea57848f11be77d468 | 657,321 |
def _iterateTrixelFinder(pt, parent, max_level):
"""
Method to iteratively find the htmid of the trixel containing
a point.
Parameters
----------
pt is a Cartesian point (not necessarily on the unit sphere)
parent is the largest trixel currently known to contain the point
max_level is... | 1cde08a587206b1028380f7376ab184d0143892d | 657,322 |
from pathlib import Path
from typing import List
from typing import Dict
from typing import Any
import json
def get_project_details(user_dir: Path) -> List[Dict[str, Any]]:
"""
This function iterates all the project directories in the user_directory and fetches the project details from the project_config.json... | 2437e2addc32c3703c93c6dad3e24f58c764e6a8 | 657,323 |
from functools import reduce
def pip(*funcs):
"""
[f,g,h] -> x -> h(g(f(x)))
Usage
-----
piped = pip(
square,
add(5)
)
compose(0) is 5
"""
def g(a):
return reduce(
lambda acc, f: f(acc),
funcs,
a
)
return g | 4f5e150d544c16d69d9ef965f23756281acc6522 | 657,324 |
import string
def find_name(input_str):
"""
A simple algorithm to extract names.
Parameters:
input_str(str) -- string containing the name
"""
for each in ['i am', 'i\'m',"i’m",'this is', 'name is', 'my name is','it is','you can call me','i am named after']:
_index = input_str.lowe... | 98296535f581cda07651d042721846e2fae8f7dd | 657,325 |
def netids_above_cutoff(grades, cutoff):
"""Returns list of netids with grades above or equal cutoff
Precondition: grades has netids as keys, ints as values.
cutoff is an int."""
netid = []
for key in grades.keys():
if grades[key] >= cutoff:
netid.append(key)
return netid | f11987303955ac968769078ece49b9b4ed6cb011 | 657,326 |
import typing
import aiohttp
import time
async def create_mmt(now: typing.Optional[int] = None) -> typing.Mapping[str, typing.Any]:
"""Create a new hoyolab mmt."""
async with aiohttp.ClientSession() as session:
r = await session.get(
"https://webapi-os.account.hoyolab.com/Api/create_mmt",
... | 97da497811de1a20374ee065ada48dccd3bf2e11 | 657,327 |
import hashlib
def PBKDF2(self, mnemonic, salt=""):
"""
Uses the PBKDF2 key-stretching function to stretch the mnemonic to a 512-bit value. The use
of salt is optional
Parameters:
mnemonic (String): the mnemonic code words to stretch
salt (String): An addi... | d333782599b2b75e3fad6a9b54575186aac24b2c | 657,328 |
def update_store(coin_store1, coin_store2):
"""Updates the contents of a coin store with values from another store."""
for coin_type, coin_num in coin_store2.items():
coin_store1[coin_type] += coin_num
return coin_store1 | 7f5d8620de39279e28cf52c73e12790bbeae7b8a | 657,330 |
def user_converts(predicted_value):
"""
Converts the predicted value into text and styles for easy visualization
:param predicted_value:
:return:
"""
style = {"border-radius": "20px", "padding": "10px", "vertical-align": "middle", "margin": "auto"}
if predicted_value == 'No Value':
... | 289236e40dd9b57d110018b32a8f5cdcc589b74a | 657,332 |
def tuples_to_dict(pairs, verbose=False):
"""
Take a list of paired tuples and convert to a dictionary
where the first element of each tuple is the key and the
second element is the value.
"""
d={}
for (k, v) in pairs:
d[k] = v
if verbose:
if isinstance(v,float):... | 41e25f3e39b51743d4ea41666207ed7f42845a6d | 657,333 |
def masked_max(hiddens, mask): # B x T x d, B x T
"""mask[i][t] = 1 iff the token is to be IGNORED"""
B, T, d = hiddens.size()
mask = mask.unsqueeze(2).expand(B, T, d)
hiddens = hiddens.float().masked_fill_(mask, float('-inf'))
pooled, indices = hiddens.max(dim=1)
return pooled, indices | acf55d1c542818e38e2f4d137d55dedf871192eb | 657,334 |
import re
def redis_mask_to_regex(mask):
"""Для тестов переводит маску редиса в регулярку
Замена не полная - только для звёздочки
"""
regex = re.sub(r'\*', '.*', mask)
return f"^{regex}$" | 6e74cfdc723b1ac87112b9bb015c2344a146eee6 | 657,335 |
def sort_swin_records(output_list):
"""
Sort SWIN output records.
Parameters
----------
output_list : list of [st0,st1,vis,chan,pol0,pol1,header,values_bytes,diff_st]
see convert_cx2d.output_list.
Notes
-----
|
| **Sorting is as follows:**
|
| 1. accum... | 695b0272ba5895bf59335f44310c50be7fa4be2c | 657,336 |
def _append_docstring(func, supplement, insert_in="Parameters", at_end=True):
"""
Local helper to automate text insertions in docstrings
Parameters
----------
func : callable
Typically a (wrapped) Syncopy metafunction such as :func:`~syncopy.freqanalysis`
supplement : str
Te... | 2a3e865d461c7d2dc2ff367a267e21c4b91676d9 | 657,337 |
def _detect_top_level_module_name():
"""
Simple function to try to auto-detect the top-level module name, based
on the name of this module. This can be used to name a logger. Hopefully
this makes it adapt to module refactoring; we don't have to hard-code
anything. I anticipate that all logging in... | 2c8b5d34acff699444006773c8f77c24a2d27e78 | 657,338 |
def get_float(prompt, lower_bound, upper_bound):
"""Prompt the user for a number and return the number as a float.
Parameters
prompt: A string to display to the user.
lower_bound: The lowest (smallest) number that the user may enter.
upper_bound: The highest (largest) number that the us... | e935cf2b6946d8969863f0fc28342ca16b98a472 | 657,341 |
def validate_height(height: str) -> bool:
"""
Validate the height field of the password.
This validator accepts heights in the units centimeter and inch.
"""
if height.endswith("cm"):
return "150" <= height[:-2] <= "193"
elif height.endswith("in"):
return "59" <= height[:-2] <= ... | dcd4964f7a75c1ac3e3f24cc88e4ea6cc8deadc6 | 657,342 |
import re
def parse_circle(msg):
"""Parse the message from CIRCLE and return the line numbers"""
matches = re.findall(r"LINE NO.=\s*(\d*)", msg)
if matches:
return [int(match) for match in matches] | 8d9ca1640691f74f84eb7da1db91b36a058ff743 | 657,343 |
import torch
def L2_penalty(B_cp):
"""
Compute the L2 penalty.
RH 2021
Args:
B_cp (list of torch.Tensor):
Beta Kruskal tensor (before softplus)
Returns:
L2_penalty (torch.Tensor):
L2 penalty.
"""
ii=0
for comp in B_cp:
# for comp in B_c... | 5a6b9f81015b86383d0cb7700e8401cc83f05537 | 657,345 |
def generate_hashtag_from_noun_chunk(chunk_list, subj_obj_list):
"""method for generating hastags from noun chunks"""
hash_tag_list = []
if not chunk_list:
return None
else:
for chunk in chunk_list:
if chunk.lower() not in subj_obj_list:
chunk_words = [word.ti... | 56c3269e135bfb91f14b797315b7282ca803ce66 | 657,346 |
import os
import sys
def get_conf_file(conf_name):
"""Function for converting a config name to a path to the actual config file.
:param conf_name: specifies the config name
:type conf_name: str
:return: path to the file as a string
"""
if not isinstance(conf_name, str):
raise TypeError("Argument not ... | 6dfc1ef932b6d1cbf1542966525d637a3bf876e0 | 657,347 |
from typing import List
def _str2list(s: str) -> List[str]:
"""Converts str into list - use for list of OCLC numbers"""
return [n.strip() for n in s.split(",")] | cc9a132b268759db01391291b6607c0c36e07ecb | 657,349 |
import re
def escape_name(name):
"""Escaped wheel name as specified in :pep:`427#escaping-and-unicode`."""
return re.sub(r"[^\w\d.]+", "_", name, flags=re.UNICODE) | 08baa74768be4e0e002ed51d083f33c3e00989f1 | 657,350 |
def StrNoneChk(fld):
""" Returns a blank string if none """
if fld is None:
return ""
return str(fld) | 3f9e7c1fe2b9ee6986c2853be7cfdb3c64bfa3df | 657,351 |
import logging
import subprocess
def get_pid_by_str(search_str):
""" Search pid by its command line """
logging.info("Searching process by string: %s", search_str)
out = subprocess.check_output(['ps', '-A', '-o pid,command'])
out = out.decode()
for line in out.splitlines():
if "openvpn" n... | ac13ce4ce905da2a101569c3dabb5d8209155562 | 657,352 |
def get_coordinates_here(response):
"""
Returns a tuple with the lat/long
:param response: dict - The here response object
:return: double, double
"""
try:
lat = response["Response"]["View"][0]["Result"][0]["Location"][
"NavigationPosition"
][0]["Latitude"]
lo... | 455727343db0874fd324e85a681798048690fbc3 | 657,354 |
def add_residue_to_dfix(dfix_head, resinum):
"""
Add a residue to a list of DFIX/DANG restraints
DFIX 1.234 C1 C2 -> DFIX 1.234 C1_4 C2_4
>>> add_residue_to_dfix(['DFIX 1.456 C1 C2', 'DFIX 1.212 C3 C4'], 4)
['DFIX 1.456 C1_4 C2_4\\n', 'DFIX 1.212 C3_4 C4_4\\n']
>>> add_residue_to_dfix(['DF... | 69fd5b22a6ef9c1ffe6956ce658a9761f1781238 | 657,355 |
import inspect
def filter_args(dict_to_filter, fn):
""" Function that filter +dict_to_filter+ to work with fn """
# Taken from https://stackoverflow.com/questions/26515595/how-does-one-ignore-unexpected-keyword-arguments-passed-to-a-function
sig = inspect.signature(fn)
filter_keys = [param.name for p... | 8a19e6a4bd4bf931a765ad65004a8e405c5df877 | 657,356 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.