content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import configparser
def load_config():
"""Create default or load existing config file."""
cfg = configparser.ConfigParser()
if cfg.read(f"{datadir}/{program}.ini"):
return cfg
cfg["settings"] = {
"timezone": "Europe/Amsterdam",
"timeinterval": 90,
"debug": False,
... | f7cdc94807db3e5870db6b720f5bb89a10e343d8 | 65,700 |
def main():
"""Render the homepage."""
return render_template('index.html') | 1763707c63ef5525370e5d37241c434a8fc0a2ab | 65,701 |
def event_fraction(match_events, Ntimes, shape_list, Nfreqs=None):
"""
Calculates the fraction of times an event was caught by the flagger for
each type of event. Narrowband occupancy levels are calculated over the whole
spectrum, instead of just the channel a particular event may have belonged to.
... | 43d56bfe79246ef5e98beb08ad4ac5171ea44ae1 | 65,702 |
def make_hap_seqs(haps, options):
"""Makes a chromosome sequence for each haplotype"""
seq_h5 = tables.open_file(options.seq)
node_name = "/%s" % options.chrom
if node_name not in seq_h5:
raise ValueError("chromosome %s is not in sequence h5 file" % options.chrom)
seq_node = se... | 239de09be2bbe4b103fcdea2ab05cd2160f0c0bf | 65,703 |
import hashlib
def cluster_name(cluster, build):
"""Return or select a cluster name."""
if cluster:
return cluster
if len(build) < 20:
return 'e2e-%s' % build
return 'e2e-%s' % hashlib.md5(build).hexdigest()[:10] | d2f2fe3d434357237ba9c645f3253447fc4ac953 | 65,704 |
def task_returner(task) -> dict:
"""
* 根据不同的task状态生成不同的返回值
Args:
task:
Returns:
"""
if task.state == "PENDING":
response = {
"state": "empty task",
"info": {"current": 0, "total": 4, "status": "empty task"},
}
elif task.state == "FILL DATA":
... | 9d020f70d2f0a00e1a0042e9cba86e58d41f41e0 | 65,705 |
def group_sum_by_keys(ungrouped, group_key, sum_key):
"""Groups dictionaries by a common value and then returns the sum of
this a second value for each group."""
grouped = group_by_key(ungrouped, group_key)
summed = sum_groups_by_key(grouped, sum_key)
return summed | b648df157abe656bd97c9d6df9f70f7990dbbbb9 | 65,706 |
import os
def start_minio_server(request, get_image, get_test_dir, get_docker_network,
get_docker_context):
"""sudo docker run -d -p 9099:9000 minio/minio server /data"""
client = get_docker_context
envs = []
command = "server /data"
client.images.pull('minio/minio:latest'... | be04693adb8c337e3262c63775efb59c009218b9 | 65,707 |
import logging
import os
def load_narr_pressure_file(parameter, layer):
"""Loads a NARR pressure layer for the parameter
Args:
parameter <str>: The parameter to load
layer <str>: The pressure layer to load for the parameter
Returns:
[<col>[<row>]]: Two-Dimensional list of the NARR... | 81ab2d8cb945e42f8cb761427d00691fb5a78c55 | 65,708 |
import os
def get_creds_file_path(file_name: str) -> str:
"""
Найди файл креденшиалс в проекте.
:param file_name: Имя файла
:return: Путь к файлу
"""
search_folders = [
os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), 'credentials'),
os.path.abspath(os.... | 369f095011be11a9f731fb18e4c375c5b37830b5 | 65,709 |
import ipaddress
def validate_ip(ip):
"""
Checks if an IP address is valid for lookup.
Will return False if an IP address is reserved or invalid.
Resource: https://en.wikipedia.org/wiki/Reserved_IP_addresses
"""
try:
return not ipaddress.ip_address(ip).is_private
except Value... | 5d10a41e6bc6d645cbef24e8e4128baaf67aa997 | 65,710 |
def flatten_dct(obj, separator):
"""
Flattens an objects so deep keys and array indices become concatinated strings
E.g. {a: {b: [1, 3]}} => {'a.b.0': 1, 'a.b.1': 2}
@param {Object} obj The object to flattened
@param {Object} separator Key segment separator, probably either '.' or '__'
@returns ... | 3a25e49f05c6fbe5ada9bec5276744be3e888c45 | 65,711 |
def _connect_to_environment(port, settings):
"""Helper function for connecting to a running dm_memorytask environment."""
if settings.level_name not in MEMORY_TASK_LEVEL_NAMES:
raise ValueError(
'Level named "{}" is not a valid dm_memorytask level.'.format(
settings.level_name))
server_add... | 5ca6e825d685f6186a9d0ea272c0621377e9d304 | 65,712 |
def circlemaker(r=10.):
"""
Creates circle mask of radius r.
"""
# Based on <https://stackoverflow.com/questions/10031580/
# how-to-write-simple-geometric-shapes-into-numpy-arrays>
# Mask grid extent (+1 to ensure we capture radius).
rhext = int(r) + 1
xx, yy = np.mgrid[-rhext:rhext + ... | 4af623ca8d822dfdaab38eed34867a102d46e164 | 65,713 |
def rupture_name_to_id_ix(
ensemble: "gm_data.Ensemble",
erf_ffp: str,
rupture_names: np.ndarray,
):
"""Convertes the rupture names to rupture_id_ix values"""
return rupture_id_to_ix(ensemble, rupture_name_to_id(rupture_names, erf_ffp)) | 33ee98f521892235adb71c07553377029f097c10 | 65,714 |
def query_datasets():
"""Query datasets a user has access to."""
if not Config.ALLOW_DIRECT_QUERY:
abort(404)
username = get_jwt_identity()
query = request.get_json()
current_app.logger.debug("Received query request '{}' from user '{}'.".format(query, username))
try:
datasets = q... | 988105f396e2c16a1aa23d5aa41bc4489f3d25a4 | 65,715 |
import six
def convert_unicode(text):
"""If the provided string is a binary string, this filter converts it
to UTF-8 (unicode).
"""
if isinstance(text, str) and six.PY2:
return text.decode("utf8")
else:
return text | 5fc868e11da09444bc285c251e8cbae7dc502d77 | 65,716 |
def extract(opts):
"""
support extraction (checkout) of a mercurial cache into a build directory
With provided extraction options (``RelengExtractOptions``), the extraction
stage will be processed. A Mercurial extraction process will populate a
working tree based off the cached Mercurial repository... | 68f57f6f57b5811d21807c4c45766fba9e7adcb5 | 65,717 |
import time
def eval_metrics(model_ova, X, y, pred, cert_tw, time_cert, deltas, weak_learner, eps_eval, log, n_trials_attack, check_bounds=True):
""" Evaluation metrics for validation and test sets. """
if X.shape[0] == 0: # if no examples provided (e.g., the validation set is empty)
return 1.0, 1.0,... | 5296082cd9cfc070d936fb6000521daacf505a32 | 65,718 |
import getpass
def get_image(
image_name: str,
client: docker.DockerClient,
try_pull: bool = True,
try_login: bool = True,
):
"""Try to get an image, if it is not present try to pull it, if that
doesn't work either try to login and pull again.
Parameters
----------
image_name : st... | 8f1e8ff6085154f6ceeee0d9efc7e123708d8491 | 65,719 |
def graph_from_edgelist(E, directed=False):
"""Make a graph instance based on a sequence of edge tuples.
Edges can be either of from (origin,destination) or
(origin,destination,element). Vertex set is presume to be those
incident to at least one edge.
vertex labels are assumed to be hashable.
"""
g = Grap... | 42831be2a7a868ec86c5244cb5e2faf221f029ea | 65,720 |
def init_symbol_table():
"""
Returns a Python dictionary mapping strings (symbol names) to
integers (address refered to by that symbol), initialized with
all of the Hack assembly predefined symbols.
"""
predefined_symbols = {
'SP': 0,
'LCL': 1,
'ARG': 2,
... | 7a64be8add2565d3dff5302df82088af7b3383e6 | 65,721 |
from operator import mul
def product_using_accumulate(n, term):
"""An implementation of product using accumulate.
>>> product_using_accumulate(4, square)
576
>>> product_using_accumulate(6, triple)
524880
"""
"*** YOUR CODE HERE ***"
return accumulate(mul, 1, n, term) | e9b250ac90bfc6d330fb0510e48d3af391fc7508 | 65,722 |
def _get_balena_os_version(etc_issue_contents):
"""
Return a balenaOS version string such as "2.53.0", given the contents
of the "/etc/issue" file in the etc_issue_contents argument.
"""
m = match('balenaOS (.+?) ', etc_issue_contents)
return m[1] if m is not None else "" | 8d33b37c33c7ff29bf66cf0fc2f7297a4de336aa | 65,723 |
import string
def AddExonInformation(sequence,
exons,
gap_char="-",
mask_lowercase=False,
mask_char="x"):
"""add exon information to an aligned string.
lowercase characters will be masked.
"""
new_chars = []
... | 16f858e5ce62e15d929624ef15a934f4776ed3cc | 65,724 |
def get_sdp_path(doc, subj: int, obj: int):
"""
'Convulsions that occur after DTaP are caused by a fever, and fever may cause headache.'
----> [Convulsions, caused, by, fever]
Get shortest dependency path without networkx lib. Usues spacy's LCA (lowest common ancestor) matrix
Adapted from:https:... | 23f994d17e3b496fe6d8d8dcd06527675c9f0795 | 65,725 |
def hookable(hookable_method):
"""Decorator which checks for corresponding hooks and calls them if they exist
When this decorator is applied to a method, it checks for the existence of `_before_method()`
and `_after_method()` hooks, and calls them before/after the correspdoning method if they do.
This... | 10d9e879feabf73bcfb41615ebe2c1df86a7e395 | 65,726 |
def is_integer(val):
"""Returns whether the given value is an integer.
Args:
val (object): value to check
Returns:
``True`` if the given value is an integer, otherwise ``False``.
"""
try:
val += 1
except TypeError:
return False
return True | ba038448c04b3072c08547c963aa24bf3cbc97b2 | 65,727 |
import re
from typing import Counter
def grant_permission_to_tag(session, tag_id, permission_id, argument=''):
# type: (Session, int, int, str) -> bool
"""
Grant a permission to this tag. This will fail if the (permission, argument) has already
been granted to this tag.
Args:
session(mode... | 57a25a5e2d5db43f60d15ba81062919d6ca1dd28 | 65,728 |
def split_one_block(data, expected_hdr=None):
"""Extract a sequence of MPEG audio frames from a single block of data.
Args:
data: A data buffer containing the data to be split into MPEG frames.
Returns:
A list of (hdr, data_buffer) pairs.
If 'hdr' is None, data buffer contains non-MPEG-a... | 3ebc217d85772f926732f1f79e1f6b7d36b924a6 | 65,729 |
def plot_acq_function_2d(
acq_func: AcquisitionFunction,
mins: TensorType,
maxs: TensorType,
grid_density: int = 20,
contour=False,
log=False,
title=None,
xlabel=None,
ylabel=None,
figsize=None,
):
"""
Wrapper to produce a 2D/3D plot of an acq_func for a grid of size grid... | 06a7805f4180e82b957c62f5532c48bd8f245777 | 65,730 |
async def get_task(
user: UserEntity = Depends(dep_current_user),
project_name: str = Depends(dep_project_name),
task_id: str = Depends(dep_task_id),
):
"""Retrieve a task by its ID."""
task = await TaskEntity.load(project_name, task_id)
await task.ensure_read_access(user)
return task.as_us... | 36b070ad55d39c228d28f22fc53c879efee7a083 | 65,731 |
from sys import platform as _platform
import _winreg
import winreg as _winreg
def Registry(varname, setvalue=None):
"""Read value from the registry or set a value. It will use HKEY_CURRENT_USER so no admin rights required."""
if _platform == "linux" or _platform == "linux2":
# Ubuntu, Linux or Debian... | 0002b878cf7c1947981d7d2743e0c0f59945d167 | 65,732 |
from typing import Callable
def compute_t_level(task_graph: TaskGraphBase, cost_fn: Callable[[Task, Task], float]):
"""
Calculates the T-level (the earliest possible time to start the task).
"""
t_level = {}
for task in task_graph.tasks.values():
t_level[task] = 0.0
graph_dist_crawl(t... | 2d38c28b7cdd88ee6473a09219c3f3185cde5269 | 65,733 |
from typing import Optional
from typing import Dict
from typing import Any
from typing import Callable
import html
from typing import List
def get_layout(
fit: nonlinear_fit,
name: str = "Lsqfit GUI",
meta_config: Optional[Dict[str, Any]] = None,
meta_values: Optional[Dict[str, Any]] = None,
use_d... | 169cddd6ba23419fcad2c343ad3e87c730828f54 | 65,734 |
def compute_std_and_max_point(data_array, selection_keys=None):
"""
Compute the standard deviations and maxima points for a subset of keys of a dictionary.
:param data_array: dictionary containing the data for the computations
:param selection_keys: list containing the keys to use. The entire dictionary... | c417edb86fc7cc935fbe9993ddf0ad7ba3ae8787 | 65,735 |
def calculate_income_tax(income: float) -> float:
"""Use this function for calculating the income tax for the users income.
This function is used for just calculating the income tax for a given income and
returning both the income tax and the leftover income.
:param income: the users pre-tax income.
... | f5e9aaa954ad5aac2008eb9c39d4b66b9ebdd04b | 65,736 |
def short_client():
"""This client is to be used with the dev server set to issue tokens
with very short expirations in order to test out the expired token
handling code
"""
return DocumentCloud(
username=USERNAME,
password=PASSWORD,
base_uri=BASE_URI,
auth_uri=AUTH_U... | 87c082419de466bf4cda99b68af0eb54c230828c | 65,737 |
def imshow(image, ax=None):
"""
Image show given a tensor as input
:param image: (torch tensor) the image data as a Torch tensor
:param ax: (matplotlib Axis) not required, will be used if given or created otherwise
:return: (matplotlib Axis)
"""
if ax is None:
fig, ax = plt.subplots(... | 58abd325dad41a3e3a2fde63a9ed5e57d47788ac | 65,738 |
def __format_value(arg: Primitive) -> str:
"""Formats a value to a string. If the value is a string,
it will be enclosed with quotes.
Args:
arg (Primitive): The value to format.
Returns:
str: The formatted argument.
"""
val: str = str(arg)
if arg is str:
val = '"... | 622722c4046c6c8482b9a655d1e001aca0a570b2 | 65,739 |
def compute_mean_var_f(
x, Xsamples, Ysamples, l, sigma, sigma0, NKInv=None, fullcov=False, dtype=tf.float32
):
"""
NKsampleInv = inv(KXsampleInv + eye(n)*sigma0)
l: 1 x d
Ysamples: m x 1
Xsamples: m x d
x: n x d
return: mean: n x 1
var : n x 1
"""
if NKInv is None:
... | 8e7698e706cbd410f08e1b959b42d90fc6e1027a | 65,740 |
import logging
from sys import version
def rest_interface_parser(list_subcommands, debug):
""" interface module for rest API
buld to handle stacked commands """
response_list = []
try:
for dict_subcommand in list_subcommands:
#nprint("Commands Recieved: %s" % dict_subcommand, ... | 2ef157aecea04992ffc88e334a0f7ed15e2b1587 | 65,741 |
from typing import List
from typing import Tuple
def read_overlap_data(config: DictConfig, mo_paths: List[str]) -> Tuple[Matrix, Matrix]:
"""Read the Molecular orbital coefficients."""
mos = retrieve_hdf5_data(config.path_hdf5, mo_paths)
# Extract a subset of molecular orbitals to compute the coupling
... | f295cd8e1c7cb4f19eb2621c9c4d6c8a9e35cacc | 65,742 |
import random
def random_contig_length(invalid_data):
"""
Generate Random Contig Length
return: int.
"""
return random.randint(10,50000), global_valid_data | 8e27074408e5347c2d385f2078725efa23189503 | 65,743 |
def average_gradients(total_grads_and_vars):
"""Calculate the average gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
total_grads_and_vars: List of lists of (gradient, variable) tuples.
The outer list ... | 7354f574dcbf9478c5081508232cadd9e76a8217 | 65,744 |
import argparse
def arguments():
""" Process CLI arguments """
description = 'Simple script to create GR application rules. Because I am lazy.'
parser = argparse.ArgumentParser(description=description)
parser.add_argument("-l", "--List", action="store", help="CSV of Plans", required=True)
return ... | c7c1de792736e15ead6f3c51ffb6b136ceb42eab | 65,745 |
import argparse
from pathlib import Path
def get_scenario(config: NestedNamespace, args: argparse.Namespace) -> Scenario:
"""Extract the scenario from the parser and config.
This function the following options be part of the parser.
args.scenario
args.targets
args.targets-default_opt_levels and
... | 297a1143ebf0d28e166d6309558439b4be7a2472 | 65,746 |
def add_links(self, value):
"""
This creates a Link header from the links
Parameters
----------
self : lib.schema.riak.objects.Link
The Link schema object
value : dict
The headers of the request to add the links to
"""
links = getattr(self, 'links', [])
if links:
... | 3d507ce928b227399ca325d5a55cab6b5ae07791 | 65,747 |
def count_all(text, content):
"""
统计数量
:param text:
:param content:
:return:
"""
word_dict = {}
word_list = [word.split(',') for word in content]
for item in word_list[0]:
if item not in word_dict:
word_dict[item] = 1
else:
word_dict[item] +=... | 26bd5e471927219a33e42e3188c983e2034b2e7b | 65,748 |
def children(level, idx):
"""
Return all the children of the Healpix pixel idx at level (in nested format)
:param level: Resolution level
:param idx: Pixel index
:return: All the parents of the pixel
"""
chld = []
for ind in range(4):
chld.append((level + 1, 4 * idx + ind))
... | ef1a127270a689fc7c05eb2f2b40abb7e6efc2ce | 65,749 |
import hashlib
from datetime import datetime
import logging
def api_request(url, cache_duration=604800):
"""Returns a function that when called results in parsed JSON data or None."""
cache_key = 'location/v2:{}'.format(hashlib.sha256(url).hexdigest())
# Attempt to get a cached response before calling the... | 300bf81b6d4dfce0cf9d1748518d66f2d6618424 | 65,750 |
def _ProcessSetLine(tline, expvals, card, errmsg):
"""process the line and obtain the cards names and values"""
# tline:: is the text line to be processed
# expvals:: is the range [a,b] of expected values
# card:: name of the card
# errmsg:: additional error message added to InputCardError
... | 2c841bba5070c9fed418d41903542db7812e3902 | 65,751 |
def update_courses(request_ctx, account_id, course_ids, event, **request_kwargs):
"""
Update multiple courses in an account. Operates asynchronously; use the `ProgressController#show <https://github.com/instructure/canvas-lms/blob/master/app/controllers/progress_controller.rb>`_
to query the status of an o... | 9108ea18ed9f7b3876f3d590212f76ddd09c9aba | 65,752 |
def data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_get(uuid, node_uuid, node_rule_group_uuid, inter_rule_group_uuid): # noqa: E501
"""data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_r... | a6d89c8711fa2c5efc5e5c3154b7beb8e26bfa8f | 65,753 |
def get_namespaces(return_separator=False, return_root=False):
"""returns namespaces
Args:
return_separator(bool): return separator
Returns:
list of unicode: namespaces
"""
cmds.namespace(set=ROOT_NAMESPACE)
namespaces = set()
if return_root:
namespaces.add(ROOT_NAM... | fa0122c31100fd994ffc305ae2a4719e660ecb01 | 65,754 |
import os
def setup_path(file):
"""Return an absolute path to the provision tempate file specified by file"""
return os.path.join(samba.param.setup_dir(), file) | b7b20b8cfdaa408be3c802c64f5ceec54adc0746 | 65,755 |
def toBytes(text, encoding=DEFAULT_ENCODING):
"""
Converts the inputted text to base string bytes array.
:param text | <variant>
:return <str> || <bytes> (python3)
"""
if not text:
return text
if not isinstance(text, bytes_type):
text = text.encode(encodin... | 1220ba953b2a0bf4d701c058f9626a340aefef51 | 65,756 |
def knapsack_iterative(items, bag_capacity):
"""
Uses dp to find optimal solution to the one-zero (either take or leave)
knapsack problem
:param items: assumed given as a tuple of (space_it_takes_up, value)
:param bag_capacity: given as an integer of the capacity of the bag
:return: maximised va... | 65872a23762d314dac2c357ba0941142237eaedb | 65,757 |
import scipy
def my_rq(M):
"""RQ decomposition, ensures diagonal of R is positive"""
R,K = scipy.linalg.rq(M)
n = R.shape[0]
for i in range(n):
if R[i,i]<0:
# I checked this with Mathematica. Works if R is upper-triangular.
R[:,i] = -R[:,i]
K[i,:] = -K[i,:]
... | 31a23cbb2c673d00d753ab92de4e369167b3930a | 65,758 |
def change_time_units(times, value, operation='divide'):
"""Change the units of timestamps.
Parameters
----------
times : 1d array
Vector of timestamps to update.
value : float
Value to divide / multiply by.
operation : {'divide', 'multiply'}
Operation to apply.
"""
... | f698d78a68d5056cf3864c47b29ed0e347b5aa4c | 65,759 |
from ..database import UserVote
def vote_exists(user, uri):
""" Check if a vote from this user for this track already exists. """
vote = db.session.query(UserVote).filter(UserVote.uid == user.id, UserVote.uri == uri).first()
return vote | 160c2b18a2dc7f880c800e2e436db9884bd97e9e | 65,760 |
from typing import Optional
from typing import Dict
from typing import Any
import time
import requests
def get_request_time(url: str, params: Optional[Dict[str, Any]] = None) -> Optional[float]:
"""timeit GET request"""
try:
start = time.monotonic()
requests.get(url, params=params)
ret... | ae99e5f706aed51c17634f92125cb2f0fe66be76 | 65,761 |
def zero_(x):
"""
**Notes**:
**This API is ONLY available in Dygraph mode**
This function fill the Tensor with zero inplace.
Args:
x (Tensor): ``x`` is the Tensor we want to filled with zero inplace
Returns:
x (Tensor): Tensor x filled with zero inplace
Examples:
... | 11eec580f6206086c6e0a8397187a33996849fed | 65,762 |
def build(options, is_training=False):
"""Builds a Model based on the options.
Args:
options: a model_pb2.Model instance.
is_training: True if this model is being built for training.
Returns:
a Model instance.
Raises:
ValueError: if options is invalid.
"""
if not isins... | 7cd3c00ad4fb661e2e1e9fb87e47666c8fd6a8e5 | 65,763 |
import re
def get_cluster_info(host, port):
"""
return dict with info about nodes in cluster and current version
{
'nodes': [
'IP:port',
'IP:port',
],
'version': '1.4.4'
}
"""
client = Telnet(host, int(port))
client.write(b'version\n')
re... | 0d4d79738c31ed770164652764577ad31690c101 | 65,764 |
def get_alpha(A,VMR,rhoe,ze):
"""
Calculate Absorption optical depth profile
A - absorption coefficient [m2/molecule]
VMR - trace gas mixing ratio [vol/vol, dimensionless]
rhoe - air number density [molecules/m3]
ze - profile altitude [m]
"""
# convert vmr to molecules/m3
nxe = VMR... | 88328687e96b535e202c5a1b5421ed09ae25adc4 | 65,765 |
import random
import string
def generate_callback_token():
"""
Generate a token and store it in the callback token file
:return: the token
"""
token = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(64))
with open(callback_token_file, "w") as fp:
fp.write(... | 7ea24be7c724fbf9eb783da89a5677b2caa455d2 | 65,766 |
import glob
import os
def Use_Model(model_path, em_folder, ho_folder, glob_str, export_path='X:\\BEP_data\\Data_Internal\\Predict_set\\',
only_EM=False,
normalize=False):
"""
This function loads a model that has been made, and saves predictions from the data it has been given. Supp... | b1872fbf38453d67d8120db22a0666f390d9cb4b | 65,767 |
from typing import Callable
import os
from operator import setitem
def from_folder(rootdir:str, func:Callable=None, filt:Callable=None) -> dict:
"""Create a nested dictionary representing the structure of a folder.
Arguments
---------
rootdir: path of a root folder
func: function processing the c... | 3fed9759177a3a4cddb2a8ec8dc37eea01a68cf7 | 65,768 |
def check_AIC_base10_checksum(AIC):
"""Check if a string checksum char in the base10 representation is correct.
Parameters
----------
AIC : str
The string containing the code to check
Returns
-------
bool
True if the checksum is correct.
"""
return AIC[-1] == calc_A... | 7a5b8f37bf2737b1a78050489d9212e0715b3ef0 | 65,769 |
import json
def getUrnJson(data):
"""Returns URN to entity in JSON data"""
decodedJson = json.loads(data)
return decodedJson["urn:lri:property_type:id"] | af1761acb9322f295af3500cc4ecc519da16d7b1 | 65,770 |
import math
def _uiconm(x, window_size):
"""
Underwater image contrast measure
https://github.com/tkrahn108/UIQM/blob/master/src/uiconm.cpp
https://ieeexplore.ieee.org/abstract/document/5609219
"""
plip_lambda = 1026.0
plip_gamma = 1026.0
plip_beta = 1.0
plip_mu = 1026... | 84ffa2d9291cbb926a1d123a6ff93fe2974d14ca | 65,771 |
from re import T
def _are_equal_or_one_is_empty(l1: tuple[T, ...], l2: tuple[T, ...]) -> bool:
"""Determine whether the two tuples are equal or one is the empty tuple."""
return (
l1 == l2 or (len(l1) == 0 and len(l2) > 0) or (len(l1) > 0 and len(l2) == 0)
) | 1c6e5319f42a9006558c16469997f26011939100 | 65,772 |
def type_to_str(_type : type | tuple, sep : str =" or "):
"""
Converts type or tuple of types to string
e. g. <class 'bin_types.functions.Function'> -> function
For tuples will separate types with argument sep, standard sep is " or "
"""
if isinstance(_type, tuple):
types = []
... | 04589e24aef9db1d302b8d4d439d7d5e1ba70e49 | 65,773 |
def scale(X):
"""データ行列Xを属性ごとに標準化したデータを返す"""
# 属性の数(=列の数)
col = X.shape[1]
# 属性ごとに平均値と標準偏差を計算
mu = np.mean(X, axis=0)
sigma = np.std(X, axis=0)
# 属性ごとデータを標準化
for i in range(col):
X[:,i] = (X[:,i] - mu[i]) / sigma[i]
return X | 61e2d935a08262d7c669719eb3055cd6704d1405 | 65,774 |
def make_storage(storage_type: str) -> Storage:
"""Storage factory."""
return STORAGE_MAP[storage_type]() | c652973660735fbca28bfc5921e54f499ae5e29f | 65,775 |
import json
def load_evaluate_metrics(workspace: str):
"""Load and return metrics."""
filepath = workspace_path(workspace, "metrics/evaluate_metrics.json")
with open(filepath, "r") as f:
data = json.load(f)
data["loss"] = float(data["loss"])
data["accuracy"] = float(data["accuracy"])
... | 33e98e8bbfcf9dd4a0707ed1c820250bffa00d9e | 65,776 |
def get_total_pages(items):
"""
returns the total number of pages for a list of serialized items
"""
items_per_page = 12
if len(items) % items_per_page == 0:
return int(len(items) / items_per_page)
pages = int(len(items) / items_per_page + 1)
return pages | 8e2b0a33f6c462e3f38d24643968bd5ed265d1a9 | 65,777 |
import time
def file_upload_to(instance, filename):
"""
文件上传相对路径
:param instance: 实例
:param filename: 文件名
:return: 上传的文件路径
"""
# 传过来的实力,需要有个user_id的值,用户ID
print(instance.user_id)
name = 'file/{}/{}_{}'.format(time.strftime('%Y/%m'), instance.user_id, filename)
return name | a24fc844c6d469cd66af4a5ade3e526781fc53c7 | 65,778 |
def dot(v, u):
"""v and u are vectors. v and u -> list"""
vx, vy = v[0], v[1]
ux, uy = u[0], u[1]
dotproduct = vx*ux + vy*uy
return dotproduct | b9a8794ff98787b7ae8e8c1420a375360abb34fa | 65,779 |
def parse_update(expression):
""" parsing something like "update some_table set (x,y,z) where a = 30;" """
pattern = 'update\s+(.*?)set(.*?)\s*(where\s(.*?)\s*)?;'
m = match(expression,pattern)
tables = m.group(1)
columns = map(str.strip,split_if_not_none(m.group(2), ","))
clauses = split_if_not... | 53e5e65410ab8c350c325528b0e01cc5d23a4a3d | 65,780 |
from typing import OrderedDict
def map_ascii_to_range_ordered(range_length):
"""
performs the same calculation as above, with difference of ordering the output as it came in
>>> map_ascii_to_range_ordered(5)
>>> OrderedDict([('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4)])
:param range_length: l... | 07934277e7a920dad4bb0a3512e7efa2219ef85a | 65,781 |
def inv_entry_to_path(data):
"""
Determine the path from the intersphinx inventory entry
Discard the anchors between head and tail to make it
compatible with situations where extra meta information is encoded.
"""
path_tuple = data[2].split("#")
if len(path_tuple) > 1:
path_str = "#... | 2c36c3a5755d7f82da534d417cc8350c96e0360a | 65,782 |
def construct_feature_columns(input_features_num=None, input_features_cat=None,
feature_type=['numerical','cat_with_identy','cat_with_hash_bucket',
'cat_with_vocab_file','cat_with_vocab_list']):
"""Construct the TensorFlow Feature Columns.
Args:
input_features_num: The na... | c60c66d4632cdd01af0777ac1dbbcd5525a030c8 | 65,783 |
import bisect
def where(start,end,arr):
"""Find where the start location and end location indexes in an array"""
astart = bisect.bisect_left(arr, start)
aend = bisect.bisect_right(arr[start:], end) + start
return astart, aend | c942a3d8f681a81e8bb473724e25f5dd980aa338 | 65,784 |
import requests
def twitter_data(access_token, screen_name):
"""
This function gets information about user from Twitter.
"""
base_url = "https://api.twitter.com/"
search_headers = {
'Authorization': 'Bearer {}'.format(access_token)
}
search_params = {
'screen_name': screen... | f72a06f9939544d45db2b0e09a0bba02a1f00294 | 65,785 |
def get_config():
"""Get the default hyperparameter configuration."""
config = ml_collections.ConfigDict()
config.batch_size = 128
config.test_batch_size = 1000
config.epochs = 20
config.seed = 1
config.train_mc_iters = 2500
#config.train_mc_iters = 2500
config.s_init = 0.27
config.eta = 1.
con... | 727ea85ca308a7b8905c9a66659e47ac631764e7 | 65,786 |
from typing import get_args
import json
def setup_model_and_optimizer(model, optimizer, train_dataset_provider, lr_scheduler_builder):
"""Setup model and optimizer."""
args = get_args()
if optimizer is None:
optimizer = get_optimizer(model)
lr_scheduler = get_learning_rate_scheduler(optimizer,... | 48ac38ce06c47ed02a8d829ebff848d015af5afc | 65,787 |
import os
def update_kwargs_for_processing(destination: str, args: list, kwargs: dict, settings: dict = None, force_epsg: bool = False):
"""
Build a dictionary of updated settings for an existing processing action, use this with FqprActionContainer to
update the action.
Parameters
----------
... | 16eb6a6e51977e2b87b2c5551e461c58d99422ea | 65,788 |
def win_segmentation(x,n_win,overlap):
"""
Segment time series x into windows of n_win points with an overlap of overlap
Parameters
----------
x: ndarray of shape (samples,)
Time series
n_win: integer
Number of data points per window
overlap: float
Percentage o... | d97e3d6ef5a3db958141eeaeae95f5b4dff54217 | 65,789 |
def simple_similarity_cost(a, b, hparams=None):
"""Experimental simplified cosine distance loss.
TODO: Consider making k a function of batch size to control weighting of
importance of self- vs non-self distances.
"""
if hasattr(hparams, "cs_balanced_k"):
k = hparams.cs_balanced_k
with tf.name_sc... | 535944d19dd72e998a69f31b08ca94e7c95ad349 | 65,790 |
def decode_powerset_labels(y):
"""Decode the label and return a binary array. Assumes the labels are encoded
the in the FastTest format: __label__x"""
def decode_label(label):
split_label = label.replace('__label__', '').split('_')
return list(map(_int_or_str, split_label))
return np.arr... | df4753d596fbbf5ffee8931bfbe2365fc8955f70 | 65,791 |
from typing import Optional
from typing import Dict
def get_book_titles(
book: Book, version: Version = DEFAULT_VERSION
) -> Optional[BookTitles]:
"""
Given a book of the Bible and optionally a version return the book title.
:param book:
:param version:
:return: the book title
"""
try... | 1cba886d5ba9c8950239ef6af51a65681c6708d7 | 65,792 |
def mime(mime_id, cursor=None):
"""
Query for mime information from the repository.
"""
cursor = check_cursor(cursor)
cursor.execute('''
SELECT *
FROM mimes
WHERE id = %s
''', (mime_id,))
return cursor | b8d1443badaa8465f3d2df103c9f9a42fc3ad5ea | 65,793 |
import time
def recognize_image(img, config):
"""Receives a numpy image and a config parameter. Returns a string recognized text"""
img = np.array(img)
img = pre_img.get_grayscale(img)
blurred1 = cv2.medianBlur(img, 3)
blurred2 = cv2.medianBlur(img, 51)
divided = np.ma.divide(blurred1, blurred... | 0eb1795245f17ba462dbbd6820917a9529e904a2 | 65,794 |
def Imu_I0c1c2c3c4(mu, c):
"""
I(mu, c) where c = (I0, c1, c2, c3, c4)
"""
return c[0]*(1-c[1]*(1-mu**0.5)-c[2]*(1-mu)-c[3]*(1-mu**1.5)-c[4]*(1-mu**2.)) | 6553deaff09f4a3e00364b271095b5e80472b3a1 | 65,795 |
def linear_chain_crf(input, label, param_attr=None, length=None):
"""
:api_attr: Static Graph
Linear Chain CRF.
${comment}
Args:
input(${emission_type}): ${emission_comment}
label(${label_type}): ${label_comment}
Length(${length_type}): ${length_comment}
param_attr... | 70fd28b436cdf5ade1762a254b76a9303efdb7e9 | 65,796 |
def centroid_linkage(active_sites,min_clusters,printMe=False):
"""
Centroid Linkage clustering
This implementation builds until it hits min_clusters. Dendrograms not supported.
Inputs: List of ActiveSite instances and number of clusters
Outputs: List of labels and cluster centers
"""
... | 45e738dab93e504a673b37666cb73152db7c7730 | 65,797 |
def add_due_reservations(create_user, add_due_flights):
"""Fixture to add reservations"""
user = create_user(USER)
reservations = [{
"flight": add_due_flights[0],
"seat_number": "E001",
"type": "ECO",
"made_by": user,
}, {
"flight": add_due_flights[1],
"s... | 92f08e064a945f4222755c8cc01ab9afe6e0555b | 65,798 |
def isinstance_qutip_qobj(obj):
"""Check if the object is a qutip Qobj.
Args:
obj (any): Any object for testing.
Returns:
Bool: True if obj is qutip Qobj
"""
if (
type(obj).__name__ == "Qobj"
and hasattr(obj, "_data")
and type(obj._data).__name__ == "fast_cs... | 3c140e012d0df97852e84c50a37e6464e107fe2e | 65,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.