content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from re import T
def sms_outbound_gateway():
""" SMS Outbound Gateway selection for the messaging framework """
# CRUD Strings
s3.crud_strings["msg_sms_outbound_gateway"] = Storage(
label_create = T("Create SMS Outbound Gateway"),
title_display = T("SMS Outbound Gateway Details"),
... | bb0796dabbfe14b6a7e2a1d25960beae3d065717 | 3,644,600 |
def _insert_volume(_migration, volume_number, volume_obj):
"""Find or create the corresponding volume, and insert the attribute."""
volumes = _migration["volumes"]
volume_obj = deepcopy(volume_obj)
volume_obj["volume"] = volume_number
volumes.append(volume_obj)
return volume_obj | 3a89024aa5b2bc9fc2bb16094a1a95ca6fd43f63 | 3,644,601 |
def create_vnet(credentials, subscription_id, **kwargs):
"""
Create a Batch account
:param credentials: msrestazure.azure_active_directory.AdalAuthentication
:param subscription_id: str
:param **resource_group: str
:param **virtual_network_name: str
:param **subnet_na... | 3a0a670c89f4a2c427a205039bf12b3af42e6b0a | 3,644,602 |
def to_inorder_iterative(root: dict, allow_none_value: bool = False) -> list:
"""
Convert a binary tree node to depth-first in-order list (iteratively).
"""
node = root
node_list = []
stack = []
while node or len(stack) > 0:
if node:
stack.append(node) # push a node into... | 90cf850f5e0fa91432bd2b9cde642e13fc0d8723 | 3,644,603 |
def symmetric_mean_absolute_percentage_error(a, b):
"""
Calculates symmetric Mean Absolute Percentage Error (sMAPE).
Args:
a (): ctual values.
b (): Predicted values.
Returns: sMAPE float %.
"""
a = np.reshape(a, (-1,))
b = np.reshape(b, (-1,))
return 100.0 * np.mean(... | 90557e6f2a702aeea27b2a881b6ef3e35c0b7f46 | 3,644,605 |
def exec_quiet(handle, *args, **kwargs):
"""
Like exe.execute but doesnt print the exception.
"""
try:
val = handle(*args, **kwargs)
except Exception:
pass
else:
return val | d0e922672c8a2d302bc2bfcb30bec91d32988945 | 3,644,606 |
def make_modified_function_def(original_type, name, original, target):
"""Make the modified function definition.
:return: the definition for the modified function
"""
arguments = format_method_arguments(name, original)
argument_names = set(target.parameters)
unavailable_arguments = [p for p in ... | 35263518c9edf9a710f66c6432ef9fb1a85df3fa | 3,644,607 |
import pathlib
import multiprocessing
from functools import reduce
def fetch_tiles(server, tile_def_generator, output=pathlib.Path('.'), force=False):
"""
fetch and store tiles
@param server
server definition object
@param tile_def_generator
generator of ti... | 6e42da71bff389b36485dc34222fa4a1b5d5abf3 | 3,644,608 |
def _UTMLetterDesignator(lat):
"""
This routine determines the correct UTM letter designator for the
given latitude returns 'Z' if latitude is outside the UTM limits of
84N to 80S.
Written by Chuck Gantz- chuck.gantz@globalstar.com
"""
if 84 >= lat >= 72: return 'X'
elif 72 > lat >= 64: ... | 3c5b9a54a9824d6755937aeaece8fa53483045fc | 3,644,609 |
import re
def is_ignored(file: str) -> bool:
"""
Check if the given file is ignored
:param file: the file
:return: if the file is ignored or not
"""
for ignored in config.get('input').get('ignored'):
ignored_regex = re.compile(ignored)
if re.match(ignored_regex, file):
... | 22b038b17435b2a2a9c79d24136de8f6322d8093 | 3,644,610 |
def enumerate_phone_column_index_from_row(row):
"""Enumerates the phone column from a given row. Uses Regexs
Parameters
----------
row : list
list of cell values from row
Returns
-------
int
phone column index enumerated from row
"""
# initial phone_column_index va... | bbc5f1abceb51d5a7385d235c7dae9ed07ffcc1f | 3,644,612 |
def fetch_words(url):
"""
Fetch a list of words from URL
Args:
url: The URL of a UTF-8 text doxument
Returns:
A list of strings containing the words from
the document.
"""
story = urlopen(url)
story_words = []
for line in story:
line_words = line.decode(... | 939bc5409b4ae824a3671e555d9ebdf8454c6358 | 3,644,613 |
from typing import Dict
def dot_keys_to_nested(data: Dict) -> Dict:
"""old['aaaa.bbbb'] -> d['aaaa']['bbbb']
Args:
data (Dict): [description]
Returns:
Dict: [description]
"""
rules = defaultdict(lambda: dict())
for key, val in data.items():
if '.' in key:
... | 06bbf2b154c1cfb840d556c082bcb0b9282c44be | 3,644,615 |
def vec2adjmat(source, target, weight=None, symmetric=True):
"""Convert source and target into adjacency matrix.
Parameters
----------
source : list
The source node.
target : list
The target node.
weight : list of int
The Weights between the source-target values
symm... | fa5e8370557b8e1f37cbe2957ec16c614c4ad70d | 3,644,616 |
def is_valid(number):
"""Check if the number provided is a valid PAN. This checks the
length and formatting."""
try:
return bool(validate(number))
except ValidationError:
return False | 2a2c99c29072e402cc046fa1eef8eefd2c4ee0af | 3,644,617 |
def remove_spaces(string: str):
"""Removes all whitespaces from the given string"""
if string is None:
return ""
return "".join(l for l in str(string) if l not in WHITESPACES) | 5dc928124c0a080f8e283450dc9754b4b301f047 | 3,644,618 |
def decode_event_to_internal(abi, log_event):
""" Enforce the binary for internal usage. """
# Note: All addresses inside the event_data must be decoded.
decoded_event = decode_event(abi, log_event)
if not decoded_event:
raise UnknownEventType()
# copy the attribute dict because that data... | 1005507ea129be88462b75685d5b8a993fd6f0cd | 3,644,619 |
def run_ode_solver(system, slope_func, **options):
"""Computes a numerical solution to a differential equation.
`system` must contain `init` with initial conditions,
`t_0` with the start time, and `t_end` with the end time.
It can contain any other parameters required by the slope function.
`opti... | ae2994aeaca5590d61921a25877807a1611841cd | 3,644,620 |
def case_configuration(group_id, det_obj, edges):
"""
Get all the needed information of the detectors for the chosen edges, as well as only those trajectories that map
onto one of the edges.
Parameters
----------
group_id
det_obj
edges
Returns
-------
"""
ds = det_obj.d... | 8e6910943e705fa952992ef5e2551140e578e8ef | 3,644,621 |
def _remarks(item: str) -> str:
"""Returns the remarks. Reserved for later parsing"""
return item | d515837e52ee88edeb5bdb5e8f2d37ed28789362 | 3,644,622 |
from datetime import datetime
def _date_to_datetime(value):
"""Convert a date to a datetime for datastore storage.
Args:
value: A datetime.date object.
Returns:
A datetime object with time set to 0:00.
"""
assert isinstance(value, datetime.date)
return datetime.datetime(value.year, value.month, ... | 872efa93fd256f38c2c82f979d0942114c6254b9 | 3,644,624 |
def get_posted_float(key):
"""
Retrieve a named float value from a POSTed form
:param key: Value key
:return: Value or None if not specified
"""
value = request.form[key]
return float(value) if value else None | 1d88d4b0fc09f8e0d323bb8cc0aba83ac5fa9d9f | 3,644,626 |
def te_ds(mass, norm_vel, x_ratios, source_distance, te_einstein, gamma, sigma_total, \
xval, val):
"""Returns the probability of a sampled value T_E by weighting from the
T_E probability distribution of the data """
if min(xval) < te_einstein <= max(xval):
omegac = gamma*norm_vel*np.sqrt(x_rati... | 4322a1266610f047e2efef023d8f0cccf80e697a | 3,644,627 |
def roulette(fitness_values, return_size, elite=0):
"""
Perform a roulette wheel selection
Return return_size item indices
"""
sorted_indices = np.argsort(fitness_values)
c_sorted = np.sort(fitness_values).cumsum()
c_sorted /= np.max(c_sorted)
sampled = [sorted_indices[np.sum(np.random... | 6ac06a28a6ce22ef8828597985332913aa0987e2 | 3,644,628 |
def create_sample_tree():
"""
1
/ \
2 3
/ \
4 5
"""
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.right.left = TreeNode(4)
root.right.right = TreeNode(5)
return root | 7e5c252cf66df3fed236e0891185b545e0c9c861 | 3,644,631 |
import copy
def sp_normalize(adj_def, device='cpu'):
"""
:param adj: scipy.sparse.coo_matrix
:param device: default as cpu
:return: normalized_adj:
"""
adj_ = sp.coo_matrix(adj_def)
adj_ = adj_ + sp.coo_matrix(sp.eye(adj_def.shape[0]), dtype=np.float32)
rowsum = np.array(adj_.sum(axis=... | a4ef96d439c27047def02234c3308e45dc934067 | 3,644,632 |
def isTileEvent(x:int, y:int):
"""
checks if a given tile is an event or not quicker than generateTileAt
x: the x value of the target tile
y: the y value of the target tile
"""
perlRand = getPerlin(x, y, s=2.501)
if Math.floor(perlRand * 3400) == 421 and deriveTile(x, y)=='H':
return True
elif Math.floor(pe... | 34efeef5e05830faef886f69fb95287817ced1c6 | 3,644,633 |
def to_onehot_sym(ind, dim):
"""Return a matrix with one hot encoding of each element in ind."""
assert ind.ndim == 1
return theano.tensor.extra_ops.to_one_hot(ind, dim) | db4871b3108aef0cbf2b2a63497dd30c22e2805e | 3,644,634 |
def generate_potential_grasp(object_cloud):
"""
The object_cloud needs to be in table coordinates.
"""
# https://www.cs.princeton.edu/~funk/tog02.pdf picking points in triangle
nrmls = object_cloud.normals.copy()
# if object_cloud.points[:,2].max()<0.11:
# nrmls[nrmls[:,2]>0] *= -1
#... | 169552dfea38c9f4a15a67f23ca40cda2e824769 | 3,644,635 |
import torch
import time
def ACP_O(model, Xtrain, Ytrain, Xtest, labels = [0,1], out_file = None, seed = 42, damp = 10**-3, batches = 1):
"""Runs ACP (ordinary) CP-IF to make a prediction for all points in Xtest
"""
N = len(Xtrain)
# Train model on D.
model_D = model
model_D = model_D.to... | 6205e62c153fac5fe58529882d232bba4a83ce8a | 3,644,636 |
import math
def func (x):
"""
sinc (x)
"""
if x == 0:
return 1.0
return math.sin (x) / x | c91242e360547107f7767e442f40f4bf3f2b53e8 | 3,644,637 |
def grad_norm(model=None, parameters=None):
"""Compute parameter gradient norm."""
assert parameters is not None or model is not None
total_norm = 0
if parameters is None:
parameters = []
if model is not None:
parameters.extend(model.parameters())
parameters = [p for p in parameters if p.grad is no... | ff471715a72f0d2afbafa60d19eb802a748a2419 | 3,644,638 |
import copy
def db_entry_trim_empty_fields(entry):
""" Remove empty fields from an internal-format entry dict """
entry_trim = copy.deepcopy(entry) # Make a copy to modify as needed
for field in [ 'url', 'title', 'extended' ]:
if field in entry:
if (entry[field] is None) or \
... | d5b31c823f4e8091872f64445ab603bcbf6a2bef | 3,644,639 |
def loadconfig(PATH):
"""Load Latte's repo configuration from
the PATH. A dictionary of the config data is returned, otherwise None."""
try:
f = open(PATH, "r")
except FileNotFoundError:
return None
else:
confobj = SWConfig(f.read())
if confobj is None:
re... | cd912b1e9d7fddbecf72165b42d1eb8b47687838 | 3,644,640 |
import logging
def _call_token_server(method, request):
"""Sends an RPC to tokenserver.minter.TokenMinter service.
Args:
method: name of the method to call.
request: dict with request fields.
Returns:
Dict with response fields.
Raises:
auth.AuthorizationError on HTTP 403 reply.
Internal... | a81a6b0f8a42517bb2b7e6fafc762f2620c18dbb | 3,644,641 |
import requests
def get_keywords(text):
"""Get keywords that relate to this article (from NLP service)
Args:
text (sting): text to extract keywords from
Returns:
[list]: list of extracted keywords
"""
extracted_keywords = []
request = {'text': text}
nlp_output = requests.po... | 56caaa6af416c425eb54ef9e85460cd5921e9d74 | 3,644,642 |
def weather_config() -> str:
"""The function config_handle() is called
and the contents that are returned are
stored in the variable 'config file'.
This is then appropriately parsed so the
weather api key is accessed. This is then
returned at the end of the function."""
#Accessing... | 6eb35a876eb73160d39417a213195b39e68ea568 | 3,644,643 |
import warnings
def interpret_bit_flags(bit_flags, flip_bits=None, flag_name_map=None):
"""
Converts input bit flags to a single integer value (bit mask) or `None`.
When input is a list of flags (either a Python list of integer flags or a
string of comma-, ``'|'``-, or ``'+'``-separated list of flags... | ea657c9f4abfe8503d7ea120ea7c5ff039f82634 | 3,644,644 |
import torch
def reparam(mu, std, do_sample=True, cuda=True):
"""Reparametrization for Normal distribution.
"""
if do_sample:
eps = torch.FloatTensor(std.size()).normal_()
if cuda:
eps = eps.cuda()
eps = Variable(eps)
return mu + eps * std
else:
retu... | dc959b0f1f3972ae612d44d90694480270b42a3e | 3,644,645 |
import random
def simu_grid_graph(width, height, rand_weight=False):
"""Generate a grid graph.
To generate a grid graph. Each node has 4-neighbors. Please see more
details in https://en.wikipedia.org/wiki/Lattice_graph. For example,
we can generate 5x3(width x height) grid graph
0---1-... | 139be873014c96f05b3fb391ea1352fab68b8357 | 3,644,646 |
def calculate_sensitivity_to_weighting(jac, weights, moments_cov, params_cov):
"""calculate the sensitivity to weighting.
The sensitivity measure is calculated for each parameter wrt each moment.
It answers the following question: How would the precision change if the weight of
the kth moment is i... | ed41e5e369446144e10bb7b7edfc59d2c3f8621e | 3,644,648 |
def subword(w):
"""
Function used in the Key Expansion routine that takes a four-byte input word
and applies an S-box to each of the four bytes to produce an output word.
"""
w = w.reshape(4, 8)
return SBOX[w[0]] + SBOX[w[1]] + SBOX[w[2]] + SBOX[w[3]] | 36dfd4c82484fda342629c94fc66454723e371f6 | 3,644,649 |
import multiprocessing
from typing import Counter
def deaScranDESeq2(counts, conds, comparisons, alpha, scran_clusters=False):
"""Makes a call to DESeq2 with SCRAN to
perform D.E.A. in the given
counts matrix with the given conditions and comparisons.
Returns a list of DESeq2 results for each comparis... | de6c6a1640819c72ef72275f3205cf24d7a8ce0a | 3,644,650 |
def cylindrical_to_cartesian(a: ArrayLike) -> NDArray:
"""
Transform given cylindrical coordinates array :math:`\\rho\\phi z`
(radial distance, azimuth and height) to cartesian coordinates array
:math:`xyz`.
Parameters
----------
a
Cylindrical coordinates array :math:`\\rho\\phi z` ... | 27b8d95c2c09b8b78069a4ad0c4cf351de93db13 | 3,644,651 |
def eigenarray_to_array( array ):
"""Convert Eigen::ArrayXd to numpy array"""
return N.frombuffer( array.data(), dtype='d', count=array.size() ) | 7caa9ab71ca86b6a8afa45879d0f29c8122973fe | 3,644,652 |
from typing import List
def _ncon_to_adjmat(labels: List[List[int]]):
""" Generate an adjacency matrix from the network connections. """
# process inputs
N = len(labels)
ranks = [len(labels[i]) for i in range(N)]
flat_labels = np.hstack([labels[i] for i in range(N)])
tensor_counter = np.hstack(
[i ... | 8e7171321f547084bdaff4cefa1bd9e00b453cc9 | 3,644,653 |
def _is_install_requirement(requirement):
""" return True iff setup should install requirement
:param requirement: (str) line of requirements.txt file
:return: (bool)
"""
return not (requirement.startswith('-e') or 'git+' in requirement) | 339f6a8a573f33157a46193216e90d62475d2dea | 3,644,655 |
def confusion_matrices_runs_thresholds(
y, scores, thresholds, n_obs=None, fill=0.0, obs_axis=0
):
"""Compute confusion matrices over runs and thresholds.
`conf_mats_runs_thresh` is an alias for this function.
Parameters
----------
y : np.ndarray[bool, int32, int64, float32, float64]
t... | 7a7b640a724a2ffba266403ac72940da5a28f57b | 3,644,656 |
def new_project(request):
"""
Function that enables one to upload projects
"""
profile = Profile.objects.all()
for profile in profile:
if request.method == 'POST':
form = ProjectForm(request.POST, request.FILES)
if form.is_valid():
pro = form.save(comm... | da4adb286e6b972b9ac37019cd4ff0ed4c82dd3f | 3,644,657 |
def move_to_next_pixel(fdr, row, col):
""" Given fdr (flow direction array), row (current row index), col (current col index).
return the next downstream neighbor as row, col pair
See How Flow Direction works
http://desktop.arcgis.com/en/arcmap/latest/tools/spatial-analyst-toolbox/how-flow-direction-w... | d134bb35ed4962945c86c0ac2c6af1aff5acd06b | 3,644,658 |
import re
import string
def clean_text(post):
"""
Function to filter basic greetings and clean the input text.
:param post: raw post
:return: clean_post or None if the string is empty after cleaning
"""
post = str(post)
""" filtering basic greetings """
for template in TEMPLATES:
... | 1896cc991e0c061bad16e0a2ae9768c06f2b0029 | 3,644,659 |
def turnIsLegal(speed, unitVelocity, velocity2):
"""
Assumes all velocities have equal magnitude and only need their relative angle checked.
:param velocity1:
:param velocity2:
:return:
"""
cosAngle = np.dot(unitVelocity, velocity2) / speed
return cosAngle > MAX_TURN_ANGLE_COS | e598630d47ca77ed953199852a08ce376cdc0e0f | 3,644,660 |
def convert_selection_vars_to_common_effects(G: ADMG) -> nx.DiGraph:
"""Convert all undirected edges to unobserved common effects.
Parameters
----------
G : ADMG
A causal graph with undirected edges.
Returns
-------
G_copy : ADMG
A causal graph that is a fully specified DAG... | 00f4530e1262bac92b31b8855efdd453de035c57 | 3,644,661 |
def mean_binary_proto_to_np_array(caffe, mean_binproto):
"""
:param caffe: caffe instances from import_caffe() method
:param mean_binproto: full path to the mode's image-mean .binaryproto created from train.lmdb.
:return:
"""
# I don't have my image mean in .npy file but in binaryproto. I'm con... | e79488051f26c9e3781c1fbeeb9f42683e8e2df0 | 3,644,663 |
def delete_channel(u, p, cid):
"""
Delete an existing service hook.
"""
c = Channel.query.filter_by(
id=cid,
project_id=p.id
).first()
if not c:
# Project or channel doesn't exist (404 Not Found)
return abort(404)
if c.project.owner.id != g.user.id or c.proj... | 31f6b7640bb222a6b7c7ae62af24e6da170fbaeb | 3,644,664 |
def joint_img_freq_loss(output_domain, loss, loss_lambda):
"""Specifies a function which computes the appropriate loss function.
Loss function here is computed on both Fourier and image space data.
Args:
output_domain(str): Network output domain ('FREQ' or 'IMAGE')
loss(str): Loss type ('L... | 9f9a95314c109d6d331c494c77cae8a3578e659d | 3,644,665 |
import requests
import json
def verify_auth_token(untrusted_message):
"""
Verifies a Auth Token. Returns a
django.contrib.auth.models.User instance if successful or False.
"""
# decrypt the message
untrusted = URLSafeTimedSerializer(settings.SSO_SECRET).loads(
untrusted_message, max_ag... | f470d96fea2561e5d754f5e39dad5cf816bb4e69 | 3,644,666 |
def get_requirements():
"""
Obtenir la liste de toutes les dépences
:return: la liste de toutes les dépences
"""
requirements = []
with open(REQUIREMENTS_TXT, encoding="utf-8") as frequirements:
for requirement_line in frequirements.readlines():
requirement_line = requirement... | 68d73653818b9ede5f7be00cc79842d9ca4fa59a | 3,644,667 |
import math as m
from math import sin, cos, atan, asin, floor
def equ2gal(ra, dec):
"""Converts Equatorial J2000d coordinates to the Galactic frame.
Note: it is better to use AstroPy's SkyCoord API for this.
Parameters
----------
ra, dec : float, float [degrees]
Input J2000 coordinates (... | ebed665e798a00b649367bc389747f046659d9af | 3,644,668 |
import unittest
from pyoptsparse import OPT
def require_pyoptsparse(optimizer=None):
"""
Decorate test to raise a skiptest if a required pyoptsparse optimizer cannot be imported.
Parameters
----------
optimizer : String
Pyoptsparse optimizer string. Default is None, which just checks for ... | 2df011c38f9a44047a5a259be983ba23bf9ebe92 | 3,644,669 |
from typing import Union
def addition(a:Union[int, float], b:Union[int, float]) -> Union[int, float]:
"""
A simple addition function. Add `a` to `b`.
"""
calc = a + b
return calc | b9adaf3bea178e23bd4c02bdda3f286b6ca8f3ab | 3,644,670 |
def print_version():
"""
Print the module version information
:return: returns 1 for for exit code purposes
:rtype: int
"""
print("""
%s version %s - released %s"
""" % (__docname__, __version__, __release__))
return 1 | 28f5ce2a922fe66de5dce2ed2bfab6241835c759 | 3,644,671 |
def splitpath(path):
""" Split a path """
drive, path = '', _os.path.normpath(path)
try:
splitunc = _os.path.splitunc
except AttributeError:
pass
else:
drive, path = splitunc(path)
if not drive:
drive, path = _os.path.splitdrive(path)
elems = []
try:
... | 830c7aa2e825bb57d819bc014afe7cb0ba31aaf5 | 3,644,672 |
def vmf1_zenith_wet_delay(dset):
"""Calculates zenith wet delay based on gridded zenith wet delays from VMF1
Uses gridded zenith wet delays from VMF1, which are rescaled from the gridded height to actual station height by
using Equation(5) described in Kouba :cite:`kouba2007`.
Args:
dset (Data... | defa135bac27c1540caceee4ca12f6741c5e6475 | 3,644,673 |
from functools import reduce
import random
import hashlib
def get_hash(dictionary):
"""Takes a dictionary as input and provides a unique hash value based on the
values in the dictionary. All the values in the dictionary after
converstion to string are concatenated and then the HEX hash is generated
:param dic... | 2e69c397611510151996d152c4fc0b5573d62fdc | 3,644,674 |
def convert_to_tensor(value, dtype=None, device = None):
"""
Converts the given value to a Tensor.
Parameters
----------
value : object
An object whose type has a registered Tensor conversion function.
dtype : optional
Optional element type for the returned tensor. If missing, t... | fbae4561f3a38b8f72146f584ce07faf5096cdc1 | 3,644,675 |
def aggregate_extrema(features, Th, percentage = True) :
"""
Summary:
Function that tries to remove false minima aggregating closeby extrema
Arguments:
features - pandas series containing the extrema to be aggregated.
The series is of the form: Max, Min, Max, Max, M... | 6eeed204de4c39f8b66353595cbc04800bb1b176 | 3,644,676 |
from pathlib import Path
def load_embedded_frame_data(session_path, camera: str, raw=False):
"""
:param session_path:
:param camera: The specific camera to load, one of ('left', 'right', 'body')
:param raw: If True the raw data are returned without preprocessing (thresholding, etc.)
:return: The f... | 865d5151680b901fb0941cf487bd01836748f2c4 | 3,644,677 |
def reconstruct(edata, mwm=80.4, cme=1000):
"""
Reconstructs the momentum of the neutrino and anti-neutrino, given the
momentum of the muons and bottom quarks.
INPUT:
edata: A list containing the x, y, and z momentum in GeV of the charged leptons
and bottom quarks, i... | 31ecb3f8982f8026a4d0052778b53f1e76912252 | 3,644,678 |
import contextlib
import sqlite3
def run_sql_command(query: str, database_file_path:str, unique_items=False) -> list:
"""
Returns the output of an SQL query performed on a specified SQLite database
Parameters:
query (str): An SQL query
database_file_path (str): absolute path o... | 705584db31fd270d4127e7d1b371a24a8a9dd22e | 3,644,679 |
def zeta_nbi_nvi_ode(t, y, nb, C, nv, nb0, nbi_ss, f, g, c0, alpha, B, pv, e, R, eta, mu, nbi_norm = True):
"""
Solving the regular P0 equation using the ODE solver (changing s > 0)
t : time to solve at, in minutes
y : y[0] = nvi, y[1] = nbi, y[2] = zeta(t)
"""
F = f*g*c0
r = R*g*... | 5c30846bbb1bbf4c9a698dcec3627edece63e4bc | 3,644,680 |
from astroquery.irsa import Irsa
def get_irsa_catalog(ra=165.86, dec=34.829694, radius=3, catalog='allwise_p3as_psd', wise=False, twomass=False):
"""Query for objects in the `AllWISE <http://wise2.ipac.caltech.edu/docs/release/allwise/>`_ source catalog
Parameters
----------
ra, dec : float
... | 13308f9ae6ffd61c70588eb7ee7980cc1cd71578 | 3,644,681 |
import platform
def os_kernel():
"""
Get the operating system's kernel version
"""
ker = "Unknown"
if LINUX:
ker = platform.release()
elif WIN32 or MACOS:
ker = platform.version()
return ker | 1f528ae3710485726736fd9596efbc84b8bc76fd | 3,644,683 |
def make_nested_pairs_from_seq(args):
"""
Given a list of arguments, creates a list in Scheme representation
(nested Pairs).
"""
cdr = Nil()
for arg in reversed(args):
cdr = Pair(arg, cdr)
return cdr | 74aeeb54b648ccf231b6619800d1727fc7504cd4 | 3,644,686 |
import ast
def get_aug_assign_symbols(code):
"""Given an AST or code string return the symbols that are augmented
assign.
Parameters
----------
code: A code string or the result of an ast.parse.
"""
if isinstance(code, str):
tree = ast.parse(code)
else:
tree = code
... | d7ee8834b5d1aa0ac93369815206c95919907ae1 | 3,644,687 |
from typing import Dict
from typing import Any
def stack_dict(state: Dict[Any, tf.Tensor]) -> tf.Tensor:
"""Stack a dict of tensors along its last axis."""
return tf.stack(sorted_values(state), axis=-1) | d50b774b708715934f2c9998d7a477839c73593a | 3,644,688 |
def compact_float(n, max_decimals=None):
"""Reduce a float to a more compact value.
Args:
n: Floating point number.
max_decimals: Maximum decimals to keep; defaults to None.
Returns:
An integer if `n` is essentially an integer, or a string
representation of `n` red... | 827e49e05aaca31d497f84c2a8c8dd52cfad73d9 | 3,644,689 |
def resample_2d(X, resolution):
"""Resample input data for efficient plotting.
Parameters:
-----------
X : array_like
Input data for clustering.
resolution : int
Number of "pixels" for 2d histogram downscaling.
Default 'auto' downscales to 200x200 for >5000
samples, ... | 88cf98f82e0bf538df6e8a00b49f07eab75da1fe | 3,644,690 |
def is_mocked(metric_resource: MetricResource) -> bool:
"""
Is this metrics a mocked metric or a real metric?
"""
return metric_resource.spec.mock is not None | d76f6a0a04026245605176799346092d4a8eb994 | 3,644,691 |
def negative_embedding_subtraction(
embedding: np.ndarray,
negative_embeddings: np.ndarray,
faiss_index: faiss.IndexFlatIP,
num_iter: int = 3,
k: int = 10,
beta: float = 0.35,
) -> np.ndarray:
"""
Post-process function to obtain more discriminative image descriptor.
Parameters
-... | da20719f1b0b46fcfa4b7b11deb81aa2731abc5f | 3,644,692 |
def op_conv_map(operator):
"""Convert operator or return same operator"""
return OPERATOR_CONVERSION.get(operator, operator) | 91f6fea341b473e4965495af23cf957fef39234a | 3,644,693 |
def getGMapKey():
"""Return value for <gmapKey/> configuration parameter."""
return sciflo.utils.ScifloConfigParser().getParameter('gmapKey') | 0d4e36e39672b698b07d4be4d2cb0b6eff8a26c9 | 3,644,694 |
def _ro_hmac(msg, h=None):
"""Implements random oracle H as HMAC-SHA256 with the all-zero key.
Input is message string and output is a 32-byte sequence containing the HMAC
value.
Args:
msg: Input message string.
h: An optional instance of HMAC to use. If None a new zeroed-out instance
will be u... | 97aa326be593096a6441546a5d449b052ccc603a | 3,644,696 |
def get_unique_slug(model_instance, sluggable_field_name, slug_field_name):
"""
Takes a model instance, sluggable field name (such as 'title') of that
model as string, slug field name (such as 'slug') of the model as string;
returns a unique slug as string.
"""
slug = slugify(getattr(model_insta... | bbf1aa6108670f45b8a5b1a112f9b42a07344763 | 3,644,697 |
def get_precomputed_features(source_dataset, experts):
"""Get precomputed features from a set of experts and a dataset.
Arguments:
source_dataset: the source dataset as an instance of Base Dataset.
experts: a list of experts to use precomputed features from
Returns: A list of dicts, where ... | d89a932490f3c3ef4aca31301586ce628a720233 | 3,644,698 |
def _local_distribution():
"""
获取地区分布
"""
data = {}
all_city = Position.objects.filter(status=1).values_list("district__province__name", flat=True)
value_count = pd.value_counts(list(all_city)).to_frame()
df_value_counts = pd.DataFrame(value_count).reset_index()
df_value_counts.columns =... | 2f81365c66680c1b04805869e45118601ed769df | 3,644,699 |
def paradigm_filler(shared_datadir) -> ParadigmFiller:
"""
hese layout, paradigm, and hfstol files are **pinned** test data;
the real files in use are hosted under res/ folder, and should not
be used in tests!
"""
return ParadigmFiller(
shared_datadir / "layouts",
shared_datadir ... | e20ca1eebfeca8b4d54d87a02f723e21fd54c3bf | 3,644,700 |
def apply_scaling(data, dicom_headers):
"""
Rescale the data based on the RescaleSlope and RescaleOffset
Based on the scaling from pydicomseries
:param dicom_headers: dicom headers to use to retreive the scaling factors
:param data: the input data
"""
# Apply the rescaling if needed
pr... | 13bc94058aa725b59f017fc069408a9d279cd933 | 3,644,701 |
from itertools import product
def allowed_couplings(coupling, flow, free_id, symmetries):
"""Iterator over all the allowed Irreps for free_id in coupling if the
other two couplings are fixed.
"""
if len(coupling) != 3:
raise ValueError(f'len(coupling) [{len(coupling)}] != 3')
if len(flow... | 1e2d71edc68b8ecebfa3e09eae17e17a381d82b4 | 3,644,702 |
def poly_iou(poly1, poly2, thresh=None):
"""Compute intersection-over-union for two GDAL/OGR geometries.
Parameters
----------
poly1:
First polygon used in IOU calc.
poly2:
Second polygon used in IOU calc.
thresh: float or None
If not provided (default), returns the floa... | c033e654144bb89093edac049b0dfcd4cdec3d1a | 3,644,703 |
def score_file(filename):
"""Score each line in a file and return the scores."""
# Prepare model.
hparams = create_hparams()
encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir)
has_inputs = "inputs" in encoders
# Prepare features for feeding into the model.
if has_inputs:
inpu... | 62cac29e72bf5e7651cd8a258fb4151b6d7e1ff4 | 3,644,704 |
import responses
from renku.core.commands.providers.dataverse import DATAVERSE_API_PATH, DATAVERSE_VERSION_API
from renku.core.commands.providers.doi import DOI_BASE_URL
import json
import re
import urllib
import pathlib
def doi_responses():
"""Responses for doi.org requests."""
with responses.RequestsMock(... | 8e467910f2d9ad4df06ff0ecb11c0812e7dc3bb5 | 3,644,705 |
def lat_lng_to_tile_xy(latitude, longitude, level_of_detail):
"""gives you zxy tile coordinate for given latitude, longitude WGS-84 coordinates (in decimal degrees)
"""
x, y = lat_lng_to_pixel_xy(latitude, longitude, level_of_detail)
return pixel_xy_to_tile_xy(x, y) | 99e2a4b3d9dee41222b434768bed5501e7561a40 | 3,644,706 |
def update_inverse_jacobian(previous_inv_jac, dx, df, threshold=0, modify_in_place=True):
"""
Use Broyden method (following Numerical Recipes in C, 9.7) to update inverse Jacobian
current_inv_jac is previous inverse Jacobian (n x n)
dx is delta x for last step (n)
df is delta errors for last step (n... | 4f6a0e3e3bdc25132fae2aa1df9d0bbcdd73c3b1 | 3,644,707 |
def _ConvertStack(postfix):
"""Convert postfix stack to infix string.
Arguments:
postfix: A stack in postfix notation. The postfix stack will be modified
as elements are being popped from the top.
Raises:
ValueError: There are not enough arguments for functions/operators.
Returns:
A string of... | d69f4a503a84efedbf623cca24c496f5540d1b77 | 3,644,708 |
import re
def count_repeats_for_motif(seq, motif, tally, intervals=None):
"""
seq --- plain sequence to search for the repeats (motifs)
motif --- plain sequence of repeat, ex: CGG, AGG
intervals --- 0-based start, 1-based end of Intervals to search motif in
"""
if intervals is None: # use the ... | 2a29339555374aaeb70ea07872a81a56050a9f36 | 3,644,709 |
def press_level(pressure, heights, plevels, no_time=False):
"""
Calculates geopotential heights at a given pressure level
Parameters
----------
pressure : numpy.ndarray
The 3-D pressure field (assumes time dimension, turn off
with `no_time=True`)
heights : numpy.ndarray
... | 7cae6fe91eb1f6ad4171006633d04744909849c5 | 3,644,711 |
def valtoindex(thearray, thevalue, evenspacing=True):
"""
Parameters
----------
thearray: array-like
An ordered list of values (does not need to be equally spaced)
thevalue: float
The value to search for in the array
evenspacing: boolean, optional
If True (default), assu... | 5540023c77b544fbd91a724badf467981a0e0a5c | 3,644,712 |
def get_converter(result_format, converters=None):
"""
Gets an converter, returns the class and a content-type.
"""
converters = get_default_converters() if converters is None else converters
if result_format in converters:
return converters.get(result_format)
else:
raise ValueE... | 79ce7a728fb801922d672716aeb77dc76e270194 | 3,644,713 |
def _to_bool(s):
"""Convert a value into a CSV bool."""
if s.lower() == 'true':
return True
elif s.lower() == 'false':
return False
else:
raise ValueError('String cannot be converted to bool') | 3f6c31a07e7ba054e5c52f9d3c09fdd2f004fec5 | 3,644,715 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.