content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def ask_daemon_sync(view, ask_type, ask_kwargs, location=None):
"""Jedi sync request shortcut.
:type view: sublime.View
:type ask_type: str
:type ask_kwargs: dict or None
:type location: type of (int, int) or None
"""
daemon = _get_daemon(view)
return daemon.request(
ask_type,
... | 665a302445c4661d3e5610914bde688cd4512968 | 30,534 |
import logging
import time
def _etl_epacems(etl_params, datapkg_dir, pudl_settings, ds_kwargs):
"""Extract, transform and load CSVs for EPA CEMS.
Args:
etl_params (dict): ETL parameters required by this data source.
datapkg_dir (path-like): The location of the directory for this
p... | 5e9b951205c8e5d50d8b07f5b7661fcbc4595a80 | 30,535 |
def GetNvccOptions(argv):
"""Collect the -nvcc_options values from argv.
Args:
argv: A list of strings, possibly the argv passed to main().
Returns:
1. The string that can be passed directly to nvcc.
2. The leftover options.
"""
parser = ArgumentParser()
parser.add_argument('-nvcc_options', n... | bb143edb6099eb6182fe7b79e53422321cb3e03d | 30,536 |
import json
def show_node(request, name='', path='', revision=''):
"""
View for show_node page, which provides context for show_node.html
Shows description for yang modules.
:param request: Array with arguments from webpage data submition.
:param module: Takes first argument from url if request do... | 20e3a87be8f2d85632fe26cc86a3cc7742d2de33 | 30,537 |
def compute_F1(TP, TN, FP, FN):
"""
Return the F1 score
"""
numer = 2 * TP
denom = 2 * TP + FN + FP
F1 = numer/denom
Acc = 100. * (TP + TN) / (TP + TN + FP + FN)
return F1, Acc | 6f012246337534af37ff233ad78d9645907739e3 | 30,538 |
def name_full_data():
"""Full name data."""
return {
"name": "Doe, John",
"given_name": "John",
"family_name": "Doe",
"identifiers": [
{
"identifier": "0000-0001-8135-3489",
"scheme": "orcid"
}, {
"identifier... | ac590635dbe33e68dc88acd890d16dd3137befb2 | 30,539 |
def platypus(in_file, data):
"""Filter Platypus calls, removing Q20 filter and replacing with depth and quality based filter.
Platypus uses its own VCF nomenclature: TC == DP, FR == AF
Platypus gVCF output appears to have an 0/1 index problem so the reference block
regions are 1 base outside regions o... | 00979a3de36b051882e42e2231cac69a67dfec20 | 30,540 |
def delete(i):
"""
Input: { See 'rm' function }
Output: { See 'rm' function }
"""
return rm(i) | 048742483608b7530ee217a60c96f4c4f6ec6fb0 | 30,541 |
def test_circuit_str(default_compilation_configuration):
"""Test function for `__str__` method of `Circuit`"""
def f(x):
return x + 42
x = hnp.EncryptedScalar(hnp.UnsignedInteger(3))
inputset = range(2 ** 3)
circuit = hnp.compile_numpy_function(f, {"x": x}, inputset, default_compilation_c... | abf2955b7cd440124eb2e2acf685aa84d69a3e4a | 30,543 |
def add_game():
"""Adds game to database"""
check_admin()
add_game = True
form = GameForm()
# Checks if form is valid
if form.validate_on_submit():
game = Game(name=form.name.data)
try:
db.session.add(game)
db.session.commit()
flash('Game suc... | 9134516408a1931a41a901b4523713871f580da0 | 30,544 |
def requires_moderation(page):
"""Returns True if page requires moderation
"""
return bool(page.get_moderator_queryset().count()) | 8f1cfa852cbeccfae6157e94b7ddf61d9597936e | 30,545 |
from typing import Optional
def _get_node_info(
node: NodeObject,
current_path: str,
node_type: str,
label: Optional[str] = None,
is_leaf: bool = True
) -> NodeInfo:
"""
Utility method for generating a NodeInfo from a NodeObject
:param node: NodeObject to convert in... | d0084dc757dd9501dc2853a1445524cbde9a0756 | 30,546 |
def get_peers():
"""Retrieve PeerIds and SSIDs for peers that are ready for OOB transfer"""
query = 'SELECT Ssid, PeerId from EphemeralState WHERE PeerState=1'
data = exec_query(query, db_path_peer)
return data | 9ab81631cf1f779b3a80b246e0a6144e46599a64 | 30,547 |
from bs4 import BeautifulSoup
def get_html_text(html):
"""
Return the raw text of an ad
"""
if html:
doc = BeautifulSoup(html, "html.parser")
return doc.get_text(" ")
return "" | 14353f368078ea6b1673d1066b0a529cc3e257d9 | 30,548 |
def valid_parentheses(string):
"""
Takes a string of parentheses, and determines if the order of the parentheses is valid.
:param string: a string of parentheses and characters.
:return: true if the string is valid, and false if it's invalid.
"""
stack = []
for x in string:
if x == "... | e8438404c461b7a113bbbab6417190dcd1056871 | 30,549 |
def in_2core_graph_slow(cats: ArrayLike) -> BoolArray:
"""
Parameters
----------
cats: {DataFrame, ndarray}
Array containing the category codes of pandas categoricals
(nobs, ncats)
Returns
-------
retain : ndarray
Boolean array that marks non-singleton entries as Tru... | 46fc377643849b68d9071c9e592c1bba68a23a83 | 30,551 |
def has_form_encoded_header(header_lines):
"""Return if list includes form encoded header"""
for line in header_lines:
if ":" in line:
(header, value) = line.split(":", 1)
if header.lower() == "content-type" \
and "x-www-form-urlencoded" in value:
... | e4fe797e4884161d0d935853444634443e6e25bb | 30,552 |
from pathlib import Path
def get_best_checkpoint_path(path: Path) -> Path:
"""
Given a path and checkpoint, formats a path based on the checkpoint file name format.
:param path to checkpoint folder
"""
return path / LAST_CHECKPOINT_FILE_NAME_WITH_SUFFIX | b0637dd0fac5df3b7645cceec62f23fc3d48d4eb | 30,553 |
def storage_charge_rule(model, technology, timepoint):
"""
Storage cannot charge at a higher rate than implied by its total installed power capacity.
Charge and discharge rate limits are currently the same.
"""
return model.Charge[technology, timepoint] + model.Provide_Power[technology, timepoint] <... | 9f437d11f1eb1ce894381de10b719c9c08271396 | 30,554 |
def blck_void(preprocessor: Preprocessor, args: str, contents: str) -> str:
"""The void block, processes commands inside it but prints nothing"""
if args.strip() != "":
preprocessor.send_warning("extra-arguments", "the void block takes no arguments")
preprocessor.context.update(preprocessor.current_position.end, "... | 841be11c1f8f7b9d4c3552cdafe0aaa590b8fb9d | 30,555 |
import typing
def resize_image(image: np.ndarray,
width: typing.Optional[int] = None,
height: typing.Optional[int] = None,
interpolation=cv2.INTER_AREA):
"""
Resize image using given width or/and height value(s).
If both values are passed, aspect ratio is... | ee8bf8424bb23a941a7858a97d1b4ff6b5187d38 | 30,556 |
def attr(*args, **kwargs):
"""Decorator that adds attributes to classes or functions
for use with unit tests runner.
"""
def wrapped(element):
for name in args:
setattr(element, name, True)
for name, value in kwargs.items():
setattr(element, name, value)
r... | 77d20af87cef526441aded99bd6e24e21e5f81f9 | 30,557 |
def convert_units(table_name, value, value_unit, targets):
"""
Converts a given value in a unit to a set of target units.
@param table_name Name of table units are contained in
@param value Value to convert
@param value_unit Unit value is currently in
@param targets List of units to convert to
... | b8cdbeafa78ec71450e69cec6913e805bd26fa8a | 30,558 |
def hex2binary(hex_num):
""" converts from hexadecimal to binary """
hex1 = h[hex_num[0]]
hex2 = h[hex_num[1]]
return str(hex1) + str(hex2) | 78d2a804d5f02c985d943e6242bc66143905df2f | 30,560 |
def nn(value: int) -> int:
"""Casts value to closest non negative value"""
return 0 if value < 0 else value | 08672feaefa99881a110e3fc629d4a9256f630af | 30,561 |
def resolve_vcf_counts_data(vcf_data, maf_data, matched_normal_sample_id, tumor_sample_data_col):
""" Resolves VCF allele counts data. """
vcf_alleles = [vcf_data["REF"]]
vcf_alleles.extend(vcf_data["ALT"].split(","))
tumor_sample_format_data = vcf_data["MAPPED_TUMOR_FORMAT_DATA"]
normal_sample_for... | 5e10d54038a84bc93a4d6b09ae5368e61ae3312f | 30,562 |
def example_profile_metadata_target():
"""Generates an example profile metadata document.
>>> root = example_profile_metadata_target()
>>> print_tree(root)
<?xml version='1.0' encoding='UTF-8'?>
<Profile xmlns="http://soap.sforce.com/2006/04/metadata">
<classAccesses>
<apexClass>ARTra... | 6e43847aec021e188c001ad59e297ecdfc31d202 | 30,563 |
def separate(expr, deep=False):
"""Rewrite or separate a power of product to a product of powers
but without any expanding, ie. rewriting products to summations.
>>> from sympy import *
>>> x, y, z = symbols('x', 'y', 'z')
>>> separate((x*y)**2)
x**2*y**2
>>> separate((x... | ae30943f0073508d85212f97d4298f63e16fcc05 | 30,564 |
def app_base(request):
"""
This should render the required HTML to start the Angular application. It is the only entry point for
the pyramid UI via Angular
:param request: A pyramid request object, default for a view
:return: A dictionary of variables to be rendered into the template
"""
de... | 3a097e920b33248b436e2eea00e05b5708b35779 | 30,566 |
from typing import List
import re
def check_lists(document: Document, args: Args) -> List[Issue]:
"""Check that markdown lists items:
- Are preceded by a blank line.
- Are not left empty.
- End with a period if they're a list of sentences.
- End without a period if they're a list of items."""
... | e224206b0683239fe957dd78795b8f2de69d4149 | 30,567 |
def transform_one(mt, vardp_outlier=100_000) -> Table:
"""transforms a gvcf into a form suitable for combining
The input to this should be some result of either :func:`.import_vcf` or
:func:`.import_vcfs` with `array_elements_required=False`.
There is a strong assumption that this function will be cal... | 7961d5ea3d0b0e58332552c9c3c72692f34868db | 30,568 |
def volume_rebalance(volume: str) -> Result:
"""
# This function doesn't do anything yet. It is a place holder because
# volume_rebalance is a long running command and I haven't decided how to
# poll for completion yet
# Usage: volume rebalance <VOLNAME> fix-layout start | start
# [force]|stop|... | 03df7752b45d90f84720be12f32703c1109d71c2 | 30,569 |
import json
def get_droplet_ip():
"""get droplet ip from cache."""
cached_droplet_info_file = 'droplet_info.json'
with open(cached_droplet_info_file, 'r') as info_f:
droplet_info = json.load(info_f)
return droplet_info['networks']['v4'][0]['ip_address'] | 21d0bfbbe6aebd7e88cc6465d49b221da271753a | 30,570 |
def country_converter(text_input, abbreviations_okay=True):
"""
Function that detects a country name in a given word.
:param text_input: Any string.
:param abbreviations_okay: means it's okay to check the list for abbreviations, like MX or GB.
:return:
"""
# Set default values
country_... | 19bdd3be63ee2a1165d8fc121203694da9732fea | 30,571 |
def lat_long_to_idx(gt, lon, lat):
"""
Take a geotransform and calculate the array indexes for the given lat,long.
:param gt: GDAL geotransform (e.g. gdal.Open(x).GetGeoTransform()).
:type gt: GDAL Geotransform tuple.
:param lon: Longitude.
:type lon: float
:param la... | 3fafcc4750daa02beaedb330ab6273eab6abcd56 | 30,572 |
def BSMlambda(delta: float, S: float, V: float) -> float:
"""Not really a greek, but rather an expression of leverage.
Arguments
---------
delta : float
BSM delta of the option
V : float
Spot price of the option
S : float
Spot price of the underlying
Returns... | ea9bf546a7cf46b3c2be01e722409663b05248e1 | 30,574 |
import pwd
def uid_to_name(uid):
"""
Find the username associated with a user ID.
:param uid: The user ID (an integer).
:returns: The username (a string) or :data:`None` if :func:`pwd.getpwuid()`
fails to locate a user for the given ID.
"""
try:
return pwd.getpwuid(uid).... | f9054e4959a385d34c18d88704d376fb4b718e47 | 30,575 |
def fit_poly(data, error_func, degree = 3):
""" Fit a polynomial to given data, using supplied error function.
Parameters
----------
data: 2D array where each row is a point (X0, Y)
error_func: function that computes the error between a polynomial and observed data
degree: polynomial degree
... | 007693c1e01edc69cee27dd1da0836087d8a2d11 | 30,576 |
def find_skyrmion_center_2d(fun, point_up=False):
"""
Find the centre the skyrmion, suppose only one skyrmion
and only works for 2d mesh.
`fun` accept a dolfin function.
`point_up` : the core of skyrmion, points up or points down.
"""
V = fun.function_space()
mesh = V.mesh()
c... | 030c704681a48cdeca1f880f08fe9fb039572640 | 30,577 |
import time
def test(num_games, opponent, silent):
""" Test running a number of games """
def autoplayer_creator(state):
""" Create a normal autoplayer instance """
return AutoPlayer(state)
def minimax_creator(state):
""" Create a minimax autoplayer instance """
return Au... | c7560e2d298039b5f201b57779e14b4a38054160 | 30,578 |
import webbrowser
def pseudo_beaker(UserId: str, SessionId: str, replay=True, scope=True, browser=None, OrgId: str=None, is_staging: bool=True) -> dict:
"""
Mimic the Beaker admin tool in opening up one or both of session replay and
Scope tools for a given User Id and Session Id.
Option to specify a ... | 6cf905762b76d90a4d32459d9259b452ffc89240 | 30,579 |
def table_parse(table):
"""
"""
data = []
rows = table.find_all('tr')
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele])
return data | 528008ada0ad7d594554ed5d577472a126df0cd1 | 30,580 |
import pandas
import numpy
def scan_mv_preprocessing_fill_pivot_nan(df):
"""
Value imputation.
Impute missing data in pivot table.
Parameters
----------
df : dataframe
Pivot table data with potentially missing values.
Returns
-------
df : dataframe
Pivot table da... | e88d1b2b0a3d4fc27afe29a10512116323046cef | 30,581 |
def image_show(request,item_container):
""" zeigt die Beschreibung der Datei an """
app_name = 'image'
vars = get_item_vars_show(request, item_container, app_name)
file_path = DOWNLOAD_PATH + item_container.container.path
file_name = file_path + item_container.item.name
width, height = get_image_size(file_n... | b68286bedd92aba7991e8994bf76d84bfe5d4c2e | 30,582 |
def common_kwargs(cfg, bin_count, pointing):
"""Creates a prepfold-friendly dictionary of common arguments to pass to prepfold"""
name = generate_prep_name(cfg, bin_count, pointing)
prep_kwargs = {}
if cfg["run_ops"]["mask"]:
prep_kwargs["-mask"] = cfg["run_ops"]["mask"]
prep_kwargs["-o"] = ... | c6a1f2ceb475e8f0d2b3e905d8109f79d77d3b79 | 30,584 |
def quatMultiply(q1,q2):
"""Returns a quaternion that is a composition of two quaternions
Parameters
----------
q1: 1 x 4 numpy array
representing a quaternion
q2: 1 x 4 numpy array
representing a quatnernion
Returns
-------
qM: 1 x 4 numpy array
rep... | 2c32f0390d01b36258c9bcabc290a47dca592ded | 30,585 |
def expandingPrediction(input_list, multiple=5):
"""
:param input_list:
:param multiple:
:return:
"""
expanded_list = []
for prediction in input_list:
for i in range(multiple):
expanded_list.append(prediction)
return expanded_list | 9a502adb15160e656bd727748eb5dae73858d7f8 | 30,586 |
def pages_siblings_menu(context, page, url='/'):
"""Get the parent page of the given page and render a nested list of its
child pages. Good for rendering a secondary menu.
:param page: the page where to start the menu from.
:param url: not used anymore.
"""
lang = context.get('lang', pages_sett... | 723249cd73ec95b947f279a99e88afe2ec51868d | 30,587 |
def aes(img, mask=None, canny_edges=None, canny_sigma=2):
"""Calculate the Average Edge Strength
Reference:
Aksoy, M., Forman, C., Straka, M., Çukur, T., Hornegger, J., & Bammer, R. (2012).
Hybrid prospective and retrospective head motion correction to mitigate cross-calibration errors.
Magnetic ... | 52cdcf45609e7ee35eb7d05a2529d4330b6509b4 | 30,588 |
def projection(basis, vectors):
"""
The vectors live in a k dimensional space S and the columns of the basis are vectors of the same
space spanning a subspace of S. Gives a representation of the projection of vector into the space
spanned by basis in term of the basis.
:param basis: an n-by-k array... | 107a1db030d0af7af346128fea10e5f7657b1a6a | 30,589 |
import numpy
def grab(sequence, random = numpy.random):
"""
Return a randomly-selected element from the sequence.
"""
return sequence[random.randint(len(sequence))] | 1760dc08b5971647f55248bd1b1f04d700dac38e | 30,591 |
def csl_url_args_retriever():
"""Returns the style and locale passed as URL args for CSL export."""
style = resource_requestctx.args.get("style")
locale = resource_requestctx.args.get("locale")
return style, locale | 96f87dd927f998b9599663432a95c2330b15b2d0 | 30,592 |
import random
def select_parents(population, m):
"""Select randomly parents for the new population from sorted by
fitness function existing population."""
fitness_population = sorted(
population,
key=lambda child: fitness_function(child, m),
reverse=True)
# ordered_population =... | 3f0a2de28da7355ce34f692f7bb0722896903c51 | 30,594 |
def rsqrt(x: Tensor):
"""Computes reciprocal of square root of x element-wise.
Args:
x: input tensor
Returns:
output tensor
Examples:
>>> x = tf.constant([2., 0., -2.])
>>> rsqrt(x)
<Tensor: shape=(3,), dtype=float32,
numpy=array([0.707, inf, nan], dtype=f... | 39b4574311eb74ccef18ddb936d1d92fbb0c1fd9 | 30,595 |
def averageObjPeg(objpegpts, planet, catalog=None, sceneid='NO_POL'):
"""
Average peg points.
"""
logger.info('Combining individual peg points: %s' % sceneid)
peg = stdproc.orbit.pegManipulator.averagePeg([gp.getPeg() for gp in objpegpts], planet)
pegheights = [gp.getAverageHeight() for gp in ob... | 92e41d33d3aa21ee6036e3f1a6550d81d793129e | 30,596 |
def _bytes_chr_py2(i):
"""
Returns a byte string of length 1 whose ordinal value is i in Python 2.
Do not call directly, use bytes_chr instead.
"""
return chr(i) | de524d1ec303cc297d7981570ef30aa9ae6840ed | 30,597 |
from typing import Any
def convert(parser: Any) -> c2gtypes.ParserRep:
"""Convert getopt to a dict.
Args:
parser (Any): docopt parser
Returns:
c2gtypes.ParserRep: dictionary representing parser object
"""
return {"parser_description": "", "widgets": extract(parser)} | cf6e53bd514bdb114c3bc5d3b7429c6a8f17881d | 30,598 |
def redirect_vurlkey(request, vurlkey, *args, **kwargs):
"""redirect_vurlkey(vurlkey) looks up the Vurl with base58-encoded index VURLKEY and issues a redirect to the target URL"""
v = Vurl.get_with_vurlkey(vurlkey.encode('utf-8'))
return v.http_response() | 99e4be6b43a8b983f9c8efdb60ccf2873ce3caf2 | 30,599 |
def rhand (x,y,z,iopt,parmod,exname,inname):
"""
Calculates the components of the right hand side vector in the geomagnetic field
line equation (a subsidiary subroutine for the subroutine step)
:param x,y,z:
:param iopt:
:param parmod:
:param exname: name of the subroutine for the external... | 008912796a0ac5c61de3b1fa5de90edbf8ed1f61 | 30,600 |
def unique_slug_generator_by_email(instance, new_slug=None):
"""
This is for a Django project and it assumes your instance
has a model with a slug field and a title character (char) field.
"""
slug = new_slug if new_slug is not None else slugify(instance.email)
Klass = instance.__class__
qs_... | a1e1ae8b25e67a9a5f1d93164deb4b769afb4588 | 30,601 |
import logging
def register_provider(price_core_min=1):
"""Register Provider"""
mine(1)
web3.eth.defaultAccount = accounts[0]
prices = [price_core_min, price_data_transfer, price_storage, price_cache]
tx = config.ebb.registerProvider(
GPG_FINGERPRINT,
provider_email,
federa... | 9385a0291af2f306075bc2775d53cd67b442d985 | 30,602 |
from typing import Callable
def get_signature_and_params(func: Callable):
"""Get the parameters and signature from a coroutine.
func: Callable
The coroutine from whom the information should be extracted.
Returns
-------
Tuple[List[Union[:class:`str`, :class:`inspect.Parameter`]]]
... | cc53ba8f8cf54d8cf6167b57bc6ecb626605d333 | 30,603 |
def quadratic_formula(polynomial):
"""
input is single-variable polynomial of degree 2
returns zeros
"""
if len(polynomial.term_matrix) == 3:
if polynomial.term_matrix[2][1] == 1:
a, b = polynomial.term_matrix[1][0], polynomial.term_matrix[2][0]
return 0, -b/a
... | 5501abff2fadcd237e3cb0efc4bca615eef455da | 30,604 |
def handle_domain_deletion_commands(client: Client, demisto_args: dict) -> str:
"""
Removes domains from the inbound blacklisted list.
:type client: ``Client``
:param client: Client to use.
:type demisto_args: ``dict``
:param demisto_args: The demisto arguments.
:... | 54f9174a3b8db9820e612cd3782dac4b9af6554e | 30,605 |
def create_l2_lag_interface(name, phys_ports, lacp_mode="passive", mc_lag=False, fallback_enabled=False,
vlan_ids_list=[], desc=None, admin_state="up", **kwargs):
"""
Perform a POST call to create a Port table entry for L2 LAG interface.
:param name: Alphanumeric name of LAG Por... | 7dcce04a7c9dd5d533bcf40bdda94c5fc8ff2951 | 30,606 |
def get_train_image_matrices(folder_name, num_images=4):
"""Gets image matrices for training images.
:param folder_name: String with name of training image folder in
input_data/train_images directory path.
:param num_images: Integer with number of images.
:return: Matrices from training images.... | be75cd1246421b13830931fd6551c94c0bd673f6 | 30,608 |
import torch
def to_chainer_device(device):
"""Create a chainer device from a given torch device.
Args:
device (torch.device): Device to be converted.
Returns:
A ``chainer.device`` object corresponding to the given input.
"""
if not isinstance(device, torch.device):
raise... | d2d1c9ddf50792225260133f1d434e3166b6338b | 30,609 |
def decode_region(code):
""" Returns the region name for the given region code.
For example: decode_region("be") => "Belgium".
"""
for tag, (language, region, iso639, iso3166) in LANGUAGE_REGION.iteritems():
if iso3166 == code.upper():
return region | 5a4467088d8824a8647d9c7ed89381b94ddab096 | 30,610 |
def neighbourhood_peaks(signal, n=10):
"""Computes the number of peaks from a defined neighbourhood of the signal.
Reference: Christ, M., Braun, N., Neuffer, J. and Kempa-Liehr A.W. (2018). Time Series FeatuRe Extraction on basis
of Scalable Hypothesis tests (tsfresh -- A Python package). Neurocomputing 3... | b684419844a747633d667abab9b6819f61d13d05 | 30,612 |
def check_success(env, policy, act_noise_pct, render=False):
"""Tests whether a given policy solves an environment
Args:
env (metaworld.envs.MujocoEnv): Environment to test
policy (metaworld.policies.policies.Policy): Policy that's supposed to
succeed in env
act_noise_pct (fl... | 260a03bc47c3864894b5d2922a636bd54b8d1253 | 30,613 |
import glob
def import_data(file_regex, index_col_val=None, parse_dates=None,
date_format=None):
"""
takes in a regular expression describing the filepath to
the data files and returns a pandas dataFrame
Usage1:
var_name = import_data.import_data("./hackat... | 411f767bd27cb40d9aaea28feb94da9f29b1f5aa | 30,614 |
def shift_num_right_by(num: int, digits: int) -> int:
"""Shift a number to the right by discarding some digits
We actually use string conversion here since division can provide
wrong results due to precision errors for very big numbers. e.g.:
6150000000000000000000000000000000000000000000000 // 1e27
... | ff29f5fbc53c8cfa5fa4172fd4e6e7c0b8b4e27b | 30,615 |
def index_handler(request):
"""
List latest 6 articles, or post a new article.
"""
if request.method == 'GET':
return get_article_list(request)
elif request.method == 'POST':
return post_article(request) | b64a81c4bde4d83f99663ffb6384ff6cde8a217c | 30,616 |
import numpy
def back_propogation(weights, aa, zz, y1hot, lam=0.0):
"""Perform a back propogation step
Args:
weights (``list`` of numpy.ndarray): weights between each layer
aa (``list`` of numpy.ndarray): activation of nodes for
each layer. The last item in the list is the hypothesis.
... | 2909809699ae3b3fd5ab97b6294391322cf3d8bb | 30,621 |
async def get_reverse_objects_topranked_for_lst(entities):
"""
get pairs that point to the given entity as the primary property
primary properties are those with the highest rank per property
see https://www.wikidata.org/wiki/Help:Ranking
"""
# some lookups just take too long, so we remove them... | 7266b4f29e3c3878abc14c995da7713a8d7121e0 | 30,622 |
import stat
def compute_confidence_interval(data,confidence=0.95):
"""
Function to determine the confidence interval
:param data: input data
:param confidence: confidence level
:return: confidence interval
"""
a = 1.0 * np.array(data)
n = len(a)
se = stat.sem(a... | b7f64935cefdb2f60a7ca7fdc720b3ecddf7e89c | 30,623 |
def adjacent_powerset(iterable):
"""
Returns every combination of elements in an iterable where elements remain ordered and adjacent.
For example, adjacent_powerset('ABCD') returns ['A', 'AB', 'ABC', 'ABCD', 'B', 'BC', 'BCD', 'C', 'CD', 'D']
Args:
iterable: an iterable
Returns:
a li... | 951418b30d541e1dcdd635937ae609d429e3cd70 | 30,624 |
from typing import Iterator
from typing import Counter
import tqdm
def export_ngrams(
docs: Iterator[str], nlp: spacy.language.Language, n: str, patterns=False
) -> Counter:
"""
Extracts n-gram frequencies of a series of documents
Parameters
----------
docs : Iterator[str]
An iterator... | 242d0b3fcb2dffd2d35ae76416dfc7861bdfb916 | 30,625 |
import torch
def solve2D_system(
pde_system, conditions, xy_min=None, xy_max=None,
single_net=None, nets=None, train_generator=None, shuffle=True, valid_generator=None,
optimizer=None, criterion=None, additional_loss_term=None, batch_size=16,
max_epochs=1000,
monitor=None, retu... | f9763819a3df3477df88dea395c45d7a357c25c7 | 30,627 |
def model_criterion(preds, labels):
"""
Function: Model criterion to train the model
"""
loss = nn.CrossEntropyLoss()
return loss(preds, labels) | c4005131b30c2e5bab03d13ec00fcf96657b4fbb | 30,628 |
def get_dbmapping(syn: Synapse, project_id: str) -> dict:
"""Gets database mapping information
Args:
syn: Synapse connection
project_id: Project id where new data lives
Returns:
{'synid': database mapping syn id,
'df': database mapping pd.DataFrame}
"""
project_ent =... | cee2daf40886a68871b400ae06298eff095a8205 | 30,629 |
def end_position(variant_obj):
"""Calculate end position for a variant."""
alt_bases = len(variant_obj['alternative'])
num_bases = max(len(variant_obj['reference']), alt_bases)
return variant_obj['position'] + (num_bases - 1) | e49110a1102ea2ca53053858597247799065f8e1 | 30,630 |
def cast_to_server(server_params, topic, msg):
"""
Invoke a remote method that does not return anything
"""
return _get_impl().cast_to_server(cfg.CONF, server_params, topic, msg) | 0fb92932dbe6f23cbc230bd2f23891a514bffd7a | 30,631 |
def get_classification_systems():
"""Retrieve all classification systems available in service."""
system = db.session.query(LucClassificationSystem).all()
return ClassificationSystemSchema().dump(system, many=True) | 03ca32de57f319144c1d185a2f5260ffab269a15 | 30,632 |
def read_annotations(filename, tagset, labeled):
""" Read tsv data and return sentences and [word, tag, sentenceID, filename] list """
with open(filename, encoding="utf-8") as f:
sentence = []
sentence.append(["[CLS]", -100, -1, -1, None])
sentences = []
sentenceID=0
for line in f:
if len(line) > 0:
... | bbb210fe631f1e10432ab6c18146d69933fe7187 | 30,633 |
def find_rmse(data_1, data_2, ax=0):
"""
Finds RMSE between data_1 and data_2
Inputs
------
data_1 (np.array)
data_2 (np.array)
ax (int) The axis (or axes) to mean over
Outpts
------
(int) RMSE between data_1 and data_2
"""
return np.sqrt(... | aed7ee0d6fda234f452056a91eb70495343579ac | 30,634 |
def validate_tag_update(update):
"""
Property: ResourceUpdateConstraint.TagUpdateOnProvisionedProduct
"""
valid_tag_update_values = [
"ALLOWED",
"NOT_ALLOWED",
]
if update not in valid_tag_update_values:
raise ValueError("{} is not a valid tag update value".format(update)... | c2abd7af00be52cf8cfecb5790d88a04d3207253 | 30,635 |
def bollinger_band(df: pd.DataFrame, window: int = 20, window_dev: int = 2) -> pd.DataFrame:
"""Implementation of bollinger band."""
df_with_signals = df.copy()
typical_price = (df["close"] + df["low"] + df["high"]) / 3
df_with_signals["typical_price"] = typical_price
std_dev = df_with_signals["typi... | 69fb61a09512967c92fc997134cad67e7659774f | 30,636 |
def close_corner_contour(contour: np.ndarray, shape: tuple) -> np.ndarray:
"""Check if contours are in the corner, and close them if needed.
Contours which cover a corner cannot be closed by joining the first
and last element, because some of the area is missed. This algorithm
adds the corner point to ... | 62564816c5e00131a5ec59242467cee464d6f5ac | 30,637 |
def simulate_spatial_ratiometric_reading(
do, temperature, sealed_patch_do=0, sealed_patch_kwargs={}, unsealed_patch_kwargs={}
):
""" Simulate a "spatial ratiometric" reading using a sealed DO patch as the ratiometric reference
Args:
do: Dissolved Oxygen partial pressure in mmHg in the unsealed pat... | 17bc66583c6d9c8a9c77b6e9e19f3adee2e73617 | 30,639 |
from .interactive._iplot_state import iplot_state
from ._state_visualization import plot_state as plot
from .interactive._iplot_state import iplot_state
from ._state_visualization import plot_state as plot
def plot_state(rho, method='city', filename=None, options=None, mode=None,
show=False):
"""Pl... | 3266a41986b8c77a966fd5b76fb55e2b330dd05e | 30,641 |
from datetime import datetime
def tick_format(ticktime):
"""
Format the tick date/time
"""
datetime_object = datetime.strptime(ticktime, '%Y-%m-%dT%H:%M:%S.%fZ')
return datetime_object.strftime("%H:%M:%S UTC %A %d %B") | 6fa02f7627bc947646046a47ab7298aad68399d8 | 30,642 |
def add_finite_filter_to_scorer(score_func):
"""Takes a scorer and returns a scorer that ignores NA / infinite elements in y_true.
sklearn scorers (and others) don't handle arrays with 0 length. In that case, return None
:param score_func: function that maps two arrays to a number. E.g. (y_true, y_pred) -... | a6ee3874b12213fa2b5ea385a8343c8ba3e1462b | 30,643 |
import gc
def lsst_fit(lc, grp):
"""Take full mock LC and SDSS cadence to find best_fit params.
Args:
lc: Kali LC object, full mock LC.
grp: HDF5 group storing the MCMC chains.
"""
best_param = [] # store best-fit params
ref_ls = []
task = kali.carma.CARMATask(1, 0, nste... | 44cd48fe3c7d3de50fdab2c007a0f4c947ae3116 | 30,644 |
def getStudioModeStatus():
"""
Indicates if Studio Mode is currently enabled.
"""
return __createJSON("GetStudioModeStatus", {}) | 544ffccc459259b52b395aadb94c0439d824f7b4 | 30,645 |
from typing import Tuple
def calc_long_short_prec(
pred: pd.Series, label: pd.Series, date_col="datetime", quantile: float = 0.2, dropna=False, is_alpha=False
) -> Tuple[pd.Series, pd.Series]:
"""
calculate the precision for long and short operation
:param pred/label: index is **pd.MultiIndex**, ind... | e74c6666922786522f55190d8f4d9125bb86c94d | 30,646 |
def prepare_tuple_argument(arg, n, arg_name, validate_args=False):
"""Helper which processes `Tensor`s to tuples in standard form."""
arg_size = ps.size(arg)
arg_size_ = tf.get_static_value(arg_size)
assertions = []
if arg_size_ is not None:
if arg_size_ not in (1, n):
raise ValueError('The size of ... | 51f94eb8e4eef0b69df443ca71fdc9def3fd55a1 | 30,647 |
import zipfile
def isValidLibreOfficeFile(file_path):
"""
Return true if given file is valid LibreOffice ods file containing
manifest.xml, false otherwise.
"""
try:
with zipfile.ZipFile(file_path, 'a') as open_document:
open_document.open(DOCUMENT_MANIFEST_PATH)
return ... | 3e36bea3c7f3bd72b91cefba94087ea8afc5116e | 30,648 |
def mean_absolute_percentage_error(y_true, y_pred, zeros_strategy='mae'):
"""
Similar to sklearn https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html
with options for behaviour for around zeros
:param y_true:
:param y_pred:
:param zeros_strategy:
:return... | 5720343835378e50399caafeada31685effde5de | 30,649 |
import json
def __get_pretty_body__(headers, body):
"""
Return a pretty printed body using the Content-Type header information
:param headers: Headers for the request/response (dict)
:param body: Body to pretty print (string)
:return: Body pretty printed (string)
"""
if HEADER_CONTENT_TYP... | 4cb173c8c5d8c924b58b0c39f5595e353e514eee | 30,650 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.