content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from pathlib import Path
def get_data_dir() -> str:
"""Get a filepath to the drem data directory.
Returns:
str: Filepath to the drem data directory
"""
cwd = Path(__file__)
base_dir = cwd.resolve().parents[3]
data_dir = base_dir / "data"
return str(data_dir) | 16e1bf3d8eab4c4f58ec90f832fd15809bdbbbca | 3,619,615 |
import select
def get_sites_by_processing_status(s_status, sorting_desc=False):
"""
Gets sites by processing status
:param s_status: str - The chosen processing status
:param sorting_desc: bool - Sorting order: True (desc), False (asc - default in PONY)
:return: sites_names: list of str - The ur... | 2316bc9a8fbd1bff0e1af72b20a390a710e9fb2e | 3,619,616 |
from typing import Dict
import logging
def _encode_json(tokenizer, sample_json: dict, max_sequence_length: int) -> Dict:
"""
Method enrich utterance json with encoded utterance, value and label for training later.
:param tokenizer: BERT tokenizer
:param sample_json: utterance JSON
:param max_sequ... | 161f8eac904674cefb815861d8c8aa5fe2787901 | 3,619,617 |
def is_trimesh_installed(raise_exception: Boolean = False) -> Boolean:
"""
Returns whether *Trimesh* is installed and available.
Parameters
----------
raise_exception
Whether to raise an exception if *Trimesh* is unavailable.
Returns
-------
:class:`bool`
Whether *Trime... | 4596af266177d424de2549b14650a1ba487a7ab7 | 3,619,619 |
import shutil
def get_unshare_path():
"""Find the path to the unshare utility."""
return shutil.which('unshare') | 5ca2f1a9bdd8cc107c00be137c6dc3ca0a6f0db7 | 3,619,620 |
def l3_interface_group_id(ne_id):
"""
L3 Interface Group Id
"""
return 0x50000000 + (ne_id & 0x0fffffff) | 00576c8c33fc965d759abc2aa00aa8f46b930a07 | 3,619,621 |
def LogStatusFrame(*args, **kwargs):
"""LogStatusFrame(wxFrame pFrame, String msg)"""
return _misc_.LogStatusFrame(*args, **kwargs) | e227ef646140b3cb7fb8ffaa938981a7cacb910d | 3,619,622 |
def set_safari_cookie(request):
"""
Special handling for Safari's third party cookie blocking: when showing a private link, user will be forwarded
to this view on WARC_HOST to have an arbitrary cookie set, so Safari will let us set an authorization cookie
in the iframe. Once we set the cooki... | 71aa8996e1ecbe9f391fa9f85e0886d4ce36e9ed | 3,619,623 |
import re
def eat_arguments(node, text):
"""
gets the (parameters) appended to the +tag
"""
DEL = r'(?P<argend>\))|(?P<has_value>=)'
ATTR = r'\s*(?P<attribute>[\w\-:\.#]+)\s*'
VAL = r'\s*"(?P<value>.*?)"\s*'
tokens = re.compile('|'.join((VAL, ATTR, DEL))).finditer(text)
for mo in tokens:
type_ = mo.lastg... | aeb61ba1ee0636af06a53848e9dcd2f9d5ec9670 | 3,619,624 |
def checkpoint(func, inputs, params, flag, final_nograd=0):
"""
Evaluate a function without caching intermediate activations, allowing for
reduced memory at the expense of extra compute in the backward pass.
:param func: the function to evaluate.
:param inputs: the argument sequence to pass to `fun... | 36cc3a8d66337992e7f8969026db386e34905825 | 3,619,625 |
def get_data(name):
"""Utility for convenient data loading."""
images, labels = extract_images()
images = np.reshape(images, list(images.shape) + [1, ])
rng = np.random.RandomState(seed=47)
# inds = rng.choice(len(images), int(len(images) / 5 * 4))
# print(inds)
if name == 'train' or name... | 635d8c246aa39ed752da747bd253bed30ea15fa3 | 3,619,626 |
def check_unlogged(tasks, logs, user, log_date):
"""Given a queryset of tasks, a queryset of logs and a log date, checks for
unlogged tasks and creates new logs where needed, returning True.
Returns False if no new logs are created."""
unlogged = []
# Check for unlogged tasks
for task in tasks:... | ac8701a343b2fbc3d473e10380bd328a78c2c293 | 3,619,627 |
from datetime import datetime
def _pipeline_runtime(jobs):
"""Compute the runtim of the pipeline"""
times = []
now = datetime.now()
# collect the times
for j in jobs:
if j.start_date:
s = j.start_date
e = j.finish_date if j.finish_date else now
times.app... | c6f819283bd736a3077e6bea3a372bcf87d7a38a | 3,619,628 |
def addresses(x: bytes) -> list:
""" Creating a list of IPv4 addresses from a byte string
Args:
x: source bytesting
Returns:
A list of one or multiple IPv4 addresses
"""
x = x[4:]
addr: list = []
while len(x) > 0:
single_address: bytes = x[5:9]
addr.append(i... | 92a4eefb537a07065f8cb6e7100030894c4a6333 | 3,619,629 |
def __max_group_mass__(groupMass, parameters):
# type: (pandas.DataFrame, LFParameters) -> pandas.DataFrame
"""Replace the m/z value of each row by the m/z with the highest
sample mean intensity.
Keyword Arguments:
groupMass -- mass or feature cluster
parameters -- LipidFinder's PeakFi... | 129f5381b18a0a89bab3758d9531175de3b61e0f | 3,619,630 |
def color_from_string(cstr):
"""
Return a Geosoft color number from a color string.
:param cstr: color string (see below)
:returns: color
Colour strings may be "R", "G", "B", "C", "M", "Y",
"H", "S", "V", or "K" or a combination of these
characters, each followed by up to three di... | bd4fccbf67f436c3a7a10b8ce13f542c6cbbf038 | 3,619,631 |
def corr_pred_gold(gold, pred, eval_type=EvalTypes.NODE):
"""Given a golden tree/sentence and a predicted tree/sentence, this counts correctly
predicted nodes/tokens (true positives), all predicted nodes/tokens (true + false
positives), and all golden nodes/tokens (true positives + false negatives).
@p... | 8e81d45af2a8ffce71962a8de9ccd3160e1a3513 | 3,619,632 |
def get_value(amount, currency):
"""
Returns the value of the transfer in the representation of the
currency it is in, without symbols
That is, 1000 cents as 10.00, 1000 yen as 1000
"""
if currency in DECIMAL_CURRENCIES:
return Decimal(amount)/Decimal(100)
return Decimal(amount) | f5edd6cafb1ffa1e87e88b09affb2182e00586f9 | 3,619,633 |
def subaward_types_are_valid_groups(type_list):
"""Check to ensure the award type list is a subset of one and only one award group.
Groups: are "Procurement" and "Assistance"
If false, the award type codes aren't a subset of either category.
"""
is_procurement = set(type_list).difference(set(procur... | 8ef5eea5e9480c8cc1573e41195fa9ea50ebd519 | 3,619,634 |
def parse_none(func):
"""Decorator for a parser which can parse None
Args:
callable: function to be decorated
Returns:
callable: func with attr indicating it can parse None
"""
setattr(func, _PARSE_NONE_ATTR, True)
return func | 4752bc774caf434b219cf8ffafa65cba067fb62b | 3,619,635 |
def register(request):
"""
Register new user.
Args:
request (HttpRequest):
Request with user `name`, `first_name` and `password` passed with
the `GET` method.
Returns:
An `HttpResponse` with search results.
"""
if request.method == 'POST':
user... | 14d55ac2d0a185797b94d9f216476e7bd0a74969 | 3,619,636 |
def make_tag_list(tag_dict):
""" make list from tag dictionary """
tag_list = tag_dict.keys()
# needless because keys doesn't overlap.
# tag_list = list(set(tag_list))
# but, in python3, type of tag_list is not list, it is dict_key.
tag_list = list(tag_list)
tag_list.sort()
return tag_li... | 3dc825c1ac9cf9b6a1d2df5d4b46f2755b267381 | 3,619,637 |
def temp_dynamics(
models: dict,
) -> np.ndarray:
"""Returns the new zone temperatures based on the current state."""
zone_temp = np.zeros(Z, dtype=np.float64)
for z in range(Z):
y = np.array(models[z]["ss_C"]).squeeze() * models[z]["x_k"].squeeze()
zone_temp[z] = y + models[z]["mean_ou... | bf4fcdfb34367663499b5dd16e4611f20cea3d0e | 3,619,638 |
def logsig(x):
""" logsig activation function """
return 1.0 / (1.0 + exp(-x)) | 896b8f779010b4591e3efcccca3bfb3a81cf1a01 | 3,619,639 |
def filter_cpgkeys_using_bedfile(cpgKeys, bedFileName):
"""
Keep only cpg keys in bed file range, return set of keys
:param cpgKeys:
:param bedFileName:
:return:
"""
cpgBed = calldict2bed(cpgKeys)
coordBed = get_region_bed(bedFileName)
intersectBed = intersect_bed_regions(cpgBed, coo... | 420f07571b0239e9df90ad25fc640baad444c253 | 3,619,640 |
def adjust_prices(utilities, caps, budgets, prices, n):
"""return the new prices"""
cleared_bool = clearing(np.sum(allocate(utilities, caps, budgets, prices, n), axis=0), utilities, caps)
# Find clearing prices
while not np.all(cleared_bool):
if not cleared_bool[0]:
for i in range(n)... | 64898029f4f5b66e8cf7b0bf2cc998efc84c8872 | 3,619,641 |
def symmetricTensor(a,b,c):
"""
symmetric tensor product from section 5.2 of Song et al. (2014)
"""
term1 = np.tensordot(np.tensordot(a,b,0),c,0)
term2 = np.tensordot(np.tensordot(c,a,0),b,0)
term3 = np.tensordot(np.tensordot(b,c,0),a,0)
return term1+term2+term3 | 6f039972b9736ffd03aa2fff81d10aecf27ec532 | 3,619,642 |
def sentinel(name):
"""Create a unique, one-off object with a useful repr"""
def __repr__(_):
return f'<{name}>'
return type(name, (), {'__repr__': __repr__})() | 6abe44a5b72bf7d5685c3d7ca97caf0b9c2ee49b | 3,619,643 |
def clifford_attractor(lvl, a, b, c, d):
"""
Inputs:
lvl -- integer, number of iterations
a, b, c, d -- numeric parameters
Return a tuple with two 1D numpy arrays, each of size lvl + 1,
with calculated xy coordinates.
"""
lvl += 1
# Containers to store xy components/coordinates... | c4c07666cc04a4cfa0f4f0f262af46f74610ad76 | 3,619,644 |
def diskAverage(s,r_out,bins=50,avgFlag=True):
"""
Computes the accretion disk mass-averaged for x via the following equation:
integral of 2*pisigma*x*r*dr / integral of 2*pi*sigma*r*dr.
Sigma, e,a... calculated on the fly to ensure that they are all evaluated at
the same location.
Paramete... | 1d1c9ee81269c45580b6c5b30f779ba156309826 | 3,619,645 |
def datestr(datetime_inst):
""" make iso time string from datetime instance
"""
return datetime_inst.isoformat("T") | 027dbaa0c3223261f4afd4e2f3aab45611eab265 | 3,619,646 |
import ast
def read_csv(fname, params_dict):
"""
Reads csv file.
Paramenters
-----------
fname : str
Path to file name.
params_dict : dict
Dict with paramenters for parsing csv file.
`csv_delimiter`, `proteins_column`, `proteins_delimiter`
Returns
-------
... | 145b0bc2beed493b788582a2240b5e0d3567e729 | 3,619,647 |
def minimal_spanning_tree(graph, mode='Prim', starting_node=None):
"""
Args:
graph: weighted adjacency matrix as 2d np.array
mode: method for calculating minimal spanning tree
starting_node: node number to start construction of minimal spanning tree (Prim)
Returns:
minimal s... | 2605761918b39efd7abc1f507b71a848f96d1047 | 3,619,648 |
def imaging_mask(maskbits, bitnamelist=get_default_maskbits(),
bgsmask=False, mwsmask=False):
"""Apply the 'geometric' masks from the Legacy Surveys imaging.
Parameters
----------
maskbits : :class:`~numpy.ndarray` or ``None``
General array of `Legacy Surveys mask`_ bits.
b... | 304a25224f37bbfb6c452c973205dee900c7abcb | 3,619,649 |
def gen_bbox(lat1_deg,lon1_deg,radius=10):
"""
gen_bbox returns the upper left and lower right coordinates of the bounding box
who's center is at the specified lat/lon
Inputs:
lat1_deg -- Input latitude (degrees)
lon1_deg -- Input longitude (degrees)
radius -- Inputs radius (meters)
... | 51bbff58c400fcdfe0a7a5a108383e5ffeef819b | 3,619,650 |
import bot_config
import traceback
def get_state(sleep_streak):
"""Returns dict with a state of the bot reported to the server with each poll.
"""
try:
if _in_load_test_mode():
state = os_utilities.get_state()
state['dimensions'] = os_utilities.get_dimensions()
else:
state = bot_config... | 4fdbe3a2f5c99ab7be73f9a0c0475fcffeb2575d | 3,619,651 |
def get_connection_probabilities(N,k_over_2,beta):
"""
Return the connection probabilities :math:`p_S` and :math:`p_L`.
"""
assert_parameters(N,k_over_2,beta)
k = float(int(k_over_2 * 2))
pS = k / (k + beta*(N-1.0-k))
pL = k * beta / (k + beta*(N-1.0-k))
return pS, pL | 4ad3f0d9214c1d920946714d28250a81f1596063 | 3,619,652 |
def GetPortagePackage(target, package):
"""Returns a package name for the given target."""
conf = Crossdev.GetConfig(target)
# Portage category:
if target == 'host' or package in Crossdev.MANUAL_PKGS:
category = conf[package + '_category']
else:
category = conf['category']
# Portage package:
pn = ... | 8acc7704a877738a8e2b1754a34ac4dd92b995f2 | 3,619,653 |
def get_new_objective(fields, objective):
"""Checks if the objective given by the user in the --objective flag
differs from the one in the dataset. Returns the new objective or None
if they are the same.
"""
if objective is None:
return None
try:
objective_id = fields.fiel... | a17cd55864a3c2215a0b7570228643b1e35e9805 | 3,619,654 |
def RandomForestClassifier():
"""Wrap a default Random Forest classifier with fixed parameter."""
return sklearn.ensemble.RandomForestClassifier(n_estimators=64) | d574a6dbb2825333b5c7c75c0ce8360619c74be0 | 3,619,655 |
def get_skew_symmetric(rotational_vector):
"""Get the skew symmetric matrix of a rotational vector.
Parameters
----------
rotational_vector: numpy.ndarray
the rotational vector.
Returns
-------
skew_symmetric:
the skew symmetric matrix of the rotational vector.
"""
... | 6dc7e43b817d51f84487083e9836235cac3cb5b4 | 3,619,656 |
import math
import torch
def wrap_phi_to_2pi_torch(x):
"""Shift input angle x to the range of [-pi, pi]
"""
pi = math.pi
x = torch.fmod(2 * pi + torch.fmod(x + pi, 2 * pi), 2 * pi) - pi
return x | 0905134f4cce5aae13f91e9e7900dd053a5861aa | 3,619,658 |
import binascii
import codecs
def utf16decode(bytes):
""" Take the UTF-16LE encoded strings as bytes from .tbl files and convert
to a UTF-8 string. Jython-compatible. """
bytes = binascii.hexlify(bytes)
bytes = [bytes[i:i+2] for i in range(0, len(bytes), 2)]
bytes = (''.join(filter(lambda a:... | eff2ccc27e2175bfb05efa59216cfc2150387c55 | 3,619,659 |
def FixAbsolutePathInLine(line, relative_paths):
"""Fix absolute paths present in |line| to relative paths."""
absolute_path = line.split(':')[0]
relative_path = relative_paths.get(absolute_path, absolute_path)
if absolute_path == relative_path:
return line
return relative_path + line[len(absolute_path):] | e0db0d2f3a0973b4db5f3e551f164481861c0b56 | 3,619,660 |
def vgg13_XXS(*args, **kwargs):
"""VGG 16-layer model (configuration "D")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = VGG(make_layers(cfg['BXXS']), final_filter=64, **kwargs)
model.name = "VGG13_XXS"
return model | 92996c6b4dc9f58b2833eaacbba9188203b0da09 | 3,619,661 |
def read_schema(path):
"""Reads a schema from the provided location.
Args:
path: The location of the file holding a serialized Schema proto.
Returns:
An instance of Schema or None if the input argument is None
"""
result = schema_pb2.Schema()
contents = file_io.read_file_to_string(path)
text_for... | 49daaee4c2edd1de290258e3167e0b37efd04d68 | 3,619,662 |
def is_http_url(url: str) -> bool:
"""判断url是否是http请求的url.
Args:
url (str): 待判断的url字符串
Returns:
bool: 是否是url
"""
try:
result = urlparse(url)
return all([result.scheme, result.netloc]) and result.scheme in ("http", "https")
except ValueError:
return False | fdce9da96da12ad212acb1b1c8b4f70e4495cf28 | 3,619,665 |
def flatten_tuple(item):
"""
"""
if not is_valid_iterable(item):
return ensure_tuple(item)
if item and is_valid_iterable(item[0]) and len(item) == 1:
item = item[0]
if item and is_valid_iterable(item[0]):
item = (*item[0], item[1])
return tuple(item) | 11dc6e87ad349b6ff79360db47426c16713f4ed0 | 3,619,668 |
import yaml
def connect_mongodb() -> MongoClient:
"""connect mongodb"""
config = yaml.load(open(SERVER_FILE_PATH, encoding="utf-8"))
config_dct = config.get("mongodb")
client = MongoClient(
"mongodb://{user}:{pwd}@{host}:{port}/{db}"
"?readPreference=primary".format(
user=c... | b50a55beadee3c2d6c0f48a9e6021f6e948a9e69 | 3,619,669 |
def f5(seq, idfun=None):
"""Uniqify a list (remove duplicates).
This is the fast order-preserving uniqifier "f5" from
http://www.peterbe.com/plog/uniqifiers-benchmark
The list does not need to be sorted.
The return value is the uniqified list.
"""
# order preserving
if idfun is None:
... | a64aa35e1d4ab89213240c8ec2325bab9ee75ffe | 3,619,670 |
def cvCrossProduct(*args):
"""cvCrossProduct(CvArr src1, CvArr src2, CvArr dst)"""
return _cv.cvCrossProduct(*args) | 14b317055dc0d47f8687a510f8cb841c6b5969a3 | 3,619,671 |
def compute_oks(points_gt, points_pr, scale=None, stddev=0.025):
"""Computes the object keypoints similarity between sets of points.
Args:
points_gt: Ground truth instances of shape (n_gt, n_nodes, n_ed),
where n_nodes is the number of body parts/keypoint types, and n_ed
is the ... | 893a995bb9fbfe0d9acf8d99911588008fe486ab | 3,619,672 |
async def get_member(message, command, example):
"""
getting the user from reply message
"""
try:
member = message.reply_to_message.from_user
logger.info(f"received the user {member}")
except AttributeError:
await message.answer(f"You must <b>send</b> the message "
... | e45250733c395fb3b2e3337b009a1a9d4e4119c0 | 3,619,673 |
import arcgis
def define_output_datastore(datastore=None, template=None):
"""
Sets the `arcgis.env.output_datastore` by providing the datastore and template name
to this method. If datastore is None, the `arcgis.env.output_datastore` will reset
to default.
========================== ===========... | 91f8030cdaf9face090b53ed9014168f3b439c7b | 3,619,674 |
import kwplot
def draw_roc(roc_info, prefix='', fnum=1, **kw):
"""
NOTE: There needs to be enough negative examples for using ROC
to make any sense!
Example:
>>> # xdoctest: +REQUIRES(module:kwplot)
>>> # xdoctest: +REQUIRES(module:ndsampler)
>>> from netharn.metrics import De... | 127237f9d327d711dd16e246cdbf1b0c6f6863fb | 3,619,675 |
import json
def verify_recognized(file_path, mkvmerge_path='mkvmerge'):
"""Verify a file is recognized by mkvmerge.
file_path (str):
Path to the file to be verified.
mkvmerge_path (str):
Alternate path to mkvmerge if it is not already in the $PATH variable.
"""
if not verify_mkvme... | 594619ceb240e384e85aa61570aab47e3e5b7e42 | 3,619,676 |
def padded_gather_nd(params, indices, r, idx_rank):
"""Version of gather_nd that supports gradients and blank indices.
Works like gather_nd, but if an index is given as -1, a 0 will be inserted
in that spot in the output tensor.
Args:
params: tensor from which to gather (see gather_nd).
indices: tenso... | 909c1b8f615367887ea5abe9a7ea881650c425b0 | 3,619,677 |
def formatted_bool_eval(token_lst, op_dict):
"""eval a formatted (i.e. of the form 'ToFa(ToF)') string"""
if not token_lst:
return None
if len(token_lst) == 1:
return token_lst[0]
has_parens, l_paren, r_paren = parens(token_lst)
if not has_parens:
return generic_eval(token... | e6e88099506884e197adb1d29d58665253904daf | 3,619,678 |
def mapk(actual, predicted, k=10):
"""
Computes the mean average precision at k.
This function computes the mean average prescision at k between two lists
of lists of items.
Parameters
----------
actual : list
A list of lists of elements that are to be predicted
(o... | 5c55bc1dfa48ee42e97560f72f7f72338eb8dfe1 | 3,619,679 |
def loss(_sender_input, _message, _receiver_input, receiver_output, labels, _aux_input):
"""
Accuracy loss - non-differetiable hence cannot be used with GS
"""
acc = (labels == receiver_output).float()
return -acc, {"acc": acc} | 85c7d614e004c6c5349c4f42eb99155b7c7aee48 | 3,619,680 |
def lazyprop(func):
"""Wraps a property so it is lazily evaluated.
Args:
func: The property to wrap.
Returns:
A property that only does computation the first time it is called.
"""
attr_name = '_lazy_' + func.__name__
@property
def _lazyprop(self):
"""A lazily evalu... | b14f82b196177be207923744dda695d6aa70248f | 3,619,681 |
def text_to_hitobject(text: str) -> HitObject:
"""
HitObjectの文字列を各情報に変換してHitObjectクラスで出力します
引数
----
text: str
-> HitObject
戻り値
------
HitObject
-> HitObjectクラス
予想される例外
--------------
ValueError
-> おそらくフォーマットが合っていないです、一旦見直しましょう
"""
text_split: list = text.split(',')
if len(text_split) != 6:
rais... | 62cfc588e5b421b411cd08c1ec94653256924caf | 3,619,682 |
def convert_DateTimeField(model, prop, kwargs):
"""Returns a form field for a DateTimeField."""
return f.DateTimeField(**kwargs) | e0a6cde4d5f96ba51a59868da20191ff4e4b2ca4 | 3,619,683 |
def extract_range(s):
""" Extract range from string"""
ranges = s.split(',')
if len(ranges) > 1:
return (int(ranges[0]), int(ranges[1]))
else:
return (int(ranges[0]), None) | 2a0fea0bdbd40a9fc998fa0b1e2af97be1cbd980 | 3,619,684 |
def expand_machine_type():
""" get machine type specs from api """
machines = {}
compute = googleapiclient.discovery.build('compute', 'v1',
cache_discovery=False)
for pid, part in cfg.instance_defs.items():
machine = {'cpus': 1, 'memory': 1}
... | 645332927003ade153f3be57eb263e7483f11422 | 3,619,685 |
def _ChooseTest(anomalies):
"""Chooses a test to use for a bisect job.
The particular TestMetadata chosen determines the command and metric name that
is chosen. The test to choose could depend on which of the anomalies has the
largest regression size.
Ideally, the choice of bisect bot to use should be based... | ddad6c52f2560e550bbbd4e72036669915fc4521 | 3,619,687 |
def _make_contrib(superclass, func=None):
"""Backport from django 1.8."""
def contribute_to_class(self, cls, name, **kwargs):
if func:
func(self, cls, name, **kwargs)
else:
super(superclass, self).contribute_to_class(cls, name, **kwargs)
setattr(cls, self.name, _C... | ed92c383c2336134ac0e1598658de45ec384af52 | 3,619,688 |
from typing import List
from typing import Callable
from typing import Optional
def get_bundle_from_waypoints(
ports1: List[Port],
ports2: List[Port],
waypoints: Coordinates,
straight: Callable = straight,
taper_factory: Callable = taper_function,
bend: Callable = bend_euler,
sort_ports: b... | b7c86dc5718b44c26ba26d98daca7185de0ee9e5 | 3,619,690 |
def Gaussian(values, errors, Nsamples=100, weights=None, guess=None, bias=True):
"""
A maximum likelihood estimator that returns the parameters for a Gaussian
that best describes a given data set. Uncertainties on the
best-fitting parameters are calculated using Monte Carlo sampling, but
this c... | e479f20049314611d7225115f27d57bfa4d7da2d | 3,619,691 |
def leNetModel():
"""
Creates a LeNet model.
"""
model = createPreProcessingLayers()
model.add(Convolution2D(6,5,5,activation='relu'))
model.add(MaxPooling2D())
model.add(Convolution2D(6,5,5,activation='relu'))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(120))
... | 27fd6d4276215cf3bb1cf93d5c639ae715910750 | 3,619,692 |
def simpleCollision(spriteOne, spriteTwo):
"""
Simple bounding box collision detection.
"""
widthSpriteOne, heightSpriteOne = spriteOne.image.get_size()
rectSpriteOne = spriteOne.image.get_rect().move(
spriteOne.pos.x - widthSpriteOne / 2,
spriteOne.pos.y - heightSpriteOne / 2)
... | b6084ad260e084effb11701a6b859e0a58c9d19b | 3,619,693 |
def points_in_box(box: 'Box', points: np.ndarray, wlh_factor: float = 1.0):
"""
Checks whether points are inside the box.
Picks one corner as reference (p1) and computes the vector to a target point (v).
Then for each of the 3 axes, project v onto the axis and compare the length.
Inspired by: https... | cd33957b0f87b71548dd20c9ca34fccb8666aa59 | 3,619,694 |
def random_flip(flip_x_chance, flip_y_chance, prng=DEFAULT_PRNG):
""" Construct a transformation randomly containing X/Y flips (or not).
Args
flip_x_chance: The chance that the result will contain a flip along the X axis.
flip_y_chance: The chance that the result will contain a flip along the Y ... | 5e4b479f4c03464ad7e76788e783f59ef445adb9 | 3,619,695 |
def load_yaml(filename: str):
"""
Load contents of a yaml file in a dictionary
:param filename: path to the yaml file
:return: a data object contains contents of the yaml file
"""
with open(filename, "r") as f:
data_stream = f.read()
return load(data_stream, Loader=Loader) | 817d7974359840b083320928918a064ba0e3008c | 3,619,697 |
def display_email_address(email):
"""Make a formatted address (eg: "User Name <username@somewhere.net>"),
from a tuple (Display name, email address) or a list of tuples.
If the parameter is a string, it is returned.
>>> recipients = [('Joe','joe@smith.com'),'sally@smith.com']
>>> displa... | 500f99d36f018f6ccf77fa941b14caca4aa02032 | 3,619,698 |
def create_dataframe(records, cache=False, require_unique=None):
"""Create a spark DataFrame from a list of records.
Parameters
----------
records : list
list of spark.sql.Row
cache : bool
If True, cache the DataFrame in memory.
require_unique : list
list of column names... | 8889c9160f2fa869592b01639b057435d65de0d3 | 3,619,699 |
def einsum_matmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix multiplication.
The returned indices are to perform a matrix multiplication A.B where
the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and
M <= N, and identity matrices are impl... | b5fb2fed515070172d7f6279d3ff5e3dbcc7db84 | 3,619,701 |
def place_review(request, place_id):
"""Create a place review for specified place.
Args:
request: auto-generated by django.
place_id: place identity defined by Google.
POST payloads:
review: review text for this user.
"""
if request.method != 'POST':
return HttpResp... | 1c882fce7a0e0ee375d358495a36d535ee754950 | 3,619,702 |
def part_2_min(guess, list_):
"""finds the position at which minimum fuel is used and returns the fuel amount"""
fuel_for_guess = part_2_fuel(guess, list_)
fuel_guess_up = part_2_fuel(guess + 1, list_)
fuel_guess_down = part_2_fuel(guess - 1, list_)
if (fuel_for_guess < fuel_guess_down) and (fuel_f... | 4ddec4ba164241491ad23494228b6f5c164c854a | 3,619,704 |
def fits2dict(fits_file,ext,par_list):
"""
'Converts' a FITS file to a Python dictionary, with a list of the original
FITS table's columns, of the user's choosing. Can use this for ANY FITS file,
but is meant for mkf/orb files in $OBSID_pipe folders from NICER, or event files
(be it from NICER-data ... | 99c0ce799aa92129fa598501d8b96e8369a5e8ee | 3,619,705 |
def vector_from_skew_matrix(skew_mat):
"""
Compute the skew-symmetric matrix,
known as the cross-product of a vector,
associated to the vector vec.
:param skew_mat: 3x3 skew-symmetric matrix
:return vec: 3d vector
"""
skew_mat = vectorization.expand_dims(skew_mat, to_ndim=3)
n_skew_... | 516e2ecf400af46c507d0b34830b3307b08fbbda | 3,619,707 |
def mutelist(request):
"""
Edit mutelist entries
"""
mutelist = MuteList.objects.filter(user=request.user)
return _template_values(request,
page_title="edit mute list",
header="mutelist",
navbar='nav_account',
... | a8487cbfe8823b5e2266e3b4d8ca5bf166e2fbc9 | 3,619,709 |
def gen_path(base, code):
"""
Generate a path for give base path and code used in data generation
"""
#return os.path.join(base, code[:2], code[:3])
return base | e05790a740b7ab0f83ba5db020598c20d0f89520 | 3,619,710 |
def script_to_bech32(script: bytes, witver: int) -> str:
"""https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program"""
witprog = sha256(script)
return bech32.encode(network('hrp'), witver, witprog) | 1eea5867b8efa2709f78ab77127ca2f3c0d4865e | 3,619,711 |
import torch
def compute_ssim(
img0,
img1,
max_val=1.0,
filter_size=11,
filter_sigma=1.5,
k1=0.01,
k2=0.03,
return_map=False,
):
"""Computes SSIM from two images.
This function was modeled after tf.image.ssim, and should produce comparable
output.
Args:
img0: to... | 251fe5a1a0df9f06bc7d8b820d24486077489e9e | 3,619,712 |
from typing import List
from typing import Set
def sample_unique_molecules(model: DistributionMatchingGenerator, number_molecules: int, max_tries=10) -> List[str]:
"""
Sample from the given generator until the desired number of unique (distinct) molecules
has been sampled (i.e., ignore duplicate molecules... | 1d8e8aaa9f7b25fcb801e6b95ee8f1e33510f119 | 3,619,713 |
import numbers
import json
import base64
def encode(d):
"""Encode an object in a way that can be transported via Mesos attributes: first to
JSON, then to base64url. The JSON string is padded with spaces so that the base64
string has no = pad characters, which are outside the legal set for Mesos.
"""
... | b1018b9eba2f136f9281dcb936d0903290abd505 | 3,619,714 |
def get_detected_head(np_img_set, cascades):
"""Detects a head and returns HeadData depending on input.
Head data is scaled normalized, x, y, and radius go from 0 to 1.
depth is same as raw data"""
potential_boxes = _run_cascades(np_img_set.ir, cascades)
if(len(potential_boxes) == 0):
retu... | a3f1d10b20724db5816a10e587ee13c4a95af13a | 3,619,715 |
def create_csv(file_path):
"""
This function will create an index file with image paths and labels in csv format
obtained csv will have two columns path(path to acess the image),label(class of the image)
"""
images=[]
labels=[]
label_file=pd.DataFrame(columns=['path','label'],index=None)
... | 42582c2d4de22998674c3a4323b909100b358080 | 3,619,716 |
from sklearn.neighbors import KDTree
def knn_cond_mutual_information(x, y, z, k, standardize = True, dualtree = True):
"""
Computes conditional mutual information between two time series x and y
conditioned on a third z (which can be multi-dimensional) as
I(x; y | z) = sum( p(x,y,z) * log( p(z)*p... | c3f384d95b8345ca63bcfea3de06348fd9084814 | 3,619,717 |
def kv_kernel(v1, v2, c=3):
""" Updated vertex kernel that multiples the dirac on the node
labels and a brownian bridge on the node attributes """
if isinstance(v1, int):
""" If just an integer, then no attr """
k_dirac = dirac(v1, v2)
k_brownian_bridge = 1
elif isinstance(v1, l... | b09bd5e14f1c07d51da96ac1928b0e44aa6c6a87 | 3,619,719 |
from typing import Any
from typing import Dict
def validate_reserved_alias(_netid: str, client: ShrunkClient, alias: str) -> Any:
"""``GET /api/validate_reserved_alias/<b32:alias>``
Validate an alias. This endpoint is used for form validation in the frontend. Response format:
.. code-block:: json
... | 5cce18b6ada5f836b4a1d46deb09fa15c060f372 | 3,619,721 |
def _kl_normal_gp(n, gp, name=None):
"""Calculate the batched KL divergence KL(gp || n).
Args:
n: instance of a Normal distribution object.
gp: instance of a GaussianProcess distribution object.
name: (optional) Name to use for created operations.
default is 'kl_normal_gp'.
Returns:
Batchw... | eeb02f4a095601c6120693e2dd3c2b6d8ad21c1f | 3,619,722 |
def mahalanobis(u, v, VI):
"""
:purpose:
Computes the Mahalanobis distance between two 1D arrays
:params:
u, v : input arrays, both of shape (n,)
VI : the inverse of the covariance matrix of u and v
note that some arrays will result in a VI containing
very high v... | 6a26d889e838a8efb4bcab5a1e4f9b124746d94d | 3,619,723 |
def is_user_blacklisted(user_id: int) -> bool:
"""
CHECK IF A USER IS BLACKLISTED
"""
return bool(
c.execute(
"""
SELECT blacklisted
FROM users
WHERE user_id=?
""",
(user_id,),
).fetchone()[0]
) | 76eb70ed968a46c2fb43e7dfa40233d0e67a6f39 | 3,619,726 |
def return_pitch_bend_tuple_dict(
tet, origin=0, size_of_semitone=SIZE_OF_SEMITONE
):
"""Returns a dictionary of form
(pitch_number: (12-tet midinum, pitch_bend))
Keyword args:
- origin: the 12 - tet pitch class from which the relevant pitches
will be calculated. (Should pro... | de1a8905a538d9b8e692d29d07e964932f37853d | 3,619,727 |
def third_function(x):
"""Third benchmark function.
Args:
x (int, float): Input.
Returns:
float: Output. :math:`sin(πx)`
"""
return x * np.sin(np.pi * x) | 2a19a139e6300175dacfd8551c6371c284855375 | 3,619,728 |
from typing import Counter
import math
def corpus_bleu(list_of_references, hypotheses, weights=(0.25, 0.25, 0.25, 0.25),
smoothing_function=None):
"""
:param references: a corpus of lists of reference sentences, w.r.t. hypotheses
:type references: list(list(list(str)))
:param hypothese... | 5b6c3100720d5a8d7402962df91ffd3d9a03e234 | 3,619,729 |
import requests
def fetch_project(name):
"""Return the loaded JSON data from PyPI for a project."""
url = 'https://pypi.python.org/pypi/{}/json'.format(name)
r = requests.get(url)
try:
return r.json()
except ValueError:
# has to *return* an error instead of raising one,
# c... | 135b3a018a8e430dc8722ae93caa3771da9e328b | 3,619,730 |
from typing import Union
from typing import Tuple
def SQuAD1(root: str, split: Union[Tuple[str], str]):
"""SQuAD1 Dataset
For additional details refer to https://rajpurkar.github.io/SQuAD-explorer/
Number of lines per split:
- train: 87599
- dev: 10570
Args:
root: Directory ... | 45ff73572df84063956854ca434bbe005d7db812 | 3,619,731 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.