content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_activity_score(target_gene, haplotype_call):
"""Convert haplotype call to activity score.
Parameters
----------
target_gene : str
Name of the target gene (e.g. cyp2d6).
haplotype_call : str
Haplotype call.
Returns
-------
float
Activity_score.
"""
... | b26d1db765cbd8189a3878cd4398db186412a4dd | 3,618,333 |
def datagroup1D(kwsd=None, _larch=None):
"""utility to perform wrapped operations on a list of 1D data
groups"""
return DataGroup1D(kwsd=kwsd, _larch=_larch) | 269eff221f149567aefe9c37ed8a763d7f2cc3cf | 3,618,336 |
import time
def wait_for_status(client, stream_name, status, wait_timeout=300,
check_mode=False):
"""Wait for the status to change for a Kinesis Stream.
Args:
client (botocore.client.EC2): Boto3 client
stream_name (str): The name of the kinesis stream.
status (str):... | c7a14e069d7c356e2bac3f05c15ee85f1b7141c3 | 3,618,338 |
import csv
def read_aa_losses(filename):
"""
Read AA losses from data file. (assume fixed structure...)
"""
aa_losses = {}
with open(filename, 'r') as f:
reader = csv.reader(f, delimiter=',')
next(reader) # skip headers
for line in reader:
if len(line) == 0:
... | b1ba8349d01d43112ef67436fa2bb09d3bed768c | 3,618,339 |
def filter_document(ctx, user_id, project_id, id_str):
"""Gets and returns the first document by project id and id str
Admin level access will ignore user_id parameter.
:param ctx: context
:param user_id: user id (not username)
:param project_id: project id
:param id_str:
:return:
"""
... | 66bfdf1f6ef82be8abffb7b9f6c50935ec36c4c0 | 3,618,340 |
def message_in_state(message, state_slug):
"""
Checks if a message is tagged with a race that is in a given state.
"""
races = get_races_from_message(message)
for race in races:
if race.split("-")[0].lower() == slug_to_postal(state_slug).lower():
return True
return False | b917bb5ce1a68cdb6d017289d6569d9fcd930137 | 3,618,341 |
def get_matching_taxon(brow):
"""
Searches taxon objects for taxa matching an occurrence
:param row:
:return: returns a single element record set
"""
# get data from all taxon fields and collect them in a list
# e.g. ["Animalia", "Chordata", "Mammalia", "Primates", "", "Hominidae", "", "", "... | 8d1edf3250035a890b25cb1bebd907dce88581de | 3,618,342 |
from typing import OrderedDict
def calc_injection(request):
"""Calculates injection dosages based on weight.
GET parameters:
weight: weight in lbs
Contxt:
calculated dose rounded to 3 decimal places
"""
meds = Injection.objects.all()
rx = dict()
# default displayed dos... | aeefe317f76cfb2dc4d802360758729aa97843f5 | 3,618,343 |
def add(M1, M2):
"""
Returns a matrix Q, where Q[i][j] = M1[i][j] + M2[i][j].
M2 is replaced by Q.
"""
m = len(M1)
n = len(M1[0])
for p in range(m):
for q in range(n):
M2[p][q] = M2[p][q] + M1[p][q]
return M2 | ac86e9109f6287cde062392992bf64dbf49614f5 | 3,618,345 |
def compute_groupwise(y_hat, y, ct, num_groups):
"""
:param y_hat: (N, ). Prediction from M, binary
:param y: (N, ) true label
:param ct: (N, ) group membership fo each instance
:param num_groups: int
:return:
"""
tpr = np.zeros((num_groups,))
fpr = np.zeros((num_groups,))
tnr =... | 06b548b3ed3939a3a704337edc208fed002c97b2 | 3,618,346 |
def attention(inputs,
input_shape,
attention_size,
context=None,
context_shape=None):
"""General attention mechanism model.
It return the weighted average of inputs and the weights.
Args:
inputs: A 3D shaped Tensor [batch_size x time x input_... | fe5cdd3b01ef39332a9bca3be65b0808c0113127 | 3,618,347 |
def cal_zscores(gdf, fieldNames):
"""
claculate z-scores for variables in sample point dataframe columns
Arguments:
gdf {GeoDataFrame} -- some new fields will add to zscore
fieldNames {list} -- field names, the columns needed to calculate zscores
Returns:
GeoDataFrame -- the da... | 36300245d5096cb511de33ec3f1575027c0af7a8 | 3,618,348 |
def analyze_tower(img, mask, data):
""" Detects tower using horizontal coins """
out_img, infos = analyze_horizontal_coin(img, mask, data)
if infos:
tower_info = init_detected_object('tower', data)
tower_info.centroid = [np.mean([i.centroid[0] for i in infos]),
... | 03bc23c0cada6b22e80b0e8e959d4e2421d50369 | 3,618,349 |
from re import X
def whowinner(board):
"""
Returns the winner of the game, if there is one.
"""
for i in range(bs-nt+1):
for j in range(bs-nt+1):
subboard = [[board[i+row][j+col] for col in range(nt)] for row in range(nt)]
if X_winner(subboard):
return X... | 7504363df97285684ea8790cc048da7d1b2b49e7 | 3,618,350 |
from typing import Optional
async def get_leak_cable_id(
cable_id: str,
from_date: Optional[str] = None,
to_date: Optional[str] = None,
token: str = Security(access_token_header),
):
"""
Download probalilities of leak on a single oilcables
Args:
cable_id: cable id
... | 076c0c4f424583e03f553c3fe5166473599304c5 | 3,618,352 |
def _async_register_events_and_services(hass: HomeAssistant):
"""Register events and services for HomeKit."""
hass.http.register_view(HomeKitPairingQRView)
def handle_homekit_reset_accessory(service):
"""Handle start HomeKit service call."""
for entry_id in hass.data[DOMAIN]:
i... | a0c713d3815827dd96e8aa3b4d8f8f18fd7fd5b7 | 3,618,353 |
import requests
def manual_action(request, **kwargs):
"""
Create an instance of Event.
Make a request to raspberry pi to lock/unlock.
Chanage lock status to pending. Redirect to dashboard
"""
lock = Lock.objects.get(pk=kwargs['pk'])
data = {
'lock_id': kwargs['pk'],
'actio... | 95403408292435020ac68129eacd5b09f02df2b2 | 3,618,354 |
def displace_PSF_moffat(x, y, FWHM, beta):
"""
:param x: x-coordinate of light ray
:param y: y-coordinate of light ray
:param FWHM: full width at half maximum
:param beta: Moffat beta parameter
:return: displaced ray by PSF
"""
X = draw_moffat_r(FWHM, beta)
dx, dy = draw_xy(X)
r... | 8ed0c7625c5f36aca3b456fcc1688b3298fa9c10 | 3,618,355 |
def generate_config(context):
""" Entry point for the deployment resources. """
properties = context.properties
name = properties.get('name', context.env['name'])
project_id = properties.get('project', context.env['project'])
zone = properties.get('zone')
# Network formatting
if 'network' ... | 8398401dea1c6a2251a7ccc9c763337fa7f0e7e5 | 3,618,356 |
def set_parameters(goal,bifurcation,parentDir):
"""Set all needed node and network parameters
Parameters
----------
goal : string, can be 'sync' or 'switch'
the control task
bifurcation : string, can be 'low' or 'high'
bifurcation lne close to which parameter... | 540ae1fd21075d8d7b5beecf6fdb0ad21e07ef22 | 3,618,357 |
def get_config_by_url(cfg, url):
"""
:param cfg: dictionary
:param url: path to value separated by dot, e.g, key1.key2.key3
:return: value from dictionary
"""
keys = url.split('.')
for key in keys:
cfg = cfg[key]
return cfg | 0dd2a01a2ecd198f044eebcd3f854f96dbf945bd | 3,618,358 |
import math
def entropy(values):
"""A slow way to calculate the entropy of the input values"""
values = values.flatten()
#calculate the probablility of a value in a vector
vUni = sp.unique(values)
vlen = len(vUni)
lenval = float(len(values))
FreqData = sp.zeros_like(vUni)
for... | db759d0ddcc910123722d20a5b9c8ca66e07276d | 3,618,359 |
def remove_brackets(s: pd.Series) -> pd.Series:
"""
Remove content within brackets and the brackets itself.
Remove content from any kind of brackets, (), [], {}, <>.
Examples
--------
>>> import texthero as hero
>>> import pandas as pd
>>> s = pd.Series("Texthero (round) [square] [curl... | f2faabd9b347c70fdf05cea4137d27d941469f5a | 3,618,360 |
def test_executor_error_override(
batch_submit_mock, iter_batch_job_status_mock, parse_task_logs_mock, get_aws_user_mock
) -> None:
"""
Some AWS Batch errors should be overridden.
"""
@task()
def task1(x):
return x + 10
@task(script=True)
def task_script1(x):
return "ls... | adc9b74a38981ebe6413ab6ce49d7963bbbb5970 | 3,618,361 |
def blur(img):
"""
:param img: SimpleImage, the image to be blurred
:return: SimpleImage, the blurred image
"""
# Create a blank frame for blurred pixels.
blur_img = SimpleImage.blank(img.width, img.height)
# Loop the original image.
for x in range(img.width):
for y in range(img.... | 88442ebe166983509e11b0ca48eda796addab0c6 | 3,618,362 |
from typing import Any
def not_a_seq_complex(request: Any) -> Any:
"""Provide random values that are not sequences of complexs."""
return request.param[1] | ad28133edced67801deab511100b19606dfa2cd3 | 3,618,363 |
def generate_markov_models(user_names):
"""
Builds a dictionary of user_name :: Markov text models from the text corpus of each user.
:param user_names: A list of the users' names to build. Assumes there is a corresponding "user.txt" corpus available
:return: text_models - a dictionary of users and thei... | 01517bdc11728ec0324021538ed497d637955e99 | 3,618,364 |
import math
def planckian_table(uv, cmfs, start, end, count):
"""
Returns a planckian table from given *CIE UCS* colourspace *uv*
chromaticity coordinates, colour matching functions and temperature range
using *Yoshi Ohno (2013)* method.
Parameters
----------
uv : array_like
*uv* ... | 357a3f645dee2c9d81431596855d65355feb5e7c | 3,618,365 |
def vault_subscribe():
""" Subscribe to a remote vault service on the specific hive node,
where would create a new vault service if no such vault existed against the DID used.
A user can subscribe to only one vault service on the specific hive node with a given DID,
then should declare that service end... | fd9b899329db11c34759b01c34fdd098770350a9 | 3,618,366 |
def atrim(stream: Stream, *args, **kwargs) -> FilterableStream:
"""https://ffmpeg.org/ffmpeg-filters.html#atrim"""
return filter(stream, atrim.__name__, *args, **kwargs) | 5f0faba73697f6e73d6d93a2cbeac52cec82f63e | 3,618,367 |
def cut_transcript_seq(seq: str, tag: str):
"""
Some of the sequences contain length % 3 != 0, because they have ambiguous
start and/or end. If this is the case, they should be cut until length % 3 == 0
There are sequences which have both ambiguous start and end => no solution yet
:param seq: dna se... | 3fdc6512f1edc47157778b828b944fdf940fa37a | 3,618,368 |
def kama(df, price, kama, n, fast_ema=2, slow_ema=30):
"""
Kaufman's Adaptive Moving Average (KAMA) is a moving average designed to
account for market noise or volatility. KAMA will closely follow prices when
the price swings are relatively small and the noise is low. KAMA will adjust
when the price... | 58969929ad098c92346e21910002f1d5c9428ed6 | 3,618,369 |
import base64
def NumpyDecoder(dct):
"""
Decodes a previously encoded numpy ndarray
with proper shape and dtype
:param dct: (dict) json encoded ndarray
:return: (ndarray) if input was an encoded ndarray
"""
if isinstance(dct, dict) and '__ndarray__' in dct:
if 'dtype' in dct:
... | 9f6e42998bfbcbf6437c63798e906748f0cc75d6 | 3,618,370 |
import warnings
def get_silverkite_uncertainty_dict(
uncertainty,
simple_freq=SimpleTimeFrequencyEnum.DAY.name,
coverage=None):
"""Returns an uncertainty_dict for
`~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`
input parameter: uncertainty_dict.... | be1b954191d1a8c8a18d33a30ed93a728219e22c | 3,618,371 |
def get_xclarity_client():
"""Generates an instance of the XClarity client.
Generates an instance of the XClarity client using the imported
xclarity_client library.
:returns: an instance of the XClarity client
:raises: XClarityError if can't get to the XClarity client
"""
try:
xcla... | f19e6c19708817fe3f65e68cf461b69f826acbc0 | 3,618,372 |
def create_vgg_model_2d(input_image_size,
number_of_classification_labels=1000,
layers=(1, 2, 3, 4, 4),
lowest_resolution=64,
convolution_kernel_size=(3, 3),
pool_size=(2, 2),
... | 2b8554cdda1eabcc6e0ec37ba455216420dbd93c | 3,618,373 |
def _transition_down_block(x, nb_filter, bn_momentum, weight_decay=1e-4, transition_pooling='max',
block_prefix='TransitionDown', data_format='channels_last'):
"""
Adds a pointwise convolution layer (with batch normalization and relu),
and a pooling layer.
The block cuts... | db5aaedb5d04d16da8414eb4162ff357f737d5c9 | 3,618,374 |
from typing import Union
from typing import List
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Dict
def collect_mentioned(
obj: Union[RawFactor, List[Union[RawFactor, str]]],
mentioned: Optional[Mentioned] = None,
ignore: Sequence[str] = (
"pre... | 6e3995087e438d450572ea60bc86bddde89aa86c | 3,618,375 |
def add(x, y):
"""相加"""
return x + y | cddb73c428639231bc993ffa775717bf10e0a04b | 3,618,376 |
def calculate_mmc(y_true, y_pred):
"""Using sklearn to compute the Matthews correlation coefficient (MCC).
Arguments:
y_true {numpy.array} -- the true labels corresponding to each input
y_pred {numpy.array} -- the model's predictions
Returns:
mmc {float} -- the calcu... | cbd66eba6c8fa5d0d00bfa36aea363ec9441113d | 3,618,378 |
def _get_element_imports(*elements: Element) -> str:
"""Get the import string for the elements in use."""
prefix = "from statham.schema.elements import "
max_length = 80
import_names = [
elem_type.__name__
for elem_type in set.union(
*(_get_single_element_imports(element) for... | 83bac80556ce0804d00307cab406e2545046787d | 3,618,380 |
def getSpawnProcPIDs():
"""Fetch all running DummyMP system process IDs.
Looking through all of the DummyMP processes, determine if any are
running, and if any, retrieve their system process IDs.
Args:
None
Returns:
list: An list with the system process IDs of current ... | da6601f53d80d3decdb64f3bc548e7c36eb31160 | 3,618,381 |
def posdef(m):
"""Map a matrix to a positive definite matrix, where all eigenvalues are >= 1e-5."""
mlambda, mvec = jnp.linalg.eigh(m)
mlambda = jnp.maximum(mlambda, 1e-5)
return (mvec * jnp.expand_dims(mlambda, -2)) @ jnp.swapaxes(mvec, -2, -1) | 1830e673f9972d0ab8ad31f5a847e5d8d8c4892c | 3,618,382 |
def error_500_view(request):
"""
Renders the 500 error page.
"""
return render(request, 'climate/500.html') | d9315290ac4c3b29505ef5c2411e6dcf5c528d3c | 3,618,383 |
def get_congratulation_template(elapsed_time: int) -> str:
"""
Получение шаблона при победе,
в зависимости от окончания числа секунд игры.
"""
if 11 <= elapsed_time <= 19 or elapsed_time % 10 in (0, 5, 6, 7, 8, 9):
template = "Поздравляем, вы прошли игру за {elapsed_time} секунд!"
elif e... | ad683c224e8db8f9cbacc500561420e5fbb82e0f | 3,618,384 |
import six
def _get_column(column):
"""
Helper to get a ``Column`` object if the given argument is a string
"""
if isinstance(column, six.text_type):
column = col(column)
if not isinstance(column, Column):
raise ValueError('A Column or a column name (as a string) is expected. Got {... | 3d344dca81408031111179f2f58adefd0081bc1e | 3,618,385 |
def smooth(path, weight_data=0.1, weight_smooth=0.2, tolerance=0.000001):
"""
Creates a smooth path for a n-dimensional series of coordinates.
Arguments:
path: List containing coordinates of a path
weight_data: Float, how much weight to update the data (alpha)
weight_smooth: Float, h... | e98e1cd0122a820ed6559ef8255e121cd6ca4bdb | 3,618,386 |
def CDLDOJI(barDs, count):
"""Doji"""
return call_talib_with_ohlc(barDs, count, talib.CDLDOJI) | 3aec27b5ad91132b63ec294cc675c83ef9b954e0 | 3,618,387 |
import json
import yaml
from pathlib import Path
from openghg.util import get_datapath
def get_ceda_file( # type: ignore
filepath=None,
site=None,
instrument=None,
height=None,
write_yaml=False,
date_range=None,
):
"""Creates a JSON (with a yaml extension for CEDA reasons) object
for ... | da9d4d9b4221acead21e34f0b258f6c02349b521 | 3,618,389 |
def parse_variable_name(packed_bytes):
""" Unpack a 6-bit packed variable name """
variable_name = ""
this_char = 0
read_bits = 0
for byte in packed_bytes:
# Read six bits at a time
for bit in range(0, 8):
bit_value = 1 & (byte >> (7 - bit))
this_char = this_... | 4aea77c7433ec9c6b411a939c2ac411f74928383 | 3,618,391 |
def divide(self, other, op_cols, **kwargs):
"""
Divide values (self / other)
Parameters
----------
other : :class:`ScmRun <scmdata.run.ScmRun>`
:class:`ScmRun <scmdata.run.ScmRun>` containing data to divide
op_cols : dict of str: str
Dictionary containing the columns to drop be... | 5094f6fffd5841dd97c395bd50ae66ba96ba6162 | 3,618,392 |
import ast
def tokenize_code(blob, language='java'):
"""
:param blob:
:param language:
:return:
"""
if language == 'python':
parsed_code = astor.to_source(ast.parse(blob))
tokenized_code = [x for x in RegexpTokenizer(r'\w+').tokenize(parsed_code) if not is_numeric(x)]
... | 8b77748a2878ab7b862a9da022741768088e7d9f | 3,618,393 |
def create_love_relationship(user, posts):
"""Creates a love relationship between a profile/user and a post
Args:
user -- user who is a fan of the post
post -- a list of posts
Returns:
a list of loves
"""
loves = []
for post in posts:
loves.append(LoveFactory(fan=... | 433fe7cf2f809534c21edb3b7e113de1e716038b | 3,618,394 |
def task_run_black():
"""
calls black code formatter
"""
task = {
'actions': ['black textwalker'],
'verbosity': 2
}
return task | 794fc232bb9096c39885d8ffe25c14b8105ac6b6 | 3,618,395 |
def to_weld_vec(weld_type, ndim):
"""Convert multi-dimensional data to WeldVec types.
Parameters
----------
weld_type : WeldType
WeldType of data.
ndim : int
Number of dimensions.
Returns
-------
WeldVec
WeldVec of 1 or more dimensions.
"""
for i in ran... | a131226065087d8923ac66f137f34691a673f6ed | 3,618,396 |
def imq_kernel(x, y, score_x, score_y, g=1, beta=0.5, return_kernel=False):
"""Compute the IMQ Stein kernel between x and y
Parameters
----------
x : torch.tensor, shape (n, p)
Input particles
y : torch.tensor, shape (n, p)
Input particles
score_x : torch.tensor, shape (n, p)
... | 08c95b04789f47b557645df975a20c1f1b478a0d | 3,618,397 |
def get_target_config_dict(target_obj):
"""Gets target config as a dict from object
:param target_obj: target object
:type target_obj:
:return: Target config
:rtype: `dict`
"""
target_config = dict(TARGET_CONFIG)
if target_obj:
for key in list(TARGET_CONFIG.keys()):
... | 828375d4883c32e1d99f14efc4264de278d9ce95 | 3,618,398 |
def blend(m):
"""Blend colors."""
base = m.group('base')
color = m.group('color')
blend_type = m.group('type')
percent = m.group('percent')
if percent.endswith('%'):
percent = float(percent.strip('%'))
else:
percent = int(alpha_dec_normalize(percent), 16) * (100.0 / 255.0)
... | 5b23a8650acca1fb81cb843466152395e616f130 | 3,618,399 |
def get_solution(program: Program, monomial: Poly):
"""
For a given monomial returns its expected value by first checking if it already has been computed and stored
"""
log(f"Start get solution, { monomial.as_expr() }", LOG_VERBOSE)
global solution_store
if monomial_is_constant(monomial):
... | 0ad925e7de45155a6898606bd82896610c391882 | 3,618,400 |
def point_cloud_label_to_volume_batch(point_clouds, labels, weights, vsize=12, radius=1.1, flatten=True):
""" Input is BxNx3 batch of point cloud
Output is Bx(vsize^3)
"""
vol_list = []
label_list = []
weight_list = []
for b in range(point_clouds.shape[0]):
vol, label, weight = p... | ea5ddf63f0bf433ea03da7db6739dae882f668bf | 3,618,401 |
def box_to_center_scale(box, model_image_width, model_image_height):
"""convert a box to center,scale information required for pose transformation
Parameters
----------
box : list of tuple
list of length 2 with two tuples of floats representing
bottom left and top right corner of a box
... | 4286fcd73e71978a32d58b0631bbb55c8be5a276 | 3,618,402 |
def build_rgb_and_opacity(s):
"""
Given a KML color string, return an equivalent RGB hex color string and an opacity float rounded to 2 decimal places.
EXAMPLE::
>>> build_rgb_and_opacity('ee001122')
('#221100', 0.93)
"""
# Set defaults
color = '000000'
opacity = 1
... | 06cb729338584c9b3b934a844f5a2ec53245e967 | 3,618,403 |
def design_sosmat_band_passes(order, band_edges, sample_rate,
edge_correction_percent=0.0):
"""Return matrix containig sos coeffs of bandpasses.
Parameters
----------
order : int
Order of the band pass filters.
band_edges : ndarray
Band edge frequencies... | 44a772245cb5fa0de8a81a96b01f85aaa01678f7 | 3,618,404 |
import aiohttp
async def shorten(long_url: str, api_base: str, api_key: str):
"""
Creates a short url if valid.
"""
params = {
'url': long_url,
'key': api_key,
'response_type': 'json'
}
async with aiohttp.ClientSession() as sess:
async with sess.get(api_base + '... | 14bad17b0b39ab09526269ec105086e2ac497f4a | 3,618,405 |
def policy_iteration(problem_data, problem_data_known, K0, L0, sim_options=None, num_iterations=100,
print_iterates=True):
"""Policy iteration"""
problem_data_keys = ['A', 'B', 'C', 'Ai', 'Bj', 'Ck', 'varAi', 'varBj', 'varCk', 'Q', 'R', 'S']
A, B, C, Ai, Bj, Ck, varAi, varBj, varCk, Q, ... | 5269f527cadd1799c0bf37fc22a83b9730c11e43 | 3,618,406 |
import tempfile
import ctypes
def delta(f, s, d=None):
"""
Create a delta for the file `f` using the signature read from `s`. The delta
will be written to `d`. If `d` is omitted, a temporary file will be used.
This function returns the delta file `d`. All parameters must be file-like
objects.
... | 0330809209b3c3a33682b6d70f6c3a3d753b4d5d | 3,618,409 |
def wrap(func):
"""
Return a wrapped function object.
If arg is already a wrapped function object, return that.
Parameters
----------
func : function or OMwrappedFunc
A plain or already wrapped function object.
Returns
-------
OMwrappedFunc
The wrapped function obj... | 028bac0c8a6d380e90c9ffe49a72044e3303cf20 | 3,618,410 |
def delete_channel(medialive, event, context):
"""
Delete a MediaLive channel
Return success/failure
"""
channel_id = event["PhysicalResourceId"]
try:
# stop the channel
medialive.stop_channel(ChannelId=channel_id)
# wait untl the channel is idle, otherwise the lambda w... | 802f65dc310ffb44ef81f91606e0b26bf3b1a6a0 | 3,618,411 |
def relevant_files(root_dir, include_regex='', exclude="*****"):
"""Return list of files with inclusion regex and exclusion regex.
inputs:
"root_dir" is the root directory
"include_regex" is the string that is searched for within filenames
"exclude_regex" is the string that will exclude files if fo... | 2c7d358619a716dbff5bcac82d9a66e9ba48073d | 3,618,412 |
def edges_and_nodes_csv_to_graph(fpath_nodes, fpath_edges, u_tag = 'stnode', v_tag = 'endnode', geometry_tag = 'Wkt', largest_G = False):
"""
Function for generating a G object from a saved .csv of edges
:param fpath_nodes:
path to a .csv containing nodes
:param fpath_edges:
path to a .c... | 7bc295a17744947e03d76b56fc6713442f802511 | 3,618,413 |
def compute_iou(rec1, rec2):
"""
computing IoU
:param rec1: (y0, x0, y1, x1), which reflects
(top, left, bottom, right)
:param rec2: (y0, x0, y1, x1)
:return: scala value of IoU
"""
# computing area of each rectangles
S_rec1 = (rec1[2]) * (rec1[3] )
S_rec2 = (rec2[2] ) * ... | 2e445d7243ace1c3255cfa4c66d72a8bef405bdc | 3,618,414 |
def fn_minimum_argcount(callable):
"""Returns the minimum number of arguments that must be provided for the call to succeed."""
fn = get_fn(callable)
available_argcount = fn_available_argcount(callable)
try:
return available_argcount - len(fn.__defaults__)
except TypeError:
return av... | 1eb56b741f5e77fdb2613737143304d7b013943e | 3,618,415 |
async def get_by_id(id: str):
"""
### Recurso que tem por objetivo buscar uma pessoa.
#### Usa como parametro de busca o seu identificador:
- id [str(ObjectId)] = "605dcc895dbd779d5e66bd90"
"""
try:
manage_legal_person = ManageLegalPerson()
legal_person = await ma... | 861348057f69dd79b793992919701bd13b9df15c | 3,618,416 |
import json
import re
import copy
def fill_template(req_sig, responses):
"""
Fills the template and returns filled request signature else
returns None if template is not fillable due to dependencies.
"""
req_sig_str = json.dumps(req_sig)
matches = re.findall(r"{([a-zA-Z0-9\.]+)}", req_sig_str)
for match in mat... | db0569f0fa1272685908f66973e322d2cc68ebce | 3,618,417 |
def get_shader(material_name):
"""
Convenience function for obtaining the shader that the specified material (as an argument)
is attached to.
:param material_name: Takes the material name as an argument to get associated shader object
:return:
"""
connections = mc.listConnections(material_n... | 84b96bfac31ea20ff9a02fca555d99994e6c71ab | 3,618,418 |
def _expr(lex):
"""Return an expression."""
return _ite(lex) | 3b033271540cca9822f73f9bef06d3943677f2c5 | 3,618,419 |
import numpy
def GQSignal_fetch_position_singal_day(start,
end,
frequence='day',
market_type=QA.MARKET_TYPE.STOCK_CN,
portfolio='myportfolio',
... | a2366001235089667fd4ba0aa878b46f62d5a45b | 3,618,420 |
import base64
def return_diagram_as_base64(activities_count, dfg, format="svg", measure="frequency", maxNoOfEdgesInDiagram=75):
"""
Return process model in Base64 format
Parameters
-----------
activities_count
Count of attributes in the log (may include attributes that are not in the DFG ... | 6525f2faf61f85b568af6005ca6610de18a59b95 | 3,618,421 |
def url_add_api_key(url_dict: dict, api_key: str) -> str:
"""Attaches the api key to a given url
Args:
url_dict: Dict with the request url and it's relevant metadata.
api_key: User's API key provided by US Census.
Returns:
URL with attached API key infor... | 1442d0f67a1f3603205870d1af0baf30eb3f1d50 | 3,618,422 |
def validate(schema, data, name=None):
"""
Validate data against a schema
"""
try:
return schema(data)
except Invalid as exn:
raise loudml.errors.Invalid(
exn.error_message,
name=name,
path=exn.path,
) | d2101b79ec9b7d64c7d692a55df291786fcb45d4 | 3,618,423 |
from pathlib import Path
def config_file_path(token_file: str) -> Path:
"""Provide Path to config file"""
if token_file is None:
return Path.joinpath(Path.home(), ".rmapi")
else:
return Path(token_file) | 8f31d64bcb720999080a9bf61b3f174d6882141c | 3,618,424 |
from typing import BinaryIO
def _read_ctb(stream: BinaryIO) -> ColorDependentPlotStyles:
""" Read a CTB-file from from binary `stream`. """
content = _decompress(stream)
content = content.decode()
styles = ColorDependentPlotStyles()
styles.parse(content)
return styles | 4e28d123c9c42a28efcc19b3816588067a9438ff | 3,618,425 |
def _compute_fans(shape):
"""Computes the fan-in and fan-out for a depthwise convolution's kernel."""
if len(shape) != 4:
raise ValueError(
'DepthwiseVarianceScaling() is only supported for the rank-4 kernels '
'of 2D depthwise convolutions. Bad kernel shape: {}'
.format(str(shape)))
... | a33bfdf32080147f092d32fca1d70a90b2b25e91 | 3,618,426 |
from typing import Mapping
from typing import List
from typing import Tuple
from typing import Optional
def _topological_sort(
graph: Mapping[str, List[str]]
) -> Tuple[Optional[List[str]], Optional[str]]:
"""
Figure out the dependency graph using the topological sort.
Return None if there is a cycle... | 64bf5f4c230e6d7d8c1eb2c159ccecf2fc054bd8 | 3,618,427 |
def get_model(pretrained_model_file, latent_dim, n_init_retrain_epochs, n_retrain_epochs, retrain_from_scratch, ite, save_dir, data_enc, data_scores, data_weighter):
""" load or train the model """
if ite == 1:
print_flush("Loading pre-trained model...")
new_weights_dir = pretrained_model_file
... | a1b7ebfe8ea7ec4e85c8290c51088199dfb212df | 3,618,428 |
def get_relation_param_dict(relation: str, filename: str) -> RelationParams:
"""'Get the relation line parameters.
Given a relation string with with the format
ID\tREL_TYPE E1_TYPE:E1_ID E2_TYPE:E2_ID'
Create a dictionary with the following entity properties:
* fname: str
* id... | 83706798d6a1eb9d0e227cba78bb6aa09b41a885 | 3,618,429 |
def get_analog_unit(itf, sig_name, log=False):
"""
Return the unit of an analog channel.
Parameters
----------
itf : win32com.client.CDispatch
COM object of the C3Dserver.
sig_name : str
Analog channel name.
log : bool, optional
Whether to write logs or not. The defa... | aff3a886a4d766bc2a7ad0ee91294d8a4a4b176c | 3,618,430 |
def truncated_mean(data, n):
"""Compute a truncated mean, n is truncation size"""
return mean(truncated_list(data, n)) | eb7698f40883081d4907a7b1119deb98f4f3cbe0 | 3,618,431 |
import pandas
import math
def HMA(df: pandas.DataFrame, period: int = 7, column: str = "positive") -> pandas.Series:
"""
HMA indicator is a common abbreviation of Hull Moving Average.
The average was developed by Allan Hull and is used mainly to identify the current market trend.
Unlike SMA (simple mo... | f40ffb434607c5a5b1b0143e9dffafe3a70d262e | 3,618,432 |
def array_affine_coord(mask, affine):
"""Compute coordinates from a boolean array and an affine transform
Parameters
----------
mask: nd array,
input array, interpreted as a mask
affine: (n+1, n+1) matrix,
affine transform that maps the mask points to some embedding space
... | 035f40ad950771b3baddaff3062611b538024068 | 3,618,433 |
def openssl_sha256(message: bytes) -> bytes:
""" Hash function for signature and public key generation
This functions wraps a hashfunction in a way that it takes a byte-sequence
as an argument and returns the hash of that byte-sequence
Args:
message: Byte-sequence to be hashed
Returns:
... | 52604fcb8fae4f34cecb7ca4c14d271ce8c68284 | 3,618,434 |
def merge_shards(shard_data, existing):
"""
Compares ``shard_data`` with ``existing`` and updates ``shard_data`` with
any items of ``existing`` that take precedence over the corresponding item
in ``shard_data``.
:param shard_data: a dict representation of shard range that may be
modified by... | 18704dd79274dd7ec6157cd28be04a5858e6cff7 | 3,618,435 |
def config() -> Config:
"""Give the rest of the plugin access to shared configuration."""
if _CONFIG is None:
raise RuntimeError("Plugin state not initialized; call set_config() before config()")
return _CONFIG | 0218216dc911c0f7b7bc6b13df2758b6f111b70d | 3,618,436 |
def densify(line, step):
"""
Given a line segment, return another line segment with the same start & endpoints,
and equally spaced sub-points based on `step` size.
All the points on the new line are guaranteed to intersect with the original line,
and the first and last points will be the same.
... | 9956ac13c1cdb586c8065e9bdc639dbe83630fee | 3,618,437 |
import math
import statistics
def get_cell_types(cpath, tissue, connect=False, smooth=False):
"""
Prepare database and clusters for upcoming ranking calculations
:param cpath: string
:param tissue: string
:param connect: boolean
:param smooth: boolean
:return: dictionary
"""
cluste... | ba28c157affec0ca12dc6bc0a7c869109227a4bc | 3,618,438 |
async def _eqxdo(text):
"""Run xdotool against the display holding EverQuest"""
return await _xdotool(await _eqdisplay(), text) | d2d824d2ebeb93f7319a9bd5745a9642e2c16792 | 3,618,439 |
from cacao_accounting.database import Cuentas, Entidad
def obtener_catalogo_base(entidad_=None):
"""Utilidad para devolver el catalogo de cuentas."""
if entidad_:
ctas_base = Cuentas.query.filter(Cuentas.padre == None, Cuentas.entidad == entidad_).all() # noqa: E711
else:
ctas_base = (
... | 84e6fde0e0a73cd6d3690a08745e7e57a64b8366 | 3,618,440 |
from typing import Tuple
def normalize_image(image: np.array,
mean: Tuple[float, float, float] = (0.485, 0.456, 0.406),
std: Tuple[float, float, float] = (0.229, 0.224, 0.225),
max_pixel_value: float = 255.0) -> np.ndarray:
"""
Normalize image (with ... | 3e39dc30909665b822b3e1be5feae91145eab384 | 3,618,441 |
def similar(a, b):
"""
Checks if wordlists are *very* similar in a *very naive* way.
:param a: set of words
:param b: set of words
:return: True if the word lists are similar
"""
count = 0
for w in a:
if w in b:
count += 1
return _almost(count, len(a), len(b)) | 907b4b7fe20b20e31baf399bdac5ef9535d13203 | 3,618,442 |
from typing import Dict
from typing import List
from typing import Match
from typing import Set
def get_lines_to_display(
flat_matches_dict: Dict[int, List[Match]], lines: List, nb_lines: int
) -> Set[int]:
""" Retrieve the line indexes to display in the content with no secrets. """
lines_to_display: Set[... | 9a31e1686576e1deac0a1e85f6dee0d708736ebb | 3,618,443 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.