content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from .esri_basemap import esrimap
def classFactory(iface): # pylint: disable=invalid-name
"""Load esrimap class from file esrimap.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
#
return esrimap(iface) | 3e067a97cba21a07c818077e4207cd8e337143d9 | 8,849 |
def gpib_open(name):
"""
Start a device session.
Returns a unique integer for the instrument at the specified GPIB address.
For example::
>>> gpib_open(lan[158.154.1.110]:19)
4
@param name : LAN/GPIB address of the device
@type name : str
@return: int
"""
(devtype,devID) = name.split()
add... | fa9e87a3873248866586758c0b0f370a3ad29e6e | 8,850 |
def myjobs_view(request):
"""
Renderbox view
:param request:
:return:
"""
return render(request, 'renderbox/myjobs.html') | ac0ffbc92a33657a165beb5e12905e3dc495c943 | 8,851 |
def _match_contact(filter_criteria):
"""
This default matching strategy function will attempt to get a single result
for the specified criteria.
It will fail with an `unmatched` result if there are no matching contacts.
It will fail with a `multiple_matches` result if there are multiple matches
... | 088199ac26dc226e1412b43ed0c9b380c669c64e | 8,853 |
from typing import Generator
def get_objects_dictionary():
"""
creates a dictionary with the types and the circuit objects
:return: Dictionary instance
"""
object_types = {'bus': Bus(),
'load': Load(),
'static_generator': StaticGenerator(),
... | bd82c2dc30877f841e4275aafbe054849b6f6ba2 | 8,854 |
def create_stripe_onboarding_link(request, stripe_id=None,):
"""Creates stripe connect onboarding link by calling Stripe API."""
account_links = stripe.AccountLink.create(
account=stripe_id,
return_url=request.build_absolute_uri(
reverse("users:stripe_callback")
),
re... | 1dd1e7c50645fb5eaa36d7426abd5cff198e1610 | 8,855 |
def add_scheme_if_missing(url):
"""
>>> add_scheme_if_missing("example.org")
'http://example.org'
>>> add_scheme_if_missing("https://example.org")
'https://example.org'
"""
if "//" not in url:
url = "http://%s" % url
return url | 97a33ce1f60ab67e6a807ef1bd1d95250b5d18c6 | 8,856 |
from typing import Dict
def _extract_assembly_information(job_context: Dict) -> Dict:
"""Determine the Ensembl assembly version and name used for this index.
Ensembl will periodically release updated versions of the
assemblies which are where the input files for this processor
comes from. All divisi... | b78513b826c0a12bf87563095e33320aee328b76 | 8,857 |
def fixture_circle_2() -> Circle:
"""Return an example circle."""
return Circle(Point(0.0, 0.0), 1.0) | 4040cb356a1e09cfe83280711d93a43b9352ff66 | 8,858 |
from warnings import warn
import logging
from fparser import api
from loopy.frontend.fortran.translator import F2LoopyTranslator
from loopy.transform.callable import merge
from loopy.frontend.fortran.translator import specialize_fortran_division
def parse_fortran(source, filename="<floopy code>", free_form=None, stri... | 69d85ba20fd429598d3441297a89a12933f69925 | 8,859 |
def compute_sources(radius, evolved_vars):
"""
Computes source terms for the symmetry.
"""
mass_density = evolved_vars[0]
momentum_density = evolved_vars[1]
energy_density = evolved_vars[2]
factor = -_symmetry_alpha / radius
pressure = compute_pressure(mass_density, momentum_density, ene... | f2c7c68f3d00a063f9a29b220f98f71c6bb02aef | 8,860 |
def average_pq(ps, qs):
""" average the multiple position and quaternion array
Args:
ps (np.array): multiple position array of shape Nx3
qs (np.array): multiple quaternion array of shape Nx4
Returns:
p_mean (np.array): averaged position array
q_mean (np.array): averaged qua... | b7064d75f07361d60375de1dad91e0139533b042 | 8,861 |
def logobase(**kwargs):
"""Create a PyGraphviz graph for a logo."""
ag = pygraphviz.AGraph(bgcolor='#D0D0D0', strict=False, directed=True, ranksep=0.3, **kwargs)
ag.edge_attr['penwidth'] = 1.4
ag.edge_attr['arrowsize'] = 0.8
return ag | 60772de3f3b33f58559ecfd3293cffc26cfe8e70 | 8,862 |
import torch
def integral_raycasting(
pixels: Tensor,
mu: Tensor,
rho: Tensor,
lambd: Tensor,
appearance: Tensor,
background_appearance: Tensor,
K: Tensor,
dist_coef: Tensor = None,
alpha: float = 2.5e-2,
beta: float = 2e0,
eps: float = 1e-8,
) -> Tensor:
"""
:para... | fc5165c04732ea021d105df5d5f997524b037abd | 8,863 |
async def cors_handler(request, handler):
"""Middleware to add CORS response headers
"""
response = await handler(request)
response.headers['Access-Control-Allow-Origin'] = '*'
return response | c9f33261b1fb2e6dc3ab3139e657106a94c5bfd1 | 8,864 |
def validate_image(task: ExternalTask):
"""
To simulate BPMN/Failure/Success, this handler uses image name variable (to be passed when launching the process)
"""
log_context = {"WORKER_ID": task.get_worker_id(),
"TASK_ID": task.get_task_id(),
"TOPIC": task.get_topic... | 97413656181bfc4480dc7b2a195713e8124d44f2 | 8,865 |
def simulate_patch(app, path, **kwargs):
"""Simulates a PATCH request to a WSGI application.
Equivalent to::
simulate_request(app, 'PATCH', path, **kwargs)
Args:
app (callable): The WSGI application to call
path (str): The URL path to request
Keyword Args:
params (di... | 48fda74dc2765e3a281a71c7ba6f4144e9a258cd | 8,866 |
def minimum_image_box(sizes):
"""Creates a distance wrapper using the minimum image convention
Arguments:
sizes (array-like of float): box sizes
"""
def _box(sizes, distance_vectors):
"""A minimum image wrapper for distances"""
shift = sizes[None, None, :] * np.round(distance_ve... | 5d26092a988a011e9fb1967a74c3ceec935f5b1b | 8,867 |
def mlrPredict(W, data):
"""
mlrObjFunction predicts the label of data given the data and parameter W
of Logistic Regression
Input:
W: the matrix of weight of size (D + 1) x 10. Each column is the weight
vector of a Logistic Regression classifier.
X: the data matrix of siz... | 57542e5b54ddd223f4cbcae7adf932e85c4ffeeb | 8,868 |
def calc_mean_score(movies):
"""Helper method to calculate mean of list of Movie namedtuples,
round the mean to 1 decimal place"""
return round(sum([movie.score for movie in movies]) / len(movies), 1) | ccf52f813091d1c907470996c62dafa61303e245 | 8,869 |
import hmac
import hashlib
def get_proxy_signature(query_dict, secret):
"""
Calculate the signature of the given query dict as per Shopify's documentation for proxy requests.
See: http://docs.shopify.com/api/tutorials/application-proxies#security
"""
# Sort and combine query parameters into a sin... | c234f18c1d44a936c4844ae2fe1b912a624eef61 | 8,870 |
def candlestick_echarts(data_frame: pd.DataFrame, time_field: str = 'time', open_field: str = "open",
high_field: str = 'high',
low_field: str = 'low',
close_field: str = 'close',
volume_field: str = 'volume', mas: list = [5... | f8bc3d1ef876a5df0f2fdbdf7dbf97b039a54cc4 | 8,871 |
def select_sounder_hac(path_sounder, sounder):
"""
Donne les indices pour un sondeur (sounder) dans un hac (path sounder), et retourne les index de sondeur et de transducer correspondant
inputs:
path_sounder: path du hac à analyser
sounder: nom du transducer
outputs:
index du son... | 2f054ef6a8e3a64f0910e5eb4bce9407befc4b33 | 8,872 |
def upvote_checklist(request, checklist_id):
# for "messages", refer https://stackoverflow.com/a/61603003/6543250
"""if user cannot retract upvote, then this code be uncommented
if Upvote.objects.filter(user=User.objects.filter(username=username).first(), checklist=Checklist.objects.get(id=checklist_id)):
... | 559f9e0341652391b824b215448f87fa3250baae | 8,873 |
def index(request):
"""查询页面"""
ctx = {}
Advert_1 = Advert.objects.get(advert_num=1) # 广告1
Advert_2 = Advert.objects.get(advert_num=2) # 广告2
ctx['Adverturl1'] = Advert_1.advert_url
ctx['Adverturl2'] = Advert_2.advert_url
ctx['Advertimg1'] = '/advert/'+ str(Advert_1.img)
ctx['Advertimg2... | 91e7a771273ed262e7025bc289defe7f6a52047e | 8,874 |
def load_amazon():
"""
"""
df = pd.read_csv('data/amazon.txt',
header=None,
delimiter='\t')
X_data = df[0].tolist()
y_data = df[1].tolist()
print 'Preprocessing...'
vectorizer = TfidfVectorizer(strip_accents='unicode',
lowercase=True,
stop_words='english',
ngram_range=(1, 2),
max_df=0.5,
min_df=5... | 8e11cf91d616f7dfe17e26da2fcf43d82ea26f80 | 8,875 |
def get_switch_filters(
switch_id, exception_when_missing=True,
user=None, session=None, **kwargs
):
"""get filters of a switch."""
return _get_switch(
switch_id, session=session,
exception_when_missing=exception_when_missing
) | db270f761fcdfb40a9d2970923b4643ebecf7cc3 | 8,876 |
def generalized_zielonka_with_psolC(g):
"""
Zielonka's algorithm with psolC partial solver.
:param g: the game to solve.
:return: the solution in the following format : (W_0, W_1).
"""
return generalized_parity_solver_with_partial(g, psolC_gen.psolC_generalized) | 1ac4a81df393970c16a5f303155c89cf74db34ab | 8,877 |
from datetime import datetime
def read_properties_core(xml_source):
"""Read assorted file properties."""
properties = DocumentProperties()
root = fromstring(xml_source)
creator_node = root.find(QName(NAMESPACES['dc'], 'creator').text)
if creator_node is not None:
properties.creator = creat... | 357411103a52bbbfc6e621c47b734b9d11f04284 | 8,879 |
import torch
def batch_decode(loc, priors, variances):
"""Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_priors,4]
priors (tensor): Prior boxes ... | 7963b771e2c7bc560e5f9e5051abea43de2f46e3 | 8,880 |
def _step2_macs_seq (configs):
"""Step2 MACS if the raw data type is seq. So it will use the output from step1.
"""
# check the input
t_rep_files = configs["samtools.treat_output_replicates"]
t_comb_file = configs["samtools.treat_output"]
c_comb_file = configs["samtools.control_output"]
... | 69deb8fafeb3f7054901d431d6e32c647504258f | 8,881 |
def menu_entry_to_db(entry):
"""
Converts a MenuEntry into Meal, Menu, and MenuItem objects which are stored in the database.
"""
menu, _ = Menu.objects.get_or_create(date=entry.date)
meal = Meal.objects.create(meal_type=entry.meal_type, vendor=entry.vendor)
for item_name in entry.items:
... | f35ddb4bb715a3a8bcee073fd863a5f4d8240651 | 8,882 |
import torch
def get_device_of(tensor: torch.Tensor) -> int:
"""
Returns the device of the tensor.
"""
if not tensor.is_cuda:
return -1
else:
return tensor.get_device() | 5532712bd812842fc462951e7c763b9753370174 | 8,883 |
def test_script_task(scheduler: Scheduler) -> None:
"""
Tasks should be definable as shell scripts.
"""
@task(script=True)
def task1(message):
return """echo Hello, {message}!""".format(message=message)
assert scheduler.run(task1("World")) == b"Hello, World!\n" | c5f764b06f1245feb9ab0c1af5a13fd368fde362 | 8,884 |
import copy
def __yaml_tag_test(*args, **kwargs):
"""YAML tag constructor for testing only"""
return copy.deepcopy(args), copy.deepcopy(kwargs) | 0abeb68caf32912c7b5a78dacbc89e537061a144 | 8,885 |
def format_data_for_training(data):
"""
Create numpy array with planet features ready to feed to the neural net.
:param data: parsed features
:return: numpy array of shape (number of frames, PLANET_MAX_NUM, PER_PLANET_FEATURES)
"""
training_input = []
training_output = []
for d in data:
... | b241a932f7a5321ed28dccd8a583fbcf7529e482 | 8,887 |
import urllib
import json
def idcardcert(appcode, card_no):
""" 身份证实名认证身份证二要素一致性验证 """
host = 'http://idquery.market.alicloudapi.com'
path = '/idcard/query'
# method = 'GET'
appcode = appcode
querys = 'number=%s' % card_no
# bodys = {}
url = host + path + '?' + querys
try:
... | a359edf15e7b8795fc80ceda1008f1809d9c52a0 | 8,888 |
def custom_error_exception(error=None, exception=None):
"""Define custom exceptions for MySQL server errors
This function defines custom exceptions for MySQL server errors and
returns the current set customizations.
If error is a MySQL Server error number, then you have to pass also the
exception ... | eb24301d2511199e1ee1407152f27d00b72adba5 | 8,889 |
import hashlib
def cal_md5(content):
"""
计算content字符串的md5
:param content:
:return:
"""
# 使用encode
result = hashlib.md5(content.encode())
# 打印hash
md5 = result.hexdigest()
return md5 | 0cd26654c364e34ecc27b0a0b4d410a539e286c3 | 8,890 |
def pas(al, ap, bl,bp):
""" Postion-angle from spherical coordinates.
:param al: longitude of point A in radians.
:type al: float
:param ap: latitude of point A in radians.
:type ap: float
:param bl: longitude of point B in radians.
:type bl: float
:param bp: latitude of point B in r... | 9d8321c908c793df84e5ff28c51e4a79f6db99c6 | 8,894 |
def get_messy_items_for_training(mod_factor=5):
"""
Fetch a subset of `FacilityListItem` objects that have been parsed and are
not in an error state.
Arguments:
mod_factor -- Used to partition a subset of `FacilityListItem` records. The
larger the value, the fewer records will be ... | d04f5471266c33cfea122adac72835043ed6c34a | 8,895 |
def tanh_squared(x: np.ndarray, margin: float, loss_at_margin: float = 0.95):
"""Returns a sigmoidal shaping loss based on Hafner & Reidmiller (2011).
Args:
x: A numpy array representing the error.
margin: Margin parameter, a positive `float`.
loss_at_margin: The loss when `l2_norm(x) == margin`. A `fl... | 4c8dbb826dad5b047682fe030362f4fe71021f06 | 8,896 |
def _inv_Jacobian_2D(J, detJ):
""" manually invert 2x2 jacobians J in place """
tmp = J[:, 1, 1, :] / detJ
J[:, 0, 1, :] = -J[:, 0, 1, :] / detJ
J[:, 1, 0, :] = -J[:, 1, 0, :] / detJ
J[:, 1, 1, :] = J[:, 0, 0, :] / detJ
J[:, 0, 0, :] = tmp
return J | 23b1ff231e32f09f09dbae781f7e97354f3ca811 | 8,897 |
def ratio_error_acc(y_true, y_pred, epsilon, threshold):
"""
Calculate the ratio error accuracy with the threshold.
:param y_true:
:param y_pred:
:param epsilon:
:param threshold:
:return:
"""
ratio_1 = keras.layers.Lambda(lambda x: (x[0] + x[2]) / (x[1] + x[2]))([y_true, y_pred, eps... | 9ae487e056800ac9fb5cc6e92301b74c00d65c21 | 8,898 |
def error_embed(ctx: context.ApplicationContext, title: str, description: str, author: bool = True) -> discord.Embed:
"""Make a basic error message embed."""
return make_embed(
ctx=ctx,
title=title if title else "Error:",
description=description,
color=discord.Color.red(),
... | aca18ec2d25c4f0a2dec7f4c083716ab9bf4dbae | 8,899 |
from typing import Dict
from typing import Any
import toml
from pathlib import Path
import textwrap
def load_configuration() -> Dict[str, Any]:
"""
Return dict from TOML formatted string or file.
Returns:
The dict configuration.
"""
default_config = """
[key_bindings]
... | a7a53382dd43023b74fbb88b9c2540499c9beb4f | 8,900 |
def type_weapon(stage, bin, data=None):
"""Weapon"""
if data == None:
return 1
if stage == 1:
return (str(data),'')
try:
v = int(data)
if 0 > v or v > 255:
raise
except:
raise PyMSError('Parameter',"Invalid Weapon value '%s', it must be 1 for ground attack or not 1 for air attack." % data)
return v | 51ad1c627b05b57ad67f5558bb76de3fe6e48f27 | 8,901 |
def to_square_feet(square_metres):
"""Convert metres^2 to ft^2"""
return square_metres * 10.7639 | 50510aad230efcb47662936237a232662fef5596 | 8,902 |
def middle_name_handler(update: Update, context: CallbackContext) -> str:
"""Get and save patronymic of user. Send hello with full name."""
u = User.get_user(update, context)
name = (f'{context.user_data[LAST_NAME]} {context.user_data[FIRST_NAME]} '
f'{context.user_data[MIDDLE_NAME]}')
cont... | dab2144282aeb63c2a3c4218236d04c3bb940ac8 | 8,903 |
def submit_barcodes(barcodes):
"""
Submits a set of {release1: barcode1, release2:barcode2}
Must call auth(user, pass) first
"""
query = mbxml.make_barcode_request(barcodes)
return _do_mb_post("release", query) | 6e975e791196ed31ef6f52cdd0ca04d71a8d19eb | 8,904 |
from typing import Counter
def get_idf_dict(arr, tokenizer, nthreads=4):
"""
Returns mapping from word piece index to its inverse document frequency.
Args:
- :param: `arr` (list of str) : sentences to process.
- :param: `tokenizer` : a BERT tokenizer corresponds to `model`.
- :pa... | e98a9578695781e4965b36d713c4c0a4351e53da | 8,905 |
import json
def load_id_json_file(json_path):
"""
load the JSON file and get the data inside
all this function does is to call json.load(f)
inside a with statement
Args:
json_path (str): where the target JSON file is
Return:
ID list (list): all the d... | fd0f7fb73636cdf407b4de3e1aa3ae66dcc8f964 | 8,906 |
def check_github_scopes(exc: ResponseError) -> str:
"""
Parse github3 ResponseError headers for the correct scopes and return a
warning if the user is missing.
@param exc: The exception to process
@returns: The formatted exception string
"""
user_warning = ""
has_wrong_status_code = e... | ebb3fffcaddc792dac7c321d9029b5042a42be86 | 8,907 |
def user_login():
"""
# 显示页面的设置
:return: 接收前端的session信息来显示不同的页面
"""
# 获取参数
name = session.get("name")
if name is not None:
return jsonify(errno=RET.OK, errmsg="True", data={"name": name})
else:
return jsonify(errno=RET.SESSIONERR, errmsg="用户未登入") | 213ad2338260364186c0539a9e995b84ee889b42 | 8,908 |
def sample_conditional(node: gtsam.GaussianConditional, N: int, parents: list = [], sample: dict = {}):
"""Sample from conditional """
# every node ~ exp(0.5*|R x + S p - d|^2)
# calculate mean as inv(R)*(d - S p)
d = node.d()
n = len(d)
rhs = d.reshape(n, 1)
if len(parents) > 0:
rhs... | b9ab05ea50eea05a779c6d601db4643a86b343d5 | 8,909 |
def _liftover_data_path(data_type: str, version: str) -> str:
"""
Paths to liftover gnomAD Table.
:param data_type: One of `exomes` or `genomes`
:param version: One of the release versions of gnomAD on GRCh37
:return: Path to chosen Table
"""
return f"gs://gnomad-public-requester-pays/relea... | 8da0f93c86568d56b3211bcb9e226b9cb495c8e2 | 8,910 |
def valueinfo_to_tensor(vi):
"""Creates an all-zeroes numpy tensor from a ValueInfoProto."""
dims = [x.dim_value for x in vi.type.tensor_type.shape.dim]
return np.zeros(
dims, dtype=onnx.mapping.TENSOR_TYPE_TO_NP_TYPE[vi.type.tensor_type.elem_type]
) | b814373e7c9d4f1e43f9d1af0c6e48b82989602e | 8,911 |
def signup_email():
"""Create a new account using data encoded in the POST body.
Expects the following form data:
first_name: E.g. 'Taylor'
last_name: E.g. 'Swift'
email: E.g. 'tswift@gmail.com'
password: E.g. 'iknewyouweretrouble'
Responds with the session cookie via the `... | e3ecca4bd244d1d20ad166a153a6c3f5c80f4876 | 8,912 |
def calculate_multi_rmse(regressor, n_task):
"""
Method which calculate root mean squared error value for trained model
Using regressor attributes
Return RMSE metrics as dict for train and test datasets
:param regressor: trained regression model object
:param n_task:
:type regressor: Traine... | 53daee6abb97a96af44831df59767a447fd2786e | 8,913 |
import torch
from re import T
def detr_predict(model, image, thresh=0.95):
"""
Function used to preprocess the image, feed it into the detr model, and prepare the output draw bounding boxes.
Outputs are thresholded.
Related functions: detr_load, draw_boxes in coco.py
Args:
model -- the... | 394824358138eb66b69569963b21ccc2d0f5a4d3 | 8,914 |
def comp_fill_factor(self):
"""Compute the fill factor of the winding"""
if self.winding is None:
return 0
else:
(Nrad, Ntan) = self.winding.get_dim_wind()
S_slot_wind = self.slot.comp_surface_wind()
S_wind_act = (
self.winding.conductor.comp_surface_active()
... | 55be8ac7aa2961ad970cd16de961fdcf857016fd | 8,915 |
def idewpt(vp):
"""
Calculate the dew point given the vapor pressure
Args:
vp - array of vapor pressure values in [Pa]
Returns:
dewpt - array same size as vp of the calculated
dew point temperature [C] (see Dingman 2002).
"""
# ensure that vp is a numpy array
... | 68b58d7702a50472a4851e1a7ecdd6ba13fe540a | 8,916 |
def _hexify(num):
"""
Converts and formats to hexadecimal
"""
num = "%x" % num
if len(num) % 2:
num = '0'+num
return num.decode('hex') | 71fabff1191f670ec503c76a3be916636e8045ce | 8,917 |
def syn_ucbpe(num_workers, gp, acq_optimiser, anc_data):
""" Returns a recommendation via UCB-PE in the synchronous setting. """
# Define some internal functions.
beta_th = _get_ucb_beta_th(gp.input_dim, anc_data.t)
# 1. An LCB for the function
def _ucbpe_lcb(x):
""" An LCB for GP-UCB-PE. """
mu, sigm... | 2c12a608c87d61f64b219aaf301189b6c8ee73a2 | 8,918 |
def get_reward(intervention, state, time):
"""Compute the reward based on the observed state and choosen intervention."""
A_1, A_2, A_3 = 60, 500, 60
C_1, C_2, C_3, C_4 = 25, 20, 30, 40
discount = 4.0 / 365
cost = (
A_1 * state.asymptomatic_humans
+ A_2 * state.symptomatic_humans
... | 72803b1a5f09d0856d29601bc766b6787a8255e7 | 8,919 |
def array_of_floats(f):
"""Read an entire file of text as a list of floating-point numbers."""
words = f.read().split()
return [builtin_float(x) for x in words] | 8b357afb3f977761118f7df2632a4f1c198d721a | 8,920 |
def change_currency():
""" Change user's currency """
form = CurrencyForm()
if form.validate_on_submit():
currency = form.rate.data
redirected = redirect(url_for('cashtrack.overview'))
redirected.set_cookie('filter', currency)
symbol = rates[currency]['symbol']
flash(... | 08a23e47a603ee5d5e49cff0259a83f4a2ffc3e0 | 8,921 |
def q2_1(df: pd.DataFrame) -> int:
"""
Finds # of entries in df
"""
return df.size[0] | d98a3d5592994e7dd3758dfab683cb96b532ce6d | 8,923 |
def is_shell(command: str) -> bool:
"""Check if command is shell."""
return command.startswith(get_shell()) | 0cc1497dc17e1535fdfb23c1b160bfcd63141eb1 | 8,924 |
def board_init():
"""
Initializes board with all available values 1-9 for each cell
"""
board = [[[i for i in range(1,n+1)] for j in range(n)] for k in range(n)]
return board | e4b7192c02e298de915eb3024f32f194942a061b | 8,926 |
def gen_int_lists(num):
"""
Generate num list strategies of integers
"""
return [
s.lists(s.integers(), max_size=100)
for _ in range(num)
] | f1bd151a09f78b1eee9803ce2a077a4f01d34aaa | 8,927 |
def is_blob(bucket: str, file:str):
""" checking if it's a blob """
client = storage.Client()
blob = client.get_bucket(bucket).get_blob(file)
return hasattr(blob, 'exists') and callable(getattr(blob, 'exists')) | ba9bb07f1f15175a28027907634c37b402c6b292 | 8,928 |
from typing import Union
def _is_whitelisted(name: str, doc_obj: Union['Module', 'Class']):
"""
Returns `True` if `name` (relative or absolute refname) is
contained in some module's __pdoc__ with a truish value.
"""
refname = doc_obj.refname + '.' + name
module = doc_obj.module
while modul... | c54c69ae0180c1764c8885d00e96640f1bfff0f8 | 8,930 |
import copy
def permute_bond_indices(atomtype_vector):
"""
Permutes the set of bond indices of a molecule according to the complete set of valid molecular permutation cycles
atomtype_vector: array-like
A vector of the number of each atoms, the length is the total number of atoms.
An A3B8C ... | ebf398e55d8a80a2e4ce2cef4f48d957e47d68a3 | 8,931 |
def get_cell_integer_param(device_resources,
cell_data,
name,
force_format=None):
"""
Retrieves definition and decodes value of an integer cell parameter. The
function can optionally force a specific encoding format if needed.
... | 6ab281004f324e8c40e176d5676cd7e42f50eaa9 | 8,932 |
import hashlib
def get_md5(filename):
""" Calculates the MD5 sum of the passed file
Args:
filename (str): File to hash
Returns:
str: MD5 hash of file
"""
# Size of buffer in bytes
BUF_SIZE = 65536
md5 = hashlib.md5()
# Read the file in 64 kB blocks
... | c43538aee954f670c671c2e26e18f4a17e298455 | 8,933 |
def is_recurrent(sequence):
"""
Returns true if the given sequence is recurrent (elements can exist more than once), otherwise returns false.
Example
---------
>>> sequence = [1,2,3,4,5]
>>> ps.is_recurrent(sequence)
False
>>> sequence = [1,1,2,2,3]
>>> ps.is_recurrent(sequence)
True
"""
element_counts... | e123ddd960b262651b20e54ccbd3d5b11fe3695e | 8,935 |
import torch
def flex_stack(items, dim=0):
"""
"""
if len(items) < 1:
raise ValueError("items is empty")
if len(set([type(item) for item in items])) != 1:
raise TypeError("items are not of the same type")
if isinstance(items[0], list):
return items
elif isinstance(it... | 47ca0e47647ce86619f1cdc86eef560fbbb9304e | 8,936 |
from pathlib import Path
def download_image_data(gpx_file,
padding,
square,
min_lat,
min_long,
max_lat,
max_long,
cache_di... | 4ceef45da21622ab716031e8f68ed4724e168062 | 8,937 |
def find_nearest_values(array, value):
"""Find indexes of the two nearest values of an array to a given value
Parameters
----------
array (numpy.ndarray) : array
value (float) : value
Returns
-------
idx1 (int) : index of nearest value in the array
idx2 (int) : index of s... | 9c873692878ef3e4de8762bb89306e7ef907f90a | 8,938 |
def channel_info(channel_id):
"""
Get Slack channel info
"""
channel_info = slack_client.api_call("channels.info", channel=channel_id)
if channel_info:
return channel_info['channel']
return None | 260eeaa2849350e2ede331ddecd68aead798f76c | 8,939 |
from typing import Callable
from typing import Any
import logging
def log(message: str) -> Callable:
"""Returns a decorator to log info a message before function call.
Parameters
----------
message : str
message to log before function call
"""
def decorator(function: Callable) -> Cal... | c8ed8f8119be8d6e80935d73034f752ad2cb1dd9 | 8,940 |
def client(identity: PrivateIdentity) -> Client:
"""Client for easy access to iov42 platform."""
return Client(PLATFORM_URL, identity) | a0ad172765b50a76485bd3ec630a2c3ffeae85ef | 8,941 |
def init_weights(module, init='orthogonal'):
"""Initialize all the weights and biases of a model.
:param module: any nn.Module or nn.Sequential
:param init: type of initialize, see dict below.
:returns: same module with initialized weights
:rtype: type(module)
"""
if init is None: # Base ... | e8cd95743b8a36dffdb53c7f7b9723e896d2071d | 8,942 |
def getsoundchanges(reflex, root): # requires two ipastrings as input
"""
Takes a modern-day L1 word and its reconstructed form and returns \
a table of sound changes.
:param reflex: a modern-day L1-word
:type reflex: str
:param root: a reconstructed proto-L1 word
:type root: str
:re... | 8230e836e109ed8453c6fdbc72e6a4f77833f69b | 8,943 |
def compute_normals(filename, datatype='cell'):
"""
Given a file, this method computes the surface normals of the mesh stored
in the file. It allows to compute the normals of the cells or of the points.
The normal computed in a point is the interpolation of the cell normals of
the cells adiacent to ... | e0cfc90a299f6db52d9cec2f39eebfc96158265c | 8,944 |
from typing import List
from typing import Optional
def build_layers_url(
layers: List[str], *, size: Optional[LayerImageSize] = None
) -> str:
"""Convenience method to make the server-side-rendering URL of the provided layer URLs.
Parameters
-----------
layers: List[:class:`str`]
The ima... | 2cc7ab58af2744a4c898903d9a035c77accbae2e | 8,945 |
def SyncBatchNorm(*args, **kwargs):
"""In cpu environment nn.SyncBatchNorm does not have kernel so use nn.BatchNorm2D instead"""
if paddle.get_device() == 'cpu':
return nn.BatchNorm2D(*args, **kwargs)
else:
return nn.SyncBatchNorm(*args, **kwargs) | f08a7141700b36286893bbbc82b28686d1ca88a9 | 8,946 |
def data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_peak_burst_size_get(uuid, local_id): # noqa: E501
"""data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_peak_burst_size_get
returns tapi.common.Capac... | 340189bc76bdbbc14666fe542aa05d467c7d4898 | 8,947 |
import re
def parse_path_length(path):
"""
parse path length
"""
matched_tmp = re.findall(r"(S\d+)", path)
return len(matched_tmp) | 762e2b86fe59689800ed33aba0419f83b261305b | 8,948 |
def check_permisions(request, allowed_groups):
""" Return permissions."""
try:
profile = request.user.id
print('User', profile, allowed_groups)
is_allowed = True
except Exception:
return False
else:
return is_allowed | 4bdb54bd1edafd7a0cf6f50196d470e0d3425c66 | 8,949 |
def kanji2digit(s):
"""
1から99までの漢数字をアラビア数字に変換する
"""
k2d = lambda m, i: _kanjitable[m.group(i)]
s = _re_kanjijiu1.sub(lambda m: k2d(m,1) + k2d(m,2), s)
s = _re_kanjijiu2.sub(lambda m: u'1' + k2d(m,1), s)
s = _re_kanji.sub(lambda m: k2d(m,1), s)
s = s.replace(u'十', u'10')
return s | 27589cee8a9b4f14ad7120061f05077b736b8632 | 8,950 |
def load_featurizer(pretrained_local_path):
"""Load pretrained model."""
return CNN_tf("vgg", pretrained_local_path) | 1f39acdae01e484302d8f8051c2f55a178aa2301 | 8,952 |
from templateflow.conf import setup_home
def make_cmdclass(basecmd):
"""Decorate setuptools commands."""
base_run = basecmd.run
def new_run(self):
setup_home()
base_run(self)
basecmd.run = new_run
return basecmd | dc66370f19e2d1b3dbc2da3942f8923a07d8d9a6 | 8,954 |
def rmse(predictions, targets):
"""Compute root mean squared error"""
rmse = np.sqrt(((predictions - targets) ** 2).mean())
return rmse | 1a5fe824c5ef768f3df34463724fdd057d37901a | 8,955 |
import math
def format_timedelta(value, time_format=None):
""" formats a datetime.timedelta with the given format.
Code copied from Django as explained in
http://stackoverflow.com/a/30339105/932593
"""
if time_format is None:
time_format = "{days} days, {hours2}:{minutes2}:{seconds2}... | 0ee6a48e0eee5e553e665d44173f0a4843b4007f | 8,956 |
def categorical_log_likelihood(probs: chex.Array, labels: chex.Array):
"""Computes joint log likelihood based on probs and labels."""
num_data, unused_num_classes = probs.shape
assert len(labels) == num_data
assigned_probs = probs[jnp.arange(num_data), jnp.squeeze(labels)]
return jnp.sum(jnp.log(ass... | 6209fc59dc6a76f8afc49788b9e5c5a11f58354f | 8,957 |
def ask_name(question: str = "What is your name?") -> str:
"""Ask for the users name."""
return input(question) | 1cc9ec4d3bc48d7ae4be1b2cf8eb64a0b4f94b23 | 8,958 |
from typing import Sequence
def _maxcut(g: Graph, values: Sequence[int]) -> float:
"""
cut by given values $$\pm 1$$ on each vertex as a list
:param g:
:param values:
:return:
"""
cost = 0
for e in g.edges:
cost += g[e[0]][e[1]].get("weight", 1.0) / 2 * (1 - values[e[0]] * val... | 1ca8d2cfce6a741fb4eab55f7fcd9d9db5e3578f | 8,959 |
def cp_als(X, rank, random_state=None, init='randn', **options):
"""Fits CP Decomposition using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of components to be compute... | b6402f03ba4e8be7d0abb2b13232d88b07a73be9 | 8,960 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.