content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_index(corners, i, jk):
""" Find the index that angle with corners
i, jk has inside the corners set.
"""
if type(jk) != list:
jk = list(jk)
assert corners.shape[1] == 3
sol = np.where(np.bitwise_or(np.all(corners == [i] + jk, axis=1),
np.all(corne... | 7fa85c7263a932d076da023adbb5b8117fa00bce | 3,603,958 |
from typing import Container
def thread(msglist):
"""([Message]) : {string:Container}
The main threading function. This takes a list of Message
objects, and returns a dictionary mapping subjects to Containers.
Containers are trees, with the .children attribute containing a
list of subtrees, so ca... | d5ee2eceef11c68d6fe1aa3b7ef5bcf2c14a81b8 | 3,603,959 |
def remove_flow_overlap(df, aggregate_flow, contributing_flows):
"""
Quantity of contributing flows is subtracted from aggregate flow and the
aggregate flow quantity is updated. Modeled after function of same name in
stewicombo.overlaphandler.py
:param df: df, FBA format
:param aggregate_flow: s... | 5e6155010559d084f6f08f6cc9baf3716374e7f6 | 3,603,960 |
def getChessTiles(a, lines_x, lines_y):
"""Split up input grayscale array into 64 tiles stacked in a 3D matrix using the chess linesets"""
# Find average square size, round to a whole pixel for determining edge pieces sizes
stepx = np.int32(np.round(np.mean(np.diff(lines_x))))
stepy = np.int32(np.round(... | 56f3b839df25563d1d2b9204d99025c12f6ad552 | 3,603,961 |
def build_model(label, X, model_info, inner_clf, metric_name, metric_func):
"""build_model
:param X:
:param y:
:param target_type:
"""
FUNC_MAPPING = {
"categorical": build_predictor,
"categorical_uniform": build_uniform_predictor,
"numerical": build_predictor,
"... | f43989e8de6fa08acd84fd82b4f582dbd10f6573 | 3,603,962 |
import re
def python_cat_to_r_cat(python_df):
"""
Return the same dataframe with the 3rd level of the multiindex ("Category") updated
so that the python-style name (e.g. race[T.3]) is converted to r-style (e.g. race3)
"""
re_str = re.compile(r"(?P<var_name>.+)\[T\.(?P<cat_name>.+)\]")
df = pyt... | c0a248978dca2c169e6a0f3acbe41c9ab53998c0 | 3,603,963 |
from typing import List
from typing import Tuple
def two_columns(pairs: List[Tuple]) -> str:
"""
Join pairs (or more) of strings to a string.
:param pairs: List of tuples of strings
:return: String separated by newlines
"""
return '\n'.join([' '.join(map(str, t)) for t in pairs]) | 810fdab52b4641c32f54c6adc772f8352b8f2ae6 | 3,603,964 |
import functools
def preprocess_tvqa(record, config):
"""
there are 7 frames, each with audio and associated text
there is also an initial "frame" that doesn't have any image, but does have metadata where we stick the Q.
:param record:
:param config:
:return:
"""
k2f = {
'id': ... | 3bd516f890cfcf3282d38e030e66340f48c4226e | 3,603,965 |
from datetime import datetime
import binascii
import json
def addCredit():
""" add credit request
:return: JSON request tous les capteurs de la classe
"""
nowDt = datetime.datetime.now()
now = round(nowDt.timestamp())
dict_req = request.get_json()
term_id = dict_req.get('terminal_id', ... | 37ddf66205a0554dd2c29b7bdd021f5ff3ebe72c | 3,603,967 |
def get_record_as_json(cur, tablename, row_id):
"""
Get a single record from the database, by id, as json.
"""
# IMPORTANT NOTE: Only use this function in trusted input. Never on data
# being created by users. The table name is not escaped.
q = """
SELECT row_to_json(new_with_table)
F... | 00521ae582a013f97b77494944e0f6e04069ed05 | 3,603,968 |
def stream_handler_set_stream(stream_handler_instance, stream):
"""
Backport of StreamHandler.setStream() for Python 2
"""
if stream is stream_handler_instance.stream:
result = None
else:
result = stream_handler_instance.stream
stream_handler_instance.acquire()
try:
... | 0da047fc1a4e7c17e91d51769ede549551ab9813 | 3,603,969 |
def key_press(name, key_index, ctrl=False, shift=False, alt=False, super=False, repeat=True):
""" Invisible widget that waits for a given key to be pressed.
No widget must be active at the time to prevent triggering hotkeys by editing text fields.
Key codes are specified by glfw, e.g. `glfw.KEY_A`, or `glf... | a441f9e1d56c4e81224078b34ee24d4522101b7a | 3,603,970 |
def zip_(self, iterable):
"""A zip object yielding tuples until an input is exhausted.
>>> [1, 2, 3].zip([1, 2, 3])
[(1, 1), (2, 2), (3, 3)]
>>> [1, 2, 3].zip([3, 2])
[(1, 3), (2, 2)]
"""
return list(zip(self, iterable)) | b71ea3414a7817959e5b58ad7cd476b7caa3c770 | 3,603,971 |
def Pre(*content, **attrs):
"""
Wrapper for pre tag
>>> Pre().render()
'<pre></pre>'
"""
return KWElement('pre', *content, **attrs) | 7bc68152449c6180aa69abe4174001156922fcea | 3,603,972 |
def is_main_thread(*args):
"""
is_main_thread() -> bool
Are we running in the main thread?
"""
return _ida_pro.is_main_thread(*args) | ae8f5dd5f1b6d1681848680b5d0987f0ddf1574d | 3,603,973 |
def segno(x):
"""
Input: x, a number
Return: 1.0 if x>0,
-1.0 if x<0,
0.0 if x==0
"""
if x > 0.0: return 1.0
elif x < 0.0: return -1.0
elif x == 0.0: return 0.0 | 5caccfa037b2972755958f647f009660aefae59d | 3,603,975 |
def pdp_importances(model,X,numx=30,normalize=True):
"""
Use standard PDP then mean center and take average magnitude as impact. Return
an importance dataframe
"""
pdpxs,pdpys = ice.friedman_partial_dependences(model, X, numx=numx, mean_centered=True)
I = pd.DataFrame(data={'Feature': X.columns}... | f2780a03f905cf37b348be27f74424411d017f98 | 3,603,976 |
def recursive_fibonacci(n: int) -> int:
"""Return the nth number of the fibonacci sequence"""
if n <= 1:
return n
else:
return recursive_fibonacci(n - 1) + recursive_fibonacci(n - 2) | c45823648833d80f6d0c2ff815bbea464775e6f1 | 3,603,978 |
from typing import Iterable
def calculate_row_weights(
row: Iterable, param_weights: dict, vars_to_optimize: dict
) -> float:
"""Used to select random rows of parameter combinations using individual parameter weights.
Args:
row (Iterable): Series of parameters, with parameter names as index. ... | 458cb546fd9fe6193e7cce66b5187ce8ea93369b | 3,603,979 |
def swap_xyz_string(xyzs, permutation):
"""
Permutate the xyz string operation
Args:
xyzs: e.g. ['x', 'y+1/2', '-z']
permuation: list, e.g., [0, 2, 1]
Returns:
the new xyz string after transformation
"""
if permutation == [0,1,2]:
return xyzs
else:
n... | efd0eb400be0dca26b49c3b2d3a04a385a2fc6e4 | 3,603,981 |
def _get_input_files(variable, config_user):
"""Get the input files for a single dataset."""
# Find input files locally.
input_files = get_input_filelist(
variable=variable,
rootpath=config_user['rootpath'],
drs=config_user['drs'])
# Set up downloading using synda if requested.
... | 1365cfd6f6e217a563c9bae807a3f02b1080d1a1 | 3,603,982 |
import time
import torch
import torchvision
def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, labels=()):
"""Performs Non-Maximum Suppression (NMS) on inference results
Returns:
detections with shape: nx6 (x1, y1, x2, y2, conf, cls)
"""
nc = ... | c108092bf75d31053e51132d68403a1d1c03ae5e | 3,603,983 |
def distance(seq1, seq2, dist=sqeuclidean):
"""
Utility function for calculating the distance between two sequences,
i.e. between two time-series or their subsequences.
:param seq1: First sequence
:param seq2: Second sequence
:param dist: Distance functor to use for calculating distances between points
... | aaaa90a7e89daeb1371a7ada5087f81fdaeba583 | 3,603,984 |
from datetime import datetime
def build_history(owner, repo, name=None, since=None, issues=None, url=None,
max_issue=None, releases=None, unpublished=False,
existing_history=None, skip_issues=None, fLOG=None):
"""
Returns an history of a module.
@param owner ... | b8cd3b6c9c5fd1d24c0a9eaf2a4075357b7b8243 | 3,603,985 |
import json
def geojson_to_wkt(geojson):
# type: (Union[str, dict]) -> str
"""Converts GeoJSON (serialize or raw) to a WKT string."""
if isinstance(geojson, str):
raw_geojson = json.loads(geojson) # type: dict
elif isinstance(geojson, dict):
raw_geojson = geojson
else:
rai... | 501555f4df460ea8c6f260d640f9cbd4c0fe525b | 3,603,986 |
def affine_softplus(real, lo=0, ref=1):
"""Maps real numbers to (lo, infinity), where 0 maps to ref."""
if not lo < ref:
raise ValueError('`lo` (%g) must be < `ref` (%g)' % (lo, ref))
shift = inv_softplus(tf.cast(1., real.dtype))
scale = (ref - lo) * tf.nn.softplus(real + shift) + lo
return ... | 53dbb64717beb53088b962744954bf4fa1b0136a | 3,603,987 |
from typing import List
from typing import Dict
import tqdm
def rouge_fn(targets: List[List[str]],
predictions: List[str]) -> Dict[str, float]:
"""Computes ROUGE by taking the max ROUGE-N per reference and N."""
# Following strategy from https://www.aclweb.org/anthology/W04-1013/.
# Identify best r... | fb3cc06da2392431ead2c61247ca3745f2456219 | 3,603,988 |
def speed_2_pace(speed):
"""Convert speed in km/hr to pace in s/km"""
return 60*60/speed | 25379049e98622ec5888461a9f6455be399d5f5a | 3,603,989 |
def vortex(xx, yy, **kwargs):
"""
analytical function that defines the domain
fmsk < 0 : solid
fmsk == 0: boundary
fmsk > 0 : fluid
"""
x0 = kwargs["x0"]
y0 = kwargs["y0"]
d = kwargs["d"]
if "vtype" in kwargs:
vtype = kwargs["vtype"]
else:
vtype = "gaussian"
... | 810f3837ea588833e683356b44256a5e44b3979d | 3,603,990 |
def computeNumericalGradient(J, theta):
"""Computes the gradient using "finite differences"
and gives us a numerical estimate of the gradient.
numgrad = computeNumericalGradient(J, theta) computes the numerical
gradient of the function J around theta. Calling y = J(theta) should
return the function... | f028612304972dfbf3f3e576c135f8d765724e08 | 3,603,991 |
import random
def load_label(directory, number=None):
"""
导入指定目录的所有图片的标签,不导入图片
:param directory:
:return:
"""
names = list_image_name(directory)
random.shuffle(names)
if number is not None:
names = names[:number]
labels = []
for name in names:
label = name.split... | a6ee5daf959a86528c1f245115d5c5dbf8b575e9 | 3,603,992 |
def quantize_uniform_to_n_bits_(arr, nb_bits):
"""Reduce each component in an array to a maximum number of bits in-place.
This operation sets the ``8-B`` highest frequency (rightmost) bits to zero.
For ``B`` bits this is equivalent to changing each component's intensity
value ``v`` to ``v' = v & (2**(8... | 009b1c3545af37e065072545268feadc3d39397d | 3,603,993 |
def median_frequency(sig, FS):
"""Compute median frequency along the specified axes.
Parameters
----------
sig: ndarray
input from which median frequency is computed.
FS: int
sampling frequency
Returns
-------
f_max: int
0.50 of max_frequency using cumsum.
"""
... | 7ef893aaee2b213feaf6f8aa452a4f9ef6236813 | 3,603,994 |
def unused(attr):
"""
This function checks if an attribute is not set (has no value in it).
"""
if isinstance(attr, (Required, Recommended)) or attr is None:
return True
else:
return False | fdab32aaafb59220d73e7a26827143036dccbab5 | 3,603,995 |
import numpy
def stat_decumulate(rec):
"""Converts the stat record from the cumulative (original) to
per-block quantities.
Returns a copy object containing the decumulated quantities."""
rslt = rec.copy()
#print rslt
t_elapsed = rslt['T_elapsed']
# Unfortunately numpy does not have a converse function o... | 1a7a10ef6836fc79c962036a8b7dfa0c32260380 | 3,603,996 |
def contiguous_regions(condition):
"""Finds contiguous True regions of the boolean array "condition". Returns
a 2D array where the first column is the start index of the region and the
second column is the end index."""
# Find the indicies of changes in "condition"
d = np.diff(condition)
idx, =... | fa94d3c5637f6cd8262365e4764d23589fa266dc | 3,603,997 |
import PIL
def find() -> None:
"""Function for rendering image"""
path = input("Enter the Path to the photo =")
try:
Image = PIL.Image.open(path)
except FileExistsError:
pass
print(path, "The given path is not valid")
return Image | 777107631245497b3416a384dc0a1c30ab25c629 | 3,603,998 |
import socket
def handle_googleapiclient_error(error, message=None, code=None, http_response=None):
"""Constructs a ``FirebaseError`` from the given googleapiclient error.
This method is agnostic of the remote service that produced the error, whether it is a GCP
service or otherwise. Therefore, this meth... | 1eacd6fc4e5c8d38763ea03f6b9a0897521689ae | 3,604,000 |
def poly_lr_scheduler(optimizer, init_lr, iteraion, lr_decay_iter=1,
max_iter=100, power=0.9):
"""Polynomial decay of learning rate
:param init_lr is base learning rate
:param iter is a current iteration
:param lr_decay_iter how frequently decay occurs, default is 1
... | 298597342c7411648881e75061d25d7cac9ef49c | 3,604,001 |
def StringSizer(field_number, is_repeated, is_packed):
"""Returns a sizer for a string field."""
tag_size = _TagSize(field_number)
local_VarintSize = _VarintSize
local_len = len
assert not is_packed
if is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in ... | 9919e194ee938a71ebcbdd166b19f5848477844d | 3,604,003 |
from pathlib import Path
from datetime import datetime
import html
def build_historic_markers(dpt_code=None):
"""
This function reads through the 'historic_fires.csv' file stored in the /data folder.
It takes as input a department code (as a character string), which will correspond to the department
... | 800518df74711e302b39d656bc3e53d4418fba33 | 3,604,005 |
def ideal_reflection(b_Qi = (3, 4.5, 6),
b_Qc = (3, 4.5, 6),
b_theta = (-np.pi, 0, np.pi),
b_fr = (1e9, 5e9, 11e9)):
""" returns a Parametric1D model for an ideal notch resonator
Params:
Qi: The log10 of the internal quality factor
... | eb7b24583dd7df418ece7390a5f1d51764995d34 | 3,604,006 |
from pathlib import Path
def get_dictionaries(base: Path) -> list[tuple[str, list[Path]]]:
"""Make a list of available dictionaries and the interesting files.
:param base: The Apple Dictionaries root directory.
:return: A list of tuples of name, files for each dictionary.
"""
all_dicts = sorted(
... | 98068ecb847aa6975cc8dc7eed59b8948316f191 | 3,604,007 |
def copy_clb_desc(clb_desc, condition=CLBNodeCondition.ENABLED, weight=1):
"""
Produce a :class:`CLBDescription` from another, but with the provided
conditions and weights instead of the original conditions and weights.
:param clb_desc: the :class:`CLBDescription` to copy
:param condition: the :cla... | e67ef372425697f374d9a480b7f953dcffc777df | 3,604,008 |
def _send(cmd):
"""Actually run send tickets command."""
success = False
try:
rc = subproc.call(cmd)
if rc == 0:
success = True
except subproc.CalledProcessError:
pass # command failed
return success | 68da3807b7e6fd92b8e8eac38ca432c44101fc5b | 3,604,010 |
def calculate_mean_vectors(X, y):
"""Calculates the mean samples per class
Parameters:
-----------
X : array-like, shape (m, n) - the samples
y : array-like, shape (m, ) - the class labels
Returns:
--------
mean_vectors : array-like, shape (k, )
Those are the mean samples f... | 0a6fd18aacba2d4d501c8530e39422be3440d3ac | 3,604,011 |
import torch
def gaussian_entropy(m_):
"""
https://en.wikipedia.org/wiki/Normal_distribution#Maximum_entropy
"""
return .5 + .5 * (np.log(2 * np.pi) + torch.log(m_.scale)) | 1d3f9ab2e8229919d864820e57482faf026b5389 | 3,604,012 |
def CountEndElements():
"""(read-only) Number of zone end elements in the active meter zone."""
return lib.Meters_Get_CountEndElements() | fbb5f5b7a01339431adbddb9b92b1c277bacf0a4 | 3,604,014 |
import re
def simplify_credentials(credentials):
""" Replace the key of the entries with host:port values.
Returns a new dictionary from the credentials where the key will be
replaced by 'host:port' values so protocols and product names will be
removed if these are given.
"""
host_entry_patte... | 3865a9ec7b5b78def9de017934ae5711052282b7 | 3,604,015 |
import math
def strafe_time(x, speedxi, K):
"""Compute the time it takes to strafe for the given distance and initial
speed.
Always returns positive times.
>>> vix = 400
>>> x = 1000
>>> K = strafe_K(30, 0.01, 320, 10)
>>> tx = strafe_time(x, vix, K)
>>> math.isclose(x, strafe_distan... | 240b0ae0773b8361c7d1f9e477e21b4108880910 | 3,604,016 |
def generate_recipient_from(nhais_cypher):
"""
Generates the recipient cypher. This value can be deduced from the nhais_cypher provided.
The nhais cypher can be 2 to 3 characters is length.
If it is 2 characters in length it will append "01" to generate the recipient cypher
If it is 3 characters in ... | ac29a09f246fc38b43301cc1b00a4056fc49e203 | 3,604,017 |
from typing import List
from typing import Optional
from typing import Dict
from typing import Tuple
from typing import Union
import math
from functools import reduce
def render_on_map(lidarpc_rec: LidarPc, # type: ignore
boxes_lidar: List[Box3D],
ego_poses: List[EgoPose], # type... | 7534c2af7c4fa9b2c554567b56be06765bdcda05 | 3,604,018 |
from pathlib import Path
from typing import Tuple
import pickle
def convert_single(result_dir: Path, pickle_file: Path) -> Tuple[str, bool]:
"""Convert a pickle file representing a soong parser to a graph and store it in
result dir.
:param result_dir: Where to store the result
:param pickle_file: Whi... | dd3cc551dfd67e13f7b5be7b057bdde1a79f8cd3 | 3,604,019 |
def removeDuplicates(aList):
""" Remove duplicates in a list. """
if type(aList) != type([]): return aList
result = []
for elem in aList:
result.append(removeDuplicates(elem))
return _removeDuplicatesOneLevel(result) | 40e208c245fa5ea5d29c26d7dd24f95ff6587821 | 3,604,020 |
def num2date(times, units, calendar='standard'):
"""
Extension to the netCDF4.num2date() function to correctly handle
time strings of format '2010-01-01T00:00:00Z', as used by netcdf-java.
Refer to netCDF4.num2date() for further documentation.
"""
# Patch to address the problem of netCDF4.num2d... | 0bd385aa1cdd634ca5092d5a486240adb86a592e | 3,604,021 |
def create_stack(heat_client, stack_name, template, parameters,
environment=None):
"""
Create Stack
"""
stack_params = {
'stack_name': stack_name,
'template': template,
'parameters': parameters,
'environment': environment,
}
stack = heat_client.s... | 6c6e838dcba1142762fd01b1ace36386c54ab8d8 | 3,604,022 |
from typing import Any
def remove_member(client: Any, group_key: str, email: str):
"""Removes member from google group."""
return make_call(client.members(), "delete", groupKey=group_key, memberKey=email) | 25be8a70f47e42566b4e34b79bf9e2c2e69e993e | 3,604,023 |
def _convert_color(color):
"""Convert a 24-bit color to 16-bit.
The input `color` is assumed to be a 3-component list [R,G,B], each with
8 bits for color level.
This method will translate that list of colors into a 16-bit number,
with first 5 bits indicating R component,
last 5 bits indicating... | 6635e30d574288146c5ff07bf3d0d1661cd33b97 | 3,604,024 |
def join_discovery (dfd, interface_address):
"""Join a socket to a multicast address for discovery.
The *interface_address* must be a host name or IP address string
that resolves to an IP (or IPv6) address bound to one of the
network interfaces on the local host. The socket passed as *dfd*
will be... | d70b711a51dc156d8ff36b1e215f5c2c37fcae50 | 3,604,026 |
def best_jshower(tracks):
"""Select the best JSHOWER track."""
return best_track(tracks, minmax=(krec.JSHOWERBEGIN, krec.JSHOWEREND)) | d1b3fe116adabf1558a6b0806cfbcd0aec5a42fa | 3,604,027 |
def plot_contours(ax, clf, xx: np.ndarray, yy: np.ndarray, **params):
"""
Generates a plot with the decision boundaries for a classifier.
:param ax: matplotlib axes object
:param clf: a classifier
:param xx: meshgrid ndarray
:param yy: meshgrid ndarray
:param params: dictionary of params to... | a81e911fab132217057da00313e5419118095abf | 3,604,028 |
import json
def available_native_languages():
"""
:return: jason with language codes for the
supported native languages. curently only english...
e.g. ["en", "fr", "de", "it", "no", "ro"]unquote_plus(flask.r
"""
available_language_codes = list(map((lambda x: x.code), Language.native_languages(... | 590b3d3feba574462645472c63753a1c81d51c1b | 3,604,029 |
from bs4 import BeautifulSoup
def strip_attrs(soup:BeautifulSoup, *args:str):
"""
Strip certain attributes from tags.
Args:
soup (BeautifulSoup): A dictionary entry extracted from the GDLC azw dictionary
args ([str]): A list of attributes to be stripped
Returns:
soup (Beautif... | e93dffa17b77dcfc71cad7b784f01e8ed549cc21 | 3,604,030 |
def MakeFutureReservationMessage(messages, reservation_name, sku_properties,
time_window, share_settings, reservation_zone):
"""Constructs a future reservation message object."""
future_reservation_message = messages.FutureReservation(
name=reservation_name,
specificSkuP... | 4ca46162638df14977e7292c25926aecc6b8876e | 3,604,031 |
def prob_roadmap(data, num_samples, z_max):
"""
Creates a probabilistic roadmap by
randomly sampling the environment and returning
a connected graph free of collisions
Args:
data: obstacle data
num_samples: number of points to be sampled
z_maz: sample limit in the z axis
... | 64956605d9141697e385c00b9c5bd028588f087a | 3,604,032 |
def create_matcher():
"""
Create different types of matchers to match descriptors.
"""
cross_check = bool(FEATURE_MATCHER == 'bf')
if FEATURE_EXTRACTOR in ('sift', 'surf'):
matcher = cv2.BFMatcher(cv2.NORM_L2, crossCheck=cross_check)
else:
matcher = cv2.BFMatcher(cv2.NORM_HAMMIN... | 61f24e7ffc76526034340583bc864717e070a219 | 3,604,033 |
def read(handle, format) :
"""Turns a sequence file into a single SeqRecord.
handle - handle to the file.
format - string describing the file format.
If the handle contains no records, or more than one record,
an exception is raised. For example, using a GenBank file
containing one record... | 4f545fc21913e15cf7fc827601e63ccba4448b21 | 3,604,034 |
def convert_float_to_rational_fraction_approximation(xi, maxsize=10000):
"""
Convert a float to its best rational fraction
approximation, where the size of the fraction numerator or
denominator cannot exceed maxsize.
Python 2.6 has this functionality built in, kind of ::
from fractions imp... | 678582bde7ff05316ca02147700c5bbb08f71107 | 3,604,035 |
def session_from_identity_service(identity_service):
"""Get Keystone Session from `identity-service` relation.
:param identity_service: reactive Endpoint
:type identity_service: RelationBase
:returns: Keystone session
:rtype: keystone_session.Session
"""
auth = keystone_identity.Password(
... | f62d6a44e701112ad13068d8a64ec8f506357190 | 3,604,036 |
def get_test_results_array(human, current_timestamp):
"""Will return an encoded test result array for this user's recent history
(starting from current_timestamp).
Negative results will be -1, unknown results 0, and positive results 1.
"""
results = np.zeros(human.conf.get("TRACING_N_DAYS_HISTORY")... | 23c8521c7123e354389a61c83f2ae6a83027b7b8 | 3,604,037 |
def resnet18(num_classes=1000, **kwargs):
"""resnet18"""
return ResNet([2, 2, 2, 2], num_classes, BasicBlock) | 86a688d2ce4141aa4ff03247f2220dbfbc7afc70 | 3,604,039 |
def list_get(lst, index, default=None):
"""
A safety mechanism for accessing uncharted indexes of a list. Always remember: safety first!
:param lst: list
:param index: int
:param default: A default value
:return: Value of list at index -or- default value
"""
assert type(lst) == list, "Re... | 41ca83d6a9b0ba66858617b48dcb6c43ca5a6a54 | 3,604,040 |
from galpy.potential_src.planarPotential import planarPotential
def verticalfreq(Pot,R):
"""
NAME:
verticalfreq
PURPOSE:
calculate the vertical frequency at R in the potential Pot
INPUT:
Pot - Potential instance or list thereof
R - Galact... | de29d91570a2ce675b0426ace818456a4b28077c | 3,604,041 |
def lbfgs(g: Tensor, s: Tensor, y: Tensor, r: Tensor):
"""P226"""
assert s.dim() == 3 # new, bch, dim
assert y.dim() == 3 # new, bch, dim
assert r.dim() == 3 # new, bch, 1
assert r.size(2) == 1
q = g # bch, dim
k = s.size(0)
a = []
for i in range(k - 1, -1, -1):
ai = r[i]... | 0bc3a543832d7fcd879328b9f140a1c52810153b | 3,604,043 |
def queryObject(graph, patterns, optionalPatterns=[], initialBindings = None) :
"""
Creation of a L{Query} instance.
@param patterns: either a
L{GraphPattern<rdfextras.sparql.graph.GraphPattern>}
instance or a list of instances thereof. Each pattern in the
list represent an 'OR' (or 'UNION') br... | 76bcbe8f8724bc56788885a7e777d02a07d69747 | 3,604,044 |
def DownloadFlags(flagList: list):
"""
下载多面旗帜
:param flagList: 下载旗帜的列表
:return: 下载旗帜的数量
"""
for flag in sorted(flagList):
image = DownloadOne(flag)
Show(flag)
SaveFlag(image, flag.lower() + ".gif")
return len(flagList) | f30c52377f0525ccc12e1b08dbd06c880a8bc75d | 3,604,046 |
import torch
def hhc_dgl_edge_compute_accuracy_unbatch(raw_scores, target):
"""
- raw_scores : shape (N_edges, 2)
- target : dgl graph with target.edata['solution'] of shape (N_edges,1)
"""
assert raw_scores.shape[1]==2, f"Scores given by model are not given with two classes but with {raw_scores... | 24278ab3837da16ea2872f14a421df35921657da | 3,604,047 |
def _context_url_pypi(context):
"""return the full sdist pypi url"""
# we need the pypi_name and the upstream_version variables to construct
# the full url
_context_check_variable(context, CONTEXT_VAR_PYPI_NAME,
'pypi_name')
_context_check_variable(context, CONTEXT_VAR_U... | ae96ebe26c0324372c961e46704f4b5f9fe4dba8 | 3,604,048 |
from typing import List
from typing import Union
from typing import Tuple
def executeToken(token: lexerTokens.baseLexerToken, inputDirection: direction, dataStack: List[int]) -> Union[Tuple[direction, List[int]], BaseException]:
"""
Executes the function associated with tokens
:param token: Input token
... | 8c75b9dd1446c54468dd6960114c7499d109cf3d | 3,604,049 |
from typing import List
def parse_der_certificates(der_bytes: bytes) -> List[Certificate]:
"""Parses a list of certificates from ASN.1 DER bytes.
Args:
der_bytes: List of X.509 certificates as ASN.1 DER bytes.
Returns:
A list of Certificate objects.
Raises:
X509CertificateEr... | 24202bc29bd26e9a24de43da3bb8272f21aae066 | 3,604,050 |
def fmt_money(amount, precision=None):
"""
Convert to string with commas for thousands, millions etc
"""
number_format = webnotes.conn.get_default("number_format") or "#,###.##"
decimal_str, comma_str, precision = get_number_format_info(number_format)
amount = '%.*f' % (precision, flt(amount))
if amount.fi... | a1d12cebca14234a7109135d82fa7e29044bb3d4 | 3,604,051 |
def lru_cache(f):
"""Can be used as a decorator for least-recently used caching. This is helpful when traversing
some edges several times during construction of the SPN, but also for reusing Tensors defined
in upward computation vs. downward computation.
Args:
f (function): A function f(*args, ... | 021c3b38733797862e6fa8f23f1b4e69563da17e | 3,604,052 |
def hz_people_stat_task():
""" 人员盘点定时任务页 """
return render_template('hz_people_stat_task.html') | 860ae6de42bc605c70aa793dbc188cff638906f0 | 3,604,054 |
def find_sense_type(wn, source, target):
"""Get the first relation type between the senses"""
(source_synset, source_entry) = decompose_sense_id(source)
entry = wn.entry_by_id(source_entry)
sense = [sense for sense in entry.senses if sense.id == source][0]
x = [r for r in source.sense_relations if r... | a7a84c69539968ff9aecc8283f5a37ea9b31f606 | 3,604,055 |
def delete_report(request, slug, pk):
"""
This view removes a report from the project detail page. For the
user, it will appear as though the report has been deleted. In
reality, the report is simply updated so that it is not longer
rendered and available on the project detail page but it will
... | 7244e0158d6bef6eecb6ff0319c3f377a0665fbe | 3,604,056 |
def iterate_items(collection, *args, **kwargs):
"""
iterates over the items of given object.
:param type collection: collection type to be used to
iterate over given object's items.
:rtype: iterator[tuple[object, object]]
"""
return iter(collection.items(*args, **k... | 49fde9f9c027ff1fc64a57ee67b06c91033f8755 | 3,604,057 |
from typing import Tuple
from pathlib import Path
def _prepifg_multiprocessing(m_path: MultiplePaths, exts: Tuple[float, float, float, float], params: dict):
"""
Multiprocessing wrapper for prepifg
"""
thresh = params[C.NO_DATA_AVERAGING_THRESHOLD]
hdr = find_header(m_path, params)
hdr[ifc.INP... | 62913ca2f8ef8f5c3f61751ec90e29468a900d3e | 3,604,058 |
def nominal_vars(term):
"""Find all bound and free nominal variables."""
if not isinstance(term, Term):
raise ValueError(term)
elif is_nvar(term):
return frozenset([term])
elif is_ivar(term) or is_atom(term):
return frozenset()
elif is_abs(term) or is_quote(term):
ret... | 87f6f4db74e2e49a49cb052bbc1d4968c118479e | 3,604,059 |
def float2uint(np_raster, dtype):
""" Função auxiliar para converter imagens em float, resultantes de filtros, para uint8 ou uint16
Args:
np_raster (np.ndarray): imagem em float
dtype (np.dtype): dtype a ser convertido
Returns:
(np.ndarray): imagem em uint8 ou uint16
"""
i... | 34c02525f9ebb97e318e32f09cfbb55066a031e0 | 3,604,060 |
def read_config(filenames=SEARCH_PATH):
"""Attempt to read local configuration files to determine spalloc client
settings.
Parameters
----------
filenames : [str, ...]
Filenames to attempt to read. Later config file have higher priority.
Returns
-------
dict
The configu... | a6c71f40eb0c86f86b2810b63189e8d1a9f38c6c | 3,604,061 |
def evidence_keys(request: HttpRequest) -> HttpResponse:
""" public page to display EKey details """
context = {
'keys': EvidenceKeyMap.instance().all_keys
}
return render(request, 'classification/evidence_keys.html', context) | ba15dd05010182d939953b78b74613b9c6bb7223 | 3,604,062 |
def sequential_or(*conditions):
"""
Use ``or`` operator between all conditions. Function is just
a syntax sugar that make long Tensorfow logical conditions looks
less ugly.
Parameters
----------
*conditions
Conditions that returns ``True`` or ``False``
"""
first_condition, o... | 66ff7729e36416d93957c32c7ae931891f9cd067 | 3,604,063 |
def _normalize_image(image, *, mean, stddev):
"""Normalize the image to zero mean and unit variance."""
image -= tf.constant(mean, shape=[1, 1, 3], dtype=image.dtype)
image /= tf.constant(stddev, shape=[1, 1, 3], dtype=image.dtype)
return image | 7bb9f9ffc834bc8f8d778883708908c677f432bc | 3,604,064 |
from pathlib import Path
from typing import List
def read_raw_data(folder: Path, split: str, lang: str) -> List[str]:
"""Makes sure we are reading each file at most once.
There is 1000 sentences per file, one file per lang so the memory footprint is ok.
"""
file = folder / f"{lang}.{split}"
asser... | 451a795b8dcc8d4698f7538b7b55800f3015038d | 3,604,065 |
def calc_first_class(d):
"""
Calculate percentage of first-class passengers
:param d: data frame
:return: rounded percents
"""
fst = np.sum(d['Pclass'] == 1)
return round(fst / d['Pclass'].count() * 100, 2) | 31f87528879429a2084826a5d9a1ed7c38c86ea1 | 3,604,066 |
def address_list(offset: int, limit: int):
"""List a subset of the address book"""
return address_book()[offset:offset+limit] | 148c6501953ab9e9327bcc0fa82268fac8426ab2 | 3,604,067 |
def two_mode_unitary_plots(target_unitary, learnt_unitary, square=False):
"""Plot the two-mode target and learnt unitaries as a matrix plot..
Args:
target_unitary (array): the size [cutoff, cutoff] target unitary.
learnt_unitary (array): the size [cutoff, gate_cutoff] learnt unitary.
Retur... | 133b58eec54d1871b3437a8c224d962e9444a92d | 3,604,068 |
from typing import Tuple
def is_multi_class(output_shape: Tuple[int, ...]) -> bool:
"""Checks if output is multi-class."""
# If single value output
if len(output_shape) == 1:
return False
return True | 66726be66cce6f837b40287b75c547d28d709a74 | 3,604,069 |
from typing import Optional
import inspect
async def axis(dataset_id: int,
data_var: str,
dim_name: str,
query: Optional[str] = None,
settings: config.Settings = Depends(config.get_settings)):
"""GET dimension values related to particular data_var"""
... | d509d01df02450f30df6cca79fc6c20298450931 | 3,604,070 |
def bipartite_single_sided_random_walk_with_restart(
g, seeds, restart_prob, max_nodes_per_seed,
max_visit_counts=0, max_frequent_visited_nodes=0):
"""Batch-generate random walk traces on given graph with restart probability.
The graph must be a bipartite graph.
A single random walk step i... | 0dc44e2f06c6075a9e6971dc906d46d293bdc9d2 | 3,604,071 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.