content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def tokenize(lines, token='word'):
"""Split text lines into word or character tokens."""
if token == 'word':
return [line.split() for line in lines]
elif token == 'char':
return [list(line) for line in lines]
else:
print('ERROR: unknown token type: ' + token) | c30c8b3f1ea5d5752e17bc9fd514acaf097cba18 | 3,643,000 |
import os
def get_versioned_persist(service):
"""Get a L{Persist} database with upgrade rules applied.
Load a L{Persist} database for the given C{service} and upgrade or
mark as current, as necessary.
"""
persist = Persist(filename=service.persist_filename)
upgrade_manager = UPGRADE_MANAGERS[... | 5d636ff552cd693a701506377643f410f3384b29 | 3,643,001 |
def gravatar(environ):
"""
Generate a gravatar link.
"""
email = environ.get('tank.user_info', {}).get('email', '')
return GRAVATAR % md5(email.lower()).hexdigest() | 0464d409f4e0c1fef251927930618236146ac3f1 | 3,643,002 |
def keyrep(kspec, enc="utf-8"):
"""
Instantiate a Key given a set of key/word arguments
:param kspec: Key specification, arguments to the Key initialization
:param enc: The encoding of the strings. If it's JSON which is the default
the encoding is utf-8.
:return: Key instance
"""
if en... | 25524953376a83562859b33a91ba10ae85c2c25d | 3,643,003 |
import math
def aa2matrix(axis, angle, radians=True, random=False):
"""
Given an axis and an angle, return a 3x3 rotation matrix.
Based on:
https://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle
Args:
axis: a vector about which to perform a rotation
angle: the angle of rotat... | d41460663edd36e5da1255636514468180e20511 | 3,643,004 |
def expand_value_range(value_range_expression):
"""Expand the value range expression.
Args:
value_range_expression: Value range or expression to expand.
Return:
iterable.
"""
if type(value_range_expression) is str:
# Grid search
if value_range_expression.startswith('... | bddfc2fd4ed65101ecb3d8ca2bc5d11de58374bd | 3,643,005 |
def date_range(df):
"""Takes the dataframe returns date range.
Example here:
http://pandas.pydata.org/pandas-docs/stable/timeseries.html
Returns as Days
"""
start_date = df.tail(1)['date']
start = pd.Timestamp.date(list(start_date.to_dict().values())[0])
end_date = df.head(1)['date'... | 1b577b29ccc7ed6751e8162f11b076042178c590 | 3,643,006 |
from datetime import datetime
def last_hit_timestamp(hit_count_rules, month):
"""
Get list of last hit timestamp to rule
:param hit_count_rules:
dictionary which contain json response with all hit count rules
:param month:
number of month elapsed since the rule was ... | 048d63e9ad77bf19974b4506aedb66d98fb84403 | 3,643,007 |
def url(should_be=None):
"""Like the default ``url()``, but can be called without arguments,
in which case it returns the current url.
"""
if should_be is None:
return get_browser().get_url()
else:
return twill.commands.url(should_be) | a9faa937ffe994136d16e5c86082f22600368431 | 3,643,008 |
def remove_outliers(X_train,y_train):
"""
This function deletes outliers on the given numpy arrays,
and returns clean version of them.
Parameters
----------
X_train: dataset to remove outliers with k features
y_train: dataset to remove outliers with k f... | 35c86ba50ca6398ec70e95c07091bb1ffc6811d2 | 3,643,009 |
import tqdm
def query_data(regions, filepath_nl, filepath_lc, filepath_pop):
"""
Query raster layer for each shape in regions.
"""
shapes = []
csv_data = []
for region in tqdm(regions):
geom = shape(region['geometry'])
population = get_population(geom, filepath_pop)
... | a4ecd234d04fc1cf677d276afe11c716a1c3b854 | 3,643,010 |
from bs4 import BeautifulSoup
import re
def scrape_urls(html_text, pattern):
"""Extract URLs from raw html based on regex pattern"""
soup = BeautifulSoup(html_text,"html.parser")
anchors = soup.find_all("a")
urls = [a.get("href") for a in anchors]
return [url for url in urls if re.match(pattern, u... | dfba40df7894db91575b51a82d89fef0f824d362 | 3,643,011 |
from typing import List
def get_num_weight_from_name(model: nn.Module, names: List[str]) -> List[int]:
"""Get list of number of weights from list of name of modules."""
numels = []
for n in names:
module = multi_getattr(model, n)
num_weights = module.weight.numel()
numels.append(nu... | ae6c3bfb5abe3522ff6d276cde052a5270e5741e | 3,643,012 |
from typing import OrderedDict
def _categories_level(keys):
"""use the Ordered dict to implement a simple ordered set
return each level of each category
[[key_1_level_1,key_2_level_1],[key_1_level_2,key_2_level_2]]
"""
res = []
for i in zip(*(keys)):
tuplefied = _tuplify(i)
res... | 35f62244c3d3b893008d7ba7b8a9f651528c198e | 3,643,013 |
def to_usd(my_price):
"""
Converts a numeric value to usd-formatted string, for printing and display purposes.
Param: my_price (int or float) like 4000.444444
Example: to_usd(4000.444444)
Returns: $4,000.44
"""
return f"${my_price:,.2f}" | a8959cdca7f011a435e35b4a4a5d2d43911a55da | 3,643,014 |
def computeNodeDerivativeHermiteLagrange(cache, coordinates, node1, derivative1, scale1, node2, scale2):
"""
Computes the derivative at node2 from quadratic Hermite-Lagrange interpolation of
node1 value and derivative1 to node2 value.
:param cache: Field cache to evaluate in.
:param coordinates: Coo... | 7eb98502341e94e277b4d7b98b68293ff28f395b | 3,643,015 |
def _step5(state):
"""
Construct a series of alternating primed and starred zeros as follows.
Let Z0 represent the uncovered primed zero found in Step 4.
Let Z1 denote the starred zero in the column of Z0 (if any).
Let Z2 denote the primed zero in the row of Z1 (there will always be one).
Contin... | 4d6e50164724b6fdaa42fa41423677dd80500a3e | 3,643,016 |
def encode_ascii_xml_array(data):
"""Encode an array-like container of strings as fixed-length 7-bit ASCII
with XML-encoding for characters outside of 7-bit ASCII.
"""
if isinstance(data, np.ndarray) and \
data.dtype.char == STR_DTYPE_CHAR and \
data.dtype.itemsize > 0:
return data... | a9baf0ca562b78ce36c49e1d64c8f8a9015df097 | 3,643,017 |
from typing import Union
from pathlib import Path
from typing import Optional
from typing import List
import queue
def download_dataset(
period: str, output_dir: Union[Path, str], fewer_threads: bool, datasets_path: Optional[Union[Path, str]] = None
) -> List[Path]:
"""Download files from the given dataset wi... | 0c98956bb54f6f948a31097e47ba6008e91ebefc | 3,643,018 |
def monospaced(fields, context):
"""
Make text monospaced.
In HTML: use tags
In Markdown: use backticks
In Text: use Unicode characters
"""
content = fields[0]
target = context['target']
if target == 'md':
return wrapper('`')([content], context)
if target == 'html':
... | eed91b414ce8cb486b115d0d203db4e7ed81e5d5 | 3,643,019 |
def indexview(request):
"""
initial page
shows all the domains in columns
"""
domdb = Domain.objects
if not request.user.has_perm('editapp.see_all'): # only see mine
domdb = domdb.filter(owner__username=request.user.username)
domains = [ d.domain for d in domdb.order_by('domain') ]
... | b99e8b3499f7d7a282b5a93606dddf7527a5e93b | 3,643,020 |
def MC_swap(alloy, N, E, T):
"""
Randomly selects an atom and one of its neighbours in a
matrix and calculates the change in energy if the two atoms were swapped.
The following assignment is used to represent the neighbouring directions:
1 = up
2 = right
3 = down
4 = left
"""
... | aea84cd605389e480d89e78fcca9806bc68e0c83 | 3,643,021 |
def _try_type(value, dtype):
"""
Examples
--------
>>> _try_type("1", int)
1
>>> _try_type(1.0, int)
1
>>> _try_type("ab", float)
'ab'
"""
try:
return dtype(value)
except ValueError:
return value | 4a188e57dfafca96e6cd8a815dbbb162c74df01b | 3,643,022 |
from datetime import datetime
def get_all_codes(date=None):
"""
获取某个交易日的所有股票代码列表,如果没有指定日期,则从当前日期一直向前找,直到找到有
数据的一天,返回的即是那个交易日的股票代码列表
:param date: 日期
:return: 股票代码列表
"""
datetime_obj = datetime.now()
if date is None:
date = datetime_obj.strftime('%Y-%m-%d')
codes = []
... | b5d861f1991763e8196f1f336faffefc00b58df4 | 3,643,023 |
def cluster_config(request_data, op_ctx: ctx.OperationContext):
"""Request handler for cluster config operation.
Required data: cluster_name
Optional data and default values: org_name=None, ovdc_name=None
(data validation handled in broker)
:return: Dict
"""
_raise_error_if_pks_not_enable... | 985e9633d54c0b7ccfc235f6c34bb4d4c5086ebf | 3,643,024 |
import os
def compute_pad_value(input_dir, list_IDs):
"""
Computes the minimum pixel intensity of the entire dataset for the pad value (if it's not 0)
Args:
input_dir: directory to input images
list_IDs: list of filenames
"""
print("Computing min/pad value...")
# iterating thro... | 68d93bf50c8653c42d22dac2382047f18a23c88e | 3,643,025 |
from .pyazureutils_errors import PyazureutilsError
def iotcentral_cli_handler(args):
"""
CLI entry point for command: iotcentral
"""
logger = getLogger(__name__)
try:
if args.action == "register-device":
status = _action_register_device(args)
except PyazureutilsError as exc... | e5c78f24c459ff45ab8a88198697eae0a9bb7abe | 3,643,026 |
def kelly_kapowski(s, g, w, its=45, r=0.025, m=1.5, **kwargs):
"""
Compute cortical thickness using the DiReCT algorithm.
Diffeomorphic registration-based cortical thickness based on probabilistic
segmentation of an image. This is an optimization algorithm.
Arguments
---------
s : ANTsim... | 809d119d5691e64504671a4915525a109d0ae375 | 3,643,027 |
def get_word_count(frame, pattern_list, group_by_name):
"""
Compute word count and return a dataframe
:param frame:
:param pattern_list:
:param column_name:
:return: frame with count or None if pattern_list is empty
"""
if not pattern_list or len(pattern_list) == 0:
return None
... | 06a1c82b387bfc2194e3d4ee0a4526e5b4e3f800 | 3,643,028 |
def parse(text, from_timezone=None):
"""
:rtype: TimeeDT
"""
timee_dt = None
if from_timezone:
timee_dt = parse_with_maya(text, timezone=from_timezone)
return timee_dt
else:
for parse_method in parsing_methods():
result = parse_method(text)
i... | c7a8b7819031ee7f97c54c9903f19d4b24112c4a | 3,643,029 |
import collections
def _command_line_objc_copts(objc_fragment):
"""Returns copts that should be passed to `clang` from the `objc` fragment.
Args:
objc_fragment: The `objc` configuration fragment.
Returns:
A list of `clang` copts, each of which is preceded by `-Xcc` so that they can be pa... | 8c55d1297b0aa116b9f6dc859cad1dfda1901f00 | 3,643,030 |
import logging
import urllib
def handle_incoming_mail(addr=None):
"""Handle an incoming email by making a task to examine it.
This code checks some basic properties of the incoming message
to make sure that it is worth examining. Then it puts all the
relevent fields into a dict and makes a new Cloud Task wh... | 9bef81cf818d433cc833e64b5291b5c371605424 | 3,643,031 |
def split(df, partition, column):
"""
:param df: The dataframe to split
:param partition: The partition to split
:param column: The column along which to split
: returns: A tuple containing a split of the original partition
"""
dfp = df[column][partition]
if column in ca... | 8d87d025695a0a2dde681e1abbbf0f5acccdc914 | 3,643,032 |
def get_gaussian_kernel(l=5, sig=1.):
"""
creates gaussian kernel with side length l and a sigma of sig
"""
ax = np.linspace(-(l - 1) / 2., (l - 1) / 2., l)
xx, yy = np.meshgrid(ax, ax)
kernel = np.exp(-0.5 * (np.square(xx) + np.square(yy)) / np.square(sig))
return kernel / np.sum(kernel) | 71982928ee89d3ac98ae8d74dcc079dd2c4ca0d8 | 3,643,033 |
def get_data_tbl(path, tblname):
"""Wrapper function around @merge_json
"""
files = get_annon_db_file(path, tblname)
log.info("files: {}".format(files))
K,V = common.merge_json(files)
return K,V | 55381098b1a702a5497a965169b0588192e0a439 | 3,643,034 |
def costes_coloc(im_1, im_2, psf_width=3, n_scramble=1000, thresh_r=0.0,
roi=None, roi_method='all', do_manders=True):
"""
Perform Costes colocalization analysis on a pair of images.
Parameters
----------
im_1: array_like
Intensity image for colocalization. Must be the
... | 34776cc4e8845e696f61750718736feae6105dee | 3,643,035 |
def get_induced_dipole_count(efpobj):
"""Gets the number of polarization induced dipoles in `efpobj` computation.
Returns
-------
int
Total number of polarization induced dipoles.
"""
(res, ndip) = efpobj._efp_get_induced_dipole_count()
_result_to_error(res)
return ndip | 1c7bbd25c17e0a1326e48319c00ad8298174a4b7 | 3,643,036 |
def _gen_parabola(phase: float, start: float, mid: float, end: float) -> float:
"""Gets a point on a parabola y = a x^2 + b x + c.
The Parabola is determined by three points (0, start), (0.5, mid), (1, end) in
the plane.
Args:
phase: Normalized to [0, 1]. A point on the x-axis of the parabola.
start... | bdd808339e808a26dd1a4bf22552a1d32244bb02 | 3,643,037 |
import uuid
def grant_perms(obj: element, mast: element, read_only: bool, meta):
"""
Grants another user permissions to access a Jaseci object
Param 1 - target element
Param 2 - master to be granted permission
Param 3 - Boolean read_only flag
Return - Sorted list
"""
mast = meta['h'].... | 3a73baf583214d95c31011e8dfc427ea364edb4a | 3,643,038 |
import os
import logging
def get_instance_ids_compute_hostnames_conversion_dict(instance_ids, id_to_hostname, region=None):
"""Return instanceIDs to hostnames dict if id_to_hostname=True, else return hostname to instanceID dict."""
try:
if not region:
region = os.environ.get("AWS_DEFAULT_R... | a0ba0710c2a79861d2b4ac818644cbe460afad59 | 3,643,039 |
def pkgdir(tmpdir, monkeypatch):
"""
temp directory fixture containing a readable/writable ./debian/changelog.
"""
cfile = tmpdir.mkdir('debian').join('changelog')
text = """
testpkg (1.1.0-1) stable; urgency=medium
* update to 1.1.0
* other rad packaging updates
* even more cool packaging up... | 0717aba1d5181e48eb11fa1e91b72933cda1af14 | 3,643,040 |
import configparser
def read_plot_config(filename):
"""Read in plotting config file.
Args:
filename (str): Full path and name of config file.
Returns:
dict: Contents of config file.
"""
config = configparser.ConfigParser()
config.read(filename)
out = {}
for section in... | 876a84b2976807d2ef02c79806c9c2d14874997a | 3,643,041 |
def parse(file_path, prec=15):
"""
Simple helper
- file_path: Path to the OpenQASM file
- prec: Precision for the returned string
"""
qasm = Qasm(file_path)
return qasm.parse().qasm(prec) | 5303753da86780854f1b2b9abff18ad9531e1ea8 | 3,643,042 |
def sinusoid(amplitude=1.0, frequency=1.0, phase=0.0, duration=60.0, samplerate=100.0):
"""Generate a sinusoid"""
t = np.arange(0, duration, 1.0/samplerate)
d = np.sin(2.0 * np.pi * frequency * t)
return t, d | ea55aec9519321221946e74504732209771b0b23 | 3,643,043 |
def get_model():
"""
Returns a compiled convolutional neural network model. Assume that the
`input_shape` of the first layer is `(IMG_WIDTH, IMG_HEIGHT, 3)`.
The output layer should have `NUM_CATEGORIES` units, one for each category.
"""
model = tf.keras.models.Sequential()
model.add(
... | d6d5ad41ec6ba61ebcf7d2dfb962f18a24b7a8a1 | 3,643,044 |
def check_datetime_str(datetime_str):
"""
Tries to parse the datetime string to a datetime object. If it fails,
it will return False
:param str datetime_str:
:return: returns True or False depending on the validity of the datetime string
:rtype: bool
"""
try:
parse_datetime_str(... | 8129a3ef87d377bc488bfbd151012241f673e07d | 3,643,045 |
def _df_pitch(df: pd.DataFrame, xcol: str = 'x',
ycol: str = 'y', zcol: str = 'z'):
"""Find angular pitch for each row in an accelerometer dataframe.
Args:
df (pd.DataFrame): accelerometer dataframe
xcol, ycol, zcol (str): column names for x, y, and z acceleration
Returns:
... | 50c6e40e535b5cd7acead652edf1a9420125fee8 | 3,643,046 |
def gan_masked_generate_face(generator_fun, face_img: np.array):
"""
Generated a face from the seed one considering a generator_fun which should output alpha mask and bgr results
:param generator_fun: takes an image and returns alpha mask concatenated with bgr results
:param face_img: img to feed to the... | 9b6ce882f509851b0a9c52364bb602909db45cb6 | 3,643,047 |
import os
def get_namespace_from_path(path):
"""get namespace from file path
Args:
path (unicode): file path
Returns:
unicode: namespace
"""
return os.path.splitext(os.path.basename(path))[0] | 5ca9bdde1dbe3e845a7d8e64ca0813e215014efd | 3,643,048 |
def feat_row_sum_inv_normalize(x):
"""
:param x: np.ndarray, raw features.
:return: np.ndarray, normalized features
"""
x_feat = x.astype(dtype=np.float64)
inv_x_rowsum = np.power(x_feat.sum(axis=1), -1).flatten()
inv_x_rowsum[np.isinf(inv_x_rowsum)] = 0.
x_diag_mat = np.diag(inv_x_rows... | ea55c7826054ca13f810852a24cf315f268dfd6a | 3,643,049 |
def cross3(v1, v2):
"""
cross3
"""
return (v1[1] * v2[2] - v1[2] * v2[1], v1[2] * v2[0] - v1[0] * v2[2], v1[0] * v2[1] - v1[1] * v2[0]) | f3bb2b82acf54d929ffc14177fde120970617886 | 3,643,050 |
import copy
def api_request(request, viewset, method, url_kwargs={}, get_params={}):
"""
Call an API route on behalf of the user request. Examples:
data = api_request(request, CaseDocumentViewSet, 'list', get_params={'q': 'foo'}).data
data = api_request(request, CaseDocumentViewSet... | c3d118d1a9857e9522f3e518a77da6e51e443ef7 | 3,643,051 |
def ca_restart(slot):
"""
:param slot:
"""
LOG.info("CA_Restart: attempting to restart")
ret = CA_Restart(CK_ULONG(slot))
LOG.info("CA_Restart: Ret Value: %s", ret)
return ret | 1192f371c14bdf8f773b1402f77e66d24d3aee94 | 3,643,052 |
import os
def ogr_wkts(src_ds):
"""return the wkt(s) of the ogr dataset"""
these_regions = []
src_s = src_ds.split(':')
if os.path.exists(src_s[0]):
poly = ogr.Open(src_s[0])
if poly is not None:
p_layer = poly.GetLayer(0)
for pf in p_layer:
... | af7a2ae2f33d7616cee224ae51f25d4b77937f9d | 3,643,053 |
import os
def load_word2vec_matrix(embedding_size):
"""
Return the word2vec model matrix.
Args:
embedding_size: The embedding size
Returns:
The word2vec model matrix
Raises:
IOError: If word2vec model file doesn't exist
"""
word2vec_file = '../data/word2vec_' + str... | adb44f40ab12ddac737c4c467c6a6fee971cf83b | 3,643,054 |
async def app_exception_handler(request, exc):
"""
Error handler for AppException errors.
Logs the AppException error detected and returns the
appropriate message and details of the error.
"""
logger.debug(exc)
return JSONResponse(
Response(success=False, error_code=422, message=s... | 049322caa0e0541e8d4348e685b533292484e2c5 | 3,643,055 |
def db_query_map(db_or_el, query, func_match, func_not) -> tuple:
"""
Helper function to find elems from query and transform them,
to generate 2 lists of matching/not-matching elements.
"""
expr = parse_query_expr(query)
elems1, elems2 = [], []
for el in _db_or_elems(db_or_el):
m = e... | d7b56e8d62d0c80c4bfdb026879d5a848b7d3b8f | 3,643,056 |
import inspect
def route(pattern, method = HTTP_METHOD.GET):
"""
Decorator to declare the routing rule of handler methods.
"""
def decorator(func):
frm = inspect.stack()[1]
class_name = frm[3]
module_name = frm[0].f_back.f_globals["__name__"]
full_class_name = module_na... | 28d107abbce1d36611fa5313b0d52491000a1f73 | 3,643,057 |
from operator import invert
def div_q(a: ElementModPOrQorInt, b: ElementModPOrQorInt) -> ElementModQ:
"""Compute a/b mod q."""
b = _get_mpz(b)
inverse = invert(b, _get_mpz(get_small_prime()))
return mult_q(a, inverse) | 285a8aa161748d8c7aaa38bd04f81fe7c22e5e43 | 3,643,058 |
def donoho_gavish_threshold(shape, sigma):
"""
(Gavish and Donoho, 2014)
Parameters
----------
shape: tuple (n_samples, n_features)
Shape of the data matrix.
sigma: float
Estiamte of the noise standard deviation.
Output
------
sigular_value_threshold: float
"... | ba6731ff2a3b27543ed2a738a5e09abf3ec5cc78 | 3,643,059 |
import pyarrow
def pyarrow_to_r_schema(
obj: 'pyarrow.lib.Schema'
):
"""Create an R `arrow::Schema` object from a pyarrow Schema.
This is sharing the C/C++ object between the two languages.
The returned object depends on the active conversion rule in
rpy2. By default it will be an `rpy2.robje... | 0eb461451ea805b3ac888084b4f46ca9cbbd7c00 | 3,643,060 |
import pandas
import os
def plot_ovlp_stats(jobdir, nproc):
"""Plot 5' and 3' Overlap distributions"""
log.info("Generating overlap plots")
overlaps = get_overlaps(jobdir, nproc)
ovlp_dict = {}
for ovlp in overlaps:
rid, length, fiveprime, threeprime = ovlp.split()
ovlp_dict[rid] ... | d96b9fbec409e112f4eb8562b1a74f0504346728 | 3,643,061 |
import calendar
def validate_days(year, month, day):
"""validate no of days in given month and year
>>> validate_days(2012, 8, 31)
31
>>> validate_days(2012, 8, 32)
31
"""
total_days = calendar.monthrange(year, month)
return (total_days[1] if (day > total_days[1]) else day) | 7499dc9654ec9ffd7f534cf27444a3236dd82e81 | 3,643,062 |
import json
def save_to_s3(bucket_name, file_name, data):
""" Saves data to a file in the bucket
bucket_name - - The name of the bucket you're saving to
file_name - - The name of the file
dat - - data to be saved """
s3 = boto3.resource('s3')
obj = s3.Object(bucket_name, file_name)... | 520599136418d635cfbaf67c7bffbb2da105985c | 3,643,063 |
def linsearch_fun_BiCM_exp(xx, args):
"""Linsearch function for BiCM newton and quasinewton methods.
This is the linesearch function in the exponential mode.
The function returns the step's size, alpha.
Alpha determines how much to move on the descending direction
found by the algorithm.
:param ... | c88f974c76ceec84a12a67ef9c6f71ae357f472b | 3,643,064 |
def getCountryName(countryID):
"""
Pull out the country name from a country id.
If there's no "name" property in the object, returns null
"""
try:
countryObj = getCountry(countryID)
return(countryObj['name'])
except:
pass | 72b90de7e49911983fe60e18b00cc577f423785d | 3,643,065 |
import os
import base64
def _pic_download(url, type):
"""
图片下载
:param url:
:param type:
:return:
"""
save_path = os.path.abspath('...') + '\\' + 'images'
if not os.path.exists(save_path):
os.mkdir(save_path)
img_path = save_path + '\\' + '{}.jpg'.format(type)
img_data =... | 05541a9991b4b3042c84d4e1b5188def365cc4fc | 3,643,066 |
def get_placeholder(default_tensor=None, shape=None, name=None):
"""Return a placeholder_wirh_default if default_tensor given, otherwise a new placeholder is created and return"""
if default_tensor is not None:
return default_tensor
else:
if shape is None:
raise ValueError('One o... | e62fe4ca8244ae45ac853a0398754375454626dc | 3,643,067 |
def get_targets(args):
"""
Gets the list of targets for cmake and kernel/build.sh
:param args: The args variable generated by parse_parameters
:return: A string of targets suitable for cmake or kernel/build.sh
"""
if args.targets:
targets = args.targets
elif args.full_toolchain:
... | 81eb31fe416303bc7e881ec2c10cfeeea4fdab05 | 3,643,068 |
def _format_warning(message, category, filename, lineno, line=None): # noqa: U100, E501
"""
Simple format for warnings issued by ProPlot. See the
`internal warning call signature \
<https://docs.python.org/3/library/warnings.html#warnings.showwarning>`__
and the `default warning source code \
<https://... | f5709df0a84d9479d6b895dccb3eae8292791f74 | 3,643,069 |
def piocheCarte(liste_pioche, x):
""" Cette fonction renvoie le nombre x de cartes de la pioche.
Args:
x (int): Nombre de cartes à retourner.
Returns:
list: Cartes retournées avec le nombre x.
"""
liste_carte = []
for i in range(x):
liste_carte.append(liste_pioche[i])
... | ed31c47d699447870207a4066a3da9c35333ada8 | 3,643,070 |
import os
def is_process_running(pid):
"""Returns true if a process with pid is running, false otherwise."""
# from
# http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid
try:
os.kill(pid, 0)
except OSError:
return False
else:
... | a05cbeb84b5d6f3d6d7a06ab3d14702742b2a289 | 3,643,071 |
def cost_logistic(p, x, y):
"""
Sum of absolute deviations of obs and logistic function
:math:`L/(1+exp(-k(x-x0)))`
Parameters
----------
p : iterable of floats
parameters (`len(p)=3`)
- `p[0]` = L = Maximum of logistic function
- `p[1]` = k = Steepness of logistic... | 4985d19ff792bf2df8fe5692330cb9c32d329cab | 3,643,072 |
import requests
def get_price(token: str, sellAmount=1000000000000000000):
"""
get_price uses the 0x api to get the most accurate eth price for the token
:param token: token ticker or token address
:param buyToken: token to denominate price in, default is WETH
:param sellAmount: token amount to s... | b1dae25571eccb28433b9bfe7c3be6f006f05184 | 3,643,073 |
from datetime import datetime
import logging
def inv_exportlog():
"""Exports a csv file formatted for Profitek's inventory task list.
"""
date = datetime.today().strftime('%Y%m%d')
scanner_terminal = escape(session["scanner_terminal"])
allscanners = escape(request.form.get('allscanners','yes'))
... | 96d8d341ebc0d8d0e2cb79669a779acf5e4a5ddb | 3,643,074 |
def _get_all_errors_if_unrecognized_properties(model: dict, props: list) -> iter:
"""Get error messages if the model has unrecognized properties."""
def get_error_if_property_is_unrecognized(key):
if key not in props:
return f"unrecognized field named '{key}' found in model '{model}'"
... | e7c380b750606adc466f335a2411619eab11312f | 3,643,075 |
import os
def no_holders(disk):
"""Return true if the disk has no holders."""
holders = os.listdir('/sys/class/block/' + disk + '/holders/')
return len(holders) == 0 | 3ef1b7754cde64f248ca9da747adb398aaefd878 | 3,643,076 |
import inspect
import sys
def main(fn):
"""Call fn with command line arguments. Used as a decorator.
The main decorator marks the function that starts a program. For example,
@main
def my_run_function():
# function body
Use this instead of the typical __name__ == "__main__" predicate.
... | 6c87ac44dc8422b8d4f02685a764f0cccffbc215 | 3,643,077 |
def get_get_single_endpoint_schema(class_name, id_field_where_type, response_schema):
"""
:param class_name:
:param id_field_where_type:
:param response_schema:
"""
return {
"tags": [class_name],
"description": f"Get a {class_name} model representation",
"parameters": [... | 98daaaa20e5e52c2480ce6aa1805ee3da6b163d7 | 3,643,078 |
from typing import Optional
def overlapping_template_matching(
sequence,
template_size: Optional[int] = None,
blocksize: Optional[int] = None,
matches_ceil: Optional[int] = None,
):
"""Overlapping matches to template per block is compared to expected result
The sequence is split into blocks, ... | 035ce0c333c69bdf437f1e6f93071c9342154e92 | 3,643,079 |
def _extract_options(config, options, *args):
"""Extract options values from a configparser, optparse pair.
Options given on command line take precedence over options read in the
configuration file.
Args:
config (dict): option values read from a config file through
configparser
... | 3d74857b3dcdd242950a35b84d3bcaae557a390b | 3,643,080 |
def _calc_fans(shape):
"""
:param shape: tuple with the shape(4D - for example, filters, depth, width, height)
:return: (fan_in, fan_out)
"""
if len(shape) == 2:
# Fully connected layer (units, input)
fan_in = shape[1]
fan_out = shape[0]
elif len(shape) in {3, 4, 5}:
... | 70535fd002f08bbaadf1a0af4ec980851e52ad92 | 3,643,081 |
from typing import List
from typing import Tuple
import logging
import torch
import copy
from pathlib import Path
def train_collision(net: nn.Module, full_props: List[c.CollisionProp], args: Namespace) -> Tuple[int, float, int, float]:
""" The almost completed skeleton of training Collision Avoidance/Detection ne... | 4fa7a37435fe316ebe63cfc4979d957a64fce8dc | 3,643,082 |
def statRobustness(compromised, status):
"""produce data for robustness stats"""
rob = {0:{"empty":0, "login based":0, "top 10 common":0, "company name":0},
1:{"top 1000 common":0, "login extrapolation":0, "company context related":0, "4 char or less":0},
2:{"top 1M common":0, "6 char or... | 46920b466b96fa37a94888e788104c1d901a9227 | 3,643,083 |
def ns_diff(newstr, oldstr):
"""
Calculate the diff.
"""
if newstr == STATUS_NA:
return STATUS_NA
# if new is valid but old is not we should return new
if oldstr == STATUS_NA:
oldstr = '0'
new, old = int(newstr), int(oldstr)
return '{:,}'.format(max(0, new - old)) | bbf58a649ef71524e7413fb47501d0054b828919 | 3,643,084 |
def get_crab(registry):
"""
Get the Crab Gateway
:rtype: :class:`crabpy.gateway.crab.CrabGateway`
# argument might be a config or a request
"""
# argument might be a config or a request
regis = getattr(registry, 'registry', None)
if regis is None:
regis = registry
return re... | 6f8f02ac4bf7e82c8f4828fb4fdab4b78451ae49 | 3,643,085 |
def create_meal():
"""Create a new meal.
---
tags:
- meals
parameters:
- in: body
name: body
schema:
id: Meal
properties:
name:
type: string
description: the name of the meal
description:
type... | ee1c235410d7d6ca9f3661ea9f7a1f9fb434a730 | 3,643,086 |
def buscaBinariaIterativa(alvo, array):
""" Retorna o índice do array em que o elemento alvo está contido.
Considerando a coleção recebida como parâmetro, identifica e retor-
na o índice em que o elemento especificado está contido. Caso esse
elemento não esteja presente na coleção, retorna -1. Utiliza ... | e74fed0781b3c1bed7f5f57713a06c58bcbde107 | 3,643,087 |
def empiricalcdf(data, method='Hazen'):
"""Return the empirical cdf.
Methods available:
Hazen: (i-0.5)/N
Weibull: i/(N+1)
Chegodayev: (i-.3)/(N+.4)
Cunnane: (i-.4)/(N+.2)
Gringorten: (i-.44)/(N+.12)
California: (i-1)/N
Where i goes from ... | 6150361002d3f008185e5deafabfdc74b3189bd8 | 3,643,088 |
def CCT_to_xy_Kang2002(CCT):
"""
Returns the *CIE XYZ* tristimulus values *CIE xy* chromaticity coordinates
from given correlated colour temperature :math:`T_{cp}` using
*Kang et al. (2002)* method.
Parameters
----------
CCT : numeric or array_like
Correlated colour temperature :mat... | cb9462e2b38bf5c55e7d7984632923ba9029e1fb | 3,643,089 |
def tel_information(tel_number):
"""
check and return a dictionary that has element of validation and operator of number
if number is not valid it return validation = 'False' and operator = 'None'
"""
validation = is_valid(tel_number)
operator = tel_operator(tel_number)
info_dict = {'valida... | b68fe615a3adf5e8a7ac8528f4b89ba2d85b4067 | 3,643,090 |
import pathlib
from typing import Dict
from typing import Any
import yaml
import json
def load_file(file_name: pathlib.Path) -> Dict[str, Any]:
"""
Load JSON or YAML file content into a dict.
This is not intended to be the default load mechanism. It should only be used
if a OSCAL object type is unkno... | c042d9e94953c2130971fe6ebf4774cd31556256 | 3,643,091 |
from tests.test_plugins.documentations_plugin import DocumentPlugin
def DocumentPlugin():
"""
:return: document plugin class
"""
return DocumentPlugin | 8cbcc4eb3ee58236f9fbf861a6e33a696db2ddff | 3,643,092 |
import os
def read_in(file_index, normalized):
"""
Reads in a file and can toggle between normalized and original files
:param file_index: patient number as string
:param normalized: boolean that determines whether the files should be normalized or not
:return: returns npy array of patient data ac... | 14690a57e6d1287ebc400a6dab3d89438febf694 | 3,643,093 |
import re
def remove_extended(text):
""" remove Chinese punctuation and Latin Supplement.
https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)
"""
# latin supplement: \u00A0-\u00FF
# notice: nbsp is removed here
lsp_pattern = re.compile(r'[\x80-\xFF]')
text = lsp_pattern.s... | 52d0f5082b519d06f7dd20ba3d755790b1f3166d | 3,643,094 |
def appointment_letter(request, tid):
"""Display the appointment letter."""
paf = get_object_or_404(Operation, pk=tid)
return render(
request, 'transaction/appointment_letter.html', {'paf': paf},
) | 765115cb98e4b99cdff1ad2ad010d635eabf4103 | 3,643,095 |
import random
from typing import Iterable
import itertools
def balance_targets(sentences: Iterable[Sentence], method: str = "downsample_o_cat", shuffle=True) \
-> Iterable[Sentence]:
"""
Oversamples and/or undersamples training sentences by a number of targets.
This is useful for linear shallow cl... | 2d0b5736bcfeb6e7b2566791dba4d74ac3c84456 | 3,643,096 |
def discriminator_loss(real_output, fake_output, batch_size):
"""
Computes the discriminator loss after training with HR & fake images.
:param real_output: Discriminator output of the real dataset (HR images).
:param fake_output: Discriminator output of the fake dataset (SR images).
:param batch_siz... | ade81d34b80226a8905d64249187f35c73d496ee | 3,643,097 |
def NNx(time, IBI, ibimultiplier=1000, x=50):
"""
computes Heart Rate Variability metrics NNx and pNNx
Args:
time (pandas.DataFrame column or pandas series): time column
IBI (pandas.DataFrame column or pandas series): column with inter beat intervals
ibimultiplier... | 94f7f7ec732532cddfe5c29a273af479733e4ced | 3,643,098 |
from datetime import datetime
def datetimeobj_YmdHMS(value):
"""Convert timestamp string to a datetime object.
Timestamps strings like '20130618120000' are able to be converted by this
function.
Args:
value: A timestamp string in the format '%Y%m%d%H%M%S'.
Returns:
A datetime ob... | d1f63b1e50f278bd4dcea78feea8942bc1112c6f | 3,643,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.