content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_devp2p_cmd_id(msg: bytes) -> int:
"""Return the cmd_id for the given devp2p msg.
The cmd_id, also known as the payload type, is always the first entry of the RLP, interpreted
as an integer.
"""
return rlp.decode(msg[:1], sedes=rlp.sedes.big_endian_int) | bd930be7205871183ac9cb4814ae793f5524964d | 26,926 |
def custom_cached(name, *old_method, **options):
"""
decorator to convert a method or function into a lazy one.
note that this cache type supports expire time and will consider method inputs
in caching. the result will be calculated once and then it will be cached.
each result will be cached using ... | a6732fee6cd484068d3171079bf4989d5367adbc | 26,927 |
def _full_url(url):
"""
Assemble the full url
for a url.
"""
url = url.strip()
for x in ['http', 'https']:
if url.startswith('%s://' % x):
return url
return 'http://%s' % url | cfb56cf98d3c1dd5ee2b58f53a7792e927c1823f | 26,928 |
from rx.core.operators.replay import _replay
from typing import Optional
import typing
from typing import Callable
from typing import Union
def replay(mapper: Optional[Mapper] = None,
buffer_size: Optional[int] = None,
window: Optional[typing.RelativeTime] = None,
scheduler: Optional[... | 8a5ff1cbbc5c12d63e0773f86d02550bf5be65c4 | 26,929 |
import io
import torch
def read_from_mc(path: str, flush=False) -> object:
"""
Overview:
read file from memcache, file must be saved by `torch.save()`
Arguments:
- path (:obj:`str`): file path in local system
Returns:
- (:obj`data`): deserialized data
"""
global mclient... | c606b131ba3d65c6b3dd320ae6a71983a79420c8 | 26,930 |
import wave
import struct
def write_wav(file, samples, nframes=-1, nchannels=2, sampwidth=2, framerate=44100, bufsize=2048):
"""
Writes the samples to a wav file.
:param file: can be a filename, or a file object.
:param samples: the samples
:param nframes: the number of frames
:param nchannels... | ec38069d59dde8dafd5aa98a826ee699ded15b29 | 26,931 |
async def check_login(self) -> dict:
"""Check loging and return user credentials."""
session = await get_session(self.request)
loggedin = UserAdapter().isloggedin(session)
if not loggedin:
informasjon = "Logg inn for å se denne siden"
return web.HTTPSeeOther(location=f"/login?informasjon... | 48dd910c143e4ca8f90d8d3da2be2ce6ed275b1b | 26,932 |
from typing import Callable
def get_knn_func_data_points(
data_points: np.ndarray,
pairwise_distances: np.ndarray = None,
approx_nn: ApproxNN = None,
metric: Callable = fastdist.euclidean,
metric_name: str = "euclidean",
) -> KnnFunc:
"""
Gets a K-nearest neighbour callable for data points... | 897289271aef24610dc949fefd14761a3bea4322 | 26,933 |
from aiida import orm
def get_database_nodecount():
"""Description pending"""
query = orm.QueryBuilder()
query.append(orm.Node)
return query.count() | dcb71a022d36c2602125cbba4dccd1c7ccb16281 | 26,934 |
def shower_profile(xdat, alpha, beta, x0):
"""Function that represents the shower profile.
Takes in the event and predicts total gamma energy using alpha and beta to fit.
Described in source in README.
shower_optimize() fits for alpha and beta.
"""
#measured_energy = event.measured_energy
#... | 99c94604a742ffd44e21b4c5cd2061f6293a4d72 | 26,935 |
def has_prefix(s, sub_index):
"""
This function can make sure that the current string(recorded in index) is in the dictionary.
(or it will return False and stop finding.
:param s: string, the user input word
:param sub_index: list, current list (recorded in the index type)
:return: (bool) If the... | a33ce5d13b473f264636bfb430d0191450103020 | 26,936 |
def get_experiment_tag(name):
"""Interfaces to callables that add a tag to the matplotlib axis.
This is a light-weight approach to a watermarking of a plot in a way
that is common in particle physics experiments and groups.
`name` can be an identifier for one of the styles provided here.
Alternativ... | 9dc11a6caac2010aa99e288897a6f60273d1a372 | 26,937 |
def _add_layer1(query, original_data):
"""Add data from successful layer1 MIB query to original data provided.
Args:
query: MIB query object
original_data: Two keyed dict of data
Returns:
new_data: Aggregated data
"""
# Process query
result = query.layer1()
new_dat... | ab2d3ad95435dd2fcc6b99745f115cab08aa6699 | 26,938 |
def encodeUcs2(text):
""" UCS2 text encoding algorithm
Encodes the specified text string into UCS2-encoded bytes.
@param text: the text string to encode
@return: A bytearray containing the string encoded in UCS2 encoding
@rtype: bytearray
"""
result = bytearray()
for b in ... | da2243ffc959db64a196a312522f967dce1da9d1 | 26,939 |
def w_kvtype(stype: str, ctx: dict) -> dict:
"""
Make definition from ktype or vtype option
"""
stypes = {'Boolean': 'boolean', 'Integer': 'integer', 'Number': 'number', 'String': 'string'}
if stype in stypes:
return {'type': stypes[stype]}
if stype[0] in (OPTION_ID['enum'], OPTION_ID['p... | e09bc0ceaed2edc2927ddbc4b6bc38bcec5a345d | 26,940 |
from typing import Optional
def create_article_number_sequence(
shop_id: ShopID, prefix: str, *, value: Optional[int] = None
) -> ArticleNumberSequence:
"""Create an article number sequence."""
sequence = DbArticleNumberSequence(shop_id, prefix, value=value)
db.session.add(sequence)
try:
... | 3be2f0399fee0c01a117ffef0f790bae80750db0 | 26,941 |
import math
def transform_side(side,theta):
"""Transform the coordinates of the side onto the perpendicular plane using Euler-Rodrigues formula
Input: side coordinates, plane
Output: new coordinates
"""
new_side = list()
#calculating axis of rotation
axis = side[len(side)-1][0]-side[0][0],0,0
#converting th... | 41e71676ee138cc355ae3990e74aeae6176d4f94 | 26,945 |
def get_approved_listings():
"""
Gets pending listings for a user
:param user_id
:return:
"""
user_id = request.args.get('user_id')
approved_listings = []
if user_id:
approved_listings = Listing.query.filter_by(approved=True, created_by=user_id)
else:
approved_listin... | 1d20094c8b3ca10a23a49aa6c83020ae3cdf65e3 | 26,946 |
def edit_profile(request):
"""
编辑公司信息
:param request:
:return:
"""
user_id = request.session.get("user_id")
email = request.session.get("email")
# username = request.session.get("username")
if request.session.get("is_superuser"):
# 管理员获取全部公司信息
data = models.I... | f106b3f6f35497bf5db0a71b81b520ac023c2b37 | 26,947 |
from typing import Optional
def get_vault(vault_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVaultResult:
"""
This data source provides details about a specific Vault resource in Oracle Cloud Infrastructure Kms service.
Gets the specified vault's con... | 586bc794d066cd3e4040aff04a39a81762016c41 | 26,948 |
def _make_dist_mat_sa_utils():
"""Generate a sample distance matrix to test spatial_analysis_utils
Returns:
xarray.DataArray:
a sample distance matrix to use for testing spatial_analysis_utils
"""
dist_mat = np.zeros((10, 10))
np.fill_diagonal(dist_mat, 0)
# Create distanc... | 706ce73e1a5e66cdf521df7d0e1bf2c43bd09d02 | 26,950 |
def _workSE(args):
"""Worker function for batch source extraction."""
imageKey, imagePath, weightPath, weightType, psfPath, configs, \
checkImages, catPostfix, workDir, defaultsPath = args
catalogName = "_".join((str(imageKey), catPostfix))
se = SourceExtractor(imagePath, catalogName, weigh... | be98194a91108268bb7873fb275416a394aee3c1 | 26,951 |
def split_match(date,time,station):
"""
Function to find and extract the measuremnt from Jack Walpoles splititng data for the same event.
This matching is done by finding an entry with the same date stamp. Inital testing has shown this to be a unique identifier.
station MUST be a string of a station cod... | b1a7a1b4265719c8d79274169593754a7f683bc2 | 26,952 |
import numpy
def schoolf_eq(temps, B0, E, E_D, T_pk):
"""Schoolfield model, used for calculating trait values at a given temperature"""
function = B0 * exp(-E * ((1/(K*temps)) - (1/(K*283.15)))) / (1 + (E/(E_D - E)) * exp((E_D / K) * (1 / T_pk - 1 / temps)))
return numpy.array(map(log,function), dtype=numpy.float6... | 67969317bee63d759071c86840e4ae9ecfb924b4 | 26,953 |
from typing import Union
from typing import Type
from typing import Any
from typing import Iterable
def heat_type_of(
obj: Union[str, Type[datatype], Any, Iterable[str, Type[datatype], Any]]
) -> Type[datatype]:
"""
Returns the corresponding HeAT data type of given object, i.e. scalar, array or iterable. ... | 2637d7559bb1ff3d6a1b07d9cedd10f1eb57e564 | 26,955 |
from typing import Union
from typing import Tuple
from typing import Dict
from typing import Any
def get_field_from_acc_out_ty(
acc_out_ty_or_dict: Union[Tuple, Dict[str, Any]], field: str
):
"""
After tracing NamedTuple inputs are converted to standard tuples, so we cannot
access them by name directl... | 44b0cac3737823c6ea7aa4b924683d17184711a6 | 26,956 |
def bhc(data,alpha,beta=None):
"""
This function does a bayesian clustering.
Alpha: Hyperparameter
Beta: Hyperparameter
If beta is not given, it uses the Multinomial-Dirichlet.
Otherwise it uses Bernoulli-Beta.
"""
n_cluster = data.shape[0]
nodekey = n_cluster
list_cluster... | a0c6cb588a66dce92a2041a02eb60b66a12422ae | 26,958 |
import logging
def get_sql_value(conn_id, sql):
"""
get_sql_value executes a sql query given proper connection parameters.
The result of the sql query should be one and only one numeric value.
"""
hook = _get_hook(conn_id)
result = hook.get_records(sql)
if len(result) > 1:
logging.... | 24cc8c633f855b5b07c602d247a543268972d615 | 26,959 |
def get_rendered_config(path: str) -> str:
"""Return a config as a string with placeholders replaced by values of the corresponding
environment variables."""
with open(path) as f:
txt = f.read()
matches = pattern.findall(txt)
for match in matches:
txt = txt.replace("[" + match + "]",... | 93445db04960fd66cc88673f397eb959d2e982ec | 26,960 |
def units_to_msec(units, resolution):
"""Convert BLE specific units to milliseconds."""
time_ms = units * float(resolution) / 1000
return time_ms | 49588d7961593b2ba2e57e1481d6e1430b4a3671 | 26,961 |
def IR(numOfLayer, useIntraGCN, useInterGCN, useRandomMatrix, useAllOneMatrix, useCov, useCluster, class_num):
"""Constructs a ir-18/ir-50 model."""
model = Backbone(numOfLayer, useIntraGCN, useInterGCN, useRandomMatrix, useAllOneMatrix, useCov, useCluster, class_num)
return model | dbe638d3cd38c66387c67e0854b07ea7f800909f | 26,962 |
import re
def extractNextPageToken(resultString):
"""
Calling GASearchVariantsResponse.fromJsonString() can be slower
than doing the variant search in the first place; instead we use
a regexp to extract the next page token.
"""
m = re.search('(?<=nextPageToken": )(?:")?([0-9]*?:[0-9]*)|null',
... | 151a5697561b687aeff8af51c4ec2f73d47c441d | 26,963 |
def underscore(msg):
""" return underlined msg """
return __apply_style(__format['underscore'],msg) | ded741e58d1f6e46fc4b9f56d57947903a8a2587 | 26,964 |
def get_slice(dimspins, y):
"""
Get slice of variable `y` inquiring the spinboxes `dimspins`.
Parameters
----------
dimspins : list
List of tk.Spinbox widgets of dimensions
y : ndarray or netCDF4._netCDF4.Variable
Input array or netcdf variable
Returns
-------
ndarr... | 3545391babb06c7cae5dc8fc6f413d34e40da57c | 26,965 |
import requests
import json
def query_real_confs(body=None): # noqa: E501
"""
query the real configuration value in the current hostId node
query the real configuration value in the current hostId node # noqa: E501
:param body:
:type body: dict | bytes
:rtype: List[RealConfInfo]
"""
... | 1313792649942f402694713df0d413fe39b8a77c | 26,966 |
def is_data(data):
""" Check if a packet is a data packet. """
return len(data) > 26 and ord(data[25]) == 0x08 and ord(data[26]) in [0x42, 0x62] | edb2a6b69fde42aef75923a2afbd5736d1aca660 | 26,968 |
def _bool_value(ctx, define_name, default, *, config_vars = None):
"""Looks up a define on ctx for a boolean value.
Will also report an error if the value is not a supported value.
Args:
ctx: A Starlark context. Deprecated.
define_name: The name of the define to look up.
default: The val... | c60799e3019c6acefd74115ca02b76feb9c72237 | 26,969 |
def get_tf_metric(text):
"""
Computes the tf metric
Params:
text (tuple): tuple of words
Returns:
tf_text: format: ((word1, word2, ...), (tf1, tf2, ...))
"""
counts = [text.count(word) for word in text]
max_count = max(counts)
tf = [counts[i]/max_count for i in range(0, len(counts))]
return text, tf | 6397e150fa55a056358f4b28cdf8a74abdc7fdb6 | 26,970 |
import torch
def R_transform_th(R_src, R_delta, rot_coord="CAMERA"):
"""transform R_src use R_delta.
:param R_src: matrix
:param R_delta:
:param rot_coord:
:return:
"""
if rot_coord.lower() == "model":
R_output = torch.matmul(R_src, R_delta)
elif rot_coord.lower() == "camera" ... | 67d4b94bcc9382fae93cc926246fb2436eac7173 | 26,971 |
def calculate_UMI_with_mismatch(UMIs):
"""
Corrected the mismatches in UMIs
input: UMI sequences and their counts;
return: Corrected unique UMI sequences
"""
if len(UMIs.keys()) == 1:
return [x for x in UMIs if UMIs[x]>0]
UMIs = sorted(UMIs.items(), key=lambda k: k[1], reverse=True)... | c0e24bf7043b3041043187ca78c8b8f5cafae7cc | 26,972 |
def create_import_data(properties):
"""
This function collects and creates all the asset data needed for the import process.
:param object properties: The property group that contains variables that maintain the addon's correct state.
:return list: A list of dictionaries containing the both the mesh an... | b8b28ac4a1d753214dbcd1361b1ababf7f366b55 | 26,973 |
def _parse_vertex_tuple(s):
"""Parse vertex indices in '/' separated form (like 'i/j/k', 'i//k'.
...).
"""
vt = [0, 0, 0]
for i, c in enumerate(s.split("/")):
if c:
vt[i] = int(c)
return tuple(vt) | 37e53236ef7a96f55aed36e929abe4472911b9ea | 26,975 |
def getKeyFromValue(dictionary, value):
"""
dictionary内に指定したvalueを持つKeyを検索して取得
"""
keys = [key for key, val in dictionary.items() if val == value]
if len(keys) > 0:
return keys[0]
return None | d2bb42938a809677f4a96e869e9e03c194a28561 | 26,976 |
def withdraw(dest):
"""
This function defines all the FlowSpec rules to be withdrawn via the iBGP Update.
////***update*** Add port-range feature similar to announce() - ADDED in TBowlby's code.
Args:
dest (str): IP Address of the Victim host.
Calls:
send_requests(messages): Calls ... | 2e0767630c72d69a914175e6bcc808d9b088b247 | 26,977 |
def get_prefix(node):
"""
Strips off the name in the URI to give the prefixlabel...
:param node: The full URI string
:return: (prefix, label) as (string, string)
"""
if '#' in node:
name = node.split("#")[-1]
else:
# there must be no # in the prefix e.g. schema.org/
n... | 5d005548da722751cdd0ae022994de5f39f9ac56 | 26,978 |
def sY(qubit: Qubit, coefficient: complex = 1.0) -> Pauli:
"""Return the Pauli sigma_Y operator acting on the given qubit"""
return Pauli.sigma(qubit, 'Y', coefficient) | 8d2444f4e9a4b9e3734a1d7ec1e686f06ded0c89 | 26,979 |
def load_data_and_labels(filename):
"""Load sentences and labels"""
df = pd.read_csv(filename, compression='zip', dtype={'faits': object}, encoding = 'utf8')
selected = [ATTRIBUTE_TO_PREDICT, 'faits']
non_selected = list(set(df.columns) - set(selected))
df = df.drop(non_selected, axis=1) # Drop non selected colum... | 651b156801dcdd5b847ab1eb3330afe569c6b63e | 26,980 |
def ovc_search(request):
"""Method to do ovc search."""
try:
results = search_master(request)
except Exception as e:
print('error with search - %s' % (str(e)))
return JsonResponse(results, content_type='application/json',
safe=False)
else:
retu... | f571627dba30a3f0a1e958e484c528fa3338defa | 26,981 |
import struct
def incdata(data, s):
"""
add 's' to each byte.
This is useful for finding the correct shift from an incorrectly shifted chunk.
"""
return b"".join(struct.pack("<B", (_ + s) & 0xFF) for _ in data) | 89633d232d655183bee7a20bd0e1c5a4a2cc7c05 | 26,982 |
from typing import Tuple
def nonsquare_hungarian_matching(
weights: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]:
"""Hungarian matching with arbitrary shape.
The matchers_ops.hungarian_matching supports only squared weight matrices.
This function generalizes the hungarian matching to nonsquare cases by paddin... | 02968da51da1d65020b544bb2467ecbe3ba4ab96 | 26,983 |
import string
def strip_non_printable(value):
"""
Removes any non-printable characters and adds an indicator to the string
when binary characters are fonud
:param value: the value that you wish to strip
"""
if value is None:
return None
# Filter all non-printable characters
#... | 279ea769bd7d57ee3e4feb9faf10f2a3af3aa657 | 26,985 |
def flatten(name):
"""Get a flatten layer.
Parameters
----------
name : string
the name of the flatten layer
Returns
-------
flatten : keras.layers.core.Flatten
"""
if LIB_TYPE == "keras":
return Flatten(name=name) | b395162b7551d4292a89a2128b651305df294069 | 26,986 |
import math
def tangent_circle(dist, radius):
"""
return tangent angle to a circle placed at (dist, 0.0) with radius=radius
For non-existing tangent use 100 degrees.
"""
if dist >= radius:
return math.asin(radius/float(dist))
return math.radians(100) | bcde88456a267239566f22bb6ea5cf00f64fa08e | 26,987 |
import re
def find_backup_path(docsents, q, cand, k=40):
"""
If no path is found create a dummy backup path
:param docsents:
:param q:
:param cand:
:param k:
:return:
"""
path_for_cand_dict = {"he_docidx": None,
"he_locs": None,
"... | 10a71c623da6c185a1e1cc1242b2e0402208837c | 26,988 |
def state_transitions():
"""Simplified state transition dictionary"""
return {
"E": {"A": {"(0, 9)": 1}},
"A": {"I": {"(0, 9)": 1}},
"I": {"H": {"(0, 9)": 1}},
"H": {"R": {"(0, 9)": 1}}
} | f8c79f8071f2b61ceacaacf3406a198b2c54c917 | 26,989 |
import json
def send(socket, action, opts=None, request_response=True, return_type='auto'):
"""Send a request to an RPC server.
Parameters
----------
socket : zmq socket
The ZeroMQ socket that is connected to the server.
action : str
Name of action server should perform. See ... | 9a2dcf2fb78c1458c0dead23c4bcc451f1316731 | 26,990 |
def brighter(data, data_mean=None):
"""
Brighter set of parameters for density remap.
Parameters
----------
data : numpy.ndarray
data_mean : None|float|int
Returns
-------
numpy.ndarray
"""
return clip_cast(amplitude_to_density(data, dmin=60, mmult=40, data_mean=data_mean)... | d00688ac99fb509ad0fe0e2f35cc5c03f598bfee | 26,991 |
import logging
import sqlite3
def get_lensed_host_fluxes(host_truth_db_file, image_dir, bands='ugrizy',
components=('bulge', 'disk'),
host_types=('agn', 'sne'), verbose=False):
"""
Loop over entries in `agn_hosts` and `sne_hosts` tables in
the host_tru... | 1b28c58ed824b988e02d40091ac633bc8187d27a | 26,994 |
from pathlib import Path
def load_challenges() -> list[Challenge]:
"""
Loads all challenges.
Returns
-------
list[Challenge]
All loaded challenges.
"""
__challenges.clear()
modules = []
for lib in (Path(__file__).parent / "saves/challenges").iterdir():
if not lib.n... | d6cd5d65d572ba081d5f2ba0bca67c755bc57d2d | 26,995 |
def get_new_user_data(GET_params):
"""Return the data necessary to create a new OLD user or update an existing one.
:param GET_params: the ``request.GET`` dictionary-like object generated by
Pylons which contains the query string parameters of the request.
:returns: A dictionary whose values ar... | 61ee952088bb37a2f5171f0bdd0ed9a59d66bed7 | 26,996 |
import six
def add_heatmap_summary(feature_query, feature_map, name):
"""Plots dot produce of feature_query on feature_map.
Args:
feature_query: Batch x embedding size tensor of goal embeddings
feature_map: Batch x h x w x embedding size of pregrasp scene embeddings
name: string to name tensorflow su... | d7807942a2e3d92b4653d822b24686b649a6df88 | 26,997 |
def ParseVecFile(filename):
"""Parse a vector art file and return an Art object for it.
Right now, handled file types are: EPS, Adobe Illustrator, PDF
Args:
filename: string - name of the file to read and parse
Returns:
geom.Art: object containing paths drawn in the file.
Retur... | accf0446a4600de77cf41fdc5a586f930156dfd6 | 26,998 |
import torch
def batchnorm_to_float(module):
"""Converts batch norm to FP32"""
if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):
module.float()
for child in module.children():
batchnorm_to_float(child)
return module | bf9ad7cbda5984465f5dcb5f693ba71c8a0ab583 | 26,999 |
def get_mat_2d(sequence, rnn=False):
"""Uses aa_to_map to turn a sequence into a 3D array representation of the
protein.
"""
if rnn:
mat = np.zeros((len(sequence), 36))
for i, aa in enumerate(sequence):
mat[i] = aa_to_map(aa)[:,:6,:].flatten()
else... | 122eb7f890995eb4d95226251bb5f2c9a4ba38df | 27,000 |
from datetime import datetime
def TimeSec():
"""[Takes current time in and convert into seconds.]
Returns:
[float]: [Time in seconds]
"""
now = datetime.now()
return now.second+(now.minute*60)+(now.hour*60*60) | 58892b89feb05a56c27d4fd62ba174f9d1c09591 | 27,001 |
def partition_variable(variable, partition_dict):
"""
As partition_shape() but takes a mapping of dimension-name to number
of partitions as it's second argument. <variable> is a VariableWrapper
instance.
"""
partitions = []
for dim in variable.dimensions:
if dim.name in partition_d... | 7ffd4075bbb6bbd156f76c9271101003c5db8c1e | 27,002 |
def _get_object_properties(agent,
properties,
obj_type,
obj_property_name,
obj_property_value,
include_mors=False):
"""
Helper method to simplify retrieving of properties
T... | d2e43bcc1700e76a7ca117eaf419d1c5ef941975 | 27,003 |
def get_crypto_currency_pairs(info=None):
"""Gets a list of all the cypto currencies that you can trade
:param info: Will filter the results to have a list of the values that correspond to key that matches info.
:type info: Optional[str]
:returns: If info parameter is left as None then the list will co... | b44a013d6bbf348321c4f00006262e1ab02e0459 | 27,004 |
def sparse_graph_convolution_layers(name, inputs, units, reuse=True):
"""
This one is used by the Joint_SMRGCN model;
A crude prototypical operation
"""
with tf.variable_scope(name, reuse=tf.AUTO_REUSE if reuse else False):
# adj_tensor: list (size nb_bonds) of [length, length] matrices
... | c5c16242fb175e851a78a34249c2f902bd2e9cb4 | 27,005 |
def update_or_create_tags(observer, repo, tag=None, type_to_update=None):
"""Create or update tags."""
observer.update_state(
state='PROGRESS',
meta='Retrieving data and media from Github'
)
git = GithubAPI(repo)
if tag:
data, media = git.get_data(tag)
if type_to_up... | 3f478c66cda9648cb72325e9668ea08b52147fbf | 27,007 |
def confirm_api_access_changes(request):
"""Renders the confirmation page to confirm the successful changes made to
the API access settings for the superuser's group.
Parameters:
request - The request object sent with the call to the confirm page if
the requested changes were su... | b31ce15ec72607200edd66e72df99b5ad9cb4afc | 27,008 |
def mpl_hill_shade(data, terrain=None,
cmap=DEF_CMAP, vmin=None, vmax=None, norm=None, blend_function=rgb_blending,
azimuth=DEF_AZIMUTH, elevation=DEF_ELEVATION):
""" Hill shading that uses the matplotlib intensities. Is only for making comparison between
blending me... | 6a881794b486e581f817bf073c7cbef465d8d504 | 27,009 |
def img_docs(filename='paths.ini', section='PATHS'):
"""
Serve the PATH to the img docs directory
"""
parser = ConfigParser()
parser.read(filename)
docs = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
docs[param[0]] = par... | c76cc9ae17fb5dd8cfc6387349b6f47545fe01ad | 27,010 |
def KGPhenio(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "current", **kwargs
) -> Graph:
"""R... | e4a3647013c0b250e29007c0db08a6d6813c8976 | 27,011 |
def _x_mul(a, b, digit=0):
"""
Grade school multiplication, ignoring the signs.
Returns the absolute value of the product, or None if error.
"""
size_a = a.numdigits()
size_b = b.numdigits()
if a is b:
# Efficient squaring per HAC, Algorithm 14.16:
# http://www.cacr.math.uw... | 84dc948c03106ce26d9b4abf67c57b5d13438ef1 | 27,012 |
import re
def server_version(headers):
"""Extract the firmware version from HTTP headers."""
version_re = re.compile(r"ServerTech-AWS/v(?P<version>\d+\.\d+\w+)")
if headers.get("Server"):
match = version_re.match(headers["Server"])
if match:
return match.group("version") | 24151f3898430f5395e69b4dd7c42bd678626381 | 27,013 |
def slice_constant(data, batch_size=32, name='constant_data', global_step=None):
"""Provide a slice based on the global_step.
This is useful when the entire data array can be stored in memory because it
allows you to feed the data very efficiently.
Args:
data: A numpy array or tensor.
batch_size: The ... | 53ebf9a6216841a4a4db8c2d77bd9545328454ac | 27,015 |
def es_subcadena(adn1, adn2):
"""
(str, str) -> bool
>>> es_subcadena('gatc', 'tta')
False
>>> es_subcadena('gtattt', 'atcgta')
False
:param:adn1:str:primera cadena a comparar
:param:adn2:str:segunda cadena a comparar
:return:bool:verificacion si una es subcadena de la otra
"""... | 9c3605e74e1c9dbf227695a4f0f6431cc845a5f1 | 27,016 |
def get_labels_and_features(nested_embeddings):
""" returns labels and embeddings
"""
x = nested_embeddings[:,:-1]
y = nested_embeddings[:,-1]
return x,y | 302505bd3aa769570fa602760f7da1ddd017e940 | 27,017 |
def all_(f : a >> bool, t : r(a)) -> bool:
"""
all :: Foldable r => (a -> bool) -> r a -> bool
Determines whether all elements of the structure satisfy the predicate.
"""
return DL.all_(toList(t)) | ec19ae23b282affd99580b9614edaec8a8a2fd44 | 27,018 |
def log_binom_sum(lower, upper, obs_vote, n0_curr, n1_curr, b_1_curr, b_2_curr, prev):
"""
Helper function for computing log prob of convolution of binomial
"""
# votes_within_group_count is y_0i in Wakefield's notation, the count of votes from
# given group for given candidate within precinct i (u... | 2a2d80671b594d2c56d6db5dc770833d5d8aa129 | 27,019 |
def parse_locator(src):
""" (src:str) -> [pathfile:str, label:either(str, None)]
"""
pathfile_label = src.split('#')
if len(pathfile_label)==1:
pathfile_label.append(None)
if len(pathfile_label)!=2:
raise ValueError('Malformed src: %s' % (src))
return pathfile_label | 970bc1e2e60eec4a54cd00fc5984d22ebc2b8c7a | 27,020 |
def detect_seperator(path, encoding):
"""
:param path: pathlib.Path objects
:param encoding: file encoding.
:return: 1 character.
"""
# After reviewing the logic in the CSV sniffer, I concluded that all it
# really does is to look for a non-text character. As the separator is
# determine... | 8436359a602d2b8caf72a6dbdac4870c502d1bad | 27,021 |
def pr_at_k(df, k):
"""
Returns p/r for a specific result at a specific k
df: pandas df with columns 'space', 'time', 'y_true', and 'y_pred'
k: the number of obs you'd like to label 1 at each time
"""
#static traits of df
universe = df['time'].nunique()
p = df['y_true'].... | 79997405f360fa66c4e0cbe35d54a15976cc6e3b | 27,022 |
def draw_segm(im, np_segms, np_label, np_score, labels, threshold=0.5, alpha=0.7):
"""
Draw segmentation on image.
"""
mask_color_id = 0
w_ratio = .4
color_list = get_color_map_list(len(labels))
im = np.array(im).astype('float32')
clsid2color = {}
np_segms = np_segms.astype(np.uint8)... | f2248256a0be01efb1e9402d1e51e04a5fde365d | 27,023 |
def solve(board):
"""
solve a sudoku board using backtracking
param board: 2d list of integers
return: solution
"""
space_found = find_empty_space(board)
if not space_found:
return True
else:
row, col = space_found
for i in range(1, 10):
if valid_number(board,... | 5b94db3ba4873c0fc5e91355dab6c59ed0603fa0 | 27,024 |
from typing import List
from typing import Optional
def check(s: str) -> None:
"""
Checks if the given input string of brackets are balanced or not
Args:
s (str): The input string
"""
stack: List[str] = []
def get_opening(char: str) -> Optional[str]:
"""
Gets the... | 720018e5b39e070f48e18c502e8a842feef32840 | 27,025 |
def format_address(msisdn):
"""
Format a normalized MSISDN as a URI that ParlayX will accept.
"""
if not msisdn.startswith('+'):
raise ValueError('Only international format addresses are supported')
return 'tel:' + msisdn[1:] | f5a5cc9f8bcf77f1185003cfd523d7d6f1212bd8 | 27,026 |
def get_nag_statistics(nag):
"""Return a report containing all NAG statistics"""
report = """Constants: {0}
Inputs: {1}
NANDs: {2}
Outputs: {3}
Min. I/O distance: {4}
Max. I/O distance: {5}""".format(
nag.constant_number,
nag.input_number,
nag.nand_number,
nag... | 44d3f32bc0b05d8b1d81c3b32dc140af4fd20aa0 | 27,027 |
def create_backup(storage, remote, parent=None):
""" Create a new backup of provided remote and return its backup object.
.. warning:: Do not forget to add a label on returned backup to avoid its
removal by the garbage collector.
"""
if parent:
parent_ref = storage.resolve(parent)
... | 7c4f5b424d6c48474fce74396eb6e47d0935f559 | 27,029 |
def get_pairwise_correlation(population_df, method="pearson"):
"""Given a population dataframe, calculate all pairwise correlations.
Parameters
----------
population_df : pandas.core.frame.DataFrame
Includes metadata and observation features.
method : str, default "pearson"
Which co... | 85f1df4357f9996492bac6053a2f0852b2318f14 | 27,030 |
def plot_route(cities, route, name='diagram.png', ax=None):
"""Plot a graphical representation of the route obtained"""
mpl.rcParams['agg.path.chunksize'] = 10000
if not ax:
fig = plt.figure(figsize=(5, 5), frameon = False)
axis = fig.add_axes([0,0,1,1])
axis.set_aspect('equal', ad... | b8ceadb0a26e6f8c2eacea66ede9db948d73ca65 | 27,032 |
import math
def bertScore(string):
"""
Function to generate the output list consisting top K replacements for each word in the sentence using BERT.
"""
corrector = SpellCorrector()
temp1 = []
temp2 = []
temp3 = []
con = list(string.split(" "))
tf.reset_default_graph()
sess = t... | 9edf75111a0df95532a1332f6b0f4b5dbe495ac2 | 27,033 |
import dataclasses
def configuration_stub(configuration_test: Configuration) -> Configuration:
"""
Configuration for tests.
"""
return dataclasses.replace(
configuration_test,
distance_between_wheels=DISTANCE_BETWEEN_WHEELS,
) | ea2fe84c19f86062fd728bd10814303026776c03 | 27,034 |
def join_smiles(df, df_smiles=None, how="left"):
"""Join Smiles from Compound_Id."""
if df_smiles is None:
load_resource("SMILES")
df_smiles = SMILES
result = df.merge(df_smiles, on="Compound_Id", how=how)
result = result.apply(pd.to_numeric, errors='ignore')
result = result.fillna("... | e36bc5d31764e5eb8fdcf006b05e4fe75eeff36a | 27,035 |
def signature(*types, **kwtypes):
"""Type annotations and conversions for methods.
Ignores first parameter.
"""
conversions = [(t if isinstance(t, tuple) else (t, t)) for t in types]
kwconversions = {k: (t if isinstance(t, tuple) else (t, t))
for k, t in kwtypes.items()}
d... | 414ecfd4738b431e8e059319c347a6e7bedabc80 | 27,036 |
def mean(image):
"""The mean pixel value"""
return image.mean() | 176dd8d483008fa1071f0f0be20c4b53ad0e2a5f | 27,037 |
import yaml
def read_event_file(file_name):
"""Read a file and return the corresponding objects.
:param file_name: Name of file to read.
:type file_name: str
:returns: ServiceEvent from file.
:rtype: ServiceEvent
"""
with open(file_name, 'r') as f:
contents = yaml.safe_load(f)
... | 66da0a76f064dd99c9b2eff5594aa58f5d1d8cca | 27,038 |
def get_layer_information(cloudsat_filenames, get_quality=True, verbose=0):
""" Returns
CloudLayerType: -9: error, 0: non determined, 1-8 cloud types
"""
all_info = []
for cloudsat_path in cloudsat_filenames:
sd = SD(cloudsat_path, SDC.READ)
if verbose:
#... | e3c52cd9284730c35da3ddbc1879d0e083fa63bd | 27,040 |
import torch
def from_magphase(mag_spec, phase, dim: int = -2):
"""Return a complex-like torch tensor from magnitude and phase components.
Args:
mag_spec (torch.tensor): magnitude of the tensor.
phase (torch.tensor): angle of the tensor
dim(int, optional): the frequency (or equivalent... | 2f33de266fa295d0c21cf5002f6420c60eb07071 | 27,041 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.