content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def user_activity_list(
user_id: str, limit: int, offset: int
) -> list[Activity]:
"""Return user_id's public activity stream.
Return a list of all activities from or about the given user, i.e. where
the given user is the subject or object of the activity, e.g.:
"{USER} created the dataset {DATASE... | 62c2035ea6fa04dbc12b3cd65fb44234bfaabcbb | 44,440 |
def repo_file(repo, *path, mkdir=False):
"""
"""
if repo_dir(repo, *path[:-1], mkdir=mkdir):
return repo_path(repo, *path) | 84c554c6ea4b69f4a6a3cd1bd2f4a3df4987e380 | 44,441 |
import csv
def lang_code_search(search_term, script_search):
"""
Returns a tuple: name of a code or a script, is it a script? (that's a boolean)
:param search_term: The term we're looking for.
:param script_search: A boolean that can narrow down our search to just ISO 15925 script codes.
:return:... | e7b5e1d18481a1628c900432e9f4efac71699128 | 44,444 |
def wrap_carracing(env, clip_rewards=True, frame_stack=True, scale=False):
"""Configure environment for DeepMind-style Atari.
"""
env = WarpFrame(env)
if scale:
env = ScaledFloatFrame(env)
if clip_rewards:
env = ClipRewardEnv(env)
if frame_stack:
env = FrameStack(env, 4)
... | de5888ba77640472fcb7d916e79d0bb33bdfa304 | 44,445 |
def continuum_imaging_workflow(vis_list, model_imagelist, context='2d', **kwargs):
""" Create graph for the continuum imaging pipeline.
Same as ICAL but with no selfcal.
:param vis_list:
:param model_imagelist:
:param context: Imaging context
:param kwargs: Parameters for functions in ... | 7fec7e6344a41023f4d1de4e3a52fecae64f1d8a | 44,446 |
import torch
def uneven_subsequent_mask(x_size: int, y_size: int) -> Tensor:
"""
Mask out subsequent positions (to prevent attending to future positions)
Transformer helper function.
:param size: size of mask (2nd and 3rd dim)
:return: Tensor with 0s and 1s of shape (1, size, size)
"""
ma... | 52524ea0411f47579591a3edb72a301a3464f368 | 44,447 |
def getTraceSpec():
"""
Return the module traceSpec used by all instances of Trace.
"""
return Trace.traceSpec | 95b9721a01c260e2f76d7088a3bc6409892b1b21 | 44,448 |
import re
def _get_version_from_git():
"""
Use the git tag to get a PEP compliant version string
"""
tag = _get_most_recent_git_tag()
# e.g. 1.0.1-4-f0f0333
m = re.match(
r"(?P<version>\d+\.\d+\.\d+)(?:-(?P<nadd>\d+)-(?P<hash>.+))?",
tag)
if not m:
raise RuntimeErro... | 2a9678a023fb9d43974c84810434b1dce0414103 | 44,449 |
def _token_param_shape():
"""Shape used in place of tokens as top-level computation arguments."""
return xc.Shape.array_shape(np.dtype(np.bool_), []) | 92b83d5a81addb82a8c8f14eb7aabd8b0226e6a2 | 44,451 |
def _is_amplitude_valid(symbolic_pulse: "SymbolicPulse") -> bool:
"""A helper function to validate maximum amplitude limit.
Result is cached for better performance.
Args:
symbolic_pulse: A pulse to validate.
Returns:
Return True if no sample point exceeds 1.0 in absolute value.
""... | 24c29a7ec8ff4f65cc6b1721ea4a1be4fa1537e7 | 44,452 |
import base64
import hashlib
def _sub_hash_password(password):
"""
Hash long password to allow bcrypt to handle password longer than 72 characters.
:param password: password to hash.
:return: (String) The hashed password.
"""
# bcrypt only handles passwords up to 72 characters.
# We use th... | 73498949c1e29712192d9379d14cf816d095a01a | 44,453 |
def _load_restricted_forward(source_vertno1, source_vertno2):
"""Load forward models and restrict them so that they include source
vertices"""
fwd_free = mne.read_forward_solution(fname_fwd)
fwd_free = mne.pick_types_forward(fwd_free, meg='grad', eeg=False)
# Restrict forward
vertno_lh = np.ran... | 19ee30addf3ac2702e21517690d94c85411dc795 | 44,455 |
def action_create_form_for_tickets_creation(article_id, erroneous_form=None):
"""Show form to register a tickets creation action for the article."""
article = _get_article_or_404(article_id)
shop = shop_service.get_shop(article.shop_id)
brand = brand_service.get_brand(shop.brand_id)
form = (
... | 3fd0faf307c7bdbf31bdc4d060272f3c820f393d | 44,456 |
import dateutil
def autoallocate(file, allocate_type='single', filename='', export_to='xlsx'):
"""Read and parse a downloaded doode poll (in '.xls' or '.xlsx') where participants are
able to choose as many timeslots as possible. Automatically allocate participants to a
slot based on their chosen availabil... | 29cc0b73aa34b2f4c253f98559a3a501662ae1ef | 44,458 |
def MultIntensity( Fin, Intens):
"""
*Multiplies the field with a given intensity distribution.*
:param Fin: input field
:type Fin: Field
:param Intens: N x N square array of real numbers or scalar
:type Intens: numpy.ndarray, float, int
:return: output field (N x N square array of comp... | a83022633a344f9445207fc2bc0fa8b02df6401c | 44,459 |
from colorsys import rgb_to_hsv
def from_rgb_to_paletton_hue(rgb, paletton):
"""
>>> p = Paletton()
>>> print(from_rgb_to_paletton_hue((120, 0, 106), p))
318
"""
rhs_hue = round(rgb_to_hsv(*rgb)[0]*360)
if rhs_hue not in paletton.HUE_OFFSETS:
keys = sorted(paletton.HUE_OFFSETS.keys... | c76f257f46fc9c84d830c2f006f1af8155cbb38f | 44,460 |
def matmul_default(
cfg,
tensor_a,
tensor_b,
bias=None,
out_dtype=None,
transpose_a=False,
transpose_b=False,
):
"""Matmul operator on GPU"""
return nn.matmul(tensor_a, tensor_b, bias, out_dtype, transpose_a, transpose_b) | ac59a9b726c08dc23f86ab1c0f1256f9b44d5336 | 44,461 |
def is_range_format(expression: str) -> bool:
"""判断表达式是否为范围表达式"""
range_list = expression.split(BuildInChar.HYPHEN)
if len(range_list) != 2:
return False
return True | bfd9fdc2cb39e0e4f06b6919b3c32b937532d938 | 44,462 |
def yukawa_green_function(k: float, alpha: float, kappa: float) -> float:
"""
Evaluate the Green's function of Coulomb/Yukawa potential.
.. math::
G(k) = \\frac{4 \\pi }{\\kappa^2 + k^2} e^{- (k^2 + \\kappa^2)/4 \\alpha^2 }
Parameters
----------
k : float, numpy.ndarray
Range ... | d134490d278baa272a9935f272dd3f468dbae7e1 | 44,463 |
def dt_compat_on_bus(kconf, _, compat, bus):
"""
This function takes a 'compat' and returns "y" if we find an "enabled"
compatible node in the EDT which is on bus 'bus'. It returns "n" otherwise.
"""
if doc_mode or edt is None:
return "n"
if compat in edt.compat2okay:
for node i... | cc3c0290f0bd03940c922121b71d720d5811554b | 44,465 |
def floodlight_report(config, task:dict, floodlight_id: int) -> int:
""" Create a report for a specific floodlight if it does not exist.
Args:
floodlight_id - the floodlight being monitored
Returns:
The id of the created report.
"""
account_id, subaccount_id = parse_account(
config,
task['a... | b3992510689091db520dcc02c1a8c794560b8575 | 44,466 |
def init_server(cli_options):
"""Initialize the flashfocus server with given command line options."""
ensure_single_instance()
if cli_options["opacity"]:
warn("--opacity is deprecated, please use --flash-opacity/-o instead")
if "flash_opacity" not in cli_options:
cli_options["fl... | d181b04f98b6bcd8a5725cef2eec83a0dbd0e9a1 | 44,467 |
def prep_rays_setup(
ghz = 95,
lat_of_cen = 10,
cml = 20,
radius = 1.1,
bfield = None,
distrib = None,
ray_tracer = None,
):
"""Create and return a VanAllenSetup object that will be used in the
"preprays" tool: it precomputes all of the key quantities need... | 138bf900c609bffc2f25330fceb33b6e0e066146 | 44,468 |
from typing import Union
from typing import cast
from typing import List
def is_admin(
channel: TextChannel, user_or_member: Union[discord.User, discord.Member]
) -> bool:
"""Checks to see if given user or member has the admin role on this server."""
member = (
user_or_member
if hasattr(us... | bff00e1c9072b4df5033166de5f9adb890a1ee1f | 44,469 |
def _get_baseline_options(site):
"""
Extracts baseline options from ``site["infer"]["baseline"]``.
"""
# XXX default for baseline_beta currently set here
options_dict = site["infer"].get("baseline", {}).copy()
options_tuple = (options_dict.pop('nn_baseline', None),
options_d... | 375a69ae370a944edfe43bfae3dd1655e2b26ae7 | 44,471 |
def _launch_client(gke_settings, stress_server_settings, stress_client_settings,
bq_settings, kubernetes_proxy):
""" Launches a configurable number of stress test clients on GKE cluster """
if not kubernetes_proxy.is_started:
print 'Kubernetes proxy must be started before calling this functio... | bb5fd654d203864b42cddca34c1b0a5527e3bcef | 44,472 |
def find_largest_digit(n):
"""
:param n:
:return:lar
"""
global lar, new_lar
if abs(n) > 0:
r = abs(n) % 10 # 取(剩下的數字)最後的數字 用餘數來取
if lar < r:
lar = r
new_lar = r
find_largest_digit(int(n/10)) # 取剩下的數字
lar = 0 # for the next to compare
return new_lar | ed490aadce460f7003af00a629cb956555acef42 | 44,473 |
import logging
def convert(value, as_type, source):
"""Convert the value as a given type where the value comes from the given source"""
getter = _get_converter(as_type)
try:
return getter(value)
except Exception as exception:
logging.warning("%s failed to convert %r as %r because %r", ... | fb4d3c429bd96942ce9f74aa14e2dbe6a188a6a2 | 44,474 |
def extractMatrix(
source,
bounds=None,
boundsSRS="latlon",
maskBand=False,
autocorrect=False,
returnBounds=False,
band=1,
):
"""extract all or part of a raster's band as a numpy matrix
Note:
-----
Unless one is trying to get the entire matrix from the raster dataset, usage
... | 85541e9a23d9f3e87c047beea95b9ffa4d7fc74b | 44,475 |
from trac.util.translation import _
def paginate(items, page=0, max_per_page=10):
"""Simple generic pagination.
Given an iterable, this function returns:
* the slice of objects on the requested page,
* the total number of items, and
* the total number of pages.
The `items` parameter can b... | b44b951b24559164862309a342cb17623809df26 | 44,476 |
def change_hsv(image, sat, bright):
"""
Args:
image : numpy array of image
sat: saturation
bright : brightness
Return :
image : numpy array of image with saturation and brightness added
"""
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
... | 3e3af52e5e13116fda78140fd5f8336d614569c3 | 44,477 |
from typing import List
from typing import Tuple
import torch
def select_foreground_proposals(
proposals: List[Instances], bg_label: int
) -> Tuple[List[Instances], List[torch.Tensor]]:
"""
Given a list of N Instances (for N images), each containing a `gt_classes` field,
return a list of Instances tha... | 74e702b0b01be41992dfd391abd2fb6e695d7b69 | 44,478 |
import torch
def hutchinson_trace_autodiff_blockwise(V):
"""Hessian trace estimate using autodiff block HVPs."""
trace = 0
for _ in range(V):
for p in model.parameters():
v = [rademacher(p.shape)]
Hv = hessian_vector_product(loss, [p], v)
vHv = torch.einsum("i,... | 1ad596ff5e7b30dd284b3e3926664eff0d71b0fa | 44,479 |
def check_received_rewards(cadet, reward_tier):
"""[checks if given reward has recieved the reward for the given reward tier]
Arguments:
cadet {[Cadet]} -- [cadet object]
reward_tier {[int]} -- [reward tier]
Return:
boolean
"""
if User_Reward_Log.objects.filter(cadet=c... | c698153d9f93db002fb48032f60e50917326280d | 44,480 |
from typing import List
from typing import Dict
def batch_obs(
obs: List[Observation], obs_space: ObsSpace, action_space: Dict[str, ActionSpace]
) -> ObsBatch:
"""
Converts a list of observations into a batch of observations.
"""
entities = {}
ids = []
action_masks: Dict[str, ActionMaskBat... | 585f126bbdf4a0fac051bb13453191dd1d908d73 | 44,481 |
def brusselator(t, X, **kwargs):
"""
The Brusselator.
@type t: number
@param t: current time
@type X: vector
@param X: current state
@rtype: vector
@return: derivative
"""
x = X[0]
y = X[1]
if len(kwargs) == 0:
x_dot = 1 - (BRUSS_B + 1) * x + BRUSS_A * x**2 *... | e2bd5f3cc4d83823909115dc168fba0917c711a8 | 44,482 |
def nearest_neghbors(descriptor_dict, descs):
"""
Computes the nearest neighbors of a list of descriptors in a descriptor dictionary
:param descriptor_dict: a descriptor dictionary like in create_kmeans_dict
:param descs: a list of descriptors of an image
:return: the indices of the nearest neighbor... | 372d7846ea6f18a86d7ae36b9874a953fd1cf159 | 44,483 |
def generate_config_from_os():
"""
Determines runlevel and project_env from environment variables, then
returns generate_eve_config(project_env, runlevel).
"""
project_env = ProjectEnv.detect_from_os(fallback_to_default=True)
LOGGER.info("Detected PROJECT_ENV: " + str(project_env))
runlevel... | 29a5dac0ddbe9b62ac25a0b1ed959d2b1cca933d | 44,484 |
import scipy
def match_bounding_boxes(t_boxes, d_boxes, iou_threshold):
"""Matches detection boxes with tracked boxes based on IoU.
This function can be used to find matches between sets of bounding boxes
found with an object detector and tracked with a tracker. It yields three
arrays with indices in... | 9ee6021a312451a2a1ebdd9e05b5253c15da9542 | 44,485 |
import random
import requests
import json
def OpenStreetMapNominatim(lon, lat):
"""
Get the target's street infomation from ip lon and lat locations by using OpenStreetMap.
請求次數少量可用,大量請求使用MapQuest提供的API.->使用geocoder庫即可。
:param lon: The IP lon infos, which refer WGS84.
:param lat: The IP lat info... | f2f0a3b774cad02b4844a0e73a0aa8015f2c88ea | 44,486 |
def check_format(format, subtype=None, endian=None):
"""Check if the combination of format/subtype/endian is valid.
Examples
--------
>>> import soundfile as sf
>>> sf.check_format('WAV', 'PCM_24')
True
>>> sf.check_format('FLAC', 'VORBIS')
False
"""
try:
return bool(_f... | 30c2a3622b974bcbfaffe70ecc4669f6141299c7 | 44,487 |
from typing import OrderedDict
import json
def kingdom_death(return_type=None):
""" Returns a dictionary of all assets. """
output = OrderedDict()
all_assets = list_game_assets()
for asset_collection in all_assets:
asset_object = get_game_asset(asset_collection, return_type=object)
i... | 6d5ec36fab52da8f40ce65ea339133cb3f659fa5 | 44,488 |
import logging
import time
def wait_for_task(task, timeout=60.0, pause_timeout=True):
"""
Waits for a single vim.Task to finish and returns its result.
:param task: The task to wait for
:type task: vim.Task
:param float timeout: Number of seconds to wait before terminating task
:param bool pa... | fe23c8fc5d701216e4ebb261ad975905679235bb | 44,489 |
def iobes2iob(iobes):
"""Converts a list of IOBES tags to IOB scheme."""
dico = {pfx: pfx for pfx in "IOB"}
dico.update({"S": "B", "E": "I"})
return [dico[t[0]] + t[1:] if not t == "O" else "O" for t in iobes] | 3baed417dfccf25ddf5f0bdae686a01fa8bfda95 | 44,490 |
def spread_scores_over_map(score_map):
# type: (np.ndarray) -> np.ndarray
"""Given a 2D score array, spread these scores to their neighbours.
The maximum neighbour wins. Deduct by 1."""
neighbour_scores = np.zeros(score_map.shape + (4,))
neighbour_scores[1:, :, 0] = score_map[:-1, :]
neighbour_scores[:-1, :, 1] ... | 6379ada6553f27ecd38eb3d8a5e373ddd9495cc8 | 44,491 |
def create_obb(bbox, R, color=(0, 1, 0)):
"""Draw an oriented bounding box."""
assert len(bbox) == 6, f'The format of bbox should be xyzwlh, but received {len(bbox)}.'
obb = o3d.geometry.OrientedBoundingBox(bbox[0:3], R, bbox[3:6])
obb.color = color
return obb | b9b517b8b39d3d091b67d8cc3bf64a69b9926b2a | 44,492 |
from torchvision.models.resnet import resnet50
def resnet50(pretrained=False, fixed_feature=True):
""" "ResNet-50 model from torchvision's resnet model.
:param pretrained: if true, return a model pretrained on ImageNet
:param fixed_feature: if true and pretrained is true, model features are fixed while t... | f8be31a93f30e6906afa598ffbfeb8bf42520e27 | 44,493 |
def constant_prices_data(report_name: str, investor_name: str, months: int) -> pd.DataFrame:
"""Переводит данные в постоянные цены."""
df = get_investor_data(report_name, investor_name)
df = df.iloc[-months - 1 :]
cpi = indexes.cpi(df.index[-1])
cpi = cpi[-len(df) :]
cpi = cpi.cumprod()
cpi ... | 2aa778a40eacbb6850d8846626cb8e4e493e062b | 44,494 |
def delta_update_basesamdb(refsampath, sampath, creds, session, lp, message):
"""Update the provision container db: sam.ldb
This function is aimed for alpha9 and newer;
:param refsampath: Path to the samdb in the reference provision
:param sampath: Path to the samdb in the upgraded provision
:param... | 404a46e444f58bf41175fcbfae7d35010ee99d04 | 44,495 |
def check_znak(m1,p1,m2,p2, treshold = 100):
"""
Checks wheather we should check for people to know each other
:type m1: numeric list
:param m1: list with all circles for client 1
:type p1: numeric list
:param p1: list with probabilities of circles for client 1
:type m2: numer... | aa27cb2ff2905fdacfad2425ee4378afc7a4245e | 44,498 |
import requests
def get_content_from_pub_json(pub, format):
"""Get text content based on a given format from a publication JSON.
In the case of abstract, the content is returned
from the JSON directly. For pdf, the content is returned as bytes
that can be dumped into a file. For txt and xml, the text... | f04a5555c8cfe63d3eb49fb604b9ad1f35fc60b3 | 44,499 |
def getFromLongestMatchingKey(object, listOfKeys, caseInsensitive=True):
"""
Function to take an object and a list of keys and return the value of the
longest matching key or None if no key matches.
:param object: The object with the keys.
:type object: dict
:param listOfKeys: A list of keys to... | 25271697197c5c16c2ad5ae7320fc452bc3c8205 | 44,500 |
def get_subscribers():
"""Get all global subs"""
return _SUBSCRIBERS | 03b080796a4688b039f0380ee3ba95202067aabe | 44,501 |
def python_version_is_greater_or_equal(major, minor=0, micro=0):
"""Alias for `~json_indent.pyversion.python_version_is_at_least()`:py:func:."""
return python_version_is_at_least(major, minor, micro) | d3a1b2680b13e20c439ae12cb334bec50f958d42 | 44,502 |
def parse_mimetype(mimetype):
"""Parses a MIME type into its components.
:param str mimetype: MIME type
:returns: 4 element tuple for MIME type, subtype, suffix and parameters
:rtype: tuple
Example:
>>> parse_mimetype('text/html; charset=utf-8')
('text', 'html', '', {'charset': 'utf-8'})
... | ae6136ecc9602a162853204642a443e904cac4b8 | 44,503 |
def generate_summary_movement_report(
movement_detail_report: pd.DataFrame,
) -> pd.DataFrame:
"""
Aggregate by source time for period statistics.
"""
summary_movement_report = movement_detail_report.groupby("source_time")[
[
"transportation_units",
"transportation_co... | e2ebc246486ef5de62d223d86ae12ab4dc8e7142 | 44,504 |
def object_key(obj):
"""Generate a checksum for a nested object or list."""
key = sha1()
if isinstance(obj, (list, set, tuple)):
for o in obj:
o = object_key(o)
if o is not None:
key.update(o)
elif isinstance(obj, dict):
for k, v in obj.items():
... | 7f503cf03d98f03a75dec53e289065ca6aec4c2b | 44,505 |
import numpy
def gfalternate_gotdataforgaps(data,data_alternate,alternate_info,mode="verbose"):
"""
Returns true if the alternate series has data where the composite series has gaps.
"""
return_code = True
ind = numpy.where((numpy.ma.getmaskarray(data)==True)&(numpy.ma.getmaskarray(data_alternate)... | 6bf3bdb84ceaf2a1a9e16efd9199b30774291281 | 44,506 |
def key_type(key):
"""String identifying if the key is a 'name' or an 'ID', or '' for None.
This is most useful when paired with key_id_or_name_as_string.
Args:
key: A datastore Key
Returns:
The type of the leaf identifier of the Key, 'ID', 'name', or ''.
"""
if key.id():
return 'ID'
elif k... | 8d055fc97313b7f613e5927d0f8f38d060a2cb2b | 44,507 |
def cvReadString(*args):
"""cvReadString(CvFileNode node, char default_value=None) -> char"""
return _cv.cvReadString(*args) | 25124e0ad0e1490ed3742d64f14cee4e43ec11e9 | 44,508 |
def compare_graph_properties(graph_properties):
"""
This function takes a dataframe of graph properties.
Each graph property is compared to other groups with the Mann-Whitney test.
Takes a pandas dataframe of graph properties with the following columns:
Network, Group, Network type, Conserved fract... | 2fd164bda1fe37e70efefbc9df75fc91b232f373 | 44,509 |
def _select_encoding(consumes, form=False):
"""
Given an OpenAPI 'consumes' list, return a single 'encoding' for CoreAPI.
"""
if form:
preference = [
'multipart/form-data',
'application/x-www-form-urlencoded',
'application/json'
]
else:
pre... | 81cac06c34f3df0d3c570ebcae90545a3a988fbc | 44,510 |
def execute_command(command: str, new_image: Image, threshold=True) -> Image:
""" __author__ = "Trong Nguyen"
Return a new image given a valid command, an image and if required,
a threshold value.
>>> execute_command("E", new_image, 10)
"""
functions = {"L": load, "S": save_as,
... | 54e87e4124ad05f21aeac99c5712da0863c8075a | 44,511 |
def previous_prime(x):
"""前一个质数"""
if x <= 2:
return None
if x == 3:
return 2
if x % 2 == 0:
x -= 1
else:
x -= 2
while True:
if is_prime(x):
return x
else:
x -= 2 | 6ae7e33d55f3794da904db2040bea49a58eafb84 | 44,513 |
def other_classes(nb_classes, class_ind):
"""
Heper function that returns a list of class indices without one class
:param nb_classes: number of classes in total
:param class_ind: the class index to be omitted
:return: list of class indices without one class
"""
other_classes_list = list(ra... | 05b88e49827523508b14400aa83aa83dd48f2b2e | 44,514 |
def manage_frozen_objects():
"""
Manage objects that have been frozen due to being unsuitable for
preservation for time being
"""
return render_template(
"tabs/manage_frozen_objects/manage_frozen_objects.html"
) | b688fdf93b144a546215ea0206a580776e951b49 | 44,515 |
def get_gvf(data_list, num_classes):
"""
The Goodness of Variance Fit (GVF) is found by taking the difference between the squared deviations
from the array mean (SDAM) and the squared deviations from the class means (SDCM), and dividing by the SDAM
"""
breaks = get_jenks_breaks(data_list, num_class... | 531454ece4102db986b8d37f21e666cad17412c8 | 44,517 |
def init_capacities(edges, transactions, amount_sat, verbose=False):
"""Initialize capacity map for path search"""
tx_targets = set(transactions["target"])
# init capacity dict
keys = list(zip(edges["src"], edges["trg"]))
is_trg = edges["trg"].apply(lambda x: x in tx_targets)
# [current_cap, tot... | cf1de4433c52d07ccd75f7ef39d2899974ec8517 | 44,518 |
def calculate_iou(gt, pr, form='pascal_voc') -> float:
"""Calculates the Intersection over Union.
Args:
gt: (np.ndarray[Union[int, float]]) coordinates of the ground-truth box
pr: (np.ndarray[Union[int, float]]) coordinates of the prdected box
form: (str) gt/pred coordinates format
... | c093fb8b36a87e2aad862d842e71f1f76b3dd791 | 44,520 |
import json
from datetime import datetime
def create_task(tenant_id='tenant_id'):
"""
Create a new task entry.
POST format:
{
"name": "My New Task",
"config": "\{\"task\": \"do something\"\}",
"agent_url": "swift://region-a.geo-1/mycontainer/myagent.py",
"email": "jeff.kramer@hp.com",
"interval": "300",... | 543213c5c370500b7076687901fcddbaa9da5ae9 | 44,521 |
from typing import Dict
from io import StringIO
def interpolate(s: str, registers: Dict) -> str:
"""
Interpolates variables in a string with values from a supplied dictionary of registers.
The parser is very lax and will not interpolate variables that don't exist, as users
may not be intending to int... | a877e455771e09bcca85455ffefe87c4622255f2 | 44,522 |
def login(user=None, verified=False, admin=False, overrides=None, return_field=None):
"""
Logs in user and returns the User object. If a user object is not specified,
one is randomly generated. The user object is force authenticated on the
DRF API client. If the return_field is specified it returns the ... | 7da1a5f50d10bce6cc4231cdb084e6a635d169a3 | 44,523 |
def retrieve_from_any(ecli, rootpath=None):
"""
Checks if it can find the xml document in the filesystem,
otherwise retrieves it from the web.
:param ecli:
:param rootpath:
:return: xml element
"""
el = None
if rootpath is not None:
el = retrieve_xml_from_filesystem(ecli, r... | 37daf8adb654e941c1fdfd075470375860569759 | 44,524 |
def defineNodePositions(smax,pmin,fun,nodegap,L=200.):
"""
Loop through sections and determine optimal placement
of nodes in order to prevent vignetting/collisions
"""
#Loop through sections and construct node positions
N = len(smax)
rsec = []
rext = []
gap = L*3e-3+0.4 #.4 mm glass ... | 52a08fa1dc25d80ff5aff5e166eec8f9b396a257 | 44,525 |
import numexpr
def normalize_mi_ma(x, mi, ma, clip=True, eps=1e-20, dtype=np.float32): # dtype=np.float32
"""This function is adapted from Martin Weigert"""
if dtype is not None:
x = x.astype(dtype, copy=False)
mi = dtype(mi) if np.isscalar(mi) else mi.astype(dtype, copy=False)
ma = d... | c8a93fff58dfa9d288128278d2d894df82427122 | 44,526 |
def read_image(img_path):
"""Keep reading image until succeed.
This can avoid IOError incurred by heavy IO process."""
got_img = False
while not got_img:
try:
img = Image.open(img_path).convert('RGB')
got_img = True
except IOError:
print("IOError incur... | 26d0d0061d14e6916273a4fd418d5364ea1256ec | 44,527 |
def check_image_valid(im_source, im_search):
"""Check if the input images valid or not."""
if im_source is not None and im_source.any() and im_search is not None and im_search.any():
return True
else:
return False | d5bc706df271163b1857158820ee707a0229b83c | 44,528 |
def fabric_inband_net_create(module, inband_static_part):
"""
Method to create in-band network.
:param module: The Ansible module to fetch input parameters.
:param inband_static_part: It contains ip address of inband ip till third
octet.
:return: The output messages fo... | a44edd0e3998cd3ac622876a852d9e2aafa045e2 | 44,529 |
def create_match_apds_input_filenames(from_date, to_date, datestring):
""" Create the list of filenames for match_apt_trajectories.py. """
return [create_flights_filename(CPR_FR24, datestring),
create_apds_flights_filename(from_date, to_date),
create_events_filename(CPR_FR24, datestring)... | 118c214bfe1da657b2020ff4cc977cbef43266d5 | 44,530 |
def get_emoji_modifier_sequences(age=None):
"""Return map of modifier sequences to name, optionally limited to
those <= the provided age."""
_load_emoji_sequence_data()
return _age_map_select(_emoji_modifier_sequences, age) | ad3f48d2492caa24bcbc4d055a95a2d088921795 | 44,531 |
def update_taxes_with_shipping_lines(taxes, shipping_lines, shopify_settings):
"""Shipping lines represents the shipping details,
each such shipping detail consists of a list of tax_lines"""
for shipping_charge in shipping_lines:
if shipping_charge.get("price"):
taxes.append({
"charge_type": _("Actual"),
... | 21a30b6d9e83432b9772c70bce30cd722ccb10c5 | 44,532 |
from typing import List
def equal_accuracy(confusion_matrix_list: List[np.ndarray],
tolerance: float = 0.2,
label_index: int = 0) -> np.ndarray:
"""
Checks if accuracy difference of all grouping pairs is within tolerance.
.. note::
This function expects a list... | f7bd87ae947acd1496fd11b5c96b492d5af978eb | 44,533 |
def vm_snapshot_list_cb(result, task_id, vm_uuid=None, snap_ids=None):
"""
A callback function for DELETE api.vm.snapshot.views.vm_snapshot_list.
"""
snaps = Snapshot.objects.filter(id__in=snap_ids)
action = result['meta']['apiview']['method']
if result['returncode'] == 0:
vm = snaps[0]... | d57eb75d596a414ec77b4a3fe471c665b34f40b0 | 44,534 |
import array
import math
def fpart(x):
"""FRACTIONAL PART OF A REAL NUMBER"""
if type(x) in [array, list]:
if len(x) == 1:
x = x[0]
return math.modf(x)[0] | 03659c7b0ae133d226019141af59f4ec039c7dde | 44,535 |
def BinomialNum(n, p):
"""Generate a binomially distributed random number with parameters n (int) and p (float)"""
assert type(n) == int, "n must be an integer"
assert n >= 1, "n must be greater than or equal to 1"
assert 0 < p < 1, "p must be between 0 and 1, exclusive"
return sum([BernoulliNum(p) for x in range(... | d96a49b07d9068e2c7352e241c515d6c5f2642b7 | 44,537 |
def graph_size_filter(graph, edge_weigths, node_sizes, min_size,
node_labels=None, relabel=False):
"""
"""
n_nodes = graph.numberOfNodes
if node_labels is None:
seeds = np.zeros(n_nodes, dtype='uint64')
assert n_nodes == len(node_sizes)
keep_nodes = node_si... | 8509d6f207bbd2ed8e676c2909b2daa2792a596e | 44,538 |
def prepare_arguments_deps(parser):
"""Parse arguments that belong to this verb.
Args:
parser (argparser): Argument parser
Returns:
argparser: Parser that knows about our flags.
"""
parser.description = """ Manage dependencies for one or more packages in
a catkin workspace.... | a81760948787921c0bdaa6d34a34f688392f2a0f | 44,539 |
from typing import Optional
def bar(a: Optional[int], b: t.Optional[int]) -> int:
"""WHAT"""
return (a or 42) + (b or 0) | b2e43cb30c8af5fa8b03220ae0f7260084a5f9fd | 44,540 |
from functools import reduce
def checkarrays(f):
""" Similar to the @accepts decorator """
def new_f(*args, **kwd):
assert reduce(lambda x, y: x == y, map(np.shape, args))\
, """Array and Subarray must have same dimensions,
got %s and %s"""\
.replace(' ', '') % (ar... | 50c579f02cd99a84eb7c9e11a1daf63e652d7f52 | 44,541 |
from PCAfold import PCA
def outlier_detection(X, scaling, method='MULTIVARIATE TRIMMING', trimming_threshold=0.5, quantile_threshold=0.9899, verbose=False):
"""
Finds outliers in the original data set, :math:`\mathbf{X}`, and returns
indices of observations without outliers as well as indices of the outli... | d5d596616ab8ee838cfbf0c679f07a7bfbb06c32 | 44,542 |
def count_smileys(arr):
"""count valid smileys from an array, better reading"""
count = 0
eyes = ":;"
noses = "-~"
smiles = ")D"
for i in arr:
if len(list(i)) > 2:
if i[0] in eyes and i[1] in noses and i[2] in smiles:
count += 1
else:
if i[0] in eyes and i[1] in... | ebcd9147614b47a9911dfcb408bfd74c71de4203 | 44,545 |
def apply_mlrun(
model,
context: mlrun.MLClientCtx = None,
X_test=None,
y_test=None,
model_name=None,
generate_test_set=True,
**kwargs
):
"""
Wrap the given model with MLRun model, saving the model's attributes and methods while giving it mlrun's additional
features.
examples... | 8b84c7ea83d9c67a481afd423218150594ecaf4f | 44,546 |
def process_file(filename,word_to_id,cat_to_id,max_length=600):
"""
Args:
filename:train_filename or test_filename or val_filename
word_to_id:get from def read_vocab()
cat_to_id:get from def read_category()
max_length:allow max length of sentence
Returns:
x_pad: sequence data from preprocessing sentence ... | 0eca98da162000b1d86a707514eb4b4b13fa85ce | 44,547 |
def get_key_list(u_id: str, um_status: int) -> list:
"""
获取某个用户保存的友盟keys
:param u_id:
:param um_status:
:return:
"""
_filter: Q = Q(u_id=u_id) & Q(um_status=um_status)
return list(UmKey.objects.filter(_filter).values()) | 09d4808161994c4515588bf9b7761842ced490e0 | 44,548 |
def balanced_tree(ordered):
"""Create balanced binary tree from ordered collection"""
bt = BinaryTree()
add_range(bt, ordered, 0, len(ordered)-1)
return bt | 50fc5c843c581107df8b1db1d1bb8db74a0b5147 | 44,549 |
def tf_split(x, num_or_size_splits, axis=0, num=None, keep_dims=False):
"""Split feature map of high dimension into list of feature map of low dimension."""
x_list = tf.split(x, num_or_size_splits, axis, num)
if not keep_dims:
x_list2 = [tf.squeeze(x_, axis) for x_ in x_list]
return x_list2... | 529f713c9fcd94599f4eb320d8529ed53f551f11 | 44,550 |
def stringify_edge_set(s: set):
""" Convert an agent-piece graph into a string, for display and testing """
return str(sorted([(agent.name(), piece) for (agent,piece) in s])) | 8d95fa4174a37bac1094a13449f92143993bdd23 | 44,551 |
def rholoc(A1: tn.Tensor, A2: tn.Tensor) -> tn.Tensor:
"""
-----A1-----A2-----
| |(3) |(4) |
| |
| |
| |(1) |(2) |
-----A1*----A2*-----
returned as a (1:2)x(3:4) matrix.
Assuming the appropriate Schmidt vectors have been contracted into the As,
np.trac... | c05735c17f0ca58f19388c691366c51c07d2f584 | 44,552 |
def _d(n, j, prec, sq23pi, sqrt8):
"""
Compute the sinh term in the outer sum of the HRR formula.
The constants sqrt(2/3*pi) and sqrt(8) must be precomputed.
"""
j = from_int(j)
pi = mpf_pi(prec)
a = mpf_div(sq23pi, j, prec)
b = mpf_sub(from_int(n), from_rational(1,24,prec), prec)
c ... | f2a37ee3df6dc2d5a1e615df88ef43e37031f872 | 44,553 |
def render_show_category_json(category_id):
"""
METHOD=GET.
Returns a JSON object of a specific category
"""
category = session.query(Category).filter_by(id=category_id).one()
items = session.query(Item).filter_by(category_id=category_id).all()
if category and items:
return jsonify(... | 29f14e41b91820c883d33539d71c96bbd9dbf047 | 44,554 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.