content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def spgr(pd, r1, r2s=None, mt=None, transmit=None, receive=None, gfactor=None,
te=0, tr=25e-3, fa=20, sigma=None, device=None):
"""Simulate data generated by a Spoiled Gradient-Echo (SPGR/FLASH) sequence.
Tissue parameters
-----------------
pd : tensor_like
Proton densit... | 78cfa5f7b264fd85603a5e66ec77974558f05d21 | 3,634,900 |
import argparse
def setup_options():
"""
add logging options to cmd-line,
but surpress them, so that they don't clobber up the help-messages
"""
my_argparser = argparse.ArgumentParser(add_help=False)
my_argparser.add_argument("--LogLevel_Model", default = "", \
help = argparse.... | dfbd38e14720f1bbe8806b1d9dab47694c7a0610 | 3,634,901 |
def create_subject(request):
"""
This is a form
"""
template = loader.get_template('form.html')
form = SubjectForm()
return HttpResponse(template.render({'form':form, 'redirect': '/subject', 'submit':'Create Subject and add to class'}, request)) | 8bea2cb4e6ba26a030a9b3008377c126af551491 | 3,634,902 |
def text2number(text):
"""
Convert arabic text into number, for example convert تسعة و عشرون = >29.
Example:
>>> text2number(u"خمسمئة و ثلاث و عشرون")
523
@param text: input text
@return: number extracted from text
@rtype: integer
"""
number_names = WORDS_NUMBERS.copy()
... | 9a0b28810549efab956d720695534e82aecf2c4f | 3,634,903 |
def parse_prototype(prototype, additional_definitions={}):
"""Given a single annotated C function prototypes (see module docstring),
for syntax), and an optional dict of non-base type definitions,
return the following information that ctypes needs to load and annotate
a function:
function_name: str
... | 93d79407bf0b4175f51dfef0fb39fa288eaa1512 | 3,634,904 |
def create_resource():
"""QonoS resource factory method."""
return wsgi.Resource(SchedulesController()) | caca6c4a6d8b3e67db79eee1937ae0479de1ab05 | 3,634,905 |
def compute_heatmap(model, saved_model, image, pred_index, last_conv_layer):
"""
construct our gradient model by supplying (1) the inputs
to our pre-trained model, (2) the output of the (presumably)
final 4D layer in the network, and (3) the output of the
softmax activations from the model
"""
... | c412a1ddb7300434334b2276df257cda51072f96 | 3,634,906 |
def get_all_orders():
"""Returns a list of ALL the orders for rooms and AGs, with reader and approver specified for each."""
# Get a list of all the orders of access groups of all responsible approvers.
ag_relation = ApprovesAgRequest.query \
.join(AccessGroupRequest, AccessGroupRequest.id == ApprovesAgRequest.ag... | 798c7347e0db7f3f7ba2f66364cbc55be3a641ed | 3,634,907 |
def isAnomaly(lowBand, highBand, value):
"""Condition for anomaly on a certain row"""
if value < lowBand or value > highBand:
return True
return False | 552513115ec9c98c40cd6487b6a33f497c562c87 | 3,634,908 |
def initWeights(positive_count, negative_count, trainingSamples):
"""
Initialise weights.
:param positive_count: Number of positive samples.
:param negative_count: Number of negative samples.
:param trainingSamples: Training samples.
:return: Weights
"""
positiveSampleInitialWeight ... | 640fb32b62fc461b9c638d3a647c53db69424fd9 | 3,634,909 |
def get_distance_calculator(name, *args, **kwargs):
"""returns a pairwise distance calculator
name is converted to lower case"""
name = name.lower()
if "moltype" in kwargs and kwargs.get("moltype") is None:
kwargs.pop("moltype")
if name not in _calculators:
raise ValueError('Unknown... | c8d1d0fca18e7f71742fb8a45829ac4e8f84077b | 3,634,910 |
import os
def git_ls_dirs(root=None):
"""
List all folders tracked by git.
"""
dirs = set()
for fn in git_ls_files(root):
dirs.add(os.path.dirname(fn))
return list(dirs) | d746543c028e00ff05154d48d198c3f6117ccd36 | 3,634,911 |
def compute_escape_peak(spectrum, ratio, params,
escape_e=1.73998):
"""
Calculate the escape peak for given detector.
Parameters
----------
spectrum : array
original, uncorrected spectrum
ratio : float
ratio of shadow to full spectrum
param : dict
... | c6948547a2bb34f32cb423b5ab0cd8d9f9f695e4 | 3,634,912 |
def create_transaction(wallet, purchase):
"""
creates a transaction of crypto from the PSP wallet to a user who has paid in fiat
Note: Ideally this will be done for more than 1 tx at a time.. would have a basket of tx ready to go
and then they will all go out in one TX with all the outputs. Then the s... | d6e31bb698782128e58ccf73e8b62e34f8937377 | 3,634,913 |
import numpy
def _create_globio_lulc_op(
lulc_array, potential_vegetation_array, pasture_array,
ffqi, globio_nodata, pasture_threshold, primary_threshold):
"""Construct GLOBIO lulc given relevant biophysical parameters."""
result = numpy.empty_like(lulc_array, dtype=numpy.int16)
result[:] ... | 1a6ca959e8da30767a264bc529f16ab6f2626851 | 3,634,914 |
import random
def temperature_dist():
"""Random normal variated temperature around RT_MEAN with RT_SIGMA"""
return random.normalvariate(RT_MEAN, RT_SIGMA) | 971b2296878780e9af568784a454d08dfead0e2c | 3,634,915 |
def pair_keys_to_items(items, key):
"""
Convert the list of key:value dicts (nics or disks) into a dict.
The key for the new dict is one value of the current dict identified by the
key parameter. If it does not exist, then the key is the order number in
the list.
"""
new_items = {}
for ... | 92c66bfbb298e767b3fedbfcfd48ad87ac1162ef | 3,634,916 |
import os
def load_results(model_no=0):
""" Loads saved results if exists """
losses_path = "./data/test_losses_per_epoch_%d.pkl" % model_no
accuracy_path = "./data/test_accuracy_per_epoch_%d.pkl" % model_no
train_accuracy_path = "./data/train_accuracy_per_epoch_%d.pkl" % model_no
if os.path.isfil... | 79406c231d548667afb24dee2f48809f83ea1a5a | 3,634,917 |
def rotateStructure(structure):
"""
Rotate a structure randomly
"""
angle_rad = _np.random.rand(1) * 2 * _np.pi
newstructure = _np.array(
[
(structure[0, :]) * _np.cos(angle_rad)
- (structure[1, :]) * _np.sin(angle_rad),
(structure[0, :]) * _np.sin(angle_r... | 9df411e82caa5827499ae5648a1ec7d24e27cff5 | 3,634,918 |
async def iamalive(name, **params):
"""
Accept services promotions
"""
await state.alive_service(name)
return OK | 82e0e8243dd8eadfc27cab484157c2d1c6db63b1 | 3,634,919 |
def add_wind_rotation_info(res: str, ds: xr.Dataset) -> xr.Dataset:
"""
Add wind rotation information to the dataset
Args:
res: grid resolution, format as f'c{number cells in tile}'
"""
rotation = _load_wind_rotation_matrix(res).drop_vars("tile", errors="ignore")
common_coords = {"x": ... | 242293904998367fe75b112adc1298ead39152a7 | 3,634,920 |
def get_human_size(size):
"""Return a string describing the size in bytes"""
if size < 1024:
return '{} B'.format(size)
if size < 1024 * 1024:
return '{:.2f} KB'.format(float(size) / 1024)
if size < 1024 * 1024 * 1024:
return '{:.2f} MB'.format(float(size) / (1024 * 1024))
if... | 48cee8ca55717d6fb48c5c1dc06becff71c58f0e | 3,634,921 |
def do_authentication(environ, start_response, authn_context, key,
redirect_uri, headers=None):
"""
Display the login form
"""
logger.debug("Do authentication")
auth_info = AUTHN_BROKER.pick(authn_context)
if len(auth_info):
method, reference = auth_info[0]
... | ee3980e67d683b2038208780fc8920c4978e8c7e | 3,634,922 |
def prepare_m2m_data(model, ctx_dict, fields, parent_ids):
"""
Recebe os argumentos e devolve um dicionário com os dados necessários para montar a lista
"""
#print('in_prepare_m2m_data')
name = ctx_dict.get('name')
record = ctx_dict.get('record')
edit_ok = ctx_dict.get('edit_ok')
popup =... | 87ec8e992e63ecf53a3e0c878d1254d70c957d11 | 3,634,923 |
def empty_when_none(_string=None):
"""If _string if None, return an empty string, otherwise return string.
"""
if _string is None:
return ""
else:
return str(_string) | 402186ee7b4ba9c3968f81bee23134067d0f260e | 3,634,924 |
def visualizeFrame(x, y, z, translation, size = 0.1):
""" Input: x - numpy array (x, y, z) or column vector
y - numpy array (x, y, z) or column vector
z - numpy array (x, y, z) or column vector
translation - numpy array (x, y, z) or column vector
... | 2ad8aaf1e16488d4b87d155c5115185a42f68fee | 3,634,925 |
def baseline_dwt(
array,
max_iter,
level=None,
wavelet="sym6",
background_regions=None,
mask=None,
mode="constant",
axis=-1,
):
"""
Iterative method of baseline determination, based on the discrete wavelet transform.
Parameters
----------
array : `~numpy.ndarray`
Data with ba... | 41edf5cc884592ee8c480881702fd02206cd55bd | 3,634,926 |
def get_ego_polygon(ego_state: StateSE2, vehicle: VehicleParameters) -> Polygon:
"""
Return Shapely polygon correspoding to Ego
:param ego_state: x, y (center of rear axle) and heading
:param vehicle: Parameters of the vehicle
:return: Shapely polygon for ego
"""
ego_rectangle = construct_eg... | eb9d3cee0a6c27fe76bbc5525c06c9e094584850 | 3,634,927 |
import hashlib
def file_hashes(f, bufsize=16000000):
"""
computes md5, sha1, sha256 from a file obj. intended for large files.
returns 3-tuple of hexstrings
"""
md5 = hashlib.md5()
sha1 = hashlib.sha1()
sha256 = hashlib.sha256()
while True:
buf = f.read(bufsize)
if len(buf) == 0:
break
... | 4e23a0d99cda07325ba3a14675bfb515c12d2950 | 3,634,928 |
def paginate_update(update):
"""
attempts to get next and previous on updates
"""
time = update.pub_time
event = update.event
try:
next = Update.objects.filter(event=event, pub_time__gt=time).order_by('pub_time').only('title')[0]
except:
next = None
try:
previous... | eda885cfdb538f6e609c097d146c3803b17fb1f8 | 3,634,929 |
def get_timestep(all_params, stuff_for_time_loop):
"""
Gets the full VFP + logging timestep
:param all_params: (dictionary) contains input parameters for simulation
:param stuff_for_time_loop: (dictionary) contains derived parameters for simulation
:return: a function with the above values initializ... | 0ca048c07b9fe230469c7e16e0a847b9b155fc50 | 3,634,930 |
from typing import Any
def _create_entities(
device: hm_device.HmDevice,
device_address: str,
custom_entity_class: type,
device_enum: EntityDefinition,
device_def: dict[str, Any],
entity_def: dict[int, set[str]],
channel_no: int | None = None,
) -> list[hm_entity.BaseEntity]:
"""Create... | d4726593e2e2db6fdfb27e5f619b634aa1aa3ec0 | 3,634,931 |
def TDF_ComparisonTool_SourceUnbound(*args):
"""
* Finds from <aRefDataSet> all the keys not bound into <aRelocationTable> and put them into <aDiffDataSet>. Returns True if the difference contains at least one key. (A key is a source object). <anOption> may take the following values: 1 : labels treatment only; 2... | 4f1ad0bbb33ff34f5bbdac37a43bf8ab8c1bd6bd | 3,634,932 |
def sorted_qubits(qbs: Qubits) -> Qubits:
"""Return a sorted list of unique qubits in canonical order.
Qubits can be of different types, so we sort first by type (as a string),
then within types.
"""
return tuple(sorted(list(set(qbs)), key=lambda x: (str(type(x)), x))) | fcff2d13d22875118348566ce6432834c31ba644 | 3,634,933 |
def lu(a: np.ndarray,
permute_l: bool = False,
overwrite_a: bool = False,
check_finite: bool = True,
is_lapack_piv: bool = True):
"""
Compute pivoted LU decomposition of a matrix.
"""
if overwrite_a:
pivot, LU = _lu_internal(a,
permut... | c417a0ec96c92f6662f2dac78b9369ca7feb18f0 | 3,634,934 |
def compute_referendum_result_by_regions(referendum_and_areas):
"""Return a table with the absolute count for each region.
The return DataFrame should be indexed by `code_reg` and have columns:
['name_reg', 'Registered', 'Abstentions', 'Null', 'Choice A', 'Choice B']
"""
tempdf = referendum_and_are... | afd55a1c514c59cdac2a507b9f90eb382f2845ee | 3,634,935 |
import logging
import os
import shutil
def get_nvsmi_win():
"""Function that probes the nvsmi in windows
:return: the path of nvsmi or `None`
"""
logging.info("Detected System: Windows")
nvsmi_exe = nvsmi + ".exe"
for p in WIN_PATHS:
loc_path = os.path.join(p, nvsmi_exe)
if sh... | 7d230e9a3f0b52dfa79c6bda4c447db7ab212bcf | 3,634,936 |
from typing import List
import json
def get_edfi_payloads(context, dbt_run_result, table_reference: str) -> List:
"""
Extract BigQUery table and return the
resulting JSON as a dict.
"""
df = context.resources.warehouse.download_table(table_reference)
df_json = df.to_json(orient="records", dat... | c2ad0026ad4e56a256a824a4c1fae0762aaa51b7 | 3,634,937 |
from typing import List
def deinterleaver(pseudo_rand_array: List[int], array: np.ndarray) -> np.ndarray:
"""Random permutations for deinterleaving an array according to a pseudo random sequence"""
dims = array.shape
flat_array = array.flatten()
matrix = np.zeros(array.size, int)
for index, positi... | 8fc1a59921875de3e647f09ba93f6d645d2829c8 | 3,634,938 |
def add_rnn_encoder_arguments(group):
"""Define arguments for RNN encoder."""
group.add_argument(
"--elayers",
default=4,
type=int,
help="Number of encoder layers (for shared recognition part "
"in multi-speaker asr mode)",
)
group.add_argument(
"--eunits"... | 64a65bd496402dedfe98c4bd0d5bbc516c87a398 | 3,634,939 |
def sum_sample(attrfx='merge'):
"""Returns a mapper that computes the sum sample of a dataset.
Parameters
----------
attrfx : 'merge' or callable, optional
Callable that is used to determine the sample attributes of the computed
sum samples. By default this will be a string representation o... | 3a86b1bd169d75a573261313181bb5ca75df3c89 | 3,634,940 |
def match_profile_to_preset(profile_lookup, colour_preset_lookup):
"""Get a list of preset names that match the current profile colour scheme.
"""
match_list = []
for preset_name, preset_colours in colour_preset_lookup.iteritems():
match = True
for colour_name, colour_val in preset_colo... | 7ac13ee2d29970f284269c6ca0e32ed6de27e8f7 | 3,634,941 |
import json
def jsonpify( data, callback ):
"""
Helper to support JSONP
"""
try:
output = json.dumps( data, sort_keys=True, indent=2 )
if callback:
output = '%s(%s)' % ( callback, output )
return output
except Exception as e:
message = 'exception jsonify... | 6b41ca031b45f835aa57bc08e738dbd6c68d59c5 | 3,634,942 |
def localize_gaspari_cohn(dist,c):
"""
Gaspari-Cohn correlation function
Arguments:
- z: Points to be evaluated
- c: Cutoff value
"""
# Initialize localization array
localization=np.zeros(dist.shape)
# Mask for mid-distance points
mid_mask=(dist<=2*c)
# c for mid-dist... | a817962324e53beb411c4f05cd263a6970dda873 | 3,634,943 |
def download_spectra(table, data_dir, save_raw=True, raw_dir=None):
"""
Downloads SDSS spectra
Parameters
----------
table : AstroPy.Table
Table with coordinates
data_dir : str
Specifies directory where the data is saved
save_raw : bool
Specifies whether the raw spec... | ef4cfc10f84fc3489ed5e129fa7e642bfd52e779 | 3,634,944 |
def serialize_gs_channel(gs_channel, exclude_fields=None):
"""JSON serializer
Serializes the given groundstation channel.
:param gs_channel: The Ground Station channel object to be serialized
:param exclude_fields: List of fields to be excluded from the object
:return: JSON serialization
"""
... | a57dc6b67939e23b853f60e847ed9a4aac27338d | 3,634,945 |
def get_is_valid_node_name(name):
"""get_is_valid_node_name(std::string name) -> bool"""
return _RMF.get_is_valid_node_name(name) | 0dda27e75692c876888b3c72135664d82dccbbdf | 3,634,946 |
def split_multi_expr_clause(s):
"""
Transforms "abc, (123 + 1) * 2, f(a,b)"
into ["abc", "(123 + 1) * 2", "f(a,b)"]
"""
sin = list(s)
sep = [-1]
rb = 0 # ()
cb = 0 # {}
sb = 0 # []
for i in range(len(sin)):
c = sin[i]
if c == "(":
rb = rb + 1
... | d0adb1334715afa63f7ad453492ab2ef524046c0 | 3,634,947 |
import os
import torch
import pickle
def load(experiment: Experiment, key: str) -> list:
"""Load kwarg from experiments.
Parameters
----------
experiment: Experiment.
Experiment meata-data.
key: str.
Key to load.
Returns
-------
data: list of data.
"""
save_... | add72e7ecdaf59bda8a7f1c4aaa1b399b48c0a92 | 3,634,948 |
def setRCmatrix(m, p):
"""Random generate matrix ids to set zeros.
Parameters
----------
m : integer
Number of rows/columns of square matrix
p : float (0. < p < 1.0)
percent of entries in matrix that set to zero.
Returns
-------
rowsZeros, columnsZeros : Tuple
Rows and columns id of matrix
that w... | aa56003f7b916cd9fcffb3db71c0bcc4cf6f8f55 | 3,634,949 |
def sections(parsed):
"""Calculates number of every type of section"""
num_small_sections = 0
num_medium_sections = 0
num_big_sections = 0
for fence in parsed.fences:
if not fence.isRemoval:
num_big_sections += (fence.length/12) // 8
if (fence.length/12) % 8 < 6 and (... | 67bf9328af627234d7dd2fc4bf6dfb11911f9985 | 3,634,950 |
def idn(sp):
""" Identity channel sp -> sp on space sp; it does nothing """
return Channel(np.eye(_prod(sp.shape)), sp, sp) | d74c6a413e89604dae70244d746018c0ebf749c8 | 3,634,951 |
def permutation_test(x1, x2, times=1000, sides=2, metrics="mean", seed=None):
"""
Permutation test: whether group x1 has equal [mean|median] as group x2
Parameters
----------
x1: array or list of int/float
samples for variable x1
x2: array or list of int/float
samples for variab... | 2faada99276d65bbf92beabd7ef54fa475731efd | 3,634,952 |
from pathlib import Path
def build_tourism(image_set, args):
"""
image_set: whether to return train, val or test dataset
"""
all_imagepaths = sorted(Path(args.image_folder).glob("*.jpg"))
all_poses = np.load(args.c2w_path)
all_kinvs = np.load(args.kinv_path)
all_bounds = np.load(args.bound... | 186568140fb52ddc39d428f0abb748e87470b5af | 3,634,953 |
def find_package(app_name, version, revision):
"""Check for a specific package version"""
# NOTE: Originally this method also used 'pkg_type' (the 'builder'
# column in the 'packages' table) to filter; this may need to be
# re-added at some point.
pkg_def = find_package_definition(app_name)
i... | 1d0865aa055640d541a4ce6cdcb78fa66a30785f | 3,634,954 |
from typing import List
def _group_by_internal_name(ports: List[WrapperPort]):
"""Group ports by their 'internal_name' attribute
return a list of (internal_name, group) where group is a list of ports
"""
ports.sort(key=lambda x: x.internal_name)
instances = [(name, list(group)) for name, group
... | 112929ccaac00d6b6fdb6ae912c3ad37ed2d8470 | 3,634,955 |
def homography_warp(patch, dst_H_src, dsize, points=None,
padding_mode='zeros'):
"""
.. note:: Functional API for :class:`torgeometry.HomographyWarper`
Warps patches by homographies.
Args:
patch (Tensor): The image or tensor to warp. Should be from source.
dst_homo_... | 2a984b0900ecba6e0754312d59e371e4dafc3b67 | 3,634,956 |
def html2text(value):
"""
Uses html2text to convert HTML to text...
"""
return _html2text.html2text(value) | 94d630eafc5433c702805e4dcdf189b6cbe8e318 | 3,634,957 |
def column_metadata(column, table_proxy, table_schema, chunks, exemplar_row=0):
"""
Infers column metadata for the purposes of creating dask arrays
that reference their contents.
Parameters
----------
column : string
Table column
table_proxy : string
CASA Table path
tabl... | bdee9efff59b404f5da37500b494b561b93552bb | 3,634,958 |
from datetime import datetime
import pytz
def generate_setup():
"""Used to initially populate the database with sample data"""
user1 = User(username="user", password=pbkdf2_sha256.hash("pass"))
user2 = User(username="user2", password=pbkdf2_sha256.hash("pass"))
user3 = User(username="user3", password=... | 5b8e5b405fde7c00e14a9f39a028b9cf59bdb036 | 3,634,959 |
def GPS_VO_Merge_plot(T_v_dict, utm_dict):
""" Plot the VO and GPS trajectories.
The GPS trajectory is rotated and translated to the origin
in order to obtain a visual comparison between both trajectories."""
k = T_v_dict.keys() + utm_dict.keys()
k = [i for i in unique_everseen([i for i in k... | 5ee5425745219255d76c01aeb4a09384ac001642 | 3,634,960 |
import json
def serialize_payload(payload):
"""Serialize a payload to a JSON string."""
return json.dumps(payload, default=_pack) | 8b9392259532cb2e18bec201d9f4258a08ee26e7 | 3,634,961 |
def get_app_users(appname):
"""List users who has permissions to the specified app
.. todo::
* write tests for this API
* add example response
"""
app = _get_app(appname)
return app.list_users() | 4fbaed9e19086a0c354fd9e1a660e39975ca4c61 | 3,634,962 |
def is_power(num, return_decomposition=False):
"""
Check if num is a perfect power in O(n^3) time, n=ceil(logN)
"""
b = 2
while (2 ** b) <= num:
a = 1
c = num
while (c - a) >= 2:
m = int((a + c) / 2)
if (m ** b) < (num + 1):
p = int(m ... | f12a3d5559e68eb72d8a920ee1e3fdfb9c813d3f | 3,634,963 |
import ray
from ray import tune
from datetime import datetime
import pytz
def train_rllib(submodule, flags):
"""Train policies using the PPO algorithm in RLlib."""
class Args:
def __init__(self):
self.horizon = 400
self.algo = 'PPO'
self.randomize_vehicles = Tr... | 7fce6f77d2a31b372be64c576f48dd9fb5e3430a | 3,634,964 |
import re
def validate_bucket_name(bucket_name):
"""
Validate bucket name
Bucket name must be compatible with DNS name (RFC 1123):
- Less than 63 characters
- Valid character set [a-z0-9-]
- Can not begin and end with "-"
Returns Trues if valid, False otherwise
"""
if len(... | 1d759408d097143b93b0af172bf8e73fe02e283a | 3,634,965 |
def format_gro_box(box):
""" Print a line corresponding to the box vector in accordance with .gro file format
@param[in] box Box NamedTuple
"""
if box.alpha == 90.0 and box.beta == 90.0 and box.gamma == 90.0:
return ' '.join(["% 13.9f" % (i/10) for i in [box.a, box.b, box.c]])
else:
... | 61fd32e7bc9eb9a81b8276afd3e35eb1b32150a5 | 3,634,966 |
def bot_has_permissions(**perms: bool) -> AC:
"""Similar to :func:`.has_permissions` except checks if the bot itself has
the permissions listed.
This check raises a special exception, :exc:`.ApplicationBotMissingPermissions`
that is inherited from :exc:`.ApplicationCheckFailure`.
If this check is ... | 8cc393bc5599f6234ea2cad3d316f09b1f725cb9 | 3,634,967 |
def get_ilsvrc_xception_trainner(config_file_path='./config/ilsvrc_2012_xception.yaml'):
"""
:param config_file_path:
:return:
"""
cfg = config_utils.get_config(config_file_path=config_file_path)
return base_trainner.BaseClsTrainner(cfg=cfg) | f12e83c5bf8e9a82d126ab01c0c4a15f95d6f295 | 3,634,968 |
def get_bpag(model: pd.DataFrame) -> tuple:
"""Calculate test statistics for heteroscedasticity
Parameters
----------
model : OLS Model
Model containing residual values.
Returns
-------
Test results from the Breusch-Pagan Test
"""
lm_stat, p_value, f_stat, fp_value = het_b... | c371d663365e9b18b383e86bd4502a81a063438b | 3,634,969 |
def name2link(name: str):
"""Used for hyperlink anchors"""
if not isinstance(name, str):
name = str(name)
return "-".join([s.lower() for s in name.split(" ")]) | 357496a291dcb16a86f830551350ff77ca9de81c | 3,634,970 |
def window_rolling(origin_data, window_size):
"""Rolling data over 0-dim.
:param origin_data: ndarray of [n_records, ...]
:param window_size: window_size
:return: [n_records - window_size + 1, window_size, ...]
"""
n_records = len(origin_data)
if n_records < window_size:
return None
... | e5a8e30272098ea01ce939d21b245e7fc4a21018 | 3,634,971 |
def get_neighbors(grid, structure_num, proximity):
""" Given a grid of structures, returns the closest proximity neighbors to the given structure
params:
- Grid: 2D numpy array
- structure_num: int
- proximity: int
:returns
- A list of neighboring structures to the ... | 4f62fb8f01beaeea32b8ae0b496e4e972e4cc74b | 3,634,972 |
import re
def vgg19_bn(pretrained=False, **kwargs):
"""VGG 19-layer model (configuration 'E') with batch normalization
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['E'], batc... | 17427df13b43f456bfb7cce1d4e2be94c2673b85 | 3,634,973 |
def init_ss_model() -> SentenceTransformer:
"""Load RoBERTa-base model."""
return SentenceTransformer(
"usc-isi/sbert-roberta-large-anli-mnli-snli", cache_folder=str(PRETRAINED_MODEL_DIR)
) | 1cbc11b0def3a81edbd06d8297964f9360713243 | 3,634,974 |
def flatten_dic(dic):
"""
Flatten dictionnary with nested keys into a single level : usable in a dataframe
Args:
dic -- a dictionnary
Returns:
out -- the flatenned dictionnary (df(out) is a Series)
"""
out = {}
def flatten(x, name=""):
"""
Rec... | 60f7caa27a2cf909ad426336bda06fcd2da127f6 | 3,634,975 |
def policy_eval(policy, env, discount_factor=1.0, epsilon=0.00001):
"""
Evaluate a policy given an environment and a full description of the environment's dynamics.
Args:
policy: [S, A] shaped matrix representing the policy.
env: OpenAI env. env.P represents the transition probabilities... | ce36895abdb0e176f8f3af9b3a72501479cbec3a | 3,634,976 |
def split_data_target(element, device, logger=None):
"""Split elements in dataloader according to pre-defined rules."""
if not (isinstance(element, list) or isinstance(element, tuple)):
msg = (
"Invalid dataloader, please check if the input dataloder is valid."
)
if logger:
... | 2aa0a5c4d80aae2dc237ba9f87c11a7fc7e206fd | 3,634,977 |
from typing import List
def get_dataset_access_list(dataset: str, access_type: str) -> List[str]:
"""Get the comma-separated list of members of a dataset's {access_type} group."""
deploy_config = get_deploy_config()
membership_key = f"{dataset}-{access_type}-members-cache"
group_membership = deploy_co... | 3081952eedff20393dca3e56290cbb65cdd8230a | 3,634,978 |
from typing import List
def deploy_whitelist_to_constraints(
deploy_whitelist: DeployWhitelist,
) -> List[Constraint]:
"""Converts a whitelist of locations into marathon appropriate constraints
https://mesosphere.github.io/marathon/docs/constraints.html#like-operator
:param deploy_whitelist: List of... | f20bd167b938ada0e4cee0c613c07f3d59c72063 | 3,634,979 |
def coerce_types(T1, T2):
"""Coerce types T1 and T2 to a common type.
Coercion is performed according to this table, where "N/A" means
that a TypeError exception is raised.
+----------+-----------+-----------+-----------+----------+
| | int | Fraction | Decimal | float |
+... | 7d412df0182ca6e1f43bfc6ce8e7c6ce1a738bed | 3,634,980 |
def read_vecstim_protocol(protocol_name, protocol_definition, recordings, syn_locs):
"""Read Vecstim protocol from definitions.
Args:
protocol_name (str): name of the protocol
protocol_definition (dict): dict containing the protocol data
recordings (bluepyopt.ephys.recordings.CompRecord... | 05f23ac1e3c903796799cb088f83b9f0194d30ed | 3,634,981 |
from typing import Tuple
def get_pair_elements(pair: str) -> Tuple[str, str, str]:
"""
Get a currency pair's base, quote, and trade base pair.
Eg. If the global trade base is 'USDT' and the pair is 'BTC-ETH', returns ('BTC', 'ETH', 'USDT-BTC').
Arguments:
pair: The currency pair eg. 'BTC-E... | abc838c50aaadd93d56b5bd3717aafaca4158ef2 | 3,634,982 |
from . import extensions
from . import modules
def create_app(**kwargs):
"""
Entry point to the Flask RESTful Server application.
"""
# Initialize the Flas-App
app: Flask = Flask(__name__, **kwargs)
# Load the config file
app.config.from_object('config.DevelopmentConfig')
# Initiali... | 790c82eed799ebe8347e4cb6d9732604a22cd817 | 3,634,983 |
import os
def GetCoastalDpaZones(kml_path=None):
"""Gets Coastal DPA zones.
Coastal DPA zones are Dynamic Protection Area monitored through the use of
ESC sensors.
Args:
kml_path: Optional path to the Coastal DPA KML. If unspecified, use the
default one from the `data/ntia/` folder.
Returns:
... | de27b33fae6f5ae259896023b41e43022606995c | 3,634,984 |
def dy4(vector, g, m1, m2, L1, L2):
"""
Abbreviations
M = m0 + m1
S = sin(y1 - y2)
C = cos(y1 - y2)
s1 = sin(y1)
s2 = sin(y2)
Equation
y4' = g*M*[s2 - s1*C] - S*[M * L1 * y3^2 + C * m2 * L2 * y4^2]
-------------------------------------------------------------
... | 680b253ced9c1faafb357eef83450d262391c885 | 3,634,985 |
from typing import OrderedDict
def sort_dict(od, d):
"""Sort parameters (same order as xsd:sequence)"""
if isinstance(od, dict):
ret = OrderedDict()
for k in od.keys():
v = d.get(k)
# don't append null tags!
if v is not None:
if isinstance(v,... | 6211a98d30e29ac9b5d0dcaeeec3ef76e9c95713 | 3,634,986 |
from matplotlib.colors import LinearSegmentedColormap
def _center_cmap(cmap, vmin, vmax, name="cmap_centered"):
"""
Center given colormap (ranging from vmin to vmax) at value 0.
Taken from MNE-Python v0.24, as it will be removed in MNE-Python v1.0.
Parameters
----------
cmap : matplotlib.col... | de13fb933e16d3179f6b02be9c02862f353464b1 | 3,634,987 |
def port_number(worker_id):
"""A fixture that returns a different port for each parallel worker."""
i = 0
if worker_id != "master":
i = int("".join([c for c in worker_id if c.isdigit()]))
return PORTS[i] | 8bf4e5936d5e2f83a0ca2bf973dfd24d0af1f950 | 3,634,988 |
def get_loss_f(**kwargs_parse):
"""Return the loss function given the argparse arguments."""
return Loss(lamlSum=kwargs_parse["lamlSum"],
lamhSum=kwargs_parse["lamhSum"],
lamL2norm=kwargs_parse["lamL2norm"],
lamCMF=kwargs_parse["lamCMF"],
lamConv=k... | 03db5b8934ae9263bf3f0668f97d77c124bf58fb | 3,634,989 |
def assert_greater_equal_v2(x, y, message=None, summarize=None, name=None):
"""Assert the condition `x >= y` holds element-wise.
This Op checks that `x[i] >= y[i]` holds for every pair of (possibly
broadcast) elements of `x` and `y`. If both `x` and `y` are empty, this is
trivially satisfied.
If `x` is not ... | bc0ef67602cd0be4e6868971f821eacd48f5fb72 | 3,634,990 |
import itertools
def pad_ends(
sequence, pad_left=True, left_pad_symbol="<s>", right_pad_symbol="</s>"
):
"""
Pad sentence ends with start- and end-of-sentence tokens
In speech recognition, it is important to predict the end of sentence
and use the start of sentence to condition predictions. Typi... | e4a341d1e777adab36ec0c0e7996e23203c53478 | 3,634,991 |
def client():
""" Create a client with authentication settings. """
cfg = get_config()
url = f"ldap://{cfg['SERVER']['hostname']}:{cfg['SERVER']['port']}"
client = LDAPClient(url)
client.set_credentials(
"SIMPLE", user=cfg["SIMPLEAUTH"]["user"], password=cfg["SIMPLEAUTH"]["password"]
)
... | 911f56339f1b995d9addf0466f01dd6f6bf6ff4e | 3,634,992 |
def _check_and_fire_deploy(job):
"""
Validates pre-conditions for deploy (hook status returned successfully)
and triggers deploy for enabled deployers.
:param job: Dictionary containing job parameters
:return: job or AsyncResult
"""
# Check and fires deploy
job_id = job['meta-info']['jo... | cc38e88c8e2e43878eb9ce4bfe722c0018931320 | 3,634,993 |
def mark_errors_flipping(events):
"""
Marks error fractions
"""
single_errors = np.zeros(len(events) - 1)
double_errors = np.zeros(len(events) - 2)
for i in range(len(events) - 1):
# A single error is associated with a qubit error
if events[i] == events[i + 1]:
singl... | 14e71e1e6947bca4382fd22c0ae714e359174476 | 3,634,994 |
import numpy
def split_with_minimum_rt_distance(rts, min_rt_delta=0, random_state=None):
"""
Sample from a set ot retention times, so that the sampled rts have a
minimum rt differences.
:param rts:
:param min_rt_delta:
:param random_state:
:return:
"""
# if min_rt_delta == 0:
... | 026adc9b8dc7f3be513a93275fb0ef0d4b7de615 | 3,634,995 |
from django.apps import apps
def create_proxy_model(name, model_mixins, base_model, attrs=None, module=None):
"""
Create a Django Proxy Model on the fly, to be used by any Cascade Plugin.
"""
class Meta:
proxy = True
app_label = 'cmsplugin_cascade'
name = str(name + 'Model')
... | ff0b8216ff83ced0cd46da1adc237614fc9e6d85 | 3,634,996 |
from django.apps import apps
def get_embed_video_model():
"""
Get the embed video model from the ``WAGTAILEMBEDVIDEOS_EMBEDVIDEO_MODEL`` setting.
Useful for developers making Wagtail plugins that need the embed video model.
Defaults to the standard :class:`~wagtail_embed_videos.models.EmbedVideo` mode... | d691a0d14f209297338c2eb3e9542c5d5c5a9d61 | 3,634,997 |
def get_filetypes(key='type'):
"""Gets the list of possible filetypes from the filetype table
Parameters
----------
key : {'type', 'filetype_id'}, optional
Defaults to "type". Determines the format of the returned dict.
Returns
-------
dict
If `key` is "type", dict is of th... | 0915680135b9460be44bbf3d127ca248637ff96b | 3,634,998 |
def make_dataloader(folder_names, data_path, batch_size, task, isTrain = False):
"""This function takes in a list of folders with images in them,
the root directory of these images, and a batchsize and turns them into a dataloader"""
# added flag isTrain - only augment/transform training set, not validation... | 1e73d30481aeca43f81a656799377fe5852e9e67 | 3,634,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.