content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def unassign_users(request, domain):
"""
Unassign all users from their locations. This is for downgraded domains.
"""
for user in get_users_assigned_to_locations(domain):
if user.is_web_user():
user.unset_location(domain)
elif user.is_commcare_user():
user.unset_... | 1b113518627b7c50003c26833571eb6f827912d3 | 3,600,227 |
def psnr(y_true, y_pred):
"""Peak signal-to-noise ratio averaged over samples and channels."""
mse = K.mean(K.square(y_true*255 - y_pred*255), axis=(-3, -2, -1))
return K.mean(20 * K.log(255 / K.sqrt(mse)) / np.log(10)) | 294a55dac0d5b59b34df1df449c956fa7c4be5b7 | 3,600,228 |
from typing import Optional
import asyncio
async def find_device(
name: Optional[str] = None,
service: str = PYBRICKS_SERVICE_UUID,
timeout: float = 10,
) -> BLEDevice:
"""Finds a BLE device that is currently advertising that matches the
given parameters.
Arguments:
name:
... | e7015fa1ea8fc4dcc3b63b4091179a2c6d82f229 | 3,600,229 |
def pol_energy(aa, slr, ecc):
"""
Calculate energy for polar Kerr case.
Parameters:
aa (mpf): spin parameter (0, 1)
slr (mpf): semi-latus rectum [6, inf)
ecc (mpf): eccentricity
Returns:
En (mpf): energy
"""
try:
prec = mp.prec
mp.prec += 10
... | a3c53efa5878f2e0430af2d3b929d10edf1ba103 | 3,600,230 |
import numpy
def run_kmeans(find_closest_centroids_func, compute_centroids_func, x_array, centroids, max_iters=10, plot_progress=False):
"""
Runs the K-means algorithm.
Parameters
----------
x_array : array_like
The data set of size (m, n). Each row of x_array is a single example of n dim... | 3737f04be7305d2ddf3d3ae43fdd91c20d0005d5 | 3,600,231 |
def get_info_block():
"""Return Div object."""
text = """
<h4>Info links</h4>
<ul>
<li><a href="https://docs.bokeh.org/en/latest/docs/user_guide/tools.html" target="_blank">Bokeh toolbar info</a></li>
<li><a href="https://github.com/sharksmhi/sharkpylib/tree/master/sharkpylib/qc" target="_bl... | 3bb188bc24b74c6673dea86a4d572481d7cf400a | 3,600,232 |
def load_rule_and_env(rule_dir_path, env_yaml, product=None):
"""
Loads a rule and returns the combination of the RuleYAML class and
the corresponding local environment for that rule.
"""
# First build the path to the rule.yml file
rule_path = get_rule_dir_yaml(rule_dir_path)
# Load rule c... | 383a0e3b9d4660d22e9d398d669d2fcd3acadfec | 3,600,234 |
def validate_3octets(value):
"""
Validate 3-octets string.
:param value:
:return:
"""
is_valid = False
try:
is_valid = int(value, base=16) >= 0 and len(value) == 6
except ValueError:
is_valid = False
except TypeError:
is_valid = False
return is_valid | 10e8240398ccde624e6bcee702acaa319289102a | 3,600,235 |
from scipy.signal import find_peaks
def _peaks(meta):
"""
Find peaks of signals
"""
peaks, _ = find_peaks(meta.iloc[:,0].values)
return meta.iloc[peaks,:] | 44f265040aba80ade6b26a782e330e3b14e3bc83 | 3,600,236 |
def add_neologisms_to_db(neolist,neosinfo, lang):
""" add neologisms to database for web interface validation """
log.info("Saving neologisms to database" + str(neolist) + ' : and info : ' + str(neosinfo))
#for neo in neolist:
# log.info("Saving neologism : " + neo + " : " + str(len(neolist[neo])) +... | e3a97f22ef2fb4dacd636d826dff2ec952fd714b | 3,600,239 |
def _isnotebook():
"""
Determine if code is being run from a Jupyter notebook
``_isnotebook`` is True if running Jupyter notebook, else False
:references:
- https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-
is-executed-in-the-ipython-notebook/39662359#39662359
... | f30988d3b2d719a8c125b2e9eb22281552ddd342 | 3,600,240 |
def detect_timestep(data):
"""
Get the time steps present in the loaded data
"""
same_trace = data.shift(-1).trace_id == data.trace_id
dts = data.shift(-1).time - data.time
dts[~same_trace] = np.nan
return dts.mean(), dts.min(), dts.max() | 805c907cf08d96f0b677fc0263108f422fc93a84 | 3,600,241 |
from typing import Tuple
import torch
def get_semantic_one_hot(
input: Tensor,
n_classes: int,
normalize: bool = False,
input_range: Tuple[float, float] = (-1.0, 1.0),
) -> Tensor:
"""
Converts a tensor of indices to a one-hot tensor.
Args:
input: (N, 1, H, W) semantic label, rang... | 93e1f2b79d38d4abcfa206dbf9c6553bc81d6179 | 3,600,243 |
def _viewer_urls(spectra, zoom=13, layer='ls-dr9'):
"""Return legacysurvey.org viewer URLs for all spectra.
Note: `layer` does not apply to the JPEG cutout service.
"""
u = "https://www.legacysurvey.org/viewer/jpeg-cutout?ra={0:f}&dec={1:f}&zoom={2:d}"
v = "https://www.legacysurvey.org/viewer/?ra={... | 6fe781b92f929f9265d464935929490b67a6e9a7 | 3,600,244 |
def jsdate(d):
"""formats a python date into a js Date() constructor.
"""
try:
return "new Date({0},{1},{2})".format(d.year, d.month - 1, d.day)
except AttributeError:
return 'undefined' | 0c8331f928cf26e4cac7663dd6619c62cfff0fae | 3,600,245 |
from unittest.mock import Mock
import json
def fakeQnAMakerAPIreplaceCallBroken(method, url, headers, data: str = ""):
"""Faked API return data based on Method and URL
second call breaks
"""
if method == "GET" and url == "https://localhost/dest/knowledgebases/456":
returnvalue = Mock()
... | df7fb2e3e0a86aee66759afdd5e02fe3962f465a | 3,600,246 |
def get_component(request):
"""Get Android Component."""
data = {}
try:
env = Environment()
comp = request.POST['component']
bin_hash = request.POST['hash']
if is_attack_pattern(comp) or not is_md5(bin_hash):
return invalid_params()
comp = env.android_comp... | da6f4d0a0a2285cc6ff051e9d912e34cbe3370c8 | 3,600,247 |
import typing
import asyncio
import functools
def run_sync(
target: typing.Callable[..., typing.Any],
*args,
timeout: int = 10,
new_loop: bool = False,
**keywords,
) -> typing.Any:
"""Run async tasks synchronously with a timeout
:param target:
:param args:
:param timeout:
:par... | 6c3af5a29e79d2e5fcd2b4422895a5a761e7295a | 3,600,248 |
def data_merge(data_list, path):
"""merge seperated sets for trainning set.
:param data_list: a list of the seperated dataset.
:param path: the path of the generated files.
"""
if len(data_list) != 0:
test_list = data_list.pop(0)
num_list = range(len(data_list))
comb_list = list(comb... | 236e81e46f1520f36818d978c34a08b267b0284e | 3,600,249 |
import random
def mutate(chromosome):
"""
Pick a random bit to mutate by XOR and shifting the selected bit. This
ensures diversity in the population.
"""
altered_bit_position = random.randint(0, 31)
mutation = chromosome ^ (1 << altered_bit_position)
return mutation | ff93fb19d7d83c558172d005fbd140284e2b16c2 | 3,600,250 |
from azure.cli.core.auth.identity import ServicePrincipalAuth
def login(cmd, username=None, password=None, service_principal=None, tenant=None, allow_no_subscriptions=False,
identity=False, use_device_code=False, use_cert_sn_issuer=None, scopes=None, client_assertion=None):
"""Log in to access Azure sub... | 6eee8eb66fe99a9fcaa946e8b927134900956770 | 3,600,252 |
def _calculate_transform_between_points(target_points, source_points):
"""Calculate a transform that maps matched sets of points.
Args:
target_points (np.ndarray): A set of matched points from the target image, of shape (n_samples, n_dimensions).
source_points (np.ndarray): A set of matched poi... | 6a40ca20a7abe11cf79f9f034f0b83e443ebe9ca | 3,600,253 |
import torch
def create_multimodal_gan_siamese_evaluator(
generator,
discriminator,
metrics=None,
device=None,
non_blocking=False,
prepare_batch=prepare_batch_siamese,
output_transform=output_transform_evaluator_siamese,
prepare_batch_variables=prepare_multimodal_batch_variables,
):
... | 213b6c30fbd37e3e460d3e5bb9c59fef17bccbba | 3,600,254 |
def count_nucleotides(dna, nucleotide):
""" (str, str) -> int
Return the number of occurrences of nucleotide in the DNA sequence dna.
>>> count_nucleotides('ATCGGC', 'G')
2
>>> count_nucleotides('ATCTA', 'G')
0
"""
cnt = 0
for s in dna :
if s == nucleotide :
cnt... | 855c29cca451f635291f4aa80fd3814f21218539 | 3,600,255 |
import torch
import functools
def count_flops_params(model, x, custom_ops=None, verbose=True, mode='default'):
"""
Count FLOPs and Params of the given model. This function would
identify the mask on the module and take the pruned shape into consideration.
Note that, for sturctured pruning, we only ide... | 706b741d25ff49df3c70e5b84f754b7c5cf4422d | 3,600,256 |
def impulse(iir, ts, n):
"""
Computa la respuesta al impulso de un filtro digital IIR
en punto fijo.
El filtro se representa como una secuencia ordenada de
etapas de segundo orden, cada una representada por los
coeficientes de su ecuación en diferencias más una
ganancia: [b0, b1, b2, a1, a2... | 8c97da341096fe8695164b8cc5ae6387db89d773 | 3,600,257 |
def str2int(v):
"""
Convert string to boolean to integer
"""
return int(str2bool(v)) | 420c6d18e1ad234ff3ac850ba987767dbba64e07 | 3,600,259 |
def fixed_point_sample(point_cloud, num_points, seed=0):
"""
:param point_cloud: (B, C, N) Point cloud data.
:param num_points: Number of samples.
:param seed: if you want fixed, set seed.
:returns: (B, C, num_points) Sampled point cloud. /
(B, num_points) Sampled point cloud indic... | 64150d4d823cc5f3d19f13ca2c5b755073662755 | 3,600,260 |
def get_experimental_pdb_info(pdbids, site="rcsb"):
"""
returns list of tuples (pdb_id, resolution, rwork, rfree) and dict
pdbid: (resolution, rwork, rfree)
"""
rlist = []
rdict = {}
assert site in ["rcsb"]
pdb_list = ",".join(pdbids)
url = web_urls.get(site).format(pdb_list=pdb_list)
data = libtbx.... | 1d38b0263914a32e8ad047ab738860aa42174a74 | 3,600,261 |
from datetime import datetime
from typing import OrderedDict
import pickle
def verification(config, output_file=None, use_cf6=True, use_climo=True, force_rain_quantity=False):
"""
Generates verification data from MesoWest and saves to a file, which is used to train the model and check test
results.
:... | 211f37e6cc938e869811dba93e88f4e2d83be613 | 3,600,262 |
def get_openapi_spec():
"""Get OpenAPI Spec."""
return jsonify(current_app.config['OPENAPI_SPEC']) | 1085fa157bdaccb624bf25d7af38ac63232c522a | 3,600,263 |
def AXIS_FILTER(arg_value):
"""Only keeps ints in the range [-1, limits.MAX_NUM_DIMENSIONS)."""
return (arg_value.type is int and
-1 <= arg_value.value < limits.MAX_NUM_DIMENSIONS) | 7095f40659a82e91c5a3afb10886a910c515ec1f | 3,600,264 |
def pairwise_diagonal_interactions_indices(num_qubits):
"""List of 1- and 2- qubit diagonal interaction terms."""
all_ints = pairwise_interactions_indices(num_qubits)
return [interaction for interaction in all_ints if is_diagonal_interaction(interaction)] | 936ff315430a35b8fe7351ca57876459efd521f5 | 3,600,265 |
def mileage_format(value):
""" Custom formatting for mileage. """
return "{:,} miles".format(value) | 056f5fbf5d291ac892bd8f2c16cda16937f758da | 3,600,266 |
from typing import Union
from pydantic_factories import ModelFactory
import inspect
def get_settings(model: Union[Model, ModelFactory]) -> Settings:
"""Get the parameters of a SAX model function"""
signature = inspect.signature(model)
settings: Settings = {
k: (v.default if not isinstance(v, dic... | 2d2a59f1bc21f574e13008fd9b2f18fb669abbbf | 3,600,267 |
def merge_patches(patches=None, image_size=(0, 0), patch_size=(0, 0), offset_row_col=None):
"""
Merge different pieces of image to form a full image. Overlapped regions are averaged.
:param patches: List of all patches to merge in order (left to right).
:param image_size: Full image size
:param patc... | 37dc011b16e61d12ae18e9e39cb394c5a6472809 | 3,600,268 |
import click
def init():
"""Return top level command handler."""
@click.command()
@click.argument('aliases')
def check(aliases):
"""Check aliases."""
subproc.load_packages(aliases.split(':'))
for exe in subproc.get_aliases():
success = True
fullpath = s... | 6bfe123a98ff997b4c2f1de960b77ac7748e3236 | 3,600,269 |
def to_TProfile3D(
fName,
fTitle,
data,
fEntries,
fTsumw,
fTsumw2,
fTsumwx,
fTsumwx2,
fTsumwy,
fTsumwy2,
fTsumwxy,
fTsumwz,
fTsumwz2,
fTsumwxz,
fTsumwyz,
fTsumwt,
fTsumwt2,
fSumw2,
fBinEntries,
fBinSumw2,
fXaxis,
fYaxis,
fZaxis,... | f1d0a6eaa41360bb7675ed5e7784a8701f7245f6 | 3,600,270 |
def sol_dec(day_of_year):
"""
Calculate solar declination from day of the year.
Based on FAO equation 24 in Allen et al (1998).
:param day_of_year: Day of year integer between 1 and 365 or 366).
:return: solar declination [radians]
:rtype: float
"""
return 0.409 * np.sin(((2.0 * np.pi ... | ebe21378383a28881804609f9e0f87e309937d4f | 3,600,271 |
def run_sync_mock(_config, _cmd):
"""mock of RemoteCmd.run_sync()"""
return lib.remote_cmd.RemoteCmd(None, None, None, 0) | d2eda62c0238d0447f4228f2d466cbb4da345a80 | 3,600,272 |
from typing import List
def drain_sock(sock: SubSocket, wait_for_one: bool = False) -> List[capnp.lib.capnp._DynamicStructReader]:
"""Receive all message currently available on the queue"""
ret: List[capnp.lib.capnp._DynamicStructReader] = []
while 1:
if wait_for_one and len(ret) == 0:
dat = sock.rece... | 4f9a51bd2e436ae2ebbe77f18b2bb81594f8583e | 3,600,273 |
def get_rows_from_times(mission_table, times):
"""
Examples
--------
>>> start = np.arange(2, 4)
>>> end = np.arange(3, 5)
>>> labels = ['AA', 'BB']
>>> mission_table = QTable({'mjdstart': start, 'mjdend': end, 'label': labels})
>>> times = np.array([1.5, 2.1, 3.5, 4.5, 5.5])
>>> ta... | 7f1b59eef11d70b94795efee153e1cea9ead70a3 | 3,600,274 |
def api_docs(request):
"""Api Docs Route."""
context = {
'title': 'REST API Docs',
'api_key': api_key(),
'version': settings.MOBSF_VER,
}
template = 'general/apidocs.html'
return render(request, template, context) | 09fb9e1659bb75ab8c3a189856f83ed96b592bae | 3,600,275 |
def _list(key: str, vals: dict) -> list:
"""Get a key from a dictionary of values and ensure it is a list."""
result = vals.get(key, [])
if not isinstance(result, list):
result = [result]
return result | cf8a5da580dc4d95f83f18a92f82f646be5c4cb3 | 3,600,276 |
def abundance(n):
"""Returns the difference between the sum of the positive
proper divisors of a number and the number.
Examples
========
>>> from sympy.ntheory import abundance, is_perfect, is_abundant
>>> abundance(6)
0
>>> is_perfect(6)
True
>>> abundance(10)
-2
>>> ... | af119159a8f62f0c62cccd9a30864ec539b54204 | 3,600,277 |
def structureSvInstance(stackedLine, tabSpace, alignCol, alignCom):
"""
This function restructures an input "stacked line" module declaration
from a .sv file. Expecting a module declaration on one line in the form
of:
blockName#(param1,param2,param3,...)(port1,port2,port3,...)
or:
blockNam... | 8939cb6cbd2115b8b6bae3866bd4be78d32e1954 | 3,600,278 |
def flatten(array):
"""Convierte un array de habilidades en dataframe.
Esta funcion convierte un array de tipo:
[
"Hola - Adios - Como - Estas",
"Hola - Como - Estas",
"Hola - Adios - Como",
"Adios - Como - Estas",
"Hola - Adios",
"Hola",
]
Y regresa un dataframe de tipo:
hab1, hab2, h... | 72d0d1c45cde76a3fb9238f2c77c2be98a0de497 | 3,600,279 |
def load_vaccine_data():
""" Function to load data
param DATA_URL: data_url
return: pandas dataframe
"""
DATA_URL = 'data/df_vaccine.csv'
data = pd.read_csv(DATA_URL)
data['date'] = pd.to_datetime(data['date']).dt.strftime('%Y-%m-%d')
return data | d7195714dd1f11b1595be0081131aacbdab729b9 | 3,600,282 |
def linkify_with_outgoing(text, nofollow=True, only_full=False):
"""Wrapper around bleach.linkify: uses get_outgoing_url."""
callbacks = [linkify_only_full_urls] if only_full else []
callbacks.append(linkify_bounce_url_callback)
if nofollow:
callbacks.append(bleach.callbacks.nofollow)
return... | bda4256a6a8a09403e2002a87280aa4a8db617a0 | 3,600,283 |
import ast
def to_annotation(typ):
"""
Converts the typ to an annotation
:param typ: A string representation of the type to annotate with. Else return give identity.
:type typ: ```Union[str, AST]```
:return: The annotation as a `Name` (usually) or else some more complex type
:rtype: ```AST``... | 7a2488eda282376b4cbc028e157e368519d8c55c | 3,600,284 |
from sklearn.neighbors import KNeighborsClassifier
def sc_knn(input_dict):
"""
:param input_dict (input): {u'n_neighbors': u'5', u'weights': u'uniform', u'algorithm': u'auto'}
:param n_neighbors : int, optional (default = 5). Number of neighbors to use by default for k_neighbors queries.
:param weigh... | 3b36ceb716b48de6c0e880ff072965acfe61a029 | 3,600,285 |
def contrast_color(hex_color):
"""
Util function to know if it's best to use a white or a black color on the foreground given in parameter
:param str hex_color: the foreground color to analyse
:return: A black or a white color
"""
r1 = int(hex_color[1:3], 16)
g1 = int(hex_color[3:5], 16)
... | 470f713af48673d7b9fb8aa3bb30f7e1498da9b5 | 3,600,286 |
def to_equity_through_by_id(uni_id: str) -> dict:
"""
根据统一社会信用代码列表,返回股权穿透信息
:param uni_id:
:return:
"""
result = {'uni_id': uni_id, 'equity': None}
method_id = 'c2e25afe-65eb-4990-a609-110ffdf5963e'
params = {
'keyWord': uni_id,
'level': '4'
}
task = to_task_inv... | 4869fec237f9ef33ffc1cb46bcf4e4bafde54e15 | 3,600,287 |
from typing import Union
from typing import List
def _toPhonemeList(phoneList: Union[PhonemeList, List[str]]) -> PhonemeList:
"""Utility function to unify the input to be PhonemeList"""
if isinstance(phoneList, list):
return PhonemeList(phoneList)
elif isinstance(phoneList, PhonemeList):
r... | 7fe961884cda936a585ebd375aa6715dd3556424 | 3,600,288 |
def search(board):
"""
Return score and best move, relative to board.turn.
The search is an implementation of a depth-unlimited
Negamax-algorithm, a variant of Minimax.
"""
# If game is over we know the score.
decided, score = board.is_decided_and_score
if decided:
# tb[board.a... | a4d1c70221703f2dc1a2f97d8a98f2e46559aab4 | 3,600,289 |
def project_lookup(auth, name_or_id):
"""Tries to find a single project by name or ID. Raises an error if
none or multiple projects found."""
try:
return keystone_project(auth, name_or_id)
except HTTPError:
# failed lookup assuming it was an id, must be a name?
pass
projects... | 07ff1a3e039cf4aabc836d3b0c66fdb3f4b05a9f | 3,600,290 |
def get_ips(filename: str) -> list:
""" Reads ips from a list of files """
ips = []
with open(filename, 'r') as f:
ips = f.read().splitlines()
return ips | 6dfd326dc57df8a8297cd27a0d3d01fbe11db3f4 | 3,600,292 |
def remove_corrupted_frames(frame_list, min_pix=18000):
"""
Remove frames that are identified as corrupted, i.e., those with pixel
values < min_pix in any image extension. Return a list of candidate
"good" frames.
"""
if getJobName() == 'scan_mode_analysis_BOT':
return frame_list
go... | 49a49c8f665f39a628852af96f7968c61a9176f6 | 3,600,293 |
def get_vlan_member(dut, vlan_list=[], cli_type="click"):
"""
To Get VLANs vs list of Members.
Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com)
:param dut:
:param vlan_list:
:param cli_type:
:return:
"""
vlan_val = {}
vlan_li = map(str, vlan_list) if isinstance(vlan_list, l... | 82dc830ba73da93a2f95c47bb3ca44c84dae93b2 | 3,600,294 |
def all_packages(request, verbose=False):
"""List all packages"""
if verbose:
packages = request.db.summary()
else:
packages = request.db.distinct()
i = 0
while i < len(packages):
package = packages[i]
name = package if isinstance(package, str) else package["name"]
... | 76103ea29f787b7cd28ff8bc9aca37daea603432 | 3,600,296 |
def variances_scaled_to_real(scaled_variances, bounds):
"""Convert variance in scaled dimensionless values to physical units
Parameters
----------
scaled_variances : array_like, shape=(n,m)
Input variances (scaled)
bounds : array_like, shape=(m,2)
Bounds to scale `scaled_variances`.... | 03c397658c43e2516aeddfff51314ae78c76c672 | 3,600,297 |
def joindicts(dest, *dictlist, prefix=''):
"""Merges one or more dictionaries into dest recursively.
Dictionaries are merged, lists are merged. Scalars and strings are ignored.
Returns the generated result.
To merge with overwrite, use the native dict update method.
"""
result = dest
for in... | 678a6fc5fc8c7b9bbd0980900760f8693d734d7c | 3,600,298 |
from typing import Callable
from typing import Any
def use_update_form(valid_user_api_client: APIClient):
"""
Uses the default edit form and view for a model to update an object to have
the passed new data and returns the new version of the object.
The ``new_data`` dictionary should contain callable ... | c844fb9a9def9c9e842623a0b063af3c24fb267a | 3,600,299 |
def rowNormCMatrix(partition):
"""
Calculate squared row norm of C factor matrices
"""
ret = []
rows = list(partition)
# dalia
for row in rows:
label = row[0]
Xi = row[1]
Ki = Xi.shape[0]
Ci = np.zeros((Ki,R))
ZiTZic = tensorOps.ZTZ(A, B)
XiZic = np.dot(unfold(Xi, 0), khatri_rao([Ci... | 72b3ee89305deac69badae8ce92d80a3f62f9481 | 3,600,300 |
def versions_to_sync(gh_releases, releases):
"""
:param gh_releases: github release objects from atom.
:param releases: the db releases.
"""
# Because many projects might have existing ones on pygame,
# but not have them on github, we don't delete ones unless
# they came originally from gi... | 209e34d3883dc35f3f6eba13e392b05930448c5d | 3,600,301 |
def test_mapping_column_list() -> None:
"""
Perform a simple mapping over a series of expressions.
"""
def replace_col(e: Expression) -> Expression:
if isinstance(e, Column) and e.column_name == "c2":
return FunctionCall(None, "f", (e,))
return e
column1 = Column(None, ... | 1bd1103b485fce5fd39e2539d8c63d76385c90bf | 3,600,302 |
import itertools
def get_common_base(files):
"""Find the common parent base path for a list of files.
For example, ``["/usr/src/app", "/usr/src/tests", "/usr/src/app2"]``
would return ``"/usr/src"``.
:param files: files to scan.
:type files: ``iterable``
:return: Common parent path.
:rty... | bb6c7fde6a9e2f9c620febf52047b547cf24e602 | 3,600,303 |
def magic_dir(tmp_path_factory):
"""Provides a temporary directory for testing copy/working directory behavior."""
magic = tmp_path_factory.mktemp('build_magic')
return magic | c891b0e7e8dbf2d23d380ce316fb80b6d78d1ec7 | 3,600,304 |
def comment(src_line: str) -> list:
"""Returns an empty list."""
return [] | c7e584811b899ae4a17ba4c9fd0debbc97e0a5cc | 3,600,305 |
def create_form(party_id, erroneous_form=None):
"""Show form to create a tourney."""
party = _get_party_or_404(party_id)
form = erroneous_form if erroneous_form else CreateForm()
form.set_category_choices(party.id)
return {
'party': party,
'form': form,
} | 33c1ccf1633d45b21b7a316fbb69f7d8638f8099 | 3,600,306 |
def setup_shift_of_ray_bundle(seq_model, start_offset):
""" compute transformation for rays "start_offset" from 1st surface
Args:
seq_model: the sequential model
start_offset: z distance rays should start wrt first surface.
positive if to left of first surface
Returns:... | 87a1c6c8761bc64339a75a06385390f9b91a646f | 3,600,307 |
def ancestors(G, source):
"""Returns all nodes having a path to `source` in `G`.
Parameters
----------
G : NetworkX DiGraph
A directed acyclic graph (DAG)
source : node in `G`
Returns
-------
set()
The ancestors of source in G
"""
if not G.has_node(source):
... | 152518fbc731bfa94a1d317e7eb16fe4ce80421e | 3,600,308 |
def avo_attributes(horizon_data: str, near_stack: DataArray, far_stack: DataArray, theta_near: int,
theta_far: int, TWT_slice: tuple, XL_slice: tuple, inline: int, well_XL=None,
well_display=True, robust=True, interpolation='spline16', add_colorbar=True,
cmap='je... | 52e74efcd0df352b1d9ebf7d84a3710bd9608f87 | 3,600,309 |
def tensor_scatter_np_benchmark(np_func, input_x, indices, updates):
"""
Feature: benchmark to generate result.
Description: benchmark function to generate result.
Expectation: match to tensor scatter binary op.
"""
result = input_x.copy()
benchmark_func = np_benchmark_func_map.get(np_func)
... | 05bdf89dfeee3aab9c2f04ac72ea2d29d0f45431 | 3,600,310 |
import torch
def train_nn1(x_train, y_train, h_0=100, cv_err_thresh=0.05, err_thresh=0.05):
"""
This function trains the single layer MLP using the Adams optimizer and
cross entropy loss. K-fold cross validation is also implemented to help
prevent overfitting of the model.
Parameters:
x_train... | ee041a7fd2752b8d4d597797dab2de4175ba521e | 3,600,312 |
import numpy as np
def mask_ccf_near_RV(rv,ccf,RVp,hw):
"""
This mask a region in the ccf near a the velocity RVp, typically for the
purpose of masking velocities that are close to the expected velocity of the planet
(hence RVp). RVp should be a list or array-like object with the same number of elemen... | d074183960dc6d665f905b592cb820a3eabf349c | 3,600,313 |
def get_time(direction, day, driver):
"""
Returns the time of departure of a given trip.
:param direction: "Salita" or "Discesa".
:param day: A day spanning the whole work week ("Lunedì"-"Venerdì").
:param driver: The chat_id of the driver.
:return: A string representing the departure time, form... | 0be7b0a100a3e105e2cce97aa4ea8e58e7a827ac | 3,600,315 |
from typing import Union
def global_mean(local_value: tc.Tensor,
world_size: int,
item: bool = False) -> Union[tc.Tensor, float]:
"""
Takes the global mean of a tensor across processes.
Args:
local_value (torch.Tensor): Torch tensor containing a metric.
wor... | 37792a76a177b7b5964d060798ed2a531461e898 | 3,600,316 |
def is_regex_url(url, regexp):
""" Wrapper method to search URL for different properties based on regex
:param url: URL
:type url: `str`
:param regexp: Regular expression for the property
:type url: `str`
:return: True/False
:rtype: `bool`
"""
return len(regexp.findall(url)) > 0 | 8e5de88e8201805b95d91001067a7756749be048 | 3,600,317 |
def hidden_loc(obj, name):
"""
Generate the location of a hidden attribute.
Importantly deals with attributes beginning with an underscore.
"""
return ("_" + obj.__class__.__name__ + "__" + name).replace("___", "__") | 5a8c3d066cb96cf282c1b8814ac1302bd68111c0 | 3,600,318 |
def get_num_accessions(session, batch):
"""
The total number of accession records in the batch
:param session: the Session in which to perform the query
:param batch: the name of the batch to limit the search to
:return: the total number of accession records in the batch
"""
return get_acce... | b88bde02292172003eb9b950b27111542f40ebdf | 3,600,319 |
def map_to_zero_one(vector):
"""
Mapping linearly the values in a 2 dimesion vector to [0,1] interval.
Parameters:
-----------
vector: 2d numpy
Return:
-------
scaled_vector: numpy
an array with the same size of vector, that its values are mapped between [0, 1]
... | 5c67a411dd63ee048ebeccea7df4dc564ca151c8 | 3,600,320 |
def get_point_image_feature(img_feature, image_v):
""" Get Image info
img_feature: [h, w, c]
image_v: [n, 2], x, y location for each
"""
points_num = image_v.shape[0]
channels = img_feature.shape[-1]
return_feature = np.zeros((points_num, channels), dtype=img_feature.dtype)
heigh... | c2d8098f8e286dbc5614e7fcc81937ae89dd5303 | 3,600,321 |
import json
def _load_cluster_config(input_file_path):
"""
Load queues_info and add information used to render templates.
:return: queues_info containing id for first queue, head_node_hostname and queue_name
"""
with open(input_file_path) as input_file:
return json.load(input_file) | b86f163da96be1f831da7997872825e852439f84 | 3,600,322 |
def PIT_training_function(loaded_file, i):
"""
:param loaded_file: file output from operant box
:param i: number of days analyzing
:return: data frame of all analysis extracted from file (one animal)
"""
(timecode, eventcode) = extract_info_from_file(loaded_file, 500)
(A_dur_individual, A_d... | 12a938a5b4bf36e9ce1eb1b27686f6976dbf53be | 3,600,323 |
def svn_repos_load_fs4(*args):
"""svn_repos_load_fs4(svn_repos_t * repos, svn_stream_t * dumpstream, svn_revnum_t start_rev, svn_revnum_t end_rev, enum svn_repos_load_uuid uuid_action, char const * parent_dir, svn_boolean_t use_pre_commit_hook, svn_boolean_t use_post_commit_hook, svn_boolean_t validate_props, svn_r... | e5a47b2865d4d012dceded24be3756413e118df3 | 3,600,324 |
def compose_official_address(company):
"""
:returns: the most official address for the given company as an object
with the following properties:
line_1
line_2
town
county
postcode
country
The values come from registered address if defined or from the addr... | 5c6b4bf5ff5c59382f00644bc19a61f4629dd174 | 3,600,325 |
import re
def divide_into_parts(text):
"""делим документ на части по паттернам"""
begin_pattern = to_bound_pattern(["УСТАНОВИЛ"])
end_pattern = to_bound_pattern(["ПРИГОВОРИЛ", "ПОСТАНОВИЛ", "РЕШИЛ"])
begin, main_part = re.split(begin_pattern, text, 1)
main_part, end = re.split(end_pattern, main_pa... | eab82e8d06424c39e882982a24ab98bac3caeba1 | 3,600,326 |
def ExtendedBinaryGolayCode():
"""
ExtendedBinaryGolayCode() returns the extended binary Golay code.
This is a perfect [24,12,8] code. This code is self-dual.
EXAMPLES::
sage: C = codes.ExtendedBinaryGolayCode()
sage: C
Linear code of length 24, dimension 12 over Finite Field o... | ba657d85bf0008dd104f975f8095759abb673cd9 | 3,600,327 |
from typing import IO
def autoOne_cmd(file: IO[str], interactionId: int = 0, where: Range = None, expr: str = ''):
"""Automatic proof search, find proofs, specific hole.
"""
return ('autoOne', {'file': file, 'expr': expr, 'interactionId': interactionId, 'where': where}) | e650f6d5f22fded1974d130ed3ca3c2e95a1d5b2 | 3,600,328 |
def find_neighbors_hexagonal_grid(map_coordinates: list, current_position: tuple) -> list:
"""Finds the set of adjacent positions of coordinates 'current_position' in a hexagonal grid.
Args:
map_coordinates (list): List of map coordinates.
current_position (tuple): Current position of the hexag... | 2a6071d59a69b828eb252504508fa3f706969e1b | 3,600,329 |
from typing import List
from typing import Tuple
def _address_balances() -> List[Tuple[str, Decimal]]:
"""
Calculate the balance for each address in ``internal['addresses']`` based on
stored transactions.
"""
balances = {}
for tx in internal['transactions']:
addr = tx['address']
... | c859f151db19cec60b6b97a15a19d02577351e93 | 3,600,330 |
def Pose_2_ABB(H):
"""Converts a pose to an ABB target (using quaternion representation).
:param H: pose
:type H: :class:`.Mat`
.. seealso:: :class:`.Mat`, :func:`~robodk.TxyzRxyz_2_Pose`, :func:`~robodk.Pose_2_TxyzRxyz`, :func:`~robodk.Pose_2_ABB`, :func:`~robodk.Pose_2_Adept`, :func:`~robodk.Pose_2_... | b4d0f6111d19ffe20c520cad0adf1f9a4b6a00f1 | 3,600,331 |
def create_encounter(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
patient_id,
):
"""Creates a new Encounter resource in a FHIR store based on a Patient."""
url = "{}/projects/{}/locations/{}".format(base_url, project_id, cloud_region)
fhi... | 9ad6f2ea0a9b8d2356be55dc0d8a8a79a35dd362 | 3,600,332 |
def find_first(pattern: str, path: str) -> str:
"""
Finds first file in ``path`` whose filename matches ``pattern`` (via
:func:`fnmatch.fnmatch`), or raises :exc:`IndexError`.
"""
try:
return find(pattern, path)[0]
except IndexError:
log.critical('''Couldn't find "{}" in "{}"''',... | b130cc09276f943bae967e639dcd8753cdeefc57 | 3,600,333 |
import pyarrow as pa
def ST_Contains(left, right):
"""
Check whether a geometry contain another geometry.
For every (left, right) pair with the same offset value in left and right, check
if left_geometry "contains" right_geometry. Left "contains" right means no points
of right_geometry lie in the... | af24efee790ec50e6b766c0a188fb3a580242436 | 3,600,334 |
import re
import json
def compileMorphemicAnalysis_(form, morpheme_delimiters=None, **kwargs):
"""Generate values fo the morphological analysis-related attributes of a form model.
:param form: the form model for which the morphological values are to be generated.
:param list valid_delimiters: morpheme de... | f6d578c80acb11bcc0bc873fe194cc5c464294be | 3,600,335 |
import toml
def load_config_from_string():
"""returns a function that loads a configuration dictionary from a string"""
def load(s):
return bridge.config.ConfigSchema().load(toml.loads(s))
return load | 10cce745dcd386f920064abe27fc65e5430b5daf | 3,600,336 |
def set_multindex_dtype(df: pd.DataFrame, dtype: str = 'str') -> pd.DataFrame:
"""set the dtype of all levels of a multi-index, by default to string"""
new_index = [df.index.get_level_values(idx).astype(dtype) for idx in range(len(df.index.levels))]
df.index = new_index
return df | 6ef0f545a861aea051e374f238b001dd7a625155 | 3,600,337 |
def image_id(identifier):
"""Redirect a plain image id"""
return flask.redirect(flask.url_for('image_info', identifier=identifier), code=303) | 813a6e66da5ee25b69245b7c1db301f224bf7d32 | 3,600,338 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.