content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_bios_reader(model_name: str):
"""
Constructs and returns a Biosbias Reader based on the model name.
"""
if model_name == "BERT":
bert_indexer = PretrainedTransformerIndexer('bert-base-uncased')
tokenizer = PretrainedTransformerTokenizer('bert-base-uncased')
reader = TextC... | 098764998fd2123bbbd55e4cdfadd1ddf7e3b0ab | 3,613,400 |
import json
def mocked_json_dumps(monkeypatch):
"""Monkeypatch json.dumps."""
mock_dumps = mock.MagicMock()
monkeypatch.setattr(json, "dumps", mock_dumps)
return mock_dumps | f49ecf285976d76416fff7b8f045807575de6425 | 3,613,401 |
def locale_factory(factory):
"""
Decorator which defines a factory function which
set forms locale. If not defined locale 'en_US' is used
:param factory: function
:return: str with locale
"""
global _get_locale
_get_locale = factory
return factory | 10c306a54ddfd7215c3fa12b0ceacb4e8f177e0e | 3,613,402 |
import io
def get_mne_sample(n_trials=10):
"""Return sample data from the mne dataset.
```
In this experiment, checkerboard patterns were presented to the subject
into the left and right visual field, interspersed by tones to the
left or right ear. The interval between the stimuli was 750 ms.
... | a546c550bd0b884be7ea864e140453ca3bbc2bac | 3,613,403 |
def sample_affine_transform(batchsize,
n_dims,
rotation_bounds=False,
scaling_bounds=False,
shearing_bounds=False,
translation_bounds=False,
enable_90_r... | fc9083498d52bc6e300defbe698278515af0c7f6 | 3,613,404 |
def get_square_lattice(height: int) -> RectangularLattice:
"""Returns a lattice of all points in a square of the given height.
Args:
height (int): Height of the lattice.
Returns:
The lattice.
"""
return get_rectangle_lattice(height, height) | 1a977fe97194c777104a1e4befc53e27a381a5bd | 3,613,405 |
def fpn_search(fpn_arch, in_channels):
"""Fpn search warpper."""
return FPN_Search(in_channels=in_channels, out_channels=64, num_outs=4, fpn_arch_str=fpn_arch) | 1be6e45c2a6108b26ddfec7ce998cdbbf1cfefd9 | 3,613,406 |
from typing import Optional
from typing import Dict
from typing import Iterable
from typing import Any
from typing import List
def get_fixture_dicts(
domain: str,
data_type_id: str,
filter_in: Optional[Dict[str, Optional[Iterable]]] = None,
filter_out: Optional[Dict[str, Any]] = None,
) -> List[Dict]:... | 92ade8b539db93f7e85e4b7e0a1542b9ceaf19ab | 3,613,407 |
def speedup(i):
"""
Input: {
samples1 - list of original empirical results
samples2 - list of new empirical results (lower than original is better)
(key1) - prefix for min/max/mean in return dict
(key2) - prefix for min/max/mean in return dict
... | 053a6d0831f8d11f34fa29e5117ea7c66e5f4bad | 3,613,408 |
from typing import Dict
from typing import Any
def deserialize_trade(data: Dict[str, Any]) -> Trade:
"""
Takes a dict trade representation of our common trade format and serializes
it into the Trade object
May raise:
- UnknownAsset: If the fee_currency string is not a known asset
- De... | e436066d70c348368bdddc811be0d4e6d7c903da | 3,613,409 |
import time
import json
import os
import warnings
def sweepAndSave(
inputDict,
extraInstruments = [],
saveEnable = True,
delay = 0.0,
plotVars = None,
comments = "No comments provided by user",
plotP... | aa337f926c5d5ea69673388e1c0f4d2419ef5a83 | 3,613,410 |
import json
def load_data(file=json_file):
"""Loads json file
:param file: Path object to load data from
:return: JSON data
"""
if not file.is_file():
soup = get_soup()
enchantment_data = generate_enchantments(soup)
minecraft_items = generate_items(enchantment_data)
... | 618f24388c7e79f78ca6f03880990f3f489ffbb0 | 3,613,411 |
def tag_to_entity(tag_seq, label_alphabet):
"""
Collect predicted tags(e.g. BIO)
in order to get entities including nested ones
"""
entities = []
for idj, tag in enumerate(tag_seq):
try:
tag = label_alphabet.get_instance(tag)
if tag.split('-', 1)[0] == 'B' or tag... | 8759a9e2e5be5aab0267909ebab82cffdb16b896 | 3,613,412 |
def calc_d(D_o, t, inner=False):
"""Return the outer or inner diameter [m].
:param float D_o: Outer diameter [m]
:param float t: Layer thickness [m]
:param boolean inner: Select diameter
"""
if inner:
return D_o - 2 * t
else:
return D_o + 2 * t | eaadfed210c0b06b7fd0bbc500fe093461d9766c | 3,613,413 |
def tobs():
"""Temperature observations from the last year"""
results = session.query(Stations.name, Measurements.date, Measurements.tobs).\
join(Measurements, Stations.station == Measurements.station).\
filter(Measurements.date> first_date()[0]).\
... | c3912633e58303d955c9599a350d52d2f9a94c52 | 3,613,414 |
from typing import Any
def get_fake_prune_images() -> tuple[int, dict[str, Any]]:
"""Get fake prune images response"""
status_code = 200
response = {
"ImagesDeleted": [FAKE_LONG_ID],
"SpaceReclaimed": 123
}
return status_code, response | 1031fb6bea58c696471da7cd452ff5f12fb14d53 | 3,613,415 |
def get_function_path(f):
"""
Passes the internal func_code to a attribute called internal_code on the wrapper.
Then we call the wrapper attribute which throws metadata of the internal function, and gets the path.
:param f: function
:return: path
"""
# does the wrapper is defining the new at... | ae88ffe5e452dc7d2ae001786ba4b58fea072528 | 3,613,416 |
def get_all_completed_labels(engine, label_task_id, dataset_id=None, label_status="admin_complete"):
"""
Get latest label history entries for all completed (approved) labels
:param engine:
:param label_task_id:
:param dataset_id: optionally specify a dataset ID to only return labels for this datase... | 16fe3d4b59a5fb2fc438c8f1b625de3a45be7b4b | 3,613,417 |
def rnn_stack(params=None,
tier : int = None,
last_tier = False,
dropout = 0,
recurrent_dropout = 0,
):
"""MultiRnn cell. Options
Args:
params = params class with cell args
tier = int designating the tier number
... | 4bd416d8dca8b73c1961d6d48efa8e17f943b76d | 3,613,418 |
from typing import Dict
from typing import Any
import requests
def signed_api_call(service: str, path: str = "/", method: str = 'GET',
configuration: Configuration = None,
secrets: Secrets = None,
params: Dict[str, Any] = None) -> requests.Response:
"""
... | f75597dc9f259004af36c8c68511fa2167fce2e0 | 3,613,419 |
def check_and_get_org_by_repo(repo_id, user):
"""
Check whether repo is org repo, get org info if it is, and set
base template.
"""
org_id = get_org_id_by_repo_id(repo_id)
if org_id > 0:
# this repo is org repo, get org info
org = get_org_by_id(org_id)
org._dict['is_staff... | 1c6270a8dd0bd13da21b0317bc8ce1ce4fbccc79 | 3,613,420 |
def upload_large(file, **options):
""" Upload large files. """
upload_id = utils.random_public_id()
with open(file, 'rb') as file_io:
upload = None
current_loc = 0
chunk_size = options.get("chunk_size", 20000000)
file_size = getsize(file)
chunk = file_io.read(chunk_si... | e23e853fd3ac1309f26e7a6ae30f83aba4350066 | 3,613,421 |
import logging
def kappa(y_true, y_pred, weights=None, allow_off_by_one=False):
"""
Calculates the kappa inter-rater agreement between two the gold standard
and the predicted ratings. Potential values range from -1 (representing
complete disagreement) to 1 (representing complete agreement). A kappa
... | ec3d76c221e7e485ef6e0af91db752cdc08eac65 | 3,613,422 |
from typing import Collection
def get_post(id):
"""获取文章
"""
post = Post.query.get_or_404(id)
post.reading_num += 1
models.add_or_update(post)
root_comment_list = db.session.query(Comment).filter_by(
post_id=post.post_id, root_comment_id=-1).all()
comment = {
i: db.session.q... | 7b623969c1bd4699707025bac17be987e5a7a70c | 3,613,423 |
def sample_noise_using_sigma(log_sigma_sample, n_obs):
"""Produces a sample of residual noises based on sigma values.
Args:
log_sigma_sample: (tf.Tensor) Samples of log sigmas, shape (n_sample, )
n_obs: (int) Number of observation to sample for each sigma value.
Returns:
(tf.Tensor... | 76972f056ef05916c7ecff757f40ba0a62e342e0 | 3,613,424 |
def rjd_to_jdn(rjd: int) -> int:
"""Return Julian day number (JDN) from Reduced Julian Day (RJD) number.
:param rjd: Reduced Julian Day (RJD) number.
:type rjd: int
"""
return rjd + 2400000 | cfb26706b16f6421449353c97960e417f77a4647 | 3,613,425 |
def clip_pad_images(tensor, pad_shape, pad=0):
"""
Clip clip_pad_images of the pad area.
:param tensor: [c, H, W]
:param pad_shape: [h, w]
:return: [c, h, w]
"""
if not isinstance(tensor, paddle.Tensor):
tensor = paddle.to_tensor(tensor)
H, W = tensor.shape[1:]
h = pad_shape[... | 638befe5a41329f57cd9f8ef612c9303838d158b | 3,613,426 |
def make_tree_parallel_nj(distance_matrix: np.ndarray, names: np.ndarray) -> Tree:
"""
Nj tree is made from random sampling with replacement from the distance matrix.
:param distance_matrix:
:param names
:return:
"""
np.random.seed(randint(0, 1000000))
selected_ids = np.random.choice(np.... | 2586726eb0a254d892099ca25a15ceb3141646a1 | 3,613,427 |
def get_doc_for_user(trunk_id, user):
"""Retrieves document based on user's visit history.
If the user has visited a particular revision (document of a trunk),
user will see that document, else user will be directed to the
latest revision.
We pass user instead of using users.get_current_user, so that this f... | dee5140df1e8d965b62b903012aad28502827682 | 3,613,428 |
def resolve_match_norm_seq_alleles(data, maf_data):
""" Resolves matched normal seq alleles. """
norm_allele1 = ""
for col in MATCHED_NORMAL_SEQ_ALLELE1_COLUMNS:
if col in data.keys():
norm_allele1 = process_datum(data.get(col,""))
break
norm_allele2 = ""
for col in ... | 25a2a7cbd18f72f910c5750128ec33b328a4fe69 | 3,613,429 |
def __lt__(self, other):
"""Computes the rich comparison LOWER THAN between two images.
Parameters
----------
self : ee.Image
Left operand.
other : ee.Image | numeric | list[numeric]
Right operand. If numeric, an ee.Image is created from its value. If list, an
ee.Image with ... | aa596d0017ed41e727e2a46c5931d9efe4d4d5f1 | 3,613,430 |
from typing import List
import logging
import tqdm
def google_query(query: str,
page_count: int) -> List:
"""Use the google package to pull weburls from google results.
Args:
query (str): query string
page_count (int): how many results to get from google
Returns:
... | baecb90b77f0b393f57116631a995d5832889fe2 | 3,613,431 |
def _missing_synset(lex: lmf.Lexicon, ids: _Ids) -> _Result:
"""synset of sense is missing"""
synset_ids = ids['synset']
return {s['id']: {'synset': s['synset']}
for e in _entries(lex)
for s in _senses(e)
if s['synset'] not in synset_ids} | 2629b50780c04c49ec5fcecdad77a84ff71cadc2 | 3,613,432 |
def create_component_analysis_timing_graph(durations, width=DEFAULT_WIDTH,
height=DEFAULT_HEIGHT, dpi=DPI):
"""Create graph with component analysis timings."""
N = len(durations)
component_selectors = ["security_issues", "source_licenses",
... | c8fdffe67f8c379666b9aec54918de6030b6fff5 | 3,613,433 |
def ask_for_path():
"""asks for the path to the GPS-device and returns it
if no path is specified: returns the standard PATH"""
print("\nGib den Pfad zum GPS-Geraet ein (NICHT zum Unterordner 'GPX').")
print("Falls Standardpfad uebernommen werden soll: keine Eingabe")
inp = input(">> ")
if inp ... | 1bb66e2faf21993f36a44a7a8caa158cd6514745 | 3,613,434 |
def add_til2(*args):
"""add_til2(char name, int flags) -> int"""
return _idaapi.add_til2(*args) | 0d2a43b723c71637d16d732dbca8bc3a55c32cf3 | 3,613,435 |
def meta_sync_register(model, fields=None, exclude=()):
"""
注册ORM模型(model)为需要进行元数据同步的类
Args:
model 需要进行数据同步的model,必须继承至django.db.models.Model
fields 需要进行数据同步的字段
exclude 不需要进行数据同步的字段
Examples:
class DemoModel(models.Model):
param1 = models.CharField(max_lengt... | fbd8d9ee1e31783932d5c2f401da21339f09bc8d | 3,613,436 |
def is_neq_prefix(text_1, text_2):
"""Return True if text_1 is a non-equal prefix of text_2"""
return text_1 != text_2 and text_2.startswith(text_1) | f9e7f835ec577dc539cd586da5e6f9e2e0903a74 | 3,613,437 |
def find_common_cond_attrs(sql_obj1, sql_obj2):
"""
Find common attributes for SQL join condition
:param sql_obj1:
:param sql_obj2:
:return:
"""
commonpr_list = []
for project1 in sql_obj1.pr_list:
for project2 in sql_obj2.pr_list:
if project1.alias == project2.alias... | 20db9c2f7d8ad1479e94411f7384fcc52a6b90f4 | 3,613,438 |
import json
def read_config(fn, perm="r"):
"""
Read config file which consists parameters used in program.
:param str fn: Name of config file (config.json)
:param str perm: Mode in which the file is opened
:return: Config file paramteres
"""
with open(fn, perm) as file:
config = ... | f77a1dbb9b1e0f9f43dbef745f550485f1003cf7 | 3,613,439 |
import optparse
def getParse():
"""Desc: get Options parse."""
usage='''\
Desc:
This is dataprocessing Tool FOR Beverly.
# python datapro.py --dir ./dir/data'''
parser = optparse.OptionParser(usage=usage)
parser.add_option("-d","--dir",dest="dataDir",help="This is the data dir path")
pars... | 0f4c085c857c238f03505abaead76b0c21268fda | 3,613,440 |
import os
def load_dataset(data_dir, url, batch_size):
"""Loads the colors data at path into a PaddedDataset."""
# Downloads data at url into data_dir/basename(url). The dataset has a header
# row (color_name, r, g, b) followed by comma-separated lines.
path = maybe_download(os.path.basename(url), da... | 5529f4601a99364c372219cd768dbc2bf87ca691 | 3,613,441 |
import re
def get_version_from_git_describe():
"""Determine a version by incrementing the git version in the context of master.
This calls `git describe`, if git is available.
Returns:
version from `git describe --tags --always --dirty` if git is
available; otherwise, None
"""
bran... | 0739a6e00ea2f978fb42e206e662fcfcec95f67b | 3,613,442 |
from typing import Tuple
def check_invalid_indentation(path: str) -> Tuple[int, str, str, IndentationErrorType]:
"""
Check if the file contains any indentation errors.
:param path: Path to file
:return: Tuple[line number: int,
error line: str,
previous start of ... | 5ca3f6ee26f9c6b616f274c0e1ac454143ab35fc | 3,613,443 |
def yolo2_filter_boxes(boxes, box_confidence, box_class_probs, threshold=.6):
"""Filter YOLOv2 boxes based on object and class confidence."""
box_scores = box_confidence * box_class_probs
box_classes = K.argmax(box_scores, axis=-1)
box_class_scores = K.max(box_scores, axis=-1)
prediction_mask = box_... | a8e9be378262ac46cba9ba622e45d6763e702a64 | 3,613,444 |
import functools
def timed_info(func):
"""Decorator to measure and logger.info a function's execution time."""
@functools.wraps(func)
def timed_(*args, **kwargs):
return _timed(func, logger.info, *args, **kwargs)
return timed_ | 5282c8df0ee9f983373063898a30e27a908f15c4 | 3,613,445 |
def get_label_base(label_path):
""" Gets directory independent label path """
return '/'.join(label_path.split('/')[-2:]) | 16748bdb197249f157a288e2c664374ad432e6c7 | 3,613,446 |
def computeTriadCounts(G, signs):
"""
:param - G: graph
:param - signs: Dictionary of signs (key = node pair (a,b), value = sign)
return type: List, each position representing count of t0, t1, t2, and t3, respectively.
return: Return the counts for t0, t1, t2, and t3 triad types. Count each triad
only once... | e8c4bee1516531ed36f7ea5dd6ebaf9d8414b9a3 | 3,613,447 |
def properties_var():
"""
Stream properties:
1. n_chunks
2. chunk_size
"""
return (200, 250) | b5f5619ed1f44fe3c18e865f1374eed26042643d | 3,613,448 |
def factored_joint_mvn(distributions):
"""Combine MultivariateNormals into a factored joint distribution.
Given a list of multivariate normal distributions
`dist[i] = Normal(loc[i], scale[i])`, construct the joint
distribution given by concatenating independent samples from these
distributions. This is m... | 430463bb9144a23b70fc4b3679c55b1c5876a9d2 | 3,613,449 |
def cli_command(fn):
"""Register function as subcommand."""
command = SUBPARSERS.add_parser(fn.__name__, description=fn.__doc__)
command.set_defaults(func=fn)
unspecified = object()
args = reversed(list(zip_longest(
reversed(fn.__code__.co_varnames[:fn.__code__.co_argcount]),
revers... | d75063f6a1850cb339c88b25cdc451760f4a8358 | 3,613,450 |
import random
def mutate(file, factor):
"""Mutate $factor% of bytes in the $file"""
file = bytearray(file)
mutations = len(file) * factor
if mutations is 0 and factor is not 0:
mutations = 1
while mutations > 0:
random_byte = random.randint(0,255)
random_position = random.randint(0, len(file)-1)
file[r... | 663013b46c71858260d055080fd20f5e0cf495eb | 3,613,451 |
def forward_fill_series(s1, s2):
""" For two pandas series with DateTimeIndex , return corresponding series with the same numer of entries, forward-filled.
:type s1: pd.Series
:type s2: pd.Series
"""
def dedup_index(s):
""" Deduplicate index values of pd.Series"""
df = s.to... | e918c94ed81b79ffd038c059b4c263d024da4bb0 | 3,613,452 |
import uuid
def uuid_uri(prefix):
"""Construct a URI using a UUID"""
return prefix + str(uuid.uuid1()) | 2361583122396296d40ff5b1c284662a918fc871 | 3,613,453 |
from typing import Any
def is_raw_json_null(py_obj: Any) -> bool:
"""
Checks if the given Python object is a raw JSON null.
:param py_obj: The Python object to check.
:return: True if the Python object is a raw JSON null,
False if not.
"""
# Must be None
return... | 1d206ed8242caeb806a646aa617a3bf6707fd5d8 | 3,613,454 |
async def async_setup_entry(hass, config, async_add_entities):
"""Create wallbox sensor entities in HASS."""
wallbox = hass.data[DOMAIN][CONF_CONNECTIONS][config.entry_id]
station = config.data[CONF_STATION]
async def async_update_data():
try:
return await hass.async_add_executor_... | 92e7cbfd7c638bbe76224fc7d4f569c138a6b7ca | 3,613,455 |
from datetime import datetime
def various_indexes(request):
"""Parametrized cached index of various types with source."""
source = mangasource.MangaSource(
'test source', 'http://www.source.com/', '_',
index_tag=request.param['tag'], index_attrs=request.param['attr']
)
now = datet... | 3b37ae2ceae04008ef2c6eba18edebd4c0e53450 | 3,613,456 |
import re
def underscore_2_space(string: str):
"""
Return string with underscores replaced by spaces.
"""
return re.sub('[_]', ' ', string) | a4ef9b19cda662ec4714cab58e1f502f668b6aaa | 3,613,457 |
import six
def jid_to_time(jid):
"""
Convert a salt job id into the time when the job was invoked
"""
jid = six.text_type(jid)
if len(jid) != 20 and (len(jid) <= 21 or jid[20] != "_"):
return ""
year = jid[:4]
month = jid[4:6]
day = jid[6:8]
hour = jid[8:10]
minute = ji... | 1b32020476cc60ade1baac6a14054bde005bb8b9 | 3,613,458 |
def iotc_connect_by_uid_parallel(
tutk_platform_lib: CDLL, p2p_id: str, session_id: c_int
) -> c_int:
"""Used by a client to connect a device and bind to a specified session ID.
This function is for a client to connect a device by specifying the UID of that device,
and bind to a tutk_platform_free sess... | cea50ae94370fe0930e8ad23f8fc9e9810f0cfbd | 3,613,459 |
from typing import Iterator
from typing import Callable
from typing import Optional
import multiprocessing
import importlib
def import_entry_point() -> Iterator[Callable[[str], Optional[int]]]:
"""
Yields a function that imports a module in a seperate Python process and returns the exit code.
"""
cont... | 07b5cb8620cee039351cc894707eb8fe3c457daf | 3,613,460 |
import numpy
def sort_radius_front_to_back(
render_position,
render_direction,
objects,
object_positions
):
"""Sorts objects from front to back based on their distance
from the camera.
:param numpy.array render_position: The position of the camera the scene
is being rendered f... | 58bc47bc729c695c005a26b7df7d67f3d2791c51 | 3,613,461 |
def preprocess_inputs(batched_data, max_sub_l, max_vcpt_l, max_vid_l, device="cuda:0"):
"""clip and move to target device"""
max_len_dict = {"sub": max_sub_l, "vcpt": max_vcpt_l, "vid": max_vid_l}
text_keys = ["q", "a0", "a1", "a2", "a3", "a4", "sub", "vcpt"]
label_key = "answer_idx"
qid_key = "qid"... | a453e68f6b799ef3215befeacf8d93704ecc3fcc | 3,613,462 |
def make_diff_prop_modified(pname, pval1, pval2):
"""Return a property diff for modification of property PNAME, old value
PVAL1, new value PVAL2. PVAL is a single string with no embedded
newlines. Return the result as a list of newline-terminated strings."""
return [
"Modified: " + pname + "\n",
... | b4201b178a1438075bc84048057f100d337abe99 | 3,613,463 |
import scipy
def mean_confidence_interval(data, confidence=0.95):
"""
Calculates 95% confidence intervals (CI).
Taken from: https://stackoverflow.com/questions/15033511/compute-a-confidence-interval-from-sample-data
: data (pd.DataFrame):
: confidence (float):
"""
a = 1.0 * ... | 60ca47d15287cd88cf1599c9987ddca6bf35778e | 3,613,464 |
import torch
from typing import Optional
from typing import Union
from typing import Tuple
def wmean(
x: torch.Tensor,
weight: Optional[torch.Tensor] = None,
dim: Union[int, Tuple[int]] = -2,
keepdim: bool = True,
eps: float = 1e-9,
) -> torch.Tensor:
"""
Finds the mean of the input tensor... | db742eb5d899b190609a8e40cd9e4a65f52a45cd | 3,613,465 |
def GetDeleteSQLByName(name):
"""获取 Delete 配置 SQL 语句"""
PS = __ParserSQL__()
return PS.GetDeleteSQLByName(name) | ffc0c999b7a0aa595e53008d3688abe6ccdd6c8f | 3,613,466 |
import os
def CPUs():
"""
Detects the number of CPUs on a system. Cribbed from pp.
"""
global cpu_count
if cpu_count is None:
cpu_count = 1 # default
# Linux, Unix and MacOS:
if hasattr(os, "sysconf"):
if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
... | 42508475beb65d01b18840730d5ffd5d456876df | 3,613,467 |
def authorized_access(response):
"""Check if access is authorized"""
return check_uuid(response.headers.get("Bearer")) | 1f636ca56b0215fcba1be77c3f308a4db06f3fce | 3,613,468 |
def language_is_allowed(code):
"""
Check a language code is valid
"""
return code in get_language_dict() | fc9fc5f890d56a61b5a7389dc507c256e675f9fd | 3,613,469 |
def calculate_distance(vector1, vector2):
"""
Calculates Euclidean distance between two vectors.
:param vector1:vector presents a face feature
:param vector2:vector presents a face feature
:return:disance:the Euclidean distance between vector1 and vector2.
"""
temp = vector1 - vector2
di... | 9f3d296486a8291a35becb01fcd8d8fb6f86979c | 3,613,470 |
import torch
def classify(img, is_url=False):
""" Runs the given image through the model and returns the results. """
data = ImageData([[True], [img]]) if not is_url else ImageData([[True], [img]], is_url=True) # pass image to be "tensorized"
tensor_image, _, img_path = data[0] # get image tensor etc
... | 8c29952940921354bce0da83a925d9b44ffecc5f | 3,613,471 |
def rb_interleaved_execution(rb_opts: dict, shots: int):
"""
Create interleaved rb circuits with depolarizing error and simulate them
Args:
rb_opts: the options for the rb circuits
shots: number of shots for each circuit simulation
Returns:
list: list of ... | ac80fa28dd0d0f704c20c40c77c69bfccd75ae7f | 3,613,472 |
def nd_to_columns(data, layers, rows, columns):
"""
Reshapes an array from nd layout to [samples (rows*columns) x dimensions]
"""
if layers == 1:
return np.ascontiguousarray(data.flatten()[:, np.newaxis])
else:
return np.ascontiguousarray(data.transpose(1, 2, 0).reshape(rows*column... | accc6c2492a3fb4c047da6c0331137829c669b61 | 3,613,473 |
def server_error(exception):
"""Return True if we should retry (in this case when it's an ServerError, False otherwise"""
return isinstance(exception, ServerError) or isinstance(exception, ConnectionError) | 4c70e2c12a455e947e23e027d639af518b289d4a | 3,613,474 |
def lat_weights_regular_grid(lat):
"""
Generate latitude weights for equally spaced (regular) global grids.
Weights are computed as sin(lat+dlat/2)-sin(lat-dlat/2) and sum to 2.0.
"""
dlat = np.abs(np.diff(lat))
np.testing.assert_almost_equal(dlat, dlat[0])
w = np.abs(np.sin(np.radians(lat +... | 97bba018efefca2a05466ff633de187c085a6bc7 | 3,613,475 |
def get_universe(name, cache=False, environ=None):
"""
Parameters
----------
name: str
cache:
Returns
-------
AbstractUniverse
"""
# cache universe in case we use it in-memory...
if name == 'test':
return TestUniverse(cache)
elif name == 'quandl':
retu... | 23c231b0de267dba320b81477c1dc71a8c78b490 | 3,613,476 |
def batch_normalization(x, mean, variance, offset, scale, variance_epsilon, data_format, name=None):
"""Data Format aware version of tf.nn.batch_normalization."""
if data_format == 'channels_last':
mean = tf.reshape(mean, [1] * (len(x.shape) - 1) + [-1])
variance = tf.reshape(variance, [1] * (le... | 70001b2df1463075de975d4ce931bf09ec7d6fa7 | 3,613,477 |
def explore_CordAttractor(N=10, angle=0.0, max_time=4.0,
a=0.25, b=4.0, F=8.0, G=1.0,
Plot=False):
"""
You can use it with animated widgets:
from IPython.html.widgets import interact, interactive
w = interactive(solve_lorenz, angle=(0.,360.), N=(0,50), sigma=(0.0,50.0), rho=(0.0,5... | 22c26a1512b424edf15ab258d723ae460c74a4d7 | 3,613,478 |
def get_current_user(sql: Session = Depends(db_session), token: str = Depends(oauth2_scheme)):
"""get authenticated user"""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
... | 55d327e234def0acfcd8bd7bdbcc30867e5c6bb7 | 3,613,479 |
def long_from_bytes(data):
"""
Return an integer from base64-encoded string.
:param data: UTF-8 string containing base64-encoded data.
:returns: Corresponding decoded integer.
"""
return int.from_bytes(decode_base64(data.encode("ascii")), 'big') | 08d5d378c1c14684b8321be8a123897a3ddfa368 | 3,613,480 |
import logging
import os
import requests
import tqdm
import shutil
def download_model(name: str, download_dir: str, cache_dir: str, force_download: bool, logger: logging.Logger) -> str:
"""
Downloads and extracts a model into cache dir and returns the path to the model directory
:param name: unique name... | c9f7ea63afc75381f6ea9ff70de71efacab837e0 | 3,613,481 |
from lingcod.common import uaparser
def valid_browser(ua):
"""
Returns boolean depending on whether we support their browser
based on their HTTP_USER_AGENT
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_... | dc8bdf87633caf8547d1f6962718ded748c78510 | 3,613,482 |
def openREADME():
"""
This is only needed because README.rst is UTF-8 encoded and that won't work
under python3 iff sys.getfilesystemencoding() returns 'ascii'
Since open() doesn't accept an encoding in python2...
"""
try:
f = open("README.rst", encoding="utf-8")
except:
f =... | d42e07721f40d7681a9a8a22787a4ba9ac78ec8d | 3,613,483 |
from pathlib import Path
import os
def draw_one_smarts_subset_relation(directed_edge: DirectedEdge,
viewer_path: str,
output_path: str):
"""
Draws one DirectedEdge, i.e., a subset relationship from directed_edge.from_smarts to
directe... | 6eca35172d2be0e83e1d98d78deab7e28f64bf77 | 3,613,484 |
def set_host_enabled(self, arg_dict):
"""Sets this host's ability to accept new instances.
It will otherwise continue to operate normally.
"""
enabled = arg_dict.get("enabled")
if enabled is None:
raise pluginlib.PluginError(
"Missing 'enabled' argument to set_host_enabled")
... | 2db8f0c8c9a97edab4042df6cc6773fb2e007b4a | 3,613,485 |
from datetime import datetime
def to_local_js_timestamp(utc_datetime):
"""Convert a UTC datetime into a local time timestamp suitable for the JavaScript date object"""
return int(datetime.timestamp(utc_datetime.replace(tzinfo=timezone.utc).astimezone(tz=None)) * 1000) | c44a2482d2990ff297bce9ad16a77adb51e7030f | 3,613,486 |
def userfcn_dcline_formulation(om, args):
"""This is the 'formulation' stage userfcn callback that defines the
user constraints for the dummy generators representing DC lines.
It expects to find a 'dcline' field in the ppc stored in om, as
described above. By the time it is passed to this callback,
... | 05db608241bfb3108c235ccec8339781c727c325 | 3,613,487 |
def read_raw(path):
"""Return the contents of `path`.
Parameters
==========
path : string
Input data file (may be compressed)
Returns
=======
data : pandas DataFrame
Contents of `path`
"""
# Set compression type
if path.endswith('.gz'):
compression = 'g... | bdceb6d53efee02d6944ac8e4249534d1db6784f | 3,613,488 |
from sys import modules
def get_module_version_list(module_list, tainted):
"""Returns a list of pairs (module name, version name) to fetch logs for.
Arguments:
module_list: list of modules to list, defaults to all modules.
tainted: if False, excludes versions with '-tainted' in their name.
"""
result... | ffd9f7911e9215034a76bcba5651ff004695c8dc | 3,613,489 |
def get_distrib_param_vars(
distrib_id,
init_params,
const_params=None,
num_class=None,
random_seed=None,
alt_distrib=False
):
"""Creates tfp.distribution and tf.Variables for the distribution's
parameters.
Parameters
----------
distrib_id : str
Name of the distribut... | cf034d1ee204a455c636b7afffd70dec225c3ed1 | 3,613,490 |
def _assign_interval_base(x, boundaries):
"""Assign each value in x an interval from boundaries.
Parameters
----------
x: numpy.array, shape (number of examples,)
The column of data that need to be discretized.
boundaries: numpy.array, shape (number of interval boundaries,)
... | 5d407ce565b188eff9248041b01796e289f2231c | 3,613,491 |
def angle_between_vectors(v1, v2, v3):
"""
Compute the angle between the vector (v2, v3) and (v1, v2)
The angle is constrained to lie in [-np.pi, np.pi]
No turn will result in an angle of 0.
A left turn will produce a positive angle.
A right turn will produce a negative angle.
The function... | a23042e6ac0a99a9065ac6c897abaad632b99ef6 | 3,613,492 |
import os
def get_config_parameter_path(param_name):
"""Finds path where Config parameter is stored.
Paramters
---------
param_name: str
Name of parameter
Returns
-------
If parameter is overridden in Model Instance, then path of
parameter from Model Instance is returned ... | 2516bec24078baa4194a034a28c9cb484393344f | 3,613,493 |
def ts(nodes, topo_order): # topo must be a list of names
"""
Orders nodes by their topological order
:param nodes: Nodes to be ordered
:param topo_order: Order to arrange nodes
:return: Ordered nodes (indices)
"""
node_set = set(nodes)
return [n for n in topo_order if n in node_set] | 741c7b3ac34c9f5beb6dc57ebf1539a27cc2b91b | 3,613,494 |
def energy_loss(ef_energy='x', gv_energy='x', n='x'):
"""
Calculate and return the value of energy loss using given values of the params
How to Use:
Give arguments for ef_energy and gv_energy parameters
or,give arguments for efficiency and gv_energy parameters
*USE KEYWORD ARGUMENTS FOR... | 868a5fa02beeda29fd053973c7cf999a1ed3ed22 | 3,613,495 |
def normalize_min_max(x, axis=None):
"""
Parameters:
----------
x: np.array()
target array
axis: int
target axis
Returns:
----------
np.array()
normalized array so that the maximum value is 1 and the minimum value is 0
"""
min = x.min(axis=axis, keepdims... | fddc3886f12d312994165641704207d97fcc1331 | 3,613,496 |
def get_2nd_or_3rd():
"""
Returns all 2nd or 3rd degree connections for a user
http://127.0.0.1:5000/2nd3rd/?ourid=3
"""
args = request.args
ourid = args['ourid']
return jsonify({'result' : n4jinstance.get_2nd_or_3rd(ourid) }) | c5a36d5d7785a7ec304f42b5552b9777c2a57c68 | 3,613,497 |
def get_features_route(model_name: str, file_hash: str) -> str:
"""Gets the features of a file from the dataset.
Args:
model_name (str): Name of the model
file_hash (str): Hash of the file
Raises:
PredictionNotCalledFirstError: The prediction route was not called
before... | 65238f3e031df5c0a432b6f9675ead9348a2e868 | 3,613,498 |
def fitted_predicted_OK3(X, y, Tree):
"""Function running OK3 and returning Y_train, Y_test, and Y_preds, for readability purposes
Parameters
----------
X : np.ndarray
features of the dataset
y : np.ndarray
labels of the dataset
Tree : estimator
estimator to fit and pred... | 7507deb4f6ad3091eff837e397c5c4b95150ae18 | 3,613,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.