content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def roundPrecision(number, precision=4):
""" Rounds the given floating point number to a certain precision, for output."""
return float(('{:.' + str(precision) + 'E}').format(number)) | 3bac0b54f1f8320c158ce0ddc14db7bbd092d2ff | 17,300 |
import sys
import tempfile
def get_profile(host, cluster = False):
""" Download profile to temporary file and return tempfile handle. """
cmd = [GETPROF, host]
if cluster: cmd.insert(1, "-C")
if debug:
cmd.insert(1, "-D")
sys.stderr.write("%s: launching '%s'\n" % (CALL, " ".join(cmd)))... | ba7bceb1b4047c811f5fc77e50b59c80aeae80bf | 17,301 |
def stringToNumbers(string, separators=[","], commentSymbol="#"):
""" Return a list of splitted string and numbers from string "string". Numbers will be converted into floats. Text after "#" will be skipped.
--- string: the string to be converted.
--- separators: a list of additional separators other than whitesp... | dea1fb1d3257d00eaa637e1b80f23ad0e6475c38 | 17,302 |
import json
def friend_invitation_by_facebook_send_view(request): # friendInvitationByFacebookSend
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
recipients_facebook_id_array = request.GET.getlist('recipien... | 6aeb2852b9e299bc8ddd5d03fbff2d0200e5c4a0 | 17,303 |
import json
def inv_send_received(r, **attr):
"""
Confirm a Shipment has been Received
- called via POST from inv_send_rheader
- called via JSON method to reduce request overheads
"""
if r.http != "POST":
r.error(405, current.ERROR.BAD_METHOD,
next = URL(),... | 645281e0e2023bd454021058e0c0ed79a61223b2 | 17,304 |
import numbers
def filter_table(table, filter_series, ignore=None):
"""
Filter a table based on a set of restrictions given in
Series of column name / filter parameter pairs. The column
names can have suffixes `_min` and `_max` to indicate
"less than" and "greater than" constraints.
Parameter... | 5e5692c46e2dd207eca8d752912dff2b712cce18 | 17,305 |
def analogy_computation_2d(f_first_enc,
f_first_frame,
f_current_enc,
first_depth):
"""Implements the deep analogy computation."""
with tf.variable_scope('analogy_computation'):
frame_enc_diff = f_first_frame - f_first_enc
fr... | 376176b8c17cf9e2f9611943b1fb18da4359748d | 17,306 |
def format_to_TeX(elements):
"""returns BeautifulSoup elements in LaTeX.
"""
accum = []
for el in elements:
if isinstance(el, NavigableString):
accum.append(escape_LaTeX(el.string))
else:
accum.append(format_el(el))
return "".join(accum) | 2df2c4979fc65656b8ef7f4b514a9c4e036b3fa1 | 17,307 |
from typing import OrderedDict
def namedlist(typename, field_names, verbose=False, rename=False):
"""Returns a new subclass of list with named fields.
>>> Point = namedlist('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22)... | 0d7e567e69c9d5c0038f4258b37f17ff1e6fb5b1 | 17,308 |
from typing import List
def has_good_frames(frames: List[MonitoredFrame]) -> bool:
"""
Find a frame with a score larger than X
"""
return any([frame.score and frame.score > 3 for frame in frames]) | 16e9e2bce53ae957254121438c2c4e4f8add2142 | 17,309 |
def updateHistory(conn, author, message_id, backer):
"""
Updates the history
Returns success
"""
c = conn.cursor()
c.execute(prepareQuery("INSERT INTO votes_history (user_id, message_id, backer) VALUES (?,?,?)"), (int(author), int(message_id), int(backer), ))
conn.commit()
return c.rowco... | 6e0f06ace0e3600c307fe3f5848da583c930bbe8 | 17,310 |
import six
def pyc_loads(data):
"""
Load a .pyc file from a bytestring.
Arguments:
data(bytes): The content of the .pyc file.
Returns:
PycFile: The parsed representation of the .pyc file.
"""
return pyc_load(six.BytesIO(data)) | 99b4b7d07d00a0c5098f1a3ded7c1929e2a4b231 | 17,311 |
import numpy
def time_series_figure(time_series, polynomial, drift, snr):
""" Return a matplotlib figure containing the time series and its
polynomial model.
"""
figure = plt.figure()
plot = figure.add_subplot(111)
plot.grid()
plt.title("Drift: {0: .1f}% - SNR: {1: .1f}dB".format(
... | 132aaf22108999e75ec6ca797753724d3198b2c8 | 17,312 |
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
class metaclass(type):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {}) | 0f20f8414adf1d324fbe8541a27cad2219e87794 | 17,313 |
def log(cm_uuid: UUID):
"""
:GET: returns the most recent logs for the specified control module. accepts the following url parameters
- limit: the number of logs that should be returned
- offset: offset the number of logs that should be returned
- log_type: the type of log that should be... | fa129b78497f44a4781e5fa2103abbb232294a7a | 17,314 |
def RetrieveResiduesNumbers(ResiduesInfo):
"""Retrieve residue numbers."""
# Setup residue IDs sorted by residue numbers...
ResNumMap = {}
for ResName in ResiduesInfo["ResNames"]:
for ResNum in ResiduesInfo["ResNum"][ResName]:
ResNumMap[ResNum] = ResName
ResNumsList = []
... | e9f522af368a8a058792b26f9cf53b1114e241ef | 17,315 |
def get_data_with_station(station_id):
"""
*** Returns Pandas DataFrame ***
Please Input Station ID: (String)"""
print("\nGETTING DATA FOR STATION: ",station_id)
ftp = FTP('ftp.ncdc.noaa.gov')
ftp.login()
ftp.cwd('pub/data/ghcn/daily/all')
ftp.retrbinary('RETR '+station_id+'.dly',... | 093b6f7d88335e3ef591cedee7c362bf3b1468d6 | 17,316 |
def _canonicalize(path):
"""Makes all paths start at top left, and go clockwise first."""
# convert args to floats
path = [[x[0]] + list(map(float, x[1:])) for x in path]
# _canonicalize each subpath separately
new_substructures = []
for subpath in _separate_substructures(path):
leftmos... | 3f5aa9a4ac75417935415b5dcc561a1057b465e5 | 17,317 |
from typing import Tuple
def extract_meta(src: bytes) -> Tuple[int, int]:
"""
Return a 2-tuple:
- the length of the decoded block
- the number of bytes that the length header occupied.
"""
v, n = uvarint(src)
if n <= 0 or v > 0xFFFFFFFF:
raise CorruptError
if v > 0x7FFFFFFF:
... | 4bb02fd1c8b9870b450fcbca790fa94870a82cf2 | 17,318 |
def metric_source_configuration_table(data_model, metric_key, source_key) -> str:
"""Return the metric source combination's configuration as Markdown table."""
configurations = data_model["sources"][source_key].get("configuration", {}).values()
relevant_configurations = [config for config in configurations ... | 718a69df60272b7cdfafdbfeff3136a1aac49707 | 17,319 |
import requests
import json
def search(keyword, limit=20):
"""
Search is the iTunes podcast directory for the given keywords.
Parameter:
keyword = A string containing the keyword to search.
limit: the maximum results to return,
The default is 20 results.
... | 922cd7dfaea30e7254c459588d28c33673281dac | 17,320 |
def job_checks(name: str):
"""
Check if the job has parameters
and ask to insert them printing
the default value
"""
p = job_parameters(name)
new_param = {}
if p:
ask = Confirm.ask(
f"Job [bold green] {name} [/bold green] has parameters, do you want to insert them?", ... | 2f64820ec6b180cc6c626fab0616774d7e9086b2 | 17,321 |
import re
def post():
"""Post new message"""
error = None
if request.method == 'POST'\
and request.form['message'] != '' and request.form['message'] is not None:
user_zid = session['logged_in']
post_message = request.form['message']
post_privacy = request.form['post_pri... | b59c5fb30d4b6ce499d0199fb794be38c5c2dfdf | 17,322 |
def data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_connection_end_pointtopology_uuidnode_uuidnode_edge_point_uuidconnection_end_point_uuid_get(uuid, local_id, topology_uuid, node_uuid, node_edge_point_uuid, connection_end_point_uuid): # noqa: E501
"""data_context_connectivity_context_... | 24fe9a977542f52d8bc8cc765c63ce32882d9f76 | 17,323 |
def softmax(logits):
"""Take the softmax over a set of logit scores.
Args:
logits (np.array): a 1D numpy array
Returns:
a 1D numpy array of probabilities, of the same shape.
"""
if not isinstance(logits, np.ndarray):
logits = np.array(logits) # 1D array
logits = logit... | 7e1897748172e095ac58ce7111bed73caa4e2cb6 | 17,324 |
def _aggregate(df, variable, components=None, method=np.sum):
"""Internal implementation of the `aggregate` function"""
# list of variables require default components (no manual list)
if islistable(variable) and components is not None:
raise ValueError(
"Aggregating by list of variables... | 25c36e6180aa5509ced7513c841eb9cc4450b41b | 17,325 |
import inspect
def get_attributes(klass):
"""Get all class attributes.
"""
attributes = list()
for attr, value in inspect.\
getmembers(klass, lambda x: not inspect.isroutine(x)):
if not (attr.startswith("__") and attr.endswith("__")):
attributes.append(attr)
return ... | 6a72db39a9982b6a4ad5462ff9a4695f9cca6ce0 | 17,326 |
import io
def render(html):
"""Convert HTML to a PDF"""
output = io.BytesIO()
surface = cairo.PDFSurface(output, 595, 842)
ctx = cairo.Context(surface)
cffictx = cairocffi.Context._from_pointer(cairocffi.ffi.cast('cairo_t **', id(ctx) + object.__basicsize__)[0], incref=True)
html = etree.par... | 9b0d4c252b7b7bf8dcdcab32e13cf183cef0312d | 17,327 |
def computeFlowImage(u,v,logscale=True,scaledown=6,output=False):
"""
topleft is zero, u is horiz, v is vertical
red is 3 o'clock, yellow is 6, light blue is 9, blue/purple is 12
"""
colorwheel = makecolorwheel()
ncols = colorwheel.shape[0]
radius = np.sqrt(u**2 + v**2)
if output:
... | 87690e34ae1509a63df982b68e35346be8b5d8dd | 17,328 |
def day_display(year, month, all_month_events, day):
"""
Returns the events that occur on the given day.
Works by getting all occurrences for the month, then drilling
down to only those occurring on the given day.
"""
# Get a dict with all of the events for the month
count = CountHandler(yea... | e17df37bb8908a557b9cf1175c3567b460a35385 | 17,329 |
import math
def decimal_to_octal(num):
"""Convert a Decimal Number to an Octal Number."""
octal = 0
counter = 0
while num > 0:
remainder = num % 8
octal = octal + (remainder * math.pow(10, counter))
counter += 1
num = math.floor(num / 8) # basically /= 8 without remain... | e6bbc23a2235812c1e2298e8a0be8396c06b1c1f | 17,330 |
def get_formatted_dates(date_ranges):
"""Returns list of dates specified by date_ranges, formtted for Swiftly API use.
date_ranges is a list of dict, with each dict specifying a range of dates
in string format. sample dict for Tue/Wed/Thu in Sep/Oct:
{
"start_date": "09-01-2019",
"end_d... | db20459ffacb8cb621acdf40b0bdcbc203787680 | 17,331 |
import os
def _get_config_path(config_path):
"""Find path to yaml config file
Args:
config_path: (str) Path to config.yaml file
Returns:
Path to config.yaml if specified else default config.yaml
Raises:
ValueError: If the config_path is not None but doesn't exist
"""
... | 4353dca4c6b30bff3b90389fc7681baeb2da9052 | 17,332 |
def read_img(img: str, no_data: float, mask: str = None, classif: str = None, segm: str = None) ->\
xr.Dataset:
"""
Read image and mask, and return the corresponding xarray.DataSet
:param img: Path to the image
:type img: string
:type no_data: no_data value in the image
:type no_data: f... | 2074269e47092313f1cb01dc81004b7ce9c8f411 | 17,333 |
def any_user(password=None, permissions=[], groups=[], **kwargs):
"""
Shortcut for creating Users
Permissions could be a list of permission names
If not specified, creates active, non superuser
and non staff user
"""
is_active = kwargs.pop('is_active', True)
is_superuser = kwargs.pop... | 914bbb58b68aad9b19a77f2dec7ea1f0e91508bd | 17,334 |
def devices_to_use():
"""Returns the device objects for the accel. we are the most likely to use.
Returns:
List of logical devices of the accelerators we will use.
"""
if tf.config.list_logical_devices("TPU"):
devices = tf.config.list_logical_devices("TPU")
elif tf.config.list_logical_devices("GPU"):... | aca8cbd28ff46e79655b47e34334c12406cc94e8 | 17,335 |
def barcode_density(bars, length):
"""
calculates the barcode density (normalized average cycle lifetime)
of a barcode
"""
densities = np.zeros(len(bars))
nums = np.array([len(bars[i][1]) for i in range(len(bars))])
num_infs = np.zeros(len(bars))
for i in range(len(bars)):
tot = ... | 4b585338cef3fd8b8ca91f89a1ae0532450b6209 | 17,336 |
import argparse
def create_parser():
"""Creates the default argument parser.
Returns
-------
parser : ArgumentParser
"""
parser = argparse.ArgumentParser()
parser.add_argument('--version', action='version', version=__version__)
parser.add_argument('--config-file')
parser.add_argum... | e2ad6357811596c75f78dc24176976434e35e379 | 17,337 |
def genRankSurvey(readername, candidates, binsize, shareWith=None):
"""
readername (str)
candidates (iterable)
binsize (int)
shareWith (str) optional
"""
# connect and craete survey
c = cornellQualtrics()
surveyname = "Ranking Survey for {}".format(readername)
surveyId = c.create... | e94f782389de86a8cbfb9c77aa078f004ac061c9 | 17,338 |
def _get_badge_status(
self_compat_res: dict,
google_compat_res: dict,
dependency_res: dict) -> BadgeStatus:
"""Get the badge status.
The badge status will determine the right hand text and the color of
the badge.
Args:
self_compat_res: a dict containing a package's sel... | f367f75321c62a7c86b4ef26be446072e5eaca7c | 17,339 |
import yaml
def _get_yaml_as_string_from_mark(marker):
"""Gets yaml and converts to text"""
testids_mark_arg_no = len(marker.args)
if testids_mark_arg_no > 1:
raise TypeError(
'Incorrect number of arguments passed to'
' @pytest.mark.test_yaml, expected 1 and '
'... | 034dab9c5380035d2303df7ea7243b84baff47a0 | 17,340 |
def combine_dicts(w_dict1, w_dict2, params, model):
"""
Combine two dictionaries:
"""
w_dict = w_dict1 + w_dict2
eps = params[0]
params[0] = 0
P_w = []
w_dict = md.remove_duplicates_w_dict(P_w,w_dict,params,model)
return w_dict | 21c2de003cca0165b5404431178450bf6e6c549c | 17,341 |
def geocode_mapping(row, aian_ranges, aian_areas, redefine_counties, strong_mcd_states):
"""
Maps an RDD row to a tuple with format (state, AIAN_bool, AIANNHCE, county, place/MCD, tract, block), where
place/MCD is the five digit MCD in MCD-strong states and 5 digit place otherwise
AIAN_bool is '1' if th... | 6d2dcd7aa5acb5bff71120d957f520d0eec79790 | 17,342 |
from typing import Dict
def get_stan_input(
scores: pd.DataFrame,
priors: Dict,
likelihood: bool,
) -> Dict:
"""Get an input to cmdstanpy.CmdStanModel.sample.
:param measurements: a pandas DataFrame whose rows represent measurements
:param model_config: a dictionary with keys "priors", "like... | d8e11401c1c86bb3306652f6f3b1aaebe47ef2d8 | 17,343 |
def get_mph(velocity):
"""
Returns
-------
convert m/s to miles per hour [mph].
"""
velocity = velocity * 3600 /1852
return velocity | f4a1922712ef2d8cfeba5650f410405956a39c31 | 17,344 |
import json
def _load_jsonl(input_path) -> list:
"""
Read list of objects from a JSON lines file.
"""
data = []
with open(input_path, 'r', encoding='utf-8') as f:
for line in f:
data.append(json.loads(line.rstrip('\n|\r')))
print('[LoadJsonl] Loaded {} records from {}'.form... | 2cd35ff8afa7c325688046165517746e2b120b77 | 17,345 |
import types
import importlib
def reload(name: str) -> types.ModuleType:
"""
Finalize and reload a plugin and any plugins that (transitively) depend on it. We try to run all finalizers in
dependency order, and only load plugins that were successfully unloaded, and whose dependencies have been
successf... | ea00d2139b51e80239960f61c0dc91dfe45de7d9 | 17,346 |
import json
def load_from_config(config_path, **kwargs):
"""Load from a config file. Config options can still be overwritten with kwargs"""
with open(config_path, "r") as config_file:
config = json.load(config_file)
config.update(kwargs)
return TokenizationConfig(**config) | 66ea64a334b265ae216413a043044767da0fd61c | 17,347 |
import collections
def get_tecogan_monitors(monitor):
"""
Create monitors for displaying and storing TECOGAN losses.
"""
monitor_vgg_loss = MonitorSeries(
'vgg loss', monitor, interval=20)
monitor_pp_loss = MonitorSeries(
'ping pong', monitor, interval=20)
monitor_sum_layer_los... | 472605e4ff7a0e487fd868a573fbecf5acd977ba | 17,348 |
def user_based_filtering_recommend(new_user,user_movies_ids,movies_num,n_neighbor,movies_ratings):
""" This function return number of recommended movies based on user based filtering using
cosine similarity to find the most similar users to the new user
it returns movies_num of movies from the top ranked ... | 4fa86b9966024e0d89969566d85ccf0b0a44bfcc | 17,349 |
def query_ps_from_wcs(w):
"""Query PanStarrs for a wcs.
"""
nra,ndec = w.array_shape[1:]
dra,ddec = w.wcs.cdelt[:2]
c = wcs.utils.pixel_to_skycoord(nra/2.,ndec/2.,w)
ddeg = np.linalg.norm([dra*nra/2,ddec*ndec/2])
pd_table = query(c.ra.value,c.dec.value,ddeg)
# Crop sources to those in t... | 806baf87722213ab021e1e3889322539069a3b55 | 17,350 |
import torch
def permute(x, in_shape='BCD', out_shape='BCD', **kw):
""" Permute the dimensions of a tensor.\n
- `x: Tensor`; The nd-tensor to be permuted.
- `in_shape: str`; The dimension shape of `x`. Can only have characters `'B'` or `'C'` or `'D'`,
which stand for Batch, Channel, or extra Dim... | e74594df581c12891963e931999563374cd89c7d | 17,351 |
def heatmap(data, row_labels, col_labels, ax=None,
cbar_kw={}, cbarlabel="", **kwargs):
"""
Create a heatmap from a numpy array and two lists of labels.
Parameters
----------
data
A 2D numpy array of shape (N, M).
row_labels
A list or array of length N with the label... | 51c60139f9f2668f8ba31859c036f48a3e8faf63 | 17,352 |
import zlib
import struct
def assert_is_normal_rpyc(f):
"""
Analyze the structure of a single rpyc file object for correctness.
Does not actually say anything about the _contents_ of that section, just that we were able
to slice it out of there.
If succesful, returns the uncompressed contents of ... | f7db901dd99b0ac9036d6569093068e8f6b3e675 | 17,353 |
import os
import json
def retrieve_s3_object_contents(s3_obj, bucket=os.environ["ARTIFACTS_BUCKET"]):
"""Retrieve S3 object contents."""
return json.loads(
s3.get_object(Bucket=bucket, Key=s3_obj)["Body"].read().decode("utf-8")
) | 33342158e327ef7d3f296b35939abb9336623060 | 17,354 |
def substract_li(cfg, data, lats, lons, future_exp):
"""Difference between historical and future fields."""
pathlist = data.get_path_list(short_name='pr', exp='historical')
ar_diff_rain = np.zeros((len(lats), len(lons), len(pathlist)))
mism_diff_rain = np.zeros(len(pathlist))
mwp_hist_rain = np.zer... | 40506221fbdf5a9b0e2174e0fe144958dd57c93b | 17,355 |
def identify_jobs_to_update(file_path, jobs):
"""identify jobs to update."""
name_map = {}
for job in jobs:
cluster = get_desired_cluster(file_path, job)
if cluster != job.get("cluster", ""):
name_map[job["name"]] = cluster
return name_map | be9b8bd38ed90c96ac185195a79a43ffbec5e7d5 | 17,356 |
def bootstrap_storage_bucket(project_id, bucket_name, google_credentials):
"""
Bootstrap the bucket used to store Terraform state for projects.
Args:
project_id:
The ID of the project to create the bucket in.
bucket_name:
The name of the bucket to create.
goo... | acdd72fbcb160d5c6347f1f41b6661fcf28ebdc2 | 17,357 |
def ValidateBucketForCertificateAuthority(bucket_name):
"""Validates that a user-specified bucket can be used with a Private CA.
Args:
bucket_name: The name of the GCS bucket to validate.
Returns:
A BucketReference wrapping the given bucket name.
Raises:
InvalidArgumentException: when the given b... | b28e501b7747f8a4d417b156c2e627d8ca524aee | 17,358 |
def load_train_val(seq_len, batch_size, dataset="hollywood2"):
"""
This returns two dataloaders correponding to the train and validation sets. Each
iterator yields tensors of shape (N, 3, L, H, W) where N is the batch size, L is
the sequence length, and H and W are the height and width of the frame.
... | 628a2c0db01b30c4736e482dbc81789afcbdc92a | 17,359 |
import os
def checkIfMeshId(projectPath, mesh, name, meshID):
"""Checks if exists another Object having the same name as the mesh
This function asks the user what to do.
If the object is not a mesh, gets all the children meshes
Args:
projectPath: a str with the path where the expo... | 8e20683c59864b17c40291345beb21a7a54c5323 | 17,360 |
import json
import yaml
def read_params_file(config_path: str) -> json:
"""Read the and open the params.yaml file
Args:
config_path (str): yaml config file
Returns:
yaml: yaml file
"""
with open(config_path) as yaml_file:
config = yaml.safe_load(yaml_file)
return con... | b8a4bf0f70d1b4e2096ebd6d96568fc7ee757e16 | 17,361 |
import re
def fullmatch(regex, string, flags=0):
"""Emulate python-3.4 re.fullmatch()."""
matched = re.match(regex, string, flags=flags)
if matched and matched.span()[1] == len(string):
return matched
return None | 72de0abe5c15dd17879b439562747c9093d517c5 | 17,362 |
import re
def html2text(html: str) -> str:
""" Change HTML to help torenizer and return text """
# Replace <br/> with PERIOD+NEW_LINE
html = re.sub(r'(\s*<br\s?\/\s*>)+', '. \n', html)
html = re.sub(r'<br\s?\/?>', '. \n', html)
html = re.sub(r'\s*(</?em>)\s*', r' \1 ', html)
html = re.sub(r'... | f410238595b760a14439486f15e13420f02db68b | 17,363 |
from typing import Any
from typing import Type
import inspect
def _is_class(module: Any, member: Type, clazz: Type) -> bool:
"""
Validates if a module member is a class and an instance of a CoreService.
:param module: module to validate for service
:param member: member to validate for service
:p... | 5792fadcc93068fa8d7050de7d84ee2bbe1fb0f1 | 17,364 |
def word_boundary(queries, count, degree, parallel=True, **kwargs):
"""
run augmentation on list of sentences
:param queries: sentences to augment
:type queries: list
:param count: number of output for each query
:type count: int
:param degree: degree of augmentation, takes value between 0 a... | 7ca4172d2900c773322d54380bde6780f2580597 | 17,365 |
def myFunction(objectIn):
"""What you are supposed to test."""
return objectIn.aMethodToMock() + 2 | 1907db338a05f2d798ccde63366d052404324e6f | 17,366 |
def read_config(filename, section):
""" Reads a section from a .ini file and returns a dict object
"""
parser = ConfigParser()
parser.read(filename)
dic = {}
if parser.has_section(section):
items = parser.items(section)
for item in items:
dic[item[0]] = item[1]
... | 3eb84afc13b0ad40bcaf434d4a38712cedb4502a | 17,367 |
def get_training_set_count(disc):
"""Returns the total number of training sets of a discipline and all its
child elements.
:param disc: Discipline instance
:type disc: models.Discipline
:return: sum of training sets
:rtype: int
"""
training_set_counter = 0
for child in disc.get_desc... | 9b28a9e51e04b559f05f1cc0255a6c65ca4a0980 | 17,368 |
import os
def search_dir(path, dir_name, type):
"""Search directory in certain path"""
target_path = ""
for item in os.listdir(path):
item_path = os.path.join(path, item)
if os.path.isdir(item_path):
if lambda_fun(dir_name, item, type):
target_path = item_path
... | 27257c5243417119067066236d73263afc54ff37 | 17,369 |
def lazy_import(module_name, callback=None):
"""Returns a proxy module object that will lazily import the given module the first
time it is used.
Example usage::
# Lazy version of `import tensorflow as tf`
tf = lazy_import("tensorflow")
# Other commands
# Now the module i... | bc94a18b4a8a2714d2cffd743de2a202ecb5af78 | 17,370 |
def _top_k(array, k):
"""Returns top k values and their indices along the last axis of the array.
This function serves the same purpose as jax.lax.top_k, but in a more XLA
friendly manner for TPUs:
(1) On TPUs, we use one-hot matrix multiplications to select the top k values.
This convoluted way of obtai... | 74c7c705b6b972d227c10146f0b5209f62c1d59f | 17,371 |
def time_to_accuracy(raw_metrics, tag, threshold):
"""Calculate the amount of time for accuracy to cross a given threshold.
Args:
raw_metrics: dict mapping TensorBoard tags to list of MetricPoint.
tag: string name of accuracy metric.
threshold: the desired model accuracy.
Returns:
float, amoun... | 5ce2727a538a25f195c0d9ab3de2c2dcdbb56f88 | 17,372 |
def create_stencil(image_shape, smooth):
"""The stencil is a mask that will enable a smooth transition between blocks. blocks will be multiplied
by the stencil so that when they are blitted to the image, transition between them are smoothed out.
image 1: 1 1 1 1 1 1 1 , image 2: 2 2 2 2 2 2 2, stencil: .25 ... | 49aca2fb63ea6bef134c0872520fd203ce21bfef | 17,373 |
def a_m_to_P(a, m):
"""Compute the orbital period given the semi-major axis and total mass.
Parameters
----------
{a}
{m}
"""
return 2*np.pi * np.sqrt(a**3 / (G * m)) | 734332ff83c06830388ceeecd64315ee738756f1 | 17,374 |
def _async_attr_mapper(attr_name, val):
"""The `async` attribute works slightly different than the other bool
attributes. It can be set explicitly to `false` with no surrounding quotes
according to the spec."""
if val in [False, 'False']:
return ' {}=false'.format(attr_name)
elif val:
... | 79e72067b244d705df9aa09a78db656f0847938c | 17,375 |
from typing import Any
from typing import Type
def wrap(val: Any) -> Value:
"""Wraps the given native `val` as Protobuf `Value` message.
Supports converting collection/array of primitives types to `Value` message:
* numpy array of primitives.
* list of primitives.
* generator of finite no. of pri... | 9208a2afd7b256ec791044531b13fe8c8b9fa2c8 | 17,376 |
def to_transform_msg(transform):
"""Convert a `Transform` object to a Transform message."""
msg = geometry_msgs.msg.Transform()
msg.translation = to_vector3_msg(transform.translation)
msg.rotation = to_quat_msg(transform.rotation)
return msg | c471ec8dfed03caa9f7096ab3294589477cf6d39 | 17,377 |
def print_pos_neg(num):
"""Print if positive or negative in polarity level
>>> print_pos_neg(0.8)
'positive'
>>> print_pos_neg(-0.5)
'negative'
"""
if num > 0:
return "positive"
elif num == 0:
return "neutral"
else:
return "negative" | 414aa98f54a2f01af24d591ae47ec4f394adf682 | 17,378 |
def delete_volume_op(name: str, namespace: str):
"""
Creates a kfp.dsl.ContainerOp that deletes a volume (Kubernetes Resource).
Parameters
----------
name : str
namespace : str
Returns
-------
kfp.dsl.ContainerOp
"""
kind = "PersistentVolumeClaim"
return kubernetes_resour... | d947905e01de29061895512fbfd1fbefb024110d | 17,379 |
def distal(combo):
""" Returns the distal subspecies from a combo
:param combo: int representation of origin combination
:return: int representation of the distal origin
>>> distal(combine(CAS, DOM)) == DOM
True
"""
return combo & _DISTAL_MASK | 163875c1b4b081027344a3bc1f05bd0cb60a58d8 | 17,380 |
def get_eval_dataset(files, ftDict, axes = [2], splits = None, one_hot = None, moments = None, **kwargs):
"""
Get the preprocessed evaluation dataset
Args:
files (list): list of tfrecords to be used for evaluation
Returns:
A tf.data.Dataset of evaluation data.
"""
dataset = get_dataset... | 73476bf1273923e77bf5f4e6d415191cf83023cc | 17,381 |
def getTopApSignals(slot_to_io):
""" HLS simulator requires that there is an ap_done at the top level """
# find which slot has the s_axi_control
for slot, io_list in slot_to_io.items():
if any('s_axi' in io[-1] for io in io_list):
# note the naming convention
ap_done_source = [f'{io[-1]}_in' fo... | e40a8fb7797653ee7414c0120ceb29e49e9dfd84 | 17,382 |
def get_line_style(image: Image = None) -> int:
"""
Get line style of the specified image.
The line style will be used when drawing lines or shape outlines.
:param image: the target image whose line style is to be gotten. None means it is the target image
(see set_target() and get_target())
... | cc1b9285fbd3b168f40e66969e0a4b1ae9ee234a | 17,383 |
def make_polygon_for_earth(lat_bottom_left, lon_bottom_left, lat_top_right, lon_top_right):
"""
Divides the region into two separate regions (if needed) so as to handle the cases where the regions
cross the international date
:param lat_bottom_left: float (-90 to 90)
:param lon_bottom_left: float (... | 6f73cc35c11cd16eea0c80aa7921ff1680ee75b6 | 17,384 |
import torch
import os
def train_coral(s_dataloaders, t_dataloaders, val_dataloader, test_dataloader, metric_name, seed, **kwargs):
"""
:param s_dataloaders:
:param t_dataloaders:
:param kwargs:
:return:
"""
s_train_dataloader = s_dataloaders
t_train_dataloader = t_dataloaders
au... | d7ff43137f7f869f0104bf0e6ba15dcdcf909a2f | 17,385 |
def first_nonzero_coordinate(data, start_point, end_point):
"""Coordinate of the first nonzero element between start and end points.
Parameters
----------
data : nD array, shape (N1, N2, ..., ND)
A data volume.
start_point : array, shape (D,)
The start coordinate to check.
end_p... | 5db67cf49c3638a80695fd76a1a16eeec992d725 | 17,386 |
def l1_distance(prediction, ground_truth):
"""L1 distance difference between two vectors."""
if prediction.shape != ground_truth.shape:
prediction, ground_truth = np.squeeze(prediction), np.squeeze(ground_truth)
min_length = min(prediction.size, ground_truth.size)
return np.abs(prediction[:min_length] - gro... | aaf79b386efa5f1b8726adda8d8e7dc66a502e87 | 17,387 |
from typing import Match
import base64
def decode(match_id: str) -> Match:
"""Decode a match ID and return a Match.
>>> decode("QYkqASAAIAAA")
Match(cube_value=2, cube_holder=<Player.ZERO: 0>, player=<Player.ONE: 1>, crawford=False, game_state=<GameState.PLAYING: 1>, turn=<Player.ONE: 1>, double=False, r... | a48fae652650d03259fd003af16add381f2729f3 | 17,388 |
def _valid_proto_paths(transitive_proto_path):
"""Build a list of valid paths to build the --proto_path arguments for the ScalaPB protobuf compiler
In particular, the '.' path needs to be stripped out. This mirrors a fix in the java proto rules:
https://github.com/bazelbuild/bazel/commit/af3605862047f7b553b... | cb834a58fa091249f16d5cdfccf536229dacd3d0 | 17,389 |
def update_stats_objecness(obj_stats, gt_bboxes, gt_labels, pred_bboxes, pred_labels, pred_scores, mask_eval=False,
affordance_stats=None, gt_masks=None, pred_masks=None, img_height=None, img_width=None, iou_thres=0.3):
"""
Updates statistics for object classification and affordance detecti... | c07d57921a6f3f3d2d97c9d84afb5dcbcb885ea6 | 17,390 |
from typing import Dict
from pathlib import Path
import inspect
import json
def load_schema(rel_path: str) -> Dict:
"""
Loads a schema from a relative path of the caller of this function.
:param rel_path: Relative path from the caller. e.g. ../schemas/schema.json
:return: Loaded schema as a `dict`.
... | 297e0e01dd2f4af071ab99ebaf203ddb64525c89 | 17,391 |
def bquantize(x, nsd=3, abstol=eps, reltol=10 * eps):
"""Bidirectionally quantize a 1D vector ``x`` to ``nsd`` signed digits.
This method will terminate early if the error is less than the specified
tolerances.
The quantizer details are repeated here for the user's convenience:
The quantizer ... | 2a2e5fb71f3198099a07d84e9ad83ba6849b38d0 | 17,392 |
import zoneinfo
def timezone_keys(
*,
# allow_alias: bool = True,
# allow_deprecated: bool = True,
allow_prefix: bool = True,
) -> SearchStrategy[str]:
"""A strategy for :wikipedia:`IANA timezone names <List_of_tz_database_time_zones>`.
As well as timezone names like ``"UTC"``, ``"Australia/S... | 9faffd54419f82b412dd9114ecfc5b950c985039 | 17,393 |
def seg_to_bdry(seg, connectivity=1):
"""Given a borderless segmentation, return the boundary map."""
strel = generate_binary_structure(seg.ndim, connectivity)
return maximum_filter(seg, footprint=strel) != \
minimum_filter(seg, footprint=strel) | dc4e66a7e6f86d2984a23a2e7a7297403502b51d | 17,394 |
def depthwise_conv2d(x, filters, strides, padding, data_format="NHWC", dilations=1):
"""Computes a 2-D depthwise convolution given 4-D input x and filters arrays.
Parameters
----------
x
Input image *[batch_size,h,w,d]*.
filters
Convolution filters *[fh,fw,d]*.
strides
T... | cc09b910d06b8fd9d1b5b00a80c6d376cf7f6005 | 17,395 |
def OUTA():
"""
The OUTA Operation
"""
control_signal = gen_control_signal_dict()
opcode_addr = gen_opcode_addr_component_dict()
mc_step_addr = gen_microcode_step_addr_component_dict()
input_sig_addr = gen_input_signal_addr_component_dict()
templates = []
# Step 2 - A -> OUT
a... | 3ebd5e74005316d3925eaa553c112df8a61eaf90 | 17,396 |
def incidence_matrices(G, V, E, faces, edge_to_idx):
"""
Returns incidence matrices B1 and B2
:param G: NetworkX DiGraph
:param V: list of nodes
:param E: list of edges
:param faces: list of faces in G
Returns B1 (|V| x |E|) and B2 (|E| x |faces|)
B1[i][j]: -1 if node i is tail of edge... | 90a82132100bb6d2e867ee7460ad55c6891b9082 | 17,397 |
def get_hosts_ram_total(nova, hosts):
"""Get total RAM (free+used) of hosts.
:param nova: A Nova client
:type nova: *
:param hosts: A set of hosts
:type hosts: list(str)
:return: A dictionary of (host, total_ram)
:rtype: dict(str: *)
"""
hosts_ram_total = dict() #dict of (host... | b913f9274339ab3ab976a17a8d07e5fe130b447d | 17,398 |
import re
import unicodedata
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-ascii characters,
and converts spaces to hyphens. For use in urls and filenames
From Django's "django/template/defaultfilters.py".
"""
_slugify_strip_re = re.compile(r'[^\w\s-]')
_s... | 471a3205c84baa55573b780375999a7658031b89 | 17,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.