content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def hrnetv2_w32(**kwargs):
"""
HRNetV2-W32 model from 'Deep High-Resolution Representation Learning for Visual Recognition,'
https://arxiv.org/abs/1908.07919.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, defaul... | 859642b2631457fd3fd8389370d2618666269ebe | 3,643,556 |
from .utils.globalcache import c
def medicare_program_engagement():
"""
Produces a wide dataset at the NPI level that shows when a provider entered
and exited the three different medicare databases: Part B, Part D, and
Physician Compare
"""
partd = part_d_files(summary=True,
... | 3a4bd0545473f229c8452680fc38c6ded2cb14bf | 3,643,557 |
def _is_bumf(value):
"""
Return true if this value is filler, en route to skipping over empty lines
:param value: value to check
:type value: object
:return: whether the value is filler
:rtype: bool
"""
if type(value) in (unicode, str):
return value.strip() == ''
return val... | 1812e82036ed4bdbdee4e2e032886ac2c788a5ff | 3,643,558 |
from .perceptron import tag as tag_
from artagger import Tagger
from .unigram import tag as tag_
def pos_tag(words, engine="unigram", corpus="orchid"):
"""
Part of Speech tagging function.
:param list words: a list of tokenized words
:param str engine:
* unigram - unigram tagger (default)
... | 8c8328950fba9082220d9c6be3b9fc8f9e6c3332 | 3,643,559 |
import warnings
def derive(control):
"""
gui.derive will be removed after mGui 2.2; for now it's going to issue a deprecation warning and call `wrap()`
"""
warnings.warn("gui.derive() should be replaced by gui.wrap()", PendingDeprecationWarning)
return wrap(control) | a2f463c9a66425e5066c504803b5754c2260cbc9 | 3,643,560 |
import base64
def hex_to_base64(hex_):
""" Converts hex string to base64 """
return base64.b64encode(bytes.fromhex(hex_)) | 26f42b25c9e804bc1b786aadab033db104882f4b | 3,643,561 |
def dt2iso(orig_dt):
"""datetime to is8601 format."""
return timeutils.isotime(orig_dt) | 9887db04c4b3703a4f0c43c874c8d907cc744ea5 | 3,643,562 |
def catalog(access_token, user_id, query=None): # noqa: E501
"""Query the list of all the RDF graphs' names (URIs) and the response will be JSON format.
# noqa: E501
:param access_token: Authorization access token string
:type access_token: dict | bytes
:param user_id: the ID of the organiz... | f3819e76be5a1559f60140542d151de1f1b50b0e | 3,643,563 |
import json
def _make_chrome_policy_json():
"""Generates the json string of chrome policy based on values in the db.
This policy string has the following form:
{
"validProxyServers": {"Value": map_of_proxy_server_ips_to_public_key},
"enforceProxyServerValidity": {"Value": boolean}
}
Returns:
... | 629450bc9bb0c2c0ce61b25568a4689b20c89766 | 3,643,564 |
def get_rgb_color(party_id):
"""Get RGB color of party."""
if party_id not in PARTY_TO_COLOR_OR_PARTY:
return UNKNOWN_PARTY_COLOR
color_or_party = PARTY_TO_COLOR_OR_PARTY[party_id]
if isinstance(color_or_party, tuple):
return color_or_party
return get_rgb_color(color_or_party) | 18585d46551e1a1646e28d4371d68537e94975ac | 3,643,565 |
from datetime import datetime
def view_application(application_id):
"""Views an application with ID.
Args:
application_id (int): ID of the application.
Returns:
str: redirect to the appropriate url.
"""
# Get user application.
application = ApplicationModel.query.filter_by(i... | dda04250b45a1a166c254b48039155e85ca62ea3 | 3,643,566 |
import logging
def build_save_containers(platforms, bucket) -> int:
"""
Entry point to build and upload all built dockerimages in parallel
:param platforms: List of platforms
:param bucket: S3 bucket name
:return: 1 if error occurred, 0 otherwise
"""
if len(platforms) == 0:
return ... | 9744577efabbd800c16e9c7f57c9c7b31654cec1 | 3,643,567 |
def get_object_record(obj_key):
"""
Query the object's record.
Args:
obj_key: (string) The key of the object.
Returns:
The object's data record.
"""
record = None
model_names = OBJECT_KEY_HANDLER.get_models(obj_key)
for model_name in model_names:
try:
... | c32bd3f12babc4f7c30567d6f2529dd037e3e563 | 3,643,568 |
def diff_cars(c1, c2):
"""
diffs two cars
returns a DiffSet containing DiffItems that tell what's missing in c1
as compared to c2
:param c1: old Booking object
:param c2: new Booking object
:return: DiffSet (c1-c2)
"""
strategy = Differ.get_strategy(CAR_DIFF_STRATEGY)
return str... | fda0e12bea0fd70fbed1a0e2c445941dc44f8cb7 | 3,643,569 |
import json
def main(request, response):
"""Helper handler for Beacon tests.
It handles two forms of requests:
STORE:
A URL with a query string of the form 'cmd=store&sid=<token>&tidx=<test_index>&tid=<test_name>'.
Stores the receipt of a sendBeacon() request along with its validation r... | 5d970bb10d689bb55f70cd841bd01501d88428c7 | 3,643,571 |
def calc_chi2(model, dof=None):
"""
Calculate chi-square statistic.
Parameters
----------
model : Model
Model.
dof : int, optional
Degrees of freedom statistic. The default is None.
Returns
-------
tuple
chi2 statistic and p-value.
"""
if dof is Non... | 46ed27fca1f36fdc8a044136da1ea4a032be1554 | 3,643,572 |
def QuadraticCommandAddControl(builder, control):
"""This method is deprecated. Please switch to AddControl."""
return AddControl(builder, control) | 9b775f34400a0deeea93fd58a211915462735fed | 3,643,573 |
def authenticated_api(username, api_root=None, parser=None):
"""Return an oauthenticated tweety API object."""
auth = tweepy.OAuthHandler(settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET)
try:
user = User.objects.get(username__iexact=username)
sa... | 82237d40b89ad860720ae3830fa37de76439a2be | 3,643,574 |
def get_model_header(fpath):
"""
:param fpath:
:return:
"""
with gz.open(fpath, 'rt') as modelfile:
header = modelfile.readline().strip().strip('#').split()
return header | bd3600d831d212821c160b994ea73c24ee04ce6d | 3,643,575 |
def clean_tag(tag):
"""clean up tag."""
if tag is None:
return None
t = tag
if isinstance(t, list):
t = t[0]
if isinstance(t, tuple):
t = t[0]
if t.startswith('#'):
t = t[1:]
t = t.strip()
t = t.upper()
t = t.replace('O', '0')
t = t.replace('B', '8... | 1d2709323c4d80f290701d5cdc3a993b4bac25d4 | 3,643,577 |
def massM2(param):
""" Mass term in the neutrino mass basis.
@type param : PhysicsConstants
@param param : set of physical parameters to be used.
@rtype : numpy array
@return : mass matrix in mass basis.
"""
M2 = np.zeros([param.numneu,param.numneu],complex)... | 38997454d308b4730e4eac5a764977fc72a6b373 | 3,643,578 |
import json
def get_input_data(train_file_path='train.json', train=True):
"""Retrieves training (X) and label (y) matrices. Note that this can take a few seconds to run.
Args:
train_file_path is the path of the file containing training data.
Returns:
A tuple containing the X training mat... | 5b42339917f0ec97ae584a03ba415881221e639c | 3,643,579 |
def dice_coef(y_true, y_pred):
"""
:param y_true: the labeled mask corresponding to a mammogram scan
:param y_pred: the predicted mask of the scan
:return: A metric that accounts for precision and recall
on the scale from 0 - 1. The closer to 1, the
better.
Dice = 2 * (... | e0f24abe29771f384e640e9e2f2420add040492f | 3,643,580 |
def linmsg(x, end_pts_msg=None, max_msg=None, fill_value=1.e20):
"""
Linearly interpolates to fill in missing values.
x = Ngl.linmsg(x,end_pts_msg=None,max_msg=None,fill_value=1.e20)
x -- A numpy or masked array of any dimensionality that contains missing values.
end_pts_msg -- how missing beginning and end points... | 342abdc7536d8a1866c156cdc238e06338a20398 | 3,643,581 |
def get_or_create_actor_by_name(name):
"""
Return the actor corresponding to name if it does not exist,
otherwise create actor with name.
:param name: String
"""
return ta.ActorSystem().createActor(MyClass, globalName=name) | cc1ad620bc29139d6230e5a134ff72c3639a2bb1 | 3,643,582 |
def client():
"""Client to call tests against"""
options = {
'bind': '%s:%s' % ('0.0.0.0', '8080'),
'workers': str(number_of_workers()),
}
return testing.TestClient(falcon.API(), options) | 3c075eb528e88a51a8f2c13e1197da6b2831197a | 3,643,583 |
import math
def hard_negative_mining(loss, labels, neg_pos_ratio=3):
"""
用于训练过程中正负例比例的限制.默认在训练时,负例数量是正例数量的三倍
Args:
loss (N, num_priors): the loss for each example.
labels (N, num_priors): the labels.
neg_pos_ratio: 正负例比例: 负例数量/正例数量
"""
pos_mask = labels > 0
num_pos = p... | 3b2e38ab2b0bbd9732fceafdfd023ea220b3c5eb | 3,643,584 |
def groups():
"""
Return groups
"""
return _clist(getAddressBook().groups()) | 16db4befa0863b15055fd7b557ecfefa8da55e20 | 3,643,585 |
def round_temp(value):
"""Round temperature for publishing."""
return round(value, dev_fan.round_temp) | 39f7d5e55d0ba444b675b8ae612f5f38350af050 | 3,643,586 |
def get_key_from_property(prop, key, css_dict=None, include_commented=False):
"""Returns the entry from the dictionary using the given key"""
if css_dict is None:
css_dict = get_css_dict()[0]
cur = css_dict.get(prop) or css_dict.get(prop[1:-1])
if cur is None:
return None
value = cu... | 169a4369a8fc5cc9cfde18b302a308bafa1d4def | 3,643,587 |
def bbox_area(gt_boxes):
"""
gt_boxes: (K, 4) ndarray of float
area: (k)
"""
K = gt_boxes.size(0)
gt_boxes_area = ((gt_boxes[:,2] - gt_boxes[:,0] + 1) *
(gt_boxes[:,3] - gt_boxes[:,1] + 1)).view(K)
return gt_boxes_area | 57ad16b8b339e4515dcd7e7126b9c6b35b6c3d8b | 3,643,588 |
def DecodedMessage(tG,x):
"""
Let G be a coding matrix. tG its transposed matrix. x a n-vector received after decoding.
DecodedMessage Solves the equation on k-bits message v: x = v.G => G'v'= x' by applying GaussElimination on G'.
-------------------------------------
Parameters:
... | 47968c4feed23a32abbbf34da1bed4521689f3d2 | 3,643,589 |
def get_ttp_card_info(ttp_number):
"""
Get information from the specified transport card number.
The number is the concatenation of the last 3 numbers of the first row and all the numbers of the second row.
See this image: https://tarjetatransportepublico.crtm.es/CRTM-ABONOS/archivos/img/TTP.jpg
:... | fc8fb31ae5daf17173567d53a9a122c3d8e11ca5 | 3,643,590 |
import re
def tag_matches(tag, impl_version='trunk', client_version='trunk'):
"""Test if specified versions match the tag.
Args:
tag: skew test expectation tag, e.g. 'impl_lte_5' or 'client_lte_2'.
impl_version: WebLayer implementation version number or 'trunk'.
client_version: WebLayer implementatio... | dab3494063cd382615648d12d5dae03a47963af6 | 3,643,591 |
def load_suites_from_directory(dir, recursive=True):
# type: (str, bool) -> List[Suite]
"""
Load a list of suites from a directory.
If the recursive argument is set to True, sub suites will be searched in a directory named
from the suite module: if the suite module is "foo.py" then the sub suites ... | 5bb0c83ee39537b0bb38a663b110f5ef6225833e | 3,643,593 |
def deep_parameters_back(param, back_node, function_params, count, file_path, lineno=0, vul_function=None,
isback=False):
"""
深层递归分析外层逻辑,主要是部分初始化条件和新递归的确定
:param isback:
:param lineno:
:param vul_function:
:param param:
:param back_node:
:param function_para... | 5cc5669a3c071d14b5d4898f60315da27e397a8b | 3,643,594 |
from typing import Optional
import re
def get_latest_runtime(dotnet_dir: Optional[str] = None, version_major: Optional[int] = 5,
version_minor: Optional[int] = 0, version_build: Optional[int] = 0) -> Optional[str]:
"""
Search and select the latest installed .NET Core runtime directory.
... | 46db4e55163e6110d48264ed5ad4394662ade336 | 3,643,595 |
def choose_action(state, mdp_data):
"""
Choose the next action (0 or 1) that is optimal according to your current
mdp_data. When there is no optimal action, return a random action.
Args:
state: The current state in the MDP
mdp_data: The parameters for your MDP. See initialize_mdp_data.
... | 2cb1f50a62ec006367fb61d8e57eb95005670e31 | 3,643,596 |
import inspect
def specialize_on(names, maxsize=None):
"""
A decorator that wraps a function, partially evaluating it with the parameters
defined by ``names`` (can be a string or an iterable of strings) being fixed.
The partially evaluated versions are cached based on the values of these parameters
... | 218cb169661507124acf1dae8076fa47eb313f1a | 3,643,598 |
def parse_docstring(docstring: str, signature) -> str:
"""
Parse a docstring!
Note:
to try notes.
Args:
docstring: this is the docstring to parse.
Raises:
OSError: no it doesn't lol.
Returns:
markdown: the docstring converted to a nice markdown text.
"""
... | f831cda6046853312f6b0afe28683d3fc81dc874 | 3,643,599 |
def get_rgeo(coordinates):
"""Geocode specified coordinates
:argument coordinates: address coordinates
:type coordinates: tuple
:returns tuple
"""
params = {'language': GEOCODING_LANGUAGE,
'latlng': ','.join([str(crdnt) for crdnt in coordinates])}
result = get(url=GEOCODING... | ca8d07f526260d48955dee1b32d18bf14b21f9f6 | 3,643,600 |
def norm_lib_size_log(assay, counts: daskarr) -> daskarr:
"""
Performs library size normalization and then transforms the
values into log scale.
Args:
assay: An instance of the assay object
counts: A dask array with raw counts data
Returns: A dask array (delayed matrix) containing ... | 3fdcde36daa3c3c491c3b85f718d75e6276af8fa | 3,643,601 |
def compare_dicts(cloud1, cloud2):
"""
Compare the dicts containing cloud images or flavours
"""
if len(cloud1) != len(cloud2):
return False
for item in cloud1:
if item in cloud2:
if cloud1[item] != cloud2[item]:
return False
else:
ret... | 4c13ed92da2cd40b543b75fac119b5da302717e3 | 3,643,602 |
import json
def ajax_stats():
"""
获取客户统计
:return:
"""
time_based = request.args.get('time_based', 'hour')
result_customer_middleman = customer_middleman_stats(time_based)
result_customer_end_user = customer_end_user_stats(time_based)
line_chart_data = {
'labels': [label for la... | a467bd656535695333030ded34ccb299d57c8ef7 | 3,643,603 |
import string
def str2int(string_with_int):
""" Collect digits from a string """
return int("".join([char for char in string_with_int if char in string.digits]) or 0) | 86955812fa3b2e6af0b98a04a1516897ccf95c25 | 3,643,604 |
def grid_to_3d(reward: np.ndarray) -> np.ndarray:
"""Convert gridworld state-only reward R[i,j] to 3D reward R[s,a,s']."""
assert reward.ndim == 2
reward = reward.flatten()
ns = reward.shape[0]
return state_to_3d(reward, ns, 5) | f848900b3b9ba7eb94fc1539fb1b24107e3db551 | 3,643,605 |
def find_routes(paths) -> list:
"""returns routes as tuple from path as list\
like 1,2,3 --> (1,2)(2,3)"""
routes = []
for path in paths:
for i in range(len(path)):
try:
route = (path[i], path[i + 1])
if route not in routes:
r... | 67fb8eb575dd45879f5e5b465a7886f2a2387b26 | 3,643,606 |
def z_step_ncg_hess_(Z, v, Y, F, phi, C_Z, eta_Z):
"""A wrapper of the hess-vector product for ncg calls."""
return z_step_tron_hess(v, Y, F, phi, C_Z, eta_Z) | 2c6e800040e5090333cbba0924985bf7fe17c873 | 3,643,607 |
def list_servers(**kwargs) -> "list[NovaServer]":
"""List all servers under the current project.
Args:
kwargs: Keyword arguments, which will be passed to
:func:`novaclient.v2.servers.list`. For example, to filter by
instance name, provide ``search_opts={'name': 'my-instance'}``
... | 3e12a6e24687e74942cc86bc616d57ebdb5a6521 | 3,643,608 |
from typing import Optional
from typing import cast
def resolve_xref(
app: Sphinx,
env: BuildEnvironment,
node: nodes.Node,
contnode: nodes.Node,
) -> Optional[nodes.reference]:
"""
Resolve as-yet-unresolved XRefs for :rst:role:`tconf` roles.
:param app: The Sphinx application.
:param env: The Sphinx b... | d4bc46765de1e892aa6753678fab5ad2ff693f68 | 3,643,609 |
def deploy_tester_contract(
web3,
contracts_manager,
deploy_contract,
contract_deployer_address,
get_random_address,
):
"""Returns a function that can be used to deploy a named contract,
using conract manager to compile the bytecode and get the ABI"""
def f(contract_n... | ee925e9632f3bfd66a843d336bd287c92543b2ed | 3,643,610 |
def make_hashable_params(params):
"""
Checks to make sure that the parameters submitted is hashable.
Args:
params(dict):
Returns:
"""
tuple_params = []
for key, value in params.items():
if isinstance(value, dict):
dict_tuple = tuple([(key2, value2) for key2, ... | 39d5de594b8caf776d2732e0e58b1c11127e5047 | 3,643,611 |
def check_member_role(member: discord.Member, role_id: int) -> bool:
"""
Checks if the Member has the Role
"""
return any(role.id == role_id for role in member.roles) | 500c9c33dd0e25a6a4704165add3d39c05d510d2 | 3,643,612 |
import itertools
def tag_bedpe(b, beds, verbose=False):
"""
Tag each end of a BEDPE with a set of (possibly many) query BED files.
For example, given a BEDPE of interacting fragments from a Hi-C experiment,
identify the contacts between promoters and ChIP-seq peaks. In this case,
promoters and Ch... | a1b95e04abd9401a6494fad2c2b6d48ecb14d414 | 3,643,613 |
from typing import Tuple
def point(x: float, y: float, z: float) -> Tuple:
"""Create a point."""
return Tuple(x, y, z, 1.0) | 035f01d990d16634867b147b7fcb7e9d5edf7f92 | 3,643,614 |
def partial_pipeline_data(backend, user=None, *args, **kwargs): # pragma: no cover
"""
Add the session key to a signed base64 encoded signature on the email request.
"""
data = backend.strategy.request_data()
if 'signature' in data:
try:
signed_details = signing.loads(data['sign... | 54c0124b49fead91fed238ded15f6c3167f0aed4 | 3,643,615 |
def arrayinv(F, Fx):
"""
Args:
F: dx.ds function value at x
Fx: dx.dx.ds derivative of function at x
Returns:
"""
return np.array([np.linalg.solve(a, b) for a, b in zip(Fx.swapaxes(0,2), F.T)]).T | ac412bf0cb03a77d0a18295b899aeabd8bcdbfb3 | 3,643,616 |
def mil(val):
"""convert mil to mm"""
return float(val) * 0.0254 | 9071b0116a7062ef93d6bee56a08db2b9bec906a | 3,643,618 |
def ask_number(question, low, high):
"""Poproś o podanie liczby z określonego zakresu."""
response = None
while type(response) != int:
try:
response = int(input(question))
while response not in range(low, high):
response = int(input(question))
except V... | fdae37e6a0cd34d36b647a23f4a0f58cad46680a | 3,643,619 |
import numpy
from typing import Tuple
import math
def _beams_longitude_latitude(
ping_header: PingHeader, along_track: numpy.ndarray, across_track: numpy.ndarray
) -> Tuple[numpy.ndarray, numpy.ndarray]:
"""
Calculate the longitude and latitude for each beam.
https://en.wikipedia.org/wiki/Geographic_... | c43171830206c5db878a817a03a4830aae878765 | 3,643,621 |
def true_range_nb(high: tp.Array2d, low: tp.Array2d, close: tp.Array2d) -> tp.Array2d:
"""Calculate true range."""
prev_close = generic_nb.fshift_nb(close, 1)
tr1 = high - low
tr2 = np.abs(high - prev_close)
tr3 = np.abs(low - prev_close)
tr = np.empty(prev_close.shape, dtype=np.float_)
for ... | 7b7594a1a5adf4e280a53af3e01d9aec5bd3b80c | 3,643,622 |
def laplacian_operator(data):
"""
apply laplacian operator on data
"""
lap = []
lap.append(0.0)
for index in range(1, len(data) - 1):
lap.append((data[index + 1] + data[index - 1]) / 2.0 - data[index])
lap.append(0.0)
return lap | 3d7755cdc52352cc445d5942e34c09f65f3e11db | 3,643,623 |
def _stringmatcher(pattern):
"""
accepts a string, possibly starting with 're:' or 'literal:' prefix.
returns the matcher name, pattern, and matcher function.
missing or unknown prefixes are treated as literal matches.
helper for tests:
>>> def test(pattern, *tests):
... kind, pattern, ... | 76a673133aaf7493b531b4f73364af2d16dd214b | 3,643,624 |
def enu_to_ecef(ref_lat_rad, ref_lon_rad, ref_alt_m, e_m, n_m, u_m):
"""Convert ENU coordinates relative to reference location to ECEF coordinates.
This converts local east-north-up (ENU) coordinates relative to a given
reference position to earth-centered, earth-fixed (ECEF) cartesian
coordinates. The... | a6a7e8e3a67a17894d68d6c62b2ac7fcef7a09ec | 3,643,625 |
import re
import requests
def is_file_url(share_url: str) -> bool:
"""判断是否为文件的分享链接"""
base_pat = r'https?://[a-zA-Z0-9-]*?\.?lanzou[a-z].com/.+' # 子域名可个性化设置或者不存在
user_pat = r'https?://[a-zA-Z0-9-]*?\.?lanzou[a-z].com/i[a-zA-Z0-9]{5,}/?' # 普通用户 URL 规则
if not re.fullmatch(base_pat, share_url):
... | d9b56a2187cedeb79cb848192b544026a5d85e29 | 3,643,626 |
def get_compton_fraction_artis(energy):
"""Gets the Compton scattering/absorption fraction
and angle following the scheme in ARTIS
Parameters
----------
energy : float
Energy of the gamma-ray
Returns
-------
float
Scattering angle
float
Compton scattering fr... | 2121712c542c967ef7008a4bdf8b88a8e2bcdb6c | 3,643,627 |
def is_argspec_compatible_with_types(argspec, *args, **kwargs):
"""Determines if functions matching 'argspec' accept given 'args'/'kwargs'.
Args:
argspec: An instance of inspect.ArgSpec to verify agains the arguments.
*args: Zero or more positional arguments, all of which must be instances of
computa... | 5103fa00737f4faeda49441f9d67388f34599d09 | 3,643,628 |
def get_span_feats_stopwords(stopwords):
"""Get a span dependency tree unary function"""
return partial(get_span_feats, stopwords=stopwords) | 86fd8c597f39f71c489665c05d164e0a3e1e69c0 | 3,643,629 |
def get_argument_parser(argparser):
"""Augments the given ArgumentParser for use with the Bonobo ETL framework."""
return bonobo.get_argument_parser(parser=argparser) | 584fc867660f85998a679d1883828ea7a8c3896f | 3,643,630 |
from pathlib import Path
def input_file_path(directory: str, file_name: str) -> Path:
"""Given the string paths to the result directory, and the input file
return the path to the file.
1. check if the input_file is an absolute path, and if so, return that.
2. if the input_file is a relative path, co... | dd866a5f8b6f776238269844d64686f7fb28347c | 3,643,631 |
def loss(S, K, n_samples=None):
"""Loss function for time-varying graphical lasso."""
if n_samples is None:
n_samples = np.ones(S.shape[0])
return sum(
-ni * logl(emp_cov, precision)
for emp_cov, precision, ni in zip(S, K, n_samples)) | 07ad436bf5aee5e8b1dc53e89b894c4c8883cedd | 3,643,632 |
def flat_dict(df):
"""
Add each key-value of a nested dictionary that is saved in a dataframe, as a new column
"""
for col in df.columns:
if type(df[col][0]) == dict:
df = pd.concat(
[df.drop([col], axis=1), df[col].apply(pd.Series)], axis=1)
# sometim... | ec817b9c7a08aab95bb29981dafbb1f1e03821eb | 3,643,633 |
from typing import List
async def run_setup_pys(
targets_with_origins: TargetsWithOrigins,
setup_py_subsystem: SetupPySubsystem,
console: Console,
python_setup: PythonSetup,
distdir: DistDir,
workspace: Workspace,
union_membership: UnionMembership,
) -> SetupPy:
"""Run setup.py command... | 713f0b7f3558e2a69dcca0a7a251f4991ee49073 | 3,643,634 |
def list_tasks():
"""
显示所有任务列表,方便管理任务
:return:
"""
try:
task_id = request.args.get("task_id")
task_status = request.args.get('status')
# 构造条件查询元组
task_info_list = list()
tasks = TaskService.get_tasks_url_num(task_id=task_id, task_status=task_status)
f... | c6d205e95bd7a1a2e76baf7f89c917310b683bc0 | 3,643,635 |
import itertools
import torch
def make_fixed_size(
protein,
shape_schema,
msa_cluster_size,
extra_msa_size,
num_res=0,
num_templates=0,
):
"""Guess at the MSA and sequence dimension to make fixed size."""
pad_size_map = {
NUM_RES: num_res,
NUM_MSA_SEQ: msa_cluster_size,... | 1125e1cdbe8f12d6613fb8dd9374afdbf1fd065a | 3,643,636 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_urlhaus package"""
reload_params = {"package": u"fn_urlhaus",
"incident_fields": [],
"action_fields": [],
"function_params": [u"urlhaus_artifact_type", u"urlhaus_artifact_val... | 1665121ab3305f517242b122e2aaae2b12fe57f0 | 3,643,637 |
def urls(page, baseurl=auto, direct=True, prev=True, next=True):
"""
Return a list of pagination URLs extracted form the page.
When baseurl is None relative URLs are returned; pass baseurl
to get absolute URLs.
``prev``, ``next`` and ``direct`` arguments control whether to return
'next page', '... | 70f0337b5ed1a1cd8c0cfd1f99f8ad67da85b23d | 3,643,638 |
def sinc_filter(audio: tf.Tensor,
cutoff_frequency: tf.Tensor,
window_size: int = 512,
sample_rate: int = None,
padding: Text = 'same') -> tf.Tensor:
"""Filter audio with sinc low-pass filter.
Args:
audio: Input audio. Tensor of shape [batch, audi... | ea13a320744bb380b20643c2a995be67fc9d1303 | 3,643,639 |
def _getDataFlows(blocks):
"""
Given a block dictonary from bifrost.proclog.load_by_pid(), return a list
of chains that give the data flow.
"""
# Find out what rings we have to work with and which blocks are sources
# or sinks
rings = []
sources, sourceRings = [], []
sinks, sinkRin... | 197cc64b5bf7ecd8e5c7d912239c93a1feffcd14 | 3,643,640 |
def find_lowest_cost_node(costs: dict, processed: list) -> dict:
"""Return the node with the lowest cost"""
lowest_cost = float("inf") # Infinity
lowest_cost_node = None
for node in costs:
cost = costs[node]
if cost < lowest_cost and node not in ... | aeb0ef046619bc9280d3d712329c672f76e36c90 | 3,643,641 |
def scale_img(image, random_coordinate=False):
"""
对原图大小进行处理,
:param image:
:param random_coordinate:
:return:
"""
h, w, c = image.shape
if max(h, w) > 640:
f_scale = min(640./h, 640./w) # scale factor
image = cv2.resize(src=image, dsize=None, fx=f_scale, fy=f_scale, in... | 6a0b93f4564c6d83e60f6f7a250822f801e0b65b | 3,643,642 |
import math
def magnitude(v: Vector) -> float:
"""computes the magnitude (length) of a vector"""
return math.sqrt(sum_of_squares(v)) | 881f2a3e75520b3f8da7ea093765e36d78e48c57 | 3,643,643 |
import time
def supply_domes1finesk():
"""
Real Name: b'"Supply Domes-1Finesk"'
Original Eqn: b'MIN("Domes-1 Demad finesk" (Time), (outflow Finesk) )'
Units: b'MCM/Month'
Limits: (None, None)
Type: component
b''
"""
return np.minimum(domes1_demad_finesk(time()), (outflow_finesk())... | e7bbbdc49e45044179053a02c4b76c1dda798bc0 | 3,643,646 |
def poll(handle):
"""
Polls an push_pull handle to determine whether underlying
asynchronous operation has completed. After `poll()` returns `True`, `synchronize()`
will return without blocking.
Arguments:
handle: A handle returned by an push_pull asynchronous
operation.
... | e228183068517962e7886c020e662b8c1a1f2912 | 3,643,647 |
from typing import Tuple
def _increase_explicit_hydrogen_for_bond_atom(
rwmol: Chem.rdchem.RWMol,
remove_bidx: bool,
bidx: int,
remove_eidx: bool,
eidx: int,
ai_to_remove: list,
) -> Tuple[Chem.rdchem.RWMol, list]:
"""Increase number of explicit hydrogens for atom in a bond.
Args:
... | cf0276730ee0837d43098f9712f7c199ba93b268 | 3,643,648 |
def plot_historical_actuals_forecast(e, title=None, ylabel='',
include_pred_int=False,
years_prior_include=2,
forecast_display_start=None,
e2=None):
"""Produce a plot of... | e6604fe35ce6a65ff61ee45a387167d019be867a | 3,643,650 |
import time
import threading
def f2(a, b):
"""
concurrent_num = 600 不用怕,因为这是智能线程池,如果函数耗时短,不会真开那么多线程。
这个例子是测试函数耗时是动态变化的,这样就不可能通过提前设置参数预估函数固定耗时和搞鬼了。看看能不能实现qps稳定和线程池自动扩大自动缩小
要说明的是打印的线程数量也包含了框架启动时候几个其他的线程,所以数量不是刚好和所需的线程计算一样的。
## 可以在运行控制台搜索 新启动线程 这个关键字,看看是不是何时适合扩大线程数量。
## 可以在运行控制台搜索 停止线程 这个关键字,看... | 4f555d2b684e06d171a821fde6c10d2a72596396 | 3,643,651 |
def minimize_loss_single_machine_manual(loss,
accuracy,
layer_collection,
device=None,
session_config=None):
"""Minimize loss with K-FAC on a single machine(I... | c5f53d7eddabe3ea5ac30ae4ecc050ee43ffa5e7 | 3,643,652 |
def bass_call_0(function, *args):
"""Makes a call to bass and raises an exception if it fails. Does not consider 0 an error."""
res = function(*args)
if res == -1:
code = BASS_ErrorGetCode()
raise BassError(code, get_error_description(code))
return res | 9355f12b7277914e2397c64103666be0f5b801e5 | 3,643,653 |
def port_speed(value : str | None = None) -> int | None:
"""Port speed -> Mb/s parcer"""
if value is None:
return None
elif value == "X":
return 0
elif value == "M":
return 100
elif value == "G":
return 1000
elif value == "Q":
return 2500
else:
... | 2bb41bf66211724a12bdf392ecf018c71836f42b | 3,643,654 |
def convert_flag_frame_to_strings(flag_frame, sep=', ', empty='OK'):
"""
Convert the `flag_frame` output of :py:func:`~convert_mask_into_dataframe`
into a pandas.Series of strings which are the active flag names separated
by `sep`. Any row where all columns are false will have a value of `empty`.
P... | fa7f0cc427e4b6e4c703ea2011af59f1bad090ab | 3,643,655 |
def pp_file_to_dataframe(pp_filename):
""" read a pilot point file to a pandas Dataframe
Parameters
----------
pp_filename : str
pilot point file
Returns
-------
df : pandas.DataFrame
a dataframe with pp_utils.PP_NAMES for columns
"""
df = pd.read_csv(pp_filename... | 777272db75f0e6c7bd1eee0b24d4879bf2ceb66a | 3,643,656 |
def edit_product(request, product_id):
""" Edit a product in the store """
if not request.user.is_superuser:
messages.error(request, 'Sorry, only store owners can do that.')
return redirect(reverse('home'))
product = get_object_or_404(Product, pk=product_id)
if request.method == 'POST':... | 0f22ca856ca71e973bd8eed85bba7f54ce3a3464 | 3,643,658 |
def _resolve_target(target, target_frame='icrs'):
"""Return an `astropy.coordinates.SkyCoord` form `target` and its frame."""
if target_frame == 'icrs':
return parse_coordinates(target)
return SkyCoord(target, frame=target_frame) | b2b8132ca15b6bcfbb6d67c90abf36760be6a2d1 | 3,643,659 |
import itertools
def iter_fragments(fragiter, start_frag_id = None, stop_frag_id = None):
"""Given a fragment iterator and a start and end fragment id,
return an iterator which yields only fragments within the range.
"""
if start_frag_id and stop_frag_id:
dpred = lambda f: fragment_id_lt(f.fra... | a1ab1245a6cb450cdb363a7029147501adf913db | 3,643,660 |
from bst import BST
def bst_right_imbalanced():
"""Bst that extends right."""
test_bst = BST((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
return test_bst | 4cdb45770634c389831057832b33755fe0a8db23 | 3,643,662 |
import time
def retry(exception_to_check, tries=4, delay=0.5, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff.
Args:
exception_to_check (Exception): the exception to check.
may be a tuple of exceptions to check
... | 8e607104abf1cd5165199b7792f6955084e674cd | 3,643,663 |
def HESSIAN_DIAG(fn):
"""Generates a function which computes per-argument partial Hessians."""
def h_fn(*args, **kwargs):
args = (args,) if not isinstance(args, (tuple, list)) else tuple(args)
ret = [
jaxm.hessian(
lambda arg: fn(*args[:i], arg, *args[i + 1 :], **kwa... | 01075519f7c3ae052a553bd3911e0447fa8da6ce | 3,643,664 |
from scipy.spatial import cKDTree
import numpy
def match_xy(x1, y1, x2, y2, neighbors=1):
"""Match x1 & y1 to x2 & y2, neighbors nearest neighbors.
Finds the neighbors nearest neighbors to each point in x2, y2 among
all x1, y1."""
vec1 = numpy.array([x1, y1]).T
vec2 = numpy.array([x2, y2]).T
... | cd360ee6fc0ec83fad565313f6cbb0e8a4292ca2 | 3,643,665 |
def make_doc():
""" Only used for sphinx documentation """
doc_app = Flask(__name__)
doc_app.register_blueprint(blueprint())
return doc_app | beff9149ceffb04f80071f6a595ef13e72ebc838 | 3,643,666 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.