content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import requests
def _getPVGIS(lat, lon):
"""
This function uses the non-interactive version of PVGIS to extract a
tmy dataset to be used to predict VRE yields for future periods.
------ inputs ------
Latitude, in decimal degrees, south is negative.
Longitude, in decimal degrees, wes... | e4d47cb3efab61bae1e5d38a87c642c687176ed3 | 3,641,559 |
def get_metric_key_samples(metricDict, metricNames, keyVal="means"):
"""
Returns a dictionary of samples for the given metric name, but only extracts
the samples for the given key
Args:
metricDict (dict): Dictionary of sampled metrics
metricNames (list): Names of the keys of the metric ... | f6b2bb32218654d90404812654623580ab4425df | 3,641,560 |
import requests
def swapi_films(episode):
"""
Gets the films listed in the api.
:param episode:
:return: response json
"""
response = requests.get(SWAPI_API + 'films/' + str(episode))
return response | fab283eeb2c96db1e509d4262fed79f7f4652fca | 3,641,562 |
def prepare_qualifications(request, bids=[], lotId=None):
""" creates Qualification for each Bid
"""
new_qualifications = []
tender = request.validated["tender"]
if not bids:
bids = tender.bids
if tender.lots:
active_lots = [lot.id for lot in tender.lots if lot.status == "active"... | 53399716f029d4b7bebc45ddef8e6f39272e33d1 | 3,641,563 |
def int_format(x):
"""
Format an integer:
- upcast to a (u)int64
- determine buffer size
- use snprintf
"""
x = upcast(x)
buf = flypy.runtime.obj.core.newbuffer(flypy.types.char, ndigits(x) + 1)
formatting.sprintf(buf, getformat(x), x)
return flypy.types.String(buf) | 363b4998bca8c45eb6a5a3b825270ce48bbb237e | 3,641,564 |
import re
def pyccparser2cbmc(srcfile, libs):
"""
Transforms the result of a parsed file from pycparser to a valid cbmc
input.
"""
fd = open(srcfile, "r")
src = fd.read()
fd.close()
# Replace the definition of __VERIFIER_error with the one for CBMC
if "extern void __VERIFIER_error();" in src:
# print "__... | 499208680da71382d652d655a95c227d29129ee5 | 3,641,565 |
import dill
import base64
def check_finished(worker, exec_id):
"""
:param worker:
:param exec_id:
:return:
"""
result = worker.status(exec_id)
status = dill.loads(base64.b64decode(result.data))
if status["status"] == "FAILED":
raise Exception("Remote job execution failed")
... | 285090fd0fcdfce6964aa43f4af0fae836175ab1 | 3,641,566 |
def round_filters(filters, global_params):
""" Calculate and round number of filters based on depth multiplier. """
multiplier = global_params.width_coefficient
if not multiplier:
return filters
divisor = global_params.depth_divisor
min_depth = global_params.min_depth
filters *= multipli... | b39ca8a0b77ae1c134983e20725297fa6bccdac8 | 3,641,567 |
def admin_user_detail():
"""管理员信息编辑详情页"""
if not g.user.is_admin:
return redirect('/')
if request.method == 'GET':
# 获取参数
admin_id = request.args.get('admin_id')
if not admin_id:
abort(404)
try:
admin_id = int(admin_id)
except Excepti... | 2b8ec2201688d0e5fcc49e77fd1a238413d259e3 | 3,641,568 |
def splitBinNum(binNum):
"""Split an alternate block number into latitude and longitude parts.
Args:
binNum (int): Alternative block number
Returns:
:tuple Tuple:
1. (int) Latitude portion of the alternate block number.
Example: ``614123`` => ``614``
2.... | da9b9cc67d592e73da842f4b686c0d16985f3457 | 3,641,569 |
def load_model_from_params_file(model):
"""
case 0: CHECKPOINT.CONVERT_MODEL = True:
Convert the model
case 1: CHECKPOINT.RESUME = False and TRAIN.PARAMS_FILE is not none:
load params_file
case 2: CHECKPOINT.RESUME = True and TRAIN.PARAMS_FILE is not none:
case 2a: if checkpoin... | 4f7c862829135e8b01038c6c9a540aeb1f55e285 | 3,641,570 |
def getPool(pool_type='avg', gmp_lambda=1e3, lse_r=10):
"""
# NOTE: this function is not used in writer_ident, s. constructor of
# ResNet50Encoder
params
pool_type: the allowed pool types
gmp_lambda: the initial regularization parameter for GMP
lse_r: the initial regularization p... | 751bd851d57d37f7cf0749ba2183b67d59722c83 | 3,641,571 |
def draw_transperency(image, mask, color_f, color_b):
"""
image (np.uint8)
mask (np.float32) range from 0 to 1
"""
mask = mask.round()
alpha = np.zeros_like(image, dtype=np.uint8)
alpha[mask == 1, :] = color_f
alpha[mask == 0, :] = color_b
image_alpha = cv2.add(image, alpha)
ret... | 900269f7a36a4daa8c87cb2e2b5adc5b9be8728e | 3,641,572 |
def split_in_pairs(s, padding = "0"):
"""
Takes a string and splits into an iterable of strings of two characters each.
Made to break up a hex string into octets, so default is to pad an odd length
string with a 0 in front. An alternative character may be specified as the
second argument.
"""
... | 8807448bb8125c80fa78ba32f887a54ba9bab1dd | 3,641,573 |
def make_slicer_query_with_totals_and_references(
database,
table,
joins,
dimensions,
metrics,
operations,
filters,
references,
orders,
share_dimensions=(),
):
"""
:param dataset:
:param database:
:param table:
:param joins:
:param dimensions:
:param m... | ea77cf6729cc8b677758801d53338d96e67b167f | 3,641,574 |
def corr_na(array1, array2, corr_method: str = 'spearmanr', **addl_kws):
"""Correlation method that tolerates missing values. Can take pearsonr or spearmanr.
Args:
array1: Vector of values
array2: Vector of values
corr_method: Which method to use, pearsonr or spearmanr.
**addl_k... | b534898dee50b06488514de5b21d6ea7fcf025f6 | 3,641,575 |
def has_global(node, name):
"""
check whether node has name in its globals list
"""
return hasattr(node, "globals") and name in node.globals | 7a2ef301cb25cba242d8544e2c191a537f63bf19 | 3,641,577 |
def make_generator_model(input_dim=100) -> tf.keras.Model:
"""Generator モデルを生成する
Args:
input_dim (int, optional): 入力次元. Defaults to 100.
Returns:
tf.keras.Model: Generator モデル
"""
dense_size = (7, 7, 256)
conv2d1_channel = 128
conv2d2_channel = 64
conv2d3_channel = 1
... | 3214afc37153471dae0c599a93cb95def1da8971 | 3,641,578 |
from unittest.mock import call
def deploy_gradle(app, deltas={}):
"""Deploy a Java application using Gradle"""
java_path = join(ENV_ROOT, app)
build_path = join(APP_ROOT, app, 'build')
env_file = join(APP_ROOT, app, 'ENV')
env = {
'VIRTUAL_ENV': java_path,
"PATH": ':'.join([join(j... | d1be9ecd675389c05324d4e1f0e077414db814a5 | 3,641,579 |
from typing import Optional
def find_badge_by_slug(slug: str) -> Optional[Badge]:
"""Return the badge with that slug, or `None` if not found."""
badge = db.session \
.query(DbBadge) \
.filter_by(slug=slug) \
.one_or_none()
if badge is None:
return None
return _db_enti... | ec4102cf529b247c0b725e7c32d4b9de9c3a1e98 | 3,641,580 |
import logging
def validate_color(color,default,color_type):
"""Validate a color against known PIL values. Return the validated color if valid; otherwise return a default.
Keyword arguments:
color: color to test.
default: default color string value if color is invalid.
color_type: string name for color type,... | 2a91a9f5db2cbed3d530af12e8c383b65c5e2fa8 | 3,641,582 |
def d_xx_yy_tt(psi):
"""Return the second derivative of the field psi by fft
Parameters
--------------
psi : array of complex64 for the field
Returns
--------------
cxx psi_xx+ cyy psi_yy + ctt psi_tt : second derivatives with respect to x
"""
# this function is to remove
glob... | 12980ca705f5a1f3f3514d792cfc4e06529d0600 | 3,641,583 |
from typing import Iterable
def negate_objective(objective):
"""Take the negative of the given objective (converts a gain into a loss and vice versa)."""
if isinstance(objective, Iterable):
return (list)((map)(negate_objective, objective))
else:
return -objective | e24877d00b7c84e04c0cb38b5facdba85694890f | 3,641,584 |
from typing import Any
import json
def process_vm_size(file_name: str) -> Any:
"""
Extract VMs instance specification.
:file_name (str) File name
Return VMs specification object
"""
current_app.logger.info(f'Processing VM Size {file_name}...')
file = open(file_name,)
data = json.loa... | 7afe372fa82769ac6add9e473bce082f0e268318 | 3,641,585 |
def gen_key(password, salt, dkLen=BLOCKSIZE):
"""
Implement PBKDF2 to make short passwords match the BLOCKSIZE.
Parameters
---------
password str
salt str
dkLen int
Returns
-------
- str
"""
return KDF.PBKDF2(pas... | 134d6c7b17f2aea869bfb79f72a0126367d44b36 | 3,641,586 |
import six
def _bytes_feature(value):
"""Wrapper for inserting bytes features into Example proto."""
if isinstance(value, six.string_types):
value = six.binary_type(value, encoding='utf-8')
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) | 85bdab9a6445ec224f8e5f54be5b775008582d48 | 3,641,587 |
def parse_plot_set(plot_set_string):
"""
Given one of the string arguments to the --plot-sets option, parse out a
data structure representing which conditions ought to be compared against
each other, and what those comparison plots/tables should be called.
The syntax of a plot set is [title:]c... | 1df83681aa3110dfd9302bd7918f15dfbfa497ab | 3,641,588 |
def check_types_excel(row: tuple) -> bool:
"""Returns true if row from excel file has correct types"""
if not isinstance(row[1], (pd.Timestamp, str)):
return False
if not ((isinstance(row[2], dt.time) and isinstance(row[3], dt.time)) or
(isinstance(row[2], str) and isinstance(row[3], str... | 80ac33feff968de076bd29f34350bcf518cd34d5 | 3,641,589 |
def add(num1, num2):
""" Adds two numbers
>>> add(2,4)
6
"""
return num1 + num2 | 932981ca91c01817242e57e1be55c35441337fc4 | 3,641,590 |
def is_palindrome1(str):
"""
Create slice with negative step and confirm equality with str.
"""
return str[::-1] == str | 39dbc19d0d73b956c9af24abc1babae18c816d73 | 3,641,591 |
from datetime import datetime
def number_generetor(view, form):
""" Генератор номера платежа (по умолчанию) """
if is_py2:
uuid_fields = uuid4().get_fields()
else:
uuid_fields = uuid4().fields
return u'{:%Y%m%d}-{:08x}'.format(datetime.now(), uuid_fields[0]) | 005cd8347b903be3adffe56d7c8c53ba79ebf2e8 | 3,641,592 |
def get_underlay_info():
"""
:return:
"""
return underlay_info | a48f2ede459a4ca8969e095e94ba09b99e59300d | 3,641,593 |
async def get_guild_roles(id_: int):
"""
Get the roles of a guild
:param id_: Guild ID
:return: List of roles
"""
guild = await router.bot.rest.fetch_guild(id_)
if guild is None:
return status.HTTP_404_NOT_FOUND
roles = await guild.fetch_roles()
return [to_dict(role) for role... | 4d5084f62f29a5038dc3111b047b1644a96a958a | 3,641,594 |
def prior_min_field(field_name, field_value):
"""
Creates prior min field with the
:param field_name: prior name (field name initial)
:param field_value: field initial properties
:return: name of the min field, updated field properties
"""
name = field_name
value = field_value.copy()
... | 9f331ee58e699318e678d881c0028486b746c05c | 3,641,595 |
def checkpoint_save_config():
"""Fixture to create a config for saving attributes of a detector."""
toolset = {
"test_id": "Dummy_test",
"saved_attributes": {
"FeatureExtraction": [
"dummy_dict",
"dummy_list",
"dummy_tuple",
... | 6cb7e05a5eb680f6915fc58f40e72403787eea8b | 3,641,596 |
def matrix_sum_power(A, T):
"""Take the sum of the powers of a matrix, i.e.,
sum_{t=1} ^T A^t.
:param A: Matrix to be powered
:type A: np.ndarray
:param T: Maximum order for the matrixpower
:type T: int
:return: Powered matrix
:rtype: np.ndarray
"""
At = np.eye(A.shape[0])
... | b590f0751c114bd7cfeaa39d3d03a3de49007c62 | 3,641,597 |
def mean_zero_unit_variance(arr, mean_vector=None, std_vector=None, samples_in='row'):
"""
Normalize input data to have zero mean and unit variance.
Return the normalized data, the mean, and the calculated standard
deviation which was used to normalize the data
[normalized, meanvec, stddev] = mean_... | 38a1ca262362b3f04aed06f3f0d21836eca8d5ad | 3,641,598 |
import torch
def soft_precision(scores: torch.FloatTensor,
mask: torch.FloatTensor) -> torch.FloatTensor:
"""
Helper function for computing soft precision in batch.
# Parameters
scores : torch.FloatTensor
Tensor of scores with shape: (num_refs, num_cands, max_ref_len, max_c... | e76552bde3ae58f5b976abbf58e5dac1d4995117 | 3,641,599 |
from pathlib import Path
import scipy
from datetime import datetime
def fit_sir(times, T_real, gamma, population, store, pathtoloc, tfmt='%Y-%m-%d', method_solver='DOP853', verbose=True, \
b_scale=1):
"""
Fit the dynamics of the SIR starting from real data contained in `pathtocssegi`.
The initial co... | 7a7da41fc178c805cc334e5a0060a2f9cc5f29d3 | 3,641,600 |
from typing import Dict
from typing import OrderedDict
def panelist_debuts_by_year(database_connection: mysql.connector.connect
) -> Dict:
"""Returns an OrderedDict of show years with a list of panelists'
debut information"""
show_years = retrieve_show_years(database_connection... | 40ba0cd67991b7c83b33e77522065b8bb75232c1 | 3,641,601 |
def _stirring_conditions_html(stirring: reaction_pb2.StirringConditions) -> str:
"""Generates an HTML-ready description of stirring conditions.
Args:
stirring: StirringConditions message.
Returns:
String description of the stirring conditions.
"""
if stirring.type == stirring.NONE:... | 0f03c67602163da3b732dfdcb0d367c6a0806c0d | 3,641,602 |
def set_effective_property_value_for_node(
nodeId: dom.NodeId, propertyName: str, value: str
) -> dict:
"""Find a rule with the given active property for the given node and set the new value for this
property
Parameters
----------
nodeId: dom.NodeId
The element id for which to set p... | 36cf035bd878ac4c4936cebbacc115273807b892 | 3,641,605 |
def classroom_page(request,unique_id):
"""
Classroom Setting Page.
"""
classroom = get_object_or_404(Classroom,unique_id=unique_id)
pending_members = classroom.pending_members.all()
admins = classroom.special_permissions.all()
members = admins | classroom.members.all()
is_admin = classr... | fc37979a44da63fb0dc174799523f3a77fefb1e4 | 3,641,606 |
def concat_hists(hist_array: np.array):
"""Concatenate multiple histograms in an array by adding them up with error prop."""
hist_final = hist_array[0]
for hist in hist_array[1:]:
hist_final.addhist(hist)
return hist_final | e659ceb97f38620f561920ddab6339ecb901ee55 | 3,641,607 |
def renorm_flux_lightcurve(flux, fluxerr, mu):
""" Normalise flux light curves with distance modulus."""
d = 10 ** (mu/5 + 1)
dsquared = d**2
norm = 1e18
# print('d**2', dsquared/norm)
fluxout = flux * dsquared / norm
fluxerrout = fluxerr * dsquared / norm
return fluxout, fluxerrout | 97f2606d54b106d2051983dfc29d942112e7a1e3 | 3,641,608 |
def find_focus(stack):
"""
Parameters
----------
stack: (nd-array) Image stack of dimension (Z, ...) to find focus
Returns
-------
focus_idx: (int) Index corresponding to the focal plane of the stack
"""
def brenner_gradient(im):
assert len(im.shape) == 2, 'Input ima... | 234cecb9c43f9427cd8c5d1e9b2ae24c14239835 | 3,641,610 |
def get_amr_line(input_f):
"""Read the amr file. AMRs are separated by a blank line."""
cur_amr=[]
has_content=False
for line in input_f:
if line[0]=="(" and len(cur_amr)!=0:
cur_amr=[]
if line.strip()=="":
if not has_content:
continue
else:
... | 5b0c980a8c68143d8fdeb413185ee445b11cd30b | 3,641,611 |
def getHwAddrForIp(ip):
"""
Returns the MAC address for the first interface that matches the given IP
Returns None if not found
"""
for i in netifaces.interfaces():
addrs = netifaces.ifaddresses(i)
try:
if_mac = addrs[netifaces.AF_LINK][0]['addr']
if_ip = addrs[netifaces.AF_INET][0]['addr']
except Inde... | efbeb494ed0a3fb135e87a66a170a94f4ca78231 | 3,641,612 |
def rbf_multiquadric(r, epsilon=1.0, beta=2.5):
"""
multiquadric
"""
return np.sqrt((epsilon*r)**2 + 1.0) | 068ab09a609a47e631d91f90634fe4a5810e0fd1 | 3,641,613 |
def is_valid_sudoku(board):
"""
Checks if an input sudoku board is valid
Algorithm:
For all non-empty squares on board, if value at that square is a number,
check if the that value exists in that square's row, column,
and minor square.
If it is, return False.
"""
cols = [set(... | 001a02a47acbaa192215d985f3d743c42a9fb42b | 3,641,614 |
def lab_to_nwb_dict(lab_key):
"""
Generate a dictionary containing all relevant lab and institution info
:param lab_key: Key specifying one entry in element_lab.lab.Lab
:return: dictionary with NWB parameters
"""
lab_info = (lab.Lab & lab_key).fetch1()
return dict(
institution=lab_in... | dcde08b3421d56003d23ca19747430c6d95bf431 | 3,641,615 |
from typing import Set
from re import A
def length(self: Set[A]) -> int:
"""
Returns the length (number of elements) of the set. `size` is an alias for length.
Returns:
The length of the set
"""
return len(self) | cab214f7b06fc8ae604286cd40d6d558d05b7175 | 3,641,616 |
import time
def timestamp(tdigits=8):
"""Return a unique timestamp string for the session. useful for ensuring
unique function identifiers, etc.
"""
return str(time.clock()).replace(".", "").replace("-", "")[: tdigits + 1] | b209795f67735ada82238e5fa47f5132efa61384 | 3,641,617 |
def is_wrapped_exposed_object(obj):
"""
Return True if ``obj`` is a Lua (lupa) wrapper for a BaseExposedObject
instance
"""
if not hasattr(obj, 'is_object') or not callable(obj.is_object):
return False
return bool(obj.is_object()) | 117a43f9dcc886dc88a77c2ace016b89e43b3c4c | 3,641,619 |
def no_transform(image):
"""Pass through the original image without transformation.
Returns a tuple with None to maintain compatability with processes that
evaluate the transform.
"""
return (image, None) | 25b45a5c77d3c2864ebc7a046e0f47b2fafb067b | 3,641,620 |
def build_menu(buttons, n_cols, header_buttons=None, footer_buttons=None):
"""Builds a menu with the given style using the provided buttons
:return:
list of buttons
"""
menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
if header_buttons:
menu.insert(0, [header_b... | f068ef9222b7e16cf19d901961f0315b2d6aebe3 | 3,641,621 |
def SSderivative(ds):
"""
Given a time-step ds, and an single input time history u, this SS model
returns the output y=[u,du/ds], where du/dt is computed with second order
accuracy.
"""
A = np.array([[0]])
Bm1 = np.array([0.5 / ds])
B0 = np.array([[-2 / ds]])
B1 = np.array([[1.5 / d... | c255937fd1f727932d5b09fc70c586e7bdb10bf1 | 3,641,623 |
def clean_post(value):
"""Remove unwanted elements in post content"""
doc = lxml.html.fragment_fromstring(value)
doc.tag = 'div' # replaces <li>
doc.attrib.clear()
# remove comment owner info
for e in doc.xpath('//div[@class="weblog_keywords"]'):
e.drop_tree()
return lxml.html.tost... | c7670d5632760b577aa7ac9dae24de15bf164c67 | 3,641,624 |
def get_houdini_version(as_string=True):
"""
Returns version of the executed Houdini
:param as_string: bool, Whether to return the stiring version or not
:return: variant, int or str
"""
if as_string:
return hou.applicationVersionString()
else:
return hou.applicationVersion(... | efcc18a89552f8dd1c4807be2042b51db2c2fb61 | 3,641,625 |
import socket
def check_port_open(port: int) -> bool:
"""
Проверка на свободный порт port
Является частью логики port_validation
"""
try:
sock = socket.socket()
sock.bind(("", port))
sock.close()
print(f"Порт {port} свободен")
return True
except OSError... | 76ba3ddd03bf1672b8b4ce5fd048561c3a9e78e8 | 3,641,626 |
from datetime import datetime
def convert_date_to_tick_tick_format(datetime_obj, tz: str):
"""
Parses ISO 8601 Format to Tick Tick Date Format
It first converts the datetime object to UTC time based off the passed time zone, and then
returns a string with the TickTick required date format.
!!! i... | 9f8efc2136b75310649d31328d4359d2030aff97 | 3,641,627 |
def measurement(resp, p):
"""model measurement effects in the filters by translating the response at
each location and stimulus (first 3 axes of resp) toward the filterwise mean
(4th axis) according to proportion p. p=1 means that all filters reduce
to their respective means; p=0 does nothing; p<0 is po... | 99d24b3b790c0aa1d2873ca5521144a1e326b661 | 3,641,628 |
def irpf(salario,base=12.5,prorrateo=0):
"""Entra el salario y la base, opcionalmente un parametro para prorratear
Si no se da el valor de la bas3e por defecto es 12.5"""
if type(salario)==float and type(base)==float:
if prorrateo==True:
return (salario*(1+2/12))*(base/100)
elif ... | b549e78f2cbd3227cc99d4ce7277a90058696895 | 3,641,629 |
def get2p3dSlaterCondonUop(Fdd=(9, 0, 8, 0, 6), Fpp=(20, 0, 8), Fpd=(10, 0, 8), Gpd=(0, 3, 0, 2)):
"""
Return a 2p-3d U operator containing a sum of
different Slater-Condon proccesses.
Parameters
----------
Fdd : tuple
Fpp : tuple
Fpd : tuple
Gpd : tuple
"""
# Calculate F_d... | 6ae077b1913bf40f93adcdbbbbc882baa9d56eea | 3,641,630 |
from typing import AnyStr
import pickle
def read_meta_fs(filename: AnyStr):
"""
Read meta data from disk.
"""
settings.Path(filename).mkdir(parents=True, exist_ok=True)
filepath = settings.pj(filename, "meta.pkl")
with open(filepath, "rb") as fh:
return pickle.load(fh) | 8fdf4c74d34c623cd1ac7d15f32f891685f1d863 | 3,641,631 |
def compile(model, ptr, vtr, num_y_per_branch=1):
"""Create a list with ground truth, loss functions and loss weights.
"""
yholder_tr = []
losses = []
loss_weights = []
num_blocks = int(len(model.output) / (num_y_per_branch + 1))
printcn(OKBLUE,
'Compiling model with %d outputs ... | 24af75f3b5bc6ba06d88f81023c2c7011f1d6922 | 3,641,632 |
import html
def strip_clean(input_text):
"""Strip out undesired tags.
This removes tags like <script>, but leaves characters like & unescaped.
The goal is to store the raw text in the database with the XSS nastiness.
By doing this, the content in the database is raw
and Django can continue to ass... | 83e2bd3cb5c2645dd4ea611fd0e0577d118b8326 | 3,641,633 |
def setup(mu=MU, sigma=SIGMA, beta=BETA, tau=TAU,
draw_probability=DRAW_PROBABILITY, backend=None, env=None):
"""Setups the global environment.
:param env: the specific :class:`TrueSkill` object to be the global
environment. It is optional.
>>> Rating()
trueskill.Rating(mu=2... | ce797c9994e477bc618f8f52cc63babcc61b78fd | 3,641,634 |
def _bytepad(x, length):
"""Zero pad byte string as defined in NIST SP 800-185"""
to_pad = _left_encode(length) + x
# Note: this implementation works with byte aligned strings,
# hence no additional bit padding is needed at this point.
npad = (length - len(to_pad) % length) % length
return to... | b02304fbb0e4bc42a80bc3fdc246c4fc9d55c816 | 3,641,635 |
def get_scalefactor(metadata):
"""Add scaling factors to the metadata dictionary
:param metadata: dictionary with CZI or OME-TIFF metadata
:type metadata: dict
:return: dictionary with additional keys for scling factors
:rtype: dict
"""
# set default scale factore to 1
scalefactors = {... | 0619d5fa8f24008ddf4364a965268755c07d09c3 | 3,641,637 |
def alignmentEntropy(align, statistic='absolute', removeGaps=False, k=1, logFunc=np.log):
"""Calculates the entropy in bits of each site (or kmer) in a sequence alignment.
Also can compute:
- "uniqueness" which I define to be the fraction of unique sequences
- "uniquenum" which is the number of... | ea06ae01cd1aa69cfc7dd19c72caafc5478fda38 | 3,641,638 |
def NodeToString(xml_node):
"""Returns an XML string.
Args:
xml_node: xml.dom.Node object
Returns:
String containing XML
"""
return xml_node.toxml() | 043072bbb40f33947febedf967679e3e39931834 | 3,641,639 |
def difference(data, interval):
""" difference dataset
parameters:
data: dataset to be differenced
interval: the interval between the two elements to be differenced.
return:
dataset: with the length = len(data) - interval
"""
return [data[i] - data[i ... | 611f4ad36935000ae7dc16f76aef7cbb494b36ac | 3,641,640 |
def merge_dictionaries(dict1, dict2):
""" Merges two dictionaries handling embedded lists and
dictionaries.
In a case of simple type, values from dict1 are preserved.
Args:
dict1, dict2 dictionaries to merge
Return merged dictionaries
"""
for k2, v2 in dict2.items():
if k2 no... | 8d46ce04496be2b5ba0e66788aed1a4e5ec1c85c | 3,641,641 |
def build(model_def, model_name, optimizer, loss_name, custom_objects=None):
"""build keras model instance in FastEstimator
Args:
model_def (function): function definition of tf.keras model or path of model file(h5)
model_name (str, list, tuple): model name(s)
optimizer (str, optimizer,... | 28cf56036b00790cf3e6350cc2741d93dd047e3a | 3,641,642 |
import wave
def check_audio_file(audio_file):
"""
Check if the audio file contents and format match the needs of the speech service. Currently we only support
16 KHz, 16 bit, MONO, PCM audio format. All others will be rejected.
:param audio_file: file to check
:return: audio duration, if file matc... | a6807cddefa7440b2f1cb11b2b3b309579f372e0 | 3,641,643 |
def uniform(name):
"""
Calls the findUniform function from util.py to return the uniform bounds for the given molecule.
Input: name of molecule
Output: array of length [2] with the upper and lower bounds for the uniform prior
"""
prior = findUniform(name, 'd_h')
return prior | e01b8c5056d199a8e0048e148170d5fc4c5c28a1 | 3,641,644 |
def merge_two_dicts(x, y):
"""Merges two dicts, returning a new copy."""
z = x.copy()
z.update(y)
return z | 9126ada395d9d7f3da5a45b7d46c5b440b5cf23d | 3,641,645 |
def num_utterances(dataset: ds.DatasetSplit):
"""Returns the total number of utterances in the dataset."""
return sum([len(interaction) for interaction in dataset.examples]) | 0927b96666f2f409c9fb0ec3c63576632810b6dc | 3,641,646 |
def __virtual__():
"""
Only return if requests and boto are installed.
"""
if HAS_LIBS:
return __virtualname__
else:
return False | 633ec9294e7585a6d5fc8a1dba2b436a20a4ab7a | 3,641,647 |
def register():
"""Register user"""
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
username = request.form.get("username")
email = request.form.get("email")
password = request.form.get("password")
# Logs user into database
... | 1c37ad0eac8f6a2230106cfd9e3754d6053956ff | 3,641,648 |
def _build_tmp_access_args(method, ip, ttl, port, direction, comment):
"""
Builds the cmd args for temporary access/deny opts.
"""
opt = _get_opt(method)
args = "{0} {1} {2}".format(opt, ip, ttl)
if port:
args += " -p {0}".format(port)
if direction:
args += " -d {0}".format(d... | 17a00e10af84519edb1a5dd8d89be614cb548ea1 | 3,641,650 |
def add_two_values(value1, value2):
""" Adds two integers
Arguments:
value1: first integer value e.g. 10
value2: second integer value e.g. 2
"""
return value1 + value2 | 10f71fcbde9d859f094724c94568eee55a7b989a | 3,641,651 |
import pandas
def combine_nearby_breakends(events, distance=5000):
"""
1d clustering, prioritizing assembled breakpoint coords
"""
breakends = []
positions = get_positions(events)
for (chrom, orientation), cur_events in positions.groupby(["chrom", "orientation"]):
cur_events = cur_e... | dad6867e7dfa406f8785b131fb2c93694fe60f0d | 3,641,652 |
def get_mongo_database(connection, database_name):
""" Access the database
Args:
connection (MongoClient): Mongo connection to the database
database_name (str): database to be accessed
Returns:
Database: the Database object
"""
try:
return connection.get_database(da... | 9299cbe0b697dec2e548fb5e26e2013214007575 | 3,641,653 |
from typing import Dict
from typing import Callable
def make_mappings() -> Dict[str, Callable[[], None]]:
"""サンプル名と実行する関数のマッピングを生成します"""
# noinspection PyDictCreation
m = {}
extlib.regist_modules(m)
return m | 598decb0b3197b1c64c982354de1fea9fdb3ce3d | 3,641,654 |
def S(state):
"""Stringify state
"""
if state == State.IDLE: return "IDLE"
if state == State.TAKING_OFF: return "TAKING_OFF"
if state == State.HOVERING: return "HOVERING"
if state == State.WAITING_ON_ASSIGNMENT: return "WAITING_ON_ASSIGNMENT"
if state == State.FLYING: return "FLYING"
if ... | 58c6005dcf8549225c233cc1af486fca9578111d | 3,641,655 |
def trace_get_watched_net(trace, i):
"""
trace_get_watched_net(Int_trace trace, unsigned int i) -> Int_net
Parameters
----------
trace: Int_trace
i: unsigned int
"""
return _api.trace_get_watched_net(trace, i) | f7140cbfcc27d511b3212ba7adf97f0b6c91582b | 3,641,657 |
from typing import Optional
from typing import OrderedDict
def dist_batch_tasks_for_all_layer_mdl_vs_adapted_mdl(
mdl: nn.Module,
spt_x: Tensor, spt_y: Tensor, qry_x: Tensor, qry_y: Tensor,
layer_names: list[str],
inner_opt: DifferentiableOptimizer,
fo: bool,
nb_inner_t... | 72830d75e195b8363936d78a8c249b9f6bbd7125 | 3,641,658 |
from typing import Callable
from typing import List
import numbers
def adjust_payload(tree: FilterableIntervalTree,
a_node: FilterableIntervalTreeNode,
adjustment_interval: Interval,
adjustments: dict,
filter_vector_generator: Callable[[dict]... | fa93deede3e7fee950834e5e02bc79bb98e68f03 | 3,641,659 |
def get_max(data, **kwargs):
"""
Assuming the dataset is loaded as type `np.array`, and has shape
(num_samples, num_features).
:param data: Provided dataset, assume each row is a data sample and \
each column is one feature.
:type `np.ndarray`
:param kwargs: Dictionary of differential priv... | 03697d2a2bc6afe3c1d576bd9f8766c97e86626d | 3,641,661 |
def find_u_from_v(matrix, v, singular_value):
"""
Finds the u column vector of the U matrix in the SVD UΣV^T.
Parameters
----------
matrix : numpy.ndarray
Matrix for which the SVD is calculated
v : numpy.ndarray
A column vector of V matrix, it is the eigenvector of the Gramian ... | ef2871c86bf7ddc4c42446a54230068282ad85df | 3,641,662 |
import torch
def transform(dataset, perm_idx, model, view):
"""
for view1 utterance, simply encode using view1 encoder
for view 2 utterances:
- encode each utterance, using view 1 encoder, to get utterance embeddings
- take average of utterance embeddings to form view 2 embedding
"""
model... | 484adb7d53f80366b591ef45551b245dce00acca | 3,641,663 |
from typing import List
def double(items: List[str]) -> List[str]:
"""
Returns a new list that is the input list, repeated twice.
"""
return items + items | 9e4b6b9e84a80a9f5cbd512ca820274bb8cad924 | 3,641,664 |
def system_from_problem(problem: Problem) -> System:
"""Extracts the "system" part of a problem.
Args:
problem: Problem description
Returns:
A :class:`System` object containing a copy of the relevant parts of the problem.
"""
return System(
id=problem.id,
name=proble... | 42c0db09d00043ba61ae164bb58a0ecb48599027 | 3,641,665 |
def get_service_endpoints(ksc, service_type, region_name):
"""Get endpoints for a given service type from the Keystone catalog.
:param ksc: An instance of a Keystone client.
:type ksc: :class: `keystoneclient.v3.client.Client`
:param str service_type: An endpoint service type to use.
:param str reg... | c962ad44e4d73a102f9c09803f94c68cee2aeb51 | 3,641,666 |
def get_task_for_node(node_id):
""" Get a new task or previously assigned task for node """
# get ACTIVE task that was previously assigned to this node
query = Task.query.filter_by(node_id=node_id).filter_by(status=TaskStatus.ACTIVE)
task = query.first()
if task:
return task
node = Nod... | 5a01869f40f5c0840dfdc2ed1e3417c694f51aca | 3,641,667 |
def cik_list():
"""Get CIK list and use it as a fixture."""
return UsStockList() | ec845471860dcf4ce9dcf0e82e2effda21bcbf0b | 3,641,670 |
def get_eval_config(hidden_dim,
max_input_length=None,
num_input_timesteps=None,
model_temporal_relations=True,
node_position_dim=1,
num_input_propagation_steps=None,
token_vocab_size=None,
... | 90ff743a372a2db3eb52927bf8c6d996a11137cb | 3,641,671 |
def classNew(u_id):
"""
Allow an ADMIN to create a new class (ADMIN ONLY)
Returns: none
"""
myDb, myCursor = dbConnect()
data = request.get_json()
createNewClass(myCursor, myDb, data)
dbDisconnect(myCursor, myDb)
return dumps({}) | 29532ea5c979b725b46c1dd775c1f093006b1a43 | 3,641,672 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.