content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def rankhist(X_f, X_o, X_min=None, normalize=True):
"""Compute a rank histogram counts and optionally normalize the histogram.
Parameters
----------
X_f: array-like
Array of shape (k,m,n,...) containing the values from an ensemble
forecast of k members with shape (m,n,...).
X_o: arr... | 91c60cdcd6b046a43fca6502ae83d8bba90e6569 | 37,950 |
def build_data_sampler(config, dataset):
"""Returns a data sampler object of :class:`colossalai.nn.data.sampler.BaseSampler`
constructed from `config`.
Args:
config (dict or :class:`colossalai.context.Config`): A python dict or
a :class:`colossalai.context.Config` object containing info... | 1afcf7dc176eba096dda3ca998f1cc075269e321 | 37,951 |
def to_kwargs(triangles):
"""
Convert a list of triangles to the kwargs for the Trimesh constructor.
Parameters
---------
triangles: (n,3,3) float, triangles in space
Returns
---------
kwargs: dict, with keys:
'vertices' : (n,3) float
'faces' : ... | 067afee9f1d848893198c94a9caef93a2667978a | 37,952 |
def get_model_field(model, name):
"""
Gets a field from a Django model.
:param model: A Django model, this should be the class itself.
:param name: A Django model's field.
:return: The field from the model, a subclass of django.db.models.Model
"""
return model._meta.get_field(name) | e0f692aff82c20c7817d7de5d1fbeec1b69d3a3d | 37,953 |
from scipy.stats.mstats import trimmed_mean, trimmed_std
def get_clean_sample_mask(log_mah_fit, logmp_sample, it_min, lim=0.01, z_cut=3):
"""Calculate mask to remove halos with outlier MAH behavior.
Parameters
----------
log_mah_fit : ndarray of shape (n_halos, n_times)
logmp_sample : float
... | d1c2e530c0e0feb14061a71c7cf71dcb8d1724d7 | 37,954 |
def inert_masses(m_1, H, z_m, E_1):
"""First stage inert masses.
Arguments:
m_1 (scalar): First stage wet mass [units: kilogram].
H (scalar): Fraction of the recovery vehicle dry mass which is added recovery
hardware [units: dimensionless].
z_m (scalar): Fraction of baseline... | 5698fcb36ef1f532cc8bc1dc0c86a25adc5bcab8 | 37,956 |
def _grid_mapping(pollon, pollat, mapping_name=None):
"""creates a grid mapping DataArray object"""
if mapping_name is None:
mapping_name = cf.DEFAULT_MAPPING_NCVAR
da = xr.DataArray(np.zeros((), dtype=np.int32))
attrs = cf.mapping.copy()
attrs["grid_north_pole_longitude"] = pollon
attrs... | 4a7478ee0ca612158b4eb3e5b83de511acf3b978 | 37,957 |
def retrieve_employees(page=1):
"""
Handle requests to the /employees/<int:page> route - @roles_required(xxx)
Retrieve all employee from the DB ordered by the First Name with the pagination support
Filter employees based on specified start date and end date
"""
employees_per_page = 7
employ... | 62cead2fcd605c8d884771ac0681e574db25b4b7 | 37,958 |
def __virtual__():
"""
Confine this module to yum based systems
"""
if __opts__.get("yum_provider") == "yumpkg_api":
return (False, "Module yumpkg: yumpkg_api provider not available")
try:
os_grain = __grains__["os"].lower()
os_family = __grains__["os_family"].lower()
exc... | 67daa8e6afdd95d6c2ffa0589579b22494869c94 | 37,959 |
def get_update_message(new_version, info_url):
"""Return a string suitable for notifying users about the status
of their update check. NEW_VERSION and INFO_URL generally come
directly from a call to update_check()."""
if new_version is None:
return (f'You are running the latest version ({__ver... | cfe8010e02d1a0f770e17c4615b737a42a98530f | 37,960 |
def str_url_encode(text):
"""
Encode package before send to Telegram API.
:param text: string.
:return: string.
"""
return quote(text) | 4c195f7df7830119277dfd6d5bb00ad9ffebdc6a | 37,961 |
from typing import Any
def block(func: AnyCallable, *args: Any, **kwargs: Any) -> Any:
"""
Run a function in a blocking manner, whether the function is async or blocking.
Args:
func - the function (async or blocking) to run
args - the args to run the function with
kwargs - the kwa... | dce4632e64f45106b66206bb7c5eca5ccdfc8335 | 37,962 |
def input(msg="", default="", title="Lackey Input", hidden=False):
""" Creates an input dialog with the specified message and default text.
If `hidden`, creates a password dialog instead. Returns the entered value. """
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(default)
PopupInpu... | 25570f21f266a92b9e2291d7c6d8338e0a242e66 | 37,963 |
def commnets(milestone):
"""Filtrira milestone tako da nadje samo broj komentara za svaki pojedinacni"""
comments = milestone.event_set.filter(event_kind="K")
size = comments.count()
return size | 9c3654911fe993c359bc593433b6fde1c467a504 | 37,964 |
import six
def finish_login(request):
"""Complete OpenID Login Process"""
response = _finish_verification(request)
if not response:
# Verification failed, redirect to login page.
return redirect(request, 'mediagoblin.plugins.openid.login')
# Verification was successfull
query = O... | e3ceefa6ae768f8aba2e26970a39b2daf037a5c9 | 37,965 |
import re
def check_tweet_emphasis(tweet):
"""
Performs check whether words in a tweet have 3 or
more repeating characters. If the word has 3 or
more repeating characters, word will be replaced
by one that matches the original word as close as
possible repeated twice, otherwise original wor... | fa14474733f684767bb52c66a0d7da3ffcd0d010 | 37,966 |
def buildList(pdList, matrix):
"""Takes a list of primary datasets (PDs) and the AlCaRecoMatrix (a dictinary) and returns a string with all the AlCaRecos for the selected PDs separated by the '+' character without duplicates."""
alCaRecoList = []
for pd in pdList:
alCaRecoList.extend(matrix[pd].spli... | 7e9351f115aac1064068e16f12276ed5506217e4 | 37,967 |
import random
def random_wish(rankings):
"""
Select a wish randomly with exponential decay
:param rankings: ordered [(pitch, role)]
:return: i the index of the chosen wish in the rankings
"""
cum_weights = exp_cum(len(rankings))
total = cum_weights[-1]
hi = len(cum_weights) - 1
ret... | 9f229d9478655dedc7f8c63a39e0140f3a6884a8 | 37,968 |
def serialize_to_database(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, date):
return str(obj.isoformat())
if isinstance(obj, (DateRange, DateTimeRange)):
return f"[{obj.lower}, {obj.upper}]"
return obj | a537ac8096e6d7955608887c7c7c08ece9467092 | 37,969 |
def _flatten_dict_into_array(dictionary, dtype=np.float32):
"""
Flatten the given dictionary into an array of scalars, and return the beginning index of each sequence of values.
Parameters
----------
dictionary : dict
Some dictionary containing scalars or array of scalars as each of its key... | e4390204b1a64adac8b0788f9d5f3ec646cf1850 | 37,970 |
def DecoderBlock(d_model, d_ff, n_heads,
dropout, mode, ff_activation):
"""Returns a list of layers that implements a Transformer decoder block.
The input is an activation tensor.
Args:
d_model (int): depth of embedding.
d_ff (int): depth of feed-forward layer.
n_... | 9b5b4678ac988714e1d3af96c0dfb9ff43847c03 | 37,971 |
def get_gradient(pixels,processing = 'normalize'):
"""returns the gradient of an image, and does basic preprocessing"""
horgradient = ndimage.sobel(pixels, axis = 1)
vergradient = ndimage.sobel(pixels, axis = 0)
gradient = np.array((vergradient,horgradient))
if processing == 'normalize':
"... | d05f562b54fb2800fa1eb1a97d6373912906e40c | 37,972 |
def get_roommates():
"""Endpoint to get all rooms for the given search conditions."""
LOGGER.info(' Inside /api/getRoommates')
roommates_list = userscontroller.get_all_roommates("")
return roommates_list | 35c9ade000f2bd07dddc78cd0d9f0c24ea3516cb | 37,973 |
def log_mean_temp_diff(T_A_one, T_A_two, T_B_one, T_B_two):
"""
Calculate the logarithmic mean temperature difference (LMTD) of two fluid
streams `one` and `two` of a heat exchanger with two ends `A` and `B`.
Parameters:
-----------
T_A_one : float, int, np.array
Fluid temperature of st... | 63e683186ba0644222c5406807c605be662cfc40 | 37,974 |
from typing import Dict
from typing import Any
from typing import Optional
def trade_from_coinbase(raw_trade: Dict[str, Any]) -> Optional[Trade]:
"""Turns a coinbase transaction into a rotkehlchen Trade.
https://developers.coinbase.com/api/v2?python#buys
If the coinbase transaction is not a trade related... | 930db004948e3f73fb423a6920c4e7c87ccf1988 | 37,975 |
def infected():
"""
Real Name: b'Infected'
Original Eqn: b'INTEG ( Infection Rate-recovery rate, 1)'
Units: b'Person'
Limits: (None, None)
Type: component
b''
"""
return _integ_infected() | 5bab3a7b2be75fca2e1ef8dc15b1dc0ef681aee3 | 37,977 |
from typing import Optional
def get_dataproc_cluster(cluster_id: Optional[str] = None,
name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDataprocClusterResult:
"""
Get information about a Yandex Data Proc cluster. For more... | a43b7db12fd88315ad28adb412dd18b915c9864d | 37,978 |
import ctypes
def GetNumberPreAmpGains(LR: ctypes, error: Error=default) -> tuple:
"""
Returns tuple(MsgError type, number)
"""
if not error['status']:
n = ctypes.c_int32(0)
number= ctypes.pointer(n)
executed = LR.GetNumberPreAmpGains(number)
return errorcodehandler(ex... | 5e30aa344860eb89d6ed112a1a283aa5f439eec0 | 37,979 |
from typing import List
def ele2json(data: list) -> List[str]:
"""把元素为dict类型的list数据,转为,元素为json字符串的list数据
Args:
data: list类型的数据,元素为dict类型
Returns:
转换后的list数据
"""
return [dict2json(item) for item in data] | 2fc4b1d6328fd1101f89a8fbc6e177e177f51207 | 37,981 |
def remove_small_components(mesh, min_volume=5e-05):
"""Removes all components with volume below the specified threshold."""
if mesh.is_empty:
return mesh
out = [m for m in mesh.split(only_watertight=False) if m.volume > min_volume]
if not out:
return mesh
return trimesh.util.concatenate(out) | b2ec1f367a28aee505c569900edc035ded3e8331 | 37,982 |
def is_retriable(exception):
"""Returns True if this exception is retriable."""
errs = list(range(500, 505)) + [429]
errs += [str(e) for e in errs]
if isinstance(exception, HttpError):
return exception.code in errs
# https://cloud.google.com/storage/docs/key-terms#immutability
if isinsta... | 27d556924e521f970124e751144b5e2675d623f1 | 37,983 |
def parse_styles(cssfiles):
"""
Parse CSS files.
This parse some CSS files and build a map of each attribute with these values.
It's very useful to inline some CSS propety to html objects.
:param cssfiles: A list of CSS files
:type cssfiles: list
:return: A map of C... | 5193b3c672de6c434cc4475a4508ab2160aa4202 | 37,985 |
def sgld_gradient_update(step_size_fn, seed):
"""Optix implementation of the SGLD optimizer"""
def init_fn(_):
return OptixSGLDState(count=jnp.zeros([], jnp.int32),
rng_key=jax.random.PRNGKey(seed))
def update_fn(updates, state, params=None):
del params
lr = step_size_fn(... | 3b4c448027f0267082fd0d747e7280cbf348b79d | 37,986 |
import re
def _get_ip_addr_num(file_path):
"""Get the next IPADDR index num to use for adding an ip addr to an
ifcfg file.
"""
num = ''
with open(file_path, 'r') as f:
data = f.read()
data = data.splitlines()
for line in data:
found = re.search(r'IPADDR(\d?)=', line)
... | 09dfd6bc8a9da240d3044bd6f5b974c69cbebf76 | 37,987 |
def subsample(X, subsample=1, seed=0):
"""Subsample a fraction of 1/subsample samples from the rows of X.
Parameters
----------
X : np.ndarray
Data array.
subsample : int
1/subsample is the fraction of data sampled, n = X.shape[0]/subsample.
seed : int
Seed for sampling.... | 2ce66b67b771bb5f7ab60d8b318cff732c292a66 | 37,988 |
def norm(collection: str, country_code: str, name: str, lang: str = DEFAULT_LANG) -> str:
"""Normalize the name with respect to a collection and country code.
>>> norm(CITY, 'RU', 'leningrad')
'Saint Petersburg'
>>> norm(CITY, 'RU', 'peterburg')
'Saint Petersburg'
>>> norm(CITY, 'RU', 'peterbur... | 925e8993dea77d88180c13ce3af42e90c80b49cb | 37,989 |
def createFeatureDF(pairs, classes, knownDrugDisease, drugDFs, diseaseDFs):
"""Create the features dataframes.
:param pairs: Generated pairs
:param classes: Classes corresponding to the pairs
:param knownDrugDisease: Known drug-disease associations
:param drugDFs: Drug dataframes
:param disease... | bf36f8cc23d50d553d00e419b781fa0d55bca029 | 37,990 |
def getBigram(words, join_string):
"""
Input: a list of words, e.g., ['I', 'am', 'Denny']
Output: a list of bigram, e.g., ['I_am', 'am_Denny']
I use _ as join_string for this example.
"""
assert type(words) == list
L = len(words)
if L > 1:
lst = []
for i in range(L-1):
... | 07c0c421b6d5530059fc06e49b338f1984a445f8 | 37,991 |
def get_xqueue_callback_url_prefix(request):
"""
Calculates default prefix based on request, but allows override via settings
This is separated from get_module_for_descriptor so that it can be called
by the LMS before submitting background tasks to run. The xqueue callbacks
should go back to the L... | b4301e623eb3886d76430289473aea3288511241 | 37,992 |
def abi_extensions():
"""List with all the ABINIT extensions that are registered."""
return list(_EXT2VARS.keys())[:] | 41b47b2c96e65c3af3ab15a7ad4cddb3213c3a1c | 37,993 |
import glob
def load_csvs():
"""Returns dataframe containing all CSV files from directory 'cache' and returns a list of the filepaths.
"""
path = 'cache'
csv_list = glob.glob(path + "/*.csv") # collect all filepaths
df = pd.concat((pd.read_csv(f, index_col=0) for f in csv_list)) # concatenate all... | 648e0819ed696024f2dd2dd9f7bbd05faf0c25f9 | 37,994 |
def merge_networks_from_tags(shape, props, fid, zoom):
"""
Take the network and ref tags from the feature and, if they both exist, add
them to the mz_networks list. This is to make handling of networks and refs
more consistent across elements.
"""
network = props.get('network')
ref = props.... | f8d4f764f885c8db7c920169d65126a783f6c1ee | 37,995 |
def tabs(text: str) -> str:
"""Remove tabs.
If you want to replace tabs with a single space, use
`normalize.whitespace()` instead.
Args:
text (str): The text from which tabs will be removed.
Returns:
The stripped text.
"""
return resources.RE_TAB.sub("", text) | 494216fa8ad5570604a69c8c37e94797b268381a | 37,996 |
from numpy import nan
def tobool(value):
"""Convert value to boolean or Not a Number if not possible"""
if value is None: value = nan
else: value = bool(value)
return value | 9517d817381111c55e73e03256d516ccbbd940a2 | 37,997 |
import json
import collections
def load_synonyms(synonym_filepath=None):
"""Loads synonym dictionary. Returns as defaultdict(list)."""
with tf.gfile.Open(synonym_filepath) as f:
synonyms = json.load(f)
synonyms_ = collections.defaultdict(list)
synonyms_.update(synonyms)
return synonyms_ | 2d98df5edf7b116a7807851db234dfa322da9a99 | 37,998 |
def get_table_code(sol, table_name, unused_options):
"""
Gets the table code of a given parameter. For example, the
DISPLACMENT(PLOT,POST)=ALL makes an OUGV1 table and stores the
displacement. This has an OP2 table code of 1, unless you're running a
modal solution, in which case it makes an OUGV1 ... | d9840f55260b92f704160906cfb65baa678881ff | 37,999 |
def wfFormIndex(text, lang, lowercase = True, contract = True, stopWords = False):
"""Returns the Formality Score of a text.
This function returns a value based on the weight that each kind of word
(adjective, noun, pronoun, etc.) has within the text.
"""
diffWords = stats.wordClass(text,... | 400cf83f5ea7eec82a9db8dd7ddfb6d9c35c23d8 | 38,000 |
def showtables(hcaturi, dbname='default', username='hdfs'):
"""
hcat.showtables
Args:
hcaturi (str): uri for webhcat host, eg hive.myorg.com:50111
dbname (Optional[str]): database name, defaults to 'default'
username (Optional[str]): user name defaults to hdfs
Returns:
list: list of available tables for t... | c5c577068882813fb4b7ff7f32da3dab4cbad6a9 | 38,002 |
def fourier_gaussian(input, sigma, n = -1, axis = -1, output = None):
"""Multi-dimensional Gaussian fourier filter.
The array is multiplied with the fourier transform of a Gaussian
kernel. If the parameter n is negative, then the input is assumed to be
the result of a complex fft. If n is larger or eq... | c71f7ede1be4a36b4ef17ce2744eff3b28ebbb67 | 38,004 |
def amplitude_kurtosis(data):
"""
(list) -> float
pass in an array or list and return the kurtosis value of data. Using Pearson's definition
>signal_skewness([3,7,8,9,1])
1.4904
"""
return stats.kurtosis(data, fisher=False) | d2db4844a5af8f16ea185a77d6de2e9c4a3e96d9 | 38,005 |
import numba
def mh_sample(
logtarget,
x0,
sigma=None,
discrete=None,
args=(),
n_burn=1000,
n_steps=1000,
tune_interval=100,
variable_names=None,
return_acceptance_rate=False,
):
"""
Parameters
----------
logtarget : function
The function to compute the ... | 2d17487960f8fd54f387044fb4ca4e652bf6faa5 | 38,006 |
from io import StringIO
def load(data):
"""loads the given byte-string representation to an object"""
stream = StringIO(data)
return _load(stream) | 0858e4ed8fd8631afbdb346e6733281b7893ce1b | 38,007 |
import torch
def drop_path(x, drop_prob: float = 0., training: bool = False):
"""
Obtained from: github.com:rwightman/pytorch-image-models
Drop paths (Stochastic Depth) per sample (when applied in main path
of residual blocks).
This is the same as the Dro... | 20c9321efd7763f8f6aa25b1e69c6db48dbf8a70 | 38,008 |
import json
def get_db_object(db_name) -> object:
"""
:type db_name: object
:return: pymongo client object
"""
db_handle = db_cache.get_db_cache(db_name)
if not __is_empty(db_handle):
__logger.info("sending db object from cache!")
return db_handle
else:
__logger.... | 32fe6cd2577553e593eda6727913fcd324b5e89f | 38,009 |
import torch
def test_value_network():
"""
Test if the CartPole value network is invariant
"""
network = BasisCartpoleNetworkWrapper(1, [64, 64])
layer = BasisCartpoleLayer(64, 1, out="invariant")
representations = get_cartpole_state_group_representations()
p_m2 = representations[1].deta... | dd9093ab1669ce82cc6cbbd3aa1718d50868f08b | 38,010 |
def tokenize(obj, tokenizer, max_seq_len):
"""Recursively convert to tokens."""
if isinstance(obj, str):
toks = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(obj)[:max_seq_len])
assert all(
[t < len(tokenizer.encoder) for t in toks]
) # all(toks < len(tokenizer.encoder)... | 9e8ae8a4c1af0df29d95afcef183851792af2b43 | 38,011 |
def manifest_to_file_list(manifest_fn):
"""
Open a manifest file and read it into a list.
Entries in the list are relative, i.e. no leading
slash.
manifest_fn -- the manifest file to read
"""
image_manifest_list = []
with open(manifest_fn) as image:
image_manifest_list = [x[1:] ... | 982f02e0b00fad20af8d50d44673d65d9bba5a37 | 38,013 |
import warnings
def perform_climatology_esp(
model_name, forecast_date, forecast_duration, workdir=None, **kwds
):
"""
This function takes the model setup and name as well as forecast data and duration and returns
an ESP forecast netcdf. The data comes from the climatology data and thus there is a mec... | 29a91ef8867fe361a5a640a648b5a0737fd5cc88 | 38,014 |
def get_fp(list_of_smi):
""" Function to get fingerprint from a list of SMILES"""
fingerprints = []
mols = [Chem.MolFromSmiles(x) for x in list_of_smi]
# if rdkit can't compute the fingerprint on a SMILES
# we remove that SMILES
idx_to_remove = []
for idx,mol in enumerate(mols):
try:... | 1ff1541f7e50b01a1ab2332dca9fd6af8d7c6ddc | 38,016 |
def intersect (sequence_a, sequence_b):
"""Return true if the two sequences contain items in common
If sequence_a is a non-sequence then return false.
"""
try:
for item in sequence_a:
if item in sequence_b:
return 1
except TypeError:
return 0
return 0 | f28c3b6258584fdc1821c65867b4d89a1c33373a | 38,017 |
def compileOverlapData(uniA,uniB,sigA,sigB,chrList):
"""
Piles-up the overlap coverage data for the fisher exact test.
:param uniA: Interval Universe A
:param uniB: Interval Universe B
:param sigA: Interval Significant A
:param sigB: Interval Significant B
:param chrList: List of chromosome... | 10aade88348682e31ebffc3d435eb92db943eeb0 | 38,019 |
def get_location_dictionary(deployment):
""" Construct location dictionary from ui deployment information.
"""
try:
have_location_dict = False
latitude = None
longitude = None
location = None
depth = None
orbitRadius = None
if 'depth' in deployment:
... | 3c2b00c97c681d89628ca8c6708545b73bf84649 | 38,020 |
def __insert_color(txt,s,c):
"""insert HTML span style into txt. The span will change the color of the
text located between s[0] and s[1]:
txt: txt to be modified
s: span of where to insert tag
c: color to set the span to"""
return txt[:s[0]]+'<span style="color: {0};">'.format(c)+\
t... | 013c011737f9b763aa8682a945883c934c99b5cd | 38,021 |
def legacy_do_linear_gst(dataFilenameOrSet, targetModelFilenameOrObj,
prepStrsListOrFilename, effectStrsListOrFilename,
gaugeOptParams=None, advancedOptions=None, comm=None,
memLimit=None, output_pkl=None, verbosity=2):
"""
Perform Linea... | cfedd3db88329a815ed1fb0ea5ab4a7de99f8931 | 38,022 |
def StopAddHeaders(builder, headers):
"""This method is deprecated. Please switch to AddHeaders."""
return AddHeaders(builder, headers) | b849725aae10132d5b41f316643cdc75a35c2d70 | 38,023 |
from typing import List
def select_dominoes(dominoes: List[str], order: int, num_players: int) -> str:
"""Randonly generate a set of dominoes for a player
- If the number of players is 3, each player gets 9 dominoes,
plus a 10th dominoe that is to be played first (all players will get it)
- If the num... | c96d1a5b54e3623807ca57a3684f63fa3ff6737c | 38,024 |
def fspecial_average(hsize=3):
"""Smoothing filter"""
return np.ones((hsize, hsize))/hsize**2 | ba095b58c994a1b12646093ebc05cd49b2854143 | 38,025 |
from typing import Union
from typing import List
from typing import Optional
async def getTwitchChannelUsers(cls:"PhaazebotTwitch", **search) -> Union[List[TwitchUserStats], int]:
"""
Get channel levels and stats.
Returns a list of TwitchUserStats().
Optional 'search' keywords:
---------------------------
* `u... | cf4c1e3ac2c8b3399ac64a41dcfc52cceb187067 | 38,026 |
def normalize_times(times, events):
"""Given a list of times and event ids, normalize the times (i.e. calculate
the time since the start of each event).
:param times: list of times
:type times: list
:param events: list of event ids
:type events: list
:return: list of normalized times
:... | 97a65dcd3fffcb8f9d686649e31a579ff104eb64 | 38,027 |
import hashlib
import hmac
def salted_hmac(key_salt, value, secret):
"""
Return the HMAC-SHA1 of 'value', using a key generated from key_salt and a
secret. A different key_salt should be passed in for every application of HMAC.
"""
assert secret, f"secret must be provided."
key_salt = bytes(... | 6b8a3cb4998f2c00d25ae1cee3f88bd39fabe6fe | 38,028 |
import dis
def _opcode(name):
"""Return the opcode by name from the dis module."""
return dis.opmap[name] | d2c8612138c94da68adcc1b8979395987090157c | 38,029 |
def validate_compare_input(message):
"""
validate input for function that compare two songs
:param message: message received by microservice
:type message: `dict`
:return: tuple with status and error message
:rtype: `tuple`
"""
input_schema = {
"type": "object",
"require... | 117fcbe275b795bacb82232c7a5ae10110b213a8 | 38,030 |
def _gcp_agent_singleton(**kwargs):
"""Manage singleton of agents to particular apis.
This treates the agent instances as singletons based on their configuration.
The reason for this is simply to reduce logging noise on the creation.
This is possible since agents are stateless.
Args:
kargs: [kwarg... | 1ec653d4de200070f2bf0b11d97b6ae713991e82 | 38,032 |
def get_media_playlist_uris(master_playlist, target_qualities):
"""From a master playlist, extract URIs of media playlists of interest.
Returns {stream name: uri}.
Note this is not a general method for all HLS streams, and makes twitch-specific assumptions,
though we try to check and emit warnings if these assumpti... | 1cb7302eb14c5b980e77a8a5907edb9cbcddb279 | 38,033 |
def layer_stack_from_hparams(hparams, prefix):
"""Create a layer stack based on the hyperparameter values."""
layers = hparams.get(prefix + "layers")
return transformer.LayerStack(
[layers_registry[l](hparams, prefix) for l in layers],
dropout_rate=hparams.layer_prepostprocess_dropout,
norm_epsi... | 220d4f71a4e270985d6d7560719f7c7f83e99781 | 38,035 |
def resample_profile(profile, periods):
"""
Resamples a profile to have the number of periods defined by periods.
Uses the mean of the period. The end point of the period is used as the
index.
Parameters
----------
profile : np.Array, pd.Series or pd.DataFrame
An array like object ... | 7cd49aeec0cf43b49c1e884483830fd9485d5202 | 38,036 |
def rs_compose_add(p1, p2):
"""
compute the composed sum ``prod(p2(x - beta) for beta root of p1)``
Examples
========
>>> from sympy.polys.domains import QQ
>>> from sympy.polys.rings import ring
>>> from sympy.polys.ring_series import rs_compose_add
>>> R, x = ring('x', QQ)
>>> f ... | c82c3c19087fea7230f20f0da14b4facce4b4a49 | 38,037 |
import re
def remove_citation(paragraph: str) -> str:
"""Remove all citations (numbers in side square brackets) in paragraph"""
return re.sub(r'\[\d+\]', '', paragraph) | dc88606e69187143d767215ddc098affdbd185d5 | 38,039 |
def parse_proxy(line):
"""Parses proxies from a string.
Args:
contents: The string that should be parsed.
Returns:
The parsed proxy.
"""
proxy = None
if not (line.strip().startswith('#') or line.strip().startswith('//')):
tokens = line.replace('\n', '').split(' ')
try:
... | 1a5583c689a6cd655265c308d3cfc9b84783f7aa | 38,040 |
import ctypes
def sg_get_pdt_str(pdt):
"""
Yield string associated with peripheral device type (pdt). Returns
'buff'. If 'pdt' out of range yields "bad pdt" string.
"""
buff = _get_buffer(48)
libsgutils2.sg_get_pdt_str(pdt, 48, ctypes.byref(buff))
return buff.value.decode('utf-8') | 4b1a45d43c3a848dfd814d18ade300712b081b28 | 38,041 |
def simulation_positions(simulation):
"""
Return atomic coordinates.
Parameters
----------
simulation : Simulation or Context object.
Returns
-------
ndarray
"""
state = simulation_state(simulation, 'positions')
return state.getPositions(asNumpy=True) | f83e042010b65bd9bfab150b90b5821c66b555e6 | 38,043 |
def regex(value, regexflags=None):
"""OpenEmbedded 'regex' type
Acts as a regular expression, returning the pre-compiled regular
expression pattern object. To use this type, set the variable type flag
to 'regex', and optionally, set the 'regexflags' type to a space separated
list of the flags to c... | 18eea0ed097dc530f98fddd88816e133e8ef5e54 | 38,044 |
import torch
def normalized_distance(x, y):
"""Distance between two vectors normalized by the number of elements and
the norm of the first vector"""
return distance(x, y) / torch.sqrt(norm(x) * norm(y)) | 846d176a5c536d93ef164a63b582fa541d304686 | 38,045 |
def lv_encode(data: bytes) -> bytes:
"""Encodes data as length-value"""
return serialize_length(len(data)) + data | 1858d3165c7fb714877be2c3448fe162678ceaa4 | 38,047 |
def get_model_field(model):
""" get the verbose_name of all fields in the model """
field_dict = dict()
for field in model._fields:
attr = getattr(model, field)
if hasattr(attr, 'verbose_name'):
verbose_name = attr.verbose_name
if verbose_name:
field_d... | 8ec9a4f9b571483c13d5a23330e98691279c12ad | 38,049 |
from typing import Callable
def _get_create_str_fn(opt: str) -> Callable:
""" A tool function to create either a str or bytes from a 8-bit string. """
def _create_str_bytes(name: bytes) -> bytes:
return name
def _create_str_str(name: bytes) -> str:
return name.decode("latin-1")
if op... | fab4e8065cfc450eda5bcccdce1888941f2f7f25 | 38,050 |
def admin_required(func):
"""
This is a decorator that can be applied to a Controller method that needs to allow request to process only if checks
are successful.
It checks:
- if the user is logged in (And)
- if the user is an admin
The current object is fetched using the Controller in... | a8d25f7c9b515c10b3fc71bd1b1819dbc2f37a8d | 38,051 |
def get_expected_tetranuc_freq(tetranuc, trinuc_freqs, dinuc_freqs):
"""
Returns the expected frequency for the given tetranucleotide.
Args:
tetranuc:
trinuc_freqs:
dinuc_freqs:
Returns:
"""
# get prefix of len 3 of tetranucleotide (n1n2n3)
first3bases = tetranuc[:3]
... | 35c99fa43e771bb5744aa0dd0f2877bcacc7e478 | 38,052 |
import math
def computeLengthsAndAngles(periodicBoxVectors):
"""Convert periodic box vectors to lengths and angles.
Lengths are returned in nanometers and angles in radians.
"""
if is_quantity(periodicBoxVectors):
(a, b, c) = periodicBoxVectors.value_in_unit(nanometers)
else:
a, b... | a18601a111b1ef624e828e87dd4b0ddb1fa44e76 | 38,053 |
def compute_info( image ):
""" Compute information on resampled and original images """
old_size, old_spac, old_orig = image.GetSize(), image.GetSpacing(), \
image.GetOrigin()
new_size, new_spac, new_orig = [], [], old_orig
for i in range(len(old_size)):
new_size.append( int(np.ceil( 1... | 3989149b2bbeb89ffea62ec13161f10c00b285d5 | 38,054 |
def macro_EmbedObject(macro, target=wikiutil.required_arg(unicode), pagename=None,
width=wikiutil.UnitArgument(None, float, ['px', 'em', 'pt', 'in', 'mm', '%'], defaultunit='px'),
height=wikiutil.UnitArgument(None, float, ['px', 'em', 'pt', 'in', 'mm', '%'], defaultunit='px')... | 0c69842efcd1cb9240053fca9c291be0fa5eeaa5 | 38,055 |
def lnprior(theta, y, lower_t_bound, upper_t_bound, transit_params,
skip_priors):
"""
Log prior for `emcee` runs.
Parameters
----------
theta : list
Fitting parameters
y : `numpy.ndarray`
Fluxes
lower_t_bound : float
Earliest in-transit time [JD]
uppe... | 5a35211e8a0138757ad490fa77f31e515ec69181 | 38,056 |
def job_metadata_filename(metadata):
"""Construct relative filename to job metadata."""
return "data/{metadata}".format(metadata=metadata) | bb5e8dc6c0ec50fed6801b9c67f8234d9115372a | 38,057 |
def get_db_cols(cur, table_name, schema='public', type_map=True):
"""
Gets the column names of a given table
if type_map is true, returns also a dictionary
mapping each column name to the corresponding
postgres column type
"""
db_cols_sql = """SELECT column_name, data_type
FROM in... | 936952ea0bbc0c165f089e700828ea876d30ec16 | 38,058 |
def wrap_elemwise(func, **kwargs):
""" Wrap up numpy function into dask.array """
f = partial(elemwise, func, **kwargs)
f.__doc__ = func.__doc__
f.__name__ = func.__name__
return f | ae480423fba7e1c01a41de5e4b61c629439dd1e5 | 38,059 |
def parse_player_node(player_node):
"""Parses a player XML node
Parameters
----------
player_node : lxml node
The player node to parse
Returns
-------
A Player database object
"""
db_player = Player(player_id=player_node.get('id'),
first=player_node.g... | e69dd475cdfc9ff4017a0c76b0387a959f25a590 | 38,060 |
import six
def is_fits(input, **kwargs):
"""
Determine whether input is in FITS format
"""
if isinstance(input, six.string_types):
if input.lower().endswith(('.fits', '.fits.gz',
'.fit', '.fit.gz',
'.fits.Z', '.fit.Z')):
... | e504fac14f3fe4d470bd84a600e622abc17da609 | 38,061 |
def calc_moverscore(gold_references, model_generations, n_gram=2, batch_size=16):
"""
Calculate MoverScore
:param gold_references: list of target sections
:param model_generations: list of generated sections
:param n_gram: unigram-based MoverScore (n-gram=1), bigram-based MoverScore (n-gram=2)
... | b4deaaf8a0a1c79dee00c5c920b0d832e7f2545a | 38,062 |
def base62_encode(raw_bytes):
"""
Encodes raw bytes into base-62 representation. URL-safe and human safe.
Encode your Unicode strings to a byte encoding before base-62-encoding
them.
Convenience wrapper for consistency.
:param raw_bytes:
Bytes to encode.
:returns:
Base-62 encoded bytes.
"... | 020a0746088902d87a217b0771096e9e41c89dbf | 38,063 |
import torch
def cmc_score_count(
distances: torch.Tensor, conformity_matrix: torch.Tensor, topk: int = 1,
) -> float:
"""
Function to count CMC from distance matrix and conformity matrix.
Args:
distances: distance matrix shape of (n_embeddings_x, n_embeddings_y)
conformity_matrix: bi... | 14519d349a55f3b5ea6f87f830af183441b86573 | 38,064 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.