content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import pathlib
from datetime import datetime
import traceback
def parse_amwg_obs(file):
"""Atmospheric observational data stored in"""
file = pathlib.Path(file)
info = {}
try:
stem = file.stem
split = stem.split('_')
source = split[0]
temporal = split[-2]
if le... | 60e00a6d2c9ac426d20e1d02f6baab05e0619988 | 3,642,700 |
def taylor(x,f,i,n):
"""taylor(x,f,i,n):
This function approximates the function f over the domain x,
using a taylor expansion centered at x[i]
with n+1 terms (starts counting from 0).
Args:
x: The domain of the function
f: The function that will be expanded/approximated
i: ... | c6d5ed8b583dba8959554bb761e7a961c84624e8 | 3,642,701 |
def precision_and_recall_at_k(ground_truth, prediction, k=-1):
"""
:param ground_truth:
:param prediction:
:param k: how far down the ranked list we look, set to -1 (default) for all of the predictions
:return:
"""
if k == -1:
k = len(prediction)
prediction = prediction[0:k]
... | cf8543279c6d7874f99c5badeb3064b621fa36a4 | 3,642,702 |
def bubble_sort(array: list, key_func=lambda x: x) -> list:
"""
best:O(N) avg:O(N^2) worst:O(N^2)
"""
if key_func is not None:
assert isfunction(key_func)
for pos in range(0, len(array)):
for idx in range(0, len(array) - pos - 1):
if key_func(array[idx]) > key_func(a... | 40e0baa0f9a36e73b2020db8c07c332dc973b919 | 3,642,703 |
from qiskit.aqua.operators import MatrixOperator
from qiskit.aqua.operators.legacy.op_converter import to_weighted_pauli_operator
import scipy
def limit_paulis(mat, n=5, sparsity=None):
"""
Limits the number of Pauli basis matrices of a hermitian matrix to the n
highest magnitude ones.
Args:
... | cd0b88316eb9cebda2a58ce30384f22fed17cb54 | 3,642,704 |
def list_clusters(configuration: Configuration = None,
secrets: Secrets = None) -> AWSResponse:
"""
List EKS clusters available to the authenticated account.
"""
client = aws_client("eks", configuration, secrets)
logger.debug("Listing EKS clusters")
return client.list_clusters(... | 289ef257e65cc68400a0562d647d4b694b4ec3bf | 3,642,705 |
def tar_cat(tar, path):
"""
Reads file and returns content as bytes
"""
mem = tar.getmember(path)
with tar.extractfile(mem) as f:
return f.read() | f07f00156c34bd60eea7fcae5d923ea9f1650f6f | 3,642,706 |
def __get_base_name(input_path):
""" /foo/bar/test/folder/image_label.ext --> test/folder/image_label.ext """
return '/'.join(input_path.split('/')[-3:]) | 5df2ef909f4b570cf6b6224031ad705d16ffff42 | 3,642,707 |
def or_ipf28(xpath):
"""change xpath to match ipf <2.8 or >2.9 (for noise range)"""
xpath28 = xpath.replace('noiseRange', 'noise').replace('noiseAzimuth', 'noise')
if xpath28 != xpath:
xpath += " | %s" % xpath28
return xpath | 7bf508c48d5a6fc09edba340e2bfc9ec13513fc8 | 3,642,708 |
def make_form(x, current_dict, publication_dict):
"""Create or update a Taxon of rank Form.
Some forms have no known names between species and form.
These keep the form name in the ``infra_name`` field.
e.g.
Caulerpa brachypus forma parvifolia
Others have a known subspecies/variety/subv... | 43ce623d67db4142f804b0c01f8e6690831387cd | 3,642,709 |
def render_view(func):
"""
Render this view endpoint's specified template with the provided context, with additional context parameters
as specified by context_config().
@app.route('/', methods=['GET'])
@render_view
def view_function():
return 'template_name.html', {'con... | 07e2f4394af5c774d3aad421cacd8f89448525b6 | 3,642,710 |
def extract_and_resize_frames(path, resize_to=None):
"""
Iterate the GIF, extracting each frame and resizing them
Returns:
An array of all frames
"""
mode = analyseImage(path)["mode"]
im = PImage.open(path)
if not resize_to:
resize_to = (im.size[0] // 2, im.size[1] // 2)
... | 27632e7485f98697b4bfe1fbb6aeaee18a29b5db | 3,642,711 |
def voter_star_off_save_doc_view(request):
"""
Show documentation about voterStarOffSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_star_off_save_doc.voter_star_off_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
... | 2f00fc92c43e7ebb6541f0e9e5bd773d3e3168a2 | 3,642,712 |
import torch
def generate_offsets(size_map, flow_map=None, kernel_shape=(3, 3, 3), dilation=(1, 1, 1)):
"""
Generates offsets for deformable convolutions from scalar maps.
Maps should be of shape NxCxDxHxW, i.e. one set of parameters for every
pixel. ``size_map`` and ``orientation_map`` expect a single channe... | f86bd6a87b887900820eb28e1a1e9f0c796e6195 | 3,642,713 |
import colorsys
def lighten_color(color, amount=0.5):
""" Lightens the given color by multiplying (1-luminosity) by the given amount.
Input can be matplotlib color string, hex string, or RGB tuple.
Examples:
>> lighten_color("g", 0.3)
>> lighten_color("#F034A3", 0.6)
>> lighten_co... | 4ef801fff6cb145a687a62dd18725258f1534abd | 3,642,714 |
def unf_gas_density_kgm3(t_K, p_MPaa, gamma_gas, z):
"""
Equation for gas density
:param t_K: temperature
:param p_MPaa: pressure
:param gamma_gas: specific gas density by air
:param z: z-factor
:return: gas density
"""
m = gamma_gas * 0.029
p_Pa = 10 ** 6 * p_MPaa
rho_gas =... | 6e41802367bbe70ab505ae5db89ee3e9a32e7d7c | 3,642,715 |
def poll():
"""Get Modbus agent data.
Performance data from Modbus enabled targets.
Args:
None
Returns:
agentdata: AgentPolledData object for all data gathered by the agent
"""
# Initialize key variables.
config = Config()
_pi = config.polling_interval()
# Initia... | b922b59c659e40ddc2b341a4605465d53e8cdaa8 | 3,642,716 |
import time
def dot_product_timer(x_shape=(5000, 5000),
y_shape=(5000, 5000),
mean=0,
std=10,
seed=8053):
"""
A timer for the formula array1.dot(array2).
Inputs:
x_shape: Tuple of 2 Int
Shape of array1;
... | 91d03070ea6efbe8d29e7bb5323aad0f20cead90 | 3,642,717 |
import os
def availible_files(path:str, contains:str='') -> list:
"""Returns the availible files in directory
Args:
path(str): Path to directory
contains(str, optional): (Default value = '')
Returns:
Raises:
"""
return [f for f in os.listdir(path) if contains in f] | c43db03d06d849c017382daee9715c8dde91b61d | 3,642,718 |
import os
def init_pretraining_params(exe,
pretraining_params_path,
main_program):
"""init pretraining params"""
assert os.path.exists(pretraining_params_path
), "[%s] cann't be found." % pretraining_params_path
def existed... | d15b3fbf2933e5f286d785c6debe309b0e1fa6c2 | 3,642,719 |
def npareatotal(values, areaclass):
"""
numpy area total procedure
:param values:
:param areaclass:
:return:
"""
return np.take(np.bincount(areaclass,weights=values),areaclass) | b5e79c7648569b84a9fad77dd9ee555392a676ab | 3,642,720 |
from AeroelasticSE.FusedFAST import openFAST
def create_aerocode_wrapper(aerocode_params, output_params, options):
""" create wind code wrapper"""
solver = 'FAST'
# solver = 'HAWC2'
if solver=='FAST':
## TODO, changed when we have a real turbine
# aero code stuff: for constructors
... | 1a530607555ce2714348184806405e68185f4012 | 3,642,721 |
import scipy
def lqr_ofb_cost(K, R, Q, X, ss_o):
# type: (np.array, np.array, np.array, np.array, control.ss) -> np.array
"""
Cost for LQR output feedback optimization.
@K gain matrix
@Q process noise covariance matrix
@X initial state covariance matrix
@ss_o open loop state space system
... | b0a22685c640c2970dad63628d1c87aac73b241a | 3,642,722 |
def steadystate_floquet(H_0, c_ops, Op_t, w_d=1.0, n_it=3, sparse=False):
"""
Calculates the effective steady state for a driven
system with a time-dependent cosinusoidal term:
.. math::
\\mathcal{\\hat{H}}(t) = \\hat{H}_0 +
\\mathcal{\\hat{O}} \\cos(\\omega_d t)
Parameters
... | 8e59e8f138116877678d7d203d4767c6fc6bd1fa | 3,642,723 |
def gsl_blas_dtrmm(*args, **kwargs):
"""
gsl_blas_dtrmm(CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag, double alpha,
gsl_matrix A, gsl_matrix B) -> int
"""
return _gslwrap.gsl_blas_dtrmm(*args, **kwargs) | 5efee7571f49afc20c3f33d010caccb199613315 | 3,642,724 |
def scale(value, upper, lower, min_, max_):
"""Scales value between upper and lower values, depending on the given
minimun and maximum value.
"""
numerator = ((lower - upper) * float((value - min_)))
denominator = float((max_ - min_))
return numerator / denominator + upper | 3e13c80b765cffb1e75a6856d343bd9a88c353e9 | 3,642,725 |
def conditional_response(view, video=None, **kwargs):
"""
Redirect to login page if user is anonymous and video is private.
Raise a permission denied error if user is logged in but doesn't have permission.
Otherwise, return standard template response.
Args:
view(TemplateView): a video-speci... | ea8e8176a979fcd46c0c72d5201c6f85c7b4ed48 | 3,642,726 |
def Flatten(nmap_list):
"""Flattens every `.NestedMap` in nmap_list and concatenate them."""
ret = []
for x in nmap_list:
ret += x.Flatten()
return ret | c630869b725d69338830e1a14ef920d6d1e87ade | 3,642,727 |
from re import T
def get_data_schema() -> T.StructType:
"""
Return the kafka data schema
"""
return T.StructType(
[T.StructField('key', T.StringType()),
T.StructField('message', T.StringType())]
) | 0cbc2fc6e7015c458e70b8d0ec6efb5fbc0d84f5 | 3,642,728 |
from typing import List
import random
def build_graph(num: int = 0) -> (int, List[int]):
"""Build a graph of num nodes."""
if num < 3:
raise app.UsageError('Must request graph of at least 3 nodes.')
weight = 5.0
nodes = [(0, 1, 1.0), (1, 2, 2.0), (0, 2, 3.0)]
for i in range(num-3):
... | 05efb60ae5cdcc561c93cf2faba172ca5a3ff0d7 | 3,642,729 |
from typing import List
from typing import Collection
def concatenate(boxes_list:List[Boxes], fields:Collection[str]=None) -> Boxes:
"""Merge multiple boxes to a single instance
B = A[:10]
C = A[10:]
D = concatenate([A, B])
D should be equal to A
"""
if not boxes_list:
if fields is... | 096067aea3d01e984befd2cadfce5a86c33580e9 | 3,642,730 |
def detect_peaks(array, freq=0, cthr=0.2, unprocessed_array=False, fs=44100):
"""
Function detects the peaks in array, based from the mirpeaks algorithm.
:param array: Array in which to detect peaks
:param freq: Scale representing the x axis (sample length as array)
:p... | c11a09624085d505d36a9e374954dd6ba5c1e05a | 3,642,731 |
def left_index_iter(shape):
"""Iterator for the left boundary indices of a structured grid."""
return range(0, shape[0] * shape[1], shape[1]) | c7da6f5de48d0446cb0729593d3dc0eb95f5ab9a | 3,642,732 |
import logging
def calculate_precision_recall(df_merged):
"""Calculates precision and recall arrays going through df_merged row-wise."""
all_positives = get_all_positives(df_merged)
# Populates each row with 1 if this row is a true positive
# (at its score level).
df_merged["is_tp"] = np.where(
... | 80d2c82c99e0bbbab8460ff997fc1358f758f2f6 | 3,642,733 |
def combine(shards, judo_file):
"""combine
this class is passed the
"""
# Recombine the shards to create the kek
combined_shares = Shamir.combine(shards)
combined_shares_string = "{}".format(combined_shares)
# decrypt the dek uysing the recombined kek
decrypted_dek = decrypt(
j... | 3ba88307c3d0cb0a43473e89b731c61e9bbfe83d | 3,642,734 |
def shiftRightUnsigned(e, numBits):
"""
:rtype: Column
>>> from pysparkling import Context
>>> from pysparkling.sql.session import SparkSession
>>> from pysparkling.sql.functions import shiftLeft, shiftRight, shiftRightUnsigned
>>> spark = SparkSession(Context())
>>> df = spark.range(-5, 4)... | 4f528609bb72a44a99581bca997fbde2f19af861 | 3,642,735 |
def change_wallpaper_job(profile, force=False):
"""Centralized wallpaper method that calls setter algorithm based on input prof settings.
When force, skip the profile name check
"""
with G_WALLPAPER_CHANGE_LOCK:
if profile.spanmode.startswith("single") and profile.ppimode is False:
t... | b4013e847cae337f83af5f3282d5551a52b4a7b3 | 3,642,736 |
import sys
from typing import ForwardRef
from typing import _eval_type
from typing import _strip_annotations
import types
from typing import _get_defaults
from typing import Optional
def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
"""Return type hints for an object.
This is often ... | a847d42f25355c3109f650206c1673674f1201b5 | 3,642,737 |
def sheets_from_excel(xlspath):
"""
Reads in an xls(x) file,
returns an array of arrays, like:
Xijk, i = sheet, j = row, k = column
(but it's not a np ndarray, just nested arrays)
"""
wb = xlrd.open_workbook(xlspath)
n_sheets = wb.nsheets
sheet_data = []
for sn in xrange(n_sheets... | 11099d2929ef0078ae0e5b07a700bdb2021eaa56 | 3,642,738 |
import numpy
import logging
def fitStatmechPseudoRotors(Tlist, Cvlist, Nvib, Nrot, molecule=None):
"""
Fit `Nvib` harmonic oscillator and `Nrot` hindered internal rotor modes to
the provided dimensionless heat capacities `Cvlist` at temperatures `Tlist`
in K. This method assumes that there are enough ... | eb110aab6a5ed35bd2ec1bdb2ca262524fe44dcf | 3,642,739 |
def add_numbers(a, b):
"""Sums the given numbers.
:param int a: The first number.
:param int b: The second number.
:return: The sum of the given numbers.
>>> add_numbers(1, 2)
3
>>> add_numbers(50, -8)
42
"""
return a + b | 7d9a0c26618a2aee5a8bbff6a65e315c33594fde | 3,642,740 |
def get_version(table_name):
"""Get the most recent version number held in a given table."""
db = get_db()
cur = db.cursor()
cur.execute("select * from {} order by entered_on desc".format(table_name))
return cur.fetchone()["version"] | 7bc55bacf7aa84ccc9ba6f6bb51bbc51c1556395 | 3,642,741 |
def area(a, indices=(0, 1, 2, 3)):
"""
:param a:
:param indices:
:return:
"""
x0, y0, x1, y1 = indices
return (a[..., x1] - a[..., x0]) * (a[..., y1] - a[..., y0]) | 17df4d4f4ad818be0b2ed7a1fe65aaeccbe63638 | 3,642,742 |
from xbbg.io import logs
def latest_file(path_name, keyword='', ext='', **kwargs) -> str:
"""
Latest modified file in folder
Args:
path_name: full path name
keyword: keyword to search
ext: file extension
Returns:
str: latest file name
"""
files = sort_by_modif... | 7d6db9994525a5fc4f109c52bede04f2c568c906 | 3,642,743 |
def infer_tf_dtypes(image_array):
"""
Choosing a suitable tf dtype based on the dtype of input numpy array.
"""
return dtype_casting(
image_array.dtype[0], image_array.interp_order[0], as_tf=True) | fd8fc353fd6a76a1dae2a693a9121415393b8d50 | 3,642,744 |
def get_cifar10_datasets(n_devices, batch_size=256, normalize=False):
"""Get CIFAR-10 dataset splits."""
if batch_size % n_devices:
raise ValueError("Batch size %d isn't divided evenly by n_devices %d" %
(batch_size, n_devices))
train_dataset = tfds.load('cifar10', split='train[:90%]')
... | 50dd1b02792ab13f4b6d42d52e6467503f319bb2 | 3,642,745 |
from disco.worker.pipeline.worker import Worker, Stage
from disco.core import Job, result_iterator
def predict(dataset, fitmodel_url, save_results=True, show=False):
"""
Function starts a job that makes predictions to input data with a given model
Parameters
----------
input - dataset object with... | dbf56e82a3ff81a899cf2c33fa83f8c0f1b73947 | 3,642,746 |
def format_string_to_json(balance_info):
"""
Format string to json.
e.g: '''Working Account|KES|481000.00|481000.00|0.00|0.00'''
=> {'Working Account': {'current_balance': '481000.00',
'available_balance': '481000.00',
'reserved_balance': '0.00',
'uncleared_balance': '0.00'}}
"""
balance_dict = frappe._dic... | 1be0d4d8ad3c5373e18e6f78957e18d8f0c0c846 | 3,642,747 |
from typing import Tuple
from typing import List
def get_relevant_texts(subject: Synset, doc_threshold: float) -> Tuple[List[str], List[int], int, int]:
"""Get all lines from all relevant articles. Also return the number of retrieved documents and retained ones."""
article_dir = get_article_dir(subject)
... | 150dca990fe67ed3fb5381e6d4a6bce8656f2619 | 3,642,748 |
def plot_mae(X, y, model):
"""
Il est aussi pertinent de logger les graphiques sous forme d'artifacts.
"""
fig = plt.figure()
plt.scatter(y, model.predict(X))
plt.xlabel("Durée réelle du trajet")
plt.ylabel("Durée estimée du trajet")
image = fig
fig.savefig("MAE.png")
plt.cl... | 3bc4225f530f7f80ea903d55963cb0a33fe1cb45 | 3,642,749 |
from typing import Optional
from typing import List
import re
def compile_options(
rst_roles: Optional[List[str]],
rst_directives: Optional[List[str]],
*,
allow_autodoc: bool = False,
allow_toolbox: bool = False,
):
"""
Compile the list of allowed roles and directives.
:param rst_roles:
:param rst_di... | 2c5ff56797ce8eb37dfd193fd0522c057e265da5 | 3,642,750 |
import types
def get_pure_function(method):
"""
Retreive pure function, for a method.
Depends on features specific to CPython
"""
assert(isinstance(method, types.MethodType))
assert(hasattr(method, 'im_func'))
return method.im_func | f0a7f25a38fd9da061f281f5c55453f8e7ae37d0 | 3,642,751 |
def _agg_samples_2d(sample_df: pd.DataFrame) -> pd.DataFrame:
"""Aggregate ENN samples for plotting."""
def pct_95(x):
return np.percentile(x, 95)
def pct_5(x):
return np.percentile(x, 5)
enn_df = (sample_df.groupby(['x0', 'x1'])['y']
.agg([np.mean, np.std, pct_5, pct_95]).reset_index())
e... | d2decff9ae5224ad77ce6f133ac0cf0099dda89f | 3,642,752 |
def get_np_num_array_str(data_frame_rows):
"""
Get a complete code str that creates a np array with random values
"""
test_code = cleandoc("""
from sklearn.preprocessing import StandardScaler
import pandas as pd
from numpy.random import randint
series = randint(0,100,siz... | 66a81bba8666a02770f1de233e458a5067e08f62 | 3,642,753 |
from typing import Any
def get_config(name: str = None, default: Any = _MISSING) -> Any:
"""Gets the global configuration.
Parameters
----------
name : str, optional
The name of the setting to get the value for. If no name is
given then the whole :obj:`Configuration` object is return... | da43dd18c3841489cf6c909acb12a95b34179135 | 3,642,754 |
def domain_domain_distance(ptg1, ptg2, pdb_struct, domain_distance_dict):
"""
Return the distance between two domains, which will be defined as
the distance between their two closest SSEs
(using SSE distnace defined in ptdistmatrix.py)
Parameters:
ptg1 - PTGraph2 object for one domain
... | 6f2f68714717a32da0182db814629ac0e55b59e8 | 3,642,755 |
def pred_error(f_pred, prepare_data, data, iterator, max_len, n_words, filter_h):
""" compute the prediction error.
"""
valid_err = 0
for _, valid_index in iterator:
x = [data[0][t] for t in valid_index]
x = prepare_data(x,max_len,n_words,filter_h... | c8f667a2eb6b9cc67d96ea0b6848f27cd337a2f9 | 3,642,756 |
def standardize_10msample(frac: float=0.01):
"""Runs each data processing function in series to save a new .csv data file.
Intended for Pandas DataFrame. For Dask DataFrames, use standardize_10msample_dask
Args:
frac (float, optional): Fraction of data file rows to sample. Defaults to 0.01.
Re... | d834cc31220a34204966160bb72399a53b99ff5b | 3,642,757 |
def is_ansible_managed(file_path):
"""
Gets whether the fail2ban configuration file at the given path is managed by Ansible.
:param file_path: the file to check if managed by Ansible
:return: whether the file is managed by Ansible
"""
with open(file_path, "r") as file:
return file.readli... | a8e70d242f598ad26a00cf0b3ccc1a1494475ba8 | 3,642,758 |
import ctypes
def sumai(array):
"""
Return the sum of the elements of an integer array.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sumai_c.html
:param array: Input Array.
:type array: Array of ints
:return: The sum of the array.
:rtype: int
"""
n = ctypes.c_int(len(a... | ece9b6a171dff66d4f66c7ce711b6a7a7b4c59a2 | 3,642,759 |
import os
import re
def _get_connection_dir(app):
"""Gets the connection dir to use for the IPKernelApp"""
connection_dir = None
# Check the pyxll config first
cfg = get_config()
if cfg.has_option("JUPYTER", "runtime_dir"):
connection_dir = cfg.get("JUPYTER", "runtime_dir")
if not... | 246094655a185fc1a2029ec0d5a899a641c62a13 | 3,642,760 |
import os
import zlib
def download(accession):
"""Downloads GEO file based on accession number. Returns a SOFTFile or ANNOTFile
instance.
For reading and unzipping binary chunks, see:
http://stackoverflow.com/a/27053335/1830334
http://stackoverflow.com/a/2424549/1830334
"""
if 'GPL' not in accession: # sof... | 4f207d7dbe2fdc99142690565c3266d7341af548 | 3,642,761 |
from typing import Union
from typing import Optional
from typing import Mapping
from typing import Any
def invoke(
node: Union[DAG, Task],
params: Optional[Mapping[str, Any]] = None,
) -> Mapping[str, NodeOutput]:
"""
Invoke a node with a series of parameters.
Parameters
----------
node
... | f05a49996912a52db37a809d078faaa208942e7f | 3,642,762 |
def convert_acl_to_iam_policy(acl):
"""Converts the legacy ACL format to an IAM Policy proto."""
owners = acl.get('owners', [])
readers = acl.get('readers', [])
if acl.get('all_users_can_read', False):
readers.append('allUsers')
writers = acl.get('writers', [])
bindings = []
if owners:
bindings.ap... | 990cdb6a51a696cf2b7825af94cf4265b2229be9 | 3,642,763 |
def get_valid_start_end(mask):
"""
Args:
mask (ndarray of bool): invalid mask
Returns:
"""
ns = mask.shape[0]
nt = mask.shape[1]
start_idx = np.full(ns, -1, dtype=np.int32)
end_idx = np.full(ns, -1, dtype=np.int32)
for s in range(ns):
# scan from start to the end
... | 41520c051d25aed203e5db9f64497f75eaab4f6c | 3,642,764 |
def pahrametahrize(*args, **kwargs) -> t.Callable:
"""Pass arguments straight through to `pytest.mark.parametrize`."""
return pytest.mark.parametrize(*args, **kwargs) | 43bbc1e8323956f1ed2e1da60abf23e5b35130ba | 3,642,765 |
from datetime import datetime
def utcnow():
"""Return the current time in UTC with a UTC timezone set."""
return datetime.utcnow().replace(microsecond=0, tzinfo=UTC) | 496c80cfa4a2b00b514346705fc0709739e2d3c0 | 3,642,766 |
def default_to(default, value):
"""
Ramda implementation of default_to
:param default:
:param value:
:return:
"""
return value or default | 58338f67332a0ff116cd2ff46d65ee92bf59c360 | 3,642,767 |
def insertGraph():
"""
Create a new graph
"""
root = Xref.getroot().elem
ref = getNewRef()
elem = etree.Element(etree.QName(root, sgraph), reference=ref)
name = makeNewName(sgraph, elem)
root.append(elem)
Xref.setDirty()
return name, (elem, newDotGraph(name, ref, elem)) | 2a60fac192d6d3448c3e48637585af2d54bdf87f | 3,642,768 |
from datetime import datetime
def get_line_notif(line_data: str):
"""
Извлечь запись из таблицы.
:param line_data: запрашиваемая строка
"""
try:
connection = psycopg2.connect(
user=USER,
password=PASSWORD,
host="127.0.0.1",
port="5432",
... | 8fbeb195faaa1f49928e3d0e49310cc3d4bcb37f | 3,642,769 |
import os
def load_alloc_model(matfilepath, prefix):
""" Load allocmodel stored to disk in bnpy .mat format.
Parameters
------
matfilepath : str
String file system path to folder where .mat files are stored.
Usually this path is a "taskoutpath" like where bnpy.run
saves its ou... | 459426256a4eee25133b7baa8fca7811432b6238 | 3,642,770 |
def bouts_per_minute(boutlist):
"""Takes list of times of bouts in seconds, returns bpm = total_bouts / total_time."""
bpm = (total_bouts(boutlist) / total_time(boutlist)) * 60
return bpm | 949f0d8758d7fcc8a1e19d4772788504b5ba10a5 | 3,642,771 |
import re
def convert_to_snake_case(string: str) -> str:
"""Helper function to convert column names into snake case. Takes a string
of any sort and makes conversions to snake case, replacing double-
underscores with single underscores."""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', string)
draft = ... | 2a8de69a6915e87e46582a1af7a7897ff6fd97ce | 3,642,772 |
def list_keys(client, keys):
"""
:param client: string
:param keys: list of candidate keys
:return: True if all keys exist, None otherwise
"""
objects = client.get_multi(keys)
if bool(objects):
return objects
else:
return None | 4370053b76ea526e1f43309112f85f968ce76b6b | 3,642,773 |
import os
import pickle
def load_config(config_name):
"""
Load a configuration object from a file and return the object. The given configuration name
must be a valid saved configuration.
:param config_name: The name of the configuration file to load from.
:return: The configuration object saved in... | dfa99668bf3f1eae39f1678cbd0eda4e3fe151aa | 3,642,774 |
def estimate_variance(ip_image: np.ndarray, x: int, y: int, nbr_size: int) -> float:
"""Estimates local variances as described in pg. 6, eqn. 20"""
nbrs = get_neighborhood(x, y, nbr_size, ip_image.shape[0], ip_image.shape[1])
vars = list()
for channel in range(3):
pixel_avg = 0
for i, j ... | 26932d333a50526f5f3bc4b10e5dd2b0bd15e871 | 3,642,775 |
def api_key_regenerate():
"""
Generate a new API key for the currently logged-in user.
"""
try:
return flask.jsonify({
constants.api.RESULT: constants.api.RESULT_SUCCESS,
constants.api.MESSAGE: None,
'api_key': database.user.generate_new_api_key(current_user.u... | 59ccc904dc80386910370dae0752c4810107224c | 3,642,776 |
def almost_equal_ignore_nan(a, b, rtol=None, atol=None):
"""Test that two NumPy arrays are almost equal (ignoring NaN in either array).
Combines a relative and absolute measure of approximate eqality.
If either the relative or absolute check passes, the arrays are considered equal.
Including an absolute... | ca364b23e5a6106a98ba52629ccb152dc0d95214 | 3,642,777 |
def make_commands(manager):
"""Prototype"""
# pylint: disable=no-member
return (cmd_t(manager) for cmd_t in
AbstractTwitterFollowersCommand.__subclasses__()) | 54443970dc69b06c530b746cb42b418bc5a7ee42 | 3,642,778 |
import logging
def copy_rds_snapshot(
target_snapshot_identifier: str,
source_snapshot_identifier: str,
target_kms: str,
wait: bool,
rds,
):
"""Copy snapshot from source_snapshot_identifier to target_snapshot_identifier and encrypt using target_kms"""
logger = logging.getLogger("copy_rds_s... | f7d3c3b9b5588afb9dd1b6e65fc3a51f6411e997 | 3,642,779 |
def get_other_menuitems():
"""
returns other menu items
each menu pk will be dict key
{0: QuerySet, 1: QuerySet, ..}
"""
menuitems = {}
all_objects = Menu.objects.all()
for obj in all_objects:
menuitems[obj.pk] = obj.menuitem_set.all()
return menuitems | 7e868e3d434dd168dfe6d9938093044e97e2bc5c | 3,642,780 |
from typing import Union
from typing import List
import os
import warnings
def gather_simulation_file_paths(in_folder: str, filePrefix: str = "",
fileSuffixes: Union[str, List[str]] = [".tre", ".tre.tar.gz"],
files_per_folder: int = 1,
... | 1f5473b147a16dfc6cb2f5101d264f45161c8e6b | 3,642,781 |
import random
def create_deck(shuffle=False):
"""Create a new deck of 52 cards"""
deck = [(s, r) for r in RANKS for s in SUITS]
if shuffle:
random.shuffle(deck)
return deck | 92b828ce373c48a0a403c519a2e25b0cb1ab7409 | 3,642,782 |
def mock_gate_util_provider_oldest_namespace_feed_sync(
monkeypatch, mock_distromapping_query
):
"""
Mocks for anchore_engine.services.policy_engine.engine.policy.gate_util_provider.GateUtilProvider.oldest_namespace_feed_sync
"""
# required for FeedOutOfDateTrigger.evaluate
# setup for anchore_e... | c6cf043b49574be44114110f5c1092d06fe531a0 | 3,642,783 |
def ESMP_LocStreamGetBounds(locstream, localDe=0):
"""
Preconditions: An ESMP_LocStream has been created.\n
Postconditions: .\n
Arguments:\n
:RETURN: Numpy.array :: \n
:RETURN: Numpy.array :: \n
ESMP_LocStream :: locstream\n
"""
llde = ct.c_int(localDe)
# lo... | 179b24463cd8dd5f70ad63530a50b6fe4dd4dfb8 | 3,642,784 |
def reverse(collection):
"""
Reverses a collection.
Args:
collection: `dict|list|depset` - The collection to reverse
Returns:
`dict|list|depset` - A new collection of the same type, with items in the reverse order
of the input collec... | 587bf847028f485783e74633b1aa2ed0ef003daa | 3,642,785 |
def A_fast_full5(S, phase_factors, r, r_min, MY, MX):
""" Fastest version, takes precomputed phase factors, assumes S-matrix with beam tilt included
:param S: B x NY x NX
:param phase_factors: K x B
:param r: K x 2
:param out: K x MY x MX
:return: exit ... | 3bffd01037f317c88328a751958aca67bc90b2dd | 3,642,786 |
from pathlib import Path
import requests
import logging
def get_metadata_for_druid(druid, redownload_mods):
"""Obtains a .mods metadata file for the roll specified by DRUID either
from the local mods/ folder or the Stanford Digital Repository, then
parses the XML to build the metadata dictionary for the r... | 982c2a89e85b07692901f1452a62c144ab1181b7 | 3,642,787 |
def logistic_dataset_gen_data(num, w, dim, temp, rng_key):
"""Samples data from a standard Gaussian with binary noisy labels.
Args:
num: An integer denoting the number of data points.
w: An array of size dim x odim, the weight vector used to generate labels.
dim: An integer denoting the number of input... | 99fed2fd2cdb1250a444a986dd182ab846477890 | 3,642,788 |
def sech(x):
"""Computes the hyperbolic secant of the input"""
return 1 / cosh(x) | 1cded1fbf37070dbecba0f8518990c3eef8e6406 | 3,642,789 |
import torch
def _map_triples_elements_to_ids(
triples: LabeledTriples,
entity_to_id: EntityMapping,
relation_to_id: RelationMapping,
) -> MappedTriples:
"""Map entities and relations to pre-defined ids."""
if triples.size == 0:
logger.warning('Provided empty triples to map.')
retu... | 5d4db571e9b9d37329df7689b7e7629559580522 | 3,642,790 |
from typing import Tuple
def pinf_two_networks(grgd: Tuple[float, float],
k: Tuple[float, float] = (3, 3),
alpha_i: Tuple[float, float] = (1, 1),
solpoints: int = 10,
eps: float = 1e-5,
method: str = "hybr"):... | c90db1bb6d9d314086887e4f5b98f422731b3853 | 3,642,791 |
def uncapped_flatprice_goal_reached(chain, uncapped_flatprice, uncapped_flatprice_finalizer, preico_funding_goal, preico_starts_at, customer) -> Contract:
"""A ICO contract where the minimum funding goal has been reached."""
time_travel(chain, preico_starts_at + 1)
wei_value = preico_funding_goal
uncapp... | 20a6a10b4cb1318e2be7fd1995d025b582ee4768 | 3,642,792 |
def depfile_name(request, tmp_path_factory):
"""A fixture for a temporary doit database file(s) that will be removed after running"""
depfile_name = str(tmp_path_factory.mktemp('x', True) / 'testdb')
def remove_depfile():
remove_db(depfile_name)
request.addfinalizer(remove_depfile)
return d... | cbe99e664abeea52a038898f3e76547795bca30a | 3,642,793 |
from typing import OrderedDict
def _convert_v3_response_to_v2(pbx_name, termtype, command, v3_response):
"""
Convert the v3 response to the legacy v2 xml format.
"""
logger.debug(v3_response)
obj = {
'command': {'@cmd': command, '@cmdType': termtype, '@pbxName': pbx_name}
}
if v3_r... | c4883706e4bbbf3297781e4bd91360c68c3ea786 | 3,642,794 |
from typing import OrderedDict
import collections
import warnings
def calculate(dbf, comps, phases, mode=None, output='GM', fake_points=False, broadcast=True, parameters=None, **kwargs):
"""
Sample the property surface of 'output' containing the specified
components and phases. Model parameters are taken ... | c69769fa322831cc021db497a329de816541a20a | 3,642,795 |
def is_negative(value):
"""Checks if `value` is negative.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is negative.
Example:
>>> is_negative(-1)
True
>>> is_negative(0)
False
>>> is_negative(1)
False
.. versi... | ce0183d95a2394db18904f0ca7f1225e43cf671d | 3,642,796 |
import torch
def get_optimizer_noun(lr, decay, mode, cnn_features, role_features):
""" To get the optimizer
mode 0: training from scratch
mode 1: cnn fix, verb fix, role training
mode 2: cnn fix, verb fine tune, role training
mode 3: cnn finetune, verb finetune, role training"""
if mode == 0:
... | 6ac2df23f6a50d3488302cfe2da6189a995c0d85 | 3,642,797 |
import os
def lan_manifold(
parameter_df=None,
vary_dict={"v": [-1.0, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1.0]},
model="ddm",
n_rt_steps=200,
max_rt=5,
fig_scale=1.0,
save=False,
show=True,
):
"""Plots lan likelihoods in a 3d-plot.
:Arguments:
parameter_df: pandas.... | 2faddac2b992b022ce27eb0c66a12968ff6d2da7 | 3,642,798 |
def _loc_str_to_pars(loc, x=None, y=None, halign=None, valign=None, pad=_PAD):
"""Convert from a string location specification to the specifying parameters.
If any of the specifying parameters: {x, y, halign, valign}, are 'None', they are set to
default values.
Returns
-------
x : float
y ... | 84094b2eaf39390a1d30fd26d8ae36ecd32a7665 | 3,642,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.