content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def rayleigh(gamma, M0, TtR):
"""
Function that takes in a input (output) Mach number and a stagnation
temperature ratio and yields an output (input) Mach number, according
to the Rayleigh flow equation. The function also outputs the stagnation
pressure ratio
Inputs:
M [dimension... | f1432158136bee529ec592f7ef539f2aac19e5f5 | 32,900 |
def attack(N, e, c, oracle):
"""
Recovers the plaintext from the ciphertext using the LSB oracle attack.
:param N: the modulus
:param e: the public exponent
:param c: the encrypted message
:param oracle: a function which returns the last bit of a plaintext for a given ciphertext
:return: the... | 3fe99894909c07da0dc42fc1101bb45853e3366f | 32,901 |
from typing import Optional
from typing import Union
from typing import Dict
from typing import Any
def setup_wandb_logging(
trainer: Engine,
optimizers: Optional[Union[Optimizer, Dict[str, Optimizer]]] = None,
evaluators: Optional[Union[Engine, Dict[str, Engine]]] = None,
log_every_iters: int = 100,
... | caf67149d8aa8d2b85f07f96b4d55677183c594b | 32,902 |
def _norm(X, y):
"""Scales data to [0..1] interval"""
X = X.astype(np.float32) / (X.max() - X.min())
return X, y | 87189d4c885d77654793373416c0d5c4be498fba | 32,903 |
import os
def check_directory(directory, verbose):
"""
Inputs: graph_directory- the directory for the graphs to be place
verbose- the verbose flag
Checks to see if the graph directory exists. If it doesn't exit, the
folder is created.
"""
cwd = os.getcwd() + '/'
if not os... | 2d76f00f4438a97e4fc91d3b23b74c94015385c5 | 32,904 |
from typing import Dict
from typing import Any
from typing import List
from datetime import datetime
import logging
import os
def compute_single_lesson_score(
lesson_metadata: Dict[str, Any],
df: pd.DataFrame,
slide_columns: List[str],
due_date: datetime.datetime,
) -> pd.Series:
"""Takes a DataFr... | b93e1dd9f6ecdfd3764320a76c208025dbe25375 | 32,905 |
async def delete_layer(location_id, layer_id):
"""
Delete layer
---
delete:
summary: Delete layer
tags:
- layers
parameters:
- name: id
in: path
required: true
description: ID of the object to be deleted
responses:
... | 537ea3907fef2998ca8ae960a05a2e5204b4ab7e | 32,906 |
def fit_and_save_model(params, data, targets):
"""Fit xgb classifier pipeline with params parameters and
save it to disk"""
pipe = make_pipeline(StandardScaler(),
XGBClassifier(learning_rate=params['learning_rate'],
max_depth=int(params['max_de... | 589dd94f0a258f8eabcbd47b2341a71303c5d6b7 | 32,907 |
def relu_backward(dout, cache):
"""
Backward pass for the ReLU function layer.
Arguments:
dout: numpy array of gradient of output passed from next layer with any shape
cache: tuple (x)
Output:
x: numpy array of gradient for input with same shape of dout
... | 3384ddf789ed2a31e25a4343456340a60e5a6e11 | 32,908 |
def run_decopath(request):
"""Process file submission page."""
# Get current user
current_user = request.user
user_email = current_user.email
# Check if user submits pathway analysis results
if 'submit_results' in request.POST:
# Populate form with data from the request
results... | d86d21a31004f971e2f77b11040e88dcd2a26ee4 | 32,909 |
import tqdm
def load_abs_pos_sighan_plus(dataset=None, path_head=""):
"""
Temporary deprecation !
for abs pos bert
"""
print("Loading Expanded Abs_Pos Bert SigHan Dataset ...")
train_pkg, valid_pkg, test_pkg = load_raw_lattice(path_head=path_head)
tokenizer_model_name_path="hfl/chinese... | 8da548c4586f42c8a7421482395895b56aa31a10 | 32,910 |
def _train_on_tpu_system(model_fn_wrapper, dequeue_fn):
"""Executes `model_fn_wrapper` multiple times on all TPU shards."""
config = model_fn_wrapper.config.tpu_config
iterations_per_loop = config.iterations_per_loop
num_shards = config.num_shards
single_tpu_train_step = model_fn_wrapper.convert_to_single_tp... | faad0d857b2741b5177f348a6f2b7a54f9470135 | 32,911 |
def get_docs_url(model):
"""
Return the documentation URL for the specified model.
"""
return f'{settings.STATIC_URL}docs/models/{model._meta.app_label}/{model._meta.model_name}/' | 613cb815ff01fa13c6c957f47c0b5f3f7edcff8f | 32,912 |
import random
def _fetch_random_words(n=1000):
"""Generate a random list of words"""
# Ensure the same words each run
random.seed(42)
# Download the corpus if not present
nltk.download('words')
word_list = nltk.corpus.words.words()
random.shuffle(word_list)
random_words = word_lis... | aaf257e3b6202555b29bdf34fd9342794a5acf6f | 32,913 |
import json
def cache_pdf(pdf, document_number, metadata_url):
"""Update submission metadata and cache comment PDF."""
url = SignedUrl.generate()
content_disposition = generate_content_disposition(document_number,
draft=False)
s3_client.put_object... | 44ffd6841380b9454143f4ac8c71ef6ea560030a | 32,914 |
def get_tile_list(geom,
zoom=17):
"""Generate the Tile List for The Tasking List
Parameters
----------
geom: shapely geometry of area.
zoom : int Zoom Level for Tiles
One or more zoom levels.
Yields
------
list of tiles that intersect with
"""
west,... | dcceb93b13ce2bbd9e95f664c12929dee10a1e63 | 32,915 |
def findTolerableError(log, file='data/psf4x.fits', oversample=4.0, psfs=10000, iterations=7, sigma=0.75):
"""
Calculate ellipticity and size for PSFs of different scaling when there is a residual
pixel-to-pixel variations.
"""
#read in PSF and renormalize it
data = pf.getdata(file)
data /= ... | 02b1771e4a363a74a202dd8d5b559efd68064f4d | 32,916 |
def squeeze_labels(labels):
"""Set labels to range(0, objects+1)"""
label_ids = np.unique([r.label for r in measure.regionprops(labels)])
for new_label, label_id in zip(range(1, label_ids.size), label_ids[1:]):
labels[labels == label_id] == new_label
return labels | 9c78f5e103fa83f891c11477d4cea6fdac6e416d | 32,917 |
import itertools
def orient_edges_gs2(edge_dict, Mb, data, alpha):
"""
Similar algorithm as above, but slightly modified for speed?
Need to test.
"""
d_edge_dict = dict([(rv,[]) for rv in edge_dict])
for X in edge_dict.keys():
for Y in edge_dict[X]:
nxy = set(edge_dict[X]) - set(edge_dict[Y]) - {Y}
for ... | 272bdd74ed5503851bd4eb5519c505d8583e3141 | 32,918 |
def _divide_evenly(start, end, max_width):
""" Evenly divides the interval between ``start`` and ``end`` into
intervals that are at most ``max_width`` wide.
Arguments
---------
start : float
Start of the interval
end : float
End of the interval
max_width : float
... | 08647cc55eca35447a08fd4ad3959db56dffc565 | 32,919 |
def uncompress_pubkey(pubkey):
""" Convert compressed public key to uncompressed public key.
Args:
pubkey (str): Hex encoded 33Byte compressed public key
Return:
str: Hex encoded uncompressed 65byte public key (4 + x + y).
"""
public_pair = encoding.sec_to_public_pair(h2b(pubkey))
... | 672f89482e5338f1e23cbe21823b9ee6625c792f | 32,920 |
def make_celery(main_flask_app):
"""Generates the celery object and ties it to the main Flask app object"""
celery = Celery(main_flask_app.import_name, include=["feed.celery_periodic.tasks"])
celery.config_from_object(envs.get(main_flask_app.config.get("ENV"), "config.DevConfig"))
task_base = celery.T... | 57fc0d7917b409cb36b4f50442dd357d384b3852 | 32,921 |
def adjustForWeekdays(dateIn):
""" Returns a date based on whether or not the input date
is on a weekend. If the input date falls on a Saturday or
Sunday, the return is the date on the following Monday. If
not, it returns the original date. """
#If Saturday, return the following Monday.
if dat... | 9db5c3fadbcb8aeb77bfc1498333d6b0f44fd716 | 32,922 |
def composed_model_input_classes(cls):
"""
This function returns a list of the possible models that can be accepted as
inputs.
TODO: lru_cache this
"""
if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES:
return [cls]
elif issubclass(cls, ModelNormal):
if cls.discrimina... | 98b248aa769391a9edd99eb8184e0af44c40d020 | 32,923 |
import os
def via_sudo():
"""
Return `True` if Blueprint was invoked via `sudo`(8), which indicates
that privileges must be dropped when writing to the filesystem.
"""
return 'SUDO_UID' in os.environ \
and 'SUDO_GID' in os.environ \
and 'blueprint' in os.environ.get('SUDO_COMMAND',... | c30c3e21f5bd780e42c37a0248a1406edf44bd44 | 32,924 |
from datetime import datetime
def get_user_or_add_user(spotify_id, display_name, display_image=None, token=None):
"""Fetch an existing user or create a user"""
user = User.query.filter(User.spotify_id == spotify_id).first()
if user is None:
spotify_id = spotify_id
spotify_display_name =... | 27f0fffcaf10e4060860c39f1df54afe21814250 | 32,925 |
from bs4 import BeautifulSoup
def get_daily_data(y, m, d, icao):
"""
grab daily weather data for an airport from wunderground.com
parameter
---------
y: year
m: month
d: day
ICAO: ICAO identification number for an airport
return
------
a di... | 35abfda3ed6f80c213099149d5a3009c03be1d48 | 32,926 |
def create_CIM_object(cimpath):
"""This function aims to speed up other bits of this and ``cgrid``
modules, by returning a ``casacore.images.image.image`` object.
The trick is, that the ``cimpath`` argument can be either a string i.e. the path
to the CASAImage wich will be read in and returned, **or** ... | 25ece938101b0b1ad65379e3fab9552e74d9e735 | 32,927 |
def image_tag_create(context, image_id, value, session=None):
"""Create an image tag."""
session = session or get_session()
tag_ref = models.ImageTag(image_id=image_id, value=value)
tag_ref.save(session=session)
return tag_ref['value'] | 5aaa684912ae18fe98beb1d62d1c219239c013c6 | 32,928 |
def test_branch_same_shape():
"""
Feature: control flow function.
Description: Two branch must return the same shape.
Expectation: Null.
"""
class Net(Cell):
def __init__(self):
super().__init__()
self.a = 1
def construct(self, x, y):
for k i... | 57326097cb0da2c3982aea2cfeee5be19923b4cf | 32,929 |
def potential(__func__=None, **kwds):
"""
Decorator function instantiating potentials. Usage:
@potential
def B(parent_name = ., ...)
return baz(parent_name, ...)
where baz returns the deterministic B's value conditional
on its parents.
:SeeAlso:
Deterministic, deterministic,... | 5023755aee2d887eb0077cb202c01013dda456e8 | 32,930 |
def numBytes(qimage):
"""Compatibility function btw. PyQt4 and PyQt5"""
try:
return qimage.numBytes()
except AttributeError:
return qimage.byteCount() | a2e5bfb28ef679858f0cdb2fb8065ad09b87c037 | 32,931 |
def _dt_to_decimal_time(datetime):
"""Convert a datetime.datetime object into a fraction of a day float.
Take the decimal part of the date converted to number of days from 01/01/0001
and return it. It gives fraction of way through day: the time."""
datetime_decimal = date2num(datetime)
time_d... | febcaa0779cbd24340cc1da297e338f1c4d63385 | 32,932 |
def poll_create(event, context):
"""
Return true if the resource has been created and false otherwise so
CloudFormation polls again.
"""
endpoint_name = get_endpoint_name(event)
logger.info("Polling for update of endpoint: %s", endpoint_name)
return is_endpoint_ready(endpoint_name) | 3ac7dd8a4142912035c48ff41c343e5d56caeba3 | 32,933 |
def outsatstats_all(percent, Reads_per_CB, counts, inputbcs):
"""Take input from downsampled bam stats and returns df of genes, UMIs and reads for each bc.
Args:
percent (int): The percent the bamfile was downsampled.
Reads_per_CB (file path): Space delimited file of the barcodes and # of reads... | f6d320e10c3171c543afdc6bdf70d83f5bcfb030 | 32,934 |
import os
def relative_uri(source, target):
"""
Make a relative URI from source to target.
"""
su = patched_urllib_parse.urlparse(source)
tu = patched_urllib_parse.urlparse(target)
extra = list(tu[3:])
relative = None
if tu[0] == '' and tu[1] == '':
if tu[2] == su[2]:
... | d125b3d40b97812a3cfe2b2ebb97ec98abdf6468 | 32,935 |
import os
import pickle
def fill_gaps_batch(slice_list, acq_datelist, training_data_path, cluster_model_path, outDir=None, cpu=20, reg_kws=None):
"""
This function fills gaps for a slice of time series.
Parameters
----------
slice_list: list
Specification of list of slice time series... | dabec97b80271bb8c9431c23071d67a037b9d6cf | 32,936 |
from typing import Optional
from typing import List
import random
import itertools
def generate_sums(
n: int, min_terms: int, max_terms: int, *, seed=12345, fold=False, choose_from=None
) -> Optional[List[ExprWithEnv]]:
""" Generate the specified number of example expressions (with no duplicates).
The... | 26dbd81ec62fe15ff6279356bb5f41f894d033d2 | 32,937 |
import string
import sys
def convert_from_string(str_input_xml):
"""Convert a string into a Python data structure type.
> *Input arguments*
* `str_input_xml` (*type:* `str`): Input string
> *Returns*
`bool`, `int`, `float`, list of `float` or `str`.
"""
if str_input_xml is None:
... | 9c1637919fb2f8e03a1cae8823cbe2593d626c70 | 32,938 |
def arr2pil(frame: npt.NDArray[np.uint8]) -> Image.Image:
"""Convert from ``frame`` (BGR ``npt.NDArray``) to ``image`` (RGB ``Image.Image``)
Args:
frame (npt.NDArray[np.uint8]) : A BGR ``npt.NDArray``.
Returns:
Image.Image: A RGB ``Image.Image``
"""
return Image.fromarray(cv2.cvtCo... | 5878d983055d75653a54d2912473eacac3b7501d | 32,939 |
def sophos_firewall_app_category_update_command(client: Client, params: dict) -> CommandResults:
"""Update an existing object
Args:
client (Client): Sophos XG Firewall Client
params (dict): params to update the object with
Returns:
CommandResults: Command results object
"""
... | 1ba77c9b2ad172e2d9c508c833a7d4b08fb5b876 | 32,940 |
import collections
def find_identities(l):
"""
Takes in a list and returns a dictionary with seqs as keys and positions of identical elements in list as values.
argvs: l = list, e.g. mat[:,x]
"""
# the number of items in the list will be the number of unique types
uniq = [item for item, coun... | db7b64cc430ab149de7d14e4f4a88abafbadbe34 | 32,941 |
def decode_event_to_internal2(event):
""" Enforce the binary encoding of address for internal usage. """
data = event.event_data
# Note: All addresses inside the event_data must be decoded.
if data['event'] == EVENT_TOKEN_ADDED2:
data['token_network_address'] = to_canonical_address(data['args']... | fdacba3f496f5aa3715b8f9c4f26c54a21ca3472 | 32,942 |
def _repeated_features(n, n_informative, X):
"""Randomly select and copy n features from X, from the col
range [0 ... n_informative].
"""
Xrep = np.zeros((X.shape[0], n))
for jj in range(n):
rand_info_col = np.random.random_integers(0, n_informative - 1)
Xrep[:, jj] = X[:, rand_info... | f15811a34bcc94fff77812a57a2f68178f7a8802 | 32,943 |
def create_auto_edge_set(graph, transport_guid):
"""Set up an automatic MultiEdgeSet for the intersite graph
From within MS-ADTS 6.2.2.3.4.4
:param graph: the intersite graph object
:param transport_guid: a transport type GUID
:return: a MultiEdgeSet
"""
e_set = MultiEdgeSet()
# use a ... | 5f6832506d0f31795dd82f92416bb532cc7237fe | 32,944 |
def jaccard(box_a, box_b):
"""Compute the jaccard overlap of two sets of boxes. The jaccard overlap
is simply the intersection over union of two boxes. Here we operate on
ground truth boxes and default boxes.
E.g.:
A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)
Args:
box_a: (t... | fc72ebcaa47b7f0f1f27a0618cbe7592ada5ad70 | 32,945 |
def concat(input, axis, main_program=None, startup_program=None):
"""
This function concats the input along the axis mentioned
and returns that as the output.
"""
helper = LayerHelper('concat', **locals())
out = helper.create_tmp_variable(dtype=helper.input_dtype())
helper.append_op(
... | 55a6e8704141a45a135402dac10d6793f2ae6a28 | 32,946 |
def is_available():
"""Return true if a pdfjs installation is available."""
try:
get_pdfjs_res('build/pdf.js')
get_pdfjs_res('web/viewer.html')
except PDFJSNotFound:
return False
else:
return True | d345ca0b881ecc749fcea8ec4f579f9ba05f25c4 | 32,947 |
def reissueMissingJobs(updatedJobFiles, jobBatcher, batchSystem,
childJobFileToParentJob, childCounts, config,
killAfterNTimesMissing=3):
"""Check all the current job ids are in the list of currently running batch system jobs.
If a job is missing, we mark it as so, ... | 6ac051049f1e454fdc92a1a136ef4736e602d121 | 32,948 |
def all_children(wid):
"""Return all children of a widget."""
_list = wid.winfo_children()
for item in _list:
if item.winfo_children():
_list.extend(item.winfo_children())
return _list | ca52791b06db6f2dd1aeedc3656ecf08cb7de6d8 | 32,949 |
def logout():
"""------------- Log out -----------------------"""
# remove user session cookies
flash("You Have Been Logged Out")
session.pop("user")
return redirect(url_for("login")) | 66577a335a3e86c56c2aa78afacef4817786ac30 | 32,950 |
def listtodict(l: ty.Sequence) -> ty.Mapping:
"""Converts list to dictionary"""
return dict(zip(l[::2], l[1::2])) | 80e645c3b7834e4fd5980fdb3e5df75114e0da82 | 32,951 |
def sqrtspace(a, b, n_points):
"""
:return: Distribute n_points quadratically from point a to point b, inclusive
"""
return np.linspace(0, 1, n_points)**2*(b-a)+a | d88f3cd808dbab7447cf9609e3770a15e703e515 | 32,952 |
from datetime import datetime
def tstr2iso(input_string: str) -> datetime:
"""
Convert a specific type of ISO string that are compliant with file pathing requirement to ISO datetime.
:return:
"""
no_colon_input_string = input_string.replace(":", "")
iso_datetime = tstr2iso_nocolon(no_colon_inp... | bb591dceef294c36eb9c028b5e28979c37f05a16 | 32,953 |
def test_processing_hooks_are_inherited():
"""Processing hooks are inherited from base classes if missing.
"""
class TestView(DummyBase):
def __call__(self, *args, **kwargs):
return self.count
testview = create_view(TestView)
assert [testview(), testview(), testview()] == [2, 4, ... | 465303560f95c098c891361b504238dc4fe22adb | 32,954 |
import argparse
from astrometry.util.plotutils import PlotSequence
from astrometry.util.multiproc import multiproc
from re import I
def main():
"""Main program.
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--force', action='store_true',
help='Run... | 3001a16aaab01ef826d2f4c9555686e24b6061b6 | 32,955 |
def lesson(request, order, slug):
"""
One lesson can be viewed in two different ways:
(1) as independent lesson
(2) as part of one course
As (1) it is well, independent. And it is not really
important to jump to next in order lesson or not.
It is more important in this conetxt to d... | 7365179a033728f6208d26e666929f8b414c8d72 | 32,956 |
def getNum(n, res_num):
"""TODO: docstring"""
res, num = res_num
try:
idx = res.index(n)
return num[idx]
except ValueError:
raise ValueError(f'{n} is not in a list of residues!') | 3eff8e3b6f2ede791f9c2c98218d13585a98e8b3 | 32,957 |
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# ... | 393435da9d7d638be0e7461ec5251a1485649d7f | 32,958 |
def dEuler212(q, w):
"""
dEuler212(Q,W)
dq = dEuler212(Q,W) returns the (2-1-2) euler angle derivative
vector for a given (2-1-2) euler angle vector Q and body
angular velocity vector w.
dQ/dt = [B(Q)] w
"""
return np.dot(BmatEuler212(q), w) | 567a7a452c1e86a01854d63b0fd2efb0ea951fcd | 32,959 |
from typing import Callable
import functools
def with_zero_out_padding_outputs(
graph_net: Callable[[gn_graph.GraphsTuple], gn_graph.GraphsTuple]
) -> Callable[[gn_graph.GraphsTuple], gn_graph.GraphsTuple]:
"""A wrapper for graph to graph functions that zeroes padded d output values.
See `zero_out_padding` f... | 5f23defb49df229b2edec46f1f018a25401ca3f4 | 32,960 |
def as_bytes(x) -> bytes:
"""Convert a value to bytes by converting it to string and encoding in utf8."""
if _is_bytes(x):
return bytes(x)
if not isinstance(x, str):
x = str(x)
return x.encode('utf8') | 2c1c48bd1b02f290ec33dc427ebc4536ba2f2caf | 32,961 |
def getGeneCount(person, geneSetDictionary):
"""
determines how many genes a person is assumed to have based upon the query information provided
"""
if person in geneSetDictionary["no_genes"]:
gene_count = 0
elif person in geneSetDictionary["one_gene"]:
gene_count = 1
else:
... | 0fef236dd805ae77f04a22670752031af15ca5b2 | 32,962 |
import json
def merge_json(*args):
"""
Take a list of json files and merges them together
Input: list of json file
Output: dictionary of merged json
"""
json_out = dict()
for json_file in args:
try:
if isinstance(json_file, dict):
json_out = {**json_ou... | 37d5e29468d2de2aa11e5a92dc59b7b7b28a170d | 32,963 |
import functools
def hyp2f1_small_argument(a, b, c, z, name=None):
"""Compute the Hypergeometric function 2f1(a, b, c, z) when |z| <= 1.
Given `a, b, c` and `z`, compute Gauss' Hypergeometric Function, specified
by the series:
`1 + (a * b/c) * z + (a * (a + 1) * b * (b + 1) / ((c * (c + 1)) * z**2 / 2 +
.... | 3088761e007a5f65ba4af0c1e739324ff30a8bae | 32,964 |
def get_KPP_PL_tag(last_tag, tag_prefix='T'):
""" Get the next P/L tag in a format T??? """
assert (len(last_tag) == 4), "Tag must be 4 characers long! (e.g. T???)"
last_tag_num = int(last_tag[1:])
return '{}{:0>3}'.format(tag_prefix, last_tag_num+1) | feb9cedce1fe4dd17aac3d28df25c951bb24cc3f | 32,965 |
from ibmsecurity.appliance.ibmappliance import IBMError
def update(isamAppliance, description, properties, check_mode=False, force=False):
"""
Update a specified Attribute Matcher
"""
id, update_required, json_data = _check(isamAppliance, description, properties)
if id is None:
raise IBMEr... | 2b7d90a15a65035aa623fc16dada0e76076221c1 | 32,966 |
import os
def name_has_image_suffix(fname):
"""Test whether file fname has an image suffix in the allowed list."""
extension = os.path.splitext(fname)[1]
return extension in allowed_image_file_suffixes | 644f91bccb2f688f7fcbc4fbe89bc1423664f6ed | 32,967 |
def get_all_themes(config, brand_id):
"""
Get all themes for the given brand id.
:param config: context config
:param brand_id: the brand id for the relevant help center
:return list: list of all themes
"""
url = f"https://{config['subdomain']}.zendesk.com/api/guide/theming/{brand_id}/themes... | 54e846e8cfbafc418fae3b57818632d1ef8bbb42 | 32,968 |
import logging
def maximum_radius_test(gpu_memory=None, number_of_gpu=None):
"""
:return:
"""
if gpu_memory is None and number_of_gpu is None:
gpu_memory, number_of_gpu = tfu.client.read_gpu_memory()
logging.info('GPU Memory={:.2f} Number of GPU={}'.format(gpu_memory, number_of_gpu))
i... | a422dd94e8003e25a011ff6f604c20c6b75a203f | 32,969 |
from vistrails.core.modules.basic_modules import Boolean, String, Integer, Float, List
from vistrails.core import debug
def get_module(value, signature):
"""
Creates a module for value, in order to do the type checking.
"""
if isinstance(value, Constant):
return type(value)
elif isinstan... | 1761f8bcb8275d00509ef26da2b40bfde94afbc1 | 32,970 |
def tca_plus(source, target):
"""
TCA: Transfer Component Analysis
:param source:
:param target:
:param n_rep: number of repeats
:return: result
"""
result = dict()
metric = 'process'
for src_name in source:
try:
stats = []
val = []
src... | 95242aa64db7b88a7f170abf619677c1d4acde57 | 32,971 |
def local_2d_self_attention_spatial_blocks(query_antecedent,
kv_channels,
heads,
memory_h_dim=None,
memory_w_dim=None,
... | 6295dff8753f4b577086fd414a386271ed6e1a1a | 32,972 |
def polling_locations_import_from_structured_json(structured_json):
"""
This pathway in requires a we_vote_id, and is not used when we import from Google Civic
:param structured_json:
:return:
"""
polling_location_manager = PollingLocationManager()
polling_locations_saved = 0
polling_loc... | 868062d4dac4a56073c832f7d2a2919a37a12203 | 32,973 |
def _mgSeqIdToTaxonId(seqId):
"""
Extracts a taxonId from sequence id used in the Amphora or Silva mg databases (ends with '|ncbid:taxonId")
@param seqId: sequence id used in mg databases
@return: taxonId
@rtype: int
"""
return int(seqId.rsplit('|', 1)[1].rsplit(':', 1)[... | 2ce74f453e3496c043a69b4205f258f06bfd0452 | 32,974 |
def has_progress(toppath):
"""Return `True` if there exist paths that have already been
imported under `toppath`.
"""
with progress_state() as state:
return len(state[toppath]) != 0 | 862c20336c7dd3b1b7d93022d4b633a9de89f336 | 32,975 |
def run_both_transfers(model: BiVAE, *args, **kwargs):
"""
Run both content-transfer and style-transfer on the each pair of the content-representative tensor images
:param model: Trained BiVAE model
:param class_reps: a dictionary of string class_id <-> a single 3dim Tensor (C,H,W)
:param log_dir: P... | 6d791931cda68b99701ccf407d78f1c470b124f0 | 32,976 |
def se_mobilenet_075():
"""
Construct SE_MobileNet.
"""
model = SE_MobileNet(widen_factor=0.75, num_classes=1000)
return model | 277d00141576f55dc6c41896725dcd2ee7c5a1d1 | 32,977 |
from pathlib import Path
def canonicalize_lookup_info(
lookup: SshPubKeyLookupInfo,
ssh_auth_dir_root: Path,
template_vars: SshPubKeyFileTemplateVars
) -> SshPubKeyLookupInfo:
"""Expand the template variables and ensure that paths are made absolute.
"""
ad_root = ssh_auth_dir_root
expd = e... | 24cb791ce5f0ea58daea268dc0e1804a3b056892 | 32,978 |
def reprojection_rms(impoints_known, impoints_reprojected):
"""
Compute root mean square (RMS) error of points
reprojection (cv2.projectPoints).
Both input NumPy arrays should be of shape (n_points, 2)
"""
diff = impoints_known - impoints_reprojected
squared_distances = np.sum(np.square(d... | 11bfbd994df21eb81581012313b838cf5e44424d | 32,979 |
import torch
def macro_accuracy_one_sub(**kwargs: dict) -> bool:
"""
Calculates whether the predicted output, after the postprocessing step of
selecting the single most 'changed' substation has been applied, wholly
matches the true output.
Differs from micro_accuracy_one_sub in that it doesn't che... | e21dcc6b2781abe9c7e5c0d03220d0624f68546c | 32,980 |
def modified_euler(f, y0, t0, t1, n):
""" Use the modified Euler method to compute an approximate solution
to the ODE y' = f(t, y) at n equispaced parameter values from t0 to t1
with initial conditions y(t0) = y0.
y0 is assumed to be either a constant or a one-dimensional numpy array.
t and t0 ... | c5549f194ee8fc446561967a49e89072abdad830 | 32,981 |
def read_tree(sha1=None, data=None):
"""Read tree object with given SHA-1 (hex string) or data, and return list
of (mode, path, sha1) tuples.
"""
if sha1 is not None:
obj_type, data = read_object(sha1)
assert obj_type == 'tree'
elif data is None:
raise TypeError('must specify... | 6d3fed787ba0e817ee67e9bfd99f5e2b6984684f | 32,982 |
def cluster(T, m):
"""
Runs PCCA++ [1] to compute a metastable decomposition of MSM states.
(i.e. find clusters using transition matrix and PCCA)
Parameters
----------
T: a probability transition matrix.
m : Desired number of metastable sets (int).
Notes
-----
The metastable de... | 7ba6f19d519d681b4b36c59409e617a9f1b385e5 | 32,983 |
def fine_tune_class_vector(nr_class, *, exclusive_classes=True, **cfg):
"""Select features from the class-vectors from the last hidden state,
softmax them, and then mean-pool them to produce one feature per vector.
The gradients of the class vectors are incremented in the backward pass,
to allow fine-tu... | 21359e128124f075ce4cf0768a24d1d5daaba4c2 | 32,984 |
def _recommend_aals_annoy(est, userid, R, n, filter_items,
recalculate_user, filter_previously_rated,
return_scores, recommend_function,
scaling_function, *args, **kwargs):
"""Produce recommendations for Annoy and NMS ALS algorithms"""
... | 76e258b64d080ef9804577c92bf41e4f4621f6c2 | 32,985 |
def url_to_filename(url):
"""Converts a URL to a valid filename."""
return url.replace('/', '_') | db3023c582590a47a6adc32501a2e3f5fd72f24f | 32,986 |
def _parallel_dict_from_expr_if_gens(exprs, opt):
"""Transform expressions into a multinomial form given generators."""
indices = {g: i for i, g in enumerate(opt.gens)}
zero_monom = [0]*len(opt.gens)
polys = []
for expr in exprs:
poly = {}
for term in Add.make_args(expr):
... | 81dec70ff041cb31062877e8b18823b8e4d283e0 | 32,987 |
def getMObjectHandle(value):
"""
Method used to get an MObjectHandle from any given value.
:type value: Union[str, om.MObject, om.MObjectHandle, om.MDagPath]
:rtype: om.MObjectHandle
"""
# Check for redundancy
#
if isinstance(value, om.MObjectHandle):
return value
else:
... | e41c7ccd48a5b8eb3b692730d4c6c8a74240f7dd | 32,988 |
def remove_dupes(inds1, inds2, inds3=None, inds4=None, tol=1e-6):
"""
Remove duplicates so as to not brake the interpolator.
Parameters
----------
inds1, inds2, inds3 : list or np.array()
to find unique values, must be same length
just_two : Bool [False]
do not include inds3
... | 6164e35d0b2c3b33d4e7a4f1737e356c096f2059 | 32,989 |
def filter_punctuation(fst: 'pynini.FstLike') -> 'pynini.FstLike':
"""
Helper function for parsing number strings. Converts common cardinal strings (groups of three digits delineated by 'cardinal_separator' - see graph_utils)
and converts to a string of digits:
"1 000" -> "1000"
"1.000.000" ... | 6e78d197fd4b05b66470622a0714bea0c4a935b4 | 32,990 |
def pixbuf2image(pix):
"""Convert gdkpixbuf to PIL image"""
data = pix.get_pixels()
w = pix.props.width
h = pix.props.height
stride = pix.props.rowstride
mode = "RGB"
if pix.props.has_alpha == True:
mode = "RGBA"
im = Image.frombytes(mode, (w, h), data, "raw", mode, stride)
r... | a44720fa3e40571d86e65b7f73cd660270919e67 | 32,991 |
def setup_s3_client(job_data):
"""Creates an S3 client
Uses the credentials passed in the event by CodePipeline. These
credentials can be used to access the artifact bucket.
Args:
job_data: The job data structure
Returns:
An S3 client with the appropriate credentia... | 98ff4d514734a5326dd709274bf0354e7d7cc255 | 32,992 |
async def get_subscriptions_handler(request: Request) -> data.SubscriptionsListResponse:
"""
Get user's subscriptions.
"""
token = request.state.token
params = {
"type": BUGOUT_RESOURCE_TYPE_SUBSCRIPTION,
"user_id": str(request.state.user.id),
}
try:
resources: Bugout... | 00b48801e4c45d117882cbda7caf35d30154907f | 32,993 |
import json
def unique_doc_key(doc):
"""
Creates a key that allows to check for record uniqueness
"""
keyparts = [doc['type']]
for attr in ('level', 'country', 'state', 'region', 'district', 'city'):
if attr in doc:
keyparts.append(doc[attr])
key = json.dumps(keyparts)
... | a2584c4628ffd4b0f433c2f85c8c4e7132ed05ea | 32,994 |
def parse_tag(vt):
"""
Get a VTag from a label
Parameters
----------
vt : str
A label that we want to get the VTag
Raises
------
UnknownTypeError
If the label is not known in VTag
"""
vt = vt.strip()
if vt == "C":
return TAG_CRITICAL
if vt == "L"... | ae551ca27f9c3cf542bf4c253c25731ffd8a6097 | 32,995 |
from datetime import datetime
import time
import random
def fetch_stock_revive_info(start_date: date = None, end_date: date = None, retry: int = 10) -> list:
"""
歷年上櫃減資資訊資料表
輸出格式: [{'code': '4153', 'name': '鈺緯', 'revive_date': date(2020-10-19), 'old_price': 27.20, 'new_price': 30.62}]
"""
result =... | 12e493accdcd8c6896e23a0c592c284c90e53de3 | 32,996 |
def _read_one(stream: BytesIO) -> int:
"""
Read 1 byte, converting it into an int
"""
c = stream.read(1)
if c == b"":
raise EOFError("Unexpected EOF while reading bytes")
return ord(c) | d3f8d22b2d2d3ff08cec42ffcf81cafe9192c707 | 32,997 |
def new_thread_mails(post, users_and_watches):
"""Return an interable of EmailMessages to send when a new thread is
created."""
c = {'post': post.content,
'post_html': post.content_parsed,
'author': post.creator.username,
'host': Site.objects.get_current().domain,
'thread... | 5a6e0bfbaf87f68d6010c84c0cb8c876042c0027 | 32,998 |
def known(words):
"""The subset of `words` that appear in the dictionary of WORDS."""
return set(w for w in words if w in WORDS) | c6665115d9cece679cef0cace8d4037aa4a8e47c | 32,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.