content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def load_randomly_augmented_audio(path, sample_rate=16000, tempo_range=(0.85, 1.15),
gain_range=(-6, 8)):
"""
Picks tempo and gain uniformly, applies it to the utterance by using sox utility.
Returns the augmented utterance.
"""
low_tempo, high_tempo = tempo_range
... | 9a4e60baee40723a81efb1aa88682e32482f6d48 | 71,816 |
from datetime import datetime
def readable_timestamp(stamp):
"""
:param stamp: A floating point number representing the POSIX file timestamp.
:return: A short human-readable string representation of the timestamp.
"""
if date.fromtimestamp(stamp) == date.today():
return str(datetime.fromti... | 734f623052bed8171829307a07c82ad76760a9c3 | 71,817 |
def mention(sourceURL, targetURL, vouchDomain=None):
"""Process the Webmention of the targetURL from the sourceURL.
To verify that the sourceURL has indeed referenced our targetURL
we run findMentions() at it and scan the resulting href list.
"""
app.logger.info('discovering Webmention endpoint for... | 3e36cf5aeca306061478cfadd2c7d6f755c233b3 | 71,819 |
def create_lasso_model(**kwargs):
"""Create lasso regression
:return: id_model, unique str
"""
model = linear_model.Lasso(**kwargs)
id_model = _save_estimator(model=model, type_model="lasso_regression")
return id_model | fd789d828794d5eb515a274bb702f87ec92cc7f8 | 71,820 |
def legacy_network_info(network_model):
"""
Return the legacy network_info representation of the network_model
"""
def get_ip(ip):
if not ip:
return None
return ip['address']
def fixed_ip_dict(ip, subnet):
if ip['version'] == 4:
netmask = str(subnet.a... | ad220b501b56e9c760c758dec4c9c03f8cd9394a | 71,821 |
def load_ensemble_models(name, limit=100):
"""Load serialized ensemble model objects that share the same name from table."""
response = DB_HANDLE.get_records(table_name=ENSEMBLE_MODEL_TABLE_NAME, offset=0, limit=limit,
options={"expression": "(name='" + str(name) + "')"})
... | 133371cd7f5ae77af65b40164f5e58895e13d2b0 | 71,822 |
def r_precision(r):
"""Score is precision after all relevant documents have been retrieved
Relevance is binary (nonzero is relevant).
>>> r = [0, 0, 1]
>>> r_precision(r)
0.33333333333333331
>>> r = [0, 1, 0]
>>> r_precision(r)
0.5
>>> r = [1, 0, 0]
>>> r_precision(r)
1.0
... | aec9362023a8cf146a869f081cf25e9589e3bee1 | 71,823 |
def pieChartInfoPlus(trips):
"""
Calculates the total distance per activity mode
Parameters
----------
trips : dict - Semantic information (nested)
Returns
-------
list(data): list - labels of the activity modes
list(data.values()): list - distance per activity mode
"""
la... | ad0306b2561b01a33c509b2c454f464e9c6ff8a3 | 71,824 |
from typing import Any
from typing import Optional
from typing import Dict
import json
def json_dumps(data: Any, **kwargs: Optional[Dict[str, Any]]) -> str:
"""Safe serialization of a Python dictionary to JSON string representation using all known encoders.
Parameters
----------
data : Any
A e... | f1ad879d42dc28d4be38faa75fdc3193aba35e22 | 71,825 |
def sample_maximizers_simple(model, count, num_discrete_points):
"""
Samples maximizers from the GP by sampling real values at each discrete point and finding the argmax
:param model: gpflow model
:param count: number of maximizers
:param num_discrete_points: number of discrete points over input spa... | ccb9fbdcf7ef7526a0c83163ab748515ab001755 | 71,827 |
def test_cli_with_string_annotation():
"""Test to ensure CLI's work correctly with string annotations"""
@hug.cli()
def test(value_1: 'The first value', value_2: 'The second value'=None):
return True
assert hug.test.cli(test, True) | b02395d3d0da48c7be600ce5b09e7fa822cda388 | 71,828 |
def sigma_exp(p, q):
"""
Returns score of an expansion/compression.
(Kondrak 2002: 54)
"""
q1 = q[0]
q2 = q[1]
return C_exp - delta(p, q1) - delta(p, q2) - V(p) - max(V(q1), V(q2)) | e96f547032adec1b099c305d0a18a93959f62128 | 71,829 |
def user_is_anonymous( user_name_or_id ):
"""
Determine if the user name or ID corresponds to
the anonymous user.
"""
try:
user_name_or_id = int(user_name_or_id)
except:
pass
if type(user_name_or_id) in [str, unicode]:
if user_name_or_id.lower() == "anonymous":
... | 6687adec454df9bbc1c942d291a934dd63f7dae3 | 71,830 |
import logging
def subinit4_initGenUnits(PATHS, PPdb, config):
"""Initializes the GenUnit instances. Returns two containers:
1) GenFleet, a Series of GenUnit idx : GenUnit instance
2) GenCos, a dictionary of generator company (str) : GenUnit indices* belonging to that gen co
*Used to subset GenFleet and PPdb.... | f4c74e5b06f91206769e865d87a15d00d46c63c5 | 71,831 |
def kalman_predict(density, motion, dt):
"""得到KF的预测(Density类):density:Density类的实例,motion:motionModel,dt:sampling time"""
F = motion.F(density.x, dt)#F
x = motion.f(density.x, dt)#xkk_1=F*xk_1
P = F @ density.P @ F.T + motion.Q(dt)#Pkk_1 = F*Pk_1*F'+Q
return Density(x=x, P=P) | e5f4110a22b20b793eb5707658ada139911542f5 | 71,832 |
import socket
def is_multicast(address):
"""Return ``True`` iff address is a multicast address.
This function is used to eliminate retransmissions for confirmable
messages sent to multicast addresses.
:param address: A socket address as supported by the Python socket
functions: i.e. a pair (... | 4177933096f85c6c303fc8c1f491ce8848e8957d | 71,833 |
def onestep_reachability(p_center, ssm, k_ff, l_mu, l_sigma,
q_shape=None, k_fb=None, c_safety=1., a=None, b=None,
t_z_gp=None):
""" Overapproximate the reachable set of states under affine control law
given a system of the form:
x_{t+1} = \mathcal{N}(\... | 5ae4ebd0aa2d30d5ff0cdf02bd09f2f29fa4c9d9 | 71,834 |
def pathname(question, aid="pathname", absolute=False, must_exist=False, **kwargs):
"""Asks user for pathname, returns path."""
parser = abspath if absolute else normpath
validf = lambda p: exists(p) if must_exist else always_true
p_func = partial(process, parser, validf)
return ask(question, aid=ai... | db6de1a6f6fd6ae9ed7ee463dff7cf777ad232d3 | 71,835 |
def areDefined(names, dic):
"""
Return True if all keys that have "names" are defined and are not "None".
"""
key_list = dic.keys()
names = toList(names)
for aName in names:
if aName not in key_list: return False
if dic[aName] == None: return False
else:
return True | d601804ad5d6eeb1cbfd32e64cbc4a0452beb17a | 71,836 |
def is_weekend(date):
""" returns True if day is on a weekend """
date = hlp.strip_date(date)
return FederalHoliday(date).weekend | 20f981f3c4cc5629350b47057669b95698f17066 | 71,837 |
def get_num_tasks(path: str) -> int:
"""
Gets the number of tasks in a data CSV file.
:param path: Path to a CSV file.
:return: The number of tasks.
"""
return len(get_header(path)) - 1 | f592fa3f4a220b6888e915d6407f6de64fd046e6 | 71,838 |
def backbone_indices(mgrph):
""" heavy atoms and hydrogen atoms not connected to heavy atoms
"""
hv_idxs = heavy_atom_indices(mgrph)
hy_idxs = tuple(idx for idx in hydrogen_atom_indices(mgrph) if
all(idx > nidx and atom_symbol(mgrph, nidx) == 'H'
for nidx in a... | 3b75df66951a4c34416446c274b76ba2e76d89d1 | 71,839 |
def get_users(session, giveaway_url):
"""Get users that entered the given giveaway
The function will loop through different available pages of the users list
:param session: SG object HTMLSession
:param giveaway_url:
:return: List of Strings (usernames)
"""
if giveaway_url[-1] != "/":
... | 31e24b095b1d0058630e5e8cff2538363e10479b | 71,841 |
def interest_submit():
"""
"""
if current_user is None:
flash('You must be logged in to submit interests!', 'danger')
return redirect(url_for('account.login', next=request.path))
form = SubmitForm(request.form)
user_id = current_user.id
if form.validate_on_submit():
nam... | 5eece1116149fe1d7df291f9ff31881b41baf36f | 71,842 |
def _dense_to_one_hot(labels, num_classes):
"""Convert class labels from scalars to one-hot vectors."""
num_labels = labels.shape[0]
index_offset = np.arange(num_labels) * num_classes
labels_one_hot = np.zeros(
shape=(num_labels, num_classes), dtype=np.uint8
)
labels_one_hot.flat[index_offset + labels.r... | 931a471d318ac43d43d37dced270b50bd53b2bce | 71,843 |
import collections
def update(dictionary, updateDict):
"""
Generic function for updating dictionaries
:param dictionary: old dict object
:param updateDict: new dict object
:return: updated dict
"""
for k, v in updateDict.items():
if isinstance(v, collections.Mapping):
d... | 66ae8ea0e41c6e4794ee57d8e276059a983b6043 | 71,846 |
def gen_data(dtype1, dtype2, shape1, shape2):
"""generate valid test data for truncate_div"""
input1 = random_gaussian(shape1).astype(dtype1)
input2 = random_gaussian(shape2).astype(dtype2)
input2 = np.where(input2 == 0,
np.ones_like(input2),
input2)
expec... | 5c332934fee1abc567a109a9c6855c5dd4be10d6 | 71,847 |
def get_user():
"""
:return: User
"""
return getattr(_tls, 'user', None) | 2fa3ad1780eb22397f368d9009d8610a3a33c3c1 | 71,851 |
def get_node_list():
"""returns a list of tuple with node_address and status as items"""
node_list = list()
cmd = "/opt/vertica/bin/admintools -t list_allnodes"
out, err = run_os_command(cmd)
if out:
#node extraction logic goes here
else:
print("Error occured: {}".format(err))
... | dbc54954f615b14e4dd3d57437b312d61ab491bc | 71,852 |
def create_webdriver():
""" Creates a chrome webdriver with custom options"""
options = webdriver.ChromeOptions()
options.add_argument("--headless")
# options.add_argument("window-size=1400,900")
options.add_argument("--incognito")
options.add_argument("--ignore-certificate-errors")
WEBDRIVE... | 5cd145fa57fb1d705a07f9c0d5f6eaf02f7c921d | 71,853 |
import re
def object_string_formatter( s, **kwargs):
"""
Makes attributes of object passed in as keyword
arguments available as {OBJECTNAME.ATTRNAME} in
the passed-in string and returns a string with
the above arguments replaced with the attribute
values of the corresponding object.
E... | b5c25088c550e494fe141b426557be94cd43037e | 71,854 |
def fillna(groupby, value=None, method=None, axis=None, limit=None, downcast=None):
"""
Fill NA/NaN values using the specified method
value: scalar, dict, Series, or DataFrame
Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame
of values specifying which value ... | 6aa8a8cbc8beffc5c2526dd03585fa7d90b0e42d | 71,855 |
def read_sbtabs(f):
"""Return reactions, fluxes, keqs, bounds."""
sbtabs = SBtabTools.openMultipleSBtabFromFile(f)
tdict = dict([(t.getTableInformation()[1].upper(), t) for t in sbtabs])
expected_tnames = ['REACTION', 'RELATIVEFLUX', 'REACTIONCONSTANT',
'CONCENTRATIONCONSTRAINT']
... | 6d4db68d988bb794ec6ee23c452e071fa0b1c663 | 71,856 |
def remove_pointer(type):
"""removes pointer from the type definition
If type is not pointer type, it will be returned as is.
"""
nake_type = remove_alias( type )
if not is_pointer( nake_type ):
return type
elif isinstance( nake_type, cpptypes.volatile_t ) and isinstance( nake_type.base... | 3e5dde64c39994d2435368f2e8b205ae24463d18 | 71,857 |
def get_dbtype(f):
"""Opens input fasta file, examines the first 10 records, and returns
either 'prot' or 'nucl' depending on what type the sequences are.
"""
# Get sequence to evaluate.
concat_seq = ''
# Determine file type.
filetype = None
with open(f) as infh:
for... | 966b87dcee4484737cb3e1e4ff665fad1b4f7fec | 71,858 |
def _gr_spline3_ ( graph , opts = 'b1e1', *args ) :
"""Get 3-spline for the given graph
>>> graph = ...
>>> spline = graph.spline3()
- see ROOT.TSpline3
"""
prev_hash , spline3 = 0 , None
attr = '__hash_spline3'
if hasattr ( graph , attr ) :
prev_hash , spline3 = ge... | bc3243238604dadae21e32e84e56157759c1000e | 71,859 |
def book_parser(book_html, date, status):
"""
Парсит html-узел с книгой
:param book_html: html-узел с книгой
:param date: string or None - дата прочтения
:param status: string - статус книги
:return: Book or None
"""
book_data = handle_xpath(book_html, './/div/div/div[@class="brow-data"]... | 56a717814742360499f5de90a84d46990b0de456 | 71,860 |
def lock(func):
"""装饰器, 用在func方法执行前后, 增加运行信息"""
def wrapper(*argv):
data = None
mutex.acquire()
data = func(*argv)
mutex.release()
return data
return wrapper | 9efec55952f836caff5be0c844faf6fed1ade04a | 71,861 |
from typing import OrderedDict
def gen_list_pcs_to_check(duthost, mg_facts, collect):
"""
Generate list of mclag interfaces to check
Args:
duthost: DUT host object
mg_facts: Dict with minigraph facts for each DUT
collect: Fixture which collects main info about link connection
"... | b49adb6dcc2d5c69721b9e21e41a3529789a559f | 71,863 |
def make_image_loader_factory():
"""Generate a factory function for constructing image loaders.
Invoke the returned factory function by passing the name of the image
loader class you want to construct, followed by the parameters for the
constructor as named arguments
(e.g., factory('Directory', dir... | fc9a19d936e20ed6777a489cf52c0755e7612465 | 71,864 |
def sample_mask(idx, l):
"""Create mask."""
mask = np.zeros(l)
mask[idx] = 1
return np.array(mask, dtype=np.bool) | e06dd489b2518e305c34381b4e1f41dfdc555416 | 71,865 |
import codecs
def jsonfile_to_docs(filename):
"""
:type filename: str
"""
f = codecs.open(filename, 'r', encoding='utf-8')
docs = jsonpickle.decode(f.read())
""":type: list[text.text_theory.Document"""
f.close()
return docs | 524676189db126c4622f117e84f7a1dfb19b8daa | 71,866 |
def company_with_investment_projects_factory():
"""Factory for a company with investment projects."""
company = CompanyFactory()
for field in INVESTMENT_PROJECT_COMPANY_FIELDS:
InvestmentProjectFactory(**{field: company})
return company | a9ea1f5dacc17a24ae2cba923c76455a114d367b | 71,867 |
def create():
"""
Create Address Function
---
/api/addresss/address:
post:
summary: Create Adress Function.
security:
- APIKeyHeader: []
tags:
- Address
requestBody:
description: Adress Functions
required: true
content:
application/js... | 46e72e4f3e21b2e1e8b87b5556daceb2d127aa54 | 71,868 |
def format_tag(organization, standard, version, tag_name):
"""
Format a YAML tag.
"""
tag = "tag:{0}:{1}/{2}".format(organization, standard, tag_name)
if version is None:
return tag
if isinstance(version, AsdfSpec):
version = str(version.spec)
return "{0}-{1}".format(tag, ... | 9d37cb7a8dd892862fb4e34c366679e8ebf48c66 | 71,869 |
def constrained_sage_poly_dual(f, gs, p=0, q=1):
"""
Compute the dual f_{SAGE}^{(p, q)} bound for
inf f(x) : g(x) >= 0 for g \in gs.
:param f: a Polynomial.
:param gs: a list of Polynomials.
:param p: a nonnegative integer,
:param q: a positive integer.
:return: a CVXPY Problem th... | 427f48514943817acb0d53e01f80400ec909a60f | 71,870 |
def findCharacter(stringList, patternCharacter):
"""
Find the specific character from the list and return their indices
"""
return([ind for ind, x in enumerate(list(stringList)) if x == patternCharacter]) | 32cc8fb5970c6cd3cefd161b9e13e340f1645d13 | 71,871 |
from . import retinanet
from . import retinanet_nl
def vgg_retinanet(num_classes, backbone='vgg16', inputs=None, modifier=None, channels=None, **kwargs):
""" Constructs a retinanet model using a vgg backbone.
Args
num_classes: Number of classes to predict.
backbone: Which backbone to use (one... | 1cb29dea06ccab5505b2929c185cc9e66be2f8cf | 71,872 |
def identify_ridge_lines(matr, max_distances, gap_thresh):
"""
Identify ridges in the 2D matrix. Expect that the width of
the wavelet feature increases with increasing row number.
Parameters
----------
matr: 2-D ndarray
Matrix in which to identify ridge lines.
max_distances: 1-D seq... | a9ce20c62ed906d67bdc274cc0ec3f62659dd3f8 | 71,873 |
import ast
def TildeDetect(word):
"""Detect tilde expansion in a word.
It might begin with LiteralPart that needs to be turned into a TildeSubPart.
(It depends on whether the second token begins with slash).
If so, it return a new word. Otherwise return None.
NOTE:
- The regex for Lit_TildeLike could... | 0393ae754f38997faaaafebd427195c1da5434ea | 71,874 |
from typing import Dict
from typing import OrderedDict
def state_dict2numpy(state_dict) -> Dict[str, np.ndarray]:
"""Convert Pytorch state dict to list of numpy arrays."""
np_state_dict = OrderedDict()
for param in list(state_dict):
np_state_dict[param] = state_dict[param].numpy()
return np_st... | c4ad8feae42a312e0fff5743795d86ab6ae1e5b4 | 71,875 |
def drop_levels(index, levels):
"""Softly drop `levels` in `index` by their name/position."""
if not isinstance(index, pd.MultiIndex):
return index
levels_to_drop = []
if not isinstance(levels, (tuple, list)):
levels = [levels]
for level in levels:
if level in index.names:
... | 76baa12d0d109ef965298c9af0651dfd181bf604 | 71,876 |
from pathlib import Path
def figure_test(test_function):
"""
A decorator for a test that verifies the hash of the current figure or the
returned figure, with the name of the test function as the hash identifier
in the library. A PNG is also created in the 'result_image' directory,
which is created... | a233dec64356892f2f0397ea79aac172f5d870b7 | 71,878 |
from typing import Optional
def _set_access_token(username : str, access_token : str,
connect_string : str) -> Optional[str]:
"""
Sets the access_token for the connect request by doing the following:
1. retrieves the token configured for the connect_string from ... | d8f80106259e9db5bf23b4272dffa5b8ea1dc19e | 71,879 |
from typing import List
def test_catch_deep_task_react(scheduler: Scheduler) -> None:
"""
Catch should react to new task hashes deep in the workflow.
"""
@task()
def deep(denom):
calls.append("deep")
return 1 / denom
@task()
def safe():
calls.append("safe")
... | 7f9b0c6e66eb07fbdd891e6ab56f223142b69b96 | 71,881 |
def try_pop(d, key, default):
"""
>>> d = {"a": "b", "c": "d", "e": "f"}
>>> try_pop(d, "g", "default")
'default'
>>> d
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> try_pop(d, "c", "default")
'd'
>>> d
{'a': 'b', 'e': 'f'}
"""
value = d.get(key, default)
if key in d:
d.... | 7f5c5def5363882a070cac5749be584e1a8e2e14 | 71,882 |
from typing import Optional
import time
def hack_vigenere(text: str, test_id: str) -> Optional[str]:
"""Attempt to determine
Args:
text (str): The encrypted text we are trying to hack.
test_id (str): Specify whether using test one (known plaintext) or test two (dictionary attack)
Returns... | 835d114d7666fa8fdc661839fdf5930b1633a9c4 | 71,883 |
def cell_trap_getter_generator(priv_attr):
""" Generates a getter function for the cell_trap property.
"""
def getter(self):
if getattr(self, priv_attr) is None:
data =\
(
self.gfpffc_bulb_1 - self.gfpffc_bulb_bg
)/self.gfpffc_bulb_bg
... | 15217adbd96ce44b361444867e5d9c6d202440f4 | 71,885 |
def shared_blockchain_instance():
""" This method will initialize ``SharedInstance.instance`` and return it.
The purpose of this method is to have offer single default
bitshares instance that can be reused by multiple classes.
"""
if not SharedInstance.instance:
clear_cache()
... | 78fed0d63da2351fe721730b51fdac1bded7878a | 71,886 |
def check_punctuation(word):
"""
This detects the punctuation if the words start or end with punctuation,
and removes it by remove_punctuation_from _end if so.
"""
punctuation = PUNC.value
while len(word)>0 and (word[0] in punctuation or word[-1] in punctuation):
word = remove_punctuatio... | 16ba6b2f62bb9127583df9e193d5432193e5ed5a | 71,887 |
def euclideanDistance(x_a, x_b):
"""
Calculates the Euclidean distance between two vectors
Arguments:
x_a (np.array): shape [m_features, ] a single vector a
x_b (np.array): shape [m_features, ] a single vector b
Returns:
distance (float): Euclidean distance between vect... | 13b14eeaba4de3b3b3bf2888a232c67bae7d0f45 | 71,888 |
def recover_signature_object(data, format_type=BBcFormat.FORMAT_BINARY):
"""Deserialize signature data"""
sig = BBcSignature(format_type=format_type)
sig.deserialize(data)
return sig | 55eeb93a1d27bd25ea5fcfcfccb24912de65a5d1 | 71,889 |
def SoftmaxCE(name=None):
"""Create a softmax layer with integrated Multinomial Cross Entropy loss.
Applies the softmax activation function on 'default' input and puts
results (per-class probabilities) in 'predictions'.
It also takes class indices (0-based) as the 'targets' input,
and computes the... | a6e708af82a595c48e8170e048bc024de1cafaf4 | 71,891 |
async def test_custom_agent(hass, hass_client):
"""Test a custom conversation agent."""
calls = []
class MyAgent(conversation.AbstractConversationAgent):
"""Test Agent."""
async def async_process(self, text, conversation_id):
"""Process some text."""
calls.append((... | 14f89286a7a5c1898bab2c8c4abf21557e30efa5 | 71,892 |
def success(request):
"""
增删改操作成功之后返回这个页面
"""
return HttpResponse('success') | a6a03a5d85710a888da60460958eef7a253edb4a | 71,894 |
def insertion_as_lsp_data(position: Position, new_text: str) -> LSP_TextEdit:
"""
Convert an expanded `Insertion` to a Language Server Protocol compatible
dictionaries for display as JSON.
Note: in LSP line numbers are zero-based, while our `Position`s are
one-based.
"""
pos = {'line': posi... | 231167cbc3d573365d26cdccb879a51addb5694c | 71,895 |
def BOPDS_Tools_IsInterfering(*args):
"""
* Returns true if the type <theT> can be participant of an interference
:param theT:
:type theT: TopAbs_ShapeEnum
:rtype: bool
"""
return _BOPDS.BOPDS_Tools_IsInterfering(*args) | b36ed58fb4043024fea2028e1423286c6a63ee17 | 71,896 |
def get_L_dash_prm_etrc_OS_0():
"""主開口方向から時計回りに0°の方向の外気に面した玄関等の土間床等の外周部の長さ (m)
Args:
Returns:
float: 主開口方向から時計回りに0°の方向の外気に面した玄関等の土間床等の外周部の長さ (m)
"""
return get_table_3(32, None) | 3bb42fe76515da73615bd11ce0123c65f32c3d4a | 71,897 |
def create_environment(env_config):
"""Creates an interest evolution environment."""
user_model = IEvUserModel(
env_config['slate_size'],
choice_model_ctor=choice_model.MultinomialProportionalChoiceModel,
response_model_ctor=IEvResponse,
user_state_ctor=IEvUserState,
seed=env_config['... | 51ee0fd00d4502ea1c9a4b4c58238c07751c9f0f | 71,898 |
def neg_norm_probability_differences(detached_output, true_labels, loss):
"""
Calculates the difference between the two most probable classes and normalises it with tanh
such that the resulting difference is between 0 and 1. The inverse of this difference is taken.
This is multiplied by the current loss... | 805189107e5641cd5e2628ef21a5e5884aa91d08 | 71,899 |
def delete_partitions(rt_info, partitions):
"""
删除指定分区
:param rt_info: rt的字段和配置信息
:param partitions: 分区值集合
:return: 执行结果
"""
params = construct_connect_config(rt_info)
params[DELETE_PARTITION] = partitions
rsp = DataHubApi.iceberg_delete_partitions.create(params)
if not rsp.is_s... | 91c827f9b3e45fcc6bba3c9a17253283aefdee2c | 71,900 |
def jucesp_simple_driver():
"""
# Fazendo DEFIS
# Driver que armazena perfil e recebi caminho para download
:return: o driver.
"""
# __padrao = profile_path
# o try já tá dentro de replace
chrome_options = Options()
# chrome_options.add_argument("--headless")
chrome_options.a... | 77160587e1821b5a4db73cadf689e82f293df892 | 71,901 |
def generate_uncrypted_record(timestamp, input_template_text, key):
"""Generates formatted individual record and returns the iv and the record as a tuple.
Keyword arguments:
timestamp -- the timestamp for the record
input_template_text -- the input template text
key -- the key for the id
plaint... | 98cc6afebc732045078e2bae461e29b9016c6cf6 | 71,902 |
def kelvin_to_fahrenheit(kelvintemp):
"""
Converts a numeric temperature from Kelvin degrees to Fahrenheit degrees
:param kelvintemp: the Kelvin temperature
:type kelvintemp: int/long/float
:returns: the float Fahrenheit temperature
:raises: *TypeError* when bad argument types are provided
... | 20b26915c9e32a52dad04704937e685b068bd081 | 71,904 |
def delete_parameter_group(name, region=None, key=None, keyid=None, profile=None):
"""
Delete an RDS parameter group.
CLI Example:
.. code-block:: bash
salt myminion boto_rds.delete_parameter_group my-param-group \
region=us-east-1
"""
try:
conn = _get_conn(reg... | 94c49786d10c2f2eee3fd5d77d040f89166f87b2 | 71,908 |
def Start():
""" Renders the Home Page """
return render_template('Start.html') | a4bb3c7f16d89afaf701a9601fe80c163d77ce6c | 71,909 |
import random
def get_fast_smallworld_graph(N, k_over_2, beta, verbose=False):
"""
Loop over all possibler short-range edges and add
each with probability :math:`p_S`.
Sample :math:`m_L` from a binomial distribution
:math:`\mathcal B(N(N-1-k)/2, p_L`. For each edge
m with :math:`0\leq m\leq m... | 8fe43e228ec3e7ab88667e14c73c5932e4cb00bd | 71,910 |
def derive_ionmode(spectrum_in: SpectrumType) -> SpectrumType:
"""Derive missing ionmode based on adduct.
Some input formates (e.g. MGF files) do not always provide a correct ionmode.
This function reads the adduct from the metadata and uses this to fill in the
correct ionmode where missing.
Param... | 12e7d98bc2b9e35df67ccccc955e545c96f9b597 | 71,911 |
def channel_type(info, idx):
"""Get channel type
Parameters
----------
info : dict
Measurement info
idx : int
Index of channel
Returns
-------
type : 'grad' | 'mag' | 'eeg' | 'stim' | 'eog' | 'emg' | 'ecg'
Type of channel
"""
kind = info['chs'][idx]['ki... | 37cd3ee91e09d0c183c472ca81c8e0e703268a4c | 71,912 |
from re import T
def init_weights__(l):
"""
source: https://github.com/Xingyu-Lin/mbpo_pytorch/blob/main/model.py#L64
"""
def truncated_normal_(w, mean=0.0, std=1.0):
nn.init.normal_(w, mean=mean, std=std)
while True:
i = T.logical_or(w < mean - 2*std, w > mean + 2*std)
... | b3a452150010343609a73a2bd254789355adb77a | 71,913 |
def calc_box(box,x_gap,y_gap,rotate_angle,center):
"""
calculate the size of the required surrounding environment for doorway segmentation
box: four corners' coordinates of doorway
x_gap: remained space in the vertical way
y_gap: remained space in the horizontal way
"""
door_box = np.array([... | 2265f83dd70f9a1ae08843dc66dc0b5a8df557a6 | 71,914 |
def get_dummy_img_point(contour, principal_point=None, offset=-7):
"""
Return an estimated position of the dummy from
its contour if principal point is provided.
"""
M = cv.moments(contour)
centroid = np.array([
M['m10']/M['m00'],
M['m01']/M['m00']
])
if principal_poi... | 91bcfd4a8e7d8d658c344545228700a1c872ce1f | 71,915 |
def jensen_shannon(vec1, vec2, num_features=None):
"""Calculate Jensen-Shannon distance between two probability distributions using `scipy.stats.entropy`.
Parameters
----------
vec1 : {scipy.sparse, numpy.ndarray, list of (int, float)}
Distribution vector.
vec2 : {scipy.sparse, numpy.ndarra... | 721c1ca1218ca5aa201af1d4e8d131424cd5d8bf | 71,918 |
from joblib import load as joblib_load
def load_extractor(extractor: str) -> BaseEstimator:
"""loads a custom feature extractor"""
return joblib_load(f"msvc/src/features/feature_extractors/{extractor}.joblib") | 1e20fad04b38eadb6874c38aca940a5fa255de99 | 71,919 |
def conv2d(x, W,strides=[1, 1, 1, 1],dilations=[1,1,1,1],padding='SAME'):
"""conv2d returns a 2d convolution layer with full stride."""
return tf.nn.conv2d(x, W, strides=strides,padding=padding) | f0919e14c948185d390eaa152a3bdce27e9f53ba | 71,920 |
def infer_keypoint_left_right_type(left_right_types, indices):
"""Infers keypoint left/right type.
The inferred left/right type is decided as follows:
1. If either type is UNKNOWN, returns UNKNOWN.
2. If both types are the same, returns this type.
3. If one type is CENTRAL, and the other type is LEFT or RIGH... | d0895036a088c20bbe4f88fb3af098a03922dcca | 71,921 |
def get_length(vector):
""" calculate the lengt of a 3d vector
@type vector: tuple(float) | list(float)
@value vector: the given 3d vector
@rtype: float
@return: the length of a vector is the square root of the dot product
of the vector with itself
"""
return sqrt(get_dot_product(ve... | be3d779e9cdd8164ac4808d155702615e98d0704 | 71,922 |
from typing import Mapping
def normalize_and_encode(
charset: Mapping[str, bytes], value: str, field_name=None
) -> bytes:
"""
unicode normalize value and translate it into the datanorm charset
:param charset: A mapping from string to bytes
:param value: A unicode string to be translated.
:pa... | a42af498157c0df5f52e4927a5ed98b02f2e192b | 71,923 |
from typing import Optional
def sqlupload_start(
request: HttpRequest,
pk: int,
workflow: Optional[Workflow] = None,
) -> HttpResponse:
"""Load a data frame using a SQL connection.
The four step process will populate the following dictionary with name
upload_data (divided by steps in which th... | 6713e6bd486fe0369e57ea0942e41ffdb3ed6b3e | 71,924 |
def evaluate_hist_x_multi_y(x, row, bins, vals):
"""
Evaluate a set of values from histograms
Parameters
----------
x : array_like (n)
X values to interpolate at
row : array_like (n)
Which rows to interpolate at
bins : array_like (N)
X-values used for the interpolati... | 93e9623e2a8eb5f106efbd0054c26dc4f2079314 | 71,925 |
def bg_trim(im):
"""
Function to programmatically crop card to edge.
`im` is a PIL Image Object.
"""
# This initial crop is hacky and stupid (should just be able to set device
# options) but scanner isn't 'hearing' those settings.
# w,h = im.size
im = im.crop((443, 0, 1242, 1200))
# ... | b5b59059aa9823cd2be385ead5cc21b135a4e24b | 71,926 |
import torch
def datasets_fn(num_features: int):
"""
Docs.
"""
X = torch.rand(int(1e4), num_features)
y = torch.rand(X.shape[0])
dataset = TensorDataset(X, y)
return {"train": dataset, "valid": dataset} | 0b812c29928f62a7e9d431376138f337572e6af9 | 71,927 |
def handle_tags(text, keeptags, tags, filetype, previewing=False):
"""
Handles tags that are found in the text. Useless tags (header tags) are deleted and
depending on the specifications chosen by the user, words between meaninful tags (corr, foreign)
are either kept or deleted.
Args:
text:... | 00ecd330ae86aee576301a8cb8c90e199f54a021 | 71,928 |
import csv
def lastMonthsRetun(fileName):
"""Function taking the formatter data array and then converting it to dataFrame, with aim to find returns data we are interested in
Args:
fileName (String): File we want to have the data from
Returns:
Float : Returns sum devided by 5
"""
... | a24d5ce7704a4751f93c4b6404a42d772360d80f | 71,929 |
import importlib
import pkgutil
def get_indexes(package_name):
"""
Gets a sorted list of migrations in a package
"""
package = importlib.import_module(package_name)
indexes = []
for (loader, name, ispkg) in pkgutil.iter_modules(package.__path__):
try:
insort(indexes, int(na... | d820c910add680a625a483b20a6c21aded630aba | 71,930 |
def get_filtered_query(must_list=None, must_not_list=None):
"""Get the correct query string for a boolean filter. Accept must and
must_not lists. Use MatchList for generating the appropriate lists.
"""
bool_filter = {}
if must_list:
bool_filter['must'] = must_list
if must_not_list:
... | 2190456ad7e91239bb623f7ec3d2c460e521e36f | 71,931 |
def _mask_tissue(image, kernel_size=(7, 7), gray_threshold=220):
"""Masks tissue in image. Uses gray-scaled image, as well as
dilation kernels and 'gap filling'
"""
# Define elliptic kernel
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, kernel_size)
# Convert rgb to gray scale for easier ... | 7f901a0625efd0e7e7fa7cd3ebcf8c77e362b761 | 71,932 |
def stack2designs(old_X, new_X, old_contrasts={}, new_contrasts={}):
"""
Add some columns to a design matrix that has contrasts matrices
already specified, adding some possibly new contrasts as well.
This basically performs an np.hstack of old_X, new_X
and makes sure the contrast matrices are dealt... | 55a11a02c09bdbbd685a0e7e88f665945e28621f | 71,933 |
def duplicate_event_files(event):
"""Get list of event files that have equivalent deferred events.
:param event: Event to compare
:type event: ServiceEvent
:returns: List of event files
:rtype: List[str]
"""
duplicates = []
for event_file, existing_event in deferred_events():
if... | 76d59e96d71da34d7a596f99ac170adbafecb83e | 71,935 |
def cluster_input(prosumer, emissions, load, PV, k, hours):
""" Clustering of hourly input data into representative time periods using
k-means clustering algorithm
Keyword arguments:
prosumer ... list of prosumer names
emissions ... marginal emissions (pandas.DataFrame(index=time_steps... | 32cf73f7175a140fbc08ce800deb66a028c377ef | 71,936 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.