content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def Bulk_emails():
"""批次寄信"""
users = [
{"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"},
{"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"},
{"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"},
{"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"},
{"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"... | 4032c17a63a9f4e4ef4c628a0c726359b2c7ec77 | 54,500 |
def model2():
"""Build a convnet with dropout and batch normalisation."""
input = layers.Input(shape=input_shape[1:], dtype=np.float)
x = layers.Conv1D(10, 5, activation='relu', name='CONV_1')(input)
x = layers.Conv1D(10, 5, activation='relu', name='CONV_2')(x)
x = layers.BatchNormalization()(x)
... | 5f60618cd5f9a7f9597d4ae9e066ed08411331a1 | 54,501 |
def in_subnet(cidr, addrs=None):
"""
Returns True if host is within specified subnet, otherwise False
"""
for address in addrs:
if ip_in_subnet(address, cidr):
return True
return False | 6a454bbbf2ce75584d094fe815c8464676efb45f | 54,502 |
from typing import AnyStr
import secrets
def constant_time_compare(val1: AnyStr, val2: AnyStr) -> bool:
"""Return True if the two strings are equal, False otherwise."""
return secrets.compare_digest(
encoding.force_bytes(val1), encoding.force_bytes(val2)
) | d28e1881f3da840b863b11ee5a12c549cb9de037 | 54,503 |
def make_company_node(c: dict) -> Node:
"""Create new Company node for dict
"""
all_attributes = c.get('all_attributes', {})
return Node('Company',
name=c['name'],
company_number=c['company_number'],
federal_state=all_attributes.get('federal_state'),
... | 3fbf35b3133f8eb7e865e6e703de061ed7e72c15 | 54,504 |
def problem_reciprocal_exponential(x):
"""Return recrprocal exponential function."""
return np.exp(-x) | 070e39a1d116907d2ce29527f28e02d57aca3208 | 54,505 |
import datetime
from azure.cli.core._session import VERSIONS
def get_cached_latest_versions(versions=None):
""" Get the latest versions from a cached file"""
if not versions:
versions = _get_local_versions()
if VERSIONS[_VERSION_UPDATE_TIME]:
version_update_time = datetime.datetime.strpt... | 7ec17fe7768295d7108bc857d252378300bb8ee0 | 54,506 |
def get_time(raw_time):
"""
Get treated time value from the raw provided time.
# 2020/09/05T05:21:48z
# 2020-09-05T05:21:48z
# dtr = dt.replace("/","-")[:-1]
:param raw_time: <string>
:return treated_time: <datetime>
"""
treated_time = raw_time.replace("/", "-")
return treate... | cccdfc8710b63c2f273fa0e8c638c5fc6e66a1b8 | 54,507 |
import os
def update_table(contents, filename, last_modified):
"""
This is the first function called when the dashboard opens
Takes in data from upload or uses default
Creates pkl file of DF to be accessed
Also takes in values from filters
Need to adjust this so if the user uploads a new file... | fb73870dfda5e78cbd6e682e8f70853aa58da672 | 54,508 |
import math
def noise_floor(nf=1, bandwidth=1, noise_temp=290):
"""
Calculate noise floor of a receiver.
:param nf: Noise figure in dB
:param bandwidth: bandwidth in Hz
:param noise_temp: noise temperature in Kelvin
"""
return (
10 * math.log10(KBOLTZMAN * noise_temp * 1000) + nf ... | 2c951b40f9526b9d3b247614d4af9679efc2983e | 54,509 |
def get_round_from_jitemid(jitemid, cursor):
"""Take a jitemid, return a round."""
round_jitemid_mapping = { (0, 'br negative one') }
# if jitemid is a key in the dictionary:
# return the value
# otherwise just return "UNKNOWN ROUND"
return round | 9242e098d31312c3181377d5bb8f4dfaf33c29ca | 54,510 |
import urllib
def safe_urlsplit(url):
"""This is a hack to prevent the regular urlsplit from splitting around question marks.
A question mark (?) in a URL typically indicates the start of a
querystring, and the standard library's urlparse function handles the
querystring separately. Unfortunately, qu... | 273b97bfb43107f7cddeb144c0dd284ca444c84c | 54,511 |
import six
def _ConvertInteger(value):
"""Convert an integer.
Args:
value: A scalar value to convert.
Returns:
The integer value.
Raises:
ParseError: If an integer couldn't be consumed.
"""
if isinstance(value, float) and not value.is_integer():
raise ParseError('Couldn\'t parse integer... | d5ca07d28827729df1bac9f1d446c623804fb4ba | 54,512 |
import logging
def to_segments(data, num=32):
"""
These code is taken from:
https://github.com/rajanjitenpatel/C3D_feature_extraction/blob/b5894fa06d43aa62b3b64e85b07feb0853e7011a/extract_C3D_feature.py#L805
:param data: list of features of a certain video
:return: list of 32 segments
"""
... | 378da87dbe710ed4e27580e6fd166c14afeab605 | 54,513 |
import os
def draw_graph_graphviz(vertices, edges, image=None, engine="dot"):
"""
Draws a graph using :epkg:`Graphviz`.
@param edges see below
@param vertices see below
@param image output image, None, just returns the output
@param engine ... | 232b596cc9a7d95d8d2159c1387b1419c385f2b6 | 54,514 |
async def discord_has_token(discord_id: int, db: AsyncSession = Depends(get_db_session)):
"""Return if a user has a valid token"""
profile = await discord_users.get_profile_from_discord_id(discord_id)
if not profile:
return DestinyHasTokenModel(token=False, value=None)
no_token = await discord_... | 575f87a27ecee04b9a411db24d182f64570c4309 | 54,515 |
import os
def calc_FID(gen, batchsize=100, stat_file="%s/cifar-10-fid.npz" % os.path.dirname(__file__), dst=None, path=None,
n_ims=5000, num_evals=1, training=True):
"""Frechet Inception Distance proposed by https://arxiv.org/abs/1706.08500"""
@chainer.training.make_extension()
def evaluatio... | d1b61c4fb98cdde686c5b29ea48571391f9f5557 | 54,516 |
def tokenize_text(text):
"""
Tokenizes and tags a given text.
Args:
text (str): Text to process.
Returns:
List(Tuple[str, str]): List of word-tag pairs.
"""
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
tokens = nltk.word_tokenize(text)
tagged =... | d61a696a0886a8aadc4aa9b202cbc246fb393816 | 54,517 |
import torch
def kl_loss_diag(mean, logvar):
"""
KL divergence of normal distributions with diagonal covariance and standard multivariate normal.
:param mean1: mean of distribution 1
:param logvar1: logarithm of the covariance diagonal of distribution 1
:return: KL divergence of the given distrib... | e8cedc4ccebc120a4367f9ce52ac96210beb0b5f | 54,518 |
def randomize(df, seed=None):
"""Develop a randomization function that randomizes all of a dataframe's cells
then returns that randomized dataframe. This function also accepts a random
seed for reproducible randomization"""
df = df.copy()
columns = df.columns
df = shuffle(df[columns], random_st... | 1ddb9623732ff16ce464b3b0fee4728c34a1e152 | 54,519 |
def add_class(add, class_):
"""Add to a CSS class attribute.
The string `add` will be added to the classes already in `class_`, with
a space if needed. `class_` can be None::
>>> add_class("foo", None)
'foo'
>>> add_class("foo", "bar")
'bar foo'
Returns the amended cl... | b5f12ea7a5c573b65ebbd84d987a5de5090e33d0 | 54,520 |
def get_model(point_cloud, is_training,num_classes,normal = False,bn_decay=None,bn=True,
num_keypoints = 192,k = 16,nsample = 32):
""" Classification PointNet, input is BxNx3, output BxNUM_CLASSES """
b = point_cloud.get_shape()[0].value
n = point_cloud.get_shape()[1].value
end_points = ... | c8334171394f4d3e872ef1e9d86af75225e86a47 | 54,521 |
import _random
def preview_synthetic_training_data(data,
target,
backgrounds=None,
verbose=True,
**kwargs):
"""
A utility function to visualize the synthetically gene... | cbcd15c732d6a6ed8fa29d584c497d20bf28f19e | 54,522 |
def guessColorName(nameMe):
"""Return a tuple (distance, guessed human-name of a color)."""
return min(colors, key=lambda x: distance(nameMe, x)) | b1562865c665ff453f309675cc31bb049e88cbbb | 54,523 |
import re
def to_lower_camel_case(str_to_convert):
"""
This function will convert any string with spaces or underscores to lower camel case string
:param str_to_convert: target string
:return: converted string
"""
if type(str_to_convert) is not str:
raise TypeError("The method only tak... | 8bfd591fcbfcff51b463596266cba1403f2d6153 | 54,524 |
def ordinal_suffix(n):
"""Return the ordinal suffix for a positive integer
>>> ordinal_suffix(0)
''
>>> ordinal_suffix(1)
'st'
>>> ordinal_suffix(2)
'nd'
>>> ordinal_suffix(3)
'rd'
>>> ordinal_suffix(4)
'th'
>>> ordinal_suffix(11)
'th'
>>> ordinal_suffix(12)
'th'
>>> ordinal_suffix(13)
... | 53617737aaf28c2d239301358f01d1b0cea9f6cb | 54,525 |
def sentence_to_token_ids(sentence, vocabulary, max_sequence_length):
"""Convert a string to a list of integers representing token-ids."""
words = sentence.strip().split()
if len(words) > max_sequence_length:
words = words[:max_sequence_length]
return [vocabulary.get(w, UNK_ID) for w in words] | 77ab881e8da7400a1db388e4db393e39b2aaab8f | 54,526 |
def _collect_facts(resource):
"""Transfrom cluster information to dict."""
facts = {
'identifier' : resource['ClusterIdentifier'],
'create_time' : resource['ClusterCreateTime'],
'status' : resource['ClusterStatus'],
'username' : resource['MasterUs... | a881451ac409288b93160d4cec4b27a3547fe3f9 | 54,527 |
import torch
import sys
from sys import version
def vendor_requirements_available(vendor_requirements: TypeDict[str, TypeAny]) -> bool:
"""
Check whether torch or python version is supported
Args:
vendor_requirements: dictionary containing version of python or torch to be supported
Returns:
... | 254d18b1c3725772b7fd10c787f8c793d90ff0fe | 54,528 |
from scipy.stats import percentileofscore
import seaborn as sns
import logging
def correlate_distance_matrix_quadrants(distmat, figdir, name):
"""
Take the lower triangle matrix of each quadrant in the distance matrix,
and then correlate all quadrants lower triangle matrices with eachother.
Repeat thi... | 18185ee2f2e2aa7f3c46d3dac904d7bc7402a26f | 54,529 |
def leave_one_in(feature_groups):
"""For each group, return a copy of just that group
Args:
feature_groups (list) The feature groups to apply the strategy to
Returns: A list of feature dicts
"""
return feature_groups | 5933925d909b6777f916b6bc585734dd768477b3 | 54,530 |
import queue
def push(ui, repo, patch=None, **opts):
"""push the next patch onto the stack
By default, abort if the working directory contains uncommitted
changes. With --keep-changes, abort only if the uncommitted files
overlap with patched files. With -f/--force, backup and patch over
uncommitt... | 9c37243b75038c23faec50b774efed6af9bad1ed | 54,531 |
def disable() -> dict:
"""Disables log domain, prevents further log entries from being reported to the client."""
return {"method": "Log.disable", "params": {}} | f5be0972e43d24fc4b69fbeb2c13850d68af52bf | 54,532 |
def repeat_each_element(element: tf.Tensor, number_of_repeats: int) -> tf.data.Dataset:
"""
A dataset mappable function which repeats the elements a given number of times.
:param element: The element to map to to repeat.
:param number_of_repeats: The number of times to repeat the element.
:return: ... | d2bc479a5b2eced6a3c906e14ce964fd4d0c3d84 | 54,533 |
import glob
import os
def read_instance(path, shape=(4, 240, 240, 155)):
""" Read a 3-d image with corresponding mask """
x = np.empty(shape)
for i, channel in enumerate(CHANNELS):
channel_path = glob.glob(os.path.join(path, f"*{channel}.nii.gz"))[0]
x[i] = nib.load(channel_path).get_fdat... | 01356c29641d82acbc99feff4a235915be20d19f | 54,534 |
def ncc(I, J):
"""
Code comes from:
Unsupervised Learning for Fast Probabilistic Diffeomorphic Registration
Adrian V. Dalca, Guha Balakrishnan, John Guttag, Mert R. Sabuncu
MICCAI 2018.
"""
eps = 1e-5
# assumes I, J are sized [batch_size, *vol_shape, nb_feats]
ndims = len(I... | fb29e1381ab0d8d3ca0521792d4d67d82d5e2b32 | 54,535 |
from typing import Sequence
from typing import Hashable
from typing import Tuple
import string
import unicodedata
def equivalent_string(
seq_x: Sequence[Hashable], seq_y: Sequence[Hashable]
) -> Tuple[str, str]:
"""
Returns a string equivalent to a sequence, for comparison.
As some methods offered by... | e5c4a4c31b687449ac16e25a6d6fe0dcf65f8266 | 54,536 |
def _get_subtopics(
corpus, dictionary, num_topics, num_words, depth, passes=10
):
"""The recursive function"""
ldamodel = models.ldamodel.LdaModel(
corpus,
num_topics=num_topics,
id2word=dictionary,
passes=passes
)
lda_output = {}
topics = ldamodel.ge... | 1b509e77b0b95a6ef55c2963ed5df3c62b59f3ee | 54,537 |
def normalizeimage(image, depth=256, verbose=False):
"""Normalize image to chosen bit depth"""
if verbose:
print 'Normalizing image from [' + str(numpy.min(image)) + ':' + str(
numpy.max(image)) + '] to',
normalizedimage = ((image - numpy.min(image)) * (depth / (numpy.max(
image)... | bddbb1bb1538e6ef47dfb88fbf394fe10cec0388 | 54,538 |
def _strftime(d):
"""
Format a date the way Atom likes it (RFC3339?)
"""
return d.strftime('%Y-%m-%dT%H:%M:%SZ%z') | 1eebf1bff9c68ba4649f1377f16b4b9feb737f01 | 54,539 |
def append_entrypoint(app: Flask, entrypoint: str, location: str) -> Flask:
"""Add routes/functions defined in entrypoint."""
mod = pw.import_entrypoint(entrypoint, location)
fm = pw.get_func_annotations(mod)
if not any([e.endpoint for e in fm]):
raise Exception("no endpoints defined")
ope... | e52c230cc24e52eb918a6f1eeb5c3ebd8f783289 | 54,540 |
from typing import Union
from typing import List
def _extract_process_nodes(cube: Union[dict, DataCube], process_id: str) -> List[dict]:
"""Extract process node(s) from a data cube or flat graph presentation by process_id"""
if isinstance(cube, DataCube):
cube = cube.flat_graph()
return [d for d i... | 353eeaaf36d26fe8f460246d22327f4032fd10f8 | 54,541 |
import imp
import marshal
def read_pyc(filename):
"""
Read the code inside a bytecode compiled file if the MAGIC number is
compatible
Returns:
a code object
"""
data = read_file(filename, 'rb')
if not is_gae and data[:4] != imp.get_magic():
raise SystemError('compiled code... | 660f352b25467f12b8db1d80fb4140dc679c9b94 | 54,542 |
def gravity_and_floor(x, y, floor, g=1, scale=100):
"""
A hard wall at the bottom of the view and a linear downward potential.
Note: y increases in the downward direction.
"""
v = np.zeros((len(y), len(x)))
v += g*np.abs(y[:,None]-floor)
v[y>floor] = scale
return v | fdaa202d92813a383b7061506e6737a7e96476b5 | 54,543 |
import logging
def action_check(opts, continuation=arch_check):
""" Continue analysis only if it compilation or link. """
if opts.pop('action') <= Action.Compile:
return continuation(opts)
else:
logging.debug('skip analysis, not compilation nor link')
return None | 2fed961b21bb6e657892789071d62ed2c02ee6ac | 54,544 |
def scan(a, dim=0, op=BINARYOP.ADD, inclusive_scan=True):
"""
Generalized scan of an array.
Parameters
----------
a : af.Array
Multi dimensional arrayfire array.
dim : optional: int. default: 0
Dimension along which the scan is performed.
op : optional: af.BINARYOP. def... | d1697420593e1fb82d93a333d6afd23df233b3f9 | 54,545 |
def get_centor(feature, centors):
"""
迭代计算聚类中心
:param node: 待判断数据[r,g,b]
:param centors: init[cen1,cen2...]
:param classes: [[node of class1],[node of class2],......[node of classk]]
:return: cens=[cen1,cen2...]
"""
k = len(centors)
# 建立k个类别数据的空集合
classes = [[] for _ in range(k)]... | e0dd6e62f76a3aad0f01fd87f0da6b697a49431b | 54,546 |
def food(request):
"""Show food.
"""
tracker = init_tracker(request)
tracker.track_page_view("http://0.0.0.0:8000/food", "food_page")
food = Food.objects.filter(owner=request.user).order_by('date_added')
is_empty = True
for f in food:
if f.quantity > 0:
is_empty = False
... | 0fbc0677375548d0560b61a325ee5da74cfdb69f | 54,547 |
from ..plot_utils import make_3d_axis, Frame
def plot_basis(ax=None, R=None, p=np.zeros(3), s=1.0, ax_s=1,
strict_check=True, **kwargs):
"""Plot basis of a rotation matrix.
Parameters
----------
ax : Matplotlib 3d axis, optional (default: None)
If the axis is None, a new 3d axi... | f53a5edf1f33050a7dfb9a3f8f4ef4f01a25b6f4 | 54,548 |
def slicify(index, length=-1):
"""
Takes an index as an instance of a list, a tuple, an np.ndarray, an int, or
anything else. In the case of a list, a tuple, or a np.ndarray return a
slice if possible, else return an np.ndarray. In the case of an int, return
slice(int, int+1). In the case of anythin... | 2885163f9affc7c3d886e3ba3a070dd3f6287136 | 54,549 |
def run_async_asyncio(func, *args, **kwargs):
"""
Runs an Async Function in a Sync Call using asyncio
in sync calls
"""
if not iscoroutinefunction(func):
func = AsyncFunction(func)
coro = func(*args, **kwargs)
return asyncio_run(coro) | 4f746a538579013090b64dc45d5204988e0ca60a | 54,550 |
from typing import Iterable
from typing import Callable
def get_combined_revision(functions: Iterable[Callable]) -> forge.Revision:
"""Combine the parameters of all revisions into a single revision"""
params = {}
for func in functions:
params.update(forge.copy(func).signature.parameters)
retur... | 643128e545fc4a6f54d3d2314d62c986ea7971b6 | 54,551 |
def create_layer_for_inference(layer: _TrainingWrapper, algorithm):
"""Internal API to create layer for inference with weight compression."""
# TODO(tfmot): move these checks to public API for
# visibility.
if not isinstance(algorithm, object):
raise ValueError('`_create_layer_for_inference` requires `algor... | e57994255c9c3623506f187940f9147f124f1251 | 54,552 |
import collections
def merge(d, u):
"""
Recursively updates a dictionary.
Example: merge({"a": {"b": 1, "c": 2}}, {"a": {"b": 3}}) = {"a": {"b": 3, "c": 2}}
"""
for k, v in u.items():
if isinstance(v, collections.Mapping):
r = merge(d.get(k, {}), v)
d[k] = r
... | d96d95fd7a236429fa5c278c800832205e073cd4 | 54,553 |
def _numba_i0(x):
"""
computes i0 to 15 digits
"""
if x < 0:
x = -x
if x <= 8.0:
y = x/2.0 - 2.0
return np.exp(x)*_numba_chbevl(y, i0_lt8)
else:
y = 32.0/x - 2.0
return np.exp(x)*_numba_chbevl(y, i0_gt8)/np.sqrt(x) | fded0baf18e8fca5b5463a7ecf633a510ee629fe | 54,554 |
def parse_args(parser):
"""
Parse commandline arguments.
"""
parser.add_argument('--waveglow', type=str, required=True,
help='Full path to the WaveGlow model checkpoint file')
parser.add_argument('-o', '--output', type=str, required=True,
help='Directo... | f0333da61342bd40055894330aa7e0e0eadf434a | 54,555 |
import math
def track_day_test(year, month, day, hour, lat, lon, elevdlim=-2.5):
"""
Given date, time, lat and lon calculate if the sun elevation is > elevdlim.
If so return daytime is True
This is the "day" test used by tracking QC to decide whether an SST measurement is night or day.
Th... | 2496099eab7ed970236d59c69949ce1ef4f93374 | 54,556 |
def arn_has_slash(arn):
"""Given an ARN, determine if the ARN has a stash in it. Just useful for the hacky methods for
parsing ARN namespaces. See
http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html for more details on ARN namespacing."""
if arn.count("/") > 0:
return True
... | a3c36eba79bc572ae5389aea9c0ef0a0924cc7b3 | 54,557 |
from typing import Callable
from typing import List
def calculate_gradient(f: Callable, x: List[float]) -> np.array:
"""Return the gradient of a function at a given point
Args:
f (Callable): function in consideration
x (List[float]): point at which gradient is evaluated
Returns:
... | cf9866f21006e5ad3c7af8b5328a8224caae8c05 | 54,558 |
import sys
def stereographic_proj(
normals,
intensity,
max_angle,
savedir,
voxel_size,
projection_axis,
min_distance=10,
background_south=-1000,
background_north=-1000,
save_txt=False,
cmap=default_cmap,
planes_south=None,
planes_north=None,
plot_planes=True,
... | 365a795270fbae696fc688be501396a4b177e6d7 | 54,559 |
import typing
def keccak_224(data: typing.Optional[bytes] = None) -> Keccak:
"""Returns a 224-bit keccak hash object"""
return Keccak(c=448, r=1152, n=224, name='keccak_224', data=data) | e34482d3fe4d4a3ad9976ad7647b6409f8a7768e | 54,560 |
def decr_id(id, id_remove):
"""Decrement a single id, with the aim of closing the gap at
id_remove. The logic used is similar to that incr_id_after.
"""
k = len(id_remove)
if len(id) >= k and id[:k-1] == id_remove[:k-1] and id[k-1] > id_remove[k-1]:
return id[:k-1] + (id[k-1] - 1,) + id... | 51f9a2254e1736a4e6014a8714789186ee4a3c63 | 54,561 |
from typing import Dict
def get_ctf_json(json: Dict) -> Dict:
"""
Get ctf in rawsec json.
Parameters
----------
json: Dict
rawsec json.
Returns
-------
Dict
ctf dict.
"""
return json["ctf_platforms"] if "ctf_platforms" in json else {} | 3ef14283c2468a41685c43051823807b7e23d561 | 54,562 |
from pesummary.core.plots.plot import _make_corner_plot
def _make_extrinsic_corner_plot(samples, latex_labels, **kwargs):
"""Generate the corner plots for a given approximant
Parameters
----------
opts: argparse
argument parser object to hold all information from the command line
samples:... | be3a9303a95f5eac4d693e70970d269ebf7663d1 | 54,563 |
import io
def GetOperationError(error):
"""Returns a ready-to-print string representation from the operation error.
Args:
error: operation error object
Returns:
A ready-to-print string representation of the error.
"""
error_message = io.StringIO()
resource_printer.Print(error, 'yaml', out=error_... | 65df8d8861212c381dc0e234e83250ec6f577bb5 | 54,564 |
import logging
def hogbom_clean(dirty, psf,
gamma=0.1,
threshold="default",
niter="default"):
"""
Performs Hogbom Clean on the ``dirty`` image given the ``psf``.
Parameters
----------
dirty : np.ndarray
float64 dirty image of shape (ny, ... | f5d920e12707ecdb197b442606401c1d90e8f887 | 54,565 |
from pyspark.pandas import sql_processor
from typing import Optional
from typing import Union
from typing import List
from typing import Any
import os
import warnings
def sql(
query: str,
index_col: Optional[Union[str, List[str]]] = None,
**kwargs: Any,
) -> DataFrame:
"""
Execute a SQL query and ... | 100b76aabc718796cf6000a27bc8e657150474b2 | 54,566 |
def to_cartisian(r, theta):
"""
Take two numbers or np arrays and return cartisian representation
of the comblex number(s) r*exp(i*theta)
Return:
tuple (x, y)
"""
x = r*np.cos(theta)
y = r*np.sin(theta)
return (x, y) | de507866eb912f93a14639fc4157326b21a9196d | 54,567 |
def _get_team_(client, jwt, project_id):
"""Get team and return response."""
headers = ss_client_auth_header(jwt)
response = client.get(TEAM_API.replace(':project_id', project_id),
headers=headers, content_type='application/json')
return response | 67de2be6391a99209a08d92a6150ffd69a61847b | 54,568 |
def counted ( f ):
"""create 'counted' function to know number of function calls
Example
-------
>>> fun = ...
>>> func = counted ( fun ) ## use as function
>>> @counted
>>> def fun2 ( ... ) : return ...
"""
def wrapped ( *args, **kwargs ):
wrapped.calls += 1
... | 75f8e297910c049b551f38b440d99b21c6c74caf | 54,569 |
def get_latex_permutations(rows, cols, tarray, title):
"""
Creates a latex table as a string.
The string can be cut and paste into the dissertation.
:param rows: number of rows in the board.
:param cols: number of columns in the board.
:param tarray: 2D array of the table contents.
:para... | 261bb367a948731748441d10afd4dcee793624b5 | 54,570 |
import logging
def load(file, collapsed=True, index=None):
"""Loads Laue diffraction data."""
if file['stacked'] is True:
files = loadstack(file)
if file['ext'] == 'h5':
vals = loadh5files2(files, file['h5']['key'], file['frame'])
else:
if file['ext'] == 'h5':
... | be2820949555d79fc76e261c587ee229459b6901 | 54,571 |
def format_map_to_vector(feature_lists: list, start: int, end: int):
"""
Convert map into vector
:param feature_lists: list of features, whose elements are maps.
:param start: starting element within list
:param end: ending element within list
:return: vector (list) of selected features
"""
... | a593c3cf12d154e924955f3fcf20dc616c2771ac | 54,572 |
def tree_subtract_mean(oks: PyTree) -> PyTree:
"""
subtract the mean with MPI along axis 0 of every leaf
"""
return jax.tree_map(partial(subtract_mean, axis=0), oks) | 9eed40b488799a44583503118fd419bc530a3e90 | 54,573 |
def patch_expsets_otherprocessedfiles_for_queried_files(connection, **kwargs):
""" Update the Higlass Items from Experiment Set Other Processed Files (aka Supplementary Files).
Args:
connection: The connection to Fourfront.
**kwargs, which may include:
called_by(opti... | 86f113d7f7dd92f9fdfa356ccaca7aeebdc6dea9 | 54,574 |
import sys
def running_in_notebook_or_ipython():
"""
Returns ``True`` if the module is running in IPython kernel,
``False`` if in IPython shell or other Python shell.
"""
return "ipykernel" in sys.modules | 77aacd398ac99b2370dd500fcbf40bedcb35f573 | 54,575 |
def selector(possibilities, names):
""" Print a selector of all possibilities, and validate the choice against the "names" list """
# Print all possibilities
for i in range(len(possibilities)):
print(f'({i +1}) {possibilities[i]}')
names.append(str(i + 1))
skip_lines(1)
# Ask a user... | 6cec0f732d8161b46899db82a7171cc30be681fa | 54,576 |
def splinit(fun, data, i, s, smax, par, x0, n0, u, v, x, y, x1, x2,
L, l, xmin, fmi, ipar, level, ichild, f, xbest, fbest, stop):
"""
splits box # par at level s according to the initialization list
in the ith coordinate and inserts its children and their parameters
in the list
"""
n... | 962fd2168ed0c16667dab8fad031bbebf41fb7d3 | 54,577 |
def handle_effect_results(permutation_result):
"""Takes in output from multiprocess_permutation function and converts to
a better formatted dataframe.
Parameters
----------
permutation_result : list
output from multiprocess_permutation
Returns
-------
permutation_df : pd.DataFr... | 564362c5db1916ff2dbb33cd253da5270edb7201 | 54,578 |
def get_one_carrot_input():
"""
Obtains pre-defined testing base astar that is assured not to fail
"""
args = g08.get_args()
args.a_estrella = True
args.vision = 2
args.zanahorias = 2
args.tablero_inicial = "_generated_inputs_/4x4(1).txt"
result = g08.get_result(algorithm="AStar", ar... | 27ebd29c4d9ec6b01a1abb070b96d9e4c9413ee9 | 54,579 |
def canvas_pull ( canvas ,
ratio = 0.80 ,
left_margin = 0.14 ,
right_margin = 0.05 ,
bottom_margin = 0.14 ,
top_margin = 0.05 ,
hSpacing = 0.0 ,
vSpacing ... | 03b765901eb276ecdabf70a849ac9383882f1630 | 54,580 |
def soft_threshold(X, thresh):
"""Proximal mapping of l1-norm results in soft-thresholding. Therefore, it is required
for the optimisation of the GFGL or IFGL.
Parameters
----------
X : ndarray
input data of arbitrary shape
thresh : float
threshold value
Returns
-------... | acf2b4db26bf821a58b5a29ab31a907325068bb8 | 54,581 |
import argparse
import logging
def iteration(data: dict, args: argparse.Namespace, it: int) -> dict:
"""Perform self-learning iteration. See Vulic et al, 2019, for details."""
# (1) update embeddings from in-dictionary terms
data['dico'].update_embeddings(data['src'], data['trg'])
# (2) solve procru... | 519fb4e0c2276e6c5c66ab573f93e9995f1575f1 | 54,582 |
def _to_ffmpeg_time(n):
""" Format number of seconds to time expected by FFMPEG.
n: int
Time in seconds to format.
returns: Formatted time in FFMPEG format.
"""
m, s = divmod(n, 60)
h, m = divmod(m, 60)
return '%d:%02d:%09.6f' % (h, m, s) | 64808a801dd4008ef61df305efa936ee1e9f5c5b | 54,583 |
def compute_similarity(network, feature_matrix):
"""
Builds a weighted graph, where each edge (u, v, sim) is constructed by
computing the Jaccard similarity (sim) of the attributes of nodes u and v.
For the sake efficiency, a vectorized implementation is used
:param network: The network
:param f... | 324b417aa7c439050147931dacb21ec61b2243b1 | 54,584 |
def vxxxxx(p, vmass, nhel, nsv):
"""
Defines a vector wavefunction. nhel=4 is for checking BRST.
Input momenta have shape (num events, 4).
Parameters
----------
p: tf.Tensor, vector boson four-momenta of shape=(None,4)
vmass: tf.Tensor, boson mass of shape=()
nhel: tf.Tensor... | 795bf250ac512416fac79601ba8bc9be692eeb38 | 54,585 |
from typing import List
from typing import Dict
def find_properties_object(path: List[str], field: str, properties) -> Dict[str, Dict]:
"""
This function is trying to look for a nested "properties" node under the current JSON node to
identify all nested objects.
@param path JSON path traversed so far... | 748399f8b8fcb6d04535059557ce1f9c9a02cffa | 54,586 |
def get_nodes(lines):
"""
Return node register IDs provided lines from a trace file.
:param lines:
The lines from the trace file to be searched.
"""
nodes = []
for line in lines:
found = re_node_register.search(line)
if found:
node_id = found.group(2)
... | 9faf8b60d734d381e0664a76bca1765620b5c510 | 54,587 |
import argparse
def build_arg_parser():
"""
Builds a standard argument parser with arguments for talking to vCenter
-s service_host_name_or_ip
-o optional_port_number
-u required_user
-p optional_password
"""
parser = argparse.ArgumentParser(
description='Standard Arguments f... | 563766fbac1e3b6f25a11ac30518515fb7ae16fd | 54,588 |
def are_infinity_coordinates(coordinates_value):
""" To check whether the coordinates are infinite.
Parameters
----------
coordinates_value: np.array, or list
x and y coordinates you want to check.
Returns
----------
bool
Are coordinates infi... | 5958790c666e550870c149019cc57480145ba6be | 54,589 |
import os
def get_twitter_api_keys(sport: str, area: str):
"""Load twitter api keys.
API keys for twitter account for a sport + area must be defined in an
environment variable. E.g. keys for latu updates in oulu must be defined in
env var LATUBOT_KEYS_LATU_OULU.
The value of the env var must con... | c981d7b8872f6ae73b215414b1ede1a24af31453 | 54,590 |
import os
import pickle
def assemble_pysb(stmts, data_genes, out_file):
"""Return an assembled PySB model."""
base_file, _ = os.path.splitext(out_file)
#stmts = ac.load_statements('%s.pkl' % base_file)
stmts = preprocess_stmts(stmts, data_genes)
# Make a SIF model equivalent to the PySB model
... | 06c5ca60f2a0a55f8eeb748a7d3502891f70b32d | 54,591 |
import json
def read_cam_from_json(path):
"""generates a Camera object from a json file"""
with open(path) as f:
config = json.load(f)
intrinsic = config['intrinsic']
coefficients = [intrinsic['k1'], intrinsic['k2'], intrinsic['k3'], intrinsic['k4']]
cam = Camera(
rotation=SciRot... | eae61d7d4757cf3df602c7f5bb16a6d3488f6ba1 | 54,592 |
def get_angle_encoding_model(theta, neural_data, ang_bin_edges, speed=None, min_speed=None, max_speed=None,
data_type='spikes', n_xval=5):
"""
:param theta: array n_samps of angles in radians
:param neural_data: array n_units x n_samps of firing rates
:param ang_bin_edges: b... | bec04c6a42562bbaec5f25a541ebb60797e78221 | 54,593 |
import timeit
import operator
def optimize(solver, func, maximize=True, max_evals=0, pmap=map, decoder=None):
"""Optimizes func with given solver.
:param solver: the solver to be used, for instance a result from :func:`optunity.make_solver`
:param func: the objective function
:type func: callable
... | 77f710af596b5a0a7024105379e146b9f28a333d | 54,594 |
import logging
import requests
def uninstall_callback():
"""Hipchat will hit this endpoint when the integration has been uninstalled by the end user."""
redirect_url = request.args.get('redirect_url')
installable_url = request.args.get('installable_url')
logging.info("Getting installable info from %s... | affed9a5e69b62502d7459924c820c227e34ec52 | 54,595 |
import pathlib
import re
def normalized_uri(root_dir):
""" Attempt to make an LSP rootUri from a ContentsManager root_dir
Special care must be taken around windows paths: the canonical form of
windows drives and UNC paths is lower case
"""
root_uri = pathlib.Path(root_dir).expanduser().re... | 230091cad5dedbe14c2e7b0f6e726e640fd63495 | 54,596 |
from typing import Dict
from typing import Any
import importlib
def _serialize(selector: str, class_name: str, values: Dict[str, Any]):
"""Serializes message using the selector and defined class name."""
package_name = _find_package_name(selector)
class_object = getattr(importlib.import_module(package_nam... | c31c62f6c5626f947ea4ddc75606102eb7fd8769 | 54,597 |
import json
def download_prs(source_url, source, credentials):
"""
INPUT:
source_url: the root url for the GitHub API
source: the team and repo '<team>/<repo>' to retrieve prs from
OUTPUT: retrieved prs sorted by their number if request was successful. False otherwise
"""
url = sou... | 4994e84f9cf429b3ac0297ef132663b2f4c3eebe | 54,598 |
import subprocess
def align(fh, transl=True):
"""
Translate and align pangenome cluster fasta file
"""
align_exe = MuscleCommandline(
r'C:\Users\matthewwhiteside\workspace\b_ecoli\muscle\muscle3.8.31_i86win32.exe',
clwstrict=True)
# Align on stdin/stdout
proc = subproces... | 7158690a2e46aff26fd2d36617e8f5240363ec3a | 54,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.