content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def lh_fus(temp):
"""latent heat of fusion
Args:
temp (float or array): temperature [K]
Returns:
float or array: latent heat of fusion
"""
return 3.336e5 + 1.6667e2 * (FREEZE - temp) | 8127970612b031d2aaf7598379f41b549a3268e1 | 3,649,620 |
def to_eaf(file_path, eaf_obj, pretty=True):
"""
modified function from https://github.com/dopefishh/pympi/blob/master/pympi/Elan.py
Write an Eaf object to file.
:param str file_path: Filepath to write to, - for stdout.
:param pympi.Elan.Eaf eaf_obj: Object to write.
:param bool pretty: Flag to ... | 605e7f711f34661daae6869419d6f8bebb05a2c4 | 3,649,621 |
def query_for_build_status(service, branch, target, starting_build_id):
"""Query Android Build Service for the status of the 4 builds in the target
branch whose build IDs are >= to the provided build ID"""
try:
print ('Querying Android Build APIs for builds of {} on {} starting at'
' buildID {}'... | 4e1e04dae1ce13217374207a1b57d7380552dfc5 | 3,649,623 |
def create_pool(
dsn=None,
*,
min_size=10,
max_size=10,
max_queries=50000,
max_inactive_connection_lifetime=300.0,
setup=None,
init=None,
loop=None,
authenticator=None,
**connect_kwargs,
):
"""Create an Asyncpg connection pool through Approzium authentication.
Takes s... | 0b50a4cba07fb4797e04cc384dd46d1e21deed12 | 3,649,624 |
import logging
def _get_all_schedule_profile_entries_v1(profile_name, **kwargs):
"""
Perform a GET call to get all entries of a QoS schedule profile
:param profile_name: Alphanumeric name of the schedule profile
:param kwargs:
keyword s: requests.session object with loaded cookie jar
... | 32d6278ce6704feb5831012c2d0050b226fc7dfa | 3,649,625 |
def loadSource(path):
"""Loads a list of transportReactions. Format:
R("Macgamb_Transp")
R("Madnb_Transp")
R("MalaDb_Transp")..."""
file = open(path, 'r')
sources = [line.strip() for line in file]
file.close()
return sources | 244e9e5619a5039822ef14dfbb3d99b55cb6cc74 | 3,649,626 |
from typing import Optional
import struct
def frombin(
__data: Bitcode,
__dtype: SupportedDataType | bytes,
num: int = 1,
*,
encoding: Optional[str] = None,
signed: bool = True,
) -> ValidDataset:
"""converts a string of 0 and 1 back into the original data
Args:
data (BinaryCo... | 6fa7219ea8622071c7bb3277c8b59717543e9286 | 3,649,627 |
def check_size():
"""Assumes the problem size has been set by set_size before some operation.
This checks if the size was changed
Size is defined as (PIs, POs, ANDS, FF, max_bmc)
Returns TRUE is size is the same"""
global npi, npo, nands, nff, nmd
#print n_pis(),n_pos(),n_ands(),n_latches()
... | 361edb3b4f20a3ae4920c784ad2d1c56fe35e2d6 | 3,649,628 |
def vrms2dbm(vp):
"""
Converts a scalar or a numpy array from volts RMS to dbm assuming there is an impedence of 50 Ohm
Arguments:
- vp: scalar or numpy array containig values in volt RMS to be converted in dmb
Returns:
- scalar or numpy array containing the result
"""
return ... | 7d0f76ab74cf82d2d56f97840153f1b9bc3cb8a8 | 3,649,629 |
def aa_i2c_read (aardvark, slave_addr, flags, data_in):
"""usage: (int return, u08[] data_in) = aa_i2c_read(Aardvark aardvark, u16 slave_addr, AardvarkI2cFlags flags, u08[] data_in)
All arrays can be passed into the API as an ArrayType object or as
a tuple (array, length), where array is an ArrayType objec... | 59cca99e3ae811e957f9dd053205f3639c1451a4 | 3,649,630 |
def urbandictionary_search(search):
"""
Searches urbandictionary's API for a given search term.
:param search: The search term str to search for.
:return: definition str or None on no match or error.
"""
if str(search).strip():
urban_api_url = 'http://api.urbandictionary.com/v0/define?te... | 3cd63486adc11f3ca20d4cd6216006d3f2d2239f | 3,649,632 |
def Performance(ALGORITHM_CONFIG, CELLULAR_MODEL_CONFIG, alog_name):
"""
Performance testing
"""
# Server profile: num_ues=200, APs=16, Scale=200.0, explore_radius=1
loadbalanceRL = interface.Rainman2(SETTINGS)
loadbalanceRL.algorithm_config = ALGORITHM_CONFIG
loadbalanceRL.environment_confi... | 87e5d6b0c400af0262b6a2c746e855b9b71a5c35 | 3,649,633 |
def launch(sid):
"""
Launch a scan
Launch the scan specified by the sid.
"""
data = connect('POST', '/scans/{0}/launch'.format(sid))
return data['scan_uuid'] | fa99e7a50e9e2ddb30ba131ebd61c998c2cdabaa | 3,649,634 |
import ast
def transpose_dict(data, data_key):
"""Function: transpose_dict
Description: Transpose specified keys in a list of dictionaries
to specified data types or None.
Arguments:
(input) data -> Initial list of dictionaries.
(input) data_key -> Dictionary of keys and data ... | 7675ea2f80e9e85993dc99a2a31df04abfeba2c8 | 3,649,635 |
def aligner_to_symbol(calls):
"""
Assign symbols to different aligners in the input file
Set the attribute of the class instances
return a list of indices for which each aligner is found uniquely and all aligners
sorted by aligners
"""
symbols = ['o', '+', 'x', 'v', '*', 'D', 's', 'p', '8',... | b9cef3ae33b6ce84daf78a8bc8ce528f97d7a8a6 | 3,649,636 |
def nfvi_create_subnet(network_uuid, subnet_name, ip_version, subnet_ip,
subnet_prefix, gateway_ip, dhcp_enabled, callback):
"""
Create a subnet
"""
cmd_id = _network_plugin.invoke_plugin('create_subnet', network_uuid,
subnet_name, ip_ver... | 383a0ffeb6e364f761c8d4038bf8e53f367021c1 | 3,649,638 |
def convertCRS(powerplants, substations, towers, crs, grid):
"""
:param powerplants:
:param substations:
:param towers:
:param crs:
:return:
"""
substations.to_crs(crs)
# powerplants = powerplants.set_crs(crs)
# powerplants = powerplants.to_crs(crs)
# print(powerplants.crs)
... | 9fcb8c51323c00935ba2c882502a273f2bf532ff | 3,649,639 |
def get_pathway(page_name, end_pg, max_len, trail, paths):
"""
Finds a list of all paths from a starting wikipedia page to an end page
Assumes page_name is a valid wikipedia article title and end_pg is a valid
Wikipedia Page Object
Args:
page_name: (Str) The name of the current article... | 3b8effcb1f5295a854d32cc6438093f5ba7c1fa4 | 3,649,640 |
def clip_to_ndc(point_clip_space, name="clip_to_ndc"):
"""Transforms points from clip to normalized device coordinates (ndc).
Note:
In the following, A1 to An are optional batch dimensions.
Args:
point_clip_space: A tensor of shape `[A1, ..., An, 4]`, where the last
dimension represents points in ... | ee49d891da941b6da48797035c5b976f5d10762d | 3,649,641 |
def read_number(dtype, prompt='', floor=None, ceil=None, repeat=False):
""" Reads a number within specified bounds. """
while True:
try:
result = dtype(input(prompt))
if floor is not None and result < floor:
raise ValueError(f'Number must be no less than... | a528b1f5912ba4bab0b87c87004311778eaa8187 | 3,649,643 |
from typing import Optional
def dem_adjust(
da_elevtn: xr.DataArray,
da_flwdir: xr.DataArray,
da_rivmsk: Optional[xr.DataArray] = None,
flwdir: Optional[pyflwdir.FlwdirRaster] = None,
connectivity: int = 4,
river_d8: bool = False,
logger=logger,
) -> xr.DataArray:
"""Returns hydrologic... | d59f5bae1df44cc84c4eb98d8dd14ca923dc4809 | 3,649,644 |
from copy import copy
from numpy import zeros, unique
from itertools import product
def trainModel(label,bestModel,obs,trainSet,testSet,modelgrid,cv,optMetric='auc'):
""" Train a message classification model """
pred = zeros(len(obs))
fullpred = zeros((len(obs),len(unique(obs))))
model = copy(bestMode... | fdf60d23894bfd997cdf7fa82cb59257ad7b2954 | 3,649,645 |
def vm_deploy(vm, force_stop=False):
"""
Internal API call used for finishing VM deploy;
Actually cleaning the json and starting the VM.
"""
if force_stop: # VM is running without OS -> stop
cmd = 'vmadm stop %s -F >/dev/null 2>/dev/null; vmadm get %s 2>/dev/null' % (vm.uuid, vm.uuid)
e... | 324dffa2a181d4b796a8f263eeb57d1452826c78 | 3,649,646 |
def get_monitor_value(image, monitor_key):
"""Return the monitor value from an image using an header key.
:param fabio.fabioimage.FabioImage image: Image containing the header
:param str monitor_key: Key containing the monitor
:return: returns the monitor else returns 1.0
:rtype: float
"""
... | cf74ab608837b6f5732a70d997afa1fe424b2ee1 | 3,649,649 |
def default_thread_index (value, threads):
"""
find index in threads array value
:param value:
:param threads:
:return:
"""
value_index = threads.index(value)
return value_index | 7be2efb6579f2880f53dac11705ba6a068c2d92d | 3,649,651 |
import requests
def new_things(url):
"""Attempts to register new things on the directory
Takes 1 argument:
url - URL containing thing descriptions to register
"""
response = requests.post('{}/things/register_url'.format(settings.THING_DIRECTORY_HOST), headers={
'Authorization': settin... | 0336d094e9581f3382dd33ac8a9bf8fd43754d82 | 3,649,652 |
def isID(value):
"""Checks if value looks like a Ulysses ID; i.e. is 22 char long.
Not an exact science; but good enougth to prevent most mistakes.
"""
return len(value) == 22 | 527db9446adc2b88c2117bd35c74474c3e7bad24 | 3,649,653 |
def tool_on_path(tool: str) -> str:
"""
Helper function to determine if a given tool is on the user's PATH variable. Wraps around
runspv.tool_on_path().
:param tool: the tool's filename to look for.
:return: the path of the tool, else ToolNotOnPathError if the tool isn't on the PATH.
"""
ret... | 52963a818bcea59eaaec1d20000d3a4a1296ee26 | 3,649,654 |
def DefineDecode(i, n, invert=False):
"""
Decode the n-bit number i.
@return: 1 if the n-bit input equals i
"""
class _Decode(Circuit):
name = 'Decode_{}_{}'.format(i, n)
IO = ['I', In(Bits[ n ]), 'O', Out(Bit)]
@classmethod
def definition(io):
if n <= ... | 9be19b191a1048dffd8a6fe82caabdcb1dd33f42 | 3,649,655 |
def absent(name, database, **client_args):
"""
Ensure that given continuous query is absent.
name
Name of the continuous query to remove.
database
Name of the database that the continuous query was defined on.
"""
ret = {
"name": name,
"changes": {},
"re... | f280dad71275cd576edbefac9376463a2ab91fc7 | 3,649,656 |
def get_ads(client, customer_id, new_ad_resource_names):
"""Retrieves a google.ads.google_ads.v4.types.AdGroupAd instance.
Args:
client: A google.ads.google_ads.client.GoogleAdsClient instanc e.
customer_id: (str) Customer ID associated with the account.
new_ad_resource_names: (str) Re... | 3e1bc99901490c53c66418a63238cf76de282896 | 3,649,657 |
def corrfact_vapor_rosolem(h, h_ref=None, const=0.0054):
"""Correction factor for vapor correction from absolute humidity (g/m3).
The equation was suggested by Rosolem et al. (2013).
If no reference value for absolute humidity ``h_ref`` is provided,
the average value will be used.
Parameters
... | 6add20bf118e85e77f245776101169efb9ba4eac | 3,649,658 |
def sine_ease_out(p):
"""Modeled after quarter-cycle of sine wave (different phase)"""
return sin(p * tau) | 58a78ad44e04df42f0533b6a94e51d04398407a9 | 3,649,659 |
def _extract_codes_from_element_text(dataset, parent_el_xpath, condition=None): # pylint: disable=invalid-name
"""Extract codes for checking from a Dataset. The codes are being extracted from element text.
Args:
dataset (iati.data.Dataset): The Dataset to check Codelist values within.
parent_e... | 45e4ec2a61dc38066ad9a71d41e63a48c6ccde23 | 3,649,660 |
def rotate_im(img, angle, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101, value=None):
"""Rotate the image.
Rotate the image such that the rotated image is enclosed inside the tightest
rectangle. The area not occupied by the pixels of the original image is colored
black.
Parame... | 40ab5d9761bdb2044fe99af4d5a51187edd34327 | 3,649,661 |
def list_modules(curdir=CURDIR, pattern=MOD_FILENAME_RE):
"""List names from {ok,ng}*.py.
"""
return sorted(
m.name.replace('.py', '')
for m in curdir.glob('*.py') if pattern.match(m.name)
) | 249b276ec5f42534a4ad162c02110bcf1f9cadf0 | 3,649,662 |
def encode_set_validator_config_and_reconfigure_script(
validator_account: AccountAddress,
consensus_pubkey: bytes,
validator_network_addresses: bytes,
fullnode_network_addresses: bytes,
) -> Script:
"""# Summary
Updates a validator's configuration, and triggers a reconfiguration of the system t... | 8b5e5d259750eecf3cea78e9abba82300baa2626 | 3,649,663 |
def _do_ecf_reference_data_import(
import_method,
widget,
logwidget=None,
specification_items=None,
ecfdate=None,
datecontrol=None,
):
"""Import a new ECF club file.
widget - the manager object for the ecf data import tab
"""
ecffile = widget.datagrid.get_data_source().dbhome
... | 593b1ac77688c92c9fcd3ea8fafb3f5089849293 | 3,649,664 |
import ast
import inspect
def ast_operators(node):
"""Return a set of all operators and calls in the given AST, or return an error if any are invalid."""
if isinstance(node, (ast.Name, ast.Constant)):
return set()
elif isinstance(node, ast.BinOp):
return {type(node.op)} | ast_operators(nod... | ce5c69e228fbab682cd41330a058b6f16b8d5d1a | 3,649,665 |
def calibrate_clock(out, tolerance=0.002, dcor=False):
"""\
currently for F2xx only:
recalculate the clock calibration values and write them to the flash.
"""
device = get_msp430_type() >> 8
variables = {}
if device == 0xf2:
# first read the segment form the device, so that only the ... | 6ad9940a0b43aff54317ff0b054a5a8e84fa5f73 | 3,649,666 |
def get_rejection_listings(username):
"""
Get Rejection Listings for a user
Args:
username (str): username for user
"""
activities = models.ListingActivity.objects.for_user(username).filter(
action=models.ListingActivity.REJECTED)
return activities | 47f7078f193de651f282d1823900cd876bf9fd93 | 3,649,667 |
def quadratic_weighted_kappa(y_true, y_pred):
"""
QWK (Quadratic Weighted Kappa) Score
Args:
y_true:
target array.
y_pred:
predict array. must be a discrete format.
Returns:
QWK score
"""
return cohen_kappa_score(y_true, y_pred, weights='quadrati... | fe3208d58cfbed7fdc51ee6069bb4d72584ea6d7 | 3,649,668 |
def statistika():
"""Posodobi podatke in preusmeri na statistika.html"""
check_user_id()
data_manager.load_data_from_file()
data_manager.data_for_stats()
return bottle.template("statistika.html", data_manager=data_manager) | afc72610e4ca245089b131d06dfb5ed8a172615c | 3,649,669 |
def decrement(x):
"""Given a number x, returns x - 1 unless that would be less than
zero, in which case returns 0."""
x -= 1
if x < 0:
return 0
else:
return x | 56b95324c147a163d3bdd0e9f65782095b0a4def | 3,649,670 |
def get_dagmaf(maf: msa.Maf) -> DAGMaf.DAGMaf:
"""Converts MAF to DagMaf.
Args:
maf: MAF to be converted.
Returns:
DagMaf built from the MAF.
"""
sorted_blocks = sort_mafblocks(maf.filecontent)
dagmafnodes = [
DAGMaf.DAGMafNode(block_id=b.id,
... | 40fd06a9429874f1ca7188f2ff185c4dd8b64e01 | 3,649,671 |
def optdat10(area,lpdva,ndvab,nglb):
"""Fornece dados para a otimizacao"""
# Tipo de funcao objetivo: tpobj==1 ---Peso
# tpobj==2 ---Energia
# tpobj==3 ---Mรกxima tensรฃo
# tpobj==... | 064813cb2e66adfed6cb5e694614b88343a7613c | 3,649,672 |
def rotvec2quat(vec):
"""
A rotation vector is a 3 dimensional vector which is
co-directional to the axis of rotation and whose
norm gives the angle of rotation (in radians).
Args:
vec (list or np.ndarray): a rotational vector. Its norm
represents the angle of rotation.
Ret... | a19b7b67e9cd5877cc5045887d071e069892e0a6 | 3,649,673 |
def generate_pop(pop_size, length):
"""
ๅๅงๅ็ง็พค
:param pop_size: ็ง็พคๅฎน้
:param length: ็ผ็ ้ฟๅบฆ
:return bin_population: ไบ่ฟๅถ็ผ็ ็ง็พค
"""
decim_population = np.random.randint(0, 2**length-1, pop_size)
print(decim_population)
bin_population = [('{:0%sb}'%length).format(x) for x in decim_population]... | d1248fe59161d2a75eaf08ffe2b180537c2d1af5 | 3,649,674 |
def CountClusterSizes(clusterLabels):
""" This function takes the labels produced by spectral clustering (or
other clustering algorithm) and counts the members in each cluster.
This is primarily to see the distribution of cluster sizes over all
windows, particularly to see if there singlet... | 25bf78a83e55b72c7a33546450655efe7ee84874 | 3,649,676 |
def solver_problem1(digits_list):
"""input digits and return numbers that 1, 4, 7, 8 occurs"""
cnt = 0
for digits in digits_list:
for d in digits:
if len(d) in [2, 3, 4, 7]:
cnt += 1
return cnt | d1946d00d368ad498c9bb0a8562ec0ea76d26449 | 3,649,677 |
def spam_dotprods(rhoVecs, povms):
"""SPAM dot products (concatenates POVMS)"""
nEVecs = sum(len(povm) for povm in povms)
ret = _np.empty((len(rhoVecs), nEVecs), 'd')
for i, rhoVec in enumerate(rhoVecs):
j = 0
for povm in povms:
for EVec in povm.values():
ret[... | 95adc6ea8e1d33899a7dc96ba99589ef9bffb7fe | 3,649,678 |
def get_chi_atom_indices():
"""Returns atom indices needed to compute chi angles for all residue types.
Returns:
A tensor of shape [residue_types=21, chis=4, atoms=4]. The residue types are
in the order specified in rc.restypes + unknown residue type
at the end. For chi angles which are not d... | 5ac6f2208e2819b8e0d04329cbfb94cb5dcd26ba | 3,649,680 |
def get_all_device_stats():
"""Obtain and return statistics for all attached devices."""
devices = get_devices()
stats = {}
for serial in devices:
model, device_stats = get_device_stats(serial)
if not stats.get(model):
stats[model] = {}
stats[model][serial] = device_stats
return stats | 9f2a50c4f6008120bc9527260f501f7e261dd19f | 3,649,681 |
def plot_coefs(coefficients, nclasses):
"""
Plot the coefficients for each label
coefficients: output from clf.coef_
nclasses: total number of possible classes
"""
scale = np.max(np.abs(coefficients))
p = plt.figure(figsize=(25, 5))
for i in range(nclasses):
p = plt.subplo... | 356c6c4bb96b08a370b8c492275e638b059594e2 | 3,649,682 |
from datetime import datetime
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['data'] = True
desc['description'] = """This plot shows the number of days with a high
temperature at or above a given threshold. You can optionally generate
this ... | 479d98e9ab19dcc03332c1a95ccc0624cdcfe24d | 3,649,684 |
def calc_cost_of_buying(count, price):
"""ๆ ชใ่ฒทใใฎใซๅฟ
่ฆใชใณในใใจๆๆฐๆใ่จ็ฎ
"""
subtotal = int(count * price)
fee = calc_fee(subtotal)
return subtotal + fee, fee | 391909bbff35c6eb7d68c965e3f36317e4164b1a | 3,649,685 |
import signal
def update_lr(it_lr, alg, test_losses, lr_info=None):
"""Update learning rate according to an algorithm."""
if lr_info is None:
lr_info = {}
if alg == 'seung':
threshold = 10
if 'change' not in lr_info.keys():
lr_info['change'] = 0
if lr_info['chan... | de6ef7d700a9c4b549b6d500f6737c84dc032c95 | 3,649,687 |
from functools import reduce
def factors(n):
"""
return set of divisors of a number
"""
step = 2 if n%2 else 1
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(sqrt(n))+1, step) if n % i == 0))) | 687608f5397181892aa338c96ee299f91d7b5431 | 3,649,689 |
import decimal
def round_decimal(x, digits=0):
"""This function returns the round up float.
Parameters
----------
x : a float
digits : decimal point
Returns
----------
Rounded up float
"""
x = decimal.Decimal(str(x))
if digits == 0:
return int(... | 8670fa1e9063376e012ebbc71df0a19c6205ea9c | 3,649,690 |
def basic_gn_stem(model, data, **kwargs):
"""Add a basic ResNet stem (using GN)"""
dim = 64
p = model.ConvGN(
data, 'conv1', 3, dim, 7, group_gn=get_group_gn(dim), pad=3, stride=2
)
p = model.Relu(p, p)
p = model.MaxPool(p, 'pool1', kernel=3, pad=1, stride=2)
return p, dim | 7cd1c1e0ff58431fc89acdec0f6c1d5f6fa9daa8 | 3,649,691 |
def log_scale(start,end,num):
"""Simple wrapper to generate list of numbers equally spaced in logspace
Parameters
----------
start: floar
Inital number
end: Float
Final number
num: Float
Number of number in the list
Returns
-------
list: 1d array
Lis... | 32d3976cb9cbcceb4cef9af15da373ea84e4d0c7 | 3,649,692 |
def measure_xtran_params(neutral_point, transformation):
"""
Description: Assume that the transformation from robot coord to camera coord is: RotX -> RotY -> RotZ -> Tranl
In this case: RotX = 180, RotY = 0; RotZ = -90; Tranl: unknown
But we know coords of a determined neutral ... | c2758158d545dbc6c2591f7f64f1df159a0c82db | 3,649,693 |
def getPrefix(routetbl, peer_logical):
""" FUNCTION TO GET THE PREFIX """
for route in routetbl:
if route.via == peer_logical:
return route.name
else:
pass | 2ca32a1fd63d6fcefbcc9ac23e8636c73e88455b | 3,649,694 |
def Logger_log(level, msg):
"""
Logger.log(level, msg)
logs a message to the log.
:param int level: the level to log at.
:param str msg: the message to log.
"""
return _roadrunner.Logger_log(level, msg) | af552b17aaeebef9713efffedcabd75946c961f1 | 3,649,695 |
import typing
def obj_test(**field_tests: typing.Callable[[typing.Any], bool]) -> typing.Callable[[typing.Any], bool]:
"""Return a lambda that tests for dict with string keys and a particular type for each key"""
def test(dat: typing.Any) -> bool:
type_test(dict)(dat)
dom_test = type_test(str... | 0439821b634807e178539b0444b69305c15e2e4e | 3,649,696 |
def hist2D(x, y, xbins, ybins, **kwargs):
""" Create a 2 dimensional pdf vias numpy histogram2d"""
H, xedg, yedg = np.histogram2d(x=x, y=y, bins=[xbins,ybins], density=True, **kwargs)
xcen = (xedg[:-1] + xedg[1:]) / 2
ycen = (yedg[:-1] + yedg[1:]) / 2
return xcen, ycen, H | 7f192f4db38e954aad96abc66fa4dc9c190acd82 | 3,649,697 |
def generate_ngram_dict(filename, tuple_length):
"""Generate a dict with ngrams as key following words as value
:param filename: Filename to read from.
:param tuple_length: The length of the ngram keys
:return: Dict of the form {ngram: [next_words], ... }
"""
def file_words(file_pointer):
... | 45f7eccae852e61f20044448955cade00174998c | 3,649,698 |
def get_end_point(centerline, offset=0):
"""
Get last point(s) of the centerline(s)
Args:
centerline (vtkPolyData): Centerline(s)
offset (int): Number of points from the end point to be selected
Returns:
centerline_end_point (vtkPoint): Point corresponding to end of centerline.... | f476e93b55bb046cfb6afb61a2e3ae37a172def3 | 3,649,699 |
def random_train_test_split(df, train_frac, random_seed=None):
"""
This function randomizes the dta based on the seed and then splits the dataframe into train and test sets which are changed to their list of vector representations.
Args:
df (Dataframe): The dataframe which is to be used to generate... | c3c399792bdc1026d74f1ccc7241bdb327f307d3 | 3,649,700 |
def calc_XY_pixelpositions(calibration_parameters, DATA_Q, nspots, UBmatrix=None,
B0matrix=IDENTITYMATRIX,
offset=0,
pureRotation=0,
... | 243bdb74da8aa429a0748d6d15b6b9d1f20814f3 | 3,649,701 |
def load_csv(path):
"""
Function for importing data from csv. Function uses weka implementation
of CSVLoader.
:param path: input file
:return: weka arff data
"""
args, _sufix = csv_loader_parser()
loader = Loader(classname='weka.core.converters.CSVLoader',
options=ar... | d7555cbe5e54543ca8f66e5f70d4f20b7b72b549 | 3,649,702 |
import json
def from_stream(stream, storage, form):
"""Reverses to_stream, returning data"""
if storage == "pure-plain":
assert isinstance(stream, str)
if isinstance(stream, str):
txt = stream
else:
assert not stream.startswith(MAGIC_SEAMLESS)
assert... | ee8c657162947354b3533b4fe607a11a8a6457ec | 3,649,703 |
def UniformExploration(j, state):
"""Fake player j that always targets all arms."""
return list(np.arange(state.K)) | 146b84ff0d9e28a8316e871b94e5bb82d67de997 | 3,649,705 |
def deduction_limits(data):
"""
Apply limits on itemized deductions
"""
# Split charitable contributions into cash and non-cash using ratio in PUF
cash = 0.82013
non_cash = 1. - cash
data['e19800'] = data['CHARITABLE'] * cash
data['e20100'] = data['CHARITABLE'] * non_cash
# Apply st... | ef1a6464e4bb0832a9398ad01e878c8aa4e6a620 | 3,649,706 |
def select_interacting(num_mtx, bin_mtx, labels):
"""
Auxiliary function for fit_msa_mdels.
Used for fitting the models in hard EM; selects observations with a hidden
variable value of 1.
"""
if labels is None:
# This is the case when initializing the models
return num_mtx, bin_m... | 4c4f6fd7b44d4c388f7ce9ba30e91886548c85ee | 3,649,708 |
def _GenDiscoveryDoc(service_class_names, doc_format,
output_path, hostname=None,
application_path=None):
"""Write discovery documents generated from a cloud service to file.
Args:
service_class_names: A list of fully qualified ProtoRPC service names.
doc_format: T... | a135c3805ee5b81e2f0f505b1710531e3db7d1f1 | 3,649,709 |
import dateutil.parser
def nitestr(nite,sep=''):
"""
Convert an ephem.Date object to a nite string.
Parameters:
-----------
nite : ephem.Date object
sep : Output separator
Returns:
--------
nitestr : String representation of the nite
"""
if isinstance(nite,bases... | 493f34ad484bbd350254c45e38c41a9559a2ce14 | 3,649,710 |
def dump_tuple(tup):
"""
Dump a tuple to a string of fg,bg,attr (optional)
"""
return ','.join(str(i) for i in tup) | ffa4838e2794da9d525b60f4606633f8940480bb | 3,649,712 |
from operator import ne
def generate_fermi_question(cfg, logratio, filter_single_number_lhs=True):
"""
Generates one Fermi question.
Args:
cfg: Expression config
logratio: Log ratio standard deviation (for RHS)
filter_single_number_lhs: Whether to exclude lhs of a single numerical... | 47ebeaa4389f7371fb56687788a696aa7e03426e | 3,649,714 |
def build_dataset(cfg, default_args=None):
"""Build a dataset from config dict.
Args:
cfg (dict): Config dict. It should at least contain the key "type".
default_args (dict | None, optional): Default initialization arguments.
Default: None.
Returns:
Dataset: The constru... | 12b7d9121b9395668b8d260790b980260e1e4ee5 | 3,649,715 |
def Packet_genReadUserTag(errorDetectionMode, buffer, size):
"""Packet_genReadUserTag(vn::protocol::uart::ErrorDetectionMode errorDetectionMode, char * buffer, size_t size) -> size_t"""
return _libvncxx.Packet_genReadUserTag(errorDetectionMode, buffer, size) | 111c391ee3bbef36e1d42666d608c72fb3e6c3cd | 3,649,716 |
def prefetch(tensor_dict, capacity):
"""Creates a prefetch queue for tensors.
Creates a FIFO queue to asynchronously enqueue tensor_dicts and returns a
dequeue op that evaluates to a tensor_dict. This function is useful in
prefetching preprocessed tensors so that the data is readily available for
consumers.
... | 44320c6ea24d42b9add4bd3a3677b157ffcd24b8 | 3,649,717 |
def get_total_shares():
"""
Returns a list of total shares (all, attending, in person, represented) for all voting principles.
"""
total_shares = {
'heads': [0, 0, 0, 0] # [all, attending, in person, represented]
}
principle_ids = VotingPrinciple.objects.values_list('id', flat=True)
... | c70ca3be6e0b7b9df03257b81f5abec343efa37e | 3,649,718 |
def gen_check_box_idx():
""" Generate a list containing the coordinate of three
finder patterns in QR-code
Args:
None
Returns:
idx_check_box: a list containing the coordinate each pixel
of the three finder patterns
"""
idx_check_box = []
for i in range(7... | e26d9c5a3b093b52f54eb2c65b844215c40ddab8 | 3,649,719 |
import pandas
def preprocess_mc_parameters(n_rv, dict_safir_file_param, index_column='index'):
"""
NAME: preprocess_mc_parameters
AUTHOR: Ian Fu
DATE: 18 Oct 2018
DESCRIPTION:
Takes a dictionary object with each item represents a safir input variable, distributed or static, distributed
inp... | 28d04122234572b57d978fc9e993707cea45a00d | 3,649,720 |
def AdjustColour(color, percent, alpha=wx.ALPHA_OPAQUE):
""" Brighten/Darken input colour by percent and adjust alpha
channel if needed. Returns the modified color.
@param color: color object to adjust
@param percent: percent to adjust +(brighten) or -(darken)
@keyword alpha: amount to adjust alpha ... | 76ca657e632467c5db730161a34f19633add06f4 | 3,649,721 |
def getdates(startdate, utc_to_local, enddate=None):
"""
Generate '~astropy.tot_time.Time' objects corresponding to 16:00:00 local tot_time on evenings of first and last
nights of scheduling period.
Parameters
----------
startdate : str or None
Start date (eg. 'YYYY-MM-DD'). If None, de... | 1bee7b83b2b4ce3f3347544441762287a3ff1c83 | 3,649,722 |
def get_dataframe_tail(n):
""" Returns last n rows of the DataFrame"""
return dataset.tail(n) | 03a01a9535da25d30c394a8339ebbd5bd0a80b03 | 3,649,724 |
import json
def json_formatter(result, verbose=False, indent=4, offset=0):
"""Format result as json."""
string = json.dumps(result, indent=indent)
string = string.replace("\n", "\n" + " "*offset)
return string | 512847722fa36eff408ac28d6e3dc8fde5c52af1 | 3,649,725 |
def _gumbel_softmax_sample(logits, temp=1, eps=1e-20):
"""
Draw a sample from the Gumbel-Softmax distribution
based on
https://github.com/ericjang/gumbel-softmax/blob/3c8584924603869e90ca74ac20a6a03d99a91ef9/Categorical%20VAE.ipynb
(MIT license)
"""
dims = logits.dim()
gumbel_noise = _sa... | a61eac3861cdca17c1d2856c83bc70e03168bc45 | 3,649,727 |
from re import VERBOSE
def interpolate_points(variable, variable_name, old_r, old_theta, new_r, new_theta):
"""Interpolate the old grid onto the new grid."""
grid = griddata(
(old_r, old_theta), variable, (new_r, new_theta), method=INTERPOLATION_LEVEL, fill_value=-1
)
n_error = 0
for i, ... | 2a830e7cd04d5d0832d35a25bc58041ba192709b | 3,649,728 |
def currentProgram():
"""currentProgram page."""
return render_template(
"currentProgram-index.j2.html",
title="currentProgram",
subtitle="Demonstration of Flask blueprints in action.",
template="currentProgram-template",
currentProgram=getCurrentProgr(),
timeStar... | f5c914560d3c1791e34749321b78951313d5f058 | 3,649,730 |
def checkIsMember(request):
"""
์ฌ์
์๋ฒํธ๋ฅผ ์กฐํํ์ฌ ์ฐ๋ํ์ ๊ฐ์
์ฌ๋ถ๋ฅผ ํ์ธํฉ๋๋ค.
- https://docs.popbill.com/statement/python/api#CheckIsMember
"""
try:
# ์กฐํํ ์ฌ์
์๋ฑ๋ก๋ฒํธ, '-' ์ ์ธ 10์๋ฆฌ
targetCorpNum = "1234567890"
response = statementService.checkIsMember(targetCorpNum)
return render(reques... | 861d4cc83102e036bb795bf8eafee2f7593925a4 | 3,649,731 |
from typing import List
from typing import Optional
from typing import Type
def f1_score(y_true: List[List[str]], y_pred: List[List[str]],
*,
average: Optional[str] = 'micro',
suffix: bool = False,
mode: Optional[str] = None,
sample_weight: Optional[Lis... | 1354e306847af1decf59ae638a1cdecd265e569a | 3,649,732 |
from typing import Any
from typing import Counter
def calc_proportion_identical(lst: Any) -> float:
"""
Returns a value between 0 and 1 for the uniformity of the values
in LST, i.e. higher if they're all the same.
"""
def count_most_common(lst):
"""
Find the most common item in LS... | adf467eba11694c5ea4583d7b53029110e59e25a | 3,649,733 |
def _rolling_mad(arr, window):
"""Rolling window MAD outlier detection on 1d array."""
outliers = []
for i in range(window, len(arr)):
cur = arr[(i - window) : i]
med, cur_mad = _mad(cur)
cur_out = cur > (med + cur_mad * 3)
idx = list(np.arange((i - window), i)[cur_out])
... | 3f28dde448b3c567a92fd22e499f812cd748a507 | 3,649,734 |
def compute_mean_and_cov(embeds, labels):
"""Computes class-specific means and shared covariance matrix of given embedding.
The computation follows Eq (1) in [1].
Args:
embeds: An np.array of size [n_train_sample, n_dim], where n_train_sample is
the sample size of training set, n_dim is the dimension ... | b6d5624b0cea9f6162ffad819d4d5917391ac73e | 3,649,735 |
def wcenergy(seq: str, temperature: float, negate: bool = False) -> float:
"""Return the wc energy of seq binding to its complement."""
loop_energies = calculate_loop_energies_dict(temperature, negate)
return sum(loop_energies[seq[i:i + 2]] for i in range(len(seq) - 1)) | 90eae3d85e90019571e4f5d674fb93d58c1d7287 | 3,649,736 |
def upload_csv():
"""
Upload csv file
"""
upload_csv_form = UploadCSVForm()
if upload_csv_form.validate_on_submit():
file = upload_csv_form.csv.data
ClassCheck.process_csv_file(file)
flash('CSV file uploaded!', 'success')
return redirect('/') | 620cc3b4e11c71fe9dedd24631f641304313150f | 3,649,738 |
async def clean(request: Request) -> RedirectResponse:
"""Access this view (GET "/clean") to remove all session contents."""
request.session.clear()
return RedirectResponse("/") | 3ef0d9298fcd7879becc8ae246656a62086f639a | 3,649,739 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.