content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import sys
def getObjectsByCustomList(conn, customList, objectType = -1, processingFlags = PROCESSING_FLAGS['stamps']):
"""getObjectsByCustomList.
Args:
conn:
customList:
objectType:
processingFlags:
"""
try:
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
... | 17ec2716692b7cfcbb57204f262d1c0107a5fd43 | 3,631,100 |
def dtype():
"""A fixture providing the ExtensionDtype to validate."""
return RaggedDtype() | d441f5e211c57edf009d9311e411dfb6d9833f75 | 3,631,101 |
import io
from pathlib import Path
from typing import OrderedDict
import pandas
def run_propka(args, protein):
"""Run a PROPKA calculation.
Args:
args: argparse namespace
protein: protein object
Returns:
1. DataFrame of assigned pKa values
2. string with filename of PROP... | a595937a2e3740dea78e5064844b956becfbcbbd | 3,631,102 |
import numpy
def geod2cart(rlat, rlon, height):
"""
Geodetic to Cartesian coordinate conversion
Call
cart = geod2cart(rlat, rlon, height)
Input
rlat -- NumPy float array of Geodetic latitudes
rlon -- NumPy float array of Geodetic longitudes
height -- NumPy float array... | 02dbb30ef4960ac523d43a89a3a76336e7b1b564 | 3,631,103 |
import os
def might_exceed_deadline(deadline=-1):
"""For hypothesis magic to work properly this must be the topmost decorator on test function"""
def _outer_wrapper(func):
@wraps(func)
def _inner_wrapper(*args, **kwargs):
dl = deadline
if os.environ.get('PYMOR_ALLOW_DEA... | 60ff79005fc1cb480dae247d9285d5a51e8bde1e | 3,631,104 |
import requests
import json
import traceback
def check_deluge():
"""
Connects to an instance of Deluge and returns a tuple containing the instances status.
Returns:
(str) an instance of the Status enum value representing the status of the service
(str) a short descriptive string represent... | 8cc129a4c7465c52e1d9b82da949c33aa5929c8a | 3,631,105 |
def minor_min_width(G):
"""Computes a lower bound for the treewidth of graph G.
Parameters
----------
G : NetworkX graph
The graph on which to compute a lower bound on the treewidth.
Returns
-------
lb : int
A lower bound on the treewidth.
Examples
--------
Thi... | 649ea7fe0a55ec5289b04b761ea1633c2a258000 | 3,631,106 |
import os
def readUptimeSeconds():
"""Read and return current host uptime in seconds
Returns:
the uptime in seconds
None on error
"""
proc_uptime_path = '/proc/uptime'
if not os.path.exists(proc_uptime_path):
printError('ERROR: unable to find uptime from file {}'.format(
... | 95770dccb98c063c57b563d95addc62e61a5b4bd | 3,631,107 |
def generate_dataset(size=10000, op='sum', n_features=2):
""" Generate dataset for NALU toy problem
Arguments:
size - number of samples to generate
op - the operation that the generated data should represent. sum | prod
Returns:
X - the dataset
Y - the dataset labels
"""
X... | 3bd1b437d64c5260ec03a60114e9b8828f868c24 | 3,631,108 |
def glob2regexp(glob: str) -> str:
"""Translates glob pattern into regexp string.
"""
res = ""
escaping = False
incurlies = 0
pc = None # Previous char
for cc in glob.strip():
if cc == "*":
res += ("\\*" if escaping else ".*")
escaping = False
elif cc... | 1ae8d180663468aaeed44974da3e409b803e4a37 | 3,631,109 |
def distance(array1, array2):
"""计算两个数组矩阵的欧式距离;
axis=0,求每列的
axis=1,求每行的
"""
distance = np.sqrt(np.sum(np.power(array1 - array2, 2)))
return distance | bf6d38c4f6ebf19a048c732bc95796ab9837907f | 3,631,110 |
import IPython.parallel
from engine_manager import EngineManager
def parallel_map(function, *args, **kwargs):
"""Wrapper around IPython's map_sync() that defaults to map().
This might use IPython's parallel map_sync(), or the standard map()
function if IPython cannot be used.
If the 'ask' keyword ar... | 111219097c46ed719e67063ccb079f01d2f38363 | 3,631,111 |
def init_glorot(shape, name=None):
"""Glorot & Bengio (AISTATS 2010) init."""
init_range = np.sqrt(6.0/(shape[0]+shape[1]))
initial = tf.random_uniform(shape, minval=-init_range, maxval=init_range, dtype=tf.float32)
return tf.Variable(initial, name=name) | 05467f77de85c2dada59785e1b211055ce38ebda | 3,631,112 |
def securities(identifier=None, query=None, exch_symbol=None):
"""
Get securities with optional filtering using parameters.
Args:
identifier: Identifier for the legal entity or a security associated
with the company: TICKER SYMBOL | FIGI | OTHER IDENTIFIER
query: Search of secur... | 4c839dc2bc606ee10a70fa6e81f706b3c0ea0f1a | 3,631,113 |
def stations_within_radius(stations, centre, r):
"""The function stations_within_radius returns a list of the stations within a radius r from a centre"""
stations_new=[]
for s in stations:
# distance can be computed using haversine library
d=haversine.haversine(s.coord, centre)
... | de690076ff6d9b58176a3bb14612892344f3c78c | 3,631,114 |
def normalize_email(email):
"""Normalizes the given email address. In the current implementation it is
converted to lower case. If the given email is None, an empty string is
returned.
"""
email = email or ''
return email.lower() | 6ee68f9125eef522498c7299a6e793ba11602ced | 3,631,115 |
def _parse_hostname(url, include_port=False):
""" Parses the hostname out of a URL."""
if url:
parsed_url = urlparse((url))
return parsed_url.netloc if include_port else parsed_url.hostname | af37380619121274c608a22f151726ac79a05ad2 | 3,631,116 |
def voy(lr_angle):
""" Returns y component for reference velocity v_0"""
return -np.sin(np.radians(lr_angle))*9+np.cos(np.radians(lr_angle))*(12.+220.) | 156238dec8630b7c98535d54f826682a94e29ed1 | 3,631,117 |
def get_l8turbidwater(rho1, rho2, rho3, rho4, rho5, rho6, rho7):
"""Returns Boolean numpy array that marks shallow, turbid water"""
watercond2 = get_l8commonwater(rho1, rho4, rho5, rho6, rho7)
watercond2 = np.logical_and(watercond2, rho3 > rho2)
return watercond2 | 2690390eab21b53581979f71e1e144a178bcaa75 | 3,631,118 |
import os
def relpath_nt(path, start=os.path.curdir):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = os.path.abspath(start).split(sep)
path_list = os.path.abspath(path).split(sep)
if start_list[0].lower() != path_list[0].lower():
... | 74937865320da9c919df16f0a69a9faa9628f6b8 | 3,631,119 |
def string_extract_only_alphabets(inputString=""):
"""
Returns only alphabets from given input string
"""
return loader.string_extract_only_alphabets(inputString) | 118cf8b6f16585cf7a7418abfe85d4fba54c4d5a | 3,631,120 |
from typing import Optional
def get_trigger(location: Optional[str] = None,
project: Optional[str] = None,
project_id: Optional[str] = None,
trigger_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTriggerResult:
... | c146b8f8bfb47d3207501004531d1d90926dda60 | 3,631,121 |
import os
def dispatch(intent_request):
"""
Dispatch function In case you want to support multiple intents with a single lambda function
"""
logger.debug('dispatch userId={}, intentName={}'.format(
intent_request['userId'], intent_request['currentIntent']['name']))
intent_name = intent_r... | cdfe6d67624911a078888843c427a033469689f8 | 3,631,122 |
def selu(x): # https://gist.github.com/naure/78bc7a881a9db17e366093c81425184f
"""Scaled Exponential Linear Unit. (Klambauer et al., 2017)
# Arguments
x: A tensor or variable to compute the activation function for.
# References
- [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.... | 784e82c3921f1b7656a3acbb81c2974d4220b113 | 3,631,123 |
import logging
import importlib
def __clsfn_args_kwargs(config, key, base_module=None, args=None, kwargs=None):
"""
Utility function called by both create_object and create_function. It
implements the code that is common to both.
"""
logger = logging.getLogger('pytorch_lm.utils.config')
logger... | 66aae2787426dc2fd7fdc06b3d0e191c2d77d170 | 3,631,124 |
def parse_read_options(form, prefix=''):
"""Extract read options from form data.
Arguments:
form (obj): Form object
Keyword Arguments:
prefix (str): prefix for the form fields (default: {''})
Returns:
(dict): Read options key - value dictionary.
"""
read_options = {
... | 660e836172015999fe74610dffc331d2b37991c3 | 3,631,125 |
import argparse
def create_arguement_parser():
"""return a arguement parser used in shell"""
parser = argparse.ArgumentParser(
prog="python run.py",
description="A program named PictureToAscii that can make 'Picture To Ascii'",
epilog="Written by jskyzero 2016/12/03",
formatter... | ce53083d1eb823063b36341667bee0666e832082 | 3,631,126 |
def get_app_version_info(domain, build_id, xform_version, xform_metadata):
"""
there are a bunch of unreliable places to look for a build version
this abstracts that out
"""
appversion_text = get_meta_appversion_text(xform_metadata)
commcare_version = get_commcare_version_from_appversion_text(a... | 78e04bb736fd7d5e7a84e2e4661f3d5c9dde4492 | 3,631,127 |
def plot_components_plotly(
m, fcst, uncertainty=True, plot_cap=True, figsize=(900, 200)):
"""Plot the Prophet forecast components using Plotly.
See plot_plotly() for Plotly setup instructions
Will plot whichever are available of: trend, holidays, weekly
seasonality, yearly seasonality, and add... | cbc9eccfc2cc12a8f0d9a2b13c0846a87f260e4e | 3,631,128 |
def _format_as_geojson(results, geodata_model):
"""joins the results to the corresponding geojson via the Django model.
:param results: [description]
:type results: [type]
:param geodata_model: [description]
:type geodata_model: [type]
:return: [description]
:rtype: [type]
"""
# re... | 5d0cde796dc4687af352de40e22df8d8e412bf8b | 3,631,129 |
def crosscorr(dfA, dfB, method='pearson', minN=0, adjMethod='fdr_bh'):
"""Pairwise correlations between A and B after a join,
when there are potential column name overlaps.
Parameters
----------
dfA,dfB : pd.DataFrame [samples, variables]
DataFrames for correlation assessment (Nans will be ... | 3c326a642cb7891298913db303792305b8f01b12 | 3,631,130 |
import torch
def normalize_gradient(netC, x):
"""
f
f_hat = --------------------
|| grad_f || + | f |
x: real_data_v
f: C_real before mean
"""
x.requires_grad_(True)
f = netC(x)
grad = torch.autograd.grad(
f, [x], torch.ones_like(f), create... | ff1b8b239cb86e62c801496b51d95afe6f6046d4 | 3,631,131 |
import os
def get_path_with_arch(platform, path):
"""
Distribute packages into folders according to the platform.
"""
# Change the platform name into correct formats
platform = platform.replace('_', '-')
platform = platform.replace('x86-64', 'x86_64')
platform = platform.replace('manylinu... | c627d01837b7e2c70394e1ec322e03179e859251 | 3,631,132 |
import numbers
def compile_snippet(tmpl, **kwargs):
"""
Compiles selected snipped with jinja2
:param tmpl: snippet name
:param kwargs: arguments passed to context
:return: generated HTML
"""
def wrapper(val):
if isinstance(val, numbers.Number):
return val
elif i... | 02926dc6b451d42d48c488811f8c4db9806f589e | 3,631,133 |
from typing import Optional
from re import T
def not_none(t: Optional[T], default: T):
"""
Returns `t` if not None, else `default`.
:param t: the value to return if not None
:param default: the default value to return
:return: t if not None, else default
"""
return t if t is not None else... | b49d9fb621af64e347dc02aebd93c6fb987e94c1 | 3,631,134 |
def fallback_feature(func):
"""Decorator to fallback to `batch_feature` in FeatureModule
"""
def wrapper(self, *args, **kwargs):
if self.features is not None:
ids = args[0] if len(args) > 0 else kwargs['batch_ids']
return FeatureModule.batch_feature(self, batch_ids=ids)
... | cb1fd52c6ddcbbf1d0065f70b5656ddda937440e | 3,631,135 |
def extract_segment_features(y, sr):
"""
Extract audio features from a segment of audio using librosa.
Input: An array of a audiofile.
Output: Dictionary of segments with keys:
tempo, beats, chroma_stft, rms, spec_cent, spec_bw, rolloff, zcr,
and mfcc values from 1-12.
"""
tem... | a64fde839199c8d800c9bae39799f353f71a4b5e | 3,631,136 |
def find_info_by_ep(ep):
""" 通过请求的endpoint寻找路由函数的meta信息"""
return manager.find_info_by_ep(ep) | 3fd834c9b17b1e0e2e58a60e790998c751c70743 | 3,631,137 |
def obtener_cantidad_total_turistas_entrantes_en_ciudad_anio(Ciudad, Anio):
"""
Dado una ciudad y un año obtiene la cantidad total de personas que llegan a esa ciudad de forma total
Dado una ciudad y un año obtiene la cantidad total de personas que llegan a esa ciudad de forma total
:param Ciudad: Ciuda... | c7512aa8e640afc3a84f94d1f0c1c3d82094921d | 3,631,138 |
def update_from_file(params, par_file):
"""Update the config dictionary params from file.
Args:
params (dict):
Dictionary holding the to-be-updated values.
par_file (str):
Name of the parameter file with the update values.
Returns:
params (dict):
... | 1de0f3fc3f379508cb29d38c6e9bd1b70fa1e9c7 | 3,631,139 |
def accumulated_other_comprehensive_income(ticker, frequency):
"""
:param ticker: e.g., 'AAPL' or MULTIPLE SECURITIES
:param frequency: 'A' or 'Q' for annual or quarterly, respectively
:return: obvious..
"""
df = financials_download(ticker, 'bs', frequency)
return (df.loc['Accumulated other ... | 81b02370790457db598cac699cc0ffa835b9f6ac | 3,631,140 |
def PDifHist (inPixHistFDR):
""" Return the differential pixel histogram
returns differential pixel histogram
inPixHistFDR = Python PixHistFDR object
"""
################################################################
# Checks
if not PIsA(inPixHistFDR):
raise TypeError("inPixHist... | eae6b0c354482b48c3ef9d39bb556ce7e9ef93ca | 3,631,141 |
def SendToRietveld(request_path, payload=None,
content_type="application/octet-stream", timeout=None):
"""Send a POST/GET to Rietveld. Returns the response body."""
def GetUserCredentials():
"""Prompts the user for a username and password."""
email = upload.GetEmail()
password = getp... | d0937307a894b55f4ed5534de81bb60bf1f46333 | 3,631,142 |
def _parse_args():
"""
For parsing args when run as __main__.
"""
parser = ArgumentParser(description='Simulates the action of a Turing Machine.')
parser.add_argument('path', help="Path of a file containing rule quintuples.")
parser.add_argument('input', help="Input string.")
parser.add_argument('--rules', ac... | 0b059e467703f34ac2358db19b87c06ab90b9771 | 3,631,143 |
def join_2_steps(boundaries, arguments):
"""
Joins the tags for argument boundaries and classification accordingly.
"""
answer = []
for pred_boundaries, pred_arguments in zip(boundaries, arguments):
cur_arg = ''
pred_answer = []
for boundary_tag in pred_boundari... | 9801ca876723d092f89a68bd45a138dba406468d | 3,631,144 |
def qac_image(image, idict=None, merge=True):
""" save a QAC dictionary, optionally merge it with an old one
return the new dictionary.
This dictionary is stored in a casa sub-table called "QAC"
image: input image
idict: new or updated dictionary. If blank, it return QAC
... | 32bd3ffac05455a7157c7471bad559df24702b6e | 3,631,145 |
import random
def get_random_useragent():
"""生成随机的UserAgent
:return: UserAgent字符串
"""
return random.choice(USER_AGENTS) | f70de4e52399a291e8d65633e8f555d748905fc6 | 3,631,146 |
def product_detail_view(request, pk='', **kwargs):
"""
Display a detailed view of a product, showing all specifications
"""
ctxt = {'pk': pk}
# Empty (thus invalid) pk
if pk == '':
return client_error_view(request, ERROR_MSG['wrong_prod_pk'].format(pk), 404)
matching_products = Product.objects.filter(pk=pk... | 3244156920798b4c3008ee2e8a19d5fd5de86559 | 3,631,147 |
def _convert_velocities(
velocities: np.ndarray, lattice_matrix: np.ndarray
) -> np.ndarray:
"""Convert velocities from atomic units to cm/s.
Args:
velocities: The velocities in atomic units.
lattice_matrix: The lattice matrix in Angstrom.
Returns:
The velocities in cm/s.
"... | 8848d58a37244b2109455a73c2fd2458b0e21c58 | 3,631,148 |
import os
import stat
def is_regular_file(element):
"""
Return True if the given element is a regular file.
It accepts input as :py:mod:`file`, :py:mod:`str` or :py:mod:`int`.
"""
if type(element) is file:
fstat = os.fstat(element.fileno())
elif type(element) is str:
fstat = o... | 3a8d57c33eeb01dfd23171fd267f0d3af4a1ef3b | 3,631,149 |
import operator
import math
def unit_vector(vec1, vec2):
""" Return a unit vector pointing from vec1 to vec2 """
diff_vector = map(operator.sub, vec2, vec1)
scale_factor = math.sqrt( sum( map( lambda x: x**2, diff_vector ) ) )
if scale_factor == 0:
scale_factor = 1 # We don't have an actu... | 79e2cff8970c97d6e5db5259801c58f82075b1a2 | 3,631,150 |
def shuffle_list(gene_list, rand=np.random.RandomState(0)):
"""Returns a copy of a shuffled input gene_list.
:param gene_list: rank_metric['gene_name'].values
:param rand: random seed. Use random.Random(0) if you like.
:return: a ranodm shuffled list.
"""
l2 = gene_list.copy()
rand... | 3e3660a2266bb8f5d7ea2172148806d20a4b1b2b | 3,631,151 |
def my_map(f, lst):
"""this does something to every object in a list"""
if(lst == []):
return []
return [f(lst[0])] + my_map(f, lst[1:]) | 20016cd580763289a45a2df704552ee5b5b4f25e | 3,631,152 |
import struct
import ipaddress
def read_ipv6(d):
"""Read an IPv6 address from the given file descriptor."""
u, l = struct.unpack('>QQ', d)
return ipaddress.IPv6Address((u << 64) + l) | c2006e6dde0de54b80b7710980a6b0cb175d3e19 | 3,631,153 |
def normalizeRounding(value):
"""
Normalizes rounding.
Python 2 and Python 3 handing the rounding of halves (0.5, 1.5, etc)
differently. This normalizes rounding to be the same (Python 3 style)
in both environments.
* **value** must be an :ref:`type-int-float`
* Returned value is a ``int``... | 442bbee5838f5bef0edbe6ce6e42f8c744f7d220 | 3,631,154 |
def pin_light(a: np.ndarray, b: np.ndarray) -> np.ndarray:
"""Combines lighten and darken blends.
:param a: The existing values. This is like the bottom layer in
a photo editing tool.
:param b: The values to blend. This is like the top layer in a
photo editing tool.
:param colorize: (Op... | f551bc26cebdbc6750fb42653ff23b4aeda09d6f | 3,631,155 |
from pathlib import Path
def sun():
"""Get Sun data source"""
filename = (
Path(nowcasting_dataset.__file__).parent.parent / "tests" / "data" / "sun" / "test.zarr"
)
return SunDataSource(
zarr_path=filename,
history_minutes=30,
forecast_minutes=60,
) | 06f9db778662d65e7a157b314b8a1cd3e647c7e7 | 3,631,156 |
def generate_level08():
"""Generate the bricks."""
bricks = bytearray(8 * 5 * 3)
colors = [2, 0, 1, 3, 4]
index = 0
col_x = 0
for x in range(6, 111, 26):
for y in range(27, 77, 7):
bricks[index] = x
bricks[index + 1] = y
bricks[index + 2] = colors[col_... | c1535d8efb285748693f0a457eb6fe7c91ce55d4 | 3,631,157 |
def jwt_decode_token(token):
"""Register jwt decode handler
:param token:
"""
return jwt_lib.decode(token, current_app.config['JWT_SECRET_KEY'],
algorithms=current_app.config['JWT_ALGORITHMS']) | 274ebd03f6ca42436eeb8963a5d34777c68395f1 | 3,631,158 |
def renormalize_vector(a, scalar):
"""This function is used to renormalise a 3-vector quantity.
Parameters
----------
a: np.ndarray
The 3-vector to renormalise.
scalar: Union[float, int]
The desired length of the renormalised 3-vector.
Returns
-------
a: np.ndarray
... | 583c66621a0de2a2555104aed3a2dbb2e6302936 | 3,631,159 |
def load_data(path='affnist.npz'):
"""Loads the affnist dataset.
x_train: centered MNIST digits on a 40x40 black background
x_test: official affNIST test dataset (MNIST digits with random affine transformation)
# Arguments
path: path where to cache the dataset locally
(relative to ... | 474276570b0c05de09e397cb8d72d728de16a6f0 | 3,631,160 |
from re import T
def as_register_event_listener(
callback: EventCallback[RegisterEventEvent[T]]
) -> ListenerSetup[RegisterEventEvent[T]]:
"""A ListenerRegistraror type"""
return (EVENT_ID_REGISTER_EVENT, callback,) | 16017d437117462ddf60c1e98422379f37ee0303 | 3,631,161 |
def read_frame(frame_dir, model_name, scale_size=[480]):
"""
read a single frame & preprocess
"""
cv2_models = ['dino.vit', 'dino.conv', 'deit', 'mlp_mixer', 'resnet50', 'resnet152', 'resnet200', 'resnext', 'beit']
if model_name in cv2_models:
img = cv2.imread(frame_dir)
ori_h, ori_w, _ = img.shape
else:
... | a0ad77bcf0bf6b0c0118bd1cf83b8360d40df320 | 3,631,162 |
import collections
import random
def gen_undirected_graph(nodes = 1000, edge_factor = 2, costs = (1,1)):
"""
generates an undicrected graph with `nodes` nodes and around `edge_factor` edges per node
@param nodes amount of nodes
@param edge_factor approximate edges per node, might happen that som... | e46efd02805e82670703f456c979990a768af09f | 3,631,163 |
import os
def user_prompt(
question_str, response_set=None, ok_response_str="y", cancel_response_str="f"
):
"""``input()`` function that accesses the stdin and stdout file descriptors
directly.
For prompting for user input under ``pytest`` ``--capture=sys`` and
``--capture=no``. Does not work wit... | 086a56fd16b89cb33eff8f8e91bb5b284ae6d8c4 | 3,631,164 |
def compute_lpips(image1, image2, model):
"""Compute the LPIPS metric."""
# The LPIPS model expects a batch dimension.
return model(
tf.convert_to_tensor(image1[None, Ellipsis]),
tf.convert_to_tensor(image2[None, Ellipsis]))[0] | 3067a5ca312dead8308fa0b573e2853bbd590ab2 | 3,631,165 |
def int2bin(n, count=16):
"""
this method converts integer numbers to binary numbers
@param n: the number to be converted
@param count: the number of binary digits
"""
return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) | 70ce01844c8e32eb24750c4420812feda73a89dd | 3,631,166 |
def conv1x1(in_planes, out_planes, stride=1, groups=1, bias=False):
"""2D 1x1 convolution.
Args:
in_planes (int): number of input channels.
out_planes (int): number of output channels.
stride (int): stride of the operation.
groups (int): number of groups in the operation.
bias (boo... | 662ebdc7026b7324a749e7ee042f6aa2760a475d | 3,631,167 |
from typing import Tuple
def _get_preprocessing_functions(
train_client_spec: client_spec.ClientSpec,
eval_client_spec: client_spec.ClientSpec,
emnist_task: str) -> Tuple[_PreprocessFn, _PreprocessFn]:
"""Creates train and eval preprocessing functions for an EMNIST task."""
train_preprocess_fn = emnis... | 4d742f99001c84db89a67e2878efe020db819730 | 3,631,168 |
def intstr(num, numplaces=4):
"""A simple function to map an input number into a string padded with
zeros (default 4). Syntax is: out = intstr(6, numplaces=4) -->
0006
2008-05-27 17:12 IJC: Created"""
formatstr = "%(#)0"+str(numplaces)+"d"
return formatstr % {"#":int(num)} | 8637a1f6146d1ff8b399ae920cfbfaab83572f86 | 3,631,169 |
def vehiclesHistoryDF(
token="", version="stable", filter="", format="json", **timeseries_kwargs
):
"""Economic data
https://iexcloud.io/docs/api/#economic-data
Args:
token (str): Access token
version (str): API version
filter (str): filters: https://iexcloud.io/docs/api/#filte... | 097c259ed6017c95e180e9974f72f3421b55cfde | 3,631,170 |
def fit(history, scale_start=None, decay_start=None, n_start=None,
scale_decay_fixed=False):
"""
Parameters
----------
history : np.array
1-dimensional array containing the event times in ascending order.
scale_start : float
Starting value for the likelihood optimization.
... | 737b5e7cef5fb017f37f2bcc0537967d96f9c5f6 | 3,631,171 |
def from_raw(raw_segment):
"""
Parse a new segment from a raw segment_changes response.
:param raw_segment: Segment parsed from segment changes response.
:type raw_segment: dict
:return: New segment model object
:rtype: splitio.models.segment.Segment
"""
keys = set(raw_segment['added']... | 2dc6cffc724a081be203c4c4e123555c522f839e | 3,631,172 |
def _max_mask_non_finite(x, axis=-1, keepdims=False, mask=0):
"""Returns `max` or `mask` if `max` is not finite."""
x = _convert_to_tensor(x)
m = np.max(x, axis=_astuple(axis), keepdims=keepdims)
needs_masking = ~np.isfinite(m)
if needs_masking.ndim > 0:
m = np.where(needs_masking, mask, m)
elif needs_m... | 2a70687891645d904552b660ee7c7c57104ffe01 | 3,631,173 |
def get_uniform_prototype(nlayer, opLibrary):
"""Creates a prototype over the uniform layer distribution (all
probabilities are equal).
Arguments
----------
nlayer: int
A number of layers in the prototype
opLibrary: list of layer classes
The layer library.
Returns
... | 37c4dca16ef0adf64483d338c142d112fa296d04 | 3,631,174 |
def make_batch_X(batch_X, n_steps_encode, dim_wordvec, word_vector):
"""Returns the world vector representation of the batch input by padding or truncating as may apply with a final dimension of [batch_size, n_steps_encode, word_vector] """
for i in range(len(batch_X)):
batch_X[i] = [word_vecto... | 3f0307c45f5a5644779147babdccbd6dc356cf14 | 3,631,175 |
def gap_fill(g, layer_qs, index, start_val, end_val, extrusion_rate, total_extruded, total_distance, n_fill_lines=None, gap=None):
"""Fill a polygon with a gap in between the lines that fill it.
The gap has a size of either `gap` or is evenly divided by `n_fill_lines`
"""
assert (n_fill_lines is not No... | bc01498a419df7444f9a2ea838a0ae2b8fe6923c | 3,631,176 |
def weekend_christmas(start_date=None, end_date=None, observance=None):
"""
If christmas day is Saturday Monday 27th is a holiday
If christmas day is sunday the Tuesday 27th is a holiday
"""
return Holiday(
"Weekend Christmas",
month=12,
day=27,
days_of_week=(MONDAY, ... | bda4ddf5d5dca18f061c5a6aa4391929aeef2033 | 3,631,177 |
from typing import List
def get_interface_packages() -> List[str]:
"""Get all packages that generate interfaces."""
return get_resources('rosidl_interfaces') | 4cfd473f939d43b51ab57339533b8ec265777981 | 3,631,178 |
def rgb2str(r, g=None, b=None):
"""
Given r,g,b values, this function returns the closest 'name'.
:Example:
.. doctest:: genutil_colors_rgb2str
>>> print rgb2str([0,0,0])
'black'
:param r: Either a list of size 3 with r, g, and b values, or an integer representing r v... | 0cf76c74fc9ad9d2e97c35f5baf59f646605e979 | 3,631,179 |
def calc_uvw(phase_centre, timestamps, antlist, ant1, ant2, ant_descriptions, refant_ind=0):
"""
Calculate uvw coordinates
Parameters
----------
phase_centre
katpoint target for phase centre position
timestamps
times, array of floats, shape(nrows)
antlist
list of ant... | b5adcfb507d1d1599e3d65fdd82e201a95afd135 | 3,631,180 |
def rename_duplicate_name(dfs, name):
"""Remove duplicates of *name* from the columns in each of *dfs*.
Args:
dfs (list of pandas DataFrames)
Returns: list of pandas DataFrames. Columns renamed
such that there are no duplicates of *name*.
"""
locations = []
for i, df i... | c816804a0ea9f42d473f99ddca470f4e527336f9 | 3,631,181 |
def test_accel_nb_1():
""" Use decorator """
accel.has_numba = True
@accel.try_jit
def fn():
return np.ones(100) * 5
assert isinstance(fn, jitd_class) | 7bc16046180c1973a6584150a1822bcd5da06d19 | 3,631,182 |
def checkH(board, intX, intY, newX, newY):
"""Check if the horse move is legal, returns true if legal"""
tmp=False
if abs(intX-newX)+abs(intY-newY)==3:
if intX!=newX and intY!=newY:
tmp=True
return tmp | f1ce66457a54dea4c587bebf9bd2dd0b56577dc4 | 3,631,183 |
def solarize_add(image, addition, threshold=None, name=None):
"""Adds `addition` intensity to each pixel and inverts the pixels
of an `image` above a certain `threshold`.
Args:
image: An int or float tensor of shape `[height, width, num_channels]`.
addition: A 0-D int / float tensor or int ... | 1a4b68abf1e64d0390d2bfa26aa0e70f4a0f5e87 | 3,631,184 |
from tappy.tappy import tappy
def do_tappy_tide_analysis(dates, val):
"""
"""
obs = pd.DataFrame(val, columns=['val'])
se = pd.Series(dates)
obs = obs.set_index (se)
obs.dropna()
obsh = obs.resample('H').mean()
dates = datetime64todatetime(obsh.index)
val = obsh.va... | 30974a672b7574bf302458c97a25107e9a7ac8dc | 3,631,185 |
def is_dirty2():
"""Function: is_dirty2
Description: Method stub holder for git.Repo.git.is_dirty().
Arguments:
"""
return False | 01ed2000d4ae6565760ed2efaa6624d75b005151 | 3,631,186 |
import re
def getTranslation(tbl, all_names, tsv_output):
"""get name translation for contig files from prokka
Args:
tbl (string): Path to the tbl file
all_names (list of string): All the name in the fasta in order
tsv_output (string): Path of the output tsv table with the prokka and ... | 301b41b87c0d84a8f36430f64f9cfae14b69d5bf | 3,631,187 |
def create(language, namespace, templatepath):
"""
Create a language by name.
"""
lang = None
if language == "Java":
lang = Java(namespace, templatepath)
elif language == "C++":
lang = CXX(namespace, templatepath)
else:
raise ModelProcessingError(
"Inval... | 8a6c04a1c8b6486d246cc7eff6bd5c20ccd2a0fd | 3,631,188 |
def dq2segs(channel, gps_start):
"""
This function takes a DQ CHANNEL (as returned by loaddata or getstrain) and
the GPS_START time of the channel and returns a segment
list. The DQ Channel is assumed to be a 1 Hz channel.
Returns of a list of segment GPS start and stop times.
"""
#-- Che... | 5c261431b73d3b0f6acc61dc04b4c41283e65e1d | 3,631,189 |
import re
def get_info(prefix, string):
"""
:param prefix: the regex to match the info you are trying to obtain
:param string: the string where the info is contained (can have new line character)
:return: the matches within the line
"""
info = None
# find and return the matches based on ... | ed41100910df8ec3e0060ecd1196fb8cc1060329 | 3,631,190 |
import calendar
def to_unix(dt):
"""Converts a datetime object to unixtime"""
return calendar.timegm(dt.utctimetuple()) | aefe370b3a812c258b83a389a136914398077b20 | 3,631,191 |
def count_circular_primes(ceiling):
"""
Counts the number of circular primes below ceiling.
A circular prime is a prime for which all rotations of the digits is also
prime.
"""
return len([
a for a in range(ceiling)
if is_prime(a) and all(is_prime(a) for a in gen_rotation_list(a)... | efab99e401b9afd799ab3d2e29c70adca90b875a | 3,631,192 |
def get_user_documents(user, documents=None):
"""
Return collections and documents for the user
"""
collections = get_user_collections(user)
if not documents:
documents = get_document_model().objects.all()
if not user.is_superuser:
documents = documents.filter(collection__in=coll... | 3b6992434477caffde10c0dba3e67830af333b43 | 3,631,193 |
from typing import Optional
from typing import Tuple
import os
import re
import warnings
def VideoWriterCreate(
input_path: Optional[str] = None,
out_path: Optional[str] = None,
codec: str = "avc1",
fps: Optional[float] = None,
size: Tuple[int, int] = (None, None),
verbose: bool = False,
*... | ea1a25188b9f7fde29beb8cbe67d974244e21695 | 3,631,194 |
from typing import Dict
async def hashtags(
db: DataBase = Depends(db_conn),
time_query: Dict = Depends(time_query),
party: str = Query(None, description="Abbreviated name of party", min_length=3),
):
"""Number of times a hashtag is used by supporters of a specific party.
A supporter of a party i... | 19ae9cea717faa9786c3a28f2f65b0df69baf7bd | 3,631,195 |
from typing import Optional
def calculate_inverse_propensity_weighted_confidence_from_df_cache(
df_cached_predictions: pd.DataFrame,
rule_head: PyloAtom,
pylo_context: PyloContext,
propensity_score_controller,
verbose: bool = False,
o_propensity_score_per_prediction: Op... | 30f1c9d9cc74c420c79fabeed828fa44eeca7886 | 3,631,196 |
from datetime import datetime
def _get_choices(ballot_type):
"""
Returns Q object that matches a ballot of the specified type that's
currently active, i.e. now() is between the vote_start and vote_end dates
"""
return Q(ballot__type=ballot_type) &\
Q(ballot__election__vote_start__lte=da... | efbc67a5542aac5bb87ebed28232c7c42fe0724e | 3,631,197 |
from typing import Any
def route(user_model: Any, request: prediction_pb2.SeldonMessage) -> prediction_pb2.SeldonMessage:
"""
Parameters
----------
user_model
A Seldon user model
request
A SelodonMessage proto
Returns
-------
"""
if hasattr(user_model, "route_rest")... | ed58df98da4d1de16de0fdfc9e8e1f56cddbd920 | 3,631,198 |
def find_percentile(array, percentile):
"""Find the value corresponding to the ``percentile``
percentile of ``array``.
Parameters
----------
array : numpy.ndarray
Array of values to be searched
percentile : float
Percentile to search for. For example, to find the 50th percentil... | 88651b16baec86b1181fef35d36be636b8a3e053 | 3,631,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.