content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Optional
from sys import path
def get_version() -> Optional[str]:
"""Returns the current version of strops.
Requires a symlink install or to run strops directly from the repository.
"""
commit = None
try:
git_dir = path.join(ROOT_DIR, ".git")
if path.exists(git_... | 27b9666be2524ca50c25b0a4849060895c67f019 | 3,624,000 |
def mock_cloud_fixture(opp):
"""Fixture for cloud component."""
opp.loop.run_until_complete(mock_cloud(opp))
return mock_cloud_prefs(opp) | d9fc59fabe3cc49848062fbe4c5c4343b1c3cfed | 3,624,001 |
from typing import OrderedDict
def get_distinct_project_attributes(attribute, path=PROJECT_HOME):
"""Get distinct values of the named attribute.
.. versionadded:: 0.16.0-d
:param attribute: The name of the attribute.
:type attribute: str
:param path: The path to where projects are stored.
:... | 066157c2d5a6e49ddb2e7a7d4ee79f1bee4a6ae1 | 3,624,002 |
def scale_y_reverse(name=None, breaks=None, labels=None, limits=None, expand=None, na_value=None):
"""
Continuous position scales (y) where trans='reverse'
Parameters
----------
name : string
The name of the scale - used as the axis label or the legend title. If None, the default, the name ... | 718b662f1c80193962896765391b89fe12fbc0df | 3,624,003 |
import math
def get_sequence_of_considered_visits(max_num_considered_actions,
num_simulations):
"""Returns a sequence of visit counts considered by Sequential Halving.
Sequential Halving is a "pure exploration" algorithm for bandits, introduced
in "Almost Optimal Explorati... | f0081ae5bfe25d6a3eaad9f032cfb88a403fbb45 | 3,624,004 |
def reader_function(path):
"""Take a path or list of paths and return a list of LayerData tuples.
Readers are expected to return data as a list of tuples, where each tuple
is (data, [add_kwargs, [layer_type]]), "add_kwargs" and "layer_type" are
both optional.
Parameters
----------
path : s... | 042f2af4367958e7ed1b0e0088cf95e25bc28f89 | 3,624,005 |
import random
def select_object():
"""Select a random image from the PDS Planetary Rings Node."""
# First randomly select a field
fields = set(META['FIELD'])
field = random.sample(fields, 1)[0]
# Having selected a field, select a random number from that mission
max_field = META['MAX_NUM'][META['FIELD'] == field... | 05d8c26ad4671bf80cfeee9afa18be558a7a2075 | 3,624,006 |
import base64
def load_all_vocabs_details_from_github():
"""Uses the GitHub API via the Python client to get all the vocab details from the files in
the vocabularies/ folder
:return: a dict of vocabularies' details
"""
print('Loading all vocabs from GitHub')
print("Vocabs to be uploaded:")
... | ad662b0ff3517e4415a0f1b0e0d4558c1d4b55ef | 3,624,007 |
def two_node_diff(a):
"""Calculate and return diffs over two nodes instead of one."""
N = len(a)
return a[2:] - a[:(N-2)] | a38abe787ef87c37104373b402fc020f85f8e3aa | 3,624,008 |
def get_hue_sample_num(gamut_boundary_lut_name=mcfl.BT709_BOUNDARY):
"""
shape[0]: luminance sample
shape[1]: hue sample
"""
return np.load(gamut_boundary_lut_name).shape[1] | 8d7b6c4a8895a9574ab07e2eae9df9b0f33336a1 | 3,624,009 |
import datetime
import os
def make_savedir(parent_dir='./'):
"""
make directory to save results
Params
----------
parent_dir : str
parent directory to save results
"""
if parent_dir[-1] != '/':
parent_dir += '/'
orig_dirname = datetime.datetime.now().strftime('%y%m%d_... | 583e45b184e7cbeee39f2371ab649a8921c19f6f | 3,624,010 |
def _get_timeout(payload_len):
"""Conservatively assume min 5 seconds or 3 seconds per 1MB."""
return max(3 * payload_len / 1024 / 1024, 5) | 70ef10f9c4630afafa0019057bdaa005eb39e7ad | 3,624,011 |
def add_member(data):
"""Adds the newly signed up user to the member Table"""
# ToDo: Get Project Details from user during signup. Current system assumes user has no project preference.
try:
CheckConnection()
with Connection.cursor() as cursor:
name = str(data["name"])
... | f303e071c56b8b1fb685adfbf2fb46d37cf09834 | 3,624,012 |
import os
def check_img(img, input_dir):
""" Checks whether the img complies with API`s restrictions.
Parameters
----------
img : str
Image name.
input_dir : str
Path to the dir with the image to check.
Returns
-------
Error message if image does not comply with A... | 524a87633b59f676c70626f92f54c8dc33600363 | 3,624,013 |
def add_vec_mod2(v, w):
"""
Mod 2 addition separately on each components of v and w
:params list/str v, w: bit-strings (or list representations) to be added mod 2
:return str: component-wise mod 2 sum of the input strings/lists
"""
if len(v) != len(w):
raise AssertionError("Input length... | 01d01b522f1f046430c7df1f7cc5486280f5588a | 3,624,014 |
def sokal_sneath3(
x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None
) -> float:
"""Sokal-Sneath similarity (v3)
Sneath, P. H., & Sokal, R. R. (1973).
Numerical taxonomy.
The principles and practice of numerical classification.
Args:
x (BinaryFeatureVecto... | 054ccadfa0f0b63a508c51ceae33027d6e3ef030 | 3,624,015 |
def deactivate(name, path, user):
"""
Deactivate a wordpress plugin
name
Wordpress plugin name
path
path to wordpress install location
user
user to run the command as
CLI Example:
.. code-block:: bash
salt '*' wordpress.deactivate HyperDB /var/www/html a... | fadb823fdf9aa9b34fc6a29b877d553f62f2f7a5 | 3,624,016 |
def _average_gradients(tower_grads, catname=None):
"""Calculate the average gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over... | 1bd6af89d32003299b00ebd3cf5e57d7d6faeb14 | 3,624,017 |
def _validate_int(
setting, value, option_parser, config_parser=None, config_section=None
) -> int:
"""Validate an integer setting."""
return int(value) | 9036b1b043bd2463cad4f26780d47e80aa404f73 | 3,624,018 |
def get_best_name(phenomena):
"""
Create a best_name field which takes the best name as defined by the preference order
:param phenomena: phenomena attributes in form [{"name":"standard_name","value":"time"},{"name":"---","value":"---"},{}...]
:return: best_name(string)
"""
preference_order = ["... | cd5f1153a22e161e96f48fdcc02f4c4dbbfdbc34 | 3,624,019 |
def GetFqdn():
"""Get the desired FQDN via flags."""
return FLAGS.glazier_spec_fqdn | 9cea852620d1c13944294f5ab8e49223b643c525 | 3,624,020 |
def get_global_evidence(a):
"""
PyMultiNest's Analyzer has a get_stats() method, but it's
a bit too sluggish if all we want is to get the global
evidence out. This is a hack around the issue.
"""
stats_file = open(a.stats_file)
lines = stats_file.readlines()
stats = {}
a._read_error_... | 8677908c4537927f168cd16ab1ddbfaf959f4546 | 3,624,021 |
def load_data(database_filepath):
"""Loads data from database and returns label and features dataframe"""
engine = db.create_engine('sqlite:///{}'.format(database_filepath))
conn = engine.connect()
df = pd.read_sql_table('messages', con=conn)
X = df['message']
Y = df.iloc[:, 4:]
return X, Y... | 74e2dc17d3971ece3faaaadb25ce6b77d912e1fd | 3,624,022 |
def merge_scalar_results(results, scalar_fields):
""" Collect all scalar results in a (hierarchical) dataframe. """
return pd.DataFrame(
[[getattr(res, k) for k in scalar_fields] for res in results],
columns=scalar_fields,
).set_index("case") | 168581d50b00acf21ab45724faf5f678331198e7 | 3,624,023 |
from re import M
def omega_KMid(r):
"""
Keplerian angular velocity
"""
return (const.G*M/((r*u.AU)**3))**0.5 | 5e3c00b367cdca232e37e6b06df98737bb89f054 | 3,624,024 |
def buildRecorderDicts(energyInterval, powerInterval, voltageInterval,
energyPowerMeter, triplexGroup, recordMode,
query_buffer_limit):
"""Helper function to construct dictionaries to be used by individuals to
add recorders to their own models.
Note that th... | def51273b940ef97d61228cfd54277a9ac053aea | 3,624,025 |
def rooms_n2():
"""
Two rooms side by side
"""
rm1 = Room('rm1', 1e3, [[0,0], [5,0], [5,5], [0,5]])
rm2 = Room('rm2', 2e3, [[5,0], [10,0], [10,5], [5,5]])
rooms = [rm1, rm2]
return rooms | ced764acc60480a2c1d5d3488e9e0428d0f425ef | 3,624,026 |
def get_env(env_var_name):
"""
If present, returns environment variable value, if not - raises
'ImproperlyConfigured'
"""
env = environ.Env()
environ.Env.read_env()
return env(env_var_name) | 77ef5e6a8762abfe6e7268f7d88c7b4e7cf9211f | 3,624,027 |
def sub(arg1, arg2):
"""
Function that subtracts two arguments.
"""
return arg1 - arg2 | fb3694bc0827f62befe67cb58c1edb9de1adb808 | 3,624,028 |
def query_for_data(driver):
"""Grab all relevant data on a jobs page.
Return:
------
job_titles: list
job_locations: list
posting_companies: list
dates: list
hrefs: list
"""
job_titles = driver.find_elements_by_xpath(
"//span[@itemprop='tit... | d3a44ec2e66f9c8ba09dac45dc253c2dd67303c4 | 3,624,029 |
def users_json():
""" Return the all the users data in json format """
users = session.query(User).all()
return jsonify(users=[user.serialize for user in users]) | dd3fec73abbbe563eaa2335c5c2a942f98d0fb34 | 3,624,030 |
def get_image_info(filepath):
"""
Gets an image's information.
"""
image = Image.open(filepath)
info = {
'width': image.size[0],
'height': image.size[1],
}
metadata = get_image_exif(image)
# camera
camera = None
if EXIF_MODEL in metadata:
camera = metada... | e0c4ac5340874acf273873d52163d8642746fa18 | 3,624,031 |
import sys
def listAll():
"""
Load listAll page
"""
old_stdout = sys.stdout
sys.stdout = open('file.txt', 'w')
i_d = wmc.repository.list()
sys.stdout.close()
sys.stdout = old_stdout
fl = open('file.txt','r')
i_d = fl.read()
fl.close()
msg = Markup(i_d)
return render... | 6382121d88e4da08bfe2984b3d4f29f841f7c24d | 3,624,032 |
import typing
def split_line(line: str) -> typing.Tuple[str, str]:
"""
Separates the raw line string into two strings: (1) the command and (2) the
argument(s) string
:param line:
:return:
"""
index = line.find(' ')
if index == -1:
return line.lower(), ''
return line[:ind... | 964877ebe0e63161f449a1d60542fbcab451de28 | 3,624,033 |
def naep_aggregate(input_df):
"""
:param input_df:
:return:
"""
# Treat years as strings
input_df['YEAR'] = input_df['YEAR'].astype('str')
# input_df.drop_duplicates(inplace=True)
# PRIMARY_KEY, STATE, and YEAR will be the same
staging_df = pd.DataFrame()
staging_df['PRIMARY_KE... | 9666ad6b886797ffe168e26d91aa9d591d1bc7f3 | 3,624,034 |
from typing import List
def matrix_transpose(mat: List[List]) -> List[List]:
"""
>>> matrix_transpose([[1, 2], [3, 4], [5, 6]])
[[1, 3, 5], [2, 4, 6]]
"""
if len(mat) == 0:
raise ValueError("Matrix is empty")
return [[mat[j][i] for j in range(len(mat))] for i in range(len(mat[0]))] | 34cf049779408f0b74a1e29cbd1f0a18a6d5dd23 | 3,624,035 |
from typing import Optional
def generate_nhs_number_from_first_9_digits(first9digits: str) -> Optional[int]:
"""
Returns a valid NHS number, as an ``int``, given the first 9 digits.
The particular purpose is to make NHS numbers that *look* fake (rather
than truly random NHS numbers which might acciden... | e939f1f2e0641355ef0d921202647aee4d1706bb | 3,624,036 |
import requests
def passthrough_rest_object(source_url):
""" Passes through a non-CORS locked down JSON object from the origin
request. """
if request.method == 'GET':
reqUrl = request.args.get('url','')
req = requests.get(reqUrl)
if req.status_code == 200:
return req.c... | 9c99e34a4635f1aec1cb4dd1e373c3dd69ec7c04 | 3,624,037 |
def randint(low, high, shape, device=None):
"""Returns a tensor filled with random integers generated uniformly between low (inclusive) and high (exclusive).
Parameters
----------
low
Lowest integer to be drawn from the distribution.
high
One above the highest integer to be drawn fr... | 84532888904c75a6866f3a2547342207559b55e7 | 3,624,038 |
def construct_formula(label, rel_cols, label_side="l"):
"""
Constructs a generic formula string from column names and a label name.
label ~ Col1+Col2+...+ColN
:param label: Label or class which should be regressed for. (case/control, treatment/untreated etc.)
:param rel_cols: Relevant columns for t... | 622489b6ecc2345362b55b7af64f120af34870ca | 3,624,039 |
def shell_context(): # pragma: no cover
"""
Make shell context.
:return: A dictionary of objects for use in shell context.
:rtype: dict
"""
return {'DB': DB, 'IMBUser': IMBUser, 'Visit': Visit} | 3e3100fa9b6f9fb1ad551fd72cf82dfaa35bacd9 | 3,624,040 |
import requests
def start_new_session(self):
"""Starts a new session to be used to send requests and returns it."""
session = requests.Session()
session.auth = (self._api_key, '') # pylint: disable=protected-access
session.headers['User-Agent'] = config.constants.USER_AGENT
session.proxies = PROX... | 721bdf2f25fb6ace67107d1f3551cc6f4ed81535 | 3,624,041 |
import types
from typing import Optional
def EvaluateMetricsAndPlots( # pylint: disable=invalid-name
extracts: beam.pvalue.PCollection,
eval_shared_model: types.EvalSharedModel,
desired_batch_size: Optional[int] = None,
metrics_key: Text = constants.METRICS_KEY,
plots_key: Text = constants.PLOTS_... | 75b262c62d6a88dc7c8651c15a725eb282163ae1 | 3,624,042 |
from typing import List
from typing import Set
from typing import Union
from typing import Dict
def _find_first_common_next_vertex_in_edges__impl(
g: Graph, es: List[Set[Union[Edge, None]]], map_of_visited: [List[Dict[int, int]]],
allow_open_branches: bool, allow_loops: bool, vs_to_not_visit: List[int... | 4431e1563cd7a957eeecdae65f941439e11d95ce | 3,624,043 |
from sentry_sdk import capture_exception
def catch_errors(exception=None, catch_generic=True, **kwargs):
"""
A decorator to preprocess an API class method,
and catch a specific error.
"""
if exception is None:
exception = RestApiException
def decorator(func):
@wraps(func)
... | cabfdbabc8ed3a9c9551dd511310f7080ab04e00 | 3,624,044 |
def set_alpha(n_points):
"""Set an alpha value for plotting that is scaled by the number of points.
Parameters
----------
n_points : int
Number of points that will be in the plot.
Returns
-------
alpha : float
Value for alpha to use for plotting.
"""
for key, val i... | b1b992fc15491ae752d3de5358e08ec61d751216 | 3,624,045 |
import re
def identify_days(year_string, date_list):
"""
The function takes a single integer number (4 digits) and returns all
itEms of a list that have this number at the very beginning.
:year_string: a string that is equivalent to a four digit integer
:date_list: a list of dates or anything els... | b8207360433b8ad8f3f3f9c4fcdafc9206120637 | 3,624,046 |
import os
import logging
import subprocess
def run_build(command, *args, **kwargs):
""" Run and report build command execution
:param command: array of tokens
:return: exit code of the process
"""
environment = kwargs.get('env', os.environ)
logging.debug('run build %s, in environment: %s', co... | 3089128fc83ff8f6c09bc11a36dcd8e6b80b43e6 | 3,624,047 |
def split_nvr_epoch(nvre: str):
"""Split nvre to N-V-R and E.
This function is backported from `kobo.rpmlib.split_nvr_epoch`.
@param nvre: E:N-V-R or N-V-R:E string
@type nvre: str
@return: (N-V-R, E)
@rtype: (str, str)
"""
if ":" in nvre:
if nvre.count(":") != 1:
... | 6b65a5dd4655b8d0d961952be41ab6a939cc24c8 | 3,624,048 |
def findMergeNode(head1, head2):
"""
Go forward the lists every time till the end, and
then jumps to the beginning of the opposite list, and
so on. Advance each of the pointers by 1 every time,
until they meet. The number of nodes traveled from
head1 -> tail1 -> head2 -> intersection point and
... | 01c24a3eda17a8063c94c92cff6d558025c03726 | 3,624,049 |
def encode_pool_list(pool, normalize_by=None):
"""
Return a matrix X of `len(shape) * reduce(mul, shape)` columns and `pool.n`
rows, encoding the payoffs of all the games in 'pool', and a vector Y, with
`pool.n` rows, of integer "labels" representing which action was played for
each example. The la... | 4844cf6fc4d1dda21324d933f03508c6ed77373e | 3,624,050 |
def set_weights():
"""Set weights for each digit in NHS number"""
weights = [10, 9, 8, 7, 6, 5, 4, 3, 2]
return np.array(weights) | 020e94c4a84e7f2eb691ab54aa41cd4057bbf52f | 3,624,051 |
def expand_and_broadcast(s1: Shape, s2: Shape):
"""Expand two shapes to make them of equal rank and then broadcast.
Args:
s1 (:class:`lab.shape.Shape`): First shape.
s2 (:class:`lab.shape.Shape`): Second shape.
Returns:
:class:`lab.shape.Shape`: Expanded and broadcasted shape.
... | a1a780f803760571fb2dca6c400fa284cd9ed329 | 3,624,052 |
import tempfile
import os
def BuildFactoryZip(buildroot,
board,
archive_dir,
factory_shim_dir,
version=None):
"""Build factory_image.zip in archive_dir.
Args:
buildroot: Root directory where build occurs.
board: Board name of... | a18d6833a6f4e575abdb2d8df716e1cba8440d4d | 3,624,053 |
import json
import os
def get_distribution_strategy(distribution_strategy="mirrored",
tpu_address=None,
**kwargs):
"""Returns a DistributionStrategy for running the model.
Args:
distribution_strategy: a string specifying which distribution strategy ... | 987b92ba5e9e6a7547bca8cc806981e46e58c083 | 3,624,054 |
from pathlib import Path
async def augment_chat(
request_data: TextData,
user: str = Path(default="default", description="user for which the chats needs to be log"),
current_user: User = Depends(Authentication.get_current_user_and_bot)
):
"""
Fetches a bot response for a given text/que... | 6a5a52627934215716e74b7338036e766e492468 | 3,624,055 |
def py_mb_convert(file_location, file_extension):
"""
Convert files from one format to another with PyMOAB.
Input:
______
file_location: str
User supplied file location.
file_extension: str
User supplied file format to convert to, including '.'
Returns:
____... | f171a976f2aab10f10f89883d60302d9e85debb5 | 3,624,056 |
def _compress_image(buffer, compression="JPEG"):
"""
Compress array to specified format.
>>> _compress_image(np.array([[0]]), 'JPEG')
'/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofH\
h0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/wAALCAABAAEBAREA/8QAHwAAAQUBAQEB\
AQEAAAAAAAAAA... | 21b5aad16eca48e25dc47194de084ae29ec49546 | 3,624,057 |
async def edit_bot(request: Request, user_id: int, bot_id: int, bot: BotMeta):
"""
Edits a bot, the owner here must be the owner editing the bot.
Due to backward compatibility, this will return a 202 and not a 200 on success
"""
bot_dict = bot.dict()
bot_dict["bot_id"] = bot_id
bot_dict["use... | b15f7e65d3a1ed3c9b620d3e86c3980245a8c2eb | 3,624,058 |
def sigfig(x, n):
"""
Produces x values to "n" significant figures
From : https://stackoverflow.com/a/55599055
:param x: numpy array, the values to round
:param n: int, the number of significant figures required
:return:
"""
if isinstance(x, np.ndarray):
xin = np.array(x)
... | 1cbdd6c1681dfff296459355a384c3635e2cdeaa | 3,624,059 |
def calc_SingleValueDiff(comp, opt, mtype='mean', ef=True):
"""
Computes a single value difference of the actual PALC results. Called by
:any:`optimize_PALC` and :any:`diff_on_ls`.
Parameters
----------
comp : list or 1D-array
Computed PALC results in optimization region.
opt : list... | 62a01eb611c033420f844659516ae230709ab64f | 3,624,060 |
def resnet_v1(input_shape, depth, num_classes=10, activation='relu'):
"""ResNet Version 1 Model builder [a]
Stacks of 2 x (3 x 3) Conv2D-BN-ReLU
Last ReLU is after the shortcut connection.
At the beginning of each stage, the feature map size is halved (downsampled)
by a convolutional layer with str... | ee9b0587fec33e105415f6f6abefa800d8b8d4bd | 3,624,061 |
def get_gains_check(speakers, position, sx, sy, sz):
"""call get_gains, and check that the return is normalised and positive"""
g = get_gains(speakers, position, sx, sy, sz)
assert np.all(g >= 0)
npt.assert_allclose(np.linalg.norm(g), 1)
return g | 1d40f9ec23949c02b609e05adc8aa543d9457e4a | 3,624,062 |
import cv2
def test_opencv():
"""
This function is workaround to
test if correct OpenCV Library version has already been installed
on the machine or not. Returns True if previously not installed.
"""
try:
# import OpenCV Binaries
# check whether OpenCV Binaries are 3.x+
if parse_version(cv2.__version__) ... | 5744b6093492bd4c8d5eb51f747c79a276d42c31 | 3,624,063 |
import logging
def test_asana_error_handler(caplog):
"""
Tests the `@asana_error_handler` decorator.
"""
caplog.set_level(logging.ERROR)
def gen_text(text1, text2, text3):
return f'{text1} | {text2} | {text3}'
dec_gen_text = aclient.asana_error_handler(gen_text)
assert dec_gen_te... | ea62be525b4ab41e2bc19c89ae8c52e559b206c6 | 3,624,064 |
def expandvars_dict(settings: dict) -> dict:
"""Expand all environment variables in a settings dictionary.
ref: http://stackoverflow.com/a/16446566
:returns: Dictionary with settings
"""
return {key: _expandvars(value) for key, value in settings.items()} | cf5793be1318759cba9e2a1d0f8c0a0c7dfc1390 | 3,624,065 |
import functools
from typing import Dict
from typing import Any
import json
from typing import Union
def token_required(func):
"""
[x] - deprecated
"""
@functools.wraps(func)
async def wrapper(self, text_data: str, *args, **kwargs):
scope = getattr(self, "scope")
user = AnonymousU... | cf24d7ed65272205606f06b0953febe3066c931b | 3,624,066 |
import time
def execute(
method,
max_retries,
retry_interval,
use_retry=True,
*args,
**kwargs
):
"""Execute HTTP request with retry support.
Args:
method (string): HTTP verb.
use_retry (bool): If True, will use retry
configuration (default: True).
m... | 5009296882fd8ff2fdecf7cfde7a42ecedb22099 | 3,624,067 |
def stacked_sectors(df):
"""
Takes dataframe and sorts table fields by sector
Parameters
----------
**df** : 'pd.df'
Dataframe to be sorted by sector.
Returns
-------
**output** : 'pd.df'
Dataframe of the table that was imported and split by sector
"""
... | 7a8a228a523f5f315b14464730ca510e37df8bd1 | 3,624,068 |
def stringify(num):
"""long int -> 20-character string"""
str = hex(num)[2:]
if str[-1] == 'L':
str = str[:-1]
if len(str) % 2 != 0:
str = '0' + str
str = str.decode('hex')
return (20 - len(str)) *'\x00' + str | 36cf6888136e42724f2744dfb59de16e4fe494e6 | 3,624,069 |
import re
import os
def replace_esp_example_includes(line, source_path):
"""Updates any includes for local example files."""
# Because the export process moves the example source and header files out of
# their default locations into the top-level 'main' folder in the ESP-IDF
# project, we have to update any ... | 70aba9d31ecc03a2bc55641c4f6b3ad228de60f4 | 3,624,070 |
def _get_max_year(out_id_list):
"""Return the current maximum year for the specified ouptut."""
try:
indicator = database.fetch_tables(['Indicator'])[0]
ind_list = indicator[indicator['fk_indicator_output'].isin(out_id_list)]['id'].tolist()
ind_str = ', '.join([str(i) for i in ind_list])... | 08e4cc881b41734000dce035bb140e2835905bc1 | 3,624,071 |
def leaky_relu_prime(Z, alpha=0.01):
"""Applies differentiation of leaky relu function to an array/value
Arguments
---------
Z: float/int/array_like
Original Value
alpha: float
Negative slope coefficient
Returns
-------
A: same shape as input
Value after applying diff ... | aa69236ac975c66b28a8373076cbcf03e48dc720 | 3,624,072 |
def runas_exit(request):
"""
Exits impersonation mode by deleting the session variable. The middleware
will not apply to further requests.
"""
user_admin_page = None
if _SESSION_KEY in request.session:
user_admin_page = reverse('admin:auth_user_change',
args=[request.s... | 1f49e46561a0c7809a14d2745ad689c38a1c51b4 | 3,624,073 |
def get_command(command_name):
"""Return the command of the given name.
:param str command_name: The name of the command to search for.
:rtype: Command
"""
global _COMMANDS
return _COMMANDS[command_name] | a0395b1738f2d730a71e4ed6caae14635746c6c6 | 3,624,074 |
def neighbours_from_centre(k=1):
"""
Gets all neighbours from the cube point (0, 0, 0).
:param k: The distance max distance of neighbours.
:return: A set of cube coords.
"""
return neighbours((0, 0, 0), k) | a3fe11badc3ca126ee7610e1079bdcf0e90e125c | 3,624,075 |
def suitable_threshold(window, desired_probability):
"""Use cumulative binomial distribution to find the number of identical
bases which we expect a nucleotide window-mer to have with the desired
probability"""
cumulative_p = 0.0
for matches in range(window, 0, -1):
mismatches = window - mat... | 98b0cda37858e46281dabc373b90d656b59fd99f | 3,624,076 |
from typing import List
from typing import Union
from typing import Any
def plot_smoothing_length(
snap: SnapLike,
indices: List[int],
fac: float = 1.0,
units: Union[str, Quantity] = None,
x: str = 'x',
y: str = 'y',
ax: Any = None,
**kwargs
) -> Any:
"""Plot smoothing length aroun... | b088aa787c82784f874e15a1c24af8c63b6f86ea | 3,624,077 |
def asarray(arraylike, strict=True):
"""
Converts arraylike objects to NumPy ndarray types. Errors if
object is not arraylike and strict option is enabled.
"""
if isinstance(arraylike, np.ndarray):
return arraylike
elif isinstance(arraylike, list):
return np.asarray(arraylike, dt... | adee797c27087751438cf0df60f131d0794e61e2 | 3,624,078 |
import copy
def parameter_map(parameter_map, fig=None, ax=None, alpha=1,
cmap='viridis', vmin=0, vmax=None, colorbar=True):
"""
This method will create a Matplotlib plot based on imshow to display the
given parameter map in different colors. The parameter map is plotted to
the curren... | c00fe05daac65e014cbcde9005ad445b50e23f0a | 3,624,079 |
def factory(class_name: str = None, **kwargs):
"""Simple factory to create a class with attributes from kwargs"""
class FactoryGeneratedClass:
pass
rewrite = {
"__randint": lambda *args: randint(100_000_000, 999_999_999),
}
for key, value in kwargs.items():
if value in rew... | 99afd1769f7e558891cb3885c8b9d1daaee314d8 | 3,624,080 |
from typing import Tuple
def which_type(statement: StatementData, choices: Tuple[StatementKey, StatementKey]) -> str:
"""Return whichever of the choices of keys is in the statement.
Note: All policy statements must have exactly one of these keys, so this raises an error if
that isn't true.
"""
l... | 8fc5c575c5d2d3b1a0cd54a8884546d909323024 | 3,624,081 |
from typing import Type
from typing import Counter
def counter(name: str, documentation: str, labels: tuple = ()) -> Type[Counter]:
"""Builds a counter with configured namespace / subsystem."""
return Counter(
name,
documentation,
labelnames=labels,
namespace=s.PROMETHEUS_NAME... | cd15e27cf7541d00a0aa151c036357cafe7a8d1d | 3,624,082 |
import os
def give_me_files():
"""
Show all json files is settings folder.
:return: list of files.
"""
path = CURRENT_PATH + "\\settings"
files = []
for r, d, f in os.walk(path):
for file in f:
if '.json' in file:
files.append(file)
return files | 6b0888b474152b55db5cd67c5e11146224ca1449 | 3,624,083 |
import functools
import os
def cached(producer):
"""Calls to a function wrapped with this decorator are cached using ``self.cache.lookup``"""
@functools.wraps(producer)
def wrapper(self):
return self.cache.lookup(data_path=os.path.join(self.category_name, producer.__name__),
... | 5d42bdba56d19cd9040becb8eb1acfe847752d98 | 3,624,084 |
def generate_linear_model_data(n=300):
"""
Generates n samples from a linear model with a small variability.
"""
m = randint(-3,3)
b = randint(-10,10)
x = np.random.rand(n)*100
errors = np.random.normal(0, .4, n) # Gaussian samples for errors
y = m*x+b + errors
return Message({'x':x... | ccdf09df70b774e2952bba114229c192f008e56c | 3,624,085 |
def prediction_error(X, y, obj_function=huber_approx_obj):
"""
Train GBMs to predict y from X.
Use obj_function during training, and test_error_function for the test evaluation.
"""
X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, test_size=0.3)
regressor = xgb.... | 674703140e31e9b2494cc62341606ecbdef2e5e8 | 3,624,086 |
import json
def get_staking_contracts(chain):
"""Returns list of supported staking contracts for the specified chain. Pulled from hardcoded values in contracts.json.
:param chain: network to query data for
:type chain: string e.g. 'testnet'
:return: list of supported staking contracts
:rtype: lis... | 0e28386ef80f012d16183483a5a00663c479e6bf | 3,624,087 |
def listify(trace, length=-1):
"""
Takes a trace as an instance of int, slice, or list and returns a list
"""
if isinstance(trace, int) or isinstance(trace, str):
return [trace]
if isinstance(trace, slice):
if trace.stop < 0 and trace.step < 0 and length < 0:
length = abs... | 87102d9e2d974afae00feb54c8f87bf964db9f92 | 3,624,088 |
def downcast_numbers(data: pd.DataFrame):
"""Downcast numerics"""
def downcast(ser: pd.Series) -> pd.Series:
ser = pd.to_numeric(ser, downcast="signed")
ser = pd.to_numeric(ser, downcast="unsigned")
return ser
df_num = data.select_dtypes("number")
data[df_num.columns] = df_num.... | f14be85150346d9fc55a6d8595e62c817c862680 | 3,624,089 |
def create_group(module, client):
"""
Creates a group.
module : AnsibleModule object
client: authenticated ionoscloud object.
Returns:
The group instance
"""
name = module.params.get('name')
create_datacenter = module.params.get('create_datacenter')
create_snapshot = module... | 24aec70f05264e2a40b7d45a0bdf9c25cc3311d7 | 3,624,090 |
from dateutil.parser import parse
def is_datetime_string(string: str) -> bool:
"""
Check if the string is date-like.
Parameters
----------
string : str
Returns
-------
is_date: bool
"""
try:
parse(string)
return True
except ValueError:
return Fal... | ec26eab5d25c2b130efbf32304b2b79f8292a6e1 | 3,624,091 |
import os
def _determine_local_import_names(start_dir):
"""Determines all import names that should be considered "local".
This is used when running the linter to insure that import order is
properly checked.
"""
file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)]
retur... | cf28d660748c3d82f2edf048823c06cd36768cdd | 3,624,092 |
import requests
def getDatasetInfo(datasetName="MyDB"):
"""
Gets information related to a particular dataset (more info in http://www.voservices.net/skyquery).
:param datasetName: name of dataset (string).
:return: returns a dictionary containing the dataset information.
:raises: Throws an except... | 14311378a50aa6fabf1f0c54b99d14551d45ee18 | 3,624,093 |
from typing import Callable
def user_passes_test(
test_fn: Callable[["models.User"], bool],
exception: Exception = PermissionDenied(PERMISSION_REQUIRED_ERROR),
):
"""
Create a decorator for a function that checks if the user passes the given test.
Parameters
----------
test_fn : Callable[... | 1d8af1b4f99acc48bf24ecc674c21918752d173e | 3,624,094 |
def is_valid_perioddata(data):
"""Check that a dictionary of period data has enough information
(based on key names) to set up stress periods.
Perlen must be explicitly input, or 3 of start_date_time, end_date_time,
nper and/or freq must be specified. This is analogous to the input
requirements for ... | d8c8f4646757177b7504181029cd39b5aa46d124 | 3,624,095 |
import textwrap
def serve():
"""
Serve the index.html for the UI.
"""
text = textwrap.dedent(
"""
Unable to display Nectar UI - landing page (index.html) not found.
"""
)
return Response(content=text, media_type="text/plain") | 2a0fdd78b31554bbce26d8f63a88016bb159b04e | 3,624,096 |
import _warnings
def convert(coeffs_in, normalization_in=None, normalization_out=None,
csphase_in=None, csphase_out=None, lmax=None):
"""
Convert an array of spherical harmonic coefficients to a different
normalization convention.
Usage
-----
coeffs_out = convert(coeffs_in, [norma... | 27b70c3356d487424c30a7ec0bc6e301099631fa | 3,624,097 |
def doubletrace(tt):
"""Determine the double trace corresponding to tt"""
(cn,vts,edgs,gp,prt) = skeleton(tt)
v = len(vts)
e = len(edgs)//2
# print(v,e)
ts = set(tt)
oriented = len(tt) == len(ts)
chi = v - e + 1
genus = 2 - chi
if oriented:
genus = genus//2
(anti,par) ... | 029f3db88a35ecaef93a05624712e21610ef1dcc | 3,624,098 |
def get_job_definition(account, region, container_name, job_def_name, job_param_sagemakerendpoint, memoryInMB, ncpus,
role_name):
"""
This is the job definition for this sample job.
:param account:
:param region:
:param container_name:
:param job_def_name:
:param memoryInM... | 465457f1345f514d5626e44f791bbcd0588743a9 | 3,624,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.