content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def check_password_by_hash(pw, hashed_pw):
"""Check a password against a salted hash"""
expected_hash = hashed_pw.encode('utf8')
return bcrypt.checkpw(pw.encode('utf8'), expected_hash) | 3aeb5699c708c28305e446c87e9d3a985dea3c33 | 40,275 |
def empty_ang():
"""Return an empty angle tensor representing 1 residue-level pad character."""
dihe_padding = np.zeros(NUM_ANGLES)
dihe_padding[:] = GLOBAL_PAD_CHAR
return dihe_padding | 0770020f1c61b5c6105a907229b74d67c2e128da | 40,276 |
def _retrieve_gb_sent_state(status: FritzStatus, last_value: str) -> float:
"""Return upload total data."""
return round(status.bytes_sent * 8 / 1024 / 1024 / 1024, 1) | 6a90fac0cbfee7ebd85506b53892ae809eb9bd51 | 40,277 |
def create_index(strings, method='fb-trie'):
"""Create a searchable index for a list of strings.
Parameters
----------
strings : iterable of str
Strings to index
method : {'fb-trie', 'trie'}
Index method to use. This affects memory usage and
query run time.
'fb-trie... | 839434a2489f99560ae5aa3a7a4d9bfdf875cfb7 | 40,278 |
def calculate_factor_initial_size(n, key):
"""
Calculate different initial embedding sizes by a chosen factor.
:param n: Number of nodes in the graph
:param key: The factor- for example if key==10, the sizes will be n/10, n/100, n/100, .... the minimum is 100 nodes
in the initial embedding
:retu... | 35fdef82e55647b20f9d86ec926e77c1d5244e2e | 40,279 |
def addAxes(pos, NixTopMargin=False, NixBottomMargin=False):
"""Add axes according the pos list, and return the axes handle.
# margin indices 0,1,2,3 for each panel (left, right, bottom, top)
"""
rect = pos[0]+margins[0], pos[1]+margins[2], pos[2]-margins[0]-margins[1], pos[3]-margins[2]-margins[3]
... | cb0b5bb671cfe2a5b774914c31c99f678716847b | 40,280 |
def main(reference_rmouth_outflows_filename, data_rmouth_outflows_filename,
grid_type='HD',param_set='default',flip_data_field=False,
rotate_data_field=False,flip_ref_field=False,rotate_ref_field=False,**grid_kwargs):
"""Top level river mouth matching routine. Deals with file handling"""
refer... | 0d7f73c41fa2881ae520c42488411eb84ea89dc7 | 40,281 |
def verify_routing_routes(device,
addr_list,
protocol,
contains,
max_time=60,
check_interval=10):
"""Verifies address list agianst 'show route protocol {protocol}'
Args:
add... | b2da7600f4862c0e3defe321bab64cd8ddaad997 | 40,283 |
def group(db):
"""Create group for the tests."""
group = GroupFactory()
db.session.commit()
return group | 34ab9dc9a9d4766feb9c6e50823efe238ae17fb1 | 40,284 |
def is_iterable(value):
""" Verifies the value is an is_iterable
:param value: value to identify if iterable or not.
"""
try:
iterable_obj = iter(value)
return True
except TypeError as te:
return False | 13728b7c28506086a3eb9b8faefcdc6276eba00e | 40,285 |
def remove_stop_words(tokenized_headline_list):
"""
Takes list of lists of tokens as input and removes all stop words.
"""
filtered_tokens = []
for token_list in tokenized_headline_list:
filtered_tokens.append([token for token in token_list if token not in set(stopwords.words('english'))])
return filtered_toke... | ddaa84becd4294881a3a7b5dc7582d0d289dd045 | 40,286 |
def set_agent_config(sampling_interval_seconds=1, cpu_limit_percentage=DEFAULT_CPU_LIMIT_PERCENTAGE):
"""
Reporting interval needs to have a minimum value and cpu_limit_percentage is used later in tests;
the other values can be None as we are not using them here.
"""
return AgentConfiguration.set(
... | 8b273996fd48ebcb82de739290e486da5956941a | 40,287 |
def rw_normalize(A):
"""
Random walk normalization: computes D^⁼1 * A.
Parameters
----------
A: torch.Tensor
The matrix to normalize.
Returns
-------
A_norm: torch.FloatTensor
The normalized adjacency matrix.
"""
degs = A.sum(dim=1)
degs[degs == 0] = 1
r... | 2a9f90d1f2bf02545e9719b0f373e6eb215fa0cd | 40,288 |
def get_all_stock_fundamentals():
"""
Returns a dict mapping instrument id to stock fundamentals
"""
db = get_db()
fundamentals_by_instrument_id = dict()
all_fundamentals = list(db["fundamentals"].find())
for f in all_fundamentals:
fundamentals_by_instrument_id[f["instrument_id"]] ... | 2933ee111b4754609a7172ac93648bccff6439fc | 40,289 |
def _binary_operator_expression(expression, expression_right):
"""Builds the IR for a chain of equal-precedence left-associative operations.
_binary_operator_expression transforms a right-recursive list of expression
tails into a left-associative Expression tree. For example, given the
arguments:
6, (T... | 3064a7b0989f38245d8b1816a3d5d3414eb5979f | 40,291 |
import re
def extract_diacritics(join=True):
"""
Extracts unique diacritics from a pasted column of IPA transcriptions.
Args:
join : specifies joining of diacritics in the same transcription.
Default True.
Requires:
regex module as re
reDiac()
... | 2ba59f3bd5463f03aecc7679fec88f02847921cc | 40,292 |
def announce_work(work_on_population):
"""Handle the worker counter."""
def wrapper(
analysis_id: str, t: int, redis: StrictRedis,
kill_handler: KillHandler, **kwargs):
# notify sign up as worker
n_worker = redis.incr(idfy(N_WORKER, analysis_id, t))
logger.info(
... | ca27bd7dfe71dc36f6e9e7743bdcfd4c73f4f803 | 40,293 |
def round(arg: ir.NumericValue, digits: int | None = None) -> ir.NumericValue:
"""Round values to an indicated number of decimal places.
Returns
-------
rounded : type depending on digits argument
digits None or 0
decimal types: decimal
other numeric types: bigint
digits non... | ceb4022f5397d76d0d55904d8c9d04536bafb490 | 40,294 |
from simtk import unit
from typing import List
from typing import Tuple
import pickle
def load_data_sets(
atom_features: List[AtomFeature], bond_features: List[BondFeature]
) -> Tuple[MoleculeGraphDataLoader, MoleculeGraphDataLoader, int]:
"""Loads in the train and test molecules and generates labelled, featu... | a3e65f6f4a5ff392662ffb7da88a355af165a22e | 40,295 |
def login():
"""View function to login. Uses the login form.
If the @login_required decorator is used on a view function
then the user will be redirected to this function."""
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on... | 202880c166dfaa9c29557caf9bd2b738e8c391c4 | 40,296 |
def to_isbn13(number):
"""Convert the number to ISBN-13 format."""
number = number.strip()
min_number = compact(number, convert=False)
if len(min_number) == 13:
return number # nothing to do, already ISBN-13
# put new check digit in place
number = number[:-1] + ean.calc_check_digit('978... | acdccd1dffc576322b6ac3af9e1c2d64131bfebc | 40,297 |
import itertools
def refine_flare_ranges(lc, sigma=3., makeplot=True, flare_ranges=None):
""" Identify the start and stop indexes of a flare event after
refining the INFF by masking out the initial flare detection indexes. """
if not flare_ranges:
flare_ranges, _ = find_flare_ranges(lc, sigma=sigm... | f73b8d46ac70bf10134749c0446382aee5d8cdb9 | 40,298 |
from typing import OrderedDict
def get_partial_lm_state_dict(model_state_dict, modules):
"""Create compatible ASR state_dict from model_state_dict (LM).
The keys for specified modules are modified to match ASR decoder modules keys.
Args:
model_state_dict (odict): trained model state_dict
... | bed8b06ba372ab0c8020d3f58fec07cdd4bdd9dd | 40,299 |
async def async_get_entry_scenes(entry: ConfigEntry, api):
"""Get the scenes within an integration."""
try:
return await api.scenes(location_id=entry.data[CONF_LOCATION_ID])
except ClientResponseError as ex:
if ex.status == HTTP_FORBIDDEN:
_LOGGER.exception(
"Unab... | ef97e7c181cefe13ea1b71393d81e13d4d5f8b2f | 40,300 |
import logging
def _get_areas(params, feature_names):
"""Returns mapping between areas and constituent feature types."""
areas = {}
for feature_id in range(len(params)):
feature_info = params[feature_id]
feature = feature_info["ID"]
area = feature_info["Area"]
if area not in areas:
areas[a... | 937797d7634ac6cd73af941c783f26d5a8028b4d | 40,301 |
def rbf_spectrum_dc(w: np.ndarray, c: np.ndarray, d: np.ndarray) -> np.ndarray:
"""Evaluate the RBF spectrum derivative w.r.t. c.
Args:
w: The (dimensionless) frequencies at which to evaluate the power spectrum, of
shape (n, ).
c: An unconstrained parameter representing
... | 8486d4dff592b093a520824d4f361745ad60b435 | 40,302 |
def render_colors(vertices, triangles, colors, width, height, channels=3, bg=None):
""" Adds color to 3D face vertices.
See https://github.com/YadiraF/face3d.
"""
if bg is None:
img = np.zeros((height, width, channels), dtype = np.float32)
else:
assert bg.shape[0] == height and b... | 670222fc1f5886698db3dca7f0179a4b5f78fdb6 | 40,303 |
def acceptanswer(request):
"""
采纳问题
:param request:
:return:
"""
answer_id = request.POST.get('answer_id')
answer = Answer.objects.filter(id=answer_id).first()
if request.user != answer.question.user and request.user != answer.user: # 保证采纳人一定是问题的提问者,而且不能自己采纳自己
return JsonRespons... | eedf5fcb45fd06c45ec323bbb0eaebba5b9386bc | 40,304 |
import numpy
def calc_m_sq_cos_sq_para(tensor_sigma, flag_tensor_sigma: bool = False):
"""Calculate the term P2 for paramagnetic sublattice.
For details see documentation "Integrated intensity from powder diffraction".
"""
sigma_13 = tensor_sigma[2]
sigma_23 = tensor_sigma[5]
p_2 = numpy.... | 910087c34ffc5ec43376fbdbc6368761fb4580ee | 40,305 |
import time
import resource
def main(samples, chunksize=1, num_workers=None):
"""Main application
"""
len_samples = len(samples)
time_start = time.perf_counter()
firstPerson = FirstPersonMR(num_workers, chunksize)
freq = firstPerson.frequency(samples)
time_elapsed = (time.perf_counter()... | c75f34ea058deab86998bfdb1e51a5746f24d70c | 40,306 |
import mpmath
def cdf(x, loc=0, scale=1):
"""
CDF of the logistic distribution.
"""
with mpmath.extradps(5):
x = mpmath.mpf(x)
loc = mpmath.mpf(loc)
scale = mpmath.mpf(scale)
z = (x - loc) / scale
p = (1 + mpmath.tanh(z/2)) / 2
return p | 395b33c9364fb279504088d0f515900c70c5ad4f | 40,307 |
def as_observer(self):
"""Hides the identity of an observer.
Returns an observer that hides the identity of the specified observer.
"""
return AnonymousObserver(self.on_next, self.on_error, self.on_completed) | 54e0493ebf4b885c831dd36b475b061c355e4708 | 40,308 |
def main(kw=False):
"""
main method to build ast tree and call subseq functions
Top level check
license info
scan for class - class check
scan for function - function check
"""
try:
f = open(sys.argv[1])
except IOError:
print "Can't find {}".format(sys.arg... | 543e44a462c17bd1cd7bc7191e72e9dfb9fe47d8 | 40,309 |
def swarmbox(df, parameter, stat_table, hue=None):
"""
Graph boxplot of a category, with each individual point
:return: matplotlib figure
"""
fig, ax = plt.subplots()
sns.swarmplot(x='Arm', y="Difference of "+parameter, data=df, ax=ax,
palette=sns.crayon_palette(['Vivid Violet'... | 02373a500ae48b71a4839c7e64717d2d7069e817 | 40,310 |
def create_qrcode(id_list, ctime, qrtype, pay_id):
"""
:param bid:表示书籍的唯一id,用isbn号码
:param ctime: 创建时间,一分钟后过期
:param type: 二维码类型
:return:
"""
qr = qrcode.QRCode(
version =1,
error_correction = qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
... | 051872c8103ed371da69221a7ef5f254e2606375 | 40,312 |
def load(file):
"""
Load an ontology from a .obo file.
"""
return OBOOntology(file) | 383cff1a4e1b93e0726c2bfb43413fa2f6c0b3e5 | 40,313 |
def transform_seed_objects(objects):
"""Map seed objects to state format."""
return {obj['instance_id']: {
'initial_player_number': obj['player_number'],
'initial_object_id': obj['object_id'],
'initial_class_id': obj['class_id'],
'created': 0,
'created_x': obj['x'],
... | 685c0c5b22fdff108311338354bb42fb53fd07f6 | 40,314 |
def get_cost_center(vehicle):
""" this is used to return cost center """
cost_center = frappe.get_value("Vehicle Details", vehicle, "vehicle_cost_center")
if cost_center:
return cost_center | ff090b203e6cbc670de97eb923e7cb0320dae7e2 | 40,316 |
import numpy
def sample_mog(prob, mean, var, rng):
"""Sample from independent mixture of gaussian (MoG) distributions
Each batch is an independent MoG distribution.
Parameters
----------
prob : numpy.ndarray
mixture probability of each gaussian. Shape --> (batch_num, center_num)
mean :... | cfd6f5e843a2d92b90d87038413a78da1be1fb40 | 40,317 |
def get_weather(location): # location can be IP address, city, or ZIP
"""This function takes the location and outputs the current weather."""
url = f"https://api.weatherapi.com/v1/current.json?" \
f"key={weatherapi_key}&" \
f"q={location}"
stats = {"temp_f": 0, "wind_mph": 0, "wind_dir"... | ad5e5bfbc81ebe0576e5afea3b8e1b522115e112 | 40,318 |
def progress_bar(t):
""" from https://gist.github.com/leimao/37ff6e990b3226c2c9670a2cd1e4a6f5
Wraps tqdm instance.
Don't forget to close() or __exit__() the tqdm instance once you're done
(easiest using `with` syntax).
"""
last_b = [0]
def update_to(b=1, bsize=1, tsize=None):
"""
... | 45b13a01ec1a55f8e2c9f8929235aec735974658 | 40,319 |
def remove_digits(text):
"""
Remove all digits from the text document
take string input and return a clean text without numbers.
Use regex to discard the numbers.
"""
result = ''.join(i for i in text if not i.isdigit()).lower()
return ' '.join(result.split()) | d9604c31391e48ab826089d39201577bdf83c2fa | 40,320 |
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up an Mila sensor entity based on a config entry."""
entry = hass.data[DOMAIN][entry.entry_id]
conf_devices = entry[CONF_DEVICES]
coordinator = entry[DATA_COORDINATOR]
def get_entities():
"""Get the Mila sensor entities.""... | 18f5c12eeff741097b255812e1dd139fb71f904e | 40,321 |
def _ipaddr(*args, **kwargs):
"""Fake ipaddr filter"""
return "ipaddr" | 8550ebc305442620e57d9b164d6751c1a16b4ef6 | 40,323 |
def hlab_to_xyz(hlab: Vector, white: VectorLike) -> Vector:
"""Convert Hunter Lab to XYZ."""
xn, yn, zn = alg.multiply(util.xy_to_xyz(white), 100, dims=alg.D1_SC)
ka = CKA * alg.nth_root(xn / CXN, 2)
kb = CKB * alg.nth_root(zn / CZN, 2)
l, a, b = hlab
l /= 100
y = (l ** 2) * yn
x = (((a... | e4747b034bc7cae858ed38b0671292c6990c97be | 40,324 |
from pathlib import Path
def get_cache_path() -> Path:
"""Returns data root folder."""
return get_data_path() / Path('cache') | 461765d615827917124a201968f68430821daa02 | 40,326 |
def create_temporary_file(
file_contents: str,
suffix: str = '.txt'
) -> NamedTemporaryFile:
"""Create a temporary file with an explicit name from a given string."""
file = NamedTemporaryFile(suffix=suffix)
file_contents_bytes = str.encode(file_contents)
file.write(file_contents_bytes)
file.... | dd9d3fb68054aa01d1dd6520b326df52a6dbeeaa | 40,327 |
import pickle
def load_CIFAR_batch(filename):
""" load single batch of cifar """
with open(filename, 'rb') as f:
datadict = pickle.load(f, encoding='latin1')
X = datadict['data']
Y = datadict['labels']
X = X.reshape(10000, 3, 32, 32).astype('float32')
Y = np.array(Y)
... | f78f29e53aaebf6b25f3d2c84710e7ee9d0d1ebb | 40,328 |
def one_minus_exp(x):
"""Returns 1-exp(x). Useful for probability calculations."""
if abs(x) < log_epsilon:
return -x
else:
return 1 - exp(x) | 6b62d053dcb034ccbdd466a59bbe2c31a05174fc | 40,329 |
from typing import List
from typing import Tuple
def get_diff_text(text1: List[str], text2: List[str]) -> List[Tuple[int, str]]:
"""
Take the alignment between two lists and get the difference.
"""
orig_words = '\n'.join(text1.split()) + '\n'
pred_words = '\n'.join(text2.split()) + '\n'
diff ... | 272c108cd97dbb73b637077ee6991bade8d209a4 | 40,330 |
def get_client(service_name, sandbox=False):
"""
Return a client for a given service.
The `sandbox` argument should only be necessary if a the client will be
used to make a request. If it will only be used to serialize objects, it is
irrelevant. A caller can avoid the overhead of determining the sa... | 62575d4aebfa049a5dae2a4c9cbd8ec9755a1616 | 40,331 |
def encrypt(key, text):
""" Encrypt a message using the public key, for decryption with the private key """
retval = b""
i = 0
txtl = len(text)
ks = int(key.key_size / 8) - 64 # bits -> bytes, room for padding
# Process data in chunks no larger than the key, leave some room for padding.
whil... | 90f97851a508fdf6c60b66ba9d40a8b4efd8975d | 40,333 |
def _DecoderBlock(positions,
d_model,
d_ff,
n_heads,
dropout,
mode):
"""Returns a layer sequence representing a Transformer decoder.
(acts, pos) --> (acts', pos')
Args:
positions: random vectors for positions
d_mod... | 09e6fb07e406127b57edb00c8d17668b0ffbaffe | 40,334 |
def accumulate_spectra(n_trajectories, n_states=10, suffix='flu', n_restarts=0):
"""
Create the spectra_flu.input file using the nasqm_flu_*.out files
"""
create_spectra_inputs(suffix, n_trajectories, n_restarts, n_states)
omegas_and_strengths = [open("{}_spectra/traj_{}.out".format(suffix, traj), '... | a446c1b67a224be18d16a896fd5b9d32374b5997 | 40,335 |
def QueryEncode(q: dict):
"""
:param q:
:return:
"""
return "?" + "&".join(["=".join(entry) for entry in q.items()]) | b92aaf02b3322b3c35b8fe8d528e2e4bc6f91813 | 40,337 |
import re
def _fast_suggest(term):
"""Return [] of suggestions derived from term.
This list is generated by removing punctuation and some stopwords.
"""
suggest = [term]
def valid(subterm):
"""Ensure subterm is valid."""
# poor man stopwords collection
stopwords = ['and',... | f4790e22abae7b33ee5585ea4a21189d7954cf40 | 40,339 |
def ind2ij(a,index):
"""
returns a[j,i] for a.ravel()[index]
"""
n,m = shape(lon)
j = ceil(index/m).astype(int)
i = remainder(index,m)
return i,j | 5aa4606466db3a62727e39f741d6454a4df6c3e3 | 40,341 |
import torch
def recording(matrix, v1, v2, v3, v4, v5, NC=None):
"""
recording matrix with row [fx, gx, oracle-calls, time, step-size, direction-type]
and iteration as columns
"""
v = torch.tensor([v1, v2, v3, v4, v5], device = matrix.device)
if NC is not None:
if NC == 'NC':
... | 2a4271865db212c7deae1fa49700915d59a2da2d | 40,342 |
def build_res_u_net(n_input=1, n_output=2, size=256, arch="resnet18", pretrained=True):
"""First pretraining step for generator -> Use a pretrained U-Net
Args:
n_input: Image input dimension
n_output: Image output dimension
size:
arch:
pretrained:
Returns:
(... | 2ddab2e6a9e40c6c982c0f10f07b61fbf769ccb9 | 40,343 |
def get_mig_identification(system: System) -> str:
"""
Returns string of GPU & subsequent MIG instance identification.
Also checks if MIG is enabled and the MIG configuration is homogeneous.
Return string omits how many MIG instances are populated.
Args:
system (System):
The sys... | 93a1393409187ec5e07808b87d3bb56e8d010fe0 | 40,344 |
def get_unmasked_indices(nc):
"""Make boolean array for converting to lat/lon pairs.
Geographic data in gridded dataset often contains many datapoints over
oceans that are not of current interest. Therefore it can be useful
instead of dealing with a 2D grid of lat/lon values to instead use a 1D
lis... | 9383f9062db89c3fd04743de01bc69a32d4b6894 | 40,345 |
def normalize(text):
"""
Lemmatize tokens and remove them if they are stop words
"""
text = nlp(text.lower())
lemmatized = list()
for word in text:
lemma = word.lemma_.strip()
if (lemma and lemma not in SW ):
lemmatized.append(lemma)
return lemmatized | a02185995b9bedb804cef7586372a9f4d65d84f1 | 40,346 |
def instance_digital_object(ref: str) -> dict:
"""
```
{
'instance_type': 'digital_object',
'digital_object': {'ref': ref}
}
```
"""
return {
'instance_type': 'digital_object',
'digital_object': _ref(ref)
} | be4b6d559972e6d828266035d853d1cb88bf2d80 | 40,347 |
def _transform_track(track):
"""Transform result into a format that
more closely matches our unified API.
"""
large_artwork = None
medium_artwork = None
small_artwork = None
if track['artwork_url']:
large_artwork = (track['artwork_url']).replace('large', 't500x500')
medium_a... | d27920b535f43f04c01afe5d7e5aa4337afb6682 | 40,349 |
def fwhm(t_r, hrf): # pragma: no cover
"""Return the full width at half maximum of the HRF.
Parameters
----------
t : array, shape (n_times_atom, ), the time
hrf : array, shape (n_times_atom, ), HRF
Return
------
s : float, the full width at half maximum of the HRF
"""
peaks_i... | bed3b9e23507852bc7f20e63eca21a57524b0383 | 40,350 |
def subtoken_cnn_encoder(*, namespace, inputs, padding_size,
subtoken_vocab_size, token_lengths,
num_filters=30, kernel_size=3,
subtoken_embedding_size=256,
padding='same', activation='tanh', strides=1):
""" Helper m... | 93544892f67cf9fb01eeea84d74243726a94158b | 40,351 |
import copy
def brute_permutation(A, B):
"""
Re-orders the input atom list and xyz coordinates using the brute force
method of permuting all rows of the input coordinates
Parameters
----------
A : array
(N,D) matrix, where N is points and D is dimension
B : array
(N,D) mat... | 58d36f0cc33ed8b7f690b17349359401fdf8ee84 | 40,352 |
async def vector_bsgn_2(x):
"""Compute bsgn_2(a) for all elements a of x in parallel."""
stype = type(x[0])
n = len(x)
await mpc.returnType(stype, n)
Zp = stype.field
p = Zp.modulus
legendre_p = lambda a: gmpy2.legendre(a.value, p)
s = mpc.random_bits(Zp, 6*n, signed=True) # 6n random ... | 3c619c75e5cb6ca9b8897477cd08ecd39a4876bf | 40,353 |
def barlamdel_to_kappal(q, barlaml, ell):
"""
$\kappa^{A,B}_\ell(\bar{\lambda}_\ell)$
Assume $q=M_A/M_B>=1$
"""
XA = q/(1.+q);
XB = 1. - XA;
blamfact = factorial2(2*ell-1) * barlaml;
p = 2*ell + 1;
kappaAl = blamfact * XA**p / q;
kappaBl = blamfact * XB**p * q;
return kapp... | c446c9c51141df9eded3505191bc0875ac6ddc0f | 40,354 |
def index():
"""index"""
return "Hello HBNB!" | 0f71803268e47ec64aa358ef71fc89d4beb04e49 | 40,355 |
def remove_duplicates(objects, equiv=None, tol=1e-12):
"""Remove duplicate objects from
a list of objects.
Parameters
----------
objects : list of objects
A list of objects,
with possible duplicates.
equiv : function, optional
A function for checking equality
of... | 712f7e71acab2564ea7652e899ae28ec671dd3e1 | 40,356 |
def upload_blueprint(archive, blueprint_id, blueprint_file):
"""execute cfy blueprints upload create
:param archive: the URL or path to a blueprint
:param blueprint_id: the blueprint ID
:param blueprint_file: the filename of the blueprint YAML
:type archive: string
:type blueprint_id: string
... | f6a8a12f32d0852556c7cb575b271647a6fee415 | 40,357 |
def yolo_head(feats, anchors, num_classes):
"""Convert final layer features to bounding box parameters"""
num_anchors = len(anchors)
# reshape to batch, height, width, num_anchors, box_params
anchors_tensor = K.reshape(K.variable(anchors), [1, 1, 1, num_anchors, 2])
# dynamic implementation of conv ... | 69834f8fbaf4c34187cc9e33dbbc889902efcc20 | 40,358 |
def _extract_neighbors (command):
"""return a list of neighbor definition : the neighbor definition is a list of string which are in the neighbor indexing string"""
# This function returns a list and a string
# The first list contains parsed neighbor to match against our defined peers
# The string is the command to... | c1ea91cc1dbdbcaad608e59d3f176eb4623b8714 | 40,359 |
def intrinsic_to_opengl_projection(intrinsic_mat, left, right, top, bottom,
near, far):
"""
Converts intrinsic matrix to OpenGL format.
:param intrinsic_mat: Intrinsic matrix in row-major order.
:return: OpenGL perspective mat (including NDC matrix) in column-major
... | 27e2390d67e522545bbf2694888cdf8a4689bff9 | 40,360 |
def makeNullRow(df, null=np.nan):
"""
Creates a row of null values to the dataframe.
:param object null: value in row
:return dict: row
"""
row = {}
for column in df.columns.tolist():
row[column] = null
return row | d3b07278338551c83fc1c0c19902a2687c01d6e1 | 40,361 |
def character_embedding_network(char_placeholder: tf.Tensor,
n_characters: int = None,
emb_mat: np.array = None,
char_embedding_dim: int = None,
filter_widths=(3, 4, 5, 7),
... | 51dc28ee085be66714eae1aa55d13deaea595db9 | 40,362 |
def _cast_list_by_data_type(field_type, list_values):
"""
将list结构的python数据转换为java能识别的数据类型
:param field_type: 字段类型,小写字符
:param list_values: list数据
:return: java能识别的数据类型构成的数组
"""
if isinstance(list_values, list):
return [_cast_value_by_data_type(field_type, value) for value in list_val... | a89aefb748b41ceecdd7a9b8820b84cdc7c2432d | 40,364 |
def fixture_perform_migrations_at_unlock():
"""Perform data migrations as normal during user unlock"""
return False | a8a8ae9118b2de4f0cdbb7ba3e39fdd7a552f77b | 40,365 |
def svn_repos_fs_begin_txn_for_update(*args):
"""svn_repos_fs_begin_txn_for_update(svn_repos_t * repos, svn_revnum_t rev, char const * author, apr_pool_t pool) -> svn_error_t"""
return _repos.svn_repos_fs_begin_txn_for_update(*args) | 5b75795deb05894c8cf9bc51fa59901df6592165 | 40,366 |
import torch
def generate_rays_th(pixel_coords, pix2cam,
cam2world):
"""Generate camera rays from pixel coordinates and poses.
Args:
pixel_coords: [width, height, 2] pixel-space coordinates.
pix2cam: [*batch, 3, 3] batched inverse intrinsic matrix.
cam2world: [*batch, 3+, 4] batc... | 132f87095b2258bdf812d8dfb6487d019383f7c8 | 40,367 |
def translate_push(x):
"""Converts list.push(v1, v2, ....) to __ee_extra_push(list, v1, v2, ...)
Args:
x (str): JavaScript code to translate.
Returns:
str: Translated JavaScript code.
Examples:
>>> from ee_extra import translate_push
>>> text = '["Banana", "Orange", "A... | 12aa97d7ab018021002d220b8fe8048cd7bf4290 | 40,368 |
def _check_and_fix(span_token_tup, span_drange, pred_field, complementary_field2ents):
"""
check if span_token_tup is in complementary_field2ents and fix result
Returns:
bool: if span_token_tup is in complementary ents
span_token_tup: fixed result
span_drange: fixed drange
"""
... | b3a8d0b75675f15c7dd857d2fb28e8713da330fe | 40,369 |
def perp( vector ):
"""
returns a vector perpendicular to the input. the vector will lie in the x=y plane.
"""
perpvector = np.array([1,1,-(vector[0] + vector[1])/vector[2]])
return perpvector/np.sqrt(np.sum(perpvector**2)) | 7d79be3bb167364b079cc2d6a7c1afa9fd99a561 | 40,370 |
def worker_history(request):
"""
跳转到工作经验证明的页面
:param request:
:return:
"""
return report.worker_history(request) | aff9249e908168742914aca90dbddb023c5db908 | 40,371 |
def generate_post_id() -> int:
"""This function creats a new directoy inside posts with post id and
returns it.
:rtype: int
"""
max_post_id = 0
for i in get_post_ids():
if i > max_post_id:
max_post_id = i
post_id = max_post_id + 1
post_path = get_post_path(post_id)... | ffb638af40a815c1a5950d2c12f0ea9b76f6ff75 | 40,372 |
from pathlib import Path
def getFileAbsolutePath(rel_path):
"""
Retorna o caminho absoluto de um arquivo a partir de seu caminho relativo no projeto
:param rel_path:
:return: absolute_path
"""
data_folder = Path("PythoWebScraper/src")
file_to_open = data_folder / rel_path
return file_... | b39baaa26e3c8a7c7a8c41dbb4fafceb7ca78c70 | 40,373 |
def _make_section_data(section, unique_sequences):
"""
Return a (CourseSectionData, List[ContentDataError]) from a SectionBlock.
Can return None for CourseSectionData if it's not really a SectionBlock that
was passed in.
This method does a lot of the work to convert modulestore fields to an input
... | a62e03222f8b3f04e6f8cc10d4c7531662b321ad | 40,375 |
from typing import Optional
from typing import Mapping
def get_connection(id: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetConnectionResult:
"""
This data source can be used to fetch informatio... | 69087603bd5b58e97f8370299f63516863610af3 | 40,376 |
def prepend_token(x_BxLxE, embed_VxE, token_id):
"""Prepend token_id embedding to a batch of sequence tensors.
Args:
x_BxLxE: sequence tensor
embed_VxE: embedding matrix
token_id: token to prepend
Returns:
x_Bx(L+1)xD tensor
"""
first_1xE = tf.nn.embedding_lookup(embed_VxE, [token_id])
fir... | f1fa10ed877deeab6880a1583fdf070f95e39f51 | 40,377 |
def residual_block(inputs, num_blocks):
"""
Applies several residual connections.
Args:
inputs (tf.Tensor): 4D (N,H,W,C) input tensor
num_blocks (int): Number of residual blocks
Returns:
tf.Tensor: 4D (N,H,W,C) output Tensor
"""
_, _, _, filters = inputs.shape
x = i... | f42544a2c38151206cfd771b952a6491273b4a1c | 40,378 |
def make_links(existings, versions):
"""
With the maping file-url<->existing-version create a mapping
file-url<-> Other-Url if exist, other url is replaced by index.html
if said page does not exits.
"""
links = defaultdict(lambda: {})
for k, ve in existings.items():
for v in versions... | 8cdda077bdd5419b976c9b45ad3d267b7c8c9b5a | 40,379 |
def _add_update_associate_key(
node, weight_key: Account, key: Account, weight: int, contract: str
):
""" Handles both add and update calls due to commonality """
session_args = ABI.args(
[ABI.account(bytes.fromhex(key.public_key_hex)), ABI.u32(weight)]
)
return node.deploy_and_propose(
... | ab20cb4215b126278f60fb735fee2902d6702aae | 40,380 |
def get_unacked_triggers(config):
"""Retrieves the unacked triggers from Zabbix.
:param config: config for zapi
:type config: dict
:return: list of triggers
"""
zapi = init(config)
all_triggers = zapi.trigger.get(only_true=1,
skipDependent=1,
... | e02391b3622bdaad30d64799743be30a9311833b | 40,381 |
def passwd_hash(p):
"""Hashing password and convert it to hex number
password in range from 6 to 40 char's"""
return sha256(p.encode('utf-8')).hexdigest() | 5ed22f70405e716b69333947e05b93b320aa864d | 40,382 |
import requests
def generate_text(query, genre):
"""
Функция отправляет POST-запрос к Балабобе,
и получает ответ в виде словаря.
Параметры POST-запроса:
query: ключевая фраза
genre: id жанра, в котором Балабоба должен сгенерировать текст
"""
text_url = 'https://zeapi.yandex.net/lab/api... | 467c40145db532f912ba2d17ad3ba588273fa682 | 40,383 |
def read_batch(filename, batch_size, random=False):
"""
Read single batch.
"""
context_features = {
"lcl": tf.FixedLenFeature([], dtype=tf.int64),
"rcl": tf.FixedLenFeature([], dtype=tf.int64),
"eml": tf.FixedLenFeature([], dtype=tf.int64),
"uid": tf.FixedLenFeature([], d... | 4e4c73f4ff86d46e8ffb21dc8c18145512a33fc3 | 40,384 |
import json
def delete_flowentry(fields, ip=DEV_VM_URL):
"""
Deletes a flowentry by using OVS REST API, flowentry is matched based on
the information in `fields`
"""
url = "http://%s:%d/stats/flowentry/delete_strict" % (ip, OF_REST_PORT)
data = json.dumps(fields)
return _ovs_api_request('... | 5e6f421b757e99d12b07025cc687d4633ede792c | 40,385 |
def directive_exists(name, line):
"""
Checks if directive exists in the line, but it is not
commented out.
:param str name: name of directive
:param str line: line of file
"""
return line.lstrip().startswith(name) | eb69044de8860b1779ce58ef107859028b8c98cf | 40,387 |
import timeit
def search_set(n):
"""Search for an element in a set.
"""
my_set = set(range(n))
start = timeit.default_timer()
n in my_set # pylint: disable=pointless-statement
return timeit.default_timer() - start | f0d8ba45df45130cc81d70e2d391825ed46dc93e | 40,388 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.