content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import json
def user_config(filename):
"""user-provided configuration file"""
try:
with open(filename) as file:
return json.loads(file.read(None))
except FileNotFoundError as fnf:
raise RuntimeError(f"File '{filename}' could not be found") from fnf
except json.JSONDecodeErr... | a6aa05d76b4aaa12c02ff97e4ab5ba4ba1245324 | 18,400 |
def _decomposed_dilated_conv2d(x, kernel_size, num_o, dilation_factor, name, top_scope, biased=False):
"""
Decomposed dilated conv2d without BN or relu.
"""
# padding so that the input dims are multiples of dilation_factor
H = tf.shape(x)[1]
W = tf.shape(x)[2]
pad_bottom = (dilation_factor -... | 578d9308834294a80e778548faba9eb9fe0329c5 | 18,401 |
from datetime import datetime
from typing import Tuple
async def post_autodaily(text_channel: TextChannel, latest_message_id: int, change_mode: bool, current_daily_message: str, current_daily_embed: Embed, utc_now: datetime.datetime) -> Tuple[bool, bool, Message]:
"""
Returns (posted, can_post, latest_message... | 309ad1c4554b2dcef6b2ddbcfd2d5652ea291488 | 18,402 |
def room_from_loc(env, loc):
"""
Get the room coordinates for a given location
"""
if loc == 'north':
return (1, 0)
if loc == 'south':
return (1, 2)
if loc == 'west':
return (0, 1)
if loc == 'east':
return (2, 1)
if loc == 'left':
return (1, 0)
... | 75192c47fd8d4b56332b35ec7c3b355927e50ca2 | 18,403 |
def count_encoder(df, cols):
"""count encoding
Args:
df: カテゴリ変換する対象のデータフレーム
cols (list of str): カテゴリ変換する対象のカラムリスト
Returns:
pd.Dataframe: dfにカテゴリ変換したカラムを追加したデータフレーム
"""
out_df = pd.DataFrame()
for c in cols:
series = df[c]
vc = series.value_counts(dropna=... | c8e5b0995d2915871e7614099cf3260566f75f05 | 18,404 |
def wrap_response(response):
"""Wrap a tornado response as an open api response"""
mimetype = response.headers.get('Content-Type') or 'application/json'
return OpenAPIResponse(
data=response.body,
status_code=response.code,
mimetype=mimetype,
) | 38edef05e0d2d0ae80c235ed82f00080b86c6cb1 | 18,405 |
def shifted(x):
"""Shift x values to the range [-0.5, 0.5)"""
return -0.5 + (x + 0.5) % 1 | c40585748120af5d0acd85e4fed49f0575a92a3d | 18,406 |
def computeAlignmentError(pP1, pP2, etype = 2, doPlot = False):
"""
Compute area-based alignment error. Assume that the
warping paths are on the same grid
:param pP1: Mx2 warping path 1
:param pP2: Nx2 warping path 2
:param etype: Error type. 1 (default) is area ratio.
2 is L1 Hausd... | cce79f3f1fa83475bc18f18004d8e2c79a8e59fa | 18,407 |
def _cumulative_grad(grad_sum, grad):
"""Apply grad sum to cumulative gradient."""
add = ops.AssignAdd()
return add(grad_sum, grad) | cb2b3ab6131fb4e289df29d33876f69c265c6e62 | 18,408 |
def run_node(node):
"""Python multiprocessing works strangely in windows. The pool function needed to be
defined globally
Args:
node (Node): Node to be called
Returns:
rslts: Node's call output
"""
return node.run_with_loaded_inputs() | a0f52020db20b4b67e83599bc0fb6c86ec2f9514 | 18,409 |
def getitimer(space, which):
"""getitimer(which)
Returns current value of given itimer.
"""
with lltype.scoped_alloc(itimervalP.TO, 1) as old:
c_getitimer(which, old)
return itimer_retval(space, old[0]) | 86716d3faedab3436bc1fcb5f77b80129884cf2d | 18,410 |
def substitute_T_and_RH_for_interpolated_dataset(dataset):
"""
Input :
dataset : Dataset interpolated along height
Output :
dataset : Original dataset with new T and RH
Function to remove interoplated values of T and RH in the original dataset and
replace with new values of T and R... | fe2fca2ea3889fca17d2e676d1d2a95634ac1782 | 18,411 |
def get_base_required_fields():
""" Get required fields for base asset from UI.
Fields required for update only: 'id', 'uid', ['lastModifiedTimestamp', 'location', 'events', 'calibration']
Present in input, not required for output:
'coordinates', 'hasDeploymentEvent', 'augmented', 'deployment_number... | 273c539d0c0b0da249e2bb171107aa775ce52ddf | 18,412 |
def reg_tab_ext(*model):
""" Performs weighted linear regression for various models building upon the model specified in section 4,
while additionally including education levels of a council candidate (university degree, doctoral/PhD degree)
A single model (i.e. function argument) takes on the form:... | be61f85e918c2cf91b720b9495968c9c9f4f7b6e | 18,413 |
def load_pdf(filename: str) -> pd.DataFrame:
""" Read PDF dataset to pandas dataframe """
tables = tabula.read_pdf(basedir + '\\' + filename, pages="all")
merged_tables = pd.concat(tables[1:])
merged_tables.head()
return merged_tables | c3d7a1c5b78a62d6d6b822ecc2a90246e1c3a6aa | 18,414 |
def he_xavier(in_size: int, out_size: int, init_only=False):
"""
Xavier initialization according to Kaiming He in:
*Delving Deep into Rectifiers: Surpassing Human-Level
Performance on ImageNet Classification
(https://arxiv.org/abs/1502.01852)
"""
stddev = tf.cast(tf.sqrt(2 / in_size), tf.float32)
W = tf.random_... | f76501537a25226f1a3f3fcb0953438dbfaa996f | 18,415 |
def GET_v1_keyboards_build_log():
"""Returns a dictionary of keyboard/layout pairs. Each entry is a dictionary with the following keys:
* `works`: Boolean indicating whether the compile was successful
* `message`: The compile output for failed builds
"""
json_data = qmk_redis.get('qmk_api_configura... | b1e2c3f5da654987bdb7530be8f62effbf878613 | 18,416 |
def logprod(lst):
"""Computes the product of a list of numbers"""
return sum(log(i) for i in lst) | fd42df8ca7170f70453ef58d46035ec2ac6b6446 | 18,417 |
import torch
def nms(dets, iou_thr, device_id=None):
"""Dispatch to either CPU or GPU NMS implementations.
The input can be either a torch tensor or numpy array. GPU NMS will be used
if the input is a gpu tensor or device_id is specified, otherwise CPU NMS
will be used. The returned type will always ... | 6a00022a6903fc73429cb0f893de3b5f018315e9 | 18,418 |
def render_template(template_name_or_list, **context):
"""Renders a template from the template folder with the given
context.
:param template_name_or_list: the name of the template to be
rendered, or an iterable with template names
the firs... | a712c5db36a0ed512411c592c695ddff8a51e8fb | 18,419 |
import re
def _ReplaceUrlWithPlaceholder(results):
"""Fix a bug by replacing domain names with placeholders
There was a bug in early dogfood versions of the survey extension
in which URLs were included in questions where they
were supposed to have a placeholder. The fix was to replace text like
"Proceed to... | f20318bd4338b16940181dad3bc32439a77e0c2f | 18,420 |
def XCL(code, error, mag=0.0167, propagation='random', NEV=True, **kwargs):
"""
Dummy function to manage the ISCWSA workbook not correctly defining the
weighting functions.
"""
tortuosity = kwargs['tortuosity']
if code == "XCLA":
return XCLA(
code, error, mag=mag, propagation... | 90efd4d07c66923d2b98739fd7684ac1ee5141e8 | 18,421 |
def to_bgr(image):
"""Convert image to BGR format
Args:
image: Numpy array of uint8
Returns:
bgr: Numpy array of uint8
"""
# gray scale image
if image.ndim == 2:
bgr = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
return bgr
# BGRA format
if image.shape[2] == 4:
bgr = cv2.cvtColor... | 51d8455bb4060ff2db662a34846a4f957d33af81 | 18,422 |
import pathlib
import yaml
def load(path: pathlib.Path) -> dict:
"""Load a YAML file, returning its contents.
:raises: RuntimeError
"""
with path.open() as handle:
try:
return yaml.safe_load(handle)
except scanner.ScannerError as error:
LOGGER.critical('Failed... | d91ba626619ec25e2dbdbe35202b26cd43d27dc3 | 18,423 |
import os
import sys
def find_package(dir):
"""
Given a directory, finds the equivalent package name. If it
is directly in sys.path, returns ''.
"""
dir = os.path.abspath(dir)
orig_dir = dir
path = map(os.path.abspath, sys.path)
packages = []
last_dir = None
while 1:
i... | 0bc904165620daa2f408a3f1c526bfe4a34def97 | 18,424 |
import warnings
def validate_settings(raw_settings):
"""Return cleaned settings using schemas collected from INSTALLED_APPS."""
# Perform early validation on Django's INSTALLED_APPS.
installed_apps = raw_settings['INSTALLED_APPS']
schemas_mapping = raw_settings.get('CONFIT_SCHEMAS', {})
# Create s... | ba764cc54eee27a8317f21d6bd69ee85b9deadbf | 18,425 |
from torch.cuda.amp import autocast
def is_autocast_module_decorated(module: nn.Module):
"""
Return `True` if a nn.Module.forward was decorated with
torch.cuda.amp.autocast
"""
try:
decorators = _get_decorators(module.forward)
for d in decorators:
if isinstance(d, autoc... | 9f4db5438cb7e14ae20fd552a54121d9ce6c0d46 | 18,426 |
def timestamp_format_is_valid(timestamp: str) -> bool:
"""
Determines if the supplied timestamp is valid for usage with Graylog.
:param timestamp: timestamp that is to be checked
:return: whether the timestamp is valid (True) or invalid (False)
"""
try:
get_datetime_from_timestamp(times... | 9c1623bede646c9ebbd5cd4200db193437728590 | 18,427 |
def indices(n, dtype):
"""Indices of each element in upper/lower triangle of test matrix."""
size = tri.tri_n(n - 1)
return np.arange(size, dtype=dtype) | 0ecdcad0d66e268125826e0e415b410a07143b6c | 18,428 |
def _sample(n, k):
""" Select k number out of n without replacement unless k is greater than n
"""
if k > n:
return np.random.choice(n, k, replace=True)
else:
return np.random.choice(n, k, replace=False) | cde012459ddb64dc7700ec0238e222fd4d26d3a2 | 18,429 |
def set_price_filter(request, category_slug):
"""Saves the given price filter to session. Redirects to the category with
given slug.
"""
req = request.POST if request.method == 'POST' else request.GET
try:
min_val = lfs.core.utils.atof(req.get("min", "0"))
except (ValueError):
mi... | 1adf1798e7fbf290d98e1b47b94cd9c9038732fe | 18,430 |
def _get_config():
"""Returns a dictionary with server parameters, or ask them to the user"""
# tries to figure if we can authenticate using a configuration file
data = read_config()
# this does some sort of validation for the "webdav" data...
if "webdav" in data:
if (
"server"... | c2105753cb4ae551bea53c0a2aaf0432dd275422 | 18,431 |
import requests
def lastfmcompare(text, nick, bot,):
"""[user] ([user] optional) - displays the now playing (or last played) track of LastFM user [user]"""
api_key = bot.config.get("api_keys", {}).get("lastfm")
if not api_key:
return "No last.fm API key set."
if not text:
return "pleas... | 42b23961f210b4004aac987ca1146ee748392949 | 18,432 |
def fourier_ellipsoid(inp, size, n=-1, axis=-1, output=None):
"""
Multidimensional ellipsoid Fourier filter.
The array is multiplied with the fourier transform of a ellipsoid of
given sizes.
Parameters
----------
inp : array_like
The inp array.
size : float or sequence
... | 41128d7972bdb0cb6100991c1dc22031b7f3e6b3 | 18,433 |
def gaussian1D(x: np.ndarray, amplitude: Number, center: Number, stdev: Number) -> np.ndarray:
"""A one dimensional gaussian distribution.
= amplitude * exp(-0.5 (x - center)**2 / stdev**2)
"""
return amplitude * np.exp(-0.5 * (x - center)**2 / stdev**2) | 5c5c36ea71a08aec3246a2ca1dedf1d62c3fd331 | 18,434 |
def BuildImportLibs(flags, inputs_by_part, deffiles):
"""Runs the linker to generate an import library."""
import_libs = []
Log('building import libs')
for i, (inputs, deffile) in enumerate(zip(inputs_by_part, deffiles)):
libfile = 'part%d.lib' % i
flags_with_implib_and_deffile = flags + ['/IMPLIB:%s' %... | f29bcf16917cf8509662cf44c7881f8c7282b37d | 18,435 |
def gather_sparse(a, indices, axis=0, mask=None):
"""
SparseTensor equivalent to tf.gather, assuming indices are sorted.
:param a: SparseTensor of rank k and nnz non-zeros.
:param indices: rank-1 int Tensor, rows or columns to keep.
:param axis: int axis to apply gather to.
:param mask: boolean ... | 87e68a99c660448a11d32fa090ca3921552cd122 | 18,436 |
def Window(node, size=-1, full_only=False):
"""Lazy wrapper to collect a window of values. If a node is executed 3 times,
returning 1, 2, 3, then the window node will collect those values in a list.
Arguments:
node (node): input node
size (int): size of windows to use
full_only (boo... | 1f85b576455f3b379e41a7247ff486281bf21f8f | 18,437 |
def fixed_rate_loan(amount, nrate, life, start, freq='A', grace=0,
dispoints=0, orgpoints=0, prepmt=None, balloonpmt=None):
"""Fixed rate loan.
Args:
amount (float): Loan amount.
nrate (float): nominal interest rate per year.
life (float): life of the loan.
s... | 10681a99ec381ec64517891d8d1101ed5eae78f4 | 18,438 |
import json
def get_results():
"""
Returns the scraped results for a set of inputs.
Inputs:
The URL, the type of content to scrap and class/id name.
This comes from the get_results() function in script.js
Output:
Returns a JSON list of the results
"""
# Decode the json data an... | 59af271fc024854258c488f17489383f424dfae3 | 18,439 |
def _mocked_presets(*args, **kwargs):
"""Return a list of mocked presets."""
return [MockPreset("1")] | ebf48fb23dff67b2d1a9faac6e72764f2a5f8f0a | 18,440 |
def play(context, songpos=None):
"""
*musicpd.org, playback section:*
``play [SONGPOS]``
Begins playing the playlist at song number ``SONGPOS``.
The original MPD server resumes from the paused state on ``play``
without arguments.
*Clarifications:*
- ``play "-1"`` when playin... | fc2cee0b3cca2df33b844004ecaaaa1b0eaa5347 | 18,441 |
from typing import Union
def SMLB(x: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
"""
Taken from Minerbo, G. N. and Levy, M. E., "Inversion of Abel’s integral equation by means of orthogonal polynomials.",
SIAM J. Numer. Anal. 6, 598-616 and swapped to satisfy SMLB(0) = 0.
"""
return (np... | ed9b59ccbf99458796d11521825ba6ab0215144d | 18,442 |
def add_colon(in_str):
"""Add colon after every 4th character."""
return ':'.join([in_str[i:i+4] for i in range(0, len(in_str), 4)]) | fa4258aa9d684a087d2a81ae09a2702d6e58e3e1 | 18,443 |
def fetch_partial_annotations():
""" Returns the partial annotations as an array
Returns:
partial_annotations: array of annotation data - [n_annotations, 5]
row format is [T, L, X, Y, Z]
"""
raw_mat = loadmat(PARTIAL_ANNOTATIONS_PATH)
annotations = raw_mat['divisionAnnotations']
#... | 69d57df06576af141dcc0eb9b00c7834e1a4a2c2 | 18,444 |
def get_alt_pos_info(rec):
"""Returns info about the second-most-common nucleotide at a position.
This nucleotide will usually differ from the reference nucleotide, but it
may be the reference (i.e. at positions where the reference disagrees with
the alignment's "consensus").
This breaks ties arbi... | 3abe3fcbbf0ddbccb44025f2e476f77dc3e8abf9 | 18,445 |
import torch
def accuracy(output, target, topk=(1,)):
""" Computes the accuracy over the k top predictions for the specified
values of k.
"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
... | d2edbbff872670f1637696e63fe448a749138985 | 18,446 |
def grim(n, mu, prec=2, n_items=1):
"""
Test that a mean mu reported with a decimal precision prec is possible, given a number of observations n and a
number of items n_items.
:param n: The number of observations
:param mu: The mean
:param prec: The precision (i.e., number of decimal places) of... | 093fdea1b59157b477642b31afa8388192188020 | 18,447 |
def split_dataframe(df:pd.DataFrame,split_index:np.ndarray):
"""
Split out the continuous variables from a dataframe \n
Params:
df : Pandas dataframe
split_index : Indices of continuous variables
"""
return df.loc[:,split_index].values | 842f9b04d0d546b8bef28f0b110e7d570eb8f0a0 | 18,448 |
def user_select_columns():
"""
Useful columns from the users table, omitting authentication-related
columns like password.
"""
u = orm.User.__table__
return [
u.c.id,
u.c.user_name,
u.c.email,
u.c.first_name,
u.c.last_name,
u.c.org,
u.c.cre... | faf7ffd18a2fc6c55c1f8a4c19d176a34f79e19f | 18,449 |
def remove_query_param(url, key):
"""
Given a URL and a key/val pair, remove an item in the query
parameters of the URL, and return the new URL.
"""
(scheme, netloc, path, query, fragment) = urlparse.urlsplit(url)
query_dict = urlparse.parse_qs(query)
query_dict.pop(key, None)
query = ur... | 4a7ac5b2b1767a6fbc082e7e5b4f2d10dbd87926 | 18,450 |
def test_ap_hs20_sim(dev, apdev):
"""Hotspot 2.0 with simulated SIM and EAP-SIM"""
if not hlr_auc_gw_available():
return "skip"
hs20_simulated_sim(dev[0], apdev[0], "SIM")
dev[0].request("INTERWORKING_SELECT auto freq=2412")
ev = dev[0].wait_event(["INTERWORKING-ALREADY-CONNECTED"], timeout=... | cbda3f0ebc33c3d0e8ee6a99a088a61c57655480 | 18,451 |
def FreshReal(prefix='b', ctx=None):
"""Return a fresh real constant in the given context using the given prefix.
>>> x = FreshReal()
>>> y = FreshReal()
>>> eq(x, y)
False
>>> x.sort()
Real
"""
ctx = _get_ctx(ctx)
return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ct... | afc312fbd85387adcfe72c81c5af5b06fe0ccee1 | 18,452 |
def ndim_rectangles_integral(
# main args
func,
up_limits,
low_limits,
ndim,
nsamples=10000,
args_func = {},
... | 60a78a14fedc571276520d71c99669829253c062 | 18,453 |
import threading
def handle_readable(client):
"""
Return True: The client is re-registered to the selector object.
Return False: The server disconnects the client.
"""
data = client.recv(1028)
if data == b'':
return False
client.sendall(b'SERVER: ' + data)
print(threading.acti... | 9a77bb893a5da4e76df5593feb6ecf49022e6ef3 | 18,454 |
from datetime import datetime
import logging
def fund_wallet():
"""
---
post:
summary: fund a particular wallet
description: sends funds to a particular user given the user id the amount will be
removed from the wallet with the respective currency, if not it falls to the default walle... | 55955335f4462ad118fb792f3335db8090f7439e | 18,455 |
import numpy
def create_objective(dist, abscissas):
"""Create objective function."""
abscissas_ = numpy.array(abscissas[1:-1])
def obj(absisa):
"""Local objective function."""
out = -numpy.sqrt(dist.pdf(absisa))
out *= numpy.prod(numpy.abs(abscissas_ - absisa))
return out
... | c63eeadffd067c2a94470ddbf03fb009265fbbbc | 18,456 |
def get_party_to_seats(year, group_id, party_to_votes):
"""Give votes by party, compute seats for party."""
eligible_party_list = get_eligible_party_list(
group_id,
party_to_votes,
)
if not eligible_party_list:
return {}
n_seats = YEAR_TO_REGION_TO_SEATS[year][group_id]
... | 02270cfeefb87b3da0ec4fa88dfb692a4645df5e | 18,457 |
def get_product(name, version):
"""Get info about a specific version of a product"""
product = registry.get_product(name, version)
return jsonify(product.to_dict()) | 0c461d672ef4d07578b098b3cb937027ad8946f1 | 18,458 |
def _is_segment_in_block_range(segment, blocks):
"""Return whether the segment is in the range of one of the blocks."""
for block in blocks:
if block.start <= segment.start and segment.end <= block.end:
return True
return False | e7509f18f0a72cf90fb1aa643c77c2e13154f0d0 | 18,459 |
from operator import add
from sys import prefix
def acrobatic(m):
"""More power and accuracy at the cost of increased complexity; can stun"""
if 'do_agility_based_dam' in m['functions'] or 'do_strength_based_dam' in m['functions']:
return None
if 'takedown' in m['features']:
return None
... | b15980d1bc68e495c9e86f16a708e80e90245954 | 18,460 |
import configparser
import sys
import os
import subprocess
def systemd(config, args):
""" Build and install systemd scripts for the server """
try:
config = load_config(args.cfg_file, explicit=True)
except (OSError, configparser.ParsingError) as exc:
print(exc, file=sys.stderr)
ret... | 1a1a8caad38fedc016f1ef6efea9adc6ab020c95 | 18,461 |
def compute_snes_color_score(img):
""" Returns the ratio of SNES colors to the total number of colors in the image
Parameters:
img (image) -- Pillow image
Returns:
count (float) -- ratio of SNES colors
"""
score = _get_distance_between_palettes(img, util.get_snes_color_p... | b52ae8d7d98700f455e126cfb447e41c1762528c | 18,462 |
def get_assignments_for_team(user, team):
""" Get openassessment XBlocks configured for the current teamset """
# Confirm access
if not has_specific_team_access(user, team):
raise Exception("User {user} is not permitted to access team info for {team}".format(
user=user.username,
... | 67b72b34b8549127728c33dfac8599d979d09f6f | 18,463 |
def is_flexible_uri(uri: Uri_t) -> bool:
"""Judge if specified `uri` has one or more flexible location.
Args:
uri: URI pattern to be judged.
Returns:
True if specified `uri` has one or more flexible location,
False otherwise.
"""
for loc in uri:
if isinstance(loc, F... | fd5138d3dfc44c36e7b5ccfe911f6640e22bc7f2 | 18,464 |
def load_frame_gray(img_path, gray_flag=False):
"""Load image at img_path, and convert the original image to grayscale if gray_flag=True.
Return image and grayscale image if gray_flag=True; otherwise only return original image.
img_path = a string containing the path to an image file readable by cv.imread
... | 8b792f2bf5f22f34e0b880c934019c238a3cc360 | 18,465 |
def read_vocab_file(path):
""" Read voc file.
This reads a .voc file, stripping out empty lines comments and expand
parentheses. It returns each line as a list of all expanded
alternatives.
Args:
path (str): path to vocab file.
Returns:
List of List... | cdf230f1fbeafbcc3839a02ce86b33719dfcf806 | 18,466 |
import re
def natural_key(string_):
"""See http://www.codinghorror.com/blog/archives/001018.html"""
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)] | f49aca918e4efc2f5e7f6541df2d5329bc2752f7 | 18,467 |
import subprocess
def _set_wpa_supplicant_config(interface, config, opt):
"""Starts or restarts wpa_supplicant unless doing so would be a no-op.
The no-op case (i.e. wpa_supplicant is already running with an equivalent
config) can be overridden with --force-restart.
Args:
interface: The interface on whi... | 09197b75393182087651d9625483928e2b92d802 | 18,468 |
def generate_episode(sim, policy, horizon=200):
"""
Generate an episode from a policy acting on an simulation.
Returns: sequence of state, action, reward.
"""
obs = sim.reset()
policy.reset() # Reset the policy too so that it knows its the beginning of the episode.
states, actions, rewards ... | 73a0bbb2703c047d3305e93dd2a340c83db12277 | 18,469 |
import asyncio
async def _ensure_meadowrun_vault(location: str) -> str:
"""
Gets the meadowrun key vault URI if it exists. If it doesn't exist, also creates the
meadowrun key vault, and tries to assign the Key Vault Administrator role to the
current user.
"""
subscription_id = await get_subsc... | 9e16940a56ae83b47d42d7583ad6efc9c5d63d23 | 18,470 |
from typing import Iterable
from typing import Dict
from typing import List
from typing import Union
from pathlib import Path
from typing import Tuple
import logging
def get_dataset_splits(
datasets: Iterable[HarmonicDataset],
data_dfs: Dict[str, pd.DataFrame] = None,
xml_and_csv_paths: Dict[str, List[Uni... | c1389dad05aa2911735b1e9099acda9e2a8a1c05 | 18,471 |
from PilotErrors import PilotException
from movers import JobMover
from movers.trace_report import TraceReport
import traceback
def put_data_es(job, jobSite, stageoutTries, files, workDir=None, activity=None):
"""
Do jobmover.stageout_outfiles or jobmover.stageout_logfiles (if log_transfer=True)
o... | b3841dc487e19ca989575e37b95a9e8f2949258b | 18,472 |
def floor(data):
"""
Returns element-wise largest integer not greater than x.
Args:
data (tvm.tensor.Tensor): Tensor of type float16, and float32
Returns:
tvm.tensor.Tensor, has the same shape as data and type of int32.
"""
vc_util.ops_dtype_check(data.dtype, vc_util.DtypeForDa... | 3d553d54330c3237908b33600fae560a92f20975 | 18,473 |
def pixel_link_model(inputs, config):
""" PixelLink architecture. """
if config['model_type'] == 'mobilenet_v2_ext':
backbone = mobilenet_v2(inputs, original_stride=False,
weights_decay=config['weights_decay'])
elif config['model_type'] == 'ka_resnet50':
back... | 0bf606e5b06d94bce98865147fb6a1cf45b04560 | 18,474 |
def ingresar_datos():
"""Pide al usuario los datos para calcular el precio de la compra
de boletos.
:return: tipo, cantidad
:rtype: tuple
"""
text_align("Datos de la compra", width=35)
tipo: str = choice_input(tuple(TIPO.keys()))
cantidad: int = int_input("Ingrese el número de boletos: ... | eb9b1c90fbc44a639a7760848723f5579eced4df | 18,475 |
def trim_spectrum(freqs, power_spectra, f_range):
"""Extract a frequency range from power spectra.
Parameters
----------
freqs : 1d array
Frequency values for the power spectrum.
power_spectra : 1d or 2d array
Power spectral density values.
f_range: list of [float, float]
... | a522a384033fc38d3bba5e7d91ca8debfdedec68 | 18,476 |
def _get_variable_for(v):
"""Returns the ResourceVariable responsible for v, or v if not necessary."""
if v.op.type == "VarHandleOp":
for var in ops.get_collection(ops.GraphKeys.RESOURCES):
if (isinstance(var, resource_variable_ops.ResourceVariable)
and var.handle.op is v... | 5e8f4b83495c89f728c30148e9b05e06713d6b82 | 18,477 |
def load_prefixes(filepath):
"""Dado um arquivo txt contendo os prefixos utilizados na SPARQL, é
devolvida uma string contendo os prefixos e uma lista de tuplas contendo
os prefixos.
Parameters
----------
filepath : str
Caminho do arquivo txt contendo o conjunto de prefixos.
Return... | a6c2f3c014dbfae73718c579da914f840489e701 | 18,478 |
def build_convolutional_box_predictor(is_training,
num_classes,
conv_hyperparams_fn,
min_depth,
max_depth,
num_layers_before_predi... | 3e3b79cbd6e99b8b9d3da5ff2545e17a92ef3f38 | 18,479 |
import os
def _get_default_directory():
"""Returns the default directory for the Store. This is intentionally
underscored to indicate that `Store.get_default_directory` is the intended
way to get this information. This is also done so
`Store.get_default_directory` can be mocked in tests and
`_ge... | 28636cc7c6d3d804a7baea4a95a1e40c8247308c | 18,480 |
def parse_command_line():
"""
:return:
"""
parser = argp.ArgumentParser(prog='TEPIC/findBackground.py', add_help=True)
ag = parser.add_argument_group('Input/output parameters')
ag.add_argument('--input', '-i', type=str, dest='inputfile', required=True,
help='Path to input fi... | 1f12e08cf4c86f40a84a09303d75a5d3506a3a14 | 18,481 |
import torch
def disparity_to_idepth(K, T_right_in_left, left_disparity):
"""Function athat transforms general (non-rectified) disparities to inverse
depths.
"""
assert(len(T_right_in_left.shape) == 3)
# assert(T_right_in_left.shape[0] == self.batch_size)
assert(T_right_in_left.shape[1] == 4)
... | 454bda2fd9ec4e4ef5615dbdb054c2f3b454f31a | 18,482 |
def processPhoto(photoInfo, panoramioreview=False, reviewer='',
override=u'', addCategory=u'', autonomous=False, site=None):
"""Process a single Panoramio photo."""
if not site:
site = pywikibot.Site('commons', 'commons')
if isAllowedLicense(photoInfo) or override:
# Should... | e753f411b028caf74ca12b5e7215f161d290afa7 | 18,483 |
def auto_apilado(datos,target,agrupacion,porcentaje=False):
"""
Esta función recibe un set de datos DataFrame,
una variable target, y la variable
sobre la que se desean agrupar los datos (eje X).
Retorna un grafico de barras apilado.
"""
total = datos[[target,agrupacion]].groupby(agru... | b3b13e0e5bd56628971004c0d6d5171929ab6de3 | 18,484 |
from datetime import datetime
def month_from_string(month_str: str) -> datetime.date:
"""
Accepts year-month strings with hyphens such as "%Y-%m"
"""
return datetime.datetime.strptime(month_str, "%Y-%m").date() | cfb901f6676d40398bd6f49c438541f00e5389e3 | 18,485 |
import hashlib
def get_isomorphic_signature(graph: DiGraph) -> str:
"""
Generate unique isomorphic id with pynauty
"""
nauty_graph = pynauty.Graph(len(graph.nodes), directed=True, adjacency_dict=nx.to_dict_of_lists(graph))
return hashlib.md5(pynauty.certificate(nauty_graph)).hexdigest() | 8dfd7dd44409fee7dddd88f21681ed93232f1dba | 18,486 |
from typing import Callable
from typing import Any
import sys
import time
def watchdog(timeout: int | float, function: Callable, *args, **kwargs) -> Any:
"""Time-limited execution for python function. TimeoutError raised if not finished during defined time.
Args:
timeout (int | float): Max time execu... | f9a54bee2d444831439d710ef882e4e117b85d62 | 18,487 |
def _encode_raw_string(str):
"""Encodes a string using the above encoding format.
Args:
str (string): The string to be encoded.
Returns:
An encoded version of the input string.
"""
return _replace_all(str, _substitutions) | bb33875b276fe822c2b43ec3ebcc57b0d2f4c7b9 | 18,488 |
from typing import Callable
def char_pred(pred: Callable[[int], bool]) -> Parser:
"""Parses a single character passing a given predicate."""
def f(x):
if pred(x):
return value(x)
else:
raise Failure(f"Character '{chr(x)}' fails predicate"
" `{p... | 2b7be4f740e7f7afad1ef66c0d544208d679fc5c | 18,489 |
def convert_bound(bound, coord_max, coord_var):
"""
This function will return a converted bound which which matches the
range of the given input file.
Parameters
----------
bound : np.array
1-dimensional 2-element numpy array which represent the lower
and upper bounding box on t... | 5784167af65b2f406bfa5c428f1421a8915359f3 | 18,490 |
def tk_window_focus():
"""Return true if focus maintenance under TkAgg on win32 is on.
This currently works only for python.exe and IPython.exe.
Both IDLE and Pythonwin.exe fail badly when tk_window_focus is on."""
if rcParams['backend'] != 'TkAgg':
return False
return rcParams['tk.window_... | 757963dce9d9dc00be54ffbcbf694656f2f770e9 | 18,491 |
from functools import reduce
def cc_filter_set_variables(operator, bk_biz_id, bk_obj_id, bk_obj_value):
"""
通过集群ID、过滤属性ID、过滤属性值,过滤集群
:param operator: 操作者
:param bk_biz_id: 业务ID
:param bk_obj_id: 过滤属性ID
:param bk_obj_value: 过滤属性值
:return:
"""
client = get_client_by_user(operator)
... | 3e1f849c59d3e3553f1c8b6f725a36921cae9451 | 18,492 |
def distance(mags, spt, spt_unc):
"""
mags is a dictionary of bright and faint mags
set a bias
"""
res={}
f110w=mags['F110W']
f140w=mags['F140W']
f160w=mags['F160W']
relations=POLYNOMIAL_RELATIONS['abs_mags']
nsample=1000
for k in mags.keys():
#take the stand... | cece86e80c03ce8d9753fe864bd746e68500fca3 | 18,493 |
import torch
import sys
def loss_function(recon_x, x, mu, logvar, cl, target, natural):
"""
Universally calculates the loss, be it for training or testing. Hardcoded to use mse_loss. Change below to binary_cross_entropy if desired.
@param recon_x: images reconstructed by the decoder(s)
@param x: original images f... | 8fc5773dbecd3f445ffb849a91ad0a95a93bc45c | 18,494 |
import math
def foo(X):
"""The function to evaluate"""
ret = []
for x in X:
r = 2*math.sqrt(sum([n*n for n in x]));
if r == 0:
ret.append(0)
else:
ret.append(math.sin(r) / r);
return ret | 7b241cf45757cdf9a5a28ee56c59ee41099ccb1e | 18,495 |
def measure_curv(left_fit, right_fit, plot_points, ym_per_pix, xm_per_pix):
"""
calculates the curvature using a given polynom
Args:
left_fit ([type]): [description]
right_fit ([type]): [description]
plot_points ([type]): [description]
"""
#get the max y value (start of the... | 7ae6d1e390906c3011349716aad0d0640a4c3a65 | 18,496 |
import logging
from datetime import datetime
def get_external_dns(result):
"""
Function to validate the ip address. Used to extract EXTERNAL_DNS server information
Args:
result(dict): Input result dictionary with all network parameters and boolean flags
Returns:
result(dict): The updat... | 14531bcd17dbc036f417ec7eca6d24e9c7931e6f | 18,497 |
def __process_agent(agent_param):
"""Get the agent id and namespace from an input param."""
if not agent_param.endswith('TEXT'):
param_parts = agent_param.split('@')
if len(param_parts) == 2:
ag, ns = param_parts
elif len(param_parts) == 1:
ag = agent_param
... | 49ebaa4c435422066c0e2345e4cf056caebbdc9e | 18,498 |
def inference(predictions_op, true_labels_op, display, sess):
""" Perform inference per batch on pre-trained model.
This function performs inference and computes the CER per utterance.
Args:
predictions_op: Prediction op
true_labels_op: True Labels op
display: print sample prediction... | 5e58ab3fff91a2fb5450b37f0bf41b2681d297d9 | 18,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.