content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def fitness_func(loci, **kwargs):
"""
Return how fit the locus is to describe a quarter of circle.
It is a minisation problem and the theorical best score is 0.
Returns
-------
float
Sum of square distances between tip locus bounding box and a defined
square.
"""
# Locu... | c0ae31416acfc62726f47db1b2dc6de52e609df7 | 3,632,990 |
def get_div(integer):
"""
Return list of divisors of integer.
:param integer: int
:return: list
"""
divisors = [num for num in range(2, int(integer**0.5)+1) if integer % num == 0]
rem_divisors = [int(integer/num) for num in divisors]
divisors += rem_divisors
divisors.append(integer)
... | 4c40a2b2da1d9681c1d7ca69a53975dd27c7bdb8 | 3,632,991 |
def ifuse(inputs):
"""Fuse iterators"""
value, extent = 0, 1
for i, ext in inputs:
value = value * ext + i
extent = extent * ext
return (value, extent) | 42c65ec62e637b668125ed27aad517d3301a7aff | 3,632,992 |
def filtered_list_gen(raw_response, term=None, partial_match=True):
"""
Iterates over items yielded by raw_response_gen, validating that:
1. the `path` dict key is a str
2. the `path` value starts with starts_with (if provided)
>>> r = [{
>>> 'checksum': {
>>> 'md5': 'd9... | 167da6e68c0450eb76ccb3697beee87de5dae4fb | 3,632,993 |
def check_job_access_permission(request, job_id):
"""
Decorator ensuring that the user has access to the job submitted to Oozie.
Arg: Oozie 'workflow', 'coordinator' or 'bundle' ID.
Return: the Oozie workflow, coordinator or bundle or raise an exception
Notice: its gets an id in input and returns the full o... | 80e8c7e610c96e275aed23f4e24ad96520da171e | 3,632,995 |
from typing import get_origin
def is_dict_type(tp):
"""Return True if tp is a Dict"""
return (
get_origin(tp) is dict
and getattr(tp, '_name', None) == 'Dict'
) | 3b9992b7b131e936472d4d0e2994ac476f0d0f76 | 3,632,996 |
def shape(pyshp_shpobj):
"""Convert a pyshp geometry object to a flopy geometry object.
Parameters
----------
pyshp_shpobj : shapefile._Shape instance
Returns
-------
shape : flopy.utils.geometry Polygon, Linestring, or Point
Notes
-----
Currently only regular Polygons, LineStrin... | 39e6152c680a4358e980095d090a0e724bc9338c | 3,632,997 |
def compute_nbr(image, sensor):
"""
Compute nbr index
NBR = (NIR-SWIR2)/(NIR+SWIR2)
"""
bands = cp.sensors[sensor]["bands"]
nir = image.select(bands["nir"])
swir2 = image.select(bands["swir2"])
doy = ee.Algorithms.Date(ee.Number(image.get("system:time_start")))
yearday = ee.Number... | 005b965e93d0f4455e01a7aae949631b94e13b16 | 3,632,998 |
def unbroadcast(array):
"""
Given an array, return a new array that is the smallest subset of the
original array that can be re-broadcasted back to the original array.
See http://stackoverflow.com/questions/40845769/un-broadcasting-numpy-arrays
for more details.
"""
if array.ndim == 0:
... | e7a205a325dc3000a920df441c5b861f66c8c3c8 | 3,632,999 |
def get_boxes_info(
boxes_thinned,
retr_mode,
approx_method=cv2.CHAIN_APPROX_SIMPLE):
"""
Retreive contours and return a list of lists, each area of the box,
and coordinates of the box.
Parameters
----------
boxes_thinned : numpy.array
Array containing photographic informati... | d3a877a2ebae771d521141048f0c05b15ac0aff5 | 3,633,000 |
def getMaxLen(fastaFilePath):
"""
Gets the length of the sequence that has maximum length in a fasta file.
"""
maxLen = 0
for val in fasta.getSequenceToBpDict(fastaFilePath).itervalues():
if maxLen < int(val):
maxLen = int(val)
return maxLen | 7b5893c5563b96f4253025f39ee8e171694ae418 | 3,633,001 |
import scipy
def align_face(filepath, output_size=1024, transform_size=4096, enable_padding=True):
"""
:param filepath: str
:return: PIL Image
"""
ensure_checkpoint_exists("models/dlibshape_predictor_68_face_landmarks.dat")
predictor = dlib.shape_predictor("models/dlibshape_predictor_68_face_... | 507c59ba35e62cff4c07a0caf7d75e654d56aca1 | 3,633,002 |
def build_model(lr_source, scaling_factor=3, hr_target=None):
"""
build espcn model
lr_source: source image batch tensor to be super resolved
hr_target: target image batch as training labels in sub-pixel convolved
shape, build a partial model for testing if hr_target is None
scali... | 8383684eb4ca69c6c8b517fe50914dde902320dd | 3,633,003 |
def sum_up_validation_dataset(dataset, batch_size, repeat=True,
number_of_repetitions=0):
"""Define how the validation dataset is suppose to behave during training.
This function is applied to the validation dataset just before the actual
training process. The characteristics... | 9bab85eba802d5198bfd39bc42bd2fae5209d356 | 3,633,004 |
def moist_lift_parcel(parcel_pressure, parcel_temperature, to_pressure, step=1):
"""
Recursively determine the temperature of a parcel lifted from one pressure to
another, assuming moist pseudoadiabatic processes.
Arguments:
parcel_pressure: The starting parcel pressure.
parcel_tem... | 5b2ae0f29258602f921395b4a3c187523509bad3 | 3,633,005 |
def has_rule(table, chain, rule_d, ipv6=False):
""" Return True if rule exists in chain False otherwise """
iptc_chain = _iptc_getchain(table, chain, ipv6)
iptc_rule = encode_iptc_rule(rule_d, ipv6)
return iptc_rule in iptc_chain.rules | 9ff524f71334e82b2bb971794427da3ec98f4df3 | 3,633,006 |
def get_pings_measurements(ip):
"""
Performs a ping measurement to an IP or returns cached result
:param ip: string ip address
:return: dictionary {src: rtt} where src is the string ip address of the measurement source, and rtt is the
minimum rtt recorded for a ping from that src to the ip addre... | 2c703be4a6e585690b90a846580ea56ea2d712a0 | 3,633,007 |
def get_timestamp(date_time):
"""Return the Unix timestamp of an ISO8601 date/datetime in seconds.
If the datetime has no offset, it is assumed to be an UTC datetime.
:param date_time: the datetime string to return as timestamp
:type date_time: str
:returns: the timestamp corresponding to the date... | daee72734b8994c11f4051a328ce49b7006451d6 | 3,633,008 |
def ssd_arg_scope(weight_decay=0.0005, data_format='NHWC'):
"""Defines the MobileNetV1 arg scope.
Args:
weight_decay: The l2 regularization coefficient.
Returns:
An arg_scope.
"""
with slim.arg_scope([slim.conv2d, slim.fully_connected],
activation_fn=tf.nn.relu,... | 8b466f120f0ac8cb385a8a26d31ab7d3c54c17c3 | 3,633,009 |
async def async_get_maker_for_service(hass, service):
"""Get coffee maker to be used for specified service."""
device_id = None
key = 'device_id'
if key in service.data:
device_id = service.data.get(key)[0]
_LOGGER.info(f'Found target: {device_id}')
device = None
if device_id is... | 19c4a9742f84796c2ebd1cebefa22e39cd57333f | 3,633,012 |
def make_deferred_related(factory, fixture, attr):
"""Make deferred function for the related factory declaration.
:param factory: Factory class.
:param fixture: Object fixture name e.g. "book".
:param attr: Declaration attribute name e.g. "publications".
:note: Deferred function name results in "b... | c27e18adf7e7cd3646fea27ef34e9ae888d38510 | 3,633,013 |
import webbrowser
def getbrowser():
"""
Get the name of the browser currently being used
"""
# Try to find the browser
try:
# Get the browser name
webbrowser.get(using=None)
# Catch an error
except RuntimeError:
# Return nothing
return None | cc74f7db8cf82b32516a0f3b462ba91b7c48b21b | 3,633,014 |
def minimize_bias_geodetic(x, gd_mb=None, mb_geodetic=None,
h=None, w=None, pf=2.5,
absolute_bias=False,
ys=np.arange(2000, 2019, 1),
oggm_default_mb = False,
**kwargs):
""" calibra... | 08313e2ed2bb04f58dba4f5c978978a3124005f2 | 3,633,015 |
def unpack_big_integer(binary_string):
"""
Convert a byte string into an integer.
Akin to a base-256 decode, big-endian.
"""
if len(binary_string) <= 8:
return unpack_big_integer_by_struct(binary_string)
# NOTE: 1.1 to 4 times as fast as unpack_big_integer_by_brute()
else:
... | 3200758ff58076c03cb21280a4af9805da438436 | 3,633,016 |
def extractLineFromTarget(**kwargs):
"""
based on the corridor and the related points, extract lines from original point clouds.
"""
img_buffer = kwargs['img_buffer']
min_xyz = kwargs['min_xyz']
cellsize = kwargs['cellsize']
pts_target = kwargs['pts_target'] # deep copy of the original data
... | 4cabf1a6de49d6014b0c31ce67aa87ff116d162a | 3,633,018 |
def contract_expanded_and_prob_pattern_nodes(
product: ProductNode
) -> ProductNode: # P(A and B) = P(A when B) * P(B)
"""Contract expanded And Probability pattern nodes ` P(Y) * P(X when Y) = P(X and Y)` in `product`
>>> contract_expanded_and_prob_pattern_nodes(1.5 * N(P(A when B)) * N(P(B)))
... | 24eed700f76d3afcf46e3c2035c1157bb7428dfd | 3,633,019 |
import requests
def get_api_data(quote, date_range):
"""request to API with error check
Error message if any of query params are invaild
Note if API call limit is reached"""
print(API_URL.format(date_range, quote))
data = requests.get(API_URL.format(date_range, quote)).json()
if "Error Messag... | a1718a7d8f558bd06da8a6d1925dc2cc00795a87 | 3,633,020 |
import numpy
def solve_TLS_Ab(A, b):
"""Solve an overdetermined TLS system by singular value decomposition.
"""
## solve by SVD
U, W, Vt = linalg.singular_value_decomposition(A, full_matrices=0)
V = numpy.transpose(Vt)
Ut = numpy.transpose(U)
## analyze singular values and generate smal... | 5a68f574f2779cf1f436c268975955805d5c35c5 | 3,633,022 |
import torch
def FixCentralTensorCalculateAuxiliaryTensor(ori_tensor_set, ori_matrix, mpo_input_shape, mpo_output_shape, ranks):
"""
In put tensor set product by matrix2MPO, and New_matrix.
return the central tensor when auxiliary tensor was fixed.
We assumes n = 5
"""
ori_matrix = torch.from... | c330725679f64532872f6477189a97753a085ca9 | 3,633,023 |
def AddEntryPoint(ordinal, ea, name, makecode):
"""
Add entry point
@param ordinal: entry point number
if entry point doesn't have an ordinal
number, 'ordinal' should be equal to 'ea'
@param ea: address of the entry point
@param name: name of the entry point. If null string,... | 3218edc3663c2f575941141b9b063b8adf9d377e | 3,633,024 |
import json
import requests
def goodsEditSkuChannel(skuId,regionId):
"""
:param skuId:
:param regionId:
:return:
"""
reqUrl = req_url('goods', "/sku/updateGroup")
if reqUrl:
url = reqUrl
else:
return "服务host匹配失败"
headers = {
'Content-Type': 'application/js... | 1fc51eb4f6ee2ee3bd0144bd3ad1e77d9962cdfc | 3,633,025 |
import math
def poly(x, y, order, rej_lo, rej_hi, niter):
"""linear least square polynomial fit with sigma-clipping"""
# x = list of x data
# y = list of y data
# order = polynomial order
# rej_lo = lower rejection threshold (units=sigma)
# rej_hi = upper rejection threshold (units=sugma)
... | 0043c58e4a579810d9f13218d6a6d0a768d1b8e4 | 3,633,026 |
def on_step_start(func):
"""A function decorator that wraps a Callable inside the NeMoCallback object and runs the function with the
on_step_start callback event.
"""
class NeMoCallbackWrapper(NeMoCallback):
def __init__(self, my_func):
self._func = my_func
def on_step_star... | 2028a8c0994927f6097fbc6f08852450e9ccb465 | 3,633,028 |
import ast
from operator import add
def reindent_docstring(node, indent_level=1, smart=True):
"""
Reindent the docstring
:param node: AST node
:type node: ```ast.AST```
:param indent_level: docstring indentation level whence: 0=no_tabs, 1=one tab; 2=two tabs
:type indent_level: ```int```
... | 2dd90c2e72e79584ae8b4fed5fff2a4a5ba01d53 | 3,633,029 |
import numpy
def xyz(x, y, z):
"""Construct a Toyplot color from CIE XYZ values, using observer = 2 deg and illuminant = D65."""
x = x / 100.0
y = y / 100.0
z = z / 100.0
r = x * 3.2406 + y * -1.5372 + z * -0.4986
g = x * -0.9689 + y * 1.8758 + z * 0.0415
b = x * 0.0557 + y * -0.2040 + z ... | 3d3189ac0d8987309d6c4839b7909d65a47f49af | 3,633,030 |
def _is_large_prime(num):
"""Inefficient primality test, but we can get away with this simple
implementation because we don't expect users to be running
print_fizzbuzz(n) for Fib(n) > 514229"""
if not num % 2 or not num % 5:
return False
test = 5
while test*test <= num:
if not nu... | 090b641872d8d25d55e8f32296e3893f59518308 | 3,633,031 |
def cleanup_code(content: str):
"""Automatically removes code blocks from the code."""
# remove ```py\n```
if content.startswith('```') and content.endswith('```'):
return '\n'.join(content.split('\n')[1:-1])
# remove `foo`
return content.strip('` \n') | a026668f01e1641618c5b25b06396516410dbe1e | 3,633,032 |
def name_generator(identifier: str= "") -> str:
"""
Generates a unique name.
:param identifier: identifier to add to the name
:return: the generated name
"""
return f"thrifty-builder-test-{identifier}{uuid4()}" | f1da6477beb1ce373b6d5e47e7f2375fe1a74661 | 3,633,033 |
import signal
def _ssim_for_multi_scale(img1,
img2,
max_val=255,
filter_size=11,
filter_sigma=1.5,
k1=0.01,
k2=0.03):
"""Calculate SSIM (structural similarity... | 5bf91fbb85a8eca8e52aeae566f23dc750037330 | 3,633,035 |
def index(request):
"""
:param request:
:return:
"""
panel = True
# auto login for test users
user = authenticate(username='admin', password='Aa1234567890')
login(request, user)
return render(request, "back/index.html", locals()) | fadd7e80eebf03c44c064754884e3dd0984450f8 | 3,633,036 |
def membersof(parser, token):
"""
Given a collection and a content type, sets the results of :meth:`collection.members.with_model <.CollectionMemberManager.with_model>` as a variable in the context.
Usage::
{% membersof <collection> with <app_label>.<model_name> as <var> %}
"""
params=token.split_contents(... | 011488e1949c1314b2f3fe73623879b9459c7585 | 3,633,037 |
def ext_s(variable, value, substitution):
"""ext_s is a helper function for eq, without checking for duplicates or
contradiction it adds a variable/value pair to the given substitution.
`unify` deals with all of the related verification.
@param variable: A LogicVariable
@param value: A value that c... | bced042fc8ea5882d4dc901e3b7df94c9b0d0893 | 3,633,038 |
def sc_fermi_sub_wrap( calc, non_native, native, stoich, non_native_limit, native_limit, im_cor, charge ):
"""
sc_fermi_sub_wrap determines the formation energy of a substitutional defect, and formats a 'ChargeState' object to be fed into sc_fermi
args: calc = DFT calculation summary of the defective materi... | 1ff6161f0b88b9f1a7765565041549f50bd7c2aa | 3,633,039 |
import re
def _include_matcher(keyword="#include", delim="<>"):
"""Match an include statement and return a (keyword, file, extra)
duple, or a touple of None values if there isn't a match."""
rex = re.compile(r'^(%s)\s*%s(.*)%s(.*)$' % (keyword, delim[0], delim[1]))
def matcher(context, line):
... | b5f57a8f007870952810a591bb8e15c86af467b1 | 3,633,040 |
import logging
def cod_converter(cod_decimal_string):
""" From a decimal value of CoD, map and retrieve the corresponding major class of a Bluetooth device
:param cod_decimal_string: numeric string corresponding to the class of device
:return: list of class(es)
"""
if not cod_decimal_string or c... | b566c70fcdfe8bd8801ce12e2358b1dcb9eb9f4d | 3,633,041 |
def get_params(ntrain, EXP_NAME, order, Nside, architecture="FCN", verbose=True):
"""Parameters for the cgcnn and cnn2d defined in deepsphere/models.py"""
n_classes = 2
params = dict()
params['dir_name'] = EXP_NAME
# Types of layers.
params['conv'] = 'chebyshev5' # Graph convolution: chebysh... | fb46d04050f88ce16f75a414dce62c1b08a0d3c9 | 3,633,042 |
import operator
def lcs(l1, l2, eq=operator.eq):
"""Finds the longest common subsequence of l1 and l2.
Returns a list of common parts and a list of differences.
>>> lcs([1, 2, 3], [2])
([2], [1, 3])
>>> lcs([1, 2, 3, 3, 4], [2, 3, 4, 5])
([2, 3, 4], [1, 3, 5])
>>> lcs('banana', 'baraban')... | 4b5d3cb9911a6834c006e78f7b40061695c464e2 | 3,633,044 |
from mpunet.preprocessing import get_preprocessing_func
def get_data_sequences(project_dir, hparams, logger, args):
"""
Loads training and validation data as specified in the hyperparameter file.
Returns a batch sequencer object for each dataset, not the ImagePairLoader
dataset itself. The preprocess... | 57230e155c1f9817ad6974198e10c0ff04a7891f | 3,633,045 |
def tick_payload():
""" Payload for tick """
data = TickEvent(tick_type=TickType.FULL).json()
return {
"context": {
"eventId": "some-eventId",
"timestamp": "some-timestamp",
"eventType": "some-eventType",
"resource": "some-resource",
},
... | 266490cd502619ad27ee248171c1fd812baa4d6a | 3,633,047 |
def calc_sparsity(optimizer, total_params, total_quant_params):
"""
Returns the sparsity of the overall network and the sparsity of quantized layers only.
Parameters:
-----------
optimizer:
An optimizer containing quantized model layers in param_groups[1]['params'] and non-quantized... | 92ee924239ee8d7ac97aebba2958671043aa2d89 | 3,633,048 |
def get_pck_normalized_joint_distances(gt_array: np.ndarray, pred_array: np.ndarray, visible_array: np.array, threshold, ref_distances):
"""
n = number of records
:param gt_array: (n, num_joints, 2)
:param pred_array: (n, num_joints, 2)
:param visible_array: (n, num_joints) # 0 if invisible, 1 if vi... | 8e42b418cdda3e89007ee44ccd8c91b859b8ea69 | 3,633,049 |
def swapKeys(d,keySwapDict):
"""
Swap keys in dictionary according to keySwap dictionary
"""
dNew = {}
for key, keyNew in keySwapDict.iteritems():
if key in d:
dNew[keyNew] = d[key]
for key in d:
if key not in keySwapDict:
dNew[key] = d[key]
return dN... | 0d8917e224574ee0bf682fed10d367f3a5d2bc2f | 3,633,051 |
def render_pyramid(pyr, levels):
"""
Renders a big image of horizontally stacked pyramid levels
:param pyr: Gaussian or Laplacian pyramid
:param levels: number of levels to present in the result <= max_levels
:return: single black image with pyramid levels stacked horizontally
"""
pyr[0] = (... | 46bd9fbcf8f973bb23a681f478087a848e93d559 | 3,633,052 |
def test_scatter_plot():
"""
Test plot of predicted electric conductivity as a
function of the mole fractions.
Input
-----
x_vals : numpy vector x-axis (mole fractions)
y_vals : numpy vector y-axis (predicted conductivities)
x_variable : string for labeling the x-axis
Returns
-... | 5e3ac6de37eb13574e85403921aea368b2224f71 | 3,633,053 |
def networkx2pandas(current_graph, input_type):
"""Converting current graph into a pandas data frame
:param: current_graph: a python dict containing all paths
:param: input_type: the semantic type of the input
"""
data = []
for paths in current_graph.values():
for path in paths:
... | 8f6a1166c8bd5818ff0d3b433f5fa84e1e064dc1 | 3,633,054 |
from typing import Union
from typing import Sequence
def assemble_matrix(form: _fem.FormMetaClass,
constraint: Union[MultiPointConstraint,
Sequence[MultiPointConstraint]],
bcs: Sequence[_fem.DirichletBCMetaClass] = [],
d... | e7d0bc5f779cc97889e52860f13b4e5e9b84b022 | 3,633,055 |
import torch
def getLayers(model):
"""
get each layer's name and its module
:param model:
:return: each layer's name and its module
"""
layers = {}
root = ''
def unfoldLayer(model, root):
"""
unfold each layer
:param model: the given model or a single layer
... | e1120460b35fa49fe8ad43cc9ce606c1d217a584 | 3,633,056 |
def redeploy():
"""
Implements redeploy handle
Runs docker-compose pull and up commands for specified service
Service must be preconfigured with yml file in SERVICES_DIR
Docker URL can be configured with DOCKER_URL option
"""
service = request.args.get("service", type=str)
if not service... | e7e898c59f9719f6c0d136ffd1ada480f3e0f9e8 | 3,633,057 |
import unittest
def unittests():
"""
Short tests.
Runs on CircleCI on every commit. Returns everything in the tests root directory.
"""
test_loader = unittest.TestLoader()
test_suite = test_loader.discover('tests')
test_suite = _circleci_parallelism(test_suite)
return test_suite | 153d716b4731bd3290d7af9ce5ff5d77f5b5309e | 3,633,058 |
import requests
import json
def get_weekly_forecasts(country_code, zip_code): #for the web app examining trends
"""
Fetches the weekly data from the Weather.gov API, for a given country and zip code.
Params:
country_code (str) the requested country, like "US"
zip_code (str) the requested ... | aa224eb54194f5115b221c66510a5b52e3b68bf8 | 3,633,059 |
import re
def parse_nml(string, ignore_comments=False):
""" parse a string namelist, and returns a list of param bundles
with four attrs: name, value, help, group
"""
group_re = re.compile(r'&([^&]+)/', re.DOTALL) # allow blocks to span multiple lines
array_re = re.compile(r'(\w+)\((\d+)\)')
... | 6463e9b5b3fb7824b496fd4426a5728a797d0c92 | 3,633,060 |
def glo2loc_2D(c,s):
"""
Build rotation matrix from global to local 2D coordinate system.
-------
Inputs:
c: cosine in radian of the angle from global to local coordinate system
s: sine in radian of the angle from global to local coordinate system
-------
Output:
R_m: rotation matrix... | 6e3a7d1e05b438a93099390c580ae49b7e5ae006 | 3,633,061 |
def model_scatter_2d(c=1500, dc=150, freq=25, dx=5, dt=0.0001, nx=[50, 50],
propagator=None, prop_kwargs=None):
"""Create a point scatterer model, and the expected waveform at point,
and the forward propagated wave.
"""
nx = np.array(nx)
model = np.ones(nx, dtype=np.float32) ... | c2f7ec47dd4da5094a673edc4236ae39d1c772dc | 3,633,062 |
def contours_and_bounding_boxes(bw_image, rgb_image):
"""Extract contours and bounding_boxes.
Parameters
----------
bw_image: np.uint8
Input thresholded image
rgb_image: np.uint8
Input rgb image
Returns
-------
image_label_overlay: label
"""
cleare... | 8e46f837d1fc6bf1c6413f32a9339b9028052694 | 3,633,063 |
def Compute_RHS_and_LHS(functional, testfunc, dofs, do_simplifications = False):
""" This computes the LHS matrix and the RHS vector
Keyword arguments:
functional -- The functional to derivate
testfunc -- The test functions
dofs -- The dofs vectors
do_simplifications -- If apply simplifications... | a8deb075186dbf2f05c87eeeb1adf48e30eba19d | 3,633,064 |
def buscaVizinhos(matrizCapacidades):
"""Função para buscar os vizihos de cada vertice"""
vizinhos = {}
for v in range(len(matrizCapacidades)):
vizinhos[v] = []
for v, fluxos in enumerate(matrizCapacidades):
for vizinho, fluxo in enumerate(fluxos):
if fluxo > 0:
... | 1e9ace4be94d80ae2637689b3d25ee1116714888 | 3,633,066 |
import logging
def get_server_numeric_version(ami_env, is_local_run=False):
"""
Gets the current server version
Arguments:
ami_env: (str)
AMI version name.
is_local_run: (bool)
when running locally, assume latest version.
Returns:
(str) Server numeric v... | 1ee8b0eb40b5db28b38bbe9e1a2080b47534b99a | 3,633,067 |
def get_all_images():
"""
:return: all data from db, except db id's
"""
return list(cursor.find({}, {'_id': False})) | 27764e962d11f71d6f536a70f22013a032158aa3 | 3,633,068 |
import typing
def historical_market_capitalization(
apikey: str, symbol: str, limit: int = DEFAULT_LIMIT
) -> typing.List[typing.Dict]:
"""
Query FMP /historical-market-capitalization/ API.
:param apikey: Your API key.
:param symbol: Company ticker.
:param limit: Number of rows to return.
... | 79a2adb718b6c60e4bf3a159476c7462dc8c39eb | 3,633,069 |
def get_search_url(query=None, start=None, end=None, page=None):
# type: (str, int, int, int) -> str
"""Constructs a search URL based on the given parameters"""
query = "+" if query is None else query
start = "+" if start is None else start
end = "+" if end is None else end
page = 1 if page is N... | 6a58f61ca3f30ef27db46bf346597fb8ca4f9a19 | 3,633,070 |
from pathlib import Path
import hashlib
def hash_file(path: PathType, algo: str, enc: str = "utf-8", bsize: int = 65536) -> str:
"""
Hash the name and contents of a file.
Parameters
----------
path : PathType
file to hash.
algo : str
hash algorithm name supported by haslib Pyt... | fc9208fa762e50c5049afd2f5c37eaf351356c0c | 3,633,071 |
import numpy
def _guess_z_grid_shape(x, y):
"""Guess the shape of a grid from (x, y) coordinates.
The grid might contain more elements than x and y,
as the last line might be partly filled.
:param numpy.ndarray x:
:paran numpy.ndarray y:
:returns: (order, (height, width)) of the regular grid... | ce84b67ead9083f297de62fb3030569353143512 | 3,633,073 |
def get_hosts_with_state(state):
"""Helper function to check the maintenance status and return all hosts
listed as being in a current state
:param state: State we are interested in ('down_machines' or 'draining_machines')
:returns: A list of hostnames in the specified state or an empty list if no machi... | 075464cc7c8a0e6f66be5f655669167bab52ea1a | 3,633,074 |
def load_category_index(label_map_path, num_classes):
"""
load the category index from the lablemap with the given path
for example, a cateory index is like the following
CATEGORORY_INDEX = {
1 : {'id':1, 'name':'Green'},
2 : {'id':2, 'name':'Red'},
3 : {'id':3, 'name':'Yellow'}
... | 1eba86fa8c6d28d265daa1c752e09e8114ad9368 | 3,633,075 |
def format_hostname(domain_parts, uid):
"""Formats hostname for a docker based on domain parts and uid.
NOTE: Hostnames are also used as docker names!
domain_parts - a single or a list of consecutive domain parts that constitute a unique name
within environment e.g.: ['worker1', 'prov1'], ['ccm1', 'prov... | e7ad7ef470c23f132ed564caa0c157cc7ffc04b8 | 3,633,077 |
def get_aspect_ratio(width_first=True):
"""
Returns the aspect ratio of the game window, or the window's width / the window's height.
If width_first is True (default), then it will return the window's height / the window's width.
:param width_first: Bool - Whether to divide the height by the width.
... | 3c87d3520aa26692835ce46ccab2ed5915bed444 | 3,633,078 |
def _environ_cols_wrapper(): # pragma: no cover
"""
Return a function which returns console width.
Supported: linux, osx, windows, cygwin.
"""
warn("Use `_screen_shape_wrapper()(file)[0]` instead of"
" `_environ_cols_wrapper()(file)`", DeprecationWarning, stacklevel=2)
shape = _screen_... | e35669b63fd755b7ce44446f0327f9c01f2dcf71 | 3,633,080 |
from typing import Optional
def encode(content, encoding: Optional[str] = "json") -> Response:
"""Encode content in given encoding.
Warning: Not all encodings supports all types of content.
:param content: Content to encode
:param encoding:
- `json` (default)
- `bin`: nD array/scalar... | fb903e3d5465328f471c3ef368023647da4e24ed | 3,633,081 |
def yesNoDialog(parent, msg, title):
"""
Convenience function to display a Yes/No dialog
Returns:
bool: return True if yes button press. No otherwise
"""
m = QMessageBox(parent)
m.setText(msg)
m.setIcon(QMessageBox.Question)
yesButton = m.addButton(_(Text.txt0082), QMessageBox.... | cc6165e017193fe85d64765fdeecbf2d056767ba | 3,633,082 |
def import_all_references(except_namespaces = []):
""" 导入所有reference文件
"""
done = False
while (done == False or (len(pm.listReferences()) != 0)):
refs = pm.listReferences()
#get rel refs
pro = []
if except_namespaces:
for ref in refs:
if ref.n... | 145cc3b6260651728f5b16661fd1f9d68d70c91a | 3,633,083 |
from labels import get_annotation
def get_annotations(element):
"""
returns a dictionary of all the annotation features of an element,
e.g. tiger.pos = ART or coref.type = anaphoric.
"""
annotations = {}
for label in element.getchildren():
if get_xsi_type(label) == 'saltCore:SAnnotatio... | 7189e3f7b3d671af40b689c2586d373d344ca10c | 3,633,084 |
def _prefAdj(coupling, leg):
"""Prefactor for the creation of an adjoint
Only implemented for regular three-legged tensors with an (in, in, out)
flow and their adjoints at the moment.
"""
if len(coupling) != 1:
raise NotImplementedError("Only for three-legged tensors")
flow = tuple(c[1... | e2889badba0cef27c4ce8c51ed14bda71524c3ec | 3,633,085 |
def recon_traj_with_preds(dataset, preds, seq_id=0, **kwargs):
"""
Reconstruct trajectory with predicted global velocities.
"""
ts = dataset.ts[seq_id]
ind = np.array([i[1] for i in dataset.index_map if i[0] == seq_id], dtype=int)
dts = np.mean(ts[ind[1:]] - ts[ind[:-1]])
# pos = np.zeros([p... | aa3150fef73450ca83617292dd9e3abf7cfd2054 | 3,633,086 |
def fitfunPowerLaw(fitparamStart, fixedparam, fitInfo, x, y):
"""
Power law fit function
y = A * B^x + C
========== ===============================================================
Input Meaning
---------- ---------------------------------------------------------------
fitparamStart ... | 8e1d234ef8f123ca3d11e8b0896865c63e15407c | 3,633,087 |
def make_2d_histogram(x, y, n_bins, xlabel, ylabel, cbar_label,
figsize=(12, 4)):
"""
Generate a rainbow-colored 2D histogram.
:param x: X-axis values, i.e. barcode group indices
:param y: Y-axis values corresponding to x
:param n_bins: (x,y) bin sizes; x should usually be 1
... | ed839db7428d743463ea37a22b0b7a16dc58aef1 | 3,633,088 |
def ingest_cop(years, month):
"""
Args:
years: list
month: str
Returns: list
"""
cop_data = []
for year in years:
directory = 'data\\raw\\copernicus\\'
wrf_file_name = year + month + '-C3S-L4_OZONE-O3_PRODUCTS-MSR-ASSIM-ALG-MONTHLY-v0021.nc'
nc = netcd... | bbe6496e5240d1d3749707a4ab79e803ca156267 | 3,633,089 |
from scipy.io.wavfile import read as readwav
def readwav(filename):
"""Read a WAV file and returns the data and sample rate
::
from spectrum.io import readwav
readwav()
"""
samplerate, signal = readwav(filename)
return signal, samplerate | 580b50d7d3585a300da1967d4481b5e9b0b9bf24 | 3,633,091 |
def get_connections_from_file(parent, filename):
"""load connections from connection file"""
error = 0
try:
doc = etree.parse(filename).getroot()
if doc.tag != 'qgsCSWConnections':
error = 1
msg = parent.tr('Invalid CSW connections XML.')
except etree.ParseError ... | 64fad1ae1f5ab295d8f09aa64f69f487407f62d2 | 3,633,092 |
from typing import List
def extract_provenance_chain(credential: Credential) -> List[Credential]:
"""
Extract the chain into an ordered list of credentials.
Root credential will be at the start of the returned list
"""
def decode(credential: Credential, acc: List[Credential]):
if credenti... | 00ed19cd953ba2fd6a3eaf591fde6c6b0113b64b | 3,633,093 |
def make_induces(x, y):
"""return [ [(0,0), (0,1),...,(0,y-1)], [(1,0),...], [(x-1, 0), (x-1, 1), ..., (x-1, y-1)]
"""
index_x = tf.expand_dims(tf.range(0, x), 1)
index_y = tf.expand_dims(tf.range(0, y), 0)
index_x = tf.tile(index_x, [1, y])
index_y = tf.tile(index_y, [x, 1])
induces = tf.stack([index_x, ... | 64780900a4c854881ec0dbd0a058b1dfa523bdd3 | 3,633,094 |
def unused_argument(editor, item):
""" Pylint unused-argument method """
line_no = item.line_no
error_text = editor.lines[line_no]
LOGGER.info("unused argument: {0}".format(error_text))
return (line_no, 0) | fd4dc3cae169b34c3e2c16321f746cbe4b83054c | 3,633,095 |
def fitjordan(f, B, losses, Bo, fo):
"""fit coeffs of
losses(f,B)=(ch*(f/fo)**alpha + ch*(f/fo)**beta)*(B/Bo)**gamma
returns (ch, alpha, cw, beta, gamma)
"""
pfe = np.asarray(losses).T
z = []
for i, fx in enumerate(f):
if fx:
if isinstance(B[0], float):
z ... | c236a0f3a7dd956cfee468b56d27a99fd90bb90c | 3,633,096 |
import itertools
def count_temporal_motif(G, sequence, delta, get_count_dict=False):
"""Count all temporal motifs.
Parameters
----------
G : the graph to count temporal motif from. This function only supports ImpulseDiGraph
sequence: a sequence of edges specifying the order of the motif. For exa... | 88851133592fc002a3cde8e7712388361e3c8f51 | 3,633,097 |
from datetime import datetime
def calc_expiry_time(minutes_valid):
"""Return specific time an auth_hash will expire."""
return (
timezone.now() + datetime.timedelta(minutes=minutes_valid + 1)
).replace(second=0, microsecond=0) | 2915ca419d234808d960d9982e234aab16a10784 | 3,633,098 |
import re
def parse(s):
"""
Parse an XML tree from the given string, removing all
of the included namespace strings.
"""
ns = re.compile(r'^{.*?}')
et = etree.fromstring(s)
for elem in et.iter():
elem.tag = ns.sub('', elem.tag)
return et | 1d026ef8978c4d774543bc1149c218bbfcf97fe8 | 3,633,099 |
def findRef(pattern, haystack):
"""Return a reference to the matching subexpression within the original structure (for in-place modifications) or None if there is no match."""
x = searchFirst(pattern, haystack)
if x is None:
return None
else:
return get(haystack, x[0]) | a0d42658fd2d0b04b6b80f873697ee5c75dc44f3 | 3,633,100 |
def parse_record(filename):
"""
This function parses house related data into a dictionary
"""
# Initialize content
content = {}
# Parse all lines
with open(filename) as f:
# Read all lines at once
all_lines = f.readlines()
# Skip the first three lines ... | 994352f78bf333c6986927e5f0da37186deb663f | 3,633,101 |
import socket
import logging
def get_hostname():
"""
:return: safely return the hostname
"""
hostname = "<Host Undetermined>"
try:
hostname = socket.gethostname()
except Exception as e:
logging.error(f"Could not get hostname.\nException: {e}")
return hostname | d5420b275c336b1295b16216a473557a24d54a61 | 3,633,102 |
def dict_get(d, key, default=None):
""":yaql:get
Returns value of a dictionary by given key or default if there is
no such key.
:signature: dict.get(key, default => null)
:receiverArg dict: input dictionary
:argType dict: dictionary
:arg key: key
:argType key: keyword
:arg default:... | 5fb6a71e507f62eb530215385c97c56a75765df7 | 3,633,103 |
def expect_keys_middleware(f):
"""
Returns a 400 error to the client if the route function tries to get a key from an object and cause a KeyError
:param f: function
:return: function
"""
def handle(*args, **kwargs):
try:
result = f(*args, **kwargs)
except KeyError:
... | 01f0c00158147ec43a4d6f67c1adf776ce05f6aa | 3,633,104 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.