content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import scipy
def lqr_ofb_cost(K, R, Q, X, ss_o):
# type: (np.array, np.array, np.array, np.array, control.ss) -> np.array
"""
Cost for LQR output feedback optimization.
@K gain matrix
@Q process noise covariance matrix
@X initial state covariance matrix
@ss_o open loop state space system
... | b0a22685c640c2970dad63628d1c87aac73b241a | 3,642,722 |
def steadystate_floquet(H_0, c_ops, Op_t, w_d=1.0, n_it=3, sparse=False):
"""
Calculates the effective steady state for a driven
system with a time-dependent cosinusoidal term:
.. math::
\\mathcal{\\hat{H}}(t) = \\hat{H}_0 +
\\mathcal{\\hat{O}} \\cos(\\omega_d t)
Parameters
... | 8e59e8f138116877678d7d203d4767c6fc6bd1fa | 3,642,723 |
def gsl_blas_dtrmm(*args, **kwargs):
"""
gsl_blas_dtrmm(CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag, double alpha,
gsl_matrix A, gsl_matrix B) -> int
"""
return _gslwrap.gsl_blas_dtrmm(*args, **kwargs) | 5efee7571f49afc20c3f33d010caccb199613315 | 3,642,724 |
def scale(value, upper, lower, min_, max_):
"""Scales value between upper and lower values, depending on the given
minimun and maximum value.
"""
numerator = ((lower - upper) * float((value - min_)))
denominator = float((max_ - min_))
return numerator / denominator + upper | 3e13c80b765cffb1e75a6856d343bd9a88c353e9 | 3,642,725 |
def conditional_response(view, video=None, **kwargs):
"""
Redirect to login page if user is anonymous and video is private.
Raise a permission denied error if user is logged in but doesn't have permission.
Otherwise, return standard template response.
Args:
view(TemplateView): a video-speci... | ea8e8176a979fcd46c0c72d5201c6f85c7b4ed48 | 3,642,726 |
def Flatten(nmap_list):
"""Flattens every `.NestedMap` in nmap_list and concatenate them."""
ret = []
for x in nmap_list:
ret += x.Flatten()
return ret | c630869b725d69338830e1a14ef920d6d1e87ade | 3,642,727 |
from re import T
def get_data_schema() -> T.StructType:
"""
Return the kafka data schema
"""
return T.StructType(
[T.StructField('key', T.StringType()),
T.StructField('message', T.StringType())]
) | 0cbc2fc6e7015c458e70b8d0ec6efb5fbc0d84f5 | 3,642,728 |
from typing import List
import random
def build_graph(num: int = 0) -> (int, List[int]):
"""Build a graph of num nodes."""
if num < 3:
raise app.UsageError('Must request graph of at least 3 nodes.')
weight = 5.0
nodes = [(0, 1, 1.0), (1, 2, 2.0), (0, 2, 3.0)]
for i in range(num-3):
... | 05efb60ae5cdcc561c93cf2faba172ca5a3ff0d7 | 3,642,729 |
from typing import List
from typing import Collection
def concatenate(boxes_list:List[Boxes], fields:Collection[str]=None) -> Boxes:
"""Merge multiple boxes to a single instance
B = A[:10]
C = A[10:]
D = concatenate([A, B])
D should be equal to A
"""
if not boxes_list:
if fields is... | 096067aea3d01e984befd2cadfce5a86c33580e9 | 3,642,730 |
def detect_peaks(array, freq=0, cthr=0.2, unprocessed_array=False, fs=44100):
"""
Function detects the peaks in array, based from the mirpeaks algorithm.
:param array: Array in which to detect peaks
:param freq: Scale representing the x axis (sample length as array)
:p... | c11a09624085d505d36a9e374954dd6ba5c1e05a | 3,642,731 |
def left_index_iter(shape):
"""Iterator for the left boundary indices of a structured grid."""
return range(0, shape[0] * shape[1], shape[1]) | c7da6f5de48d0446cb0729593d3dc0eb95f5ab9a | 3,642,732 |
import logging
def calculate_precision_recall(df_merged):
"""Calculates precision and recall arrays going through df_merged row-wise."""
all_positives = get_all_positives(df_merged)
# Populates each row with 1 if this row is a true positive
# (at its score level).
df_merged["is_tp"] = np.where(
... | 80d2c82c99e0bbbab8460ff997fc1358f758f2f6 | 3,642,733 |
def combine(shards, judo_file):
"""combine
this class is passed the
"""
# Recombine the shards to create the kek
combined_shares = Shamir.combine(shards)
combined_shares_string = "{}".format(combined_shares)
# decrypt the dek uysing the recombined kek
decrypted_dek = decrypt(
j... | 3ba88307c3d0cb0a43473e89b731c61e9bbfe83d | 3,642,734 |
def shiftRightUnsigned(e, numBits):
"""
:rtype: Column
>>> from pysparkling import Context
>>> from pysparkling.sql.session import SparkSession
>>> from pysparkling.sql.functions import shiftLeft, shiftRight, shiftRightUnsigned
>>> spark = SparkSession(Context())
>>> df = spark.range(-5, 4)... | 4f528609bb72a44a99581bca997fbde2f19af861 | 3,642,735 |
def change_wallpaper_job(profile, force=False):
"""Centralized wallpaper method that calls setter algorithm based on input prof settings.
When force, skip the profile name check
"""
with G_WALLPAPER_CHANGE_LOCK:
if profile.spanmode.startswith("single") and profile.ppimode is False:
t... | b4013e847cae337f83af5f3282d5551a52b4a7b3 | 3,642,736 |
def sheets_from_excel(xlspath):
"""
Reads in an xls(x) file,
returns an array of arrays, like:
Xijk, i = sheet, j = row, k = column
(but it's not a np ndarray, just nested arrays)
"""
wb = xlrd.open_workbook(xlspath)
n_sheets = wb.nsheets
sheet_data = []
for sn in xrange(n_sheets... | 11099d2929ef0078ae0e5b07a700bdb2021eaa56 | 3,642,738 |
import numpy
import logging
def fitStatmechPseudoRotors(Tlist, Cvlist, Nvib, Nrot, molecule=None):
"""
Fit `Nvib` harmonic oscillator and `Nrot` hindered internal rotor modes to
the provided dimensionless heat capacities `Cvlist` at temperatures `Tlist`
in K. This method assumes that there are enough ... | eb110aab6a5ed35bd2ec1bdb2ca262524fe44dcf | 3,642,739 |
def add_numbers(a, b):
"""Sums the given numbers.
:param int a: The first number.
:param int b: The second number.
:return: The sum of the given numbers.
>>> add_numbers(1, 2)
3
>>> add_numbers(50, -8)
42
"""
return a + b | 7d9a0c26618a2aee5a8bbff6a65e315c33594fde | 3,642,740 |
def get_version(table_name):
"""Get the most recent version number held in a given table."""
db = get_db()
cur = db.cursor()
cur.execute("select * from {} order by entered_on desc".format(table_name))
return cur.fetchone()["version"] | 7bc55bacf7aa84ccc9ba6f6bb51bbc51c1556395 | 3,642,741 |
def area(a, indices=(0, 1, 2, 3)):
"""
:param a:
:param indices:
:return:
"""
x0, y0, x1, y1 = indices
return (a[..., x1] - a[..., x0]) * (a[..., y1] - a[..., y0]) | 17df4d4f4ad818be0b2ed7a1fe65aaeccbe63638 | 3,642,742 |
def infer_tf_dtypes(image_array):
"""
Choosing a suitable tf dtype based on the dtype of input numpy array.
"""
return dtype_casting(
image_array.dtype[0], image_array.interp_order[0], as_tf=True) | fd8fc353fd6a76a1dae2a693a9121415393b8d50 | 3,642,744 |
def get_cifar10_datasets(n_devices, batch_size=256, normalize=False):
"""Get CIFAR-10 dataset splits."""
if batch_size % n_devices:
raise ValueError("Batch size %d isn't divided evenly by n_devices %d" %
(batch_size, n_devices))
train_dataset = tfds.load('cifar10', split='train[:90%]')
... | 50dd1b02792ab13f4b6d42d52e6467503f319bb2 | 3,642,745 |
from disco.worker.pipeline.worker import Worker, Stage
from disco.core import Job, result_iterator
def predict(dataset, fitmodel_url, save_results=True, show=False):
"""
Function starts a job that makes predictions to input data with a given model
Parameters
----------
input - dataset object with... | dbf56e82a3ff81a899cf2c33fa83f8c0f1b73947 | 3,642,746 |
def format_string_to_json(balance_info):
"""
Format string to json.
e.g: '''Working Account|KES|481000.00|481000.00|0.00|0.00'''
=> {'Working Account': {'current_balance': '481000.00',
'available_balance': '481000.00',
'reserved_balance': '0.00',
'uncleared_balance': '0.00'}}
"""
balance_dict = frappe._dic... | 1be0d4d8ad3c5373e18e6f78957e18d8f0c0c846 | 3,642,747 |
from typing import Tuple
from typing import List
def get_relevant_texts(subject: Synset, doc_threshold: float) -> Tuple[List[str], List[int], int, int]:
"""Get all lines from all relevant articles. Also return the number of retrieved documents and retained ones."""
article_dir = get_article_dir(subject)
... | 150dca990fe67ed3fb5381e6d4a6bce8656f2619 | 3,642,748 |
def plot_mae(X, y, model):
"""
Il est aussi pertinent de logger les graphiques sous forme d'artifacts.
"""
fig = plt.figure()
plt.scatter(y, model.predict(X))
plt.xlabel("Durée réelle du trajet")
plt.ylabel("Durée estimée du trajet")
image = fig
fig.savefig("MAE.png")
plt.cl... | 3bc4225f530f7f80ea903d55963cb0a33fe1cb45 | 3,642,749 |
import types
def get_pure_function(method):
"""
Retreive pure function, for a method.
Depends on features specific to CPython
"""
assert(isinstance(method, types.MethodType))
assert(hasattr(method, 'im_func'))
return method.im_func | f0a7f25a38fd9da061f281f5c55453f8e7ae37d0 | 3,642,751 |
def _agg_samples_2d(sample_df: pd.DataFrame) -> pd.DataFrame:
"""Aggregate ENN samples for plotting."""
def pct_95(x):
return np.percentile(x, 95)
def pct_5(x):
return np.percentile(x, 5)
enn_df = (sample_df.groupby(['x0', 'x1'])['y']
.agg([np.mean, np.std, pct_5, pct_95]).reset_index())
e... | d2decff9ae5224ad77ce6f133ac0cf0099dda89f | 3,642,752 |
def get_np_num_array_str(data_frame_rows):
"""
Get a complete code str that creates a np array with random values
"""
test_code = cleandoc("""
from sklearn.preprocessing import StandardScaler
import pandas as pd
from numpy.random import randint
series = randint(0,100,siz... | 66a81bba8666a02770f1de233e458a5067e08f62 | 3,642,753 |
from typing import Any
def get_config(name: str = None, default: Any = _MISSING) -> Any:
"""Gets the global configuration.
Parameters
----------
name : str, optional
The name of the setting to get the value for. If no name is
given then the whole :obj:`Configuration` object is return... | da43dd18c3841489cf6c909acb12a95b34179135 | 3,642,754 |
def domain_domain_distance(ptg1, ptg2, pdb_struct, domain_distance_dict):
"""
Return the distance between two domains, which will be defined as
the distance between their two closest SSEs
(using SSE distnace defined in ptdistmatrix.py)
Parameters:
ptg1 - PTGraph2 object for one domain
... | 6f2f68714717a32da0182db814629ac0e55b59e8 | 3,642,755 |
def pred_error(f_pred, prepare_data, data, iterator, max_len, n_words, filter_h):
""" compute the prediction error.
"""
valid_err = 0
for _, valid_index in iterator:
x = [data[0][t] for t in valid_index]
x = prepare_data(x,max_len,n_words,filter_h... | c8f667a2eb6b9cc67d96ea0b6848f27cd337a2f9 | 3,642,756 |
def standardize_10msample(frac: float=0.01):
"""Runs each data processing function in series to save a new .csv data file.
Intended for Pandas DataFrame. For Dask DataFrames, use standardize_10msample_dask
Args:
frac (float, optional): Fraction of data file rows to sample. Defaults to 0.01.
Re... | d834cc31220a34204966160bb72399a53b99ff5b | 3,642,757 |
def is_ansible_managed(file_path):
"""
Gets whether the fail2ban configuration file at the given path is managed by Ansible.
:param file_path: the file to check if managed by Ansible
:return: whether the file is managed by Ansible
"""
with open(file_path, "r") as file:
return file.readli... | a8e70d242f598ad26a00cf0b3ccc1a1494475ba8 | 3,642,758 |
import ctypes
def sumai(array):
"""
Return the sum of the elements of an integer array.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sumai_c.html
:param array: Input Array.
:type array: Array of ints
:return: The sum of the array.
:rtype: int
"""
n = ctypes.c_int(len(a... | ece9b6a171dff66d4f66c7ce711b6a7a7b4c59a2 | 3,642,759 |
from typing import Union
from typing import Optional
from typing import Mapping
from typing import Any
def invoke(
node: Union[DAG, Task],
params: Optional[Mapping[str, Any]] = None,
) -> Mapping[str, NodeOutput]:
"""
Invoke a node with a series of parameters.
Parameters
----------
node
... | f05a49996912a52db37a809d078faaa208942e7f | 3,642,762 |
def convert_acl_to_iam_policy(acl):
"""Converts the legacy ACL format to an IAM Policy proto."""
owners = acl.get('owners', [])
readers = acl.get('readers', [])
if acl.get('all_users_can_read', False):
readers.append('allUsers')
writers = acl.get('writers', [])
bindings = []
if owners:
bindings.ap... | 990cdb6a51a696cf2b7825af94cf4265b2229be9 | 3,642,763 |
def get_valid_start_end(mask):
"""
Args:
mask (ndarray of bool): invalid mask
Returns:
"""
ns = mask.shape[0]
nt = mask.shape[1]
start_idx = np.full(ns, -1, dtype=np.int32)
end_idx = np.full(ns, -1, dtype=np.int32)
for s in range(ns):
# scan from start to the end
... | 41520c051d25aed203e5db9f64497f75eaab4f6c | 3,642,764 |
def pahrametahrize(*args, **kwargs) -> t.Callable:
"""Pass arguments straight through to `pytest.mark.parametrize`."""
return pytest.mark.parametrize(*args, **kwargs) | 43bbc1e8323956f1ed2e1da60abf23e5b35130ba | 3,642,765 |
from datetime import datetime
def utcnow():
"""Return the current time in UTC with a UTC timezone set."""
return datetime.utcnow().replace(microsecond=0, tzinfo=UTC) | 496c80cfa4a2b00b514346705fc0709739e2d3c0 | 3,642,766 |
def default_to(default, value):
"""
Ramda implementation of default_to
:param default:
:param value:
:return:
"""
return value or default | 58338f67332a0ff116cd2ff46d65ee92bf59c360 | 3,642,767 |
def insertGraph():
"""
Create a new graph
"""
root = Xref.getroot().elem
ref = getNewRef()
elem = etree.Element(etree.QName(root, sgraph), reference=ref)
name = makeNewName(sgraph, elem)
root.append(elem)
Xref.setDirty()
return name, (elem, newDotGraph(name, ref, elem)) | 2a60fac192d6d3448c3e48637585af2d54bdf87f | 3,642,768 |
from datetime import datetime
def get_line_notif(line_data: str):
"""
Извлечь запись из таблицы.
:param line_data: запрашиваемая строка
"""
try:
connection = psycopg2.connect(
user=USER,
password=PASSWORD,
host="127.0.0.1",
port="5432",
... | 8fbeb195faaa1f49928e3d0e49310cc3d4bcb37f | 3,642,769 |
def bouts_per_minute(boutlist):
"""Takes list of times of bouts in seconds, returns bpm = total_bouts / total_time."""
bpm = (total_bouts(boutlist) / total_time(boutlist)) * 60
return bpm | 949f0d8758d7fcc8a1e19d4772788504b5ba10a5 | 3,642,771 |
import re
def convert_to_snake_case(string: str) -> str:
"""Helper function to convert column names into snake case. Takes a string
of any sort and makes conversions to snake case, replacing double-
underscores with single underscores."""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', string)
draft = ... | 2a8de69a6915e87e46582a1af7a7897ff6fd97ce | 3,642,772 |
def list_keys(client, keys):
"""
:param client: string
:param keys: list of candidate keys
:return: True if all keys exist, None otherwise
"""
objects = client.get_multi(keys)
if bool(objects):
return objects
else:
return None | 4370053b76ea526e1f43309112f85f968ce76b6b | 3,642,773 |
def estimate_variance(ip_image: np.ndarray, x: int, y: int, nbr_size: int) -> float:
"""Estimates local variances as described in pg. 6, eqn. 20"""
nbrs = get_neighborhood(x, y, nbr_size, ip_image.shape[0], ip_image.shape[1])
vars = list()
for channel in range(3):
pixel_avg = 0
for i, j ... | 26932d333a50526f5f3bc4b10e5dd2b0bd15e871 | 3,642,775 |
def api_key_regenerate():
"""
Generate a new API key for the currently logged-in user.
"""
try:
return flask.jsonify({
constants.api.RESULT: constants.api.RESULT_SUCCESS,
constants.api.MESSAGE: None,
'api_key': database.user.generate_new_api_key(current_user.u... | 59ccc904dc80386910370dae0752c4810107224c | 3,642,776 |
def almost_equal_ignore_nan(a, b, rtol=None, atol=None):
"""Test that two NumPy arrays are almost equal (ignoring NaN in either array).
Combines a relative and absolute measure of approximate eqality.
If either the relative or absolute check passes, the arrays are considered equal.
Including an absolute... | ca364b23e5a6106a98ba52629ccb152dc0d95214 | 3,642,777 |
def make_commands(manager):
"""Prototype"""
# pylint: disable=no-member
return (cmd_t(manager) for cmd_t in
AbstractTwitterFollowersCommand.__subclasses__()) | 54443970dc69b06c530b746cb42b418bc5a7ee42 | 3,642,778 |
import logging
def copy_rds_snapshot(
target_snapshot_identifier: str,
source_snapshot_identifier: str,
target_kms: str,
wait: bool,
rds,
):
"""Copy snapshot from source_snapshot_identifier to target_snapshot_identifier and encrypt using target_kms"""
logger = logging.getLogger("copy_rds_s... | f7d3c3b9b5588afb9dd1b6e65fc3a51f6411e997 | 3,642,779 |
def get_other_menuitems():
"""
returns other menu items
each menu pk will be dict key
{0: QuerySet, 1: QuerySet, ..}
"""
menuitems = {}
all_objects = Menu.objects.all()
for obj in all_objects:
menuitems[obj.pk] = obj.menuitem_set.all()
return menuitems | 7e868e3d434dd168dfe6d9938093044e97e2bc5c | 3,642,780 |
import random
def create_deck(shuffle=False):
"""Create a new deck of 52 cards"""
deck = [(s, r) for r in RANKS for s in SUITS]
if shuffle:
random.shuffle(deck)
return deck | 92b828ce373c48a0a403c519a2e25b0cb1ab7409 | 3,642,782 |
def mock_gate_util_provider_oldest_namespace_feed_sync(
monkeypatch, mock_distromapping_query
):
"""
Mocks for anchore_engine.services.policy_engine.engine.policy.gate_util_provider.GateUtilProvider.oldest_namespace_feed_sync
"""
# required for FeedOutOfDateTrigger.evaluate
# setup for anchore_e... | c6cf043b49574be44114110f5c1092d06fe531a0 | 3,642,783 |
def ESMP_LocStreamGetBounds(locstream, localDe=0):
"""
Preconditions: An ESMP_LocStream has been created.\n
Postconditions: .\n
Arguments:\n
:RETURN: Numpy.array :: \n
:RETURN: Numpy.array :: \n
ESMP_LocStream :: locstream\n
"""
llde = ct.c_int(localDe)
# lo... | 179b24463cd8dd5f70ad63530a50b6fe4dd4dfb8 | 3,642,784 |
def reverse(collection):
"""
Reverses a collection.
Args:
collection: `dict|list|depset` - The collection to reverse
Returns:
`dict|list|depset` - A new collection of the same type, with items in the reverse order
of the input collec... | 587bf847028f485783e74633b1aa2ed0ef003daa | 3,642,785 |
def A_fast_full5(S, phase_factors, r, r_min, MY, MX):
""" Fastest version, takes precomputed phase factors, assumes S-matrix with beam tilt included
:param S: B x NY x NX
:param phase_factors: K x B
:param r: K x 2
:param out: K x MY x MX
:return: exit ... | 3bffd01037f317c88328a751958aca67bc90b2dd | 3,642,786 |
from pathlib import Path
import requests
import logging
def get_metadata_for_druid(druid, redownload_mods):
"""Obtains a .mods metadata file for the roll specified by DRUID either
from the local mods/ folder or the Stanford Digital Repository, then
parses the XML to build the metadata dictionary for the r... | 982c2a89e85b07692901f1452a62c144ab1181b7 | 3,642,787 |
def logistic_dataset_gen_data(num, w, dim, temp, rng_key):
"""Samples data from a standard Gaussian with binary noisy labels.
Args:
num: An integer denoting the number of data points.
w: An array of size dim x odim, the weight vector used to generate labels.
dim: An integer denoting the number of input... | 99fed2fd2cdb1250a444a986dd182ab846477890 | 3,642,788 |
def sech(x):
"""Computes the hyperbolic secant of the input"""
return 1 / cosh(x) | 1cded1fbf37070dbecba0f8518990c3eef8e6406 | 3,642,789 |
import torch
def _map_triples_elements_to_ids(
triples: LabeledTriples,
entity_to_id: EntityMapping,
relation_to_id: RelationMapping,
) -> MappedTriples:
"""Map entities and relations to pre-defined ids."""
if triples.size == 0:
logger.warning('Provided empty triples to map.')
retu... | 5d4db571e9b9d37329df7689b7e7629559580522 | 3,642,790 |
from typing import Tuple
def pinf_two_networks(grgd: Tuple[float, float],
k: Tuple[float, float] = (3, 3),
alpha_i: Tuple[float, float] = (1, 1),
solpoints: int = 10,
eps: float = 1e-5,
method: str = "hybr"):... | c90db1bb6d9d314086887e4f5b98f422731b3853 | 3,642,791 |
def uncapped_flatprice_goal_reached(chain, uncapped_flatprice, uncapped_flatprice_finalizer, preico_funding_goal, preico_starts_at, customer) -> Contract:
"""A ICO contract where the minimum funding goal has been reached."""
time_travel(chain, preico_starts_at + 1)
wei_value = preico_funding_goal
uncapp... | 20a6a10b4cb1318e2be7fd1995d025b582ee4768 | 3,642,792 |
def depfile_name(request, tmp_path_factory):
"""A fixture for a temporary doit database file(s) that will be removed after running"""
depfile_name = str(tmp_path_factory.mktemp('x', True) / 'testdb')
def remove_depfile():
remove_db(depfile_name)
request.addfinalizer(remove_depfile)
return d... | cbe99e664abeea52a038898f3e76547795bca30a | 3,642,793 |
from typing import OrderedDict
import collections
import warnings
def calculate(dbf, comps, phases, mode=None, output='GM', fake_points=False, broadcast=True, parameters=None, **kwargs):
"""
Sample the property surface of 'output' containing the specified
components and phases. Model parameters are taken ... | c69769fa322831cc021db497a329de816541a20a | 3,642,795 |
def is_negative(value):
"""Checks if `value` is negative.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is negative.
Example:
>>> is_negative(-1)
True
>>> is_negative(0)
False
>>> is_negative(1)
False
.. versi... | ce0183d95a2394db18904f0ca7f1225e43cf671d | 3,642,796 |
import torch
def get_optimizer_noun(lr, decay, mode, cnn_features, role_features):
""" To get the optimizer
mode 0: training from scratch
mode 1: cnn fix, verb fix, role training
mode 2: cnn fix, verb fine tune, role training
mode 3: cnn finetune, verb finetune, role training"""
if mode == 0:
... | 6ac2df23f6a50d3488302cfe2da6189a995c0d85 | 3,642,797 |
def _loc_str_to_pars(loc, x=None, y=None, halign=None, valign=None, pad=_PAD):
"""Convert from a string location specification to the specifying parameters.
If any of the specifying parameters: {x, y, halign, valign}, are 'None', they are set to
default values.
Returns
-------
x : float
y ... | 84094b2eaf39390a1d30fd26d8ae36ecd32a7665 | 3,642,799 |
def skeda_from_skedadict(line_dict, filing_number, line_sequence, is_amended):
"""
We can either pass the header row in or not; if not, look it up.
"""
line_dict['transaction_id'] = line_dict['transaction_id'][:20]
line_dict['line_sequence'] = line_sequence
line_dict['superseded_by_amendment'] =... | 2e07efa96f93ef777185e48bb07787774d4e5180 | 3,642,801 |
from datetime import datetime
def oracle_to_date(string2convert, fmt, nlsparam=None):
"""
https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions183.htm
TO_DATE(char [, fmt [, 'nlsparam' ] ])
TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype to a value of DATE datatyp... | eeaee6289d43bd446fbf27ce25ed87555a116ae4 | 3,642,802 |
import re
def replace_whitespace(s, rep=' '):
"""Replace any length white spaces in the given string with a replacement.
Parameters
----------
s : str
The string in which any length whitespaces should be replaced.
rep : Optional[str]
The string with which all whitespace should be ... | b583a627dda830275822f6276af33b58afb55f1e | 3,642,803 |
import aiohttp
async def handle_xml_response(request):
""" Faking response """
response = load_data("equipment_data.xml")
return aiohttp.web.Response(
content_type="text/xml",
body=response
) | d56526414469424483fc8461c29f3b9c9963e698 | 3,642,805 |
import this
def plugin_prefs(parent, cmdr, is_beta):
"""
Return a TK Frame for adding to the EDMC settings dialog.
"""
global listbox
frame = nb.Frame(parent)
nb.Label(frame, text="Faction Name:").grid(row=0,column=0)
nb.Label(frame, text="System Name").grid(row=0,column=1)
factio... | 25df93343750cdac60604e6f5f91f84b3d105a12 | 3,642,806 |
from typing import Concatenate
def Conv1D_positive_r(x, kernel_size):
"""index of r is hard-coded to 2!"""
out1 = Conv1D(1, kernel_size=kernel_size, padding='valid', activation='linear')(x)
out2 = Conv1D(1, kernel_size=kernel_size, padding='valid', activation='linear')(x)
out3 = Conv1D(1, kernel_size=... | b66db8e65007d6044ad711b4ac9e7e9f967ecd91 | 3,642,807 |
def decrypt(text, key):
"""Decrypt the supplied text and return the result.
Args:
text (str): The text to decrypt.
key (str): The key with which to perform the decryption.
"""
return transform(text, key, True) | bb7fb87622a38c3eba9156d9a8678357e40adcb3 | 3,642,809 |
def psi_gauss_1d(x, a: float = 1.0, x_0: float = 0.0, k_0: float = 0.0):
"""
Gaussian wave packet of width a and momentum k_0, centered at x_0
:param x: mathematical variable
:param a: Amplitude of pulse
:param x_0: Mean spatial x of pulse
:param k_0: Group velocity of pulse
"""
re... | 278ffa7f15fd8c52346f5b232a89d40ee48c8843 | 3,642,810 |
def get(address, limit=LIMIT):
"""
Recursively dereferences an address.
Returns:
A list containing ``address``, followed by up to ``limit`` valid pointers.
"""
result = []
for i in range(limit):
# Don't follow cycles, except to stop at the second occurrence.
if result.co... | 1a3b7122ede440ddee773d7e260430517181909d | 3,642,811 |
def find_availability_by_year(park, campground, year, months=range(1, 13)):
"""
Parameters
----------
park : str
campground : str
year : str
months : list
list of months as str or int. Default is `range(1, 13)`
Returns
-------
list
list of weekend availability... | 28e81b2382f2733d1cc024a221c11feaa5ae5653 | 3,642,814 |
def seconds(value=None, utc=True, **kwargs):
"""
Converts value to seconds. If value is timedelta or struc_time, it will be just converted to seconds.
If value is datetime instance it will be converted to milliseconds since epoch (UTC). If value is number,
it's assumed that it's in milliseconds, so it w... | aced764fc038b316ca0b772254b6c6a44f333d9e | 3,642,815 |
def fix_mocov2_state_dict(state_dict):
"""
Ref: https://bit.ly/3cDfGVA
"""
new_state_dict = {}
for k, v in state_dict.items():
if k.startswith("model.encoder_q."):
k = k.replace("model.encoder_q.", "")
new_state_dict[k] = v
return new_state_dict | 13471d6863eb14eb3248f6d6e1d6b5882c341ed0 | 3,642,816 |
def get_perspective(image, contours, ratio):
"""
This function takes image and contours and returns perspective of this contours.
:param image: image, numpy array
:param contours: contours, numpy array
:param ratio: rescaling parameter to the original image
:return: warped image
"""
poin... | 237db75baa8b72314e095f435075e75b8aa126b0 | 3,642,817 |
from pathlib import Path
def load_model_selector(folder_path):
"""Load information about stored model selection
Parameters
----------
folder_path : str
path where .model_selector_result files are stored
Returns
-------
ModelSelector
Information about model selection for e... | 1e977ca422c5004e510f4989f7778bd0ca95f4c0 | 3,642,819 |
def generate_expired_date():
"""Generate a datetime object NB_DAYS_BEFORE_DELETING_LIVE_RECORDINGS days in the past."""
return timezone.now() - timedelta(
days=settings.NB_DAYS_BEFORE_DELETING_LIVE_RECORDINGS
) | 8d6fb9aae4cd5065416ccea4ba17d11080d8ccbc | 3,642,820 |
from typing import Dict
def make_dummy_authentication_request_args() -> Dict[str, bytes]:
"""Creates a request to emulate a login request.
Returns:
Dict[str, bytes]: Authenticator dictionary
"""
def _make_dummy_authentication_request_args():
args = {
"username": ["foobar"... | 2e0919bac46a5140a72c02ee09c1ce3b1cb9269a | 3,642,821 |
def add_experiment_images_to_image_info_csv(image_info_df, experiment_xml_file):
"""
Goes through the xml file of the experiment and adds the info of its images to the image info dataframe.
If the gene name is missing in the experiment, then this experiment is considered invalid.
:param image_info_df: ... | 99b545cba5aeb53f9ba2af2a1a5bf3acb72c6fa7 | 3,642,822 |
from typing import Iterable
from re import T
from typing import Optional
from typing import Callable
from re import U
from typing import Iterator
def dedup(iterable: Iterable[T], key: Optional[Callable[[T], U]] = None) -> Iterator[T]:
"""
List unique elements.
>>> tuple(dedup([5, 4, 3, 5, 3, 3]))
(3,... | 8334d08f926584b1c976c24bde180930124b78ba | 3,642,823 |
def get_product(barcode):
"""
Return information of a given product.
"""
return utils.fetch('api/v0/product/%s' % barcode) | 2cc298cf640b4aa742c51b5d076f0021660fe0d5 | 3,642,824 |
def knn_matcher(arr2, arr1, neighbours=2, img_id=0, ratio_threshold=0.75):
"""Computes the inlier matches for given descriptor ararys arr1 and arr2
Arguments:
arr2 {np.ndarray} -- Image used for finding the matches (train image)
arr1 {[type]} -- Image in which matches are found (test image)
... | 6397938b3624e1f32426b429f809e60e6bb72b49 | 3,642,825 |
from typing import Optional
def get_virtual_network_gateway_bgp_peer_status(peer: Optional[str] = None,
resource_group_name: Optional[str] = None,
virtual_network_gateway_name: Optional[str] = None,
... | ade144cd6ce8c6827c0631a5c795d4ef2fbcaf7f | 3,642,826 |
import pathlib
def cat(file_path: str) -> str:
"""pathlib.Path().read_textのshortcut
Args:
file_path (str): filepath
Returns:
str: file内の文字列
Example:
>>> cat('unknown.txt')
"""
file_path = pathlib.Path(file_path)
if file_path.is_file():
return file_path.r... | 17eef15686a97e62380d077d678f2993e02e6d5c | 3,642,828 |
def _get_role_by_name(role_name):
"""
Get application membership role
Args:
role_name (str): role name.
Returns:
int: application membership role id.
"""
base_request = BaseRequest()
settings = Settings()
params = {
'filter': 'name',
'eq': role_n... | 0599f6c9571345318be71b9f453f89d1439c64fa | 3,642,829 |
def parse_filename(filename, is_adversarial=False, **kwargs):
"""Parse the filename of the experment result file into a dictionary of settings.
Args:
filename: a string of filename
is_adversarial: whether the file is from experiments/GIB_node_adversarial_attack.
"""
if is_adversaria... | 1972de5803a8eb0ff50438adbe0adee1597199a9 | 3,642,830 |
def WHo_mt(dist, sigma):
"""
Speed Accuracy model for generating finger movement time.
:param dist: euclidian distance between points.
:param sigma: speed-accuracy trade-off variance.
:return: mt: movement time.
"""
x0 = 0.092
y0 = 0.0018
alpha = 0.6
x_min = 0.006
x_max = 0.... | 36d8b7e913df658b52f1f03617d0b9817091d0ef | 3,642,831 |
def find_next_sibling_position(element, tag_type):
"""
Gets current elements next sibling's (chosen by provided tag_type) actual character position in html document
:param element: Whose sibling to look for, type: An object of class bs4.Tag
:param tag_type: sibling tag's type (e.g. p, h2, div, span etc... | 9b912fd9b7d30e81d6b4c2fec0e0573017b51a83 | 3,642,832 |
def one_hot(arr, n_class=0):
"""Change labels to one-hot expression.
Args:
arr [np.array]: numpy array
n_class [int]: number of class
Returns:
oh [np.array]: numpy array with one-hot expression
"""
if arr is None:
return None
if isinstance(arr, list) or isinstan... | ba22f7f1f7d97d5d3989eff69c42bdce2ca34e87 | 3,642,834 |
def boost_nfw_at_R(R, B0, R_scale):
"""NFW boost factor model.
Args:
R (float or array like): Distances on the sky in the same units as R_scale. Mpc/h comoving suggested for consistency with other modules.
B0 (float): NFW profile amplitude.
R_scale (float): NFW profile scale radius.
... | a7e13f5309fa663b41c5eec1c8518f444ba86b5f | 3,642,835 |
def get_swatches(root):
"""Get swatch elements in the SVG"""
swatches = {}
for node in descendants(root):
if "hasAttribute" not in dir(node) or not node.hasAttribute("id"):
continue
classname = extract_class_name(node.getAttribute("id"))
if classname:
swatches... | 2d9cd4ca2ff034d4200b242eaa5592311c250155 | 3,642,836 |
def chunks(l, n):
"""
Split list in chunks - useful for controlling memory usage
"""
if n < 1:
n = 1
return [l[i:i + n] for i in range(0, len(l), n)] | d878aeb50bd42c9f5a2060f4bb2747aecb1a3b58 | 3,642,837 |
def UserLevelAuthEntry(val=None):
"""Provide a 2-tuple of user and level
* user: string
* level: oneof(ACCESS_LEVELS)
currently: GUEST, USER, ADMIN
"""
if len(val) != 2:
raise ValueError('UserLevelAuthEntry entry needs to be a 2-tuple '
'(name, ac... | e26c723a55d215c71d46d2e45e30b3a39d78723d | 3,642,838 |
import tokenize
def parseCookie(headers):
"""Bleargh, the cookie spec sucks.
This surely needs interoperability testing.
There are two specs that are supported:
Version 0) http://wp.netscape.com/newsref/std/cookie_spec.html
Version 1) http://www.faqs.org/rfcs/rfc2965.html
"""
cookies = []... | f12cfc5303f466eebe3f1b2731d22d02caf12b1d | 3,642,839 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.