content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def crypto_scalarmult_base(n):
"""
Computes and returns the scalar product of a standard group element and an
integer ``n``.
:param n: bytes
:rtype: bytes
"""
q = lib.ffi.new("unsigned char[]", crypto_scalarmult_BYTES)
if lib.crypto_scalarmult_base(q, n) != 0:
raise CryptoError... | 5f5d50e6960f8640a46bd440de36b1ac9e81194e | 3,623,716 |
def verify_ospf3_interface(device,
expected_interface=None,
expected_interface_type=None,
expected_state=None,
extensive=True,
max_time=60,
check_interval=10,... | 11baaa70287458641cc22ec72e01fbb5d4d54994 | 3,623,717 |
def trainCount(
trainData,
questionType,
questionDict,
questionIdict,
objDict,
objIdict,
numAns):
"""
Calculates count(w, a), count(a)
"""
count_wa = np.zeros((len(objIdict), numAns))
c... | 00f55da3cffd84abecbf6fddae09f876e8af463c | 3,623,718 |
def get_corr_account_full_name(split):
"""
Iterate through the parent splits and return all of the accounts that have a value in the opposite sign of the value
in split.
:param split:
:return:
"""
return_value = []
signed = split.value.is_signed()
for child_split in split.transacti... | cbfa9109d205824df5a8b668f6c267e07120a013 | 3,623,719 |
def data_block(block_str):
""" find all thermo data
"""
thm_dstr_lst = data_strings(block_str)
thm_dat_lst = tuple(zip(
map(species_name, thm_dstr_lst),
map(temperatures, thm_dstr_lst),
map(low_coefficients, thm_dstr_lst),
map(high_coefficients, thm_dstr_lst)))
return... | a58d2bc0e1931988114c853021a26b12b67a4359 | 3,623,720 |
import re
def is_match(a,b):
"""Evaluates if a or elements of a are a regex match to the pattern in b."""
if is_array(a):
return all(is_match(a=elem,b=b) for elem in a)
else:
try:
result = bool(re.search(b,a))
except ValueError as e:
print(e)
else:
... | deae8ffab8594f5e853bf1c5fef0ae8cd977aa74 | 3,623,721 |
def remove_class(class_name_gen):
"""
Removes a class on a HTML element
**Important**: this works with the assumption that the element is processed with 'html.parser' or something
similar, that is the 'class' attribute is a list of classes. If processing with the 'html' parser the 'class'
attribute... | 0e3483546587a16ae892c12d8dc3c19660e9973c | 3,623,722 |
import math
import torch
def relative_position_embedding(seq_length, out_dim, repeat_pos_encoding=1):
"""Creates a [seq_length x out_dim] matrix for rel. pos encoding.
Denoted as Phi in [2] and [3]. Phi is the standard sinusoid encoding
matrix.
Args:
seq_length (int): The max. sequence length ... | 585e18eed414e5dbb27d537227d58f7b73531905 | 3,623,723 |
def previous_line(view, sr):
"""sr should be a Region covering the entire hard line"""
if sr.begin() == 0:
return None
else:
return view.full_line(sr.begin() - 1) | b6c668044d57983d2b66a7ae567b59126031cf9f | 3,623,724 |
def Compress():
"""Compresses the go tool into tar.gz and generates sha1 code, renames the
archive to sha1.tar.gz and returns the sha1 code."""
print "Compressing go tool, this may take several minutes."
os.chdir(INSTALL_DIR)
with tarfile.open(os.path.join('a.tar.gz'), 'w|gz') as arch:
arch.add('andro... | f0eac2212b5a5d47e9936cc64001cd11bb29c38f | 3,623,725 |
import async_timeout
import asyncio
import aiohttp
async def async_citybikes_request(hass, uri, schema):
"""Perform a request to CityBikes API endpoint, and parse the response."""
try:
session = async_get_clientsession(hass)
with async_timeout.timeout(REQUEST_TIMEOUT):
req = await... | f215f47f92c8deb5f86fd9085573dd1cf5017fa3 | 3,623,726 |
def times(allow_naive=None, timezones=None):
"""Return a strategy for generating times.
.. deprecated:: 3.9.0
use :py:func:`hypothesis.strategies.times` instead.
The allow_naive and timezones arguments act the same as the datetimes
strategy above.
"""
note_deprecation('Use hypothesis.s... | ea112f95edf363f1be569d5e814e0209f95f0b3e | 3,623,727 |
import logging
from datetime import datetime
def split_by_returning(df_train, df_test):
"""
Split out clients by total number of sessions (single or >=2)
:param df_train:
:param df_test:
:return:
"""
df = pd.concat([df_train, df_test], axis=0, sort=True)
df_grp = df.groupby('fullVisito... | b995033e5e7ea5e16b46f911f79af8f24a54ee22 | 3,623,728 |
def senel_noise(SPLt_dBA_max):
"""This method calculates the effective perceived noise level (EPNL) based on a time history
Perceived Noise Level with Tone Correction (PNLT).
Assumptions:
None
Source:
None
Inputs:
PNLT - Perceived Noise Level wit... | 99644c61a8f31d3dcf8762ca943908bad13607fc | 3,623,729 |
def convertToVerifaiType(value, strict=True):
"""Attempt to convert a Scenic value to a type known to VerifAI"""
ty = underlyingType(value)
if ty is float or ty is int:
return float(value)
elif ty is list or ty is tuple:
return tuple(convertToVerifaiType(e, strict=strict) for e in value)... | da8d5bcb441f666798fb18599efaf287a8afa2e9 | 3,623,730 |
def predecessor_to_forwarding(predecessor, source):
"""
Compute a forwarding table from a predecessor list.
"""
# Create variable to return (forwarding-table dictionary)
FT = {}
# Loop over all nodes that AREN'T the source
for (key, value) in predecessor.items():
if (key != source)... | af0d241fc2b8447581ea582d756a4a3735220815 | 3,623,731 |
def init_atlas_grid(im_size, nb_patterns, rand_seed=None):
""" initialise atlas with a grid schema
:param tuple(int,int) im_size: size of image
:param int nb_patterns: number of pattern in the atlas to be set
:param rand_seed: random initialisation
:return ndarray: np.array<height, width>
>>> ... | 20c372c5668d96ad0176ac94069b6ca1580e5ff5 | 3,623,733 |
def block_diag(values, like=None):
"""Combine a sequence of 2D tensors to form a block diagonal tensor.
Args:
values (Sequence[tensor_like]): Sequence of 2D arrays/tensors to form
the block diagonal tensor.
Returns:
tensor_like: the block diagonal tensor
**Example**
>... | 5d3c64bd04086af4038c9f392ebeae541ca36407 | 3,623,734 |
def parse_menu_command(cmd_addr, sctp_client, keys):
"""Parse specified command from sc-memory and
return hierarchy map (with childs), that represent it
@param cmd_addr: sc-addr of command to parse
@param sctp_client: sctp client object to work with sc-memory
@param keys: keynodes ob... | 015df395293108ae82c6e6d78413718e94401d7b | 3,623,735 |
def main_crimmins_func(port_list: list = None) -> bool:
"""
The Crimmins complementary culling algorithm is used to remove speckle noise and smooth the edges.
It also reduces the intensity of salt and pepper noise. The algorithm compares the intensity of a pixel
in a image with the intensities of its 8 ... | 14696b39b7d814513e7bf79560af1af9d1365fef | 3,623,736 |
from typing import Type
from typing import Any
from typing import List
def find_builtin_server_type(type_name: str) -> Type[Any]:
"""Find first installed server implementation"""
supported_packages = ["sanic", "flask", "tornado"]
installed_builtins: List[str] = []
for name in supported_packages:
... | 49227ea0397a9a9dc0c76a22b6a6b9580f809291 | 3,623,737 |
def uriel_distance_vec(languages):
"""
Adapted from langrank [https://github.com/neulab/langrank/blob/master/langrank.py]
"""
geographic = l2v.geographic_distance(languages)
genetic = l2v.genetic_distance(languages)
inventory = l2v.inventory_distance(languages)
syntactic = l2v.syntactic_dist... | cb174066a61496046aca04b460e16a7cf2c61caf | 3,623,738 |
from typing import List
def create_platform_product_gui(platforms: List[str],
products: List[str],
datacube: datacube.Datacube,
default_platform:str = None,
default_product:str = None,):
... | f739b0f651a84a6aa2c4eba4464ab843e9e88914 | 3,623,739 |
def async_wraps(cls, wrapped_cls, attr_name):
"""Similar to wraps, but for async wrappers of non-async functions."""
def decorator(func):
func.__name__ = attr_name
func.__qualname__ = ".".join((cls.__qualname__, attr_name))
func.__doc__ = """Like :meth:`~{}.{}.{}`, but async.
... | c93fb2a52bfcb3edc9cbf0442138daa1ecf84dda | 3,623,740 |
def commands_getter(manager_router):
"""
Gets the command processor using `Client.command_processor` of an ``_EventHandlerManagerRouter``.
Parameters
----------
manager_router : ``_EventHandlerManagerRouter``
The caller manager router.
Returns
-------
handlers : `list` ... | b0411f10a839859c07c2cc86900b110614d3232f | 3,623,741 |
def PowMod(a, e, m):
"""Deprecated. Use pow(a, e, m) instead."""
if e == 0:
return 1%m
if e == 1:
return a%m
return MulMod(PowMod(a, e/2, m), PowMod(a, e-e/2, m), m) | 75045e2f45760fee1ffca9b27913186fb82c7308 | 3,623,742 |
def uniform_density_prior(d, rlim=30.):
"""
Uniform space density prior
Input:
d: distance (typically an array)
Optional:
rlim: Maximum allowed distance (default: 30 kpc)
Output:
Uniform density prior
"""
return np.piecewise(d, [d < 0, (d >= 0)*(d<=rlim), d>rlim]... | 37870e5eab3bb27970d8de048bfa16851fed5655 | 3,623,743 |
import warnings
def _load_cube(input_files, constraints):
"""Load single :class:`iris.cube.Cube`."""
with warnings.catch_warnings():
warnings.filterwarnings(
'ignore',
message='Ignoring netCDF variable',
category=UserWarning,
module='iris',
)
... | 37b92b96af85ee85b9ef417e161be5c03a834b10 | 3,623,744 |
import scipy
def block_ndi_label_delayed(block, structure):
"""
Delayed version of ``scipy.ndimage.label``.
Parameters
----------
block : dask array (single chunk)
The input array to be labeled.
structure : array of bool
Structure defining the connectivity of the labeling.
... | 82afbf8fdf5bc30298530e8466e8e54db28ea585 | 3,623,745 |
def weighting_matrix(weights, name=None):
""" Creates a weighting matrix.
The ith weight is in the ith upper diagonal of the matrix.
All other entries are 0.
This functions is called once per curriculum update / iteration,
but then used for the entire batch.
Args:
weights: Curriculum w... | 8476041f08c5a38e2fdf3cf8a8543bf77ef45c97 | 3,623,746 |
from typing import Union
from typing import Collection
import re
def pattern(
text: str,
*,
pattern: Union[str, Collection[str]]
) -> str:
"""Remove strings from `text` using a regex pattern.
Args:
text (str): The text from which patterns will be removed.
pattern: The pattern to m... | 3aa1959a03b11ee46dcfd4a675733252533d266e | 3,623,748 |
def drawFrequencies(drawType,d,m,Sigma = None):
"""Draw the 'frequencies' or projection matrix Omega for sketching.
Arguments:
- drawType: a string indicating the sampling pattern (Lambda) to use, one of the following:
-- "gaussian" or "G" : Gaussian sampling > Lambda = N(0,Sigma... | a760f1eb9b707e4e8f6d61f3d684b8a508139021 | 3,623,749 |
def _get_trigger(model, machine, trigger_name, *args, **kwargs):
"""Convenience function added to the model to trigger events by name.
Args:
model (object): Model with assigned event trigger.
machine (Machine): The machine containing the evaluated events.
trigger_name (str): Name of the ... | 1f16e62480f0caf661dc144d6dd92feae9426e96 | 3,623,751 |
def variogram(stats, t):
"""
Helper function that computes the variogram for a given lag t. The variogram
is the mean of the mean squared sum of deviations of lag t of each sequence.
Args:
stats: A list of sequences
"""
m = len(stats)
n = stats[0].size
return sum([np.sum((s[t+1:... | d490cd0871dbc5b256374d16d038c5a7f0a9ee18 | 3,623,752 |
import platform
def _environ_cols_wrapper(): # pragma: no cover
"""
Return a function which gets width and height of console
(linux,osx,windows,cygwin).
"""
current_os = platform.system()
_environ_cols = None
if current_os == 'Windows':
_environ_cols = _environ_cols_windows
... | f199646d10f1e3e3a3a097456dae1401f80a352e | 3,623,753 |
import pandas
def from_timestamp_to_datetime(timestamp, unit='ms'):
"""
:param timestamp: timestamp in unix format.
:param unit: measurement unit used in the timestamp.
:return: the timestamp in date_time format.
"""
return pandas.to_datetime(timestamp, unit=unit) | 48046c91956a9a7195203a84871241d84dd6cd10 | 3,623,756 |
def as_unit_vector(vec):
"""Divides a vector by its length to give a vector of length 1
(unit vector)"""
return vec / np.linalg.norm(vec) | 5c05f1ddde8d5eafb64a0a86d15b58f606200213 | 3,623,758 |
def followers(request, username, template_name="microblogging/followers.html"):
"""
a list of users following the given user.
"""
return _follow_list(request, username, template_name) | a0db1b9d55c562d2646329fcde99cdd00abcadaa | 3,623,759 |
def calc_total_fuel_reqs(filename):
"""
This function iterates through all modules and find total fuel
requirements.
"""
input_file = open(filename, "r")
cumulative_total = 0 # initialize sum as 0
# iterate through list
for input_line in input_file:
try:
mass = input... | 519025809b856a1ec40bc93db0a168c333f5d325 | 3,623,760 |
def check_valid_user(function):
"""
Custom decorator for batch views.
Check if the authenticated user is a user in the batch database and make
the record available in the decorated function.
"""
@wraps(function)
def wrap(request, *args, **kwargs):
user = get_user_from_request(reques... | 0f877b27c5554ceb5211d8bd558901f3430b232f | 3,623,761 |
def formatTarget(data):
"""
:param data: int
"""
good = 0
bad = 0
avg = np.mean(data)
for index in range(data.shape[0]):
val = data[index]
if val < avg:
data[index] = 0
good += 1
else:
data[index] = 1
bad += 1
# prin... | 418df03d2b56728046ff783895ae7de9229d9dc2 | 3,623,762 |
def session_maker(engine): # pylint: disable=redefined-outer-name
"""Create an ORM session from the engine"""
return sessionmaker(bind=engine) | f7b872b44a2d7bc31450e728b5c8987d6d451ce6 | 3,623,763 |
from typing import Optional
import logging
def log_me(name: str = "NetEmbs", folder: Optional[str] = None, file_name: Optional[str] = "logs.log",
level: Optional[int] = logging.INFO) -> logging.Logger:
"""
Attach logger to specific file and location
Parameters
----------
name : str, de... | a2f9bc9d755e641373e195fa0b4abf89cdabc021 | 3,623,764 |
from typing import List
def getNextMineToFinish(games: List[Game]) -> Game:
"""Given a list of games, return the mine that is open and
next to finish; returns None if there are no unfinished games
(finished=past the 4th our, regardless of whether the reward
has been claimed)
If a game is alre... | 71b85bc5eaac8ed15e391edbe806ea47a8dac214 | 3,623,765 |
from pathlib import Path
import inspect
def caller_module() -> Path:
"""Returns the name of the file containing the module from which this
function was called. This ignores all modules located directly inside the
parent directory of the current file (tsfile/*)."""
this_file_parent = Path(__file__).par... | a7c01b9b747ef838315f6c41fc01aa2c70ccb1da | 3,623,766 |
def read_file(file_path='', sheet_name=0, na_values=NA_VALUES, encoding='ISO-8859-1', delimiter=None, **kwargs):
"""
Read pandas dataframe or file.
Parameters
----------
file_path : dataframe or string
string must refer to file. Currenlty, Excel and csv are supported
sheet_name : integer... | 10666963d01cce84a0a738e8585d448361e54668 | 3,623,767 |
def get_matrices(src, domain):
"""Reads the STIX and returns a list of all matrices in the STIX"""
matrices = src.query([
stix2.Filter('type', '=', 'x-mitre-matrix'),
])
# Filter out by domain
matrices = [x for x in matrices if not hasattr(x, 'x_mitre_domains') or domain in x.get('x_mitre_... | 95a1a649c4272cc3322ce051c8f0b9a262d602e8 | 3,623,768 |
import json
import traceback
def get_test_queue_contents(vmcfg, courseId):
"""Get the contents of the test queues for all testers configured
in the system."""
try:
tstcfg = vmcfg.testers()
queue_contents = {} # dict of strings
for tester_id in tstcfg:
queue_contents[tes... | c7a908e845d737387f87c024965667b3a111e914 | 3,623,769 |
def qgrams_to_char(s: list) -> str:
"""Converts a list of q-grams to a string.
Parameters
----------
s : list
List of q-grams.
Returns
-------
A string from q-grams.
"""
if len(s) == 1:
return s[0]
return "".join([s[0]] + [s[i][-1] for i in range(1, len(s))]) | cc7dc5eb4d5c9e3e5f751cf7c2190e68c3ba11bd | 3,623,770 |
def traverse(coord, np_mask, coord_str):
"""Edge case: if pixel value in mask is 0 at coord, then
bounding box has captured the extreme points in this corner
of the image
"""
x, y = coord
if np_mask[y, x] == 0.0:
return (x, y)
height, width = np_mask.shape
store_x, store_y = 0,... | e46889c358deeb2cd26fdba0a6e2eff03034d016 | 3,623,771 |
def collect_pc(grasp_, pc):
"""
grasp_bottom_center, normal, major_pc, minor_pc
"""
grasp_num = len(grasp_)
grasp_ = np.array(grasp_)
grasp_ = grasp_.reshape(-1, 5,
3) # prevent to have grasp that only have number 1
grasp_bottom_center = grasp_[:, 0]
approach... | 53d08217142af77812f98bd6145a899f9c458be5 | 3,623,772 |
from typing import Callable
from typing import Iterable
import functools
def change_ids(dataset: Dataset, change_id: Callable, methods: Iterable[str] = ()) -> Dataset:
"""
Change the ``dataset``'s ids according to the ``change_id`` function and adapt the provided ``methods``
to work with the new ids.
... | 51a3efb98f94f1b3a57d135a4ccf50b3b27ba7d4 | 3,623,773 |
def _configure_learning_rate(num_samples_per_epoch, global_step):
"""Configures the learning rate.
Args:
num_samples_per_epoch: The number of samples in each epoch of training.
global_step: The global_step tensor.
Returns:
A `Tensor` representing the learning rate.
Raises:
ValueE... | b06843b605c9748c4e5633dc29f0e5d03dc9a8e1 | 3,623,774 |
import numpy
import math
def power(inputArray, power_index=3.0, scale_min=None, scale_max=None):
"""Performs power scaling of the input numpy array.
@type inputArray: numpy array
@param inputArray: image data array
@type power_index: float
@param power_index: power index
@type scale_min: floa... | f5f903946c0b532cd0f70f49c17cb54c4be7c22a | 3,623,776 |
import uuid
def get_key_for_player_ui(game_id: int, player_name: str) -> JSONResponse:
"""
Method used to generate user private access token for view ui and send moves
:param game_id: integer value of existing game
:param player_name: string with name of player
:return: Response with access token ... | 17e41d5fc812bbfcda200c1b64bb4a693a21e24b | 3,623,777 |
def load_speakers(fileobj):
"""Load a list of speakers from a yaml file.
This is a legacy wrapper around load_real_layout; see its documentation for
format info.
Parameters:
file: a file-like object to read yaml from
Returns:
list of Speaker
"""
return load_real_layout(fil... | 36781a91a4845138a9b879edfdcf32233cf31447 | 3,623,778 |
def softmax(x):
"""Compute softmax values for each sets of scores in x.
Copied from Andrew Ng's Deep Learning courses on Coursera
"""
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum() | 1030e23642edc52749584b527f682c90b8c3551a | 3,623,779 |
import html
from typing import Dict
from typing import Any
def result(app: dash.Dash, data: GameData) -> html:
"""Layout for the result page. This page get display after every user prediction.
This pages displays the predictions from the user and the ai together with
the ground truth. An explanation for t... | 031739565654ca3353c8783e51008de0a92329a9 | 3,623,782 |
def iterate_module_func(m, module, func, converged):
"""Call function func() in specified module (if available) and use the result to
adjust model convergence status. If func doesn't exist or returns None, convergence
status will not be changed."""
module_converged = None
iter_func = getattr(module,... | f7221e003dcc627f6e19a9b4961e62d7d98b87e3 | 3,623,783 |
def trace_color_table(measurement):
"""
Returns one of the standard color tables for TRACE JP2 files.
"""
if measurement == 'WL':
return cmap_from_rgb_file(f'TRACE {measurement}', 'grayscale.csv')
try:
return cmap_from_rgb_file(f'TRACE {measurement}', f'trace_{measurement}.csv')
... | 624f5659d39f584617ad2c4726afccf5e9b673e0 | 3,623,784 |
def redeemBLVT(tokenName, amount, recvWindow=""):
"""# Redeem BLVT (USER_DATA)
#### `POST /sapi/v1/blvt/redeem (HMAC SHA256)`
### Weight:
1
### Parameters:
Name |Type |Mandatory |Description
--------|--------|--------|--------
tokenName |STRING |YES |BTCDOWN, BTCUP
amount |DECIMAL |YES |
recvWindow |LONG |NO |
ti... | 0adc7544c10839c09a57ca44a61fae247b6f6731 | 3,623,785 |
def getGitInfo():
"""Make a build string for svn
Returns a string or None if not in a git repository"""
(gitLocalVersion, local) = ("","")
# need to do a 'git diff' because 'describe --dirty' can get confused by timestamps
(gitLocalVersion,stderr) = Popen("git diff --shortstat", shell=True, s... | c133abba0e47cb0803b1e97a4b963c265c5f6c40 | 3,623,786 |
from pysat import DataFrame, Series, Panel
import warnings
def computational_form(data):
"""
Repackages numbers, Series, or DataFrames
.. deprecated:: 2.2.0
`computational_form` will be removed in pysat 3.0.0, it will
be added to pysatSeasons
Regardless of input format, mathematical oper... | 1f506f09c793915a8d3d3b9ed8d34879dd10ea8e | 3,623,787 |
def _check_df_load(df):
"""Check if `df` is already loaded in, if not, load from file."""
if isinstance(df, str):
if df.lower().endswith("json"):
return _check_gdf_load(df)
else:
return pd.read_csv(df)
elif isinstance(df, pd.DataFrame):
return df
else:
... | bfe7f6e311fe99590e9680be0453776991a6914d | 3,623,788 |
import requests
def delete_channel(accountId, apiKey, channelId, verbose=False):
"""Deletes a channel.
Parameters
----------
accountId: str
apiKey: str
channelId: str
the channel ID to delete
verbose: bool, optional
Returns
-------
bool
True if the channel was... | 937422a3f51a036390968e941621ba50d248ca4c | 3,623,789 |
def make_all_figures(close_figs=False):
"""
Call all the figure generators for this chapter
:close_figs: Boolean flag. If true, will close all figures after generating them; for batch scripting.
Default=False
:return: List of figure handles
"""
# Find the output directory
... | 18afa8c0f344dd05d851f54628a63e0f1df68ace | 3,623,790 |
import re
def arguments_from_docstring(doc):
"""Parse first line of docstring for argument name.
Docstring should be of the form ``min(iterable[, key=func])``.
It can also parse cython docstring of the form
``Minuit.migrad(self[, int ncall_me =10000, resume=True, int nsplit=1])``
"""
if doc... | 4b08f36678247df6119e594ff9859f697f2e8d23 | 3,623,793 |
def _check_mod_11_2(numeric_string: str) -> bool:
"""
Validate numeric_string for its MOD-11-2 checksum.
Any "-" in the numeric_string are ignored.
The last digit of numeric_string is assumed to be the checksum, 0-9 or X.
See ISO/IEC 7064:2003 and
https://support.orcid.org/knowledgebase/artic... | 685a9e8085000248290c9e482a115c99942c51d1 | 3,623,794 |
def fft_convolve3(signal, kernel, conv_mode = CONV_MODE.DEFAULT):
"""
FFT based Convolution: 3D
Parameters
-----------
signal: af.Array
- A 3 dimensional signal or batch of 3 dimensional signals.
kernel: af.Array
- A 3 dimensional kernel or batch of 3 dimensional kerne... | 4d3034b8dd7c9c67724e387729d1b37b1e391499 | 3,623,795 |
def check_en_wik9_dataset(method):
"""Wrapper method to check the parameters of EnWik9 dataset."""
@wraps(method)
def new_method(self, *args, **kwargs):
_, param_dict = parse_user_args(method, *args, **kwargs)
nreq_param_int = ['num_samples', 'num_parallel_workers', 'num_shards', 'shard_id... | aac1c9757922c3ea29657c2530572c69ae23ac71 | 3,623,796 |
import time
def low_depth_second_order_trotter_error_operator(
terms, indices=None, is_hopping_operator=None, jellium_only=False,
verbose=False):
"""Determine the difference between the exact generator of unitary
evolution and the approximate generator given by the second-order
Trotter-Suz... | 4602f73b1fb2998d3ea612f3b09bf5b6aa00f65d | 3,623,798 |
import time
from datetime import datetime
def get_historical(ticker: str, metric: str) -> pd.DataFrame:
"""Get historical sentiment data [Source: sentimentinvestor]
Parameters
----------
ticker : str
Stock
metric : str
Metric to get
Returns
-------
pd.DataFrame
... | 88e8d968d449d7688f4b4bced7b23cc7b6a77b3d | 3,623,799 |
def _calculate_euclidean_similarity(distances, zero_distance):
"""Calculates the euclidean distance between two sets of detections, and then converts this into a similarity
measure with values between 0 and 1 using the following formula: sim = max(0, 1 - dist/zero_distance).
The default zero_distance of 2.0... | d14882504004220143c136e20a32290afe378e32 | 3,623,800 |
import json
import requests
def setInitialParameters(initialSuggestions):
"""Initial parameters for optimization problem being solved"""
global params
params = initialSuggestions
sugjson = json.dumps(list(initialSuggestions))
apipath = __SERVER_HOST__ + __SERVER_PARAMETERS_API__ + "/" + s... | c714663372e57f2d8475eef41d2ce6054a642c0a | 3,623,801 |
def compute_signature_strength(cpds_list, df, metadata_cols = metadata_cols):
"""Computes signature strength for each compound based on its replicates"""
cpds_SS = {}
for cpd in cpds_list:
cpd_replicates = df[df['pert_iname'] == cpd].copy()
cpd_replicates.drop(metadata_cols, axis = 1, i... | 6f5ac11cb5ded6aa1b6ae33cd11db872742335d6 | 3,623,802 |
def join_3_query():
"""Finds all players from country X who scored at least one goal in a game played in Y city and Z year."""
desired_country = "Brazil"
desired_gameDest = "Europe"
desired_gameYear = 2017
sql = text('''SELECT distinct a.name, a.teamID, a.status, a.salary
FROM Ath... | 751a0be79e27e9f71e22d3f84a07399711dce7f2 | 3,623,805 |
def calc_ac_fit(df, objects):
"""
created dataframe of features
for train objects
"""
object_ids, ac_decay, ac_decay_err, ac_loss, ac_amp, ac_amp_err = (
[],
[],
[],
[],
[],
[],
)
for obj in objects:
obj_df = df[(df.object_id == obj)... | 12076c6021feaab949d5044766487558d24ca2a4 | 3,623,806 |
from typing import List
def get_forge_plugin_command_names() -> List[str]:
""" Returns a list of plugin command names"""
return [
get_command_from_config(plugin_config)
for plugin_config in get_plugins()
] | f6c747df98d418a90baeed5cffbbee77f18ee106 | 3,623,807 |
def array_to_datetime(array):
"""
Convert an 1d datetime array from various types into pandas.DatetimeIndex
(i.e., numpy.datetime64).
If the input array is not in legal datetime formats, raise a "ParseError"
exception.
Parameters
----------
array : list or 1d array
The input da... | 3fa1280ad9b84416f5000f01497a615bbba5099e | 3,623,808 |
def then(name, converters=None):
"""Then step decorator.
:param name: Step name or a parser object.
:param converters: Optional `dict` of the argument or parameter converters in form
{<param_name>: <converter function>}.
:return: Decorator function for the step.
"""
retu... | 55baabeecb74f56390da45804091dab3ce755ab3 | 3,623,810 |
import json
def get_stored_username():
"""get stored username if available"""
file_name = 'chapter_10/remember.json'
try:
with open(file_name) as f_o:
usern = json.load(f_o)
except FileNotFoundError:
return None
else:
return usern | 6abe0542a882fe01f63c5392d112514595a167d7 | 3,623,811 |
import json
def evaluate(gt_file, re_file, logger=None):
"""
This function is reformed from MSCOCO evaluating code.
The reference sentences are read from gt_file,
the generated sentences to be evaluated are read from res_file
"""
gts = json.load(open(gt_file, 'r'))
scorers = [
(B... | a51e768a38c34add431cd5b20002fd63641a5151 | 3,623,812 |
def redis_error_handler(func):
"""Decorator for returning better errors if Redis is unreachable"""
def wrapper(*args, **kwargs):
try:
if 'body' in kwargs:
# Our get/patch functions don't take body, but the **kwargs
# in the arguments to this wrapper cause it t... | d699f4c846a3e0e6788e73bdd32ff894997a96a7 | 3,623,813 |
def find_versions_from_versioncontrol(dependencies):
"""Determine whether a file is under version control, and if so,
obtain version information from this."""
for dependency in dependencies:
if dependency.version == "unknown":
try:
wc = versioncontrol.get_working_copy(... | 631d2d193e8b4e066675e465c66da171b0e1417c | 3,623,814 |
import pdb
def findDistortionCoefficients(filename,Nx,Ny,method='cubic'):
"""
Fit L-L coefficients to distortion data produced by Vanessa.
"""
#Load in data
d = np.transpose(np.genfromtxt(filename,skip_header=1,delimiter=','))
#Compute angle and radial perturbations
x0,y0,z0 = d[2:5]
... | bb24aa3d0e44bf0bbf75966b8aa8b2df1fdded24 | 3,623,815 |
import six
def keras_test(func):
"""Function wrapper to clean up after TensorFlow tests.
# Arguments
func: test function to clean up after.
# Returns
A function wrapping the input function.
"""
@six.wraps(func)
def wrapper(*args, **kwargs):
output = func(*args, **kwarg... | 1d6224d91597cb1baf6a6ba92c9a228e9ca83304 | 3,623,816 |
def drawbox(img,bbox):
"""
skeleton function which draws bbox on an img
:param img:
:param bbox:
:return:
"""
return img | c1f56b17d3f78333f7c6e9cd5dcda0b0d792040c | 3,623,817 |
from typing import Any
def is_valid_route_protection(protection: Any) -> bool:
"""Checks if the protection text is a valid protection name.
Returns True if valid, False if not."""
if not isinstance(protection, str):
return False
# Once the protection scheme is established, this can be loosened... | 00ea1980fbd38523de0d39b63fa29d0d1f4626f7 | 3,623,818 |
from pathlib import Path
def open_CsvDataset(filename, delimiter=',', M='M', T='T', tlabels=False, varnames=False, parameter='climate_var'):
"""opens a .csv file formatted like n_samples x m_features. returns Xarray DataArray with X=0, Y=0, Samples=N, features=M.
Can include labels for each sample, and labels for e... | d4841240212d037006fe84768aaf1620fc02929e | 3,623,819 |
def parse_coalesce_object_response(coalesce_object_response):
"""
Parse a response from RpcGetObject.
Returns (modification time, inode no., no. writes).
"""
return (_ctime_or_mtime(coalesce_object_response),
coalesce_object_response["InodeNumber"],
coalesce_object_response[... | 18af73840346f6770d464de94ca80cc692baae5a | 3,623,821 |
from typing import Dict
from typing import List
def make_hist_dict(
bin_edges: Dict[str, Dict[str, str]],
adj: bool,
hist_metric_list: List[str] = HISTS,
label_delimiter: str = "_",
) -> Dict[str, str]:
"""
Generate dictionary of Number and Description attributes to be used in the VCF header, ... | 01b2969900f9cb41a26d89e5779c565bd9002bbd | 3,623,822 |
def create_running_ema(alpha=0.95, initial=0):
"""
Returns a function to compute running
exponentially weighted averaging
Args:
alpha (0.95): relative importance of accumulated value
initial (0): initial value
"""
return partial(running_f,
f=lambda acc, elem: alpha*a... | c19d3df9fcb245d07e5eebba30ec5a1e967179dc | 3,623,823 |
from typing import Optional
def get_tarred_char_dataset(
config: dict, shuffle_n: int, global_rank: int, world_size: int, augmentor: Optional['AudioAugmentor'] = None
) -> audio_to_text.TarredAudioToCharDataset:
"""
Instantiates a Character Encoding based TarredAudioToCharDataset.
Args:
confi... | 8227bf532db08eefa44b71d069e6e6661e68b10f | 3,623,824 |
def gtf_row_to_bed(row):
""" Converts gtf row to bed format:
Args:
row (pd.Series): One GTF row
Returns:
pd.Series([chrom, start, end, ensID, "."])
"""
# Extract required fields
chrom = str(row[0])
strand = row[6]
# Take end of transcript for forward/reverse strand
if... | 06bfbaf6668758385dcc070d2504285fa7e465b2 | 3,623,826 |
def mtotal_from_mtotal_source_z(total_mass_source, z):
"""Return the detector-frame total mass of the binary given samples for
the source-frame total mass and redshift
"""
return _detector_from_source(total_mass_source, z) | 715bd3d4b8a93d63ed51b7e7437d0dde88777acf | 3,623,828 |
def sim_spiketrain(spike_param, n_samples, method, refractory=None, **kwargs):
"""Simulate a spike train.
Parameters
----------
spike_param : float
Parameter value that controls the simulated spiking. rate or probability.
For `prob` or `binom` methods, this is the probability of spiking... | 73c4ec8519884374c34cb0cefd811a337a6c83a9 | 3,623,829 |
def weight_mask_variable(var, scope):
"""Create a mask for the weights.
This function adds a variable 'mask' to the graph.
Args:
var: the weight variable that needs to be masked
scope: The variable scope of the variable var
Returns:
the mask variable of the same size and shape as var, initialized... | 203d607fc203de794a5d13e19b1200cce80641f5 | 3,623,830 |
def youngest_oldest(_dict):
"""Return youngest and oldest billionaires."""
oldest = None
youngest = float('inf')
for person in _dict:
if person['age'] < 80:
if oldest is not None:
if person['age'] > oldest['age']:
oldest = person
else:
... | 9c7bd8834701fc6136447c6693c22efc2461f26b | 3,623,831 |
import requests
import time
def get_management_token() -> dict:
"""
Gets a token for contacting the management endpoint of auth0.
Returns:
dict -- Dictionary with token and expirey information.
"""
payload = {
'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
... | c293ed416b6850033f2a9b3b82381008d2475bb5 | 3,623,834 |
def simulate(t=1000, poly=(0.,), sinusoids=None, sigma=0, rw=0, irw=0, rrw=0):
"""Simulate a random signal with seasonal (sinusoids), linear and quadratic trend, RW, IRW, and RRW
Arguments:
t (int or list of float): number of samples or time vector, default = 1000
poly (list of float): polynomial c... | d6c747937340a181b6eb99f3c5c539f7c920705e | 3,623,835 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.