content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from datetime import datetime
def get_time():
"""
This is just a wrapper of datetime.datetime.now to simplify mocking in the
unittests.
"""
return datetime.now() | 40e88ed69cf80dab76f25347a74617bac28c454a | 632,180 |
import requests
def status_crawler(LEETCODE_SESSION: str, question_name: str) -> bool:
"""Check if question solved
Args:
LEETCODE_SESSION (str): User's LeetCode session.
question_name (str): LeetCode question name.
Returns:
bool: Solved or not.
"""
cookies = {"LEETCODE_SE... | 0cad01ba7331680628da089c33cc9dccf37d3815 | 632,181 |
def edgeCheck(yedges, xedges, coord, sp_buffer):
"""Identify edge cases to make merging events quicker later"""
y = coord[0]
x = coord[1]
if y in yedges:
edge = True
elif x in xedges:
edge = True
else:
edge = False
return edge | ac3920adb04f0263a5843c12f528f01cfa590acb | 632,182 |
import numbers
import math
def is_scalar_nan(x):
"""Tests if x is NaN.
This function is meant to overcome the issue that np.isnan does not allow
non-numerical types as input, and that np.nan is not float('nan').
Parameters
----------
x : any type
Returns
-------
boolean
Example... | 7af08b4f4f6f3a77b6ce96c683781c415a6abebf | 632,184 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_ansible package"""
reload_params = {"package": u"fn_ansible",
"incident_fields": [],
"action_fields": [u"ansible_hosts", u"ansible_module", u"ansible_module_arguments", u"ansible_playbook_name", ... | 43ac71c83ca229fd94154678bd0989a5b925e2e7 | 632,185 |
import os
import sys
def get_server_name():
"""Gets the TANGO server name from the command line arguments
Returns
=======
server_name : str
tango device server name
Note
====
Extract the Tango server_name or equivalent executable
(i.e.sim_xmi_parser.py -> sim_xmi_parser or
... | 5723cad1cd91dbf80897a65a88b0631ede3ef325 | 632,187 |
def resolveFieldIndex(source, attr):
"""This method takes an object and returns the index field it
refers to in a layer. If the passed object is an integer, it
returns the same integer value. If the passed value is not an
integer, it returns the field whose name is the string
representation of the p... | 6173ca3deb54e730cb1c45912e73b2c08149c59e | 632,188 |
import pprint
def just_metadata(conc_results):
"""Find the book metadata and return that"""
for r in conc_results:
# ('footer', footer)
if isinstance(r, tuple) and r[0] == 'footer':
# NB: pprint will sort dicts for us
return pprint.pprint(r[1])
raise ValueError("No... | 8e906b533052fa4dacda36beae48259ff7e919a1 | 632,189 |
import random
def random_lineup(DF, formation):
"""create random 11 person lineup
starting with 4-4-2 layout (DEF, MID, FW + assumed GK)
(1xGK, 2xFW, 2xILRM, 2xW, 2xWB, 2xCLRD)
lineup_dict = {players_name, position}
DF is Positions as columns, Names as rows
"""
#formation = ['FW', 'FW', 'I... | ee78951f1095c35ff4a11369b7304b0e4fe45768 | 632,190 |
import os
def get_measurement_time(spectrum_file):
"""
Reads time of measurement from mcd file of same name as spectrum file.
"""
# get mcd file of respective spectrum file
mcd_file = '%s.%s' % (spectrum_file.split('.')[0], 'mcd')
# file does not exist
if not os.path.isfile(mcd_file):
... | 89aaaa988d83c54d64199917733dd98554b094b5 | 632,191 |
def add_special_tokens(tokenizer):
""" Returns GPT2 tokenizer after adding separator and padding tokens """
#tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
special_tokens = {'bos_token':'<|startoftext|>','eos_token':'<|endoftext|>', 'pad_token':'<|pad|>','sep_token':'<|summarize|>'}
num_add_toks = tokenizer.add_... | df424fb3ef9e4db5f66f12a81dcb9974376cfa75 | 632,192 |
from typing import Sequence
def sub_seq(s1: Sequence, s2: Sequence) -> bool:
"""
Checks if sequence s1 is subsequence of s2,
:param s1: First sequence.
:type s1: Sequence
:param s2: Second sequence.
:type s2: Sequence
:return: True if s1 is subsequence of s2.
:rtype: bool
"""
... | 4bb5c7eb8b680129fd3f419479d22ec787bea6ed | 632,193 |
def _plot_hist(values, *, axis, **kwargs):
"""
Plot histogram subplot
"""
return axis.hist(values, **kwargs) | 09581f0ab3981bbf4f38c73f1c898cc0d10ceedd | 632,195 |
def drop_null_rows(df):
"""Drop all rows containing null values"""
return df.dropna().reset_index(drop=True) | c7bb10b89b9fddd0f526443368214b3d8da278ef | 632,196 |
def get_error_name(error):
"""Return canonical error name as string.
For builtin errors like ValueError or Exception, will return the bare
name, like ValueError or Exception.
For all other exceptions, will return modulename.errorname, such as
arbpackage.mod.myerror
Args:
error: Except... | de57d629ba53d453ab3066c3f4024df42efef11e | 632,197 |
import re
def get_host(email: str) -> str:
""" Get host from email
Arguments:
email (str): email to get host from
Returns:
str
"""
try:
host = re.findall(r"@(.*)$", email)[0]
if "." not in host:
host = "invalid"
except IndexError:... | 4f50704247118d19584c1b4b58ef4f8c085a86e3 | 632,198 |
def is_s3_path(path: str) -> bool:
"""Returns True if the path points to a S3 bucket, False otherwise."""
return path.startswith("s3://") | e559486b24e357ce27931456763848e9b7505b1f | 632,199 |
def slug_is_available(slug, job_category_model, job_category=None):
"""
Determine whether the given slug is available for use and not a duplicate
"""
JobCategory = job_category_model
siblings = JobCategory.objects.all()
if job_category:
siblings = siblings.exclude(id=job_category.id)
... | 20d8014dc8a6574bc0253eae7f22ddb42edb2998 | 632,200 |
def st_fleet_details(fleet, user):
"""
Details of a sitetracker fleet.
"""
return {'fleet': fleet, 'user': user} | cb66b728b18de0bb26fce6fb7321e9f3638b3b60 | 632,201 |
def get_sub_neptune_radius(Mp, f_env=0.01, Fp=1.0, age=5.):
"""Approx M-R relation from Lopez & Fortney (2014)
https://iopscience.iop.org/article/10.1088/0004-637X/792/1/1/"""
Renv = 2.06 * (Mp**-0.21) * ((f_env/5.)**0.59) * \
(Fp**0.044) * ((age/5.)**-0.18)
Rcore = Mp**0.25
return Renv ... | 264190f1defecf71aedd4a9f66fbab99d77d80cc | 632,202 |
import json
def parse_env(environment_string: str) -> str:
"""
Parses an environment string as passed from the command line and ensures that it is a JSON
object with the appropriate structure (i.e. a map of strings to strings)
Args:
environment_string
JSON string denoting a mapping of env... | 3fc588c23007a3df7b1f52e3ed23efdd970437f1 | 632,203 |
from typing import Counter
def get_sources_by_geo(news_list, limit=10):
"""
:param news_list:
:param limit:
:return: dict of the most speaking sources bout a location
"""
sources = Counter()
sources.update(news.source for news in news_list)
return dict((k, v) for k, v in sources.most_c... | 8e2c647b37540f945a7d192c198e9cd209628a7b | 632,204 |
def toint(number):
"""
Helper to return rounded int for a float or just the int it self.
"""
if isinstance(number, float):
number = round(number, 0)
return int(number) | 23f07ba85a5a674330c006187c7d6f01aa94716b | 632,205 |
def get_asset_url(release, quiet=False):
"""
get the assets url from the release information
:return: the assets_url
"""
return release["assets_url"] | 38815dce5158c4980e57a4cf7aa7a386e371e57f | 632,206 |
def check(classtype, subclass=False):
"""Type checking."""
def _second(f):
def _inner(self, value):
if value is not None:
if subclass:
if not isinstance(value, classtype):
raise TypeError("{0} is an invalid type. Accepts an instance... | 77f89fdf7782c5efd296d491fb2d11926e431a97 | 632,207 |
import glob
import os
def sort_dir(dir_name):
"""
:param dir_name: Full directory name to be sorted
:return: Sorted directory according to first (subID) and third value (TI) following underscores
"""
print(dir_name)
listed_niis = [os.path.basename(x) for x in glob.glob(os.path.join(dir_name, '... | d8d34b53e3324b84e7b9438e561a756360d3d79d | 632,208 |
import torch
def make_pad_mask(seq_lens):
"""Make mask for padding.
Args:
seq_lens (IntTensor): `[B]`
Returns:
mask (IntTensor): `[B, T]`
"""
bs = seq_lens.size(0)
max_time = seq_lens.max()
seq_range = torch.arange(0, max_time, dtype=torch.int32, device=seq_lens.device)
... | 10f264cf9578d1ef18d7073aad589a9b5ed575e8 | 632,209 |
import os
import sys
def getenv_or_exit(name):
""" Gets the required variable from the environment. Closes the application
with error if it's not set.
Args:
name (string) - The name of required environment variable.
Return:
var (respective type) - The value of the variable.
"""... | 34762df9035bd7de37c5d6cc49563367cbd9078d | 632,210 |
def _construct_key(previous_key, separator, new_key):
"""
MIT License
Copyright (c) 2016 Amir Ziai
Returns the new_key if no previous key exists, otherwise concatenates previous key, separator, and new_key
:param previous_key:
:param separator:
:param new_key:
:return: a string if previ... | fdd4dc5a986318553ac7e663d58c6749646bfb57 | 632,211 |
def _data_range(data: str) -> bool:
""" Checks if a string data are a numbers in range. """
return True if data.find('-') != -1 else False | 16ba9bade3ec711c59e33f0410d6b48eda4963e6 | 632,212 |
from typing import Any
from typing import Tuple
import operator
def _ensure_index_tuple(x: Any) -> Tuple[int, ...]:
"""Convert x to a tuple of indices."""
try:
return (operator.index(x),)
except TypeError:
return tuple(map(operator.index, x)) | 3c328971d7110f826f377aee008f85027caa28f8 | 632,213 |
def bounding_box(points):
"""returns a list containing the bottom left and the top right
points in the sequence
Here, we use min and max four times over the collection of points
"""
top_left_x = min(point[0] for point in points)
top_left_y = min(point[1] for point in points)
bot_r... | 8cb61061c22effdc4bcb9e5f5037c26e52238a11 | 632,214 |
import string
def clean_punctuation(texts):
"""Remove punctuation from strings"""
cleaned_tokens = [[word.strip(string.punctuation) for word in sentence] for sentence in texts]
return cleaned_tokens | 06f76dd62ae047b5379b9047f737673bc52c63e8 | 632,216 |
def kHat(c, ell, em, ess=-2):
"""
Compute diagonal elements of sparse matrix to be solved.
Inputs:
c (float): a * omega
ell (int): swsh mode number
em (int): mode number
ess (int) [-2]: spin number
Returns:
kHat (float): diagonal element
"""
# print(ell)... | 762a7e214dd6429ada6ac9038f235ed892572252 | 632,217 |
def common_chars(seq, k):
""" Returns the set of characters that appear more than k times in
the input string, along with their number of occurrences.
Example:
>>> common_chars("cat in a hat", 2)
{("a", 3), (" ", 3)}
"""
chars = set()
for i in range(len(seq)):
if seq.count(seq[... | 9a2fc7cfae84ae06abc54526e6a9b020ba238367 | 632,218 |
import csv
def get_data():
"""
"""
f = open("../data/new_train.csv")
reader = csv.reader(f)
data = []
for row in reader:
data.append((row[0]+" "+row[1],row[2]))
return data | 6da19d1cd0939d6252ad1e7d08c5fed90fae586b | 632,219 |
def extract_data_key(returned_data):
"""
Build and return dict containing measurement 'name', description ('text')
and unit of measurement.
"""
return {i["name"]: {"text": i["$"], "units": i["units"]} for i in returned_data["SiteRep"]["Wx"]["Param"]} | 7c9ba5e1d4f0c6f416f5f1f370ea52bc68b3e1cf | 632,220 |
def _gen_index_list_to_fifty_mbyte_increment(file_buffer_list):
"""Create a list of indexes marking the ~50 MByte increments of cumulative size
of the file_buffers provided by the streamlit.file_uploader
Parameters
----------
file_buffer_list : ``list``
list of file_buffers (derived from io... | 35ed1ce2dfe81e216d87b66b77f078386b8404a4 | 632,221 |
from datetime import datetime
import pytz
def current_year():
"""Gets the current year in the US/Eastern timezone"""
d = datetime.now()
timezone = pytz.timezone("US/Eastern")
d_aware = timezone.localize(d)
return d_aware.year | 3aa3a04134632fbb57e913c13e419629aa79046d | 632,222 |
def get(execution_id, client):
"""Request a execution with certain ID."""
return client.get_execution(str(execution_id)) | 723cfef7b67be2e3307ec4f7313e2381446ac1df | 632,223 |
import torch
def mask_background(image_rgb: torch.Tensor, mask_fg: torch.Tensor, ch_axis=-3):
"""
Mask the background input image tensor `image_rgb` with `bg_color`.
The background regions are obtained from the binary foreground segmentation
mask `mask_fg`.
"""
tgt_view = [1] * len(image_rgb.s... | 772dcc4e16f076699d06677691f60f3690d23290 | 632,225 |
def harmonic( ranks ):
""" returns the harmonic mean of the assembly's ranks
"""
h = 0
for r in ranks:
h += 1.0 / r
h = 1.0 / h
h *= len( ranks )
return h | 25f998396b700fe774afa84d2ec17c4da8f7f388 | 632,226 |
def input_key_judge(bin_key):
"""
全部秘钥以补0的方式实现长度不满足64位的
:param bin_key:
"""
ans = len(bin_key)
if len(bin_key) < 64:
if ans % 64 != 0:
for i in range(64 - (ans % 64)): # 不够64位补充0
bin_key += '0'
# else:
# bin_key = bin_key[0:64] #秘钥超过64位的情况默认就是应该跟密文一样长 直接将密钥变为跟明文一样的长度,虽然安全性会有所下降
return bin_key | a0105f88875e50681424885810713dcf9225b3f8 | 632,227 |
def push_stream(cache, user_id, stream):
"""
Push a stream onto the stream stack in cache.
:param cache: werkzeug BasicCache-like object
:param user_id: id of user, used as key in cache
:param stream: stream object to push onto stack
:return: True on successful update,
False if fa... | ff2213edf1f0ee65edd73e4318eb6bc9a64700d7 | 632,228 |
def querysort(value, arg):
"""
Sorts a query set based on a field
"""
value = value.order_by(arg)
return value | ccbf5d07648360a10fa0314a5a490f6de582b605 | 632,229 |
import numpy
def solution(resources, args):
"""Problem 11 - Version 1
Go through all possible 4-adjacent values (vertical, horizontal, and
diagonal) in the 20 x 20 matrix and find the maximum product.
Parameters:
resources The 20 x 20 matrix (numpy.array)
Return:
The quadruple... | b5cd1dea6dfc0e9cb58c01f887a312278f8ef57a | 632,230 |
from typing import Tuple
import re
def format_header(header: str) -> Tuple[str, int, str]:
"""Calculates the level of the header, removes leading and trailing whitespaces and creates the markdown-link.
:param header: header line from the markdown file
:return: a tuple consisting of the cleaned header, th... | 7dc52247d4c9702d03f402634ef615a359084373 | 632,231 |
def load_features_list(input_path):
"""
Reads in a file of distinct feature names line-by-line and returns
these features as a list. Each feature name in the file must occur
on a separate line.
Parameters
----------
input_path : str
Path to the features file. Each feature in the inp... | df36db1f537d407d2769f70dc4e143542fccb363 | 632,232 |
def get_nodedepth(node, root=None):
"""Return the node's depth"""
if node.is_island() or node.is_root():
return 0
if root:
roots = [root]
else:
roots = node.get_roots()
return min(map(lambda x: x.distance(node), roots)) | f6e52bcec21d9e70f6f115b28861304435863bee | 632,233 |
def all_bases_valid(seq):
"""Confirm that the sequence contains only bases"""
valid_bases = ['a', 'A', 'c', 'C', 'g', 'G', 't', 'T', 'N']
for base in seq:
if base not in valid_bases:
return False
return True | ff04072d7280d1f09e11d6c0f5537861a5cb38e7 | 632,234 |
def _format_permission(decimal_permissions):
""" formats a decimal representation of UNIX-style permissions,
removing leading 0 for octal numbers with length > 4,
into a string representation """
return "{0:04o}".format(decimal_permissions)[-4:] | 8fe7000f6f2ca027e4012fcedf59f0104f48b511 | 632,235 |
import os
def here(subpath=None):
"""
:return: the path in which the package resides (the directory containing the 'kgbench' dir)
"""
if subpath is None:
return os.path.abspath(os.path.dirname(__file__))
return os.path.abspath(os.path.join(os.path.dirname(__file__), subpath)) | 1bbca9cb118b4961a7461b84f8eb27a5a54c85fc | 632,237 |
import itertools
def bool_split_iters (seq, predicate = bool) :
"""Return an iterator pair yielding the false, respectively true,
elements of `seq`, as determined by `predicate`
>>> seq = list (range (10))
>>> _show (list (x) for x in bool_split_iters (seq))
[[0], [1, 2, 3, 4, 5, 6, 7, 8, 9]]
... | aac59e70b7d71bb28bd6da839d47fd3baa06170e | 632,238 |
import six
def to_float(x):
"""Convert an object to a float, unless it is None
Examples:
>>> print(to_float(12.3))
12.3
>>> print(to_float('12.3'))
12.3
>>> print(to_float(None))
None
"""
if isinstance(x, six.string_types) and x.lower() == 'none':
x = None
retu... | 4ac05529e0eb733c3d0901896e87e9f6a5fd4915 | 632,239 |
import torch
def stack_lengths_to_batch_indices(stack_lengths, device=None):
"""
Example:
[2, 3] -> [0, 0, 1, 1, 1]"""
return torch.cat([torch.tensor([b] * l, dtype=torch.int64, device=device)
for (b, l) in enumerate(stack_lengths)]) | 63fb852fa113bb33ad4047634b293f26ba53a485 | 632,240 |
import functools
def len_gen(gen):
"""return length of a generator.
built-in len() does not work on generators.
Note: like iterators, generators can only iter once, so after running
len_gen() on it, you can't iter over it again.
"""
return functools.reduce(lambda x, y: x + 1, gen, 0) | 85633117872a3df2d2baa6ea0bbdd80ea8b69a22 | 632,241 |
def matrix_transpose(matrix: list) -> list:
"""
Compute the transpose of a matrix
"""
transpose: list = []
for row in range(len(matrix[1])):
column = []
for col in range(len(matrix)):
column.append(matrix[col][row])
transpose.append(column)
return transpose | bd6b3c6befb3efb488ad5f4ec33d181042e35574 | 632,242 |
import torch
def gmm_loglikelihood(x_t, x_loc, log_var, mask_logprobs):
"""
mask_logprobs: [N, K, 1, H, W]
"""
# NLL [batch_size, 1, H, W]
sq_err = (x_t.unsqueeze(1) - x_loc).pow(2)
# log N(x; x_loc, log_var): [N, K, C, H, W]
normal_ll = -0.5 * log_var - 0.5 * (sq_err / torch.exp(log_var))... | 5b155dbc7efe9f283a7e37600faad9e3dff05308 | 632,243 |
import time
def my_decorator(fn):
"""my_decorator is a custom decorator that wraps any function
and prints on stdout the time for execution.
"""
def wrapper_function(*args, **kwargs):
start_time = time.time()
# invoking the wrapped function and getting the return value
value =... | a4f09253d4230403a69e05dc50435c3469701a51 | 632,244 |
def strtobool (val, yesvals = ["yes", "y"], novals = ["no", "n"]):
"""Convert a string representation of truth to true (1) or false (0).
Raises ValueError if 'val' is anything else."""
val = val.lower()
if val in yesvals:
return 1
elif val in novals:
return 0
else:
raise ... | a273f56761f9fd675668408f629051ea11cf8a42 | 632,245 |
def solve_dlog_naive(g, h, dlog_max):
"""
Naively attempts to solve for the discrete log x, where g^x = h, via trial and
error. Assumes that x is at most dlog_max.
"""
for j in range(dlog_max):
if g ** j == h:
return j
return -1 | 28acf74c0d7e946ac7bd4e911e43741dc0cf0e7f | 632,246 |
def title_is_in_row(title_search_string, title_row):
"""Returns true if the target title in the passed row."""
return title_search_string.lower() in title_row.lower() | baf5e0e57cc90907b5d8d8ee44435245ee58eacd | 632,247 |
def _rsMultiply(a, b):
""" Return the product of the multiplication """
# <www.wikipedia.org/wiki/Finite_field_arithmetic#C_programming_example>
p = 0
while a and b:
if b & 1:
p ^= a
if a & 128:
a = (a << 1) ^ 285
else:
a <<= 1
b >>= 1
... | b04bd0536ae4fc74a7f558d68bedeba51af62f8b | 632,248 |
def clean(text):
""" mainly for cleaning < and > from `Repr`s """
return text.replace('<', '<').replace('>', '>') | 5b78d6ce237df93a1bc9d9001def0080e81d22f0 | 632,249 |
from typing import Iterable
def _is_iterable(value):
"""
Check whether the value is an iterable (excludes strings).
*value* is the value to check,
Returns whether *value* is a iterable (:class:`bool`).
"""
return isinstance(value, Iterable) and not isinstance(value, (str, bytes)) | 45b3bbfb142738e132d47d649fe7340e16480fea | 632,250 |
import tarfile
def scan_gz(filepath):
""" Scan a .tar.gz file. """
return tarfile.open(filepath, 'r:gz').getnames() | 547dc0a5e0301f1a198823a4ca6c770efa8f2309 | 632,251 |
def printAngle(angle, shift, molecule, alchemicalTransformation):
"""Generate angle line
Parameters
----------
angle : Angle Object
Angle Object
shift : int
Shift produced by structural dummy atoms
molecule : molecule object
Molecule object
alchemicalTransformation :... | 0e4d20acce1a7f8abbd2efee07d319df2955a814 | 632,252 |
def label_case(snake_case):
"""Specialized helper function to replace underscore with spaces and capitalize first letter of string, but keep WMR and WMQ capitalized
Args:
snake_case (str): String written in snake case to be reformatted.
Returns:
str: The reformatted string.
... | 54bce935de444c1fdc99ce22dc3809f5cd38e0d4 | 632,253 |
def clip(val, minval, maxval):
"""clip val between minval,maxval"""
return max(min(maxval, val), minval) | 34da06a4895996c804f12462d70cfce9d2242e82 | 632,256 |
def parse_espn_dates(date, identifier, b_identifier=True):
"""Parse for subset date of the original date
Args:
date (str) - date of a tournament (ex. 'Oct 5-8 2018')
identifier (str) - ident. to be searched for
b_identifer (bool) - flag to tell where subset search begins
Returns:
... | dffec50e4deabcaceaee6696ed163b17d8fd5750 | 632,257 |
def ComptonRotationAngle(azimuth):
"""Reference frame rotation so that MuellerMatrixCompton holds
Args:
azimuth(num): scattering azimuth (degree)
Returns:
angle: rotation of the axes in degrees
"""
# First component axis perpendicular to the scattering plane
return azimuth - 90 | 522b9b5acb8b6d83f09a88c456b4cd0dc8318ce8 | 632,258 |
from typing import List
import torch
def _collate_frames(
frames: List[torch.Tensor], is_audio_input: bool = False
) -> torch.Tensor:
"""
Convert a list of 2D frames into a padded 3D tensor
Args:
frames (list): list of 2D frames of size L[i]*f_dim. Where L[i] is
length of i-th ... | 4af59bf4a4c93b4957799d90f6a45d413e943102 | 632,259 |
def get_user_pool_domain(prefix, region):
"""Return a user pool domain name based on the prefix received and region.
Args:
prefix (str): The domain prefix for the domain
region (str): The region in which the pool resides
"""
return '%s.auth.%s.amazoncognito.com' % (prefix, region) | c43cb15bb960281f6ffbe5a4823471191ac01b2f | 632,260 |
def getxmlelement(xml_root, path):
"""
extract an element of a xml file
"""
try:
res = xml_root.find(path)
except:
raise Exception('Cannot find path %s'%(path))
if res is None:
raise Exception('Cannot find path %s'%(path))
return res | 20b3c10ac180dec076ce63dbabff03ab19c21d7b | 632,261 |
def is_vcf_chrom_header(line):
"""
Returns ``True`` if ``line`` is a VCF chrom-definition header line, ``False`` otherwise.
:param line: line from VCF file
:return: ``bool``
"""
if line.startswith('##contig='):
return True
else:
return False | 7b519b73a8bd978595c859bb19fb5b6f6f6b3849 | 632,263 |
def get_top_users_and_orgs(user_data_df, top_repos_df):
"""Gets the top 25 Github Users and top 25 Organizations.
Note: Top 25 Users are determined based on total followers.
Top 25 Organizations are determined based on total stars
for all of an organizations repos.
Parameters
-----... | 285885028d35574475c9bbf0a0d2c6f98feadcb0 | 632,264 |
import re
def clean_text(message):
""" Delete extra characters from text before validation
Keyword arguments:
message -- a plain sentence or paragraph
"""
sent = re.sub(r'[\-_*+,\(\).:]{1,}', "", message)
sent = re.sub(r'[ ]{1,}', "", sent)
sent = re.sub(r'(?i)\bnº', "", sent)
retu... | 91fb3e455cf24cdb4433244742ca14610a1a8b4c | 632,265 |
def compute_mmd_loss(kernel_values, batch_size):
"""Computes the Maximum Mean Discrepancy (MMD) between domains.
Examples:
See DANtrainer and JANtrainer in kale.pipeline.domain_adapter
"""
loss = 0
for i in range(batch_size):
s1, s2 = i, (i + 1) % batch_size
t1, t2 = s1 + ba... | 5317fa2e38c44857a3984e5fcbcaac5b13600299 | 632,266 |
import sys, os
import importlib
def import_module(module_name):
"""Helper function to import module"""
sys.path.append(os.path.dirname(__file__))
return importlib.import_module(module_name) | b78f224587b3c4a9f1e1641265e30e2a908be2f8 | 632,267 |
def check_dtype(**kwds):
""" Check a dtype for h5py special type "hint" information. Only one
keyword may be given.
vlen = dtype
If the dtype represents an HDF5 vlen, returns the Python base class.
Currently only builting string vlens (str) are supported. Returns
None if the dtype... | 5cc43f94209c9a2ed4c31cbc1c5cf432725dfeb8 | 632,268 |
from typing import Callable
from typing import Tuple
def recurse_tsv(contents: str, fnc: Callable, delim: str = "\t") -> Tuple[str, bool]:
"""Recurse with a callback function in TSV contents.
Just visit each line and look at values only.
Args:
contents:
TSV/CSV contents string
... | ecf7072bdcd1f8679c8046c4cf641e2e91a31686 | 632,269 |
def Step(v, threshold=0, act_value=1, inact_value=0):
"""
Step function where the threshold,
activated and inactivated value can be defined.
"""
return act_value if v > threshold else inact_value | e4b90c902a89e1bdab47ec761e704a2cae2789dc | 632,270 |
def _format_result(counts, cl_reg_index, cl_reg_nbits):
"""Format the result bit string.
This formats the result bit strings such that spaces are inserted
at register divisions.
Args:
counts (dict): dictionary of counts e.g. {'1111': 1000, '0000':5}
cl_reg_index (list): starting bit in... | 7dffaa93f8e84ac1ebf26a90e859a92c059102f2 | 632,272 |
def one_is_not_none(*args) -> bool:
"""
Return True if exactly one arg is not None.
"""
return sum([arg is not None for arg in args]) == 1 | 2d5d462516c44c1347be0a2b08f5d5ead1a68884 | 632,273 |
def calculate(action, a, b):
"""
Calculate the result of the action and the two numbers.
"""
print(f'{action}ing a = {a} and b = {b}')
if action == 'add':
return a + b
elif action == 'subtract':
return a - b
elif action == 'multiply':
return a * b
elif action =... | f6f8f24fbc7df462d6fefc5793c3e26956c5f1e0 | 632,274 |
def update_teams(lottery_info, top_pick_list,
teams_selected, top_pick_order,
request):
""" update_teams populates the proper list
depending on the team selected
@param lottery_info (dict): Dictionary keyed by
reverse standings order, with dictionary
values... | 9fe3a540d53282c23870a08bdde92a71c7cc487c | 632,275 |
from datetime import datetime
def search_time_range_year(type, year):
"""
get search timerange on a given year
@see https://github.com/ianshan0915/clinical-opensource-projects
"""
if type == 1:
timerange = '<' + str(year) + '-01-01'
else:
start = str(year) + '-01-01'
if... | b7d6f1b5d29934e3fe303c7ef75f37afa8d57cc3 | 632,276 |
import numpy
def calc_m_q_mt(m_ij, q_ij, flag_m: bool = False, flag_q: bool = False):
"""
q is quadratic form q_11, q_22, q_33, q_12, q_13, q_23
m is matrix m_11, m_12, m_13, m_21, m_22, m_23, m_31, m_32, m_33
Output is quadratic form o = M * Q * MT:
o is o_11, o_22, o_33, o_12, o_13, o_23
"... | d219ba5b7194bda6be1ccf23fbefe18506856a2a | 632,277 |
def relink(links, walf):
"""complete pairs and print matrix"""
# make symmetrtic links set, because we have non-directional (non-oriented) graph
links1 = set()
for el in links:
links1.add((el[1], el[0]))
links |= links1
del links1
# print matrix
print ("\n ", walf)
for c1 i... | 9ed9c57a92f4a50eed915f1505e67e3795299c4d | 632,278 |
import torch
def torch_pc_from_disparity_crop(disp, stereo_calib_f, stereo_calib_baseline,
stereo_calib_centre_u, stereo_calib_centre_v,
box_2d, roi_size):
"""Transforms disparity map to 3d point cloud
Args:
disp: disparity map
... | ee12c36c1ad2208880948963b08cd450e822aa17 | 632,279 |
def my_decorator5(func5):
"""
my decorator5
:param func5:
:return:
"""
def wrapper(*args, **kwargs):
"""
wrapper
:param args:
:param kwargs:
:return:
"""
print('wrapper of decorator')
func5(*args, **kwargs)
return wrapper | 81dc38955b24515957bf3d89751c4dc7836192d1 | 632,280 |
from typing import Iterable
def any_not_none(iterable: Iterable) -> bool:
"""
Verify if any of the elements of the iterable is not None.
The default behaviour of the builtin any function checks the value
with `if element` and causes the values like zero (0) to be
treated as Falsy values. This func... | 5b93147db9f78eaa8d2b9e9060e6a5283c2ff201 | 632,281 |
from operator import concat
def Main(ba1, ba2):
# b = ba2
# m = ba2[1] # subscribt for a byte array does not work
"""
:param ba1:
:param ba2:
:return:
"""
m = ba2[1:2] # but you can do this instead
# strings and byte arrays work the same
mystr = 'staoheustnau'
# th... | e50f41c1558738570a7c57be16a5aa07f1d45f5f | 632,282 |
def average_overlap(similarity_fn, samples, *ignore_params):
"""Returns the arithmetic mean of each candidate sentence in the samples
Args:
similarity_fn (function): similarity function used to compute the overlap
samples (list of lists): tokenized version of the translated sentences
*i... | f5bbe73ae1f4400378612f6670782f3751906240 | 632,283 |
def to_primitive(rho, rhou, rhov, ener, gamma=1.4):
"""Converts conservative variables to primitive variables rho, u, v, and p."""
u = rhou / rho
v = rhov / rho
p = (gamma - 1.0) * (ener - 0.5 * rho * (u**2 + v**2))
return rho, u, v, p | f45ffb914b69bb57d817a5b2a541299ea15fa666 | 632,284 |
def p_testlist_list(p, l_el, el=-1):
"""testlist_plus : testlist_plus COMMA test"""
l, _ = l_el
l.append(el)
return l, None | b27a13e99243d0eebcf68ea330a053d623a0e833 | 632,286 |
def toascii(data):
"""
Converts a utf-8 string to ascii. needed since nosetests xunit is not UTF-8 safe
https://github.com/nose-devs/nose/issues/649
https://github.com/nose-devs/nose/issues/692
"""
return data
udata = data.decode('utf-8')
return udata.encode('ascii', 'xmlcharrefreplace... | 2211e63129ea6216011aafd542b6aeca0a0bf6bb | 632,287 |
import torch
def torch_eye(n, m=None, out=None):
"""
Like `torch.eye()`, but works with cuda tensors.
"""
if m is None:
m = n
try:
return torch.eye(n, m, out=out)
except TypeError:
# Only catch errors due to torch.eye() not being available for cuda tensors.
modu... | 9ba8ca767ea4bc60dee5ed3b35d4eb82afca609b | 632,288 |
def google_vision_LF(row, information_extractor):
""" Analyze image with Google vision API """
item_candidates = information_extractor.google_vision_lookup(row.image_path)
items = information_extractor.map_candidates_to_ontology(item_candidates)
google_vision_classes = {}
google_vision_classes["item... | 20ae8ef31c97e724f64ad0b0d54780c4115581f2 | 632,289 |
def monthly_avg_2darray(x):
"""
Monthly average for a given 2d dataset where columns are monthly timeseries
"""
return x.reshape(-1,12).transpose().reshape(-1,int(x.shape[1]/12)).mean(1).reshape(12,-1).transpose() | e9898342a17bb50cd9647ec99104f3e50f61bea2 | 632,291 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.