content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from datetime import datetime
def read_gml_ozone(filename=None, **kwargs):
"""
Function to read carbon dioxide data from NOAA GML.
Parameters
----------
filename : str or pathlib.Path
Data file full path name.
**kwargs : keywords
Keywords to pass through to ACT read_csv() rout... | 457cfbf38a9e074d4c84d98af8993cdb5058c13f | 3,598,479 |
def test_fallback_round_with_x_tuple_n_default():
"""
Feature: JIT Fallback
Description: Test sum() in graph mode with input x tuple and input n default.
Expectation: No exception.
"""
@ms_function
def foo():
x = sum((1, 2, 3))
return x
out = foo()
assert out == 6 | 7e94a68322aa8fbfd4efaefa4f282a66d0e1972c | 3,598,480 |
def degree_matrix(adjacency, rtype='array'):
"""Creates a matrix representing vertex degrees.
Parameters
----------
adjacency : list
List of lists, vertex adjacency data.
rtype : {'array', 'csc', 'csr', 'coo', 'list'}
Format of the result.
Returns
-------
array-like
... | 622bd1cda4f77a0a6006189826d3d871365338a7 | 3,598,481 |
import json
import math
def extend_django_sqlite():
"""给 django sqlite 补上一些基础函数"""
def float_max(value_x, value_y):
return float(max(float(value_x), float(value_y)))
def json_contains(column_value, value):
return json.loads(value) in json.loads(column_value)
def json_extract(value, ... | 3ffc1c098b62c4acbe3534db70cabc66959cd421 | 3,598,482 |
from typing import Dict
def get_node_type_counts(plc: plc_client.PlacementCost) -> Dict[Text, int]:
"""Returns number of each type of nodes in the netlist.
Args:
plc: the placement cost object.
Returns:
Number of each type of node in a dict.
"""
counts = {
'MACRO': 0,
'STDCELL': 0,
... | b3fd76f9e3ef3b48ad3c30e766bc9319c77427b0 | 3,598,483 |
def init_csv(file_name: str, header: list, close=True):
"""
create a csv and write header, option to close
"""
csv_file = open(file_name, "a")
write_list(csv_file, header)
if close:
csv_file.close()
else:
return csv_file | bc2883ea84eeeb2cb615e2816e11f3a6acddcfae | 3,598,484 |
def DoCheck(sdk_root):
"""Run layering check at the given root folder."""
return LayeringChecker(sdk_root).Check() | ff19107d77e5dc36b0fc9e91fd6c07f782481aa0 | 3,598,485 |
def spanishwfn(data):
"""Return statistics for Spanish Word-Formation Network."""
return polishwfn(data) | 1df8a0fc1a1f3285e3700aed4eb66f6a931e4c68 | 3,598,486 |
def get_user(username):
"""
Get username line from switch
.. code-block:: bash
salt '*' nxos.cmd get_user username=admin
"""
return sendline('show run | include "^username {0} password 5 "'.format(username)) | feebc6140c030d51bf93a2ebb1fe7070de5f90c5 | 3,598,487 |
import functools
from typing import Any
def _complement(pred: PredicateFn) -> PredicateFn:
"""Return the complement to the predicate function ``pred``."""
@functools.wraps(pred)
def complement(v: Any) -> bool:
return not pred(v)
return complement | 4ff3437403fa80dd053c264e40532196632e4cd0 | 3,598,488 |
from typing import Tuple
from typing import Union
def checkout(args: Tuple[str]) -> Union[res.ResponseFailure, res.ResponseSuccess]:
"""Batch `git checkout` command."""
return guc.GitUseCase().execute(
CONFIG_MANAGER.config.github_selected_repos, "checkout", args
) | 8e2bc5bc512d6e08fd325f5f9e79480edaff2d0d | 3,598,489 |
from typing import Optional
import re
def anonymize_run_string(t: Optional[str]) -> Optional[str]:
"""
Generalizes hex addresses, some sanitizer error numbers, values in "()" brackets.
Use with output, location or issue title
"""
if not t:
return t
re_hex_addr = re.compile(r"0[xX][0-... | ff475c9fa6e4d56a8a00477c34e2e9451ac8713d | 3,598,491 |
def filter_refgene_ensgene_exon(var_df_per_chrom, exon_class,
refgene, ensgene):
"""Filter for a refgene function, ensembl function or both.
Args:
var_df_per_chrom (:obj:`DataFrame`): all variants in a chromosome
variant_class (:obj:`str`): annovar variant class ... | 905db5cab873eabce8ee24872231f2dacabcec29 | 3,598,492 |
import types
from typing import Optional
from typing import List
def references(
ls: LanguageServer, params: types.ReferenceParams = None
) -> Optional[List[types.Location]]:
"""Find references to current symbol, if a bibliography key is present"""
if params is None:
return None
markdown_file ... | 97ae980dc545e664d4f92fb1375cdf123aee98f3 | 3,598,493 |
def get_op_for_request(request, route_info, spec):
"""
Find out which operation in the Swagger schema corresponds to the given
pyramid request.
:type request: :class:`pyramid.request.Request`
:type route_info: dict (usually has 'match' and 'route' keys)
:type spec: :class:`bravado_core.spec.Spe... | b558f7512fead97a5b2777357e9e14cf3093b500 | 3,598,494 |
def get_domains(sents, lang, engine='corenlp', options=None):
"""
>>> from sagas.nlu.legacy.aiobj_kit import get_domains
>>> get_domains('你有几台笔记本电脑?', 'zh', 'ltp')
>>> get_domains('列出上周编辑的文件。', 'zh', 'ltp', DomainGetOptions(enable_predicts=True))
:param sents:
:param lang:
:param engine:
... | 46440c41da735a927325a62280836b57f6eecafe | 3,598,495 |
def _lin_f(p, x):
"""Basic linear regression 'model' for use with ODR.
This is a function of 2 variables, slope and intercept.
"""
return (p[0] * x) + p[1] | 52bc228dd48ee7939fa60cd052989de70a44b197 | 3,598,496 |
from pathlib import Path
def find_cfg_file(directory: Path, name: str) -> str:
"""Find the configuration file by matching the value of BASIC section name paramter to the name variable."""
ini_files = []
for filename in directory.glob("*.ini"):
try:
config = ConfigParser()
i... | 301ac645fbd4a8dc2a6444f2ce70a65a83220000 | 3,598,497 |
def mock_user(request):
"""Define a mock user to be used when testing REST API services"""
user = dict(
id="test_id",
name="User Name",
description="I'm a test user",
url="someurl",
)
return user | ff6eee62cd27328130bcd37c6164d3b4b17e2558 | 3,598,499 |
def check_create_sampler(test):
"""Gets the next vkCreateSampler call atom, and checks its return value and
arguments. Also checks the returned sampler handle is not null. Returns the
checked vkCreateSampler atom, device and sampler handle. This method does
not check the content of the VkSamplerCreate... | 5ca7d4c2960a2cf900146e8d3e4ae950dc34b7b6 | 3,598,501 |
def get_type_as_string(instance: object) -> str:
"""
>>> x='a'
>>> get_type_as_string(x)
'str'
>>> x=1
>>> get_type_as_string(x)
'int'
>>> import decimal
>>> x=decimal.Decimal(1.00)
>>> get_type_as_string(x)
'Decimal'
>>> x=[]
>>> get_type_as_string(x)
'list'
... | 5fd2dd4362a98b2121f9ad2eb4e44ead83446327 | 3,598,502 |
def normalize_4d_nifti(img):
"""Normalize 4d nifti image by subtracting mean voxel intensity over time
and dividing by voxel intensity standard deviation over time.
Args:
img (4d Nifti1Image):
Represent fMRI timecourse.
Returns:
List of individual timepoint 3d norm... | 92385009a3916f8f931f52cfc9078ab38929ccf3 | 3,598,503 |
import numbers
def update(default_obj, custom_obj):
"""
Recursively updates data objects, according to the custom settings
"""
# if simple basic type, return the custom object
if any((
isinstance(custom_obj, numbers.Number),
isinstance(custom_obj, str),
isinstance(custom_ob... | 26fe3d6d16b58420913143316d6d2ce3c5ade0e2 | 3,598,504 |
def get_bool_ids_greater_than(probs, limit=0.5, return_prob=False):
"""
get idx of the last dim in prob arraies, which is greater than a limitation
input: [[0.1, 0.1, 0.2, 0.5, 0.1, 0.3], [0.7, 0.6, 0.1, 0.1, 0.1, 0.1]]
0.4
output: [[3], [0, 1]]
"""
probs = np.array(probs)
dim_len = ... | 4a6eef463851fba84745e9bbcf77e1f932264afa | 3,598,506 |
def replace_group_resource_permissions_view(request):
"""
Create or modify an existing permission on a resource for a group.
Can be used to adjust permission modifiers.
"""
group = ar.get_group_matchdict_checked(request)
resource = ar.get_resource_matchdict_checked(request)
permission = ar.... | eed4b218154df32daefd9bbe100ae5e857ad6abf | 3,598,507 |
def get_fn_args(fn, kwargs: dict, prefix: str = None):
"""
Given function and a dict of kwargs return a dict containing only the args
used by the function.
If prefix is specified, also search for args that begin with '{prefix}__'.
Removes prefix in returned dict.
Raises ValueError if a require... | c7a3c1df35708cb5e696d8a28ba67a37cd29abcb | 3,598,508 |
def getBaseCmd(bin_or_docker):
""" Gets the configured 'base_command' for an image or binary.
Returns a path or image name and a boolean if it's a docker
image or not (needed to know if any mounts are needed)
returns a tuple: ( name , isDocker)
"""
binary = local_cfg["{}.binary".format(bin_o... | 1d672f785eb4d05dcf50964f4ec4434deeb24059 | 3,598,509 |
import ctypes.wintypes
def getWindowsShortPathName(filename):
"""Gets the short path name of a given long path.
Args:
filename - long Windows filename
Returns:
Path that is a short filename pointing at the same file.
Notes:
Originally from http://stackoverflow.com/a/23598461/2... | 0e7a78a9f64397dd2b32ba8ef52822a81d64439d | 3,598,510 |
def make_struct(struct_schema, dictionary, null_prob):
"""Function that generates value for StructType field.
Return dictionary of values. Alias for generate_row().
"""
return generate_row(struct_schema, dictionary, null_prob) | 8c145be0066ef2b02428b7b2b39004e1c4cd248a | 3,598,511 |
import math
def get_factors(number):
"""
Returns all possible factors
:param number:
:return:
"""
factors = set()
# efficient way of finding all the factors of a number in Python
for n in range(1, int(math.sqrt(number)) + 1):
if number % n == 0:
factors.add(n)
... | 2ee587a0459a4868993e56448da29dda40298519 | 3,598,512 |
def resample(x, fs):
"""
If the input streams (or traces) have different sampling rates, the one
characterized by the largest sampling rate is downsampled to the sampling
rate of the other stream (or trace).
The downsampling is carried out via the seislib.processing.resample method,
which ... | c72df4fca33e1fdbbd0ef76fbed476c1e61b145d | 3,598,513 |
def load_xml(document):
"""Methods loads XML document
Args:
document (str): XML document
Returns:
obj
"""
try:
return fromstring(document)
except XMLSyntaxError as ex:
print(ex)
return None | 734c12822a542bf5959809e4b9bcb175f2af6f41 | 3,598,514 |
import sqlite3
def insert_new_class(tx_list):
""" Uses a call to a function helper"""
test_new = sqlite3.connect('file:ledger_new_class?mode=memory', uri=True, timeout=1)
create(test_new, SQL_CREATE)
for tx in tx_list:
# converts into bin tuple - just conversion, no object created, no stored p... | 818bb816de2a68c4c162e7f07c42f8321e1a28d1 | 3,598,515 |
def is_property(class_to_check, name):
"""Determine if the specified name is a property on a class"""
if hasattr(class_to_check, name) and isinstance(
getattr(class_to_check, name), property
):
return True
return False | 0f7dce28f1e78e8b6b937a5a6536060886666371 | 3,598,516 |
def remove_single_value_features(feature_matrix, features=None, count_nan_as_value=False):
"""Removes columns in feature matrix where all the values are the same.
Args:
feature_matrix (:class:`pd.DataFrame`): DataFrame whose columns are feature names and rows are instances.
features... | 496bcc9b7e08163529ba4c26dfdad6f1c05dea03 | 3,598,517 |
def most_recent_searches(parser, token):
"""
Returns the most recent queries seen. By default, returns the top 10.
Usage::
{% most_recent_searches as <varname> [for_user user] [for_search_key search_key] [limit n] %}
Example::
{% most_recent_searches as recent %}
... | 3991eaafcda5118fa9ecec88a3f4cedd2766a397 | 3,598,518 |
def diag_val(request):
"""Diagonal value of matrix."""
return request.param | d00bc2f9c8e676eb3cbc1c9769be2c8b584cb390 | 3,598,519 |
def get_module_dependencies(iri_or_onto, strip_base=None):
"""Reads `iri_or_onto` and returns a dict mapping ontology names to a
list of ontologies that they depends on.
If `strip_base` is true, the base IRI is stripped from ontology
names. If it is a string, it lstrip'ped from the base iri.
"""
... | 6e95f906a4b427fcf51c73012d8d5367c4c229d0 | 3,598,520 |
from string import ascii_uppercase
def get_cluster_label(cluster_id):
"""
It assigns a cluster label according to the cluster id that is
supplied.
It follows the criterion from below:
Cluster id | Cluster label
0 --> A
1 --> B
2 --> C
25 ... | 06210786dfb375dce31ec3c014cc5f545d019c50 | 3,598,521 |
def t_fc(x, y, z, radius=5.0, tmag=1.0):
"""a radially symmetric anomaly in the center of the domain.
units are meters and degC.
"""
ny, nx = x.shape
nz = z.shape[0]
x0 = x[int(ny/2), int(nx/2)]
y0 = y[int(ny/2), int(nx/2)]
tl = np.zeros((nz, ny, nx))
zb = z[-1]
if len(z) > 1:
... | 545df21e14dddbe85c1ffa3787ab1e94b51bf3fc | 3,598,522 |
def professors(request: HttpRequest) -> HttpResponse:
"""Render the professors page"""
professors_list = Professor.objects.all()
context = {'professors': professors_list, 'form': SelectProfessorForm()}
if request.method == 'POST':
if 'choose' in request.POST:
form = SelectProfessorFo... | 0d70ce69cb1d3a6792bce14be1670e4dc2864343 | 3,598,523 |
from re import M
def rest_has_access(obj, user, perm):
"""
Helper function that encapsulates common functionality for has_access API
"""
security.require_access(obj, 'admin')
resp = {'result': False}
user = M.User.by_username(user)
if user:
resp['result'] = security.has_access(obj,... | 11d4dadc74d00e7f181e0795a58d07662ae2edff | 3,598,524 |
import requests
import json
def send_command(args, lambda_addr):
"""
*
* @Purpose: Sends a command to the LEX (Lambda Executor) to execute.
* @Params: args -> list of form [cmd, arg1, arg2, ... argN]
* lambda_addr -> address of lambda
*
* @Returns: result -> LEXResult Enum... | e0ef686bf0917bb4ea6e2d577260c48ec115aa47 | 3,598,525 |
def get_cookie_from(response):
"""
:param response: a requests.response object
:rtype: string
:return: cookie information as string
"""
cookie = response.headers['Set-Cookie'].split(';')[0]
return cookie | d5b34eecf092119cd537b84b8aed9877becff62d | 3,598,526 |
def uclust_cluster_from_sorted_fasta_filepath(
fasta_filepath,
uc_save_filepath=None,
percent_ID=0.97,
max_accepts=1,
max_rejects=8,
stepwords=8,
word_length=8,
optimal = False,
exact = False,
suppress_sort = False,
enable_rev_strand_matching=False,
subject_fasta_filep... | ba5b10b9969aced31be5f7201606eecdbcac93f4 | 3,598,527 |
import time
def calc_desired_torque2(laser_data, steering_percentage, max_velocity, prev_time, desired_torque_percentage):
"""
:param laser_data:
:param steering_percentage:
:return:
"""
front_distance = get_distance_at_angle(laser_data, 0)
side_distance = get_distance_at_angle(laser_data... | 565af884afaf823b79c621286d38eb6fc9693339 | 3,598,529 |
from typing import Optional
from typing import Any
from typing import Callable
def _first_or_default(predicate: Optional[Predicate] = None,
default_value: Any = None
) -> Callable[[Observable], Observable]:
"""Returns the first element of an observable sequence that
... | ed39b99dff8943f973b21950bc63383f133fbb13 | 3,598,530 |
def cmd1(event):
"""cmd1: base description"""
return get_function_name() | 1dc6aca1371c19e28700059be69cbde004e26053 | 3,598,532 |
def encode(data, encodingType):
"""
Encode data as a url
Parameters:
data - a string holding the data to be encoded
encodingType - an string indicating what type of expression to hide
the data in
Returns: a dictionary with the key 'url' referencing a string
holding the url and the key 'cookie' holding... | 743d4e6a5089554b9ebca93cb45cd161191af4d3 | 3,598,533 |
def goldman_q_dna_pair(seq1, seq2):
"""Returns the Goldman rate matrix"""
if len(seq1) != len(seq2):
raise ValueError, "seq1 and seq2 are not the same length!"
seq1, seq2 = ModelDnaSequence(seq1), ModelDnaSequence(seq2)
m = Counts.fromPair(seq1, seq2, DnaPairs,average=True)._data
q = m / ... | 9581517436abe93f1a3d631fbee5f6f26ba0f825 | 3,598,534 |
def extract_keys(nested_dict):
"""
This function is used in order to parse the.json output generated by executing conda search <package-name>
for potential install candidates.
Parameters
----------
nested_dict : dictionary
.json file
Returns
-------
key_lst: list
list containing only the keys (the potent... | 04cb7066f9e2c593a650cb23152b177508f0dc48 | 3,598,535 |
from pathlib import Path
import requests
def test_check_latest3(tmpdir, monkeypatch, bad_cache):
"""Test latest version check when the cache file is corrupted."""
tmpdir.chdir()
monkeypatch.setenv("HOME", str(tmpdir))
assert str(Path.home()) == str(tmpdir)
def mock_get(*args, **kwargs):
r... | 357ceab792101304ab91e162048a46ffe5c3e780 | 3,598,536 |
import warnings
def steepest_descent(A, b, x0=None, tol=1e-5, criteria='rr',
maxiter=None, M=None,
callback=None, residuals=None):
"""Steepest descent algorithm.
Solves the linear system Ax = b. Left preconditioning is supported.
Parameters
----------
A ... | ae8daae985b50dd64dca919c921bc20696454aaf | 3,598,537 |
def compute_quantile_diff(a, q):
"""Computes difference between q and 1-q quantiles."""
q1 = np.quantile(a=a, q=q, axis=0)
q2 = np.quantile(a=a, q=1-q, axis=0)
return q2 - q1 | 0e787dc3c2e6291f42e3276b83f5e107b456b671 | 3,598,539 |
def text_value(value):
"""Force a value to text, render None as an empty string."""
return "" if value is None else force_str(value) | eeecb39c8f8b1c248f05915afa085785c057018f | 3,598,540 |
def calculate_slug(first_name, last_name, mother_family_name, email, User):
"""
This function calculate a slug name
"""
slug = None
i = 0
# check if the values are defined
if first_name or last_name or mother_family_name or email:
# check if the slug is valid
while not slug o... | 4169251e5a8dd1a35fb96571309c20c31c16e833 | 3,598,541 |
def load_model(spec):
"""Read the openapi specification and convert it into a model.
In the process, resolve references and pull out relevant properties for CLI
parsing and function invocation.
The output data structure is a map for operationId to data shaped liked the
following:
{'list-clust... | 45fc4c2a3ad593252c54352fef48a003e6cbc3f1 | 3,598,542 |
import scipy
def matprep_info(matprep_artifacts):
"""Get the runtime info data from MATLAB PREP for comparison with PyPREP.
This fixture helps convert the MATLAB PREP runtime info into a format that's
easier to compare with PyPREP, replacing channel indices with channel names
and renaming variables f... | 436b0f2788709ec9b3d4064dbdab7e868332b681 | 3,598,545 |
def _butterworth(ts, low_frequency, high_factor, order, sampling_frequency):
"""Butterworth filter
Parameters
----------
ts: np.array
T numpy array, where T is the number of time samples
low_frequency: int
Low pass frequency (Hz)
high_factor: float
High pass factor (prop... | f3d90640d4a84741adba98599c3da57eee0b03a5 | 3,598,546 |
def run(model, file_path, X, Y):
"""
Define checkpoints and run model
:param model:
:param file_path:
:param X:
:param Y:
:return:
"""
# Set global random seed for reproducibility
tf.set_random_seed(42)
# Define callbacks
checkpoint = ModelCheckpoint(
file_path, ... | 7b48c258e3b0b15c71879f391457b70f1dc11466 | 3,598,547 |
def all_tags():
""" Fetch all tags. """
cursor = Tag.find({}, sort=[('weight', pymongo.DESCENDING)])
return [t for t in cursor] | a447673fe16f645076fc0840d14ffab42e037d00 | 3,598,548 |
def get_all_recommendations(csv_file):
"""
This function reads all recommendations for users using the result of the recommendation system stored in a csv file
:param csv_file: the csv file where the recommendations are stored
:return: the dataframe of recommendations predicted for users
"""
df_... | fe0578bb77c60deaf833a22fd9a1b9e946183f91 | 3,598,549 |
from bs4 import BeautifulSoup
def filter_bank_account_info(html: str) -> dict:
"""Filter the bank account info in the data of the HTML structure.
Keyword arguments:
`html: str` - Content in html structure.
"""
soup = BeautifulSoup(html, 'html.parser')
# Get all the labels to use as a key i... | e4558d52895dbb01f57a26d3722597577367ba26 | 3,598,550 |
def find_size(resultDict, db_name, db_password, db_user, db_host):
"""
For each city, depending on the average temperature, the size of pointer is decided and stored in key "size".
:param resultDict: dictionary with cities as key and sub dictionary as values
:param db_name: database name
:param db_... | 4a0bcb57f03f6460e4140d266cf0feeec8d7c91b | 3,598,551 |
def _add_entitlements(
name,
platform_type,
product_type,
include_entitlements = True,
is_stub = False,
**kwargs):
"""Adds entitlements targets for a bundle target.
This function creates an entitlements target to ensure that a binary
created using the `link_m... | 8af70ff46374d4684577828aaf2e6b55ab3c1970 | 3,598,552 |
def imagenet_model_fn(features, labels, mode, params):
"""Our model_fn for ResNet to be used with our Estimator."""
if params['flag_bias'] == True:
## lr for bias correction learning
learning_rate_fn = resnet.learning_rate_with_decay(
batch_size=params['batch_size'], batch_denom=256,
num_im... | e90141b2d7ae3bc6b078c557d395a78eb4d04df8 | 3,598,553 |
def help_text(contains: str = ""):
"""
Built in help - prints out the public function names for the collection object for the token API
Parameters:
filter(string): filters out functions beginning with this text, defaults to all
"""
functions = [search,
search_by_id,
help_text... | 4a9021847019bf633df846249b7e883126477885 | 3,598,554 |
import typing
def U(theta, phi, lambd, target: typing.Union[list, int], control: typing.Union[list, int] = None) -> QCircuit:
"""
Notes
----------
Convenient gate, one of the abstract gates defined by OpenQASM.
.. math::
U(\\theta, \\phi, \\lambda) = R_z(\\phi)R_x(-\\pi/2)R_z(\\theta)R_x(... | 847b180c1ef673d3dcf5da09e1d301832bb9f389 | 3,598,555 |
def get_action_dim(action_space: space.EveSpace) -> int:
"""
Get the dimension of the action space.
:param action_space:
:return:
"""
if isinstance(action_space, space.EveBox):
return int(np.prod(action_space.shape[1:]))
elif isinstance(action_space, space.EveDiscrete):
retu... | 154b3b2711dfe37b4f2f0a635a35e1c614dd3dd9 | 3,598,556 |
def is_prime(nb: int) -> bool:
"""Check if a number is a prime number or not
:param nb: the number to check
:return: True if prime, False otherwise
"""
# even numbers are not prime
if nb % 2 == 0 and nb > 2:
return False
# checking all numbers up to the square root of the number
... | 4368fd20eadd4d773d5f5af06f8717ef633d48b8 | 3,598,557 |
def primes_example_1(N):
"""
This function returns a stream which consists of all primes up to
N.
Parameters
----------
N : int
Integer greater than 2.
Returns
-------
prime_stream: Stream
Sequence of primes less than or equal to N.
"""
# 1. Define streams
... | 25cb299ea79b5a0c80a6541d3c81b8c491fecd52 | 3,598,558 |
def api_exchange_rate_sbv_post():
""".. :quickref: 02. SBV; Post new exchange rate
Limited function that allows data manager to push newest price
**Request**:
.. sourcecode:: http
POST /api/exchange_rate/sbv HTTP/1.1
Host: https://vapi.vnappmob.com
Accept: application/json
**R... | 2a8265061dfb30d627310b88c658e154b5c9b1e8 | 3,598,559 |
import functools
def residual_connection(
skip_name,
input_name,
prefix,
filter_mul,
strides = 1):
"""Returns a sequence of ops making a residual connection.
skip_name refers to the original output (e.g., x), and input_name refers to
the layer output (e.g., f(x)). Then this computes
may... | 77aa9c71909bdd5342a36f4f88652879df7f4e78 | 3,598,560 |
def database(connection_string, db_class=SimplDB):
"""Return database singleton instance.
This function will always return the same database instance for the same
connection_string. It stores instances in a dict saved as an attribute of
this function.
"""
if not hasattr(database, "singletons"):... | 841aadd99dc3ec91825ced2a2d8703939617ef3f | 3,598,561 |
def get_ids_by_accession(accessions):
"""
Search NCBI's nucleotide database for the given accessions and return a list
of nucleotide database ids.
>>> get_ids_by_accession(["AC254980.1"])
['595582430']
>>> get_ids_by_accession(["fakeclone"])
[]
"""
# By default, expect no results.
... | 704bcb6cacaf032c1c69cda4f48cd961a2f09d05 | 3,598,562 |
import torch
import tqdm
def primaldual(
y,
OpA,
OpW,
c0,
eta,
y0=None,
iter=20,
sigma=0.5,
tau=0.5,
theta=1.0,
silent=False,
report_pd_gap=False,
):
""" Primal Dual algorithm.
Reconstruction algorithm for the inverse problem y = Ax + e under the
synthesis ... | 7194fc8fec508768d226d0274c58436972ff3540 | 3,598,563 |
def lBoundedBackward(x, lower):
"""
Transform from physical parameters with lower limit to transformed (unconstrained) ones
Args:
x (float): vector of parameters
lower (float): vector with lower limits
Returns:
Float: transformed vector of parameters
"""
return np.l... | 488240b6835eb8bd43bf1343efd2170400dcbf78 | 3,598,564 |
from pathlib import Path
from typing import Dict
import csv
def get_file_data(datafile: Path) -> Dict:
"""Extract data from CSV file.
Parameters
----------
datafile : Path
Path to the file to extract data from.
"""
data = {}
with open(datafile) as file:
reader = csv.reade... | 2b93d141273f5965b668eaeb2a3a9ab076f5d071 | 3,598,565 |
def define_vggish_slim(x, is_training, num_classes):
"""Defines the VGGish TensorFlow model.
All ops are created in the current default graph, under the scope 'vggish/'.
The input is a placeholder named 'vggish/input_features' of type float32 and
shape [batch_size, num_frames, num_bands] where batch_siz... | 6578e44158faca11068ba1ba59613d02ccee1e7d | 3,598,566 |
import torch
def load_model(schema, model_file):
"""
Load a model, given the scheme file of model parameters and the model state dictionary
saved after the model fitting.
Parameters:
- - - - -
schema: dict
dictionary of parameter values for a given architecture
model_file: str
... | 3ea3a5dba57f9d17d0467957ae915660b46b1c7b | 3,598,567 |
def _CreateHostGroupConfigEntityFromGroupInventory(lab_name, group):
"""Creates HostGroupConfig from Group model.
Args:
lab_name: the lab name.
group: the ansible inventory Group object.
Returns:
the HostGroupConfig entity.
"""
return datastore_entities.HostGroupConfig(
id=datastore_entitie... | fa5ec4cd6ebfcce75721d8896bf38cab997e24b4 | 3,598,568 |
async def predict(item: str):
"""
## How to use -
* Click on "try it out."
* Enter a song id (without the quotes) obtained from the song search above.
* This will output 10 similar songs based on your song's features.
* The output will list the songs by song ID.
* The songs are pulled from a... | 1a1a8c3c1eb3a887645b0784756b62046a7c86af | 3,598,569 |
def read_config_directly(path: str) -> dict:
"""
Overview:
Read configuration from a file path(now only suport python file) and directly return results.
Arguments:
- path (:obj:`str`): Path of configuration file
Returns:
- cfg (:obj:`Tuple[dict, dict]`): Configuration dict.
"... | 1404602c04690c3da39793348dc8c45377fc3773 | 3,598,572 |
def get_projection(args):
"""
Returns a projection as specified in args.
Keyword arguments:
- args: arguments as dict
Returns:
- a projection object with fit_transform(X) method
"""
# get and check arguments
method = args['method']
random_state = args['random_state']
check(... | bcf55cc0a3d7aa6dd3463273df072bf2bd5007d1 | 3,598,573 |
async def present(hub, ctx, name: str, image: str, **kwargs):
"""
Ensure a container is present
.. code-block:: yaml
new container:
lxd.containers.present:
- name: webserver01
- image: ubuntu1804
"""
ret = {
"result": False,
"name": name,
... | 911b27a3318bc273f790041f2c003f6e8f56645d | 3,598,574 |
import itertools
def ONN(linear_feature_columns, dnn_feature_columns, embedding_size=4, dnn_hidden_units=(128, 128),
l2_reg_embedding=1e-5, l2_reg_linear=1e-5, l2_reg_dnn=0, dnn_dropout=0,
seed=1024, use_bn=True, reduce_sum=False, task='binary',
):
"""Instantiates the Operation-aware Neura... | 40d17fbbb546e2df99f04b118685b140b41f0a47 | 3,598,576 |
from typing import Tuple
from typing import List
def mask_set(dataset_length: int,
val_size: float = 0.1,
test_size: float = 0.1) -> Tuple[List[bool], List[bool], List[bool]]:
"""Returns three boolean arrays of length `dataset_length`,
representing the train set, validation set and t... | 4714a7701aead6f8ceb0e71ae1f15296550fc57c | 3,598,577 |
def train(lr, plot=False):
"""Training Function"""
data = pd.read_csv('housepricedata.csv')
headers = data.columns
X_train, X_test, Y_train, Y_test = train_test_split(data[headers[:-1]],
data[headers[-1]])
X = standardize(X_train[headers[:-1]]... | 2cd4dd96a50cd454606a312612cc0ab43fcc4aff | 3,598,578 |
def _fill_in_missing(x):
"""Replace missing values in a SparseTensor.
Fills in missing values of `x` with '' or 0, and converts to a dense tensor.
Args:
x: A `SparseTensor` of rank 2. Its dense shape should have size at most 1
in the second dimension.
Returns:
A rank 1 tensor where missing value... | e75e245198aaab001e76377761172a872dc77d6d | 3,598,579 |
def get_routes(package):
"""
This will walk ``package`` and generates routes from any and all
``APIHandler`` and ``ViewHandler`` subclasses it finds. If you need to
customize or remove any routes, you can do so to the list of
returned routes that this generates.
:type package: package
:par... | 845c820e040dd5053fdf56b77732ae66f7665308 | 3,598,580 |
from typing import Sequence
from typing import Any
from functools import reduce
from operator import getitem
def get_in_dict(d: dict, keys: Sequence[str]) -> Any:
"""
Retrieve nested key from dictionary
>>> d = {'a': {'b': {'c': 3}}}
>>> get_in_dict(d, ('a', 'b', 'c'))
3
"""
return reduce... | d851c1d9360e90cbecbff401b98b76afb9b7e52f | 3,598,581 |
def tree_psum(A, axis_name, axis_index_groups=None):
"""Compute a `psum` as a tree-reduction, to save memory with ef57.
The return value is the same as that of
`jax.lax.psum(masked, axis_name, axis_index_groups)`.
This function is only needed as a workaround for psum for ef57 using a lot of
memory, see b/188... | 70ae505d7dc444f1bed3cab0e9a87cdb6c2b5c56 | 3,598,582 |
from io import StringIO
def make_df(
n_cols: int,
rows_str: str,
sep: str,
names: list[str] | None = None,
) -> pd.DataFrame:
"""
Read a CSV into a DataFrame without NaN value conversion so that any None values are
only present due to a missing field, permitting a check for parsed CSV colu... | e88aedf1e3ec8c6fc08998007b8c86415bb14fab | 3,598,583 |
def reduce_mem_usage(df):
""" iterate through all the columns of a dataframe and modify the data type
to reduce memory usage.
"""
start_mem = df.memory_usage().sum() / 1024**2
print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))
for col in df.columns:
col_ty... | 1aa08b1c556aa04248fdfe9332c60357b2f4fe10 | 3,598,584 |
def create_user_and_auth_token(username, is_staff=False):
"""Creates a user and generates token for the user.
Returns:
tuple: (User object, token)
"""
user = User.objects.create(
username=username,
email=f'{username}@rssapifier.com',
is_staff=is_staff
)
token = T... | 7f9babe251a1b084d5483472d60de43537e6ad7a | 3,598,585 |
def svn_repos_parse_dumpstream2(*args):
"""
svn_repos_parse_dumpstream2(svn_stream_t stream, svn_repos_parse_fns2_t parse_fns,
void parse_baton, svn_cancel_func_t cancel_func,
apr_pool_t pool) -> svn_error_t
"""
return apply(_repos.svn_repos_parse_dumpstream2, args) | 12d237d5d1570bfd74f27fffc823527124a90513 | 3,598,586 |
import xml
def parse_xml(element):
"""
Parse an XML API Response xml.dom.minidom.Document. Returns the result as dict or string
depending on amount of child elements. Returns None in case of empty elements
"""
if not isinstance(element, xml.dom.minidom.Node):
try:
element = xml... | 293e7fdd7ea3884934745c7fd708d11fd48f7cfd | 3,598,587 |
def barycentric_refinement(grid):
"""Return the barycentric refinement of a given grid."""
new_vertices, new_elements = _create_barycentric_connectivity_array(
grid.vertices,
grid.elements,
grid.element_edges,
grid.edges,
grid.number_of_edges,
)
return Grid(
... | e384424392d2ae1806947ffb7fae40d5fc5e3cdc | 3,598,588 |
import scipy
def test_Regridder_init_small():
"""
Simplified test for :meth:`~esmf_regrid.esmf_regridder.Regridder.regrid`.
This test is designed to be simple enough to generate predictable weights.
With predictable weights it is easier to check that the weights are
associated with the correct in... | fd02fbd757835e505b7b1b93ce37d84af13a7454 | 3,598,590 |
from typing import Any
from typing import Union
def is_union(arg_type: Any) -> bool:
"""Check if the input type is `Union`.
Args:
arg_type (typing.Any): input type.
Returns:
bool: True if input type is `Union`
"""
try:
return safe_issubclass(arg_type.__origin__, Union)
... | f094a45af0a6b89382ca9ed6e34de6b94ebeaf98 | 3,598,591 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.