content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _upsampled_dft(data, upsampled_region_size,
upsample_factor=1, axis_offsets=None):
"""
Upsampled DFT by matrix multiplication.
This code is intended to provide the same result as if the following
operations were performed:
- Embed the array "data" in an array that is ``up... | ad0621f2d572e8f1ef3a4559f9da470057c0f869 | 39,000 |
from io import StringIO
def extract_text(pdf_file, password='', page_numbers=None, maxpages=0,
caching=True, codec='utf-8', laparams=None):
"""Parse and return the text contained in a PDF file.
:param pdf_file: Either a file path or a file-like object for the PDF file
to be worked on... | d3fca176eb33d06a2a2c8d2ad7a16f0d51ccecde | 39,001 |
from typing import Optional
from typing import Callable
import functools
import click
def server_add_and_update_opts(f: Optional[Callable] = None, *, add=False):
"""
shared collection of options for `globus transfer endpoint server add` and
`globus transfer endpoint server update`.
Accepts a toggle to... | bc2427a7a0996528dc1411186c51b11c7b4db339 | 39,002 |
def richicon_src(icon):
"""
Returns link to the icon.
"""
src = richtemplates_settings.ICONS_URL + icon
return src | b3c84e79bec69507ee0b384aeaf4ece16096dd64 | 39,003 |
def stanley_control(
state, cx, cy, cyaw, last_target_idx=0, k=0.7, params=VehicleParams()
):
"""
Stanley steering control.
:param state: (State object)
:param cx: [m] x-coordinates of (sampled) desired trajectory
:param cy: [m] y-coordinates of (sampled) desired trajectory
:param cyaw: [ra... | 25be40759d1bd73135cc3b274763afee97ad891c | 39,004 |
def dumps(obj: dict, encoding=None, iso_config=None, hex_bitmap=False):
"""
Serialize obj to a ISO8583 message byte string
:param obj: dict containing message data
:param encoding: python text encoding scheme
:param iso_config: iso8583 message configuration dict
:param hex_bitmap: bitmap in hex... | b192c63361553882ee756b498644d0a60ba137e1 | 39,005 |
def pixel_to_cube(p, size):
"""
Converts pixel position to cube coords.
:param p: The point x, y.
:param size: The size of each hex.
:return: The cube coord x, y, z of the pixel.
"""
return cube_round(axial_to_cube(pixel_to_axial(p, size))) | 8e5a0c5ca720fc960dffa6b2bfd59fa5d46db246 | 39,006 |
def mock_pydicom_config_data_element_callback(mocker: MockerFixture):
"""
Mocking pydicom config
"""
return mocker.patch.object(pydicom.config, 'data_element_callback') | cfac4d4715edda8077c736f1d3fe74c24b0dfcfa | 39,007 |
def kwp_edge_disjoint(graph, node_start, node_end, max_k, credit_mat):
""" compute k edge disjoint widest paths """
""" using http://www.cs.cmu.edu/~avrim/451f08/lectures/lect1007.pdf """
graph = copy.deepcopy(graph)
capacity_mat = credit_mat
A = []
try:
path = nx.shortest_path(graph, ... | 0426e2b0a7dc9263fdba6fa7b0041a4ad4d41cc2 | 39,008 |
def build_tag_regex(plugin_dict):
"""Given a plugin dict (probably from tagplugins) build an 'or' regex
group. Something like: (?:latex|ref)
"""
func_name_list = []
for func_tuple in plugin_dict:
for func_name in func_tuple:
func_name_list.append(func_name)
regex = '|'.joi... | 367b95067cabd4dcdfd8981f6a14b650da3601c5 | 39,009 |
def is_html_like(text):
"""
Checks whether text is html or not
:param text: string
:return: bool
"""
if isinstance(text, str):
text = text.strip()
if text.startswith("<"):
return True
return False
return False | a499e14c243fcd9485f3925b68a0cef75fa069cb | 39,010 |
def linear_surge(
state: np.ndarray, thrust: np.ndarray, parameters: np.ndarray
) -> np.ndarray:
"""AUV equation of motion for low velocities in 1DOF (surge)
Args:
state (np.ndarray): position and velocity in surge
thrust (np.ndarray): current thrust in surge
parameters (np.ndarray)... | c019381bfdc6c43a5b2308c14679cffe0277d054 | 39,011 |
def login(request):
"""View to check the auth0 assertion and remember the user"""
login = request.authenticated_userid
if login is None:
namespace = userid = None
else:
namespace, userid = login.split('.', 1)
# create new user account if one does not exist
if namespace != 'auth0... | 469285fd9adde29a4142935b3649b4303311f537 | 39,013 |
def construct_M(frequencies,basis='gaussian',order=1,epsilon=1):
"""
Construct M matrix for calculation of DRT ridge penalty.
x^T@M@x gives integral of squared derivative of DRT over all ln(tau)
Parameters:
-----------
frequencies : array
Frequencies at which basis functions are centered
basis : string, opt... | 1867dd76b5acf6d09df683c6d543160cf027a12e | 39,014 |
def KK_RC76_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
... | 9acc5a8acc7dc9749aef122e250e3966a3304af5 | 39,015 |
def relu_prime(x):
""" ReLU derivative. """
return (0 <= x) | 8908af6f6748291477e3379443fe7714fed289ad | 39,016 |
from typing import Optional
def get_api_key(auth_header: Optional[models.AuthHeader] = None) -> models.ApiKey:
"""Get a user's API key."""
res_json = Users.get('apikey', auth=auth_header)
return models.ApiKey.from_dict(res_json) | 7247d5a1c1fde8097d7142b4b03d4148a0626d44 | 39,017 |
def opts2v_polys_bb(opts):
"""Creates VPolysBb functor by calling its constructor with options
from opts.
Args:
opts (obj): Namespace object with options.
Returns:
v_polys_bb (obj): Instantiated VPolysBb functor.
"""
return VPolysBb(opts.lm_ordering_lm_order) | 7a83b00658969a6f692d98d3f8f9c2e62f44f648 | 39,019 |
import importlib
def import_optional_dependency(name, message):
"""
Import an optional dependecy.
Parameters
----------
name : str
The module name.
message : str
Additional text to include in the ImportError message.
Returns
-------
module : ModuleType
The... | 22d638e86b8d979b746507790532273d161323c8 | 39,020 |
def road_distance(lat1, lon1, lat2, lon2):
"""
Calculate the distance by road between two points
"""
point1 = lat1, lon1
point2 = lat2, lon2
url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins={0},{1}&destinations={2},{3}&mode=driving&language=en-EN&sensor=false&key={4}".form... | 20fce2805a66b162861ed4da5bebad86122165d4 | 39,021 |
import inspect
def initializer(fun):
""" Automatically initialize instance variables
Args:
fun: an init function
Returns: a wrapper function
"""
names, varargs, keywords, defaults, kwonlyargs, kwonlydefaults, annotations = inspect.getfullargspec(fun)
@wraps(fun)
def wrapper(sel... | 41adee7703f5185bbdd8c6adf1868467a681c803 | 39,022 |
def _twosided_zerolag(data, zerolag):
"""Build a symmetric vector out of stricly positive lag vector and zero-lag
.. doctest::
>>> data = [3,2,1]
>>> zerolag = 4
>>> twosided_zerolag(data, zerolag)
array([1, 2, 3, 4, 3, 2, 1])
.. seealso:: Same behaviour as :func:`twosided... | 07e1728ce53291d9bb0eaad269da308643ece936 | 39,023 |
def Filter2D(src, dst, ker, type=DataType.none):
"""\
Convolve an image with a kernel.
:param src: source image
:param dst: destination image
:param ker: convolution kernel
:param type: destination DataType. If set to DataType.none, the DataType
of ``src`` is used
:return: None
""... | f9d703c2e2241b117725521acaed91b3bf79adda | 39,024 |
import torch
def collate_function(batch):
"""
create a mini batch an make sure the image are of the same size
"""
batch.sort(key=lambda data: len(data[1]), reverse=True) # sort by the longest caption
images, captions = zip(*batch) # unzip the batch
images = torch.stack(images) # stack the imag... | 98e936ac31b7328cff3e6c9ec4155d6d207aa8a1 | 39,025 |
def scheduled_operation_state_update(context, operation_id, values):
"""Update the ScheduledOperationState record with the most recent data."""
session = get_session()
with session.begin():
state_ref = _scheduled_operation_state_get(context, operation_id,
... | abc3d2eca30bfd6e38d9f00821741fca5de39dd4 | 39,027 |
def msec2cmyear(ms):
""" Return m/s converted to cm/year Quantity
Args:
ms (float): meters per second
Returns:
cm / year
"""
return (ms * UR.m / UR.s).to(UR.cm / UR.year).magnitude | cbf82205a59c17a190b5f168bc04020af22b0542 | 39,028 |
import re
def find_chinese(str):
"""
查找字符串中中文集合
:param str:
:return:
"""
return re.findall(RE_CHINESE, str) | 03cca814c9b3cc435671eb677939f724191e112e | 39,029 |
def localpooling_filter(adj, symmetric=True):
"""
Computes the local pooling filter from the given adjacency matrix, as
described by Kipf & Welling (2017).
:param adj: a np.array or scipy.sparse matrix of rank 2 or 3;
:param symmetric: boolean, whether to normalize the matrix as
\(D^{-\\frac{1}... | a5be522446b2123739c085e87176ace6593e8833 | 39,030 |
def curate_url(url):
""" Put the url into a somewhat standard manner.
Removes ".txt" extension that sometimes has, special characters and http://
Args:
url: String with the url to curate
Returns:
curated_url
"""
curated_url = url
curated_url = curated_url.replace(".txt",... | 42ea836e84dfb2329dd35f6874b73ac18bde48d1 | 39,031 |
from typing import Optional
def full(shape: Shape, fill_value: Array, dtype: Optional[DType] = None) -> Array:
"""Returns an array of `shape` filled with `fill_value`.
Args:
shape: sequence of integers, describing the shape of the output array.
fill_value: the value to fill the new array with.
dtype:... | 5a51a0d07c73f668890601eece7cbb1f9b3c846a | 39,032 |
import requests
def get_news():
"""
Returns two dictionnary object containing news articles
informations. The first one is a short version, with little
informations and the second one contains all the informations.
"""
API_KEY = 'd913f4f1287a42819abc66f428e0fad4'
sources = 'b... | 4145ddfd669c54f8bfe285ccde67b7a08b724a85 | 39,033 |
def post(request):
"""
新增关注
@param request:
@return:
"""
try:
# 获取当前登录用户的user_id
user_id = request.session.get('user_id')
user = User.objects.get(pk=user_id)
query_dict = request.POST
# 获取要关注的用户的id
following_user_id = query_dict.get('user_id')
... | 76e39c2fbe12b0538939825d35a9937117ac8dbf | 39,034 |
def read_saved_ip():
"""reads current ip"""
with CURRENT_IP_ADDRESS_PATH.open('r') as fp:
saved_ip = fp.read()
return saved_ip | a4eaa0290b8115177f26a7a014b0f865a8ccdc13 | 39,036 |
def runProtocolsWithReactor(reactorBuilder, serverProtocol, clientProtocol,
endpointCreator):
"""
Connect two protocols using endpoints and a new reactor instance.
A new reactor will be created and run, with the client and server protocol
instances connected to each other us... | 6dd0ab7a9dc87ad3fc146cd333c8dac405e97198 | 39,037 |
def datetime_to_string(dt):
""" Convert the given datetime (converted in UTC) to a string value. """
return fields.Datetime.to_string(dt.astimezone(utc)) | 6365d2a60255fd8cefe3d639f9f7e16edea6aa08 | 39,038 |
def load_model(path='../models/inception_v3'):
"""Retrieves the trained model"""
model = keras_load_model(path)
return model | 03d68786e11abefdcdcf013f5e55f1250868dfda | 39,039 |
def mqtt_client(ini: dict, mqtt_iface: MQTTInterface):
"""
Establishes an MQTT connection with the brocker server, subscribes
all configured topics and enqueue received messages into the MQTT
interface queue.
"""
# Validate mqtt configuration parameters
if not verify_params(ini, 'mqtt', ['se... | 890aa487f00be8f4b571fda17cc65ed11f040915 | 39,041 |
def dcdt_liden(t, y):
"""
System of ODEs representing the biomass pyrolysis kinetic reactions from
Liden 1988. Reactions in the kinetic scheme are
Reaction 1: wood -> tar
Reaction 2: tar -> gas
Reaction 3: wood -> (gas + char)
Parameters
----------
t : scalar
Ti... | 71178a8e5b0160a6964b5e556606da6f28d7198b | 39,042 |
from pp.components.polarization_rotator import polarization_rotator
def cutback_polarization_rotator(n_devices_target, design=3):
""" sample of component cutback """
rows = 4
cols = n_devices_target // (rows * 2)
c = cutback_component(
component=polarization_rotator(design=design), rows=rows,... | 637b54385084012533bc116432e060b2bca65ea4 | 39,044 |
import math
def get_ky_and_hyp_pack(name, s1, e1, s2, e2, same: bool,
hyps: np.ndarray, kernel_grad, cutoffs=None, hyps_mask=None):
"""
computes a block of ky matrix and its derivative to hyper-parameter
If the cpu set up is None, it uses as much as posible cpus
:param hyps: list of hyper-par... | 5267c2716dc74799d90c7beb85b788385474cffe | 39,045 |
def generate_language_cnf(cnf_grammar):
""" Returns the language of a grammar in form 2 (CNF). """
key_productions = {key: [[key]] for key in _NO_EXPAND}
def is_terminal_rule(rule_rhs):
return isinstance(rule_rhs, str)
def is_nonterminal_rule(rule_rhs):
return isinstance(rule_rhs, tupl... | f4bc96da443f92bcd93912b005d5a87477d3e4ba | 39,046 |
import asyncio
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry."""
unload_ok = all(await asyncio.gather(*[
hass.config_entries.async_forward_entry_unload(entry, component)
for component in PLATFORMS
]))
if unload_ok:
hass.data[DO... | a2bd14272bf99ec509641bb4d5927d1508643510 | 39,047 |
def get_todays_image(session: Session = Depends(generate_session), group_name: str = "Home"):
"""
Returns the image for todays meal-plan.
"""
group_in_db: GroupInDB = db.groups.get(session, group_name, "name")
recipe = get_todays_meal(session, group_in_db)
recipe_image = recipe.image_dir.joinpa... | b2a6b72a1e565fa23ce204a37848899b795a3449 | 39,048 |
def get_enzyme_train_set(traindata):
"""[获取酶训练的数据集]
Args:
traindata ([DataFrame]): [description]
Returns:
[DataFrame]: [trianX, trainY]
"""
train_X = traindata.iloc[:,7:]
train_Y = traindata['isemzyme'].astype('int')
return train_X, train_Y | 8a3f6e29aca5737396c0e4007c5ff512592e51b9 | 39,049 |
import re
def get_last_cherry_pick_sha():
"""
Finds the SHA of last cherry picked commit.
SHA should be added to cherry-pick commits with -x option.
:return: SHA if found, None otherwise.
"""
get_commit = ['git', 'log', '-n', '1']
_, output = run_cmd_with_output(get_commit, exit_on_failu... | d920a847eb6f6319b4a90e88e3d551390481f461 | 39,050 |
def patch_utils_path(endpoint: str) -> str:
"""Returns the utils module to be patched for the given endpoint"""
return f"bluebird.api.resources.{endpoint}.utils" | 31ae02bd0bee7c51ea5780d297427fdac63295b3 | 39,051 |
def extract_proportions(groups: InpGroups):
""" Get species proportions of each source
and the total source emission rates
Returns:
numpy.ndarray: proportions, [sources x species]
numpy.ndarray: total emission of every source [sources x 1]
"""
srcEmiss = groups.sourceEmiss
total = np.... | c1ef46249721868617f9e30f935bbc388ce949cf | 39,052 |
def sample_randdir(num_obs, signal_ranks, R=1000, n_jobs=None):
"""
Draws samples for the random direction bound.
Parameters
----------
num_obs: int
Number of observations.
signal_ranks: list of ints
The initial signal ranks for each block.
R: int
Number of sample... | cdbbe0dcd0a362d18ff3c1692444b19848d97aae | 39,053 |
def get_artist_playmeid(h5, songidx=0):
"""
Get artist playme id from a HDF5 song file, by default the first song in it
"""
return h5.root.metadata.songs.cols.artist_playmeid[songidx] | 27fdc68a3212b9ed5a763dc7582e9178336e461f | 39,055 |
import inspect
from pathlib import Path
def validate_transformer_unit_tests(transformer):
"""Validate the unit tests of a transformer.
This function finds the module where the unit tests of the transformer
have been implemented and runs them using ``pytest``, capturing the code
coverage of the tests ... | 2211017c7ac7d31d2469fb62516a961ccc519b9f | 39,056 |
def rgbToGray(r, g, b):
"""
Converts RGB to GrayScale using luminosity method
:param r: red value (from 0.0 to 1.0)
:param g: green value (from 0.0 to 1.0)
:param b: blue value (from 0.0 to 1.0)
:return GreyScale value (from 0.0 to 1.0)
"""
g = 0.21*r + 0.72*g + 0.07*b
return g | 59a874d1458ae35e196e1ca0874b16eadfd1a434 | 39,057 |
def BottleneckBlock(
filters: int,
strides: int,
use_projection: bool,
bn_momentum: float = 0.0,
bn_epsilon: float = 1e-5,
activation: str = "relu",
se_ratio: float = 0.25,
survival_probability: float = 0.8,
name=None,
):
"""Bottleneck block variant for residual networks with BN.""... | debe89a3a1a17f0d738ed5adea9263105c759e46 | 39,058 |
def bag_of_words(words, dictionary, count=True):
"""
Compute Bag-of-Words from word list and dictionary
"""
n_feature_words = len( dictionary.keys() )
BOW = sp.zeros(n_feature_words, dtype=int)
for word in words:
if word in dictionary.keys():
if count:
BOW[ d... | edc9602edb742f6655dcd2669c2fd685977467f3 | 39,059 |
def gen_plane_cdmesh(updirection=np.array([0, 0, 1]), offset=0, name='autogen'):
"""
generate a plane bulletrigidbody node
:param updirection: the normal parameter of bulletplaneshape at panda3d
:param offset: the d parameter of bulletplaneshape at panda3d
:param name:
:return: bulletrigidbody
... | 1092cede34b8ef4c6a0eb4f24adea6bfbe528c2e | 39,060 |
def create_virt_emb(n, size):
"""Create virtual embeddings."""
emb = slim.variables.model_variable(name='virt_emb',
shape=[n, size],
dtype=tf.float32,
trainable=True,
... | 844b704d2ef0ed267f506c4976b6db6721ede791 | 39,061 |
def domain_to_index(search_domain):
"""
Convert domain name into corresponding index
"""
domain_tokens_dict = get_domain_dict()
if search_domain == 'Лингвистика':
domain_token = domain_tokens_dict.get('Linguistics')
elif search_domain == 'Социология':
domain_token = domain_token... | a6a6337aa1a079b743e1aab531eacde6c7e14df5 | 39,062 |
def choose_reads(hole, rng, n, predicate):
"""Select reads from the hole metadata."""
reads = []
required_reads = set(v for v in hole.metadata.required_reads if predicate(v))
allowed_reads = set(v for v in hole.metadata.allowed_reads if predicate(v))
while len(reads) < n and (required_reads or allowed_reads):... | cae99bcd36b6d7169da0682a5f54d168538766d5 | 39,063 |
import json
import requests
def task_test_send_template(request):
"""测试发送模板"""
datas = json.loads(request.body.decode())
address = datas["params"]["wx_bot_addr"]
data = {
"msgtype": "text",
"text": {
"content": datas["params"]["template"]
}
}
return response... | ff1e07373b0945040dd37927cca7fb6334d1f9b7 | 39,064 |
def kbrandmac(length = 8):
"""Returns a random MAC address using a list valid OUI's from ZigBee device manufacturers."""
return randmac(length) | f7cf0a139ffe8274dff0a0443d92d7dee93e2e6e | 39,065 |
import numpy
def Acf(poly, dist, N=None, **kws):
"""
Auto-correlation function.
Args:
poly (numpoly.ndpoly):
Polynomial of interest. Must have ``len(poly) > N``.
dist (Dist):
Defines the space the correlation is taken on.
N (int):
The number of ... | 0275628b070b1606781e5c7a2009e94dd2121a37 | 39,066 |
import numpy
import itertools
def position_potential_operator(n_dimensions, grid_length,
length_scale, spinless=False):
"""Return the potential operator in position space second quantization.
Args:
n_dimensions: An int giving the number of dimensions for the model.
... | 0d518089b863ee4010f864dfdac13815496f577d | 39,067 |
def maximum(x, y):
"""Returns the larger one between real number x and y."""
return x if x > y else y | e98a4e720936a0bb271ee47c389811111fd65b00 | 39,068 |
def swissPairings():
"""Returns a list of pairs of players for the next round of a match.
Assuming that there are an even number of players registered, each player
appears exactly once in the pairings. Each player is paired with another
player with an equal or nearly-equal win record, that is, a pla... | d693a5ffa010fc77e71f45e8b467a222161a2bba | 39,069 |
import asyncio
def patched_auth_succeeded_open_connection(
auth_succeeded_prepared_stream_reader, event_loop
):
"""Return a tuple of patched stream_reader and stream_writer."""
stream_writer = MagicMock()
if asyncio.iscoroutinefunction(stream_writer):
# Python 3.8.2 and later
return_va... | ed8723d1d22e6448f24708e3d558a7cf086ed039 | 39,070 |
def make_scores_df(metatlas_dataset):
"""
Returns pandas dataframe with columns 'max_intensity', 'median_rt_shift','median_mz_ppm', 'max_msms_score',
'num_frag_matches', and 'max_relative_frag_intensity', rows of compounds in metatlas_dataset, and values
of the best "score" for a given compound across a... | a8ed98b7d1a8c45977bbbb5a82e81e899967123d | 39,071 |
import tqdm
def compute_sensitivity(f_jac, X):
"""Calculate sensitivity for many samples via
.. math::
S = (I - J)^{-1} D(\frac{1}{{I-J}^{-1}})
"""
J = f_jac(X)
n_genes, n_genes_, n_cells = J.shape
S = np.zeros_like(J)
I = np.eye(n_genes)
for i in tqdm(
np.arange(n_cells... | cd8f0968be1866d1915171523338be865e7baefb | 39,072 |
import torch
def subsequent_mask(size):
"""Mask out subsequent positions (adapted from
http://nlp.seas.harvard.edu/2018/04/03/attention.html)"""
attn_shape = (1, size, size)
subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')
return torch.from_numpy(subsequent_mask) == 0 | 5612b2073c40ee01410a1b1582540338eb4c25e7 | 39,073 |
def game_to_dict(game: cpp.Game) -> GameDict:
"""Convert a game object into a dictionary (easily convertible to JSON)."""
result = {
"total": game.total_bet_score,
"bet": game.table.bet_money,
"state": game.game_state.value,
}
for cards_key, card_list in [
("playerHand", ... | 2f8bf56404063ea3818c7aafa78c94fbff7f23da | 39,074 |
def cut_square_to_circle(img):
"""
将正方形图片切割成圆形
:param img对象
:return: img对象
"""
ima = img
size = ima.size
print(size)
# 因为是要圆形,所以需要正方形的图片
r2 = min(size[0], size[1])
if size[0] != size[1]:
ima = ima.resize((r2, r2), Image.ANTIALIAS)
# 最后生成圆的半径
r3 = int(r2 / 2)
... | 7117bf2033a550cf55c7c924537dd86e19400e20 | 39,075 |
def is_acceptable_multiplier(m):
"""A 61-bit integer is acceptable if it isn't 0 mod 2**61 - 1.
"""
return 1 < m < (2 ** 61 - 1) | d099dd53296138b94ca5c1d54df39b9cf7ad2b5d | 39,076 |
def vol_rms_diff(arr_4d):
""" Return root mean square of differences between sequential volumes
Parameters
----------
data : 4D array
4D array from FMRI run with last axis indexing volumes. Call the shape
of this array (M, N, P, T) where T is the number of volumes.
Returns
---... | 08975ef02fb8cf056acbf5313e735f6aa300c0f0 | 39,077 |
def extract_all_features(imgs_collection, feature_extractor, mode):
"""
feature extraction of local and global features
This function is necessary because it is not possible to extract local features directly
with `extract_features`. Instead, if any local features are to be extracted this method calls
... | 591215b80923bc4ff52c5d8daf805068d0a90294 | 39,078 |
def extractRSS_VSIZE(line1, line2, record_number):
"""
>>> extractRSS_VSIZE("%MSG-w MemoryCheck: PostModule 19-Jun-2009 13:06:08 CEST Run: 1 Event: 1", \
"MemoryCheck: event : VSIZE 923.07 0 RSS 760.25 0")
(('1', '760.25'), ('1', '923.07'))
"""
if ("Run" in line1) and ("Event" in line1): # the first li... | 89c14bbb3a2238ec9570daf54248b4bd913eecca | 39,079 |
def cosine_distance(a, b=None):
"""Compute element-wise cosine distance between `a` and `b`.
Parameters
----------
a : tf.Tensor
A matrix of shape NxL with N row-vectors of dimensionality L.
b : tf.Tensor
A matrix of shape NxL with N row-vectors of dimensionality L.
Returns
... | 61a91f3e78dc7a3f23d35d374a4183ef8477550f | 39,080 |
import logging
def get_dicom_roi_seqs(input_dir, roi_set_zip_file):
"""Gets an iterator of ROIs from a .zip file and the list of all DICOM images in the corresponding directory.
:param input_dir: path containing the DICOM images
:param roi_set_zip_file: path to the RoiSet.zip file containing the regions o... | a55f98f5335d50010fcfc7c9453b5d5833211689 | 39,081 |
import json
def Get_db_names():
"""
Get and return database name initials from the Cloudant storage for dataset initialization
"""
#return uniqueDbnames
return json.dumps(dataset.Get_db_names()) | 2d7eaad099a84565181bf510e8175489c542aa9b | 39,082 |
def map_remove_by_key(bin_name, key, return_type):
"""Creates a map_remove_by_key operation to be used with operate or operate_ordered
The operation removes an item, specified by the key from the map stored in the specified bin.
Args:
bin_name (str): The name of the bin containing the map.
... | 6786a2cb842015483aa783b846fe688103756346 | 39,083 |
def eval_one_epoch(sess, ops, test_writer, test_data=True):
""" ops: dict mapping from string to tf ops """
if test_data:
current_data, current_label = data_utils.get_current_data_h5(
TEST_DATA, TEST_LABELS, NUM_POINT
)
else:
print("WARNING: Evaluating on train data")
... | 4527476c346e48b2944598c68299428d4dd7fdae | 39,084 |
def decode_compress_to_multi_index(encoded, idxnames=None):
"""
Decode a compressed variable to a pandas MultiIndex.
Parameters
----------
encoded : xarray.Dataset
Encoded Dataset with variables that use "compression by gathering".capitalize
idxnames : hashable or iterable of hashable, ... | b278e20da22a34a5860d6180bdd4d34e0508698b | 39,085 |
import scipy
def rank(X, cond=1.0e-12):
"""
Return the rank of a matrix X based on its generalized inverse,
not the SVD.
"""
X = np.asarray(X)
if len(X.shape) == 2:
D = scipy.linalg.svdvals(X)
return int(np.add.reduce(np.greater(D / D.max(), cond).astype(np.int32)))
else:
... | 5e513fb89fddca978f7dbde00411f153a393a4c9 | 39,086 |
def __virtual__():
"""
Only load this execution module if TTP is installed.
"""
if HAS_TTP:
return __virtualname__
return (False, " TTP execution module failed to load: TTP library not found.") | 3349eb40130b136617b0684cf69e0416a5b7e8dc | 39,087 |
def _Region4(P, x):
"""Basic equation for region 4"""
T=_TSat_P(P)
P1=_Region1(T, P)
P2=_Region2(T, P)
propiedades={}
propiedades["T"]=T
propiedades["P"]=P
propiedades["v"]=P1["v"]+x*(P2["v"]-P1["v"])
propiedades["h"]=P1["h"]+x*(P2["h"]-P1["h"])
propiedades["s"]=P1["s"]+x*(P2["s... | f074247ec1915b235386dd8eab5193ba2e47f81b | 39,088 |
import pkg_resources
def show_template_list():
"""Show available HTML templates."""
filenames = pkg_resources.resource_listdir(__name__, "data")
filenames = [f for f in filenames if f.endswith(".html")]
if not filenames:
print("No templates")
else:
for f in filenames:
p... | f86d5ec772127be6183bfe14ebda324a05e43cd3 | 39,089 |
import pathlib
def load_map(
ebsd_path: str,
min_grain_size: int = 3,
boundary_tolerance: int = 3,
use_kuwahara: bool = False,
kuwahara_tolerance: int = 5
) -> ebsd.Map:
"""Load in EBSD data and do the required prerequisite computations."""
ebsd_path = pathlib.Path(ebsd_path)
if ebsd_... | b12313028a2aecc9b17cfced8b5c19bf22e434cd | 39,090 |
import random
def print_logo():
"""
print random ascii art
"""
logo = []
logo.append("""
.------..------..------..------.
|S.--. ||T.--. ||O.--. ||Q.--. |
| :/\: || :/\: || :/\: || (\/) |
| :\/: || (__) || :\/: || :\/: |
| '--'S|| '--'T|| '--'O|| '--'Q|
`------'`------'... | 6cb2e6341c39cecd6e962dd569956508eaeee3c9 | 39,091 |
def validate(number):
"""Checks to see if the number provided is a valid CNPJ. This checks the
length and whether the check digits are correct."""
number = compact(number)
if not number.isdigit() or int(number) <= 0:
raise InvalidFormat()
if len(number) != 14:
raise InvalidLength()
... | 7a184029aa94487408d1846b4afc01f991bf1e2d | 39,092 |
def proba2float(proba, values=None, K=None, names=None):
"""Replace mu_k by a numerical value and evaluation the formula."""
if hasattr(proba, "evalf"):
if values is None and K is not None:
values = uniform_means(nbArms=K)
if names is None:
K = len(values)
na... | f90fda5917c61ac9c8ad48f72011e4a83d73a969 | 39,093 |
import hashlib
def ripemd160(msg):
"""one-line rmd160(msg) -> bytes"""
return hashlib.new('ripemd160', msg).digest() | a8484404fc3418fcca20bebfd66f36c3a33c9be3 | 39,094 |
import time
def run_ibmcloud_cmd(cmd, secrets=None, timeout=600, ignore_error=False, **kwargs):
"""
Wrapper function for `run_cmd` which if needed will perform IBM Cloud login
command before running the ibmcloud command. In the case run_cmd will fail
because the IBM cloud got disconnected, it will log... | 1d117ea5340cfb86aa7f967f36e46bdb1c3397a5 | 39,096 |
def quartznet15x5_es(classes=36, **kwargs):
"""
QuartzNet 15x5 model for Spanish language from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel
Separable Convolutions,' https://arxiv.org/abs/1910.10261.
Parameters:
----------
classes : int, default 36
Number of classif... | 64df0e85bf42ec7cfa4d20b742407ed1dda1fd6a | 39,097 |
def create_sprite_image(images):
"""Returns a sprite image consisting of images passed as argument.
Images should be count x width x height"""
if isinstance(images, list):
images = np.array(images)
img_h = images.shape[1]
img_w = images.shape[2]
n_plots = int(np.ceil(np.sqrt(images.shape[0])))
if l... | ec6514b88a651744ab2ceca74b411226ee43d806 | 39,099 |
def lineage(taxonomy, data):
"""
Get a standardized lineage for the given taxon id.
"""
if data["ncbi_tax_id"] in taxonomy:
return taxonomy["ncbi_tax_id"].lineage
return phy.lineage(data["ncbi_tax_id"]) | dcc3d583bcce2dcfc498e0cd8311a69a72a1a950 | 39,101 |
def label_accuracy_score(label_trues, label_preds, n_class):
"""Returns accuracy score evaluation result.
- overall accuracy
- mean accuracy
- mean I0U
- fwavacc
"""
hist = np.zeros((n_class, n_class))
for lt, lp in zip(label_trues, label_preds):
hist += _fast_his... | 3039e958862889f6efa9f1df156e76f8c4fd591d | 39,102 |
def candidates(address, text, confidence=0.0, support=0,
spotter='Default', disambiguator='Default',
filters=None, headers=None):
"""
Get the candidate entities from a text.
Uses the same arguments as :meth:`annotate`.
:rtype: list of surface forms
"""
payload = {... | e03810151b54cc5e9dd65c846b3df77774a41a27 | 39,103 |
def service_account_permissions(session, service_account):
# type: (Session, ServiceAccount) -> List[ServiceAccountPermission]
"""Return the permissions of a service account."""
permissions = session.query(Permission, ServiceAccountPermissionMap).filter(
Permission.id == ServiceAccountPermissionMap.... | a4fe5535a6c1b5fc788666ac50c3c79c5fd27d56 | 39,104 |
def compete_metabolite(model, metabolite, reference_dist, fraction=0.5, allow_accumulation=True, constant=1e4):
"""
Increases the usage of a metabolite based on a reference flux distributions.
Parameters
----------
model : Model
A constraint-based model.
metabolite : cobra.Metabolite
... | f127454e6319754e5bd27ea32648cc35f0b9e887 | 39,105 |
import warnings
def check_angle_sampling(nvecs, angles):
"""
Returns a list of the index of elements of n which do not have adequate
toy angle coverage. The criterion is that we must have at least one sample
in each Nyquist box when we project the toy angles along the vector n.
Parameters
---... | 60701c11d94624f9560379ef6f48bd7f3aa334b2 | 39,106 |
def corrfrac(filelist):
"""Invokes validate() on the given list of file names.
Returns the fraction of correct predictions.
"""
return float(len(validate(filelist))) / len(filelist) | 307c6e52f53162e1b24ec115f314930f3b7ed38b | 39,107 |
import requests
def create_graph(workspace: str, graph_name: str, edge_table: str) -> bool:
"""Create a graph."""
resp = requests.post(
f"{root_api_endpoint()}/workspaces/{workspace}/graphs/{graph_name}",
params={"edge_table": edge_table},
)
if resp.ok:
return True
return... | f6ab58b4d76909950e06e441874877009dfc732e | 39,108 |
def main():
"""Main method of this script."""
# Use the directory that contains recordings on Dreamboxes as default.
default_directory = '/media/hdd/movie'
# Per default we want to have 50GB of free space.
min_avail_space = 50*1024
# Override defaults with values given on the command line.
... | 8f89b2054c480974b70e487053582ed14ce006e0 | 39,109 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.