content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def paradigm_filler(shared_datadir) -> ParadigmFiller:
"""
hese layout, paradigm, and hfstol files are **pinned** test data;
the real files in use are hosted under res/ folder, and should not
be used in tests!
"""
return ParadigmFiller(
shared_datadir / "layouts",
shared_datadir ... | e20ca1eebfeca8b4d54d87a02f723e21fd54c3bf | 3,644,700 |
def apply_scaling(data, dicom_headers):
"""
Rescale the data based on the RescaleSlope and RescaleOffset
Based on the scaling from pydicomseries
:param dicom_headers: dicom headers to use to retreive the scaling factors
:param data: the input data
"""
# Apply the rescaling if needed
pr... | 13bc94058aa725b59f017fc069408a9d279cd933 | 3,644,701 |
from itertools import product
def allowed_couplings(coupling, flow, free_id, symmetries):
"""Iterator over all the allowed Irreps for free_id in coupling if the
other two couplings are fixed.
"""
if len(coupling) != 3:
raise ValueError(f'len(coupling) [{len(coupling)}] != 3')
if len(flow... | 1e2d71edc68b8ecebfa3e09eae17e17a381d82b4 | 3,644,702 |
def poly_iou(poly1, poly2, thresh=None):
"""Compute intersection-over-union for two GDAL/OGR geometries.
Parameters
----------
poly1:
First polygon used in IOU calc.
poly2:
Second polygon used in IOU calc.
thresh: float or None
If not provided (default), returns the floa... | c033e654144bb89093edac049b0dfcd4cdec3d1a | 3,644,703 |
def score_file(filename):
"""Score each line in a file and return the scores."""
# Prepare model.
hparams = create_hparams()
encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir)
has_inputs = "inputs" in encoders
# Prepare features for feeding into the model.
if has_inputs:
inpu... | 62cac29e72bf5e7651cd8a258fb4151b6d7e1ff4 | 3,644,704 |
import responses
from renku.core.commands.providers.dataverse import DATAVERSE_API_PATH, DATAVERSE_VERSION_API
from renku.core.commands.providers.doi import DOI_BASE_URL
import json
import re
import urllib
import pathlib
def doi_responses():
"""Responses for doi.org requests."""
with responses.RequestsMock(... | 8e467910f2d9ad4df06ff0ecb11c0812e7dc3bb5 | 3,644,705 |
def lat_lng_to_tile_xy(latitude, longitude, level_of_detail):
"""gives you zxy tile coordinate for given latitude, longitude WGS-84 coordinates (in decimal degrees)
"""
x, y = lat_lng_to_pixel_xy(latitude, longitude, level_of_detail)
return pixel_xy_to_tile_xy(x, y) | 99e2a4b3d9dee41222b434768bed5501e7561a40 | 3,644,706 |
def update_inverse_jacobian(previous_inv_jac, dx, df, threshold=0, modify_in_place=True):
"""
Use Broyden method (following Numerical Recipes in C, 9.7) to update inverse Jacobian
current_inv_jac is previous inverse Jacobian (n x n)
dx is delta x for last step (n)
df is delta errors for last step (n... | 4f6a0e3e3bdc25132fae2aa1df9d0bbcdd73c3b1 | 3,644,707 |
def _ConvertStack(postfix):
"""Convert postfix stack to infix string.
Arguments:
postfix: A stack in postfix notation. The postfix stack will be modified
as elements are being popped from the top.
Raises:
ValueError: There are not enough arguments for functions/operators.
Returns:
A string of... | d69f4a503a84efedbf623cca24c496f5540d1b77 | 3,644,708 |
import re
def count_repeats_for_motif(seq, motif, tally, intervals=None):
"""
seq --- plain sequence to search for the repeats (motifs)
motif --- plain sequence of repeat, ex: CGG, AGG
intervals --- 0-based start, 1-based end of Intervals to search motif in
"""
if intervals is None: # use the ... | 2a29339555374aaeb70ea07872a81a56050a9f36 | 3,644,709 |
import requests
import re
def get_oauth2_token(session: requests.Session, username: str, password: str):
"""Hackily get an oauth2 token until I can be bothered to do this correctly"""
params = {
'client_id': OAUTH2_CLIENT_ID,
'response_type': 'code',
'access_type': 'offline',
'... | 1361f76cdba195e43ba77ee756ef434ee6dab991 | 3,644,710 |
def press_level(pressure, heights, plevels, no_time=False):
"""
Calculates geopotential heights at a given pressure level
Parameters
----------
pressure : numpy.ndarray
The 3-D pressure field (assumes time dimension, turn off
with `no_time=True`)
heights : numpy.ndarray
... | 7cae6fe91eb1f6ad4171006633d04744909849c5 | 3,644,711 |
def valtoindex(thearray, thevalue, evenspacing=True):
"""
Parameters
----------
thearray: array-like
An ordered list of values (does not need to be equally spaced)
thevalue: float
The value to search for in the array
evenspacing: boolean, optional
If True (default), assu... | 5540023c77b544fbd91a724badf467981a0e0a5c | 3,644,712 |
def get_converter(result_format, converters=None):
"""
Gets an converter, returns the class and a content-type.
"""
converters = get_default_converters() if converters is None else converters
if result_format in converters:
return converters.get(result_format)
else:
raise ValueE... | 79ce7a728fb801922d672716aeb77dc76e270194 | 3,644,713 |
import ast
def _deduce_ConstantArray(
self: ast.ConstantArray, ctx: DeduceCtx) -> ConcreteType: # pytype: disable=wrong-arg-types
"""Deduces the concrete type of a ConstantArray AST node."""
# We permit constant arrays to drop annotations for numbers as a convenience
# (before we have unifying type inferen... | 91b9966bc5f0fd1254551e450593b8f8b669baad | 3,644,714 |
def _to_bool(s):
"""Convert a value into a CSV bool."""
if s.lower() == 'true':
return True
elif s.lower() == 'false':
return False
else:
raise ValueError('String cannot be converted to bool') | 3f6c31a07e7ba054e5c52f9d3c09fdd2f004fec5 | 3,644,715 |
def register(*args, cache_default=True):
"""
Registers function for further caching its calls and restoring source.
Example:
``` python
@register
def make_ohe_pclass(df):
...
```
"""
def __register(func):
# if source_utils.source_is_saved(func) and not source_ut... | 41610d7f3463088f29125fe335a04b9b0292b74f | 3,644,716 |
import re
def make_absolute_paths(content):
"""Convert all MEDIA files into a file://URL paths in order to
correctly get it displayed in PDFs."""
overrides = [
{
'root': settings.MEDIA_ROOT,
'url': settings.MEDIA_URL,
},
{
'root': settings.STATIC... | 4632513f73bf49ec6d1acfef15d632ee980ab345 | 3,644,717 |
def social_distancing_start_40():
"""
Real Name: b'social distancing start 40'
Original Eqn: b'31'
Units: b'Day'
Limits: (None, None)
Type: constant
b''
"""
return 31 | c874afed46a8303ec2d3ad0d571183ddc30059a0 | 3,644,718 |
import argparse
def parse_argv(argv):
"""
parse argv
"""
psr = argparse.ArgumentParser(prog=argv[0])
psr.add_argument("--users-csv", default="users.csv",
help=("a csv file describing directories to monitor, which at minimum must have a column 'notebooks'."
... | 750c9ffd47e7e4a00c11292f78c154da93eda246 | 3,644,719 |
def get_token_auth_header(params):
"""
Obtains the Access Token from the Authorization Header
"""
auth = get_token(params)
parts = auth.split()
if parts[0].lower() != "bearer":
raise AuthError({"code": "invalid_header", "description": "Authorization header must start with Bearer"}, 401)... | c48a2306ea76b1b5f611194eb33fa13e40f0e155 | 3,644,720 |
from typing import Optional
def check_hu(base: str, add: Optional[str] = None) -> str:
"""Check country specific VAT-Id"""
weights = (9, 7, 3, 1, 9, 7, 3)
s = sum(int(c) * w for (c, w) in zip(base, weights))
r = s % 10
if r == 0:
return '0'
else:
return str(10 - r) | 48f1043eeede4ea0b04eb71685f19901da495195 | 3,644,721 |
import requests
from bs4 import BeautifulSoup
def scrape_headline(news_link):
"""
function to scrape the headlines from a simple news website
:return: a dictionary with key as html link of the source and
value as the text in the headline of the news in the html link
"""
#Headli... | f87453a925ace26a3f848c0ed380b6e4ab7030a7 | 3,644,722 |
def read_xml(img_path):
"""Read bounding box from xml
Args:
img_path: path to image
Return list of bounding boxes
"""
anno_path = '.'.join(img_path.split('.')[:-1]) + '.xml'
tree = ET.ElementTree(file=anno_path)
root = tree.getroot()
ObjectSet = root.findall('object')
bboxes ... | 7102edccb5258d88b67476770123e54e1b75a5c1 | 3,644,723 |
def a2funcoff(*args):
"""a2funcoff(ea_t ea, char buf) -> char"""
return _idaapi.a2funcoff(*args) | 0cac71a4e071bf99bf6777fc35002e48099ecc46 | 3,644,724 |
def str(obj):
"""This function can be used as a default `__str__()` in user-defined classes.
Classes using this should provide an `__info__()` method, otherwise the `default_info()`
function defined in this module is used.
"""
info_func = getattr(type(obj), "__info__", default_info)
return "{}(... | 651e6f3e047a8f7583a39d337d202c09934bc37a | 3,644,725 |
from typing import Union
from typing import Optional
from typing import Sequence
from typing import Any
def isin_strategy(
pandera_dtype: Union[numpy_engine.DataType, pandas_engine.DataType],
strategy: Optional[SearchStrategy] = None,
*,
allowed_values: Sequence[Any],
) -> SearchStrategy:
"""Strat... | aecf05b269b7f89b6fea0b5bfbbc98e51d4caddb | 3,644,726 |
def arrToDict(arr):
"""
Turn an array into a dictionary where each value maps to '1'
used for membership testing.
"""
return dict((x, 1) for x in arr) | 3202aac9a6c091d7c98fd492489dbcf2300d3a02 | 3,644,727 |
def getPercentGC(img, nbpix) :
"""Determines if a page is in grayscale or colour mode."""
if img.mode != "RGB" :
img = img.convert("RGB")
gray = 0
for (r, g, b) in img.getdata() :
if not (r == g == b) :
# optimize : if a single pixel is no gray the whole page is color... | e8ee682889e0f9284cecfcf57cf260b7056c1879 | 3,644,728 |
import ctypes
def rotate(angle: float, iaxis: int) -> ndarray:
"""
Calculate the 3x3 rotation matrix generated by a rotation
of a specified angle about a specified axis. This rotation
is thought of as rotating the coordinate system.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rotate_... | 035144bdf04b4c39cc4bf1e41ec02d4c71d4d951 | 3,644,729 |
def build_categories(semanticGroups):
"""
Returns a list of ontobio categories or None
Parameters
----------
semanticGroups : string
a space delimited collection of semanticGroups
"""
if semanticGroups is None:
return None
categories = []
for semanticGroup in semant... | 5262b62cd5ce8e8c0864f91f43a0925ea991cc83 | 3,644,730 |
from x84.bbs import getterminal
import time
def show_nicks(handles):
""" return terminal sequence for /users result. """
term = getterminal()
return u''.join((
time.strftime('%H:%M'), u' ',
term.blue('-'), u'!', term.blue('-'),
u' ', term.bold_cyan('%d' % (len(handles))), u' ',
... | 6863b7a67686a337304c9f22eb4bd9488f959a1f | 3,644,731 |
def cvCmp(*args):
"""cvCmp(CvArr src1, CvArr src2, CvArr dst, int cmp_op)"""
return _cv.cvCmp(*args) | ec2b9d8d68083fff3a09a5293e9950a2c67c424b | 3,644,732 |
def convert_to_dtype(data, dtype):
"""
A utility function converting xarray, pandas, or NumPy data to a given dtype.
Parameters
----------
data: xarray.Dataset, xarray.DataArray, pandas.Series, pandas.DataFrame,
or numpy.ndarray
dtype: str or numpy.dtype
A string denoting a... | ec3130311fe9c136707d5afb8f564b4f89067f4e | 3,644,733 |
def process_files(data_path, output_path):
"""Returns a pipeline which rebalances data shards.
Args:
data_path: File(s) to read.
output_path: Path to which output CSVs are written, if necessary.
"""
def csv_pipeline(root):
_ = (
root
| beam.io.ReadFromText(data_path)
| bea... | 320a66857dfcfa43995226ee20f714f0694c8f8d | 3,644,734 |
def delete_tasklog_cached(dc_id, user_id=None):
"""
Remove tasklog cache entry.
"""
if user_id:
key = _cache_log_key(user_id, dc_id)
else:
key = _cache_log_key(settings.TASK_LOG_STAFF_ID, dc_id)
return cache.delete(key) | 29435d0618850a442a56d4d28e96be5989bca1f5 | 3,644,735 |
def strip_headers(data):
""" Strips headers from data #depreciate"""
try:
return data['items']
except (TypeError, KeyError) as e:
print(e)
return data | 2eb044e45043f103fff76bfa47007dbcd4aa49c7 | 3,644,736 |
def sns_plot(chart_type: str, df):
""" return seaborn plots """
fig, ax = plt.subplots()
if chart_type == "Scatter":
with st.echo():
sns.scatterplot(
data=df,
x="bill_depth_mm",
y="bill_length_mm",
hue="species",
... | 8081349e83745167443d76c9be30ee8b884e8d67 | 3,644,737 |
def decode_fields(source_str: str, resp_type):
""" This is the lower level decode of fields, no automatic guess of type is performed."""
field_decoding = FIELD_MAPPING[resp_type]
unpacked_fields = {}
for field_name, field_type, field_subtype in field_decoding:
search_term = f"{field_name}:".e... | 6d1afebcfb377be0ce454f5a1db7b6aad37313c5 | 3,644,738 |
def make_egg(a=-1.25, b=7):
"""
Return x, y points that resemble an egg.
Egg equation is:
r = cos(2θ) + a * cos(θ) + b
@param a: Number.
@param b: Number.
"""
theta = np.linspace(0, 2 * np.pi, 100)
r = np.cos(2 * theta) + a * np.cos(theta) + b
y = r * np.cos(theta)
x =... | b94ca316ba9e8bcfdcc3622205204e322c2bccb8 | 3,644,739 |
def test_styling_object_which_implements_str_proto():
"""
Test styling an object which implements the str protocol
"""
class Dummy(object):
def __str__(self):
return 'I am a dummy object'
colorful = core.Colorful(colormode=terminal.ANSI_8_COLORS)
assert str(colorful.black(Du... | d14567675db25c66bdc00e28904b721bb3af536d | 3,644,740 |
def determine_auto_approval(financial_aid, tier_program):
"""
Takes income and country code and returns a boolean if auto-approved. Logs an error if the country of
financial_aid does not exist in CountryIncomeThreshold.
Args:
financial_aid (FinancialAid): the financial aid object to determine au... | 280af275564046ed36b8b5442879f8dcc7e515cb | 3,644,741 |
def crustal_model_files(alt = [200, 1000], anomaly = 'Global', lim = [0., 360. -90., 90.], binsize = 0.1):
""""
Reads the .bin IDL files of the crustal magnetic field model (Langlais) for a range of altitudes and creates a function based on a linear interpolation.
Parameters:
alt: 2-elements ar... | e5deb36b571c0cc75e738bd0bdce7a2fa6ea8d7a | 3,644,742 |
def f1(y_true, y_pred):
"""
Function for computing the unweighted f1 score using tensors. The Function
handles only the binary case and compute the unweighted f1 score
for the positive class only.
Args:
- y_true: keras tensor, ground truth labels
- y_pred: keras tensord, labels esti... | 793fbcbd2ddcec2608139174794e94304f69a631 | 3,644,743 |
def get_selector_score(key, selector, use_median, best_based_on_final):
"""
:param key: Thing to measure (e.g. Average Returns, Loss, etc.)
:param selector: Selector instance
:param use_median: Use the median? Else use the mean
:param best_based_on_final: Only look at the final value? Else use all
... | 4c9d2e08fcc4f4ee3ecbd2cf67e4db829850707a | 3,644,744 |
import pytz
def str_to_timezone(tz):
"""
从字符串构建时区
"""
return pytz.timezone(tz) if tz else pytz.utc | 02c004171f50ceb4b60272769036634f6778c791 | 3,644,745 |
def _get_previous_index_search_col(
m, col, nested_list, trans_function=None, transformation=False
):
"""Return previous index of a a key, from a sorted nested list where a key is being seached in the col number.Returns -1 if value is not found.
Args:
m (comparable): comparable being searched
... | 4545395928128ce2858c1d0508e77a47be543dd7 | 3,644,746 |
import json
def guest_import(hypervisor, host):
"""
Import a new guest
::
POST /:hypervisor/:host/guests
"""
response.content_type = "application/json"
manager = create_manager(hypervisor, host)
guest = manager.guest_import(
request.environ['wsgi.input'],
request.c... | d26ecbac6bce0ab07c365aabb8352ec57719798d | 3,644,747 |
from typing import List
def get_doc_count(
group_by: List[str] = ["year", "country"],
sort_by: List[metadata.SortOn] = [
metadata.SortOn(field="year", order=metadata.SortOrder.desc),
metadata.SortOn(field="count", order=metadata.SortOrder.desc)],
limit: int = 10):
"... | c815d6d9a2746c61d3affbca07e8334c75862030 | 3,644,748 |
import re
def get_author_list(text):
"""function to extract authors from some text that will also include
associations
example input:
`J. C. Jan†, F. Y. Lin, Y. L. Chu, C. Y. Kuo, C. C. Chang, J. C. Huang and C. S. Hwang,
National Synchrotron Radiation Research Center, Hsinchu, Taiwan, R.O.C`
o... | 94b7f74ed24be8bb8bbfacca37dfc9f65f1fc99b | 3,644,749 |
def find_matching_format_function(word_with_formatting, format_functions):
""" Finds the formatter function from a list of formatter functions which transforms a word into itself.
Returns an identity function if none exists """
for formatter in format_functions:
formatted_word = formatter(word_with... | 3d2ce0956de4c8ca0de6d0d21f8bbd718247caff | 3,644,750 |
from typing import List
def mean (inlist:List(float))->float:
"""
Returns the arithematic mean of the values in the passed list.
Assumes a '1D' list, but will function on the 1st dim of an array(!).
Usage: lmean(inlist)
"""
sum = 0
for item in inlist:
sum = sum + item
return sum/float(len(i... | 713bbbec706671043a5b76f142d4f19cfa247c6a | 3,644,751 |
def create_file_download_url(file_path: str) -> str:
"""
Creates Telegram URL for downloading of file.
- contains secret information (bot token)!
:param file_path: `file_path` property of `File` object.
"""
token = environ["TELEGRAM_API_BOT_TOKEN"]
return create_url(
"https://api.... | 6395d17520778d6bf4507ba69559b6ef1ba32ba9 | 3,644,752 |
import csv
from datetime import datetime
def convert_to_csv(items):
"""
Args:
items: all arns in a region from the DynamoDB query as a list
returns:
csv_body: body of the csv file to write out
"""
fieldnames = ["Package", "Package Version", "Status", "Expiry Date", "Arn"]
# sort ... | 6e651065f06595e9b964bee1b8dab2965e0076f6 | 3,644,753 |
def manhattan(train_X, val_X):
"""
:param train_X: one record from the training set
(type series or dataframe including target (survived))
:param val_X: one record from the validation set
series or dataframe include target (survived)
:return: the Manhattan distanc... | 1989466af70d38a17c2b52dd667733da46bbed0c | 3,644,754 |
def author_idea_list(request, registrant_id):
"""
Returns author ideas
"""
registrant = get_object_or_404(Registrant, pk=registrant_id)
ideas = Idea.objects.filter(author=registrant)
serializer = IdeaSerializer(ideas, many=True)
return Response(serializer.data, status=status.HTTP_200_OK) | 64ee16535243bfe5414326bed86f5b9efdb97941 | 3,644,755 |
import re
def match(text: str, pattern: str) -> bool:
"""
Match a text against a given regular expression.
:param text: string to examine.
:param pattern: regular expression.
:returns: ``True`` if pattern matches the string.
"""
return re.match(pattern, text) is not None | a59d71283766c5079e8151e8be49501246218001 | 3,644,756 |
def _compute_hash_check(input_strings: tf.Tensor, field_size: int, seed: int,
dtype: tf.dtypes.DType) -> tf.Tensor:
"""Returns the hash_check for input_strings modulo field_size."""
hash_check_salt = _get_hash_check_salt(seed)
salted_input = tf.strings.join([hash_check_salt, input_strings]... | bff5d9b24f17fd32ea3a5bfbd60a8446f10471aa | 3,644,757 |
def _trademark(request):
"""
access to the produt database is available here, making a request to save/check the data
for storage inside the database
"""
# site data from scrap program
websitename = WebsiteClassName().getProducts( WebsiteClassName().getCategoryLinks() )
# access the data structure we need to ... | e34c77a423a23310e9fbdb6f867795b3ce16935f | 3,644,758 |
import numpy
def calc_extinction(radius:float, mosaicity:float, model:str,
a:float, b:float, c:float, alpha:float, beta:float, gamma:float,
h:float, k:float, l:float,
f_sq:float, wavelength:float, flag_derivative_f_sq=False):
"""
Isotropical extinct... | b0922fde0246ee250033d9ff9eb3fde59c17c343 | 3,644,759 |
def smape(y_true: Yannotation, y_pred: Yannotation):
"""
Calculate the symmetric mean absolute percentage error between `y_true`and `y_pred`.
Parameters
----------
y_true : array, `dataframe`, list or `tensor`
Ground truth values. shape = `[batch_size, d0, .. dN]`.
y_pred : array, `data... | 0046481ea6b2ddc3295f9d597d6cc3488b498415 | 3,644,760 |
def acosh(rasters, extent_type="FirstOf", cellsize_type="FirstOf", astype=None):
"""
The ACosH operation
The arguments for this function are as follows:
:param rasters: array of rasters. If a scalar is needed for the operation, the scalar can be a double or string
:param extent_type: one of "First... | 593b13639f40c347a27d4fc772d7b2ec2d062a86 | 3,644,761 |
from typing import Optional
from typing import Dict
from typing import Tuple
from typing import Any
def load_does(
filepath: PathType, defaults: Optional[Dict[str, bool]] = None
) -> Tuple[Any, Any]:
"""Load_does from file."""
does = {}
defaults = defaults or {"do_permutation": True, "settings": {}}
... | 22cebd75da899bebb092c1c470eabe87e17c41f5 | 3,644,762 |
def causal_segment_mask(segment_ids: JTensor,
dtype: jnp.dtype = jnp.float32) -> JTensor:
"""Computes the masks which combines causal masking and segment masks.
Args:
segment_ids: a JTensor of shape [B, T], the segment that each token belongs
to.
dtype: data type of the input.... | 7e16f2a943e19b232fb3f1e55f7b348aa7f56a72 | 3,644,763 |
def remove_outliers(peaks: np.ndarray, **kwargs):
"""
https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.LocalOutlierFactor.html#sklearn.neighbors.LocalOutlierFactor
https://scikit-learn.org/stable/modules/outlier_detection.html
Parameters
----------
peaks
kwargs
Retur... | 969fe4523e8529edd49a5c0cd81c51949bbe3de5 | 3,644,764 |
def powerset(iterable):
""" Calcualtes the powerset, copied from https://docs.python.org/3/library/itertools.html#itertools-recipes """
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) | 3b645848c0810c69685c06b94fee42e5747bb6e8 | 3,644,765 |
def get_rotational_vector(skew_symmetric):
"""Get the rotational vector from a skew symmetric matrix.
Parameters
----------
skew_symmetric: numpy.ndarray
the skew symmetric matrix.
Returns
-------
rotational_vector:
the rotational vector.
"""
# make sure that the ... | e63b771f6db93f63d7307a85689d87162208c6ff | 3,644,766 |
def diaperchange_lifetimes(changes):
"""
Create a graph showing how long diapers last (time between changes).
:param changes: a QuerySet of Diaper Change instances.
:returns: a tuple of the the graph's html and javascript.
"""
changes = changes.order_by("time")
durations = []
last_change... | 4937cff711b8e37e4162a4c7de8cc258c25d2979 | 3,644,767 |
def batch_norm_conv(x, n_out, phase_train, scope='bn'):
"""
Batch normalization on convolutional maps.
Args:
x: Tensor, 4D BHWD input maps
n_out: integer, depth of input maps
phase_train: boolean tf.Varialbe, true indicates training phase
scope: string, ... | 2a08db220f08270a8f2870671ee93278f0c7ddd2 | 3,644,768 |
def strip_variants(address):
"""Return a copy of the given address with the variants (if any) stripped from the name.
:rtype: :class:`pants.build_graph.address.Address`
"""
address, _ = parse_variants(address)
return address | a2cc1c68b6032304720b9cae05516535cb9ede22 | 3,644,769 |
def deleteIdentifiedStock(bot, update):
"""Deletes the user's selected stock.
If the user's selected stock is valid, proceed to delete it.
Returns:
Return MENU state with normal keyboard.
"""
if update.message.chat.username is None:
# User has no username
update.mess... | 7a47579f7e0b9b9388ef0f0f4650cb045cf53570 | 3,644,770 |
def z_inc_down(grid):
"""Return True if z increases downwards in the coordinate reference system used by the grid geometry
:meta common:
"""
if grid.crs is None:
assert grid.crs_uuid is not None
grid.crs = rqc.Crs(grid.model, uuid = grid.crs_uuid)
return grid.crs.z_inc_down | 26b05defc1b75ec5a4f3aa9f61c3ba0cb5921bdc | 3,644,771 |
def load_coord_var(prob_data_type):
"""
Loads a coordinate variable from the source data and returns it.
:param prob_data_type:
:return:
"""
fpath = "{}/source_others/a1b_tas_jja_EAW_1961-1990.dat".format(BASEDIR)
with open(fpath, 'rb') as reader:
data = cPickle.load(reader)
k... | 46969ac762393c8b7c60d08b543a2fc2f0069b74 | 3,644,772 |
import platform
def get_os():
"""Get the current operating system.
:returns: The OS platform (str).
"""
return platform.system() | 307c6c94573733d900b2e31cfc8bcf3db8b6e5b7 | 3,644,773 |
import os
import yaml
def get_config():
"""This function retrieves API keys, access tokens, and other key data from the config file."""
global LOG_NAME, TARGET, URL_NUMBER, WHERE, BOT
print("Building OAuth header...")
if 'XKCD_APPNAME' in os.environ: # Running on a cloud server
key = [os.envi... | 0b898df5edb85c5d826b94c8962a0d5f327e94d2 | 3,644,774 |
def count_hits(space, positions, pi_plus_4_vecs_lab, pi_null_4_vecs_lab, r):
"""returns a list of hit counts for z values in space"""
return [count_double_hits(positions, pi_plus_4_vecs_lab, pi_null_4_vecs_lab, r=r, z_detector=z) for z in space] | 66ba0f61d8491ef6687c0fb20761375c6470cae2 | 3,644,775 |
import time
import math
def time_since(since, m_padding=2, s_padding=2):
"""Elapsed time since last record point."""
now = time.time()
s = now - since
m = math.floor(s / 60)
s -= m * 60
return '{}m:{}s'.format(str(int(m)).zfill(m_padding),
str(int(s)).zfill(s_paddin... | 62641b723bf286f54280bb5c6fb1d54c9753907c | 3,644,776 |
import subprocess
import collections
def run_cmd(cmd, encoding=DEFAULT_ENCODING):
"""
Run a command as a subprocess.
# Arguments
* `cmd` (list<str>): The command to run.
* `encoding` (str): The encoding to use for communicating with the
subprocess.
# Returns
A named tuple with ... | b03ae4949d00f8a1019ea6bde739550a21585409 | 3,644,777 |
def record_check(record):
"""
record dict check
--- a dictionary is required as the input ---
"""
assert isinstance(
record, dict), 'record should be dict, while the input is {}'.format(type(record))
cnn_json_struct = JsonFormatSetting.CNN_JSON_STRUCTURE
record_struct = cnn_json_stru... | 965cced685b45de8083dc1c8e161e9aa100b4cf0 | 3,644,778 |
import struct
def encrypt_chunk(chunk, password=None):
"""Encrypts the given chunk of data and returns the encrypted chunk.
If password is None then saq.ENCRYPTION_PASSWORD is used instead.
password must be a byte string 32 bytes in length."""
if password is None:
password = saq.ENCRYPT... | 328484205dff850f3857f0a7d19e922ffa230c61 | 3,644,779 |
def convert_to_pj_lop_plus(lops):
"""
Converts the list of PlayerStates to an LOP+
:param lops: The PlayerStates to be converted
:type lops: [PlayerState, ...]
:return: The LOP+
:rtype: PyJSON
"""
return [convert_to_pj_player_plus(ps) for ps in lops] | 968e0a38b5df2a1ce4bf6106632c31213d278a29 | 3,644,780 |
from typing import Tuple
import math
def euler_to_quaternion(roll: float = 0, pitch: float = 0, yaw: float = 0) -> Tuple[float, float, float, float]:
"""
Convert Euler to Quaternion
Args:
roll (float): roll angle in radian (x-axis)
pitch (float): pitch angle in radian (y-axis)
yaw... | e8346172f07510c377e14827842eb18f1631402e | 3,644,781 |
import logging
def supervisorctl_url():
"""This parses supervisord.conf which contains the URL of supervisorctl."""
parsed_config = _get_parsed_configuration()
# For example 'http://localhost:9001'
control_url = _clean_config_value(parsed_config['supervisorctl']['serverurl'])
logging.debug("con... | 9ada9298f99eccfac3c02c2653ead753ea208119 | 3,644,782 |
def create_generic_constant(type_spec, scalar_value):
"""Creates constant for a combination of federated, tuple and tensor types.
Args:
type_spec: Instance of `computation_types.Type` containing only federated,
tuple or tensor types for which we wish to construct a generic constant.
May also be som... | 9e1db57d93407eef385c1ac88ba83a4e578f891a | 3,644,783 |
from django_openid.models import UserOpenidAssociation
def has_openid(request):
"""
Given a HttpRequest determine whether the OpenID on it is associated thus
allowing caller to know whether OpenID is good to depend on.
"""
for association in UserOpenidAssociation.objects.filter(user=request.user):... | ad193ae3c299867ed4c29ee059c45fe24a07523c | 3,644,784 |
def get_wordcloud():
"""
Generates the wordcloud and sends it to the front end as a png file.
:return: generated tag_cloud.png file
"""
update_tagcloud(path_to_save='storage/tmp', solr_service=solr)
return send_from_directory("storage/tmp", "tag_cloud.png", as_attachment=True) | c40cbf95676ac1b3da9c589934bb67a589a80810 | 3,644,785 |
def rtc_runner(rtc):
"""
:type rtc: pbcommand.models.ResolvedToolContract
:return:
"""
return gather_run_main(chunk_json=rtc.task.input_files[0],
chunk_key=Constants.CHUNK_KEY,
gathered_fn=rtc.task.output_files[0],
ln_n... | 10aa9c707284a04a0d002b95169d0a28e91213eb | 3,644,786 |
from typing import Tuple
def get_matching_axis(shape: Tuple, length: int) -> int:
"""
Infers the correct axis to use
:param shape: the shape of the input
:param length: the desired length of the axis
:return: the correct axis. If multiple axes match, then it returns the last
one... | 981e2bb2487cd113ffc5dd19c2a62d581cf38304 | 3,644,787 |
def is_paths(maybe_paths, marker='*'):
"""
Does given object `maybe_paths` consist of path or path pattern strings?
"""
return ((is_path(maybe_paths) and marker in maybe_paths) or # Path str
(is_path_obj(maybe_paths) and marker in maybe_paths.as_posix()) or
(is_iterable(maybe_pa... | dc825d7417cb7cb52beaecc4fb6eef333db1514b | 3,644,788 |
import logging
def output_numpy_or_asa(obj, data, *, output_type=None, labels=None):
"""This function returns a numpy ndarray or nelpy.AnalogSignalArray
Parameters
----------
obj : numpy.ndarray or a nelpy object
data : numpy.ndarray, with shape (n_samples, n_signals)
Data is either passe... | 2e19de7caa58d4be606fa3c2fef623c32a08a201 | 3,644,789 |
def embed_oar(features: Array, action: Array, reward: Array,
num_actions: int) -> Array:
"""Embed each of the (observation, action, reward) inputs & concatenate."""
chex.assert_rank([features, action, reward], [2, 1, 1])
action = jax.nn.one_hot(action, num_classes=num_actions) # [B, A]
reward = ... | 624b1ca67fa031e548411b4c9cfd9f86765cbd7e | 3,644,790 |
import json
async def kibana(es, params):
"""
Simulates Kibana msearch dashboard queries.
It expects the parameter hash to contain the following keys:
"body" - msearch request body representing the Kibana dashboard in the form of an array of dicts.
"params" - msearch request para... | d07b3278bb7fc62565cce905e575bcc21a54f79a | 3,644,791 |
import requests
import json
def aggregations_terms(query=None):
"""Get page for aggregations."""
if query is None:
# Default query
query = "state,config.instance_type"
# Remove all white spaces from the str
query = query.replace(" ", "")
data = {"query": query}
end_point = "a... | c69308a007ec4b366129de3c3aa277c96fda2edd | 3,644,792 |
import tqdm
import torch
def validate_base(model,
args,
loader,
loadername,
train=True):
"""
The validation function. Validates the ELBO + MIL, ELBO, and the accuracy
of the given [training, validation or test] loader.
Returns
... | 85c9558bd484190eb61599509b9c9ec9f4a5cc0a | 3,644,793 |
def parse_person(person):
"""
https://doc.rust-lang.org/cargo/reference/manifest.html#the-authors-field-optional
A "person" is an object with an optional "name" or "email" field.
A person can be in the form:
"author": "Isaac Z. Schlueter <[email protected]>"
For example:
>>> p = parse_person('Bar... | 3fe30bf85f3ba4877b2924c5b5778d5a5205b6ee | 3,644,794 |
def _glasstone_surface_cf(y):
"""Correction factor provided by TEoNW for contact surface bursts (p. 335)."""
return np.interp(y, [1.0, 50.0, 100.0, 300.0, 700.0, 2000.0, 5000.0, 5000.0], [0.6666666666666666, 0.6666666666666666, 1.0, 1.25, 1.5, 2.0, 3.0, 3.0]) | 8ac3b0273e8c8fe218d15a2b89aad994a7413d68 | 3,644,795 |
import torch
def create_eval_fn(task_id, calculate_gradient=False):
"""Creates an evaluation function for a given task. Returns an evaluation
function that takes in a model, dataloader, and device, and evaluates the
model on the data from the dataloader. Returns a dictionary with mean
"loss" and "accu... | ac0a7107f695170f2fa6c65dfeae63056b53452d | 3,644,796 |
import os
def get_dashboard_oauth_client_id():
"""Gets the client ID used to authenticate with Identity-Aware Proxy
from the environment variable DASHBOARD_OAUTH_CLIENT_ID."""
return os.environ.get('DASHBOARD_OAUTH_CLIENT_ID') | 37a0ba23dab00d2e43fc1cbd124713d2231d91a9 | 3,644,797 |
def naming_style(f):
"""Decorator for name utility functions.
Wraps a name utility function in a function that takes one or more names,
splits them into a list of words, and passes the list to the utility function.
"""
def inner(name_or_names):
names = name_or_names if isinstance(name_or_na... | bbcb1b0b06bbb7a24abe60131a9a5ba525ed01db | 3,644,798 |
import argparse
def parse_args(argv, app_name):
"""Parse command line arguments"""
parser = argparse.ArgumentParser(description=app_name)
parser.add_argument(
"-c",
"--config",
dest="config",
type=str,
default="config.yaml",
help="Set config.yaml file",
... | 5befd81f895ee8d15b9972587a980bbdba51085e | 3,644,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.