content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_footprint(request):
"""Generates and render png"""
template = loader.get_template('dashboard/fits_to_png.html')
start = request.GET.get('start')
end = request.GET.get('end')
program = request.GET.get('program')
if not program:
processed_exposures = []
elif not start or not en... | be8b12b04d8fb2cd14a5f66e703d539ed07acf5c | 44,400 |
def test_game(env, agent, n_eval_episodes):
"""
Test the agent to measure rewards.
It evlautes the agent with the environment for some epidoses,
and record totol rewards.
:param env: environment to intereact with
:param agent: agent
:param n_eval_episodes: number of episodes
"""
all... | 8ed5db93ad5af4fa99910e732ee8b1c62f3a7eb0 | 44,401 |
def dict_union_combine(dict1, dict2, combine_op=op.add,
default=util_const.NoParam,
default2=util_const.NoParam):
"""
Combine of dict keys and uses dfault value when key does not exist
CAREFUL WHEN USING THIS WITH REDUCE. Use dict_stack2 instead
"""
key... | df0519411a82f416b797a87c9cd728d0b95ad419 | 44,402 |
import operator
import calendar
def _get_order_book(base_asset, quote_asset,
bid_book_min_pct_fee_provided=None, bid_book_min_pct_fee_required=None, bid_book_max_pct_fee_required=None,
ask_book_min_pct_fee_provided=None, ask_book_min_pct_fee_required=None, ask_book_max_pct_fee_... | 6651e6ba63f58ce44ed10155111c8bb272740062 | 44,403 |
def mixed_treatment_intervention():
"""Apply mixed strategy on all controls starting at time 0."""
return zika.Intervention(
time=0,
treated_bednet_use=0.5,
condom_use=0.5,
treatment_of_infected=0.5,
indoor_spray_use=0.5,
) | 8bac3c90cbe77dc55c24e35707cbeccbc3b09f8f | 44,404 |
def expand_agent(agent, ontology, ns_filter=None):
"""Return children agents of a given parent agent.
Parameters
----------
agent : indra.statements.Agent
An INDRA Agent whose children in the given ontology should
be returned as Agents.
ontology : indra.ontology.IndraOntology
... | 16995d99344259164a4ed33c908636f3037d4c71 | 44,405 |
def sphericalize_density_matrix(mol, dm):
"""Sphericalize the density matrix in the sense of an integral over all possible rotations.
Args:
mol (pyscf Mole): pyscf Mole object used for the computation of the density matrix.
dm (numpy ndarray): density matrix in AO-basis.
Returns:
n... | 4f8e0182aa46a2ef5cf8ec9251c11c280f3e23f9 | 44,406 |
def has_specific_team_access(user, team):
"""
To have access to a team a user must:
- Be course staff
OR
- be in the correct bubble
- be in the team if it is private
"""
return has_course_staff_privileges(user, team.course_id) or (
user_protection_status_matches_t... | 2a3246e18afefe3df0cb590dfd89d4200f87d451 | 44,407 |
import logging
def check_queue(queue_name):
"""
Args:
queue_name : queue_name of the queue
Checks queue for messages, logs queue status of messages left on que and hidden messages
returns only when queue is empty
"""
region = get_config()['provider']['region']
client = boto3.cli... | 7d6972aaf1a0cb6734dc25b503d424504fed507c | 44,408 |
def plot_trap(radius= default_radius, height= default_height, slope= default_slope, delta= default_delta, constant_population= True):
"""Generates a plot for the fish trap operating over 1 week
Args:
radius: the radius of the semi-circular trap created
height: the height of the trap
slo... | ab92b847117033d61117720f4e25c5cbbcd6706d | 44,409 |
def systematic_sample(n, prob):
""" systematic re-sampling algorithm.
Note: objects with > 1/n probability (better than average) are guaranteed to occur atleast once.
see section 2.4 of 'Comparison of Resampling Schemes for Particle Filtering' by Douc et. al for more info.
"""
assert(n == len(prob))... | b4a170327b095c2d69d808a29dc75121b99b6964 | 44,410 |
def add_organization(authn):
"""Add organization."""
try:
post_data = request.get_json()
org_name = post_data['name']
primary_admin = User.from_uuid(authn.sub)
is_public = post_data.get('is_public', True)
except NoResultFound:
raise NotFound('User does not exist')
... | 2f8fc7b47b1772649ecc61e982b2f2fffeeda500 | 44,411 |
def _f_integrand(z, cosmo):
"""
Calculate the integrand for a given redshift and cosmology. This
the integrand for integral that appears in Zhang2018, Inoue2004
and Ioka2003.
Parameters
----------
z : float
The input redshift.
cosmo : An instance of :obj:`astropy.cosmology`
... | 4e344dca4260f830839a9f20c9f8bf7ec8989330 | 44,412 |
import jwt
import datetime
from result_linker.utils.rest_utilities import load_request_data
from result_linker.utils.svn_utils import get_revision_number
def link_to_ticket_from_redmine():
"""API to link the ticket with the repostiory data."""
if request.method == "POST":
data = load_request_data(requ... | ecfc11ed948e88ca12a57239e7d6df3f21b778ff | 44,413 |
def generate_type_handlers(model):
"""
Generates msg handlers for all messages except for dumps and requests (handled by vpp, not client).
:param model: meta-model of VPP API used for jVPP generation.
"""
type_handlers = []
for t in model.types:
if not isinstance(t, Class):
c... | b05bdb26a732900255d52c2a6f550a1802fef967 | 44,414 |
def ex9():
"""
Example 9
Breakable Activity
file name: Example9.py
Copyright Log Opt Co., Ltd.
Consider the same scenario as in Example 6.
Here, Activities can interrupt their processing and re-start after one unit of break time.
Find the optimal schedule (minimum tardiness solution) un... | eff77c2432f96a8c17b176aa9430f0610377d31e | 44,415 |
def _applySpecial_ColourMapOpts_negativeCmap(
args, overlayList, displayCtx, target):
"""Handles the :attr:`.ColourMapOpts.negativeCmap` option. See
:func:`_applyColourMap`.
"""
args.negativeCmap = _applyColourMap(
args.negativeCmap, overlayList, displayCtx)
return True | c2cbedf04402bdd183ab35c373240c32ba81d58b | 44,416 |
def concrete_head(expr, n=10):
""" Return head of computed expression """
if not expr._resources():
raise ValueError("Expression does not contain data resources")
if iscollection(expr.dshape):
head = expr.head(n + 1)
result = compute(head)
if not len(result):
ret... | b96417320441a4f3a1257aed9752a19131765bc8 | 44,417 |
def list():
"""Seznam cvičení"""
usr = getUser()
if request.params.get("activate"):
lec = Lecture.get( request.params.get("activate") )
lec.activate()
msg("Cvičení %s bylo zapnuto" % lec.name,"success")
redirect(request.path)
if request.params.get... | 28167e6e93b8d9fb720bce0a711ab480b9aced39 | 44,418 |
import torch
def load_snapshot(snapshot_file):
"""Load a training snapshot"""
print("--- Loading model from snapshot")
# Create network
norm_act = partial(InPlaceABN, activation="leaky_relu", slope=.01)
body = models.__dict__["net_wider_resnet38_a2"](norm_act=norm_act, dilation=(1, 2, 4, 4))
... | 980c291141387ba6490391f2f014802280ad5f7b | 44,419 |
def squash(x, axis=-1):
"""The Squashing Function.
The nonlinear activation function used in Capsule Network
# Arguments
x: Input Tensor.
axis: Integer axis along which the squashing function is to be applied.
# Returns
Tensor with scaled value of the input tensor
"""
s_... | 0812568db60940ffa4bdaf517f2ac54e0a7e1b06 | 44,420 |
import json
def update_user_chosen(request):
"""This view updates the team member: this is needed to see the ground truth of a specific user"""
request_body_json = json.loads(request.body)
user = request_body_json['user_chosen']
if user is not None:
request.session['team_member'] = user
... | 2c96338eb1e52d589efcc85a023697e4c9b9273f | 44,421 |
def encode(ds, is_implicit_vr, is_little_endian):
"""Encode a pydicom Dataset `ds` to bytes.
Parameters
----------
ds : pydicom.dataset.Dataset
The dataset to encode
is_implicit_vr : bool
The element encoding scheme the dataset will be encoded with.
is_little_endian : bool
... | 7765c5fb6ac649b421091081220d1035f7f427c4 | 44,422 |
import os
def process_alignment(data, alt_input=None):
"""Do an alignment of fastq files, preparing a sorted BAM output file.
"""
data = cwlutils.normalize_missing(utils.to_single_data(data))
data = cwlutils.unpack_tarballs(data, data)
fastq1, fastq2 = dd.get_input_sequence_files(data)
if alt_... | 82b1609d946c027456cde3bdb475826729f5ef6f | 44,423 |
import sys
import re
def listen_print_loop(responses):
# print(responses)
"""Iterates through server responses and prints them.
The responses passed is a generator that will block until a response
is provided by the server.
Each response may contain multiple results, and each result may con... | b606726f4ea6f98a44896b161cb9e8790f96b0bc | 44,424 |
import json
def tryJSON(response: Response) -> dict:
"""
Try to convert response data to JSON
"""
try:
response_data = response.json()
except json.decoder.JSONDecodeError:
raise PluginException(
cause="Received an unexpected response from Deep Security",
as... | 4fbd9e092cd983b468d4e97a3e9596c486dc653a | 44,425 |
def path_to_coords(svg_path: str, xtype: str = None) -> np.array:
"""From SVG path to numpy array of coordinates, each row being a (row, col) point"""
indices_str = [
pt.replace("M", "").replace("Z", "").replace("_", " ").split(",") for pt in svg_path.split("L")
]
if xtype == "datetime":
... | eb782543a602557129b732086e0f61272058c8d8 | 44,426 |
def insert(*data):
"""
Create an insert clause, e.g. `INSERT INTO ...`
Each value in *data* should be dictionary with key/values representing
columns/values. The format of this should be the same as in
:py:func:`.update`.
"""
return QueryBuilder().insert(*data) | 3a9645018e6f3c5773eceeba3b77be573fa5fd3d | 44,427 |
def get_default_gl_major_version():
""" Default GL major version """
return __gl_major_version__ | 16c7862da2d8172cc51180473d3be8093f9ccfcd | 44,428 |
def expandf(m, format): # noqa B002
"""Expand the string using the format replace pattern or function."""
if isinstance(format, (Replace, ReplaceTemplate)):
if not format.use_format:
raise ValueError("Replace not compiled as a format replace")
elif not isinstance(format, (compat.string... | 6fd5fee15e3e9a6cac6223564189dad352f64346 | 44,429 |
import time
def validate(val_loader, model, crf_criterion, vb_decoder):
"""
Performs one epoch's validation.
:param val_loader: DataLoader for validation data
:param model: model
:param crf_criterion: viterbi loss layer
:param vb_decoder: viterbi decoder
:return: validation F1 score
"... | fc71d1593a13f607e6ad2ce7087bb56c003b1da8 | 44,430 |
def base_context(request):
"""
`nav_category` gets a default value here, but you can override it by setting a `nav_category` property on the
`request` object to the value you want.
"""
user = request.user
following, following_truncated = [], []
if user.is_authenticated():
following ... | b4f128f6946b75e9b9f2b126eedd1ff52b5b288c | 44,431 |
def sort_box(box):
"""
对box排序,及页面进行排版
box[index, 0] = x1
box[index, 1] = y1
box[index, 2] = x2
box[index, 3] = y2
box[index, 4] = x3
box[index, 5] = y3
box[index, 6] = x4
box[index, 7] = y4
"""
box = sorted(box,key=lambda x:sum([x[1],x... | 41946a66cda6bce0371ca11c6c95890608115ab8 | 44,432 |
def get(proj_dir, key) :
"""return settings value by key, default value if the value
doesn't exist in the project-local settings file
:param proj_dir: absolute project directory
:param key: settings key
:returns: settings value, default value for key, or None
"""
util.e... | ade8ac3bac6e8f8889be09f6166078aca6818adf | 44,433 |
from typing import Union
def pair_correlation_neighbor_list(
displacement_or_metric: Union[DisplacementFn, MetricFn],
box_size: Box,
radii: Array,
sigma: float,
species: Array=None,
dr_threshold: float=0.5):
"""Computes the pair correlation function at a mesh of distances.
The pair correl... | b13485e4a11b78948058132040badca2b2b372ca | 44,434 |
import time, random
def generate_trade_id():
"""
采取一定规则生成一个11位的交易号
"""
trade_id = str(time.time())
trade_id = trade_id[:3] + str(random.randint(1000, 10000)) + trade_id[7:10] + trade_id[11]
return trade_id | 79a25817b5eaa0e18c46f419e0373e620d5d9b6f | 44,435 |
def area(spectra, energy, a, b):
"""
This function helps to determinate area under each photopeak through,
trapeziodal method.
Where:
spectra: net count rate vector
energy: energy vector
a: lower limit
b: upper limit
"""
spec = []
spec = spectra
spec = ... | 448cbdedacbfdd9ae16f30c42b942d4dd8925525 | 44,436 |
def get_task_app_id(task_id):
"""
Return the application id associated to the given task_id
:param task_id: Task id
:return: The associated application id associated to the given task id
"""
global fgapisrv_db
task_info = fgapisrv_db.get_task_info(task_id)
app_record = task_info.get('app... | 2dfeeecae810e12d6a306201dac75c5d203843e0 | 44,437 |
def create_tuple_1(t0_type_info: CLTypeInfo):
"""Returns CL type information for a byte array.
:param CLTypeInfo t0_type_info: Type information pertaining to first tuple element.
"""
return CLTypeInfoForTuple1(
typeof=CLType.TUPLE_1,
t0_type_info=t0_type_info
) | 4bf3781600bf3ddb6ebf1c4d61268c4ba5ed0e27 | 44,438 |
def request_path( request ):
"""
Get the path of the request
"""
return str(request.path) | 506672b635b6196aa032c7bed5b740c5a8d70c79 | 44,439 |
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 os
def executable_directory():
"""Always determine the directory of the executable, even when run with py2exe or otherwise frozen"""
executable = get_executable()
path = os.path.abspath(os.path.dirname(executable))
return path | 58c36b9f2cdddd69dc101de8eebb9af10a15d74f | 44,442 |
def rescale(x, y, coeff, mx, my):
"""
Rescale x y - axis.
Args:
x: (todo): write your description
y: (todo): write your description
coeff: (todo): write your description
mx: (todo): write your description
my: (todo): write your description
"""
# Bring the dat... | 0ebca0f73730a8fa1565266900544caab8df9fe2 | 44,443 |
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 |
import sys
def find(json, search_text):
"""
Takes a JSON string and a search string and output a list of
matching keys, values and text.
"""
assert isstr(json) or is_dict_or_list(json)
assert isstr(search_text)
if sys.version[0] == '2' and type(search_text) is str:
search_text = se... | 89d1ecbcd5a0b20b5bf64fd5c5832a3baf67f03e | 44,450 |
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 |
import os
def get_default_version_hostname():
"""Get the standard hostname of the default version of the app.
For example if your application_id is my-app then the result might be
my-app.appspot.com.
Returns:
The standard hostname of the default version of the application.
"""
return os.getenv(... | b23bf9786fa4209a66d6581d86b1d4e4de6c7a41 | 44,454 |
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 sys
def login(request, next_page=None, required=False):
"""Forwards to CAS login URL or verifies CAS ticket"""
service_url = get_service_url(request, next_page)
client = get_cas_client(service_url=service_url, request=request)
if not next_page and settings.CAS_STORE_NEXT and 'CASNEXT' in reque... | 092d02bd96f0e12f867967f7dfe76bde903f3d09 | 44,457 |
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 drop_corr_columns(dataframe: pd.DataFrame, drop_columns: bool = True,
print_columns: bool = True, threshold: float = 0.98) -> pd.DataFrame:
""" Correlated columns eliminator
The function drop correlated columns and keep only one of these columns. Usually removing high correlated colum... | a0f38b3d60c4f7caafd4b58181afb5d591f16e21 | 44,464 |
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 |
import os
import pickle
from datetime import datetime
import pandas
import scipy
def get_tsne_hazium_data(is_drawing=False, verbose=False):
"""
Get TSNE hazium data.
Get TSNE with hazium data. Save this with pickle format. Last modified: 2019-11-27T09:42:47+0900
Args:
is_drawing (bool): If i... | ad1f6ece2f7fe5cd17fe7b2d7f7e3262f7869dcd | 44,470 |
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 |
import subprocess
import shlex
def pipe_cmds(command1, command2):
"""
Pipe to commands together. Useful for things like `ps x | grep python`
Args:
command1 (str): The initial command to run
command2 (str): The command to receive stdout of command1
Returns:
list: Output of pipe... | 6774a2df5268e1fb81f2793154f2a602f198e94f | 44,496 |
def full_url(path):
"""
Return the full URL for the given path (eg. with scheme and domain)
"""
# Only in production
if settings.DEBUG:
return path
else:
return make_full_url(path) | 83f1d88632a30fda135f596f3b40e3eaad7c457f | 44,497 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.