content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def assert_not_null(attribute, value):
# type: (Any, str) -> Any
"""Asserts that the given object is non-null and returns it.
:param attribute: Object to assert on
:param value: Field name to display in exception message if null
:return: Object if non null
:raises: ValueError if object is null
... | ed305a880946a879a501f0d5580f0183bd8d2cfa | 67,200 |
import struct
def parse_images(filename):
"""
Reading images information and converting from bytearray to list of ints
with help of python's struct module.
"""
images = []
imgs_file = open(filename, 'rb')
# Get only the size of following data
size = struct.unpack(">IIII", imgs_file.rea... | bf17dded918051d52cc807f01aed350d94897077 | 67,201 |
from pathlib import Path
def read_psw_file(psw_file: Path) -> bytes:
"""
Attempts to read the password from the given `psw_file`.
Raises:
`OSError`: If some IO related error occurred during file reading
"""
if not psw_file.is_file():
raise FileNotFoundError("'{}' does not exist".f... | 64b91077ff4e728f1d6ef26b770bf222e3c8f34a | 67,202 |
from typing import Match
import re
def _convert_all_hexes_to_ints(vbf_string: str) -> str:
"""
>>> _convert_all_hexes_to_ints('abc 0xff def 0XF')
'abc 255 def 15'
"""
def hex_match_to_int_str(match: Match) -> str:
return str(int(match.group(0), base=16))
return re.sub(r"(?i)0x[0-9-a-... | 4b671facb107c8d8ac0d93ad859dcb1b22ddf151 | 67,203 |
import os
import requests
import gzip
def load_etext(etextno, refresh_cache=False, mirror=None):
"""Returns a unicode representation of the full body of a Project Gutenberg
text. After making an initial remote call to Project Gutenberg's servers,
the text is persisted locally.
"""
etextno = valid... | 25f116c2fb993f468c210d6a8abccd57838b72fc | 67,204 |
def create_cwe_text(cwe_string):
"""Create a text representation of a CWE string along with a verbose translation.
For example, "CWE-190->CWE-122" becomes: "CWE-190->CWE-122: Integer Overflow or
Wraparound leads to Heap-based Buffer Overflow".
"""
cwe_defs = load_cwe_definitions()
cwe_parts = c... | b310a22f12ee93ee43dda0bf5a89794a92124024 | 67,205 |
import requests
def _write_points(points, num_points):
"""
Write the points to the InfluxDB in groups that are MAX_POINTS_PER_WRITE in
size.
"""
LOG.debug("Writing points %d", num_points)
write_index = 0
points_written = 0
while write_index < num_points:
max_write_index = write... | d702b7a1cbd9ef4819bd0501bf2b5e25e1aae654 | 67,206 |
def projection_error(states, basis):
"""Calculate the absolute and relative projection errors induced by
projecting states to a low dimensional basis, i.e.,
absolute_error = ||Q - Vr Vr^T Q||_F,
relative_error = ||Q - Vr Vr^T Q||_F / ||Q||_F
where Q = states and Vr = basis. Note that Vr Vr... | fb99b6a34de928ecb27a889e2926ce6a60feb17e | 67,207 |
import time
def create_env(user_token, inherit, timeout=1):
"""
CreateEnvironmentBlock might fail when we close a login session and then
try to re-open one very quickly. Run the method multiple times to work
around the async nature of logoffs.
"""
start = time.time()
env = None
exc = N... | d6b9bfbcefc8a8a85af4b348618085861885572e | 67,208 |
def with_weight_decay(
grads_and_vars: GradsAndVars, weight_decay: float
) -> GradsAndVars:
"""Add weight decay to gradients as done in pytoch."""
if weight_decay:
return [(g + weight_decay * v, v) for g, v in grads_and_vars]
return grads_and_vars | e8b173c057b303381d2c2c4377bb2201f6786ad0 | 67,209 |
def exponential_mode_response_function(mode, alpha, cutoff, nfilt, filter_order):
"""Return an exponential filter coefficient for the user-provided *mode*."""
return np.exp(-1.0 * alpha * ((mode - cutoff) / nfilt)
** (2*filter_order)) | 915e11d3b494454d3fdcf6503342bc1521dcd3dc | 67,210 |
def matmul_cupydense(left, right, scale=1, out=None):
"""
Perform the operation
``out := scale * (left @ right) + out``
where `left`, `right` and `out` are matrices. `scale` is a complex scalar,
defaulting to 1.
"""
# This may be done more naturally with gemm from cupy.cublas
# but... | 244a956221054b7fa330100badf8ec5e15e20f8a | 67,211 |
from typing import Union
from typing import List
from typing import Optional
from pathlib import Path
from typing import Dict
import shlex
import os
import subprocess
import logging
import sys
def run_command(
cmd: Union[List[str], str],
error_message: Optional[str] = None,
cwd: Union[str, Path, None] = N... | 47d244a8919abd01799bcd825e6ebeb7e46c54f9 | 67,212 |
def merge_dicts(x):
"""A quick function to combine dictionaries.
Parameters
----------
x : list or array-like
A list of dictionaries to merge.
Returns
-------
dict
The merged dictionary.
"""
z = x[0].copy() # start with keys and values of x
for y in x[1:]:
... | 73ce60aa167d6c4dcfce9e80e09c53db1202b86b | 67,213 |
def success_response(data: dict, web):
"""Успешный ответ"""
return web.json_response({'success': True, 'message': '', **data}) | 000939a3cb832cb0a104788b91db5140c25462b0 | 67,214 |
def load_linear_models_from_avro(model_file, feature_file):
"""
Load linear models from avro files.
The models are in photon-ml format.
Intercept is moved to the end of the coefficient array.
:param model_file: Model avro file, photon-ml format
:param feature_file: A file containing all features... | b2d060a16f4353c2e29c091b9bf9836a36194ba8 | 67,215 |
import functools
def compute_transition_probabilities(
states, transit_keys, optim_paras, dense_key_to_dense_covariates
):
"""Get transition probabilities by dense_key.
We calculate transition probabilities for one dense key
in this function. Therefore we retrieve probabilities for individuals
an... | 9b5f0b738228accba9709b94345f2db2d3d68c8b | 67,216 |
import logging
def configure_logging(add_handler, log=log):
"""
Configure log records. If adding a handler, make the formatter print all
passed in key:value data.
ie log.extra('msg', extra=dict(a=1))
generates 'msg a=1'
`add_handler` (True, False, None, or Handler instance)
... | 78969e72f3e92dc087d6d7e24efd4d82e34046e9 | 67,217 |
def get_bounding_box(pts, img_shape, relax=0.1):
"""
Computes the bounding box of a set of points with same height and width, based on the size of the larger side
:param pts:
:param img_shape:
:param relax:
:return:
"""
# format is x,y,w,h
x, y, w, h = cv2.boundingRect(pts[:, :2])
... | 399ae6c771dd49fe3660971487ad3243b0c57b58 | 67,218 |
def tile(image, level, mask, size, margin, mask_level=5):
"""
Loads a folder of numpy array into a dictionnary.
Parameters
----------
image: string or wsi image,
image to tile.
level: int,
level to which apply the analysis.
mask_level: int,
level to which apply the m... | 887ceeb8e5ce9a987d9f674ab80f9d5086b6614b | 67,219 |
def get_entropy(y_predict, y_real):
"""
Returns entropy of a split
y_predict is the split decision, True/Fasle, and y_true can be multi class
"""
if len(y_predict) != len(y_real):
print('They have to be the same length')
return None
n = len(y_real)
s_true, n_true = entropy_of... | d738c498f09fa0c2e1484bdbe6ed44e53ac86bea | 67,220 |
import __main__
import builtins
def get_global_namespaces(ip):
"""
Get the global interactive namespaces.
@type ip:
C{InteractiveShell}
@param ip:
IPython shell or C{None} to assume not in IPython.
@rtype:
C{list} of C{dict}
"""
# logger.debug("get_global_namespaces()")
... | 5700c2b12eb810e4325149c6cdd500cba086edac | 67,221 |
from re import S
def factor(f, *gens, **args):
"""Returns factorization into irreducibles of `f`. """
frac = args.get('frac', False)
gens = _analyze_gens(gens)
def _factor(f):
"""Factor a true polynomial expression. """
F = NonStrictPoly(f, *gens, **args)
if not F.is_Poly:
... | 76058671493744d00453c6ee2ab16b0b30481f12 | 67,222 |
def safe_name(arg):
"""
Make a leaf or container name safe for use in Python.
"""
#print "safe_name", arg
if ENABLE_CAMEL_CASE:
l = arg.split('-')
if len(l) > 0:
arg = "".join([x[0].upper() + x[1:] for x in l if x != ''])
l = arg.split('.')
if len(l) > 0... | 3a4fb99a9a91f978fde938ef3e9de6d03ac652b8 | 67,223 |
def mackey_glass(n, a=0.2, b=0.8, c=0.9, d=23, e=10, initial=0.1):
"""
Mackey-Glass discrete equation.
**Args:**
* `n` - length of the output data (int) - how many samples will be on output
**Kwargs:**
Parameters `a`, `b`, `c`, `d`, `e` can be a scalar or a vector. In case
o... | c0839027a6150f582492d3cd361018d931f2f4d4 | 67,224 |
def get_user_by_id(id: int, db: Session) -> Query:
"""
get_user_by_id takes the user from database by his id.
:param id: id of user to get.
:param db: database session.
:return: first result of session query or None if the result doesn't contain any row.
"""
return db.query(models.User).fi... | 769b0d3ee38655a4c2a07e36c52b102906f9160e | 67,225 |
def cross_entropy(y_hat, y):
"""
交叉熵损失函数
:param y_hat:
:param y:
:return:
"""
return -nd.pick(y_hat, y).log() | 3fe49e0a3d0e1957fa83df73cbff4e0c78321749 | 67,226 |
import socket
def lookup_host(ip):
""" Attempt to associate IP to DNS name, retain cache """
if ip not in dns:
try:
result = socket.gethostbyaddr(ip)
dns[ip] = result[0]
except Exception as e:
log.warning(
"Failed to determine hostname for '%... | 7413e1e9763ec309912b84a1187414036bf54988 | 67,227 |
from typing import List
def _translate_output_is_valid(translate_outputs: List[str]) -> bool:
"""
True if there are invalid tokens in out_path, or if no valid outputs were found.
"""
# At least one output must be non-empty
found_valid_output = False
bad_tokens = set(C.VOCAB_SYMBOLS)
for js... | 2616b242f0f50d1b5190bf27f276ca54edf3087b | 67,228 |
def either(*funcs):
"""Return ``True`` is any of the function evaluate true"""
return lambda x: any(f(x) for f in funcs) | 32f037748a1fb4cf06e5fdce7c1bad20e8200d61 | 67,229 |
def sliding_window_1D(x, windowLen):
"""
Constructs a 2D array whose rows are the data in a sliding window that
advances one time step at a time.
Parameters
----------
x : 1D, array-like
An ordered collection of objects
windowLen : int > 0
The legnth of the sliding window
Returns
-------
X : 2D array
... | d84882ca7bd68aa215960f120d4826f9e2102441 | 67,230 |
import re
def findalliter(patter, string):
"""Function used to return all re.findall objects in string"""
m_test = re.findall(r'(\d+)_(.+)', string)
m_iter = [m_test]
while m_test:
m_test = re.findall(r'(\d+)_(.+)', m_test[0][1])
m_iter.append(m_test)
return m_iter | eddeb7393a7e883a313b9612a78c0e3d0be0e23f | 67,231 |
def load(cls, *, where=None, create_if_none_callback=None):
""" Returns records for a specific class. """
table = db.table(cls.__name__)
if where:
result = table.search(where(Query()))
else:
result = table.all()
if len(result) > 0:
return (cls.fromdict(item) fo... | 3cac43813c45e9cac28a2902b7513dfabbd1f608 | 67,232 |
def lrelu(alpha=0.01):
"""Create a leaky rectified linear unit function.
This function returns a new function that implements the LReLU with a
specified alpha. The returned value can be used as an activation function in
network layers.
Parameters
----------
alpha: float
the slope of the function wh... | d45b9cd88ab3f4d36cdbce3c5880db29793afd7e | 67,233 |
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import os.path
import json
import sys
def gen_pdf_dir(request):
"""Генерация PDF направлений"""
if SettingManager.get("pdf_auto_print", "true", "b"):
pdfdoc.PDFCatalog.OpenAction = '<</S/JavaScript/JS(this.print\({bU... | 7972bbc3ded4b520e49e5b1d9dcada497a9c86a1 | 67,234 |
def split(matrix):
"""
Splits a given matrix into quarters.
Input: nxn matrix
Output: tuple containing 4 n/2 x n/2 matrices corresponding to a, b, c, d
"""
row, col = matrix.shape
row2, col2 = row//2, col//2
return matrix[:row2, :col2], matrix[:row2, col2:], matrix[row2:, :col2], matrix[row2:, col2:] | 6284c4a8ff6747b005971a7a37f0327aa5815a7c | 67,235 |
import tempfile
import os
import copy
import platform
import subprocess
import time
from unittest.mock import call
def minimize_file(filepath):
""" This method runs lithium on a java source code and returns an
object that contains the filepath and the similar loc in the original file
obj = {
... | e1a8c0887b96988750f811119f4b62fed99c0149 | 67,236 |
import ctypes
def dskx02(handle, dladsc, vertex, raydir):
"""
Determine the plate ID and body-fixed coordinates of the
intersection of a specified ray with the surface defined by a
type 2 DSK plate model.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskx02_c.html
:param handle: H... | 804c507886b9864a8a4701e17d23acd23f465e88 | 67,237 |
def my_fitness_functions(l):
"""
Utility functions of M. Sefrioui and J. Perlaux, "Nash genetic algorithms:
examples and applications," Proceedings of the 2000 Congress on Evolutionary Computation.
CEC00 (Cat. No.00TH8512), La Jolla, CA, USA, 2000, pp. 509-516 vol.1,
doi: 10.1109/CEC.2000.870339.
... | 1da2cf3e1298228f77eb7ed4ae4b6ccbb7401d3a | 67,238 |
import re
def normalize_tokenize(string):
"""
Takes a string, normalizes it (makes it lowercase and
removes punctuation), and then splits it into a list of
words.
Note that everything in this function is plain Python
without using NLTK (although as noted below, NLTK provides
some more sop... | 800be8deabbc109f7d9459e5cf2da9fb134557ae | 67,239 |
def solve_tsp_brute_force(g):
"""
This is the brute-force algorithm to solve the TSP.
Args:
g: the graph to solve
Returns:
the list of the optimized walk in the visiting order and the optimal distance
"""
n = len(g.nodes)
all_routes = list(permutations(range(n)))
best_di... | b774bba7feb468ef31b0b74b398747a876e35080 | 67,240 |
import json
from os import path
from ...cli import set_default_dropout
def read_json(options, json_path=None, test=False, read_all_para=False):
"""
Read a json file to update python argparse Namespace.
Args:
options: (argparse.Namespace) options of the model.
json_path: (str) If given pat... | 3a3c77fde77569c81bcb95704119653069ee1fac | 67,241 |
import requests
def get(domain_name=None):
"""Retreives the DNS SOA record for a particular domain.
:param domain_name: string, (required) the domain name for which to
retrieve the SOA record
"""
url = 'https://api.cloudns.net/dns/soa-details.json'
params = Parameters({'domain-name': dom... | 34a0c8a3ab075c9611f63307465d4297dbc26b3b | 67,242 |
from typing import Generator
from typing import Tuple
from typing import List
from typing import Dict
def filter_by_point(
file_diagnostics: Generator[Tuple[SessionBufferProtocol, List[Diagnostic]], None, None],
point: Point
) -> Tuple[Dict[str, List[Diagnostic]], Range]:
"""XXX: Move this odd function to... | 1e119ee37c2a375080eedee0f419c6a6203eead9 | 67,243 |
def get_best_fit_plane(pts, weights=None):
"""
:param pts:
:param weights:
:return:
"""
if weights is None:
wSum = len(pts)
origin = np.sum(pts, 0)
origin /= wSum
sums = np.zeros((3, 3), np.double)
for pt in pts:
dp = pt - origin
for i in range(3):
... | cfc2fdc48c4a0d201bcb825517cc183cb32593a7 | 67,244 |
import warnings
from contextlib import suppress
import numbers
def _score(estimator, X_test, y_test, eras_test, scorer, error_score="raise"):
"""Compute the score(s) of an estimator on a given test set.
Will return a dict of floats if `scorer` is a dict, otherwise a single
float is returned.
"""
i... | c2fd3a2c6f456779d0836930f4edc5a1ae506fdf | 67,245 |
from typing import Dict
from typing import Type
def get_widgets_from_entrypoints(
key: str = config.ENTRYPOINT_WIDGET
) -> Dict[str, Type[PyDMDesignerPlugin]]:
"""
Get all widgets from entrypoint definitions.
Parameters
----------
key : str, optional
The entrypoint key. Defaults to `... | c73186d07a4424625271101522580b2841638327 | 67,246 |
def dagNodeTypes():
"""
Return a list of node types presently loaded.
"""
return DagNode.__subclasses__() | 1fdf6741afdbd3a1ca2d3c083260b9b854049a46 | 67,247 |
import torch
def replace_masked_values(tensor: torch.Tensor, mask: torch.Tensor, replace_with: float) -> torch.Tensor:
"""
Replaces all masked values in ``tensor`` with ``replace_with``. ``mask`` must be broadcastable
to the same shape as ``tensor``. We require that ``tensor.dim() == mask.dim()``, as oth... | 04370638cf533c67273df57e597d2506dfd457a5 | 67,248 |
import subprocess
import os
import json
def _download_wget(url, filename):
"""
First try with Python requests (which handle well compression), then move to a more robust download approach
"""
result = "fail"
# This is the most robust and reliable way to download files I found with Python... to re... | 67406c40991a9307f27e99a0612d8e08d12216cd | 67,249 |
from pathlib import Path
def show_normalized_pyramid(
path: Path = Depends(imagepath_parameter)
):
"""
Get image normalized pyramid
"""
original = path.get_original()
check_representation_existence(original)
return PyramidInfo.from_pyramid(original.normalized_pyramid) | 548c45348e14adda04afa9e0e6b37b705f764575 | 67,250 |
import warnings
def remove_small_structures(calibration, binary):
"""
Cleans up the image by removing structures smaller than the configured size.
:param calibration:
:param binary:
:return:
>>> remove_small_structures(0.1, np.array([[ False, False, False],
... ... | 79bc3e0ed25c2198629f0837d1b890c970bce7f4 | 67,251 |
def _IsDisallowedPropertiesError(error):
"""Checks if an error is due to properties that were not in the schema.
Args:
error: A ValidationError
Returns:
Whether the error was due to disallowed properties
"""
prop_validator = 'additionalProperties'
prop_message = 'Additional properties are not allo... | 2042806486e861cf97d0e2ec168a167610749ebd | 67,252 |
def html_tag_checker(html_file):
"""
This function open and read the html file then checks for a tag validity
:param html_file:
:return:
"""
html_file = open(html_file, 'r')
html_document = html_file.read()
tags = tag_search(html_document) # calling the tag searcher function
tag_a... | b9d1085a3fd08700838ee62929c05b19e60a6851 | 67,253 |
def simple_integrate(ts, peak_list, base_ts=None, intname='simple'):
"""
Integrate each peak naively; without regard to overlap.
This is used as the terminal step by most of the other integrators.
"""
peaks = []
for hints in peak_list:
t0, t1 = hints['t0'], hints['t1']
hints['in... | c1ce0259bc75894ce02653b8a6a60252a77c32ca | 67,254 |
def CSourceToInput(source: str) -> str:
"""Create a bytecode for the given C source string.
This is a convenience method for generating test inputs. If this method fails,
it is because clang is broken.
"""
bytecode = CSourceToBytecode(source)
return bytecode | 1bcfefce22bca1d30fa69955d539fd22dff7c5f2 | 67,255 |
from .utils import FileSize
import json
import os
def UploadFile(request):
"""上传文件"""
if not request.method=="POST":
return HttpResponse(json.dumps(u"{'state:'ERROR'}"),content_type="application/javascript")
state=u"SUCCESS"
action=request.GET.get("action")
#上传文件
upload_field_name={
... | 2d8c05f244639c22b9d2a0945d1a6ff122c6e957 | 67,256 |
import copy
import scipy
def hexdensity(x, y, bounds=None, bins='log', scale='log',
cmap=None, vmin=None, vmax=None, ax=None, cax=None,
unit='TPM', entity='genes',
gridsize=175, fontsize=12, show_corr=True, clip_on=True, rasterized=False):
"""Wrapper for hexbin"""
... | 9e94e00368103d02a67f9077ed3fbe02d30cc53d | 67,257 |
def add_lags_to_sequences(X, lags):
"""
Given input sequences X adds its lagged versions as extra dimensions,
where non-integer lagged versions are computed via linear interpolation.
# Input
:X: an array of sequences of shape (..., num_examples, len_examples, num_features)
:lags: a ... | 8d4af80bce97d640080ac9f15945e0371504d5f3 | 67,258 |
def reinforce_score(reward: tf.Tensor,
baseline: tf.Tensor,
decoded: tf.Tensor,
logits: tf.Tensor) -> tf.Tensor:
"""Cost function whose derivative is the REINFORCE equation.
This implements the primitive function to the central equation of the
REI... | f9ceb3f6bae1be453136fbd29a48f0378ac281e1 | 67,259 |
def set_exposure():
"""
JSON requirements:
- device-type
- exposure-time
"""
data = request.get_json()
# Ensure body data
if "exposure-time" not in data.keys():
abort(400, "Missing 'exposure-time' object.")
try:
# Set exposure time
CaptureImage.set_ex... | 98e1e0db0aa559c66a30b57df6b1eb8f6ebbe5cd | 67,260 |
from re import T
def build_cost_functional(lambda_val, h, y_sh, Thetas):
""" build_cost_functional (with regularization) J=J_y(Theta,b) # J\equiv J_y(\Theta,b), but now with
X,y being represented as theano symbolic variables first, before the actual numerical data values are given
INPUT/PARAMETERS
=============... | ed670bd7e8d0174d4d9beb9c1902f625792ef119 | 67,261 |
def estimatefwhm(objects,verbose=False):
""" Estimate FWHM using objects."""
print = getprintfunc() # Get print function to be used locally, allows for easy logging
# Check that we have all of the columns that we need
for f in ['mag_auto','magerr_auto','flags','fwhm']:
if f not in objec... | bf8ed2612529c41ab1756de0d23cda8554c8fbd5 | 67,262 |
def sigmoid(x):
"""Compute softmax values for each sets of scores in x."""
return 1.0 / (1+ np.exp(-x)) | 67a4db30250aa5c9d03769bf83678f89898bc821 | 67,263 |
def create_objects(texture_map, list_of_meshes):
"""
Create an object for each mesh. For each object, we set the diffuse reflectance as the corresponding
texture.
Parameters:
texture_map (dict[str -> pyreder.Texture): List of textures to apply to diffuse reflectance.
... | 719cd34cb2ca28ab205771711ce90132aeef4da0 | 67,264 |
def check_uk_postal_code(code, start, end):
"""Check postal code for uk, split the code by regex.
Example postal codes: BH20 2BC (UK), IM16 7HF (Isle of Man).
"""
pattern = r"^([A-Z]{1,2})([0-9]+)([A-Z]?) ?([0-9][A-Z]{2})$"
code, start, end = group_values(pattern, code, start, end)
# replace ... | ba7afb6f4c5ff8e6ae593d18c5d18f0a0ea83ac8 | 67,265 |
def is_auth(username, password):
"""
Userテーブルに存在するか否かを返す
"""
users = db.session.query(User.username, User.password)
db.session.close()
for user in users:
if user.username == username and user.password == password:
return True
return False | ceadd075ebbb28f3fbff8df4cb2c3ac8a26eee4f | 67,266 |
from functools import reduce
import operator
def indent(rows, hasHeader=False, headerChar='-', delim=' | ', justify='left',
separateRows=False, prefix='', postfix='', wrapfunc=lambda x:x):
"""Indents a table by column.
- rows: A sequence of sequences of items, one sequence per row.
- hasH... | 4359e9d7908d08dbbc9cee4ef5b52514cc6b9d2d | 67,267 |
def dCOV(x, y, rowvar=1, uv=False, all_est=True):
"""Estimate dCov measure(s) between x and y. Allows uni- or multi-variate estimations
Name dCOV was chosen to match implementation in R energy toolbox:
http://cran.r-project.org/web/packages/energy/index.html
Parameters
----------
rowvar : int... | 6d9c2d7cff26b1e00e8bab68867513a0de75c2bf | 67,268 |
import PIL
import io
def img_bin_to_img_arr(img_bin_bytes, use_grayscale=False):
"""Convert image binary data to numpy array.
Args:
img_bin_bytes: binary image data bytes.
use_grayscale: convert to grayscale.
Returns:
numpy array: (height, width, chs).
"""
pil_img = PIL.Image.open(io.BytesIO(i... | 38b9ba17eb288e0b69172b6ec48a535cbb5df54d | 67,269 |
from websauna.system.model.meta import Base
def create_test_dbsession(request, registry: Registry, transaction_manager=transaction.manager) -> Session:
"""Create a test database session and setup database.
Create and drop all tables when called. Add teardown function py.test to drop all tables during teardow... | 7a0d8323566d5d098b8e0df230246ac0612947dc | 67,270 |
def rgb_blend(col1, col2, fraction=0.5):
"""
Calculates colour between two colors.
Definition
----------
def rgb_blend(col1, col2, fraction=0.5):
Input
-----
col1 1st rgb colour tuple
col2 2nd rgb colour tuple
Optional Input
--------------
fractio... | b7526edb6983c618cd01cd78b259b12479602a3e | 67,271 |
def normalize(x):
"""Normalization helper function."""
return x / np.linalg.norm(x) | 4bf3c21f1a7cfa8e8929671d24f545f1208206a2 | 67,272 |
import torch
def plot_meshes(meshes: Meshes, *, in_subplots: bool = False, ncols: int = 1, **kwargs):
"""
Takes a Meshes object and generates a plotly figure. If there is more than
one mesh in the batch and in_subplots=True, each mesh will be
visualized in an individual subplot with ncols number of su... | cd7b6cbe2cfa7b191034c52cf358d6124972e3f4 | 67,273 |
def my_simple_str(x):
"""Seems to be useless, but "no signature found for builtin type <class 'str'>" is raised otherwise"""
return str(x) | bbe332fa413a093d634b1ea9010f6b17212594a2 | 67,274 |
def convect(sigma, interps):
"""Convect interps based on density (sigma).
Ignores variations in cell depths and convects vertically
:arg interps: dictionary of 3D numpy arrays.
Key represents the variable name.
:type interps: dictionary
:arg sigma: sigma-t, density, 3D array
... | 0538cd97dd09a808071fee28f5097ea1a4298eb2 | 67,275 |
def notqdm(iterable, *args, **kwargs):
"""
silent replacement for `tqdm`
"""
return iterable | f37a5f84cf02987e4ada0ba8c0ee324c7a676903 | 67,276 |
def getUserUTXO(user: int, UTXO: list = None):
"""
Get a list containing the amount of each UTXO for a given user
user: user ID of the user whose UTXO you want to get
UTXO: array of UTXO to use instead of default one: c.BC_UTXO
"""
if UTXO is None:
UTXO = c.BC_UTXO
amounts = []
... | 5a6eea0507b4ff892a2b7937adb63d494eecf3df | 67,277 |
def make_surv_array(t,f,breaks):
"""Transforms censored survival data into vector format
Arguments
t: Array of failure/censoring times.
f: Censoring indicator. 1 if failed, 0 if censored.
breaks: Locations of breaks between time intervals for discrete-time survival model (always ... | 87275a603f5d63e358f7b2e69086167d37eaaf79 | 67,278 |
def get_dc_environment_by_search(search=dict()):
"""Return a list of dc environments by dict."""
try:
environments = DivisaoDc.objects.filter()
env_map = build_query_to_datatable_v3(environments, search)
except FieldError as e:
raise ValidationAPIException(str(e))
except Excepti... | b5d036795d7ac5ddfcb21f37c2764c76c5490ac3 | 67,279 |
def load_task(task_type):
"""Preload organisation data."""
task_type = TaskType[task_type]
record_model = getattr(models, task_type.name.title().replace('_', '') + "Record")
form = FileUploadForm(extensions=["csv", "tsv", "json", "yaml", "yml"])
if form.validate_on_submit():
try:
... | 3d5c8b768aae3ac320810a954f61c4acb55fc68b | 67,280 |
from typing import Tuple
def belief_sim_from(
gridverse_inner_env: InnerEnv,
) -> belief_types.Simulator:
"""Transforms ``gridverse_inner_env`` into a sim usable for the belief
:param gridverse_inner_env: a domain from ``gym_gridverse``
:return: a simulator suitable for ``pomdp_belief_tracking``
... | b6abb4767a5340aa4babd763cb8c9e2495481290 | 67,281 |
import os
def file_is_empty(file_path):
"""Returns True if the file is empty. """
return os.stat(file_path).st_size == 0 | e6124a27ebf394cb79b9dfbcdb118a9fde9264cd | 67,282 |
import scipy
def convert_continuos_f0(f0):
"""CONVERT F0 TO CONTINUOUS F0
Reference:
https://github.com/bigpon/vcc20_baseline_cyclevae/blob/master/baseline/src/bin/feature_extract.py
Args:
f0 (ndarray): original f0 sequence with the shape (T)
Return:
(ndarray): continuous f0 with the shape (T)
... | 38cacad911faf3c4240f6737aa0915cd5f78896e | 67,283 |
import six
from typing import OrderedDict
def getHistory(symbols, startDate, typ='daily', session=None):
"""
Returns history for ONE (or SEVERAL) symbol(s)
"""
try:
startDate = startDate.dt.strftime(TIMESTAMP_NOSEP_FMT)
except:
pass
if isinstance(symbols, six.string_types):
... | 4697019941c69887056a1ff87eee1442eec5c232 | 67,284 |
def resnet50_earlyexit(pretrained=False, **kwargs):
"""Constructs a ResNet-50 model.
"""
model = ResNetEarlyExit(Bottleneck, [3, 4, 6, 3], **kwargs)
return model | 865f7ff36a0079b870498bbfba7d5cf5fa95aa6a | 67,285 |
def _aux_epoch_indicators(epoch):
"""
"""
all_accuracy, all_loss = [], []
for row in epoch:
aux = ' '.join(row)
if 'accuracy:' in aux:
# / remove '\x08' / separate num / remove space
acc = row[-1].replace('\x08', '').split(':')[-1].strip()
... | a4ecfc9ac23a5a56cec5f89bf4cf79643fbc1e3b | 67,286 |
def convertFrom1D(list):
"""
Convert from a list to a matrix with the appropriate dimensions
"""
return [[x] for x in list] | c3bd41be26a20c6895c6ecc30d7e28005a17a44e | 67,287 |
def get_verification_url(user=None):
"""
Returns the verification url.
"""
verf_link = ""
if user:
try:
prev_token = UserToken.objects.get(email = user.email, token_type = 0, status = False)
if prev_token:
prev_token.status = True
... | 6fe4f7665a862aa4b7591c18ba32b6c7d14502d4 | 67,288 |
from pycalphad import __version__ as pycalphad_version
from typing import OrderedDict
from datetime import datetime
import warnings
def equilibrium(dbf, comps, phases, conditions, output=None, model=None,
verbose=False, broadcast=True, calc_opts=None,
scheduler=dask.local.get_sync,
... | 4e7b42b24cf6c8c1236f2ed247544756e99cef04 | 67,289 |
import asyncio
async def maybe_async(func, *args, **kwargs):
"""异步调用一个函数,该函数可能是同步函数,也可能是异步函数"""
result = func(*args, **kwargs)
if asyncio.iscoroutine(result):
result = await result
return result | ac1d507c8f83b573ef5c3416e2285f3df752d4aa | 67,290 |
import time
import math
from datetime import datetime
def browse(
request,
letter=None,
details=[DETAIL_ZZT, DETAIL_SZZT, DETAIL_UTILITY],
page=1, show_description=False
):
""" Returns page containing a list of files filtered by letter, details,
and page
Keyword arguments:
letter ... | 1f3a74674bba7c01e4ddc05a6407502c3dc143f7 | 67,291 |
from datetime import datetime
def get_tail_nature_date(nature_year: str):
"""
根据传入自然年的年份获取该自然年最后自然周最后一天的日期
@日期: 2021/05/07
@作者: 徐嘉辉
Args:
nature_year: 自然年字符串,形如2020
Returns:
yyyymmdd格式的自然年最后自然周最后一天的日期
"""
"""
判断本年度12月31日属于哪个自然年,若属于本年度则判断12.31的自然周,得到本年度最后一个自然周的... | 968309bd7518f603cbcddcf377bf90ecf04e87cb | 67,292 |
import pprint
from datetime import datetime
def _JSONtoCSV1_1(data, domains_metadata, columns_to_add):
"""Rework the top-level JSON results to a CSV file with the added metadata from the domains file"""
logger.info("Structure of this file is API 1.1")
header = ''
body = []
pp = pprint.PrettyPri... | 9d821286fe4c184dd307747d48fc60edb464793e | 67,293 |
import sys
import mpmath
def tables(f, r, v, xi, symmetric, is64, verbose=False):
"""Calculate k[i], w[i], and f[i]."""
ki = [None] * len(xi)
wi = ki[:]
fi = ki[:]
if is64:
# The ziggurat user masks off bits to select the bin and symmetry.
im = 2 ** (63 - (len(xi)-1).bit_length())
else:
if symmetric:
i... | a33ca631153d183d01a45f75a72f474396a2df05 | 67,294 |
def tracking_error(r_a, r_b):
"""
Returns the Tracking Error between the two return series
"""
return np.sqrt(((r_a - r_b)**2).sum()) | 8fb180568fc838458cf3754380869714f7b3fd80 | 67,295 |
def get_current_price(symbol):
"""Get current price by symbol."""
if len(symbol) > 5:
return "symbol exceeded length", status.HTTP_400_BAD_REQUEST
sanitized_symbol = alpha_string(symbol)
data = Robinhood.get_current_price(sanitized_symbol)
return data | 8cb1c853b8a20c072705c784ebaf3789b556e237 | 67,296 |
def _format_decode_code_level(message,
signal_names,
variable_lines):
"""Format one decode level in a signal tree.
"""
body_lines = []
conversion_lines = []
muxes_lines = []
for signal_name in signal_names:
if isinstance(sign... | 8b31e6224616f2cb16077a42d0f1e31372a3e073 | 67,297 |
def url_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Role for linking to url articles.
:url:`https://google.com` ->
link: https://google.com
text: https://google.com
:url:`Google <https://google.com>` ->
link: https://google.com
text: Google
:ur... | 3a25cf711b69e7092fe429b2a2e0fefc07aefb09 | 67,298 |
from typing import List
from typing import Dict
def build_label_relationship_dict(df: pd.DataFrame,
names_to_ignore: List[str]=["UNKNOWN, BENIGN"]
) -> Dict[str, str]:
"""Builds a dictionary which contains as key malware family name and as value m... | 5400ad7a96dfdae8d46c258d66ecdc690d1d0b24 | 67,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.