content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def body_contour(binary_image):
"""Helper function to get body contour"""
contours = find_contours(binary_image)
areas = [cv2.contourArea(cnt) for cnt in contours]
body_idx = np.argmax(areas)
return contours[body_idx] | 0ccfa7340d492f89c6c0090c296e7aede379754a | 8,152 |
def rule_like(rule, pattern):
"""
Check if JsonLogic rule matches a certain 'pattern'.
Pattern follows the same structure as a normal JsonLogic rule
with the following extensions:
- '@' element matches anything:
1 == '@'
"jsonlogic" == '@'
[1, 2] == '@'
{'+': [1, 2]... | cd058d799cdee4d548c3e2075e1555ea28e594f1 | 8,153 |
def apt_repo(module, *args):
"""run apt-repo with args and return its output"""
# make args list to use in concatenation
args = list(args)
rc, out, err = module.run_command([APT_REPO_PATH] + args)
if rc != 0:
module.fail_json(msg="'%s' failed: %s" % (' '.join(['apt-repo'] + args), err))
... | d4572cb9d586b973d461e4ac33709e582c26dda7 | 8,154 |
def get_rasterization_params() -> RasterizationParams:
"""
Construct the RasterizationParams namedtuple
from the static configuration file
:return: the rasterization parameters
"""
if cfg is None:
load_cfg()
# get rasterization section
rasterization_dict = cfg[compute_dsm_tag][... | 9adea0ffd838cbf3425cad5a0ab30bfe92829bc7 | 8,156 |
def rain_attenuation_probability(lat, lon, el, hs=None, Ls=None, P0=None):
"""
The following procedure computes the probability of non-zero rain
attenuation on a given slant path Pr(Ar > 0).
Parameters
----------
lat : number, sequence, or numpy.ndarray
Latitudes of the receiver points... | 728879dc2b51de813f8e1c83a99a8117883c423f | 8,157 |
import itertools
def largets_prime_factor(num):
"""
Returns the largest prime factor of num.
"""
prime_factors = []
for n in itertools.count(2):
if n > num:
break
if num%n == 0:
prime_factors.append(n)
while (num%n == 0):
num = num/n
return max(prime_factors) | 12100b6cdc2e0553295c1803e699544aa930bbfb | 8,159 |
def compute_eigenvectors(exx, exy, eyy):
"""
exx, eyy can be 1d arrays or 2D arrays
:param exx: strain component, float or 1d array
:param exy: strain component, float or 1d array
:param eyy: strain component, float or 1d array
:rtype: list
"""
e1, e2 = np.zeros(np.shape(exx)), np.zeros... | 524fe0cabeda91ca3086c3e46e88f19a919ff489 | 8,161 |
def name_looks_valid(name: str) -> bool:
"""
Guesses if a name field is valid. Valid is defined as being at least two words, each beginning with a capital
letter and ending with a lowercase letter.
:param name: the name to check
:return: whether this name is considered valid
"""
existing_pa... | 3f980ac4db9623c599733794253e6563abe698cb | 8,162 |
import tqdm
from pathlib import Path
def convert_polygons_to_lines(src_polygons, dst_lines, crs=None, add_allone_col=False):
"""Convert polygons to lines.
Arguments:
src_polygons {path to geopandas-readable file} -- Filename of the the polygon vector dataset to be
converted to lines.
... | 7340eccc3b02f70d38967f3c325c968bcec67f26 | 8,163 |
def format_decimal(amount):
""" jinja2 filter function for decimal number treatment """
amt_whole = int(amount)
amt_whole_len = len(str(amt_whole))
if amount < 1:
amt_str = '{:0.15f}'.format(amount).rstrip("0").rstrip(".")
elif amt_whole_len < 4:
amt_str = '{:0.3f}'.format(amount).r... | 55ee4b6134abd409ade396233fa07061d0a30764 | 8,164 |
def remove_special_char(df, col):
"""Removes special characters such as % and $ from numeric variables and converts them into float"""
df[col] = df[col].replace(regex = True, to_replace = r'[^0-9.\-]', value=r'')
df[col] = df[col].astype("float")
return df[col] | c6c4c86eb480d2f045e40b3eb831d0b8d5381d33 | 8,165 |
def getNonlinearInfo(numHiddenLayers, numBinary, unaryPerBinary):
"""
Generates a 2D list to be used as a nonlinearInfo argument in building an
EQL/EQL-div model
# Arguments
numHiddenLayers: integer, number of hidden layers (i.e. layers
including nonlinear keras layer components)
... | e62f8d016501ad48aeae09ebd8e61b659618e0b0 | 8,166 |
import types
def construct_magmad_gateway_payload(gateway_id: str,
hardware_id: str) -> types.Gateway:
"""
Returns a default development magmad gateway entity given a desired gateway
ID and a hardware ID pulled from the hardware secrets.
Args:
gateway_id: ... | 87826b72fd2f33a4a862ffbacbbce14f206dc086 | 8,167 |
def script_rename_number(config):
""" The scripting version of `rename_number`. This function
applies the rename to the entire directory. It also adds the
tags to the header file of each fits.
Parameters
----------
config : ConfigObj
The configuration object that is to be used for... | bd0c14cbec43644ed5b6e7b9e23e1c1f71f51984 | 8,169 |
def jasper10x4(**kwargs):
"""
Jasper 10x4 model from 'Jasper: An End-to-End Convolutional Neural Acoustic Model,'
https://arxiv.org/abs/1904.03288.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.chain... | 4b8e210a619a28ca0d28ee6ba85fd7a7acf15335 | 8,170 |
def swap(lst, idx1, idx2):
"""
>>> swap([0, 1, 2], 0, 1)
[1, 0, 2]
>>> swap([0, 1, 2], 0, 0)
[0, 1, 2]
"""
# print("Swapping [{}, {}] from {}".format(idx1, idx2, lst))
lst[idx1], lst[idx2] = lst[idx2], lst[idx1]
# print("resulting to {}".format(lst))
return lst | 81dee804db05eedaa1a9b5611e836a4c1da89b4b | 8,171 |
def substring_index(column, delim=' ', cnt=1):
"""
Returns the substring from string ``column`` before ``cnt`` occurrences of the delimiter ``delim``.
If ``cnt`` is positive, everything the left of the final delimiter (counting from left) is
returned. If ``cnt`` is negative, every to the right of the fi... | b17fe73e19ece0d9e2511f8b45c43accb65f4138 | 8,172 |
def askPrize(mon: int) -> str:
"""
Args :
n:欲查詢的期別
Returns:
查詢結果字串
"""
(date, data) = initData(mon)
date = f"{date}月\n"
ssp_prize = f"特別獎:{data[0]}\n"
sp_prize = f"特獎:{data[1]}\n"
first_prize = f"頭獎:{data[2]}、{data[3]}、{data[4]}\n"
six_prize = f"六獎:{data[2][5:]}、{... | 1fcd388a38823a53719e8b50b02d2758b8ebe6dc | 8,173 |
import pickle
import tokenize
def get_letters_df(letters_dict_pickle):
"""Get the letters Pandas Dataframe
Parameters
----------
letters_dict_pickle: string
Path to the dict with the letters text
Returns
-------
Pandas DataFrame
Pandas DataFrame with a columns with the to... | f6c40627ae917d51ce30cd572bb02c378ca7f7e2 | 8,174 |
def lorenzmod1(XYZ, t, a=0.1, b=4, dz=14, d=0.08):
"""
The Lorenz Mod 1 Attractor.
x0 = (0,1,0)
"""
x, y, z = XYZ
x_dt = -a * x + y**2 - z**2 + a * dz
y_dt = x * (y - b * z) + d
z_dt = -z + x * (b * y + z)
return x_dt, y_dt, z_dt | 17dbd87b25968ca0e24b6e6fc602007932983f54 | 8,175 |
def binomial_p(x, n, p0, reps=10**5, alternative='greater', keep_dist=False, seed=None):
"""
Parameters
----------
sample : array-like
list of elements consisting of x in {0, 1} where 0 represents a failure and
1 represents a seccuess
p0 : int
hypothesized number of successes in... | 486257dfc1c517313556d08c8e2ad4ed3e85980d | 8,176 |
def is_guild_owner() -> commands.check:
"""
Returns True under the following conditions:
- **ctx.author** is the owner of the guild where this command was called from
"""
def predicate(ctx):
if ctx.guild is None:
raise commands.NoPrivateMessage('This command can only be used... | 3f3c9a5d5990794bced7b021c646041e514e72ed | 8,177 |
def round_grade(grade: int) -> int:
"""
Round the grade according to policy.
Parameters
----------
grade: int
Raw grade.
Returns
-------
rounded_grade: int
Rounded grade.
"""
if grade < 38:
rounded_grade = grade
else:
closest_multiple_5 = (gr... | 8f1be9575d98b4ed24ff1e5904a5345d7ebc3e48 | 8,178 |
def patch_indecies(i_max: int, j_max: int, ps: int, pstr: int):
"""
Given the sizes i_max and j_max of an image, it extracts the top-left corner pixel
location of all the patches of size (ps,ps) and distant "pstr"
pixels away from each other. If pstr < ps, the patches are overlapping.
Input:
... | 6b760311513b3ded56f85690bab6622c999cc40d | 8,179 |
def model_fn():
"""
Defines a convolutional neural network for steering prediction.
"""
model = Sequential()
# Input layer and normalization
model.add(InputLayer(input_shape=(20, 80, 1)))
model.add(Lambda(lambda x: (x / 255.0) - 0.5))
# Convolutional layer 1
model.add(Conv2D(filter... | 42b85775635ee71ac6ed76f64170776eb36b5953 | 8,180 |
def authenticate(request):
"""Return the user model instance associated with the given request
If no user is retrieved, return an instance of `AnonymousUser`
"""
token, _ = get_token_from_request(request)
jwt_info = {
'token': token,
'case': TokenCase.OK,
'payload': None,
... | 15d2d4343673cd30f2b201b834bd26889813d4ab | 8,181 |
def _urpc_test_func_2(buf):
"""!
@brief u-RPC variable length data test function.
@param buf A byte string buffer
@return The same byte string repeated three times
"""
return buf*3 | f13f7dcf45eaa0706b69eb09c63d29ba2bbd3d60 | 8,182 |
from datetime import datetime
def main():
"""
Use Netmiko to connect to each of the devices. Execute
'show version' on each device. Record the amount of time required to do this
"""
start_time = datetime.now()
for device in devices:
print()
print('#' * 40)
output = show... | 9182a63ea3e6a98d995c4ae00126175164cd6dfc | 8,183 |
def versionString(version):
"""Create version string."""
ver = [str(v) for v in version]
numbers, rest = ver[:2 if ver[2] == '0' else 3], ver[3:]
return '.'.join(numbers) + '-'.join(rest) | 2feec3f8ac5a1f2b848d0805dfa0c3ff53a44ead | 8,186 |
import warnings
import builtins
def any(iterable, pred):
"""Returns True if ANY element in the given iterable is True for the
given pred function"""
warnings.warn(
"pipe.any is deprecated, use the builtin any(...) instead.",
DeprecationWarning,
stacklevel=4,
)
return builti... | 32f48ab7a6be329b8758ba3dbbe6721923890e11 | 8,187 |
def build_prev_df_n(
dispositions) -> pd.DataFrame:
"""Build admissions dataframe from Parameters."""
days = np.array(range(0, n_days))
data_dict = dict(
zip(
["day", "hosp", "icu", "vent"],
[days] + [disposition for disposition in dispositions],
)
)
proj... | e17ca1ab78e16aeaeac0afa5a1a9fa193cb9777f | 8,189 |
import html
def main() -> VDOMNode:
"""Main entry point."""
vdom = html("<{Heading} />")
return vdom | c29d55ec4d469373e5504cc089e8370d0573a719 | 8,190 |
def GT(x=None, y=None):
"""
Compares two values and returns:
true when the first value is greater than the second value.
false when the first value is less than or equivalent to the second value.
See https://docs.mongodb.com/manual/reference/operator/aggregation/gt/
for more details
... | 62a4321d5d36306b9cc5b910e7eac0eec4d914f3 | 8,191 |
def pymongo_formatter(credentials):
"""Returns a DSN for a pymongo-MongoDB connection.
Note that the username and password will still be needed separately in the constructor.
Args:
credentials (dict):
The credentials dictionary from the relationships.
Returns:
(string) A f... | 69216575258f297c368ec3015c1c14569bb82cd2 | 8,192 |
def sigma_disp_over_vcirc(gal, R=None):
"""The velocity dispersion over circular velocity computed at R=x*Rs [km/s]. Isotropic NFW is assumed.
:param R: radius [kpc]
:param gal: galaxy object
"""
# get Rs
(rho, rs, c) = reconstruct_density_DM(gal, DM_profile='NFW')
# make array of r, pre... | f05bb1f1a7ca2e0899ab67bb1c2a355236e3e810 | 8,193 |
def filters(param: str, default_value: str, base_key: str, key_manager: KeyManager) -> list:
"""Filter combo box selector for parameter"""
update_type = '|filters|'
row = combo_row(param, default_value, base_key, key_manager, update_type)
return row | 6645d369116d10cc4392810c9228f0e72fc21fd5 | 8,194 |
def get_scanner(fs_id):
""" get scanner 3T or 1.5T"""
sc = fs_id.split("_")[2]
if sc in ("15T", "1.5T", "15t", "1.5t"):
scanner = "15T"
elif sc in ("3T", "3t"):
scanner = "3T"
else:
print("scanner for subject " + fs_id + " cannot be identified as either 1.5T or 3T...")
... | f905bd16f3103b0c6c02193d30fb945646afb54c | 8,195 |
def _find_query_rank(similarities, library_keys, query_keys):
"""tf.py_func wrapper around _find_query_rank_helper.
Args:
similarities: [batch_size, num_library_elements] float Tensor. These are not
assumed to be sorted in any way.
library_keys: [num_library_elements] string Tensor, where each column... | f3b002b77c77845681b35c3d6f629f6290324a47 | 8,196 |
def random_adjust_brightness(image, max_delta=0.2, seed=None):
"""Randomly adjusts brightness. """
delta = tf.random_uniform([], -max_delta, max_delta, seed=seed)
image = tf.image.adjust_brightness(image / 255, delta) * 255
image = tf.clip_by_value(image, clip_value_min=0.0, clip_value_max=255.0)
re... | 9d371ebb268708b983a523ce71a64103d3e46717 | 8,197 |
import re
def get_assign_ops_and_restore_dict(filename, restore_all=False):
"""Helper function to read variable checkpoints from filename.
Iterates through all vars in restore_all=False else all trainable vars. It
attempts to match variables by name and variable shape. Returns a possibly
empty list of assign_... | d93583c914bbe066b6a62d1f2041ab60cd511ab6 | 8,198 |
def log_creations(model, **extra_kwargs_for_emit):
"""
Sets up signal handlers so that whenever an instance of `model` is created, an Entry will be emitted.
Any further keyword arguments will be passed to the constructor of Entry as-is. As a special case,
if you specify the sentinel value `INSTANCE` as... | 4eee202ccb335c658c1f6bf15b02f00955eb3da7 | 8,199 |
def notebook(request, id=0):
"""
:param request:
:param id:
:return:
"""
get_notebook = JupyterNotebooks.objects.get(id=id)
return render(request, "customdashboard/notebook.html",
{'get_notebook': get_notebook}) | 3d1e3880182f6c8d507391fc66a9c0b41f18e3bc | 8,200 |
def encrypt_decrypt(data_string, password, mode='encrypt'):
"""Encrypts OR Decrypts data_string w.r.t password based on mode specified
Parameters:
data_string: Text that needs to be encoded. passed in string format
password: a string to encrypt data before encoding into an image.
mo... | c0ecdf2009fe1b40cb9ed86e12904e241eb5ea86 | 8,201 |
def compute_alphabet(sequences):
"""
Returns the alphabet used in a set of sequences.
"""
alphabet = set()
for s in sequences:
alphabet = alphabet.union(set(s))
return alphabet | cf8f7dc1e31a28fe0910d806d18189aae7d7a85b | 8,202 |
def Diff(a, b):
"""Returns the number of different elements between 2 interables.
Args:
a(iterable): first iterable.
b(iterable): second iterable.
Returns:
int: the number of different elements.
"""
return sum(map(lambda x, y: bool(x-y), a, b)) | 0885bd224f956f138e80a4b681ebc581c733cc51 | 8,204 |
def load_description(model):
"""Load description of the <model>."""
desc = get_available_pkgyaml(model)
entry = read_mlhubyaml(desc)
return entry | 2a97ee446d0693af704c6b0ebd14376d3e6dea37 | 8,205 |
import math
def generate_star(rect: RectType, line_count: int = 20) -> vp.LineCollection:
"""Generate a set of line from a random point."""
orig_x = np.random.uniform(rect[0], rect[0] + rect[2])
orig_y = np.random.uniform(rect[1], rect[1] + rect[3])
r = math.hypot(rect[2], rect[3])
angles = np.li... | a430b486af8606d949a057b4578fdddd9968386b | 8,206 |
def failure(request):
"""Display failure message"""
return HttpResponse(f"Failure! {request.session['failure message'] if request.session['failure message'] is not None else ''}") | c9eee874106fce87d6816e3216e3a86d6eef5fab | 8,207 |
import torch
def visualize_image(cam, rgb_img, target_category):
"""
Visualize output for given image
"""
input_tensor = preprocess_image(rgb_img)
grayscale_cam = cam(input_tensor=input_tensor, target_category=target_category)
grayscale_cam = grayscale_cam[0, :]
output = cam.activations... | 2644eca6cd50078a167b7d791a625ecb13fef17d | 8,208 |
import random
def _get_random_hangul(count=(0xd7a4 - 0xac00)):
"""Generate a sequence of random, unique, valid Hangul characters.
Returns all possible modern Hangul characters by default.
"""
valid_hangul = [chr(_) for _ in range(0xac00, 0xd7a4)]
return random.sample(valid_hangul, count) | 3a41edd36cd2aac05e51a121743bcfb61455bd9b | 8,210 |
def build(dir, **kwargs):
"""run cmake to generate a project buildsystem
Parameters:
----------
dir str: Location of the CMake build directory
Keyword Args:
----------
parallel int: The maximum number of concurrent processes to use when building. Default: 1 less than
... | 2f21fc901d7c95d3b1a2b37d6ba3584d6cb96efb | 8,211 |
def is_builtin_model(target: type) -> bool:
"""returns ``True`` if the given type is a model subclass"""
return is_builtin_class_except(target, ["MetaModel", "Model", "DataBag"]) | 6b1cf3b0fdd0db50c0dde6a2ca3f3bcb8e8328cf | 8,212 |
def runQ(qparsed, params=dict(), nbcircuits=1, nbqubits = None):
"""
qparsed: qlang circuit (already parsed)
params:{x:np.array, t:np.array}
"""
#*** verify if parameters are ok for qparsed circuit ****
_ , vector_parameters = parseqlang.parameters_from_gates(qparsed)
for pname, dimension i... | d6ca4afd14e56961920033e9e7ab40f4fc4a9ae6 | 8,213 |
def simulation_wells(self):
"""Get a list of all simulation wells for a case
Returns:
:class:`rips.generated.generated_classes.SimulationWell`
"""
wells = self.descendants(SimulationWell)
return wells | ecf13fc524f12be21593c49d8d22c365564716e9 | 8,215 |
from typing import Optional
def getSmartMeter() -> Optional[str]:
"""Return smartmeter name used in recording."""
mapping = getDeviceMapping()
# Identifier for smartmeter is meter with phase 0
try: return next(key for key in mapping if mapping[key]["phase"] == 0)
except StopIteration: return None | 8e947d5d9078886f9bc2b662162304eb2fb6474b | 8,216 |
import http
from typing import Optional
def view_index(
request: http.HttpRequest,
workflow: Optional[models.Workflow] = None,
) -> http.HttpResponse:
"""Render the list of views attached to a workflow.
:param request: Http request received.
:param workflow: Workflow being processed
:return: ... | 2dca3e42a3d2b855d795fc0c61b41c2a2f449724 | 8,218 |
def inverseLPSB(data, mu, g):
"""Compute regularized L-PSB step."""
mUpd = data.mUpd
gamma = data.gamma
gammah = data.gamma + mu
Q22 = np.tril(data.STY[:mUpd, :mUpd], -1) + np.tril(data.STY[:mUpd, :mUpd], -1).T + \
np.diag(np.diag(data.STY[:mUpd, :mUpd])) + \
gamma * np.diag(np.diag... | 500705d0fd5cb5ccae7fa8dfeaa1548a65fa2203 | 8,219 |
import json
def canPlay(request):
"""
Endpoint qui retourne la liste des cartes qui peuvent être jouées ( pour le Player )
rq : {
"cards_played" : [
{
"card_name": "As",
"value_non_atout": 0,
"value_atout": 0,
... | b579e0e99eebed68fa55f8eeb287cb2cdf283de6 | 8,220 |
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Genie Aladdin component."""
return True | 22f6c6126d8d7b3ce7df124b144b9ccfb4fc30c2 | 8,221 |
import importlib
def _module_available(module_path: str) -> bool:
"""Testing if given module is avalaible in your env
>>> _module_available('os')
True
>>> _module_available('bla.bla')
False
"""
mods = module_path.split('.')
assert mods, 'nothing given to test'
# it has to be teste... | 6673bf25845af6c12494ffbec0dc8bb8ab950ff2 | 8,222 |
def _GetPathBeforeFinalDir(uri):
"""
Returns the part of the path before the final directory component for the
given URI, handling cases for file system directories, bucket, and bucket
subdirectories. Example: for gs://bucket/dir/ we'll return 'gs://bucket',
and for file://dir we'll return file://
Args:
... | 20cad56a858e8feccfd7154ecff33d9508a7ec80 | 8,223 |
import toml
def load_page_details(data, filename=None):
"""
# Raises
ValueError of (filename, error)
"""
try:
options = toml.loads(data)
except toml.TomlDecodeError as exc:
raise ValueError(filename, exc)
if not isinstance(options, dict):
raise ValueError(filename, 'page details could not b... | 117bb7d84625475745a30522fda7dccf1bc5a487 | 8,224 |
def nested_render(cfg, fully_rendered_cfgs, replacements):
"""
Template render the provided cfg by recurisevly replacing {{var}}'s which values
from the current "namespace".
The nested config is treated like nested namespaces where the inner variables
are only available in current block and further... | 9958e792ef09aa7c88e4c8b7d29a61a8713927a2 | 8,225 |
from operator import sub
import warnings
def element_by_atomic_number(atomic_number):
"""Search for an element by its atomic number
Look up an element from a list of known elements by atomic number.
Return None if no match found.
Parameters
----------
atomic_number : int
Element atom... | 42a23d0bd2ce1391a74ee8b5d5f97aa5fc8b2d3f | 8,226 |
import tqdm
def get_data_from_db(cursor):
"""
Get data from the database given a query-instantiated cursor
:param cursor: query-instantiated database cursor
:return: tuple of labels and training data
"""
training_data, labels = [], []
cols = [desc[0] for desc in cursor.description]
fo... | a3db9af7912fd38e9966f0c95639613cb4dac087 | 8,227 |
def parse(input_str, file_path=True):
"""
Parse a GLM into an omf.feeder tree. This is so we can walk the tree,
change things in bulk, etc.
Input can be a file path or GLM string.
"""
tokens = _tokenize_glm(input_str, file_path)
return _parse_token_list(tokens) | 2e53a6870baae3fa9bfb511b28baf73e697b44a0 | 8,228 |
def pred(model, x_pred_scaled, scaler_y):
"""
Predict
:param model: model for prediction
:param x_pred_scaled: scaled x values we need to predict for
:param scaler_y: scaler for y values
:return:
"""
MAX_PREDICT_SIZE = 10000
g_mean_full = g_std_full = None
start = 0
while s... | 7a43020a2b4817b3287c849bc0059027346bf5a5 | 8,229 |
def metadataAbstractElementEmptyValuesTest3():
"""
Empty value for unknown attribute.
>>> doctestMetadataAbstractElementFunction(
... testMetadataAbstractElementEmptyValue,
... metadataAbstractElementEmptyValuesTest3(),
... requiredAttributes=["required1"],
... optionalAttri... | 4f9e0d33948a9ac1ab35bc9cf0c5c3274cfc9d41 | 8,230 |
def orthonormal_initializer(input_size, output_size):
"""from https://github.com/patverga/bran/blob/32378da8ac339393d9faa2ff2d50ccb3b379e9a2/src/tf_utils.py#L154"""
I = np.eye(output_size)
lr = .1
eps = .05/(output_size + input_size)
success = False
tries = 0
while not success and tries < 10... | 11cc28d6342ed20699c96051a36199c3b8941381 | 8,231 |
def stick_figure (ax, type, num, start, end, prev_end, scale, linewidth, opts):
""" General function for drawing stick based parts (e.g., ribozyme and protease sites).
"""
# Default options
color = (0,0,0)
start_pad = 2.0
end_pad = 2.0
x_extent = 5.0
y_extent = 10.0
linestyle = '-'
linetype = "";
shapetyp... | 68ae3194ad1dd38e0e18f8da3b0b5f1b0e22071a | 8,232 |
def display_datetime(datetime_str, time_zone=None, verbose=True):
"""Returns a formatted datetime with TZ (if provided) or 'Error (Missing)"""
"""
>>> print(datetime.datetime.utcnow().strftime("%Y/%m/%d %a %I:%M %p"))
2019/05/19 Sun 01:10 AM
"""
if datetime_str: # and type(datetime_str) =... | 45caa488688e790ae19f8f3f2cda2cb0f250b1fd | 8,233 |
import torch
def mask_channels(mask_type, in_channels, out_channels, data_channels=3):
"""
Creates an autoregressive channel mask.
Input:
mask_type: str
Either 'A' or 'B'. 'A' for first layer of network, 'B' for all others.
in_channels: int
Number of input channels... | 772fa71f63d2f31c80966db0b0eb43a70ac5e9a9 | 8,234 |
import textwrap
def dedent(text):
"""
Remove all common indentation from every line but the 0th.
This will avoid getting <code> blocks when rendering text via markdown.
Ignoring the 0th line will also allow the 0th line not to be aligned.
Args:
text: A string of text to dedent.
Returns:
String d... | b450a873c4c2b667d10c66985d19f8057aa205f9 | 8,235 |
def dpsplit(n,k, sig):
""" Perform the dynamic programming optimal segmentation, using the sig function
to determine the cost of a segment sig(i,j) is the cost of the i,j segment. These
are then added together
"""
# Set up the tracking tables
K = k + 1
N = n
segtable = np.zeros((n,K)) ... | db1513ae0a4725b63e62b102dc2c5fdd77fd4ceb | 8,237 |
from typing import List
def get_wind_tiles() -> List[Tile]:
"""return a list of four wind tiles
"""
return [Tile(Suit.JIHAI.value, Jihai.TON.value),
Tile(Suit.JIHAI.value, Jihai.NAN.value),
Tile(Suit.JIHAI.value, Jihai.SHAA.value),
Tile(Suit.JIHAI.value, Jihai.PEI.value... | 469ec29795291bb8345fa3beccbbf2c6d4bb3101 | 8,238 |
from datetime import datetime
def datetime_now_filename_string():
"""create a string representation for now() for use as part of the MHL filename"""
return datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d_%H%M%S") | 37a733ddd93ca1bc4eed82e920222c644c494fcd | 8,240 |
from pathlib import Path
import inspect
import tqdm
def generate_simulation_dataset(path, runs, **kawrgs):
"""Generate and save a simulation dataset.
Parameters
----------
path : str
Root path where simulation data will be stored.
runs : int, array
If int then number of runs to us... | 8383f42cfe2604e5f82761bb351b6cf4f16f33aa | 8,241 |
def num_sites(sequence, rule, **kwargs):
"""Count the number of sites where `sequence` can be cleaved using
the given `rule` (e.g. number of miscleavages for a peptide).
Parameters
----------
sequence : str
The sequence of a polypeptide.
rule : str or compiled regex
A regular ex... | dc0840e33206c9db7058a7257a60c59bee0403f8 | 8,242 |
def get_packages(code: str) -> defaultdict:
"""Extracts the packages that were included in the file being inspected.
Source for this code: https://stackoverflow.com/questions/2572582/
Example:
input:
'from collections import Counter\n
import kivy\n
from stats import median as stats_median... | 977f20e2d3c12993ef26ff8b199f943fb153c79b | 8,243 |
def beam_name():
"""Session level fixture for beam path."""
return str(beam_path) | a702d91c62024685d14125123ead41a2a4e38942 | 8,244 |
import itertools
def get_mv_sandwich(a_blade_indices, b_blade_indices, signature, prod="gp"):
"""a b ~a"""
out_indices = []
out_blade_indices = []
out_signs = []
out_indices = []
indices_a = []
indices_b = []
indices_a_r = []
blade_to_index = {}
for (i_a, index_a), (i_b, inde... | 8e30f31de944bd6aa19e60fe7a93aceb8ccb73ef | 8,245 |
def ldns_dnssec_create_nsec3(*args):
"""LDNS buffer."""
return _ldns.ldns_dnssec_create_nsec3(*args) | 653d899f7d30e1e272c0a7026e4383e191b3e78f | 8,246 |
def S_difference_values(_data_lista, _data_listb):
"""
Returns new data samples where values are transformed by transformer values.
"""
d_data = []
dsa = len(_data_lista)
dsb = len(_data_listb)
if dsa != dsb:
return []
for i in range(dsa):
d_data.append(_data_lista[i] ... | 40ec82cb7ef53d5e227b3287a9c1d08e78112e09 | 8,247 |
def parseFixedZone(s):
"""Convert a +hhmm or -hhmm zone suffix.
[ s is a string ->
if s is a time zone suffix of the form "+hhmm" or "-hhmm" ->
return that zone information as an instance of a class
that inherits from datetime.tzinfo
else -> raise SyntaxError ]
... | 681b5ad02f228ee40b099a461131de42309e58f0 | 8,248 |
def tica_eigenvalues_plot(tica, num=12, plot_file=None):
"""
Plots the highest eigenvalues over the number of the time-lagged independent components.
Parameters
----------
tica : TICA obj
Time-lagged independent components information.
num : int, default = 12
... | 707ebbacf0dc90e96760ae26d316da4c27bdd997 | 8,249 |
def _split_train_test(features, labels, train_set, random_seed):
"""Split the dataset into training and test sets.
Parameters
----------
features : pandas.DataFrame
Features of the dataset events.
labels : pandas.DataFrame
Labels of the dataset events.
train_set : {float, list-l... | 67210e0462cdd4be58f5446b6220f921aa8c4ea0 | 8,251 |
def generate_enc_keypair():
"""
Generate Curve25519 keypair
:returns tuple: A byte pair containing the encryption key and decryption
key.
"""
private_key = PrivateKey.generate()
return private_key.public_key.encode(), private_key.encode() | c2ba00b6463d7ab1708dcc43d9cafba2d11af0c6 | 8,253 |
from typing import List
from typing import Tuple
def filter_molecular_components(
components: List[Component],
) -> Tuple[List[Component], List[Component]]:
"""Separate list of components into molecular and non-molecular components.
Args:
components: A list of structure components, generated usin... | 72a43a5195ef3d35ca8216225dcae7f699c7bbd5 | 8,254 |
import types
def argument(name, type):
"""
Set the type of a command argument at runtime. This is useful for more
specific types such as mitmproxy.types.Choice, which we cannot annotate
directly as mypy does not like that.
"""
def decorator(f: types.FunctionType) -> types.Function... | 8f93c8e8cd4289d2b4747feb93ecfe3df74350f7 | 8,255 |
async def async_google_actions_request_sync(cloud):
"""Request a Google Actions sync request."""
return await cloud.websession.post(
f"{cloud.google_actions_report_state_url}/request_sync",
headers={AUTHORIZATION: f"Bearer {cloud.id_token}"},
) | 5d75e4b67bc04878108066660b0f43939a1eab4e | 8,256 |
def convert_time_string_to_secs(string: str) -> int:
"""
Takes a string in the format '1h30m25s' and converts it to an integer
in seconds. This functions uses the regular expression RE_CONVERT_TIME
above for matching the string.
"""
match = regexp_time.match(string)
if not match:
rai... | b520fde06640cd3d22a6c619031633bf21383687 | 8,257 |
def polar_cube(c, index, n=512, interp='cubic'):
"""VIMS cube polar projected.
Parameters
----------
c: pyvims.VIMS
Cube to interpolate.
index: int, float, str, list, tuple
VIMS band or wavelength to plot.
n: int, optional
Number of pixel for the grid interpolation.
... | 6a02932e8685a1cdd43e6831b2a3544bd903a40b | 8,258 |
from nibabel.gifti.parse_gifti_fast import ParserCreate, Outputter
import gzip
def _load_surf_files_gifti_gzip(surf_file):
"""Load surface data Gifti files which are gzipped. This
function is used by load_surf_mesh and load_surf_data for
extracting gzipped files.
Part of the code can be removed while... | 2fdc083a208f1a288b7d99bd3863bff22d36bf50 | 8,259 |
import platform
def get_platform_system():
"""return platform.system
platform module has many regexp, so importing it is slow...
import only if required
"""
return platform.system() | 2531f1883d5acd0c192c0061d7cbf29637197706 | 8,260 |
import sympy
def factorial(n):
"""Stop sympy blindly calculating factorials no matter how large.
If 'n' is a number of some description, ensure that it is smaller than
a cutoff, otherwise sympy will simply evaluate it, no matter how long that
may take to complete!
- 'n' should be a sy... | 73dc223df2b23a93aafb0ec2b897f1668869e07a | 8,262 |
import re
def getSupplier(num):
"""" get the supplier for a card number
Attributes:
@num: card number
"""
supplier = str()
for key, value in suppliers.items():
if bool(re.match(value, num)):
supplier = key
break
if supplier == "":
suppl... | 2572a0595d03cc3056b1155f8a3f0b007ec65b9e | 8,263 |
from typing import Optional
import torch
def load_torch_hub_model(repo: str, model: str, *args, **kwargs):
"""Tries to load a torch hub model and handles different exceptions that could be raised.
Args:
repo: The GitHub repository containing the models.
model: The model name to download.
... | 3cc928f1026d276290ed97360a0cfebbcde82bb8 | 8,264 |
def compute_medoid(data):
"""
Get medoid of data
Parameters
----------
data: ndarray
Data points
Returns
------
medoid: ndarray
Medoid
"""
dist_mat = pairwise_distances(data)
return data[np.argmin(dist_mat.sum(axis=0))] | 3fd071cd6c48566caa3a52ead26f06621682703d | 8,265 |
def int_sphere(fx, xgrid):
"""
Computes integrals over the sphere defined by the logarithmic
grid provided as input
Parameters
----------
fx : array_like
The function (array) to be integrated
xgrid : ndarray
The logarithmic radial grid
Returns
-------
I_sph : fl... | d92962cde5200f0c25d8bd0e1011c969e2287125 | 8,266 |
def run_webserver(destination_root_dir):
""" Run a local """
destination_root_dir = destination_root_dir
if destination_root_dir.startswith('/'):
destination_root_dir = destination_root_dir[1:]
if destination_root_dir.endswith('/'):
destination_root_dir = destination_root_dir[:-1]
... | df5d26ae754009135061abb4a1a2d1cad0937e97 | 8,268 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.