content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
import logging
import json
def export_ovdm_config(gearman_worker, ovdm_config_file_path, finalize=False):
"""
Export the current OpenVDM configuration to the specified filepath
"""
ovdm_config = gearman_worker.ovdm.get_ovdm_config()
if finalize:
ovdm_config['cruiseFinalizedOn']... | 455d7bc01d87e68b2bd5b8685399a6b7ad6577a7 | 57,100 |
from pydantic import BaseModel # noqa: E0611
def get_model(Q_c: float, Q_lin: float, omega_0: float,
model_parameters=None) -> BaseModel:
"""
Generate a model based on the input parameters injected in the method.
At least a coupling quality factor, Q_c, a linear quality factor for the
c... | a3cecdfc3cde8e605616501c4240f647eb3e672a | 57,101 |
import numpy
def calculate_rkls(
ls_factor_uri, erosivity_uri, erodibility_uri, stream_uri,
rkls_uri):
"""Calculates per-pixel potential soil loss using the RKLS (revised
universial soil loss equation with no C or P).
ls_factor_uri - GDAL uri with the LS factor pre-calculated
ero... | eb839559953f982e18501ee8bd70ab7555ca1e22 | 57,102 |
import os
def ReadCsv(source):
"""Reads a csv from source and returns as a python object."""
original_directory = os.getcwd()
source = os.path.abspath(source)
os.chdir(os.path.dirname(source))
# Try dict first, because dict is a subset of list of dict.
try:
if IsCsvADictHeader(source):
ret = Rea... | 4311e1d2387de071021354319663b33e2088047b | 57,103 |
def bbox_iou_np_expand(box1, box2, x1y1x2y2=True, eps=1e-16):
"""
Calculate the iou of box1 and box2 with numpy.
Args:
box1 (ndarray): [N, 4]
box2 (ndarray): [M, 4], usually N != M
x1y1x2y2 (bool): whether in x1y1x2y2 stype, default True
eps (float): epsilon to avoid divide ... | aa195efdd6766574d7b5213f01af6a0b4804382f | 57,104 |
def get_temp_irradiance_for_voc_percentile(df, percentile=99.5, cushion=0.0025):
"""
Find the lowest temperature and associated irradiance that produces the
percentile value of Voc.
Parameters
----------
df : dataframe
Dataframe containing 'v_oc'
percentile
cushion : numeric
... | a0d36cf74257d8262a67bee9328a33ead161ac58 | 57,105 |
import functools
from typing import Callable
def with_argument_list(func: Callable) -> Callable:
"""A decorator to alter the arguments passed to a do_* cmd2
method. Default passes a string of whatever the user typed.
With this decorator, the decorated method will receive a list
of arguments parsed fro... | be76a4ad67b64396c7b8bb3ecc200256d6ccc8eb | 57,106 |
def featureScale(x, xRef=None):
"""Helper function to perform feature scaling.
INPUTS:
x: pandas DataFrame or Series.
xRef: reference pandas DataFrame.
If only x is provided, x will be normalized against itself.
If xRef is additionally supplied, x will be normalized against xRef
... | bffa3403e8083efaa8deb24e03b48d0210d39652 | 57,107 |
from typing import Optional
def keydoor(shape: Shape, *, rng: Optional[rnd.Generator] = None) -> State:
"""An environment with a key and a door
Creates a height x width (including outer walls) grid with a random column
of walls. The agent and a yellow key are randomly dropped left of the
column, whil... | a36e9936b414440320a4f702a50b173ffda1526d | 57,108 |
def match_cluster_constraints(app, cluster):
"""Evaluate if all application cluster constraints match cluster.
Args:
app (krake.data.kubernetes.Application): Application that should be
bound.
cluster (krake.data.kubernetes.Cluster): Cluster to which the
application shoul... | 8d0fa52598eb88c3bbd96edc06a0eaf810c23536 | 57,109 |
from datetime import datetime
def from_u_and_v_winds(lats, lons, ubar, vbar, uprime=None, vprime=None, interp=True,
linearized=False, ntrunc=None, idate=None):
"""
Creates ICs from numpy arrays describing the intial wind field.
Args
----
lats : numpy array
1D array ... | 822372aa1fa7b5efeb4cf30d2374fcc2a51c8a10 | 57,110 |
def gen_std_mat_id(elements, mat_id=0):
"""
Generate the standard material ids from given elements.
Parameters
----------
elements : dict of ndarrays
Contains array of nodes for elements sorted by element types.
mat_id : integer, optional
Define the standard material ID. Default... | f851056b2b04b5b25546a3ad9b5127441f4d496c | 57,111 |
import torch
def scan_discounted_sum(sequence, decay, initial_value, reverse=False,
sequence_lengths=None, back_prop=True,
name="scan_discounted_sum"):
"""Evaluates a cumulative discounted sum along dimension 0.
```python
if reverse = False:
resu... | 48ad4464f3f74e5e53a1b862fdee4c7bbb68babc | 57,112 |
def coherence_weighting(disp_arr: np.ndarray = None, reli_arr: np.ndarray = None) -> [np.ndarray, np.ndarray]:
"""
Merge disparity maps using weights from the coherence as a reliability measure.
:param disp_arr: stacked array of disparity maps
:param reli_arr: stacked array of coherence maps
:retur... | c1b14feb65e526fb0b5de617dcd5c8593a4d5fa7 | 57,113 |
import importlib
import sys
def import_object(module_and_object):
"""
Import a specific object from a specific module by name, such as "extras.plugins.utils.import_object".
Returns the imported object, or None if it doesn't exist.
"""
target_module_name, object_name = module_and_object.rsplit('.'... | 23021381681aa51e266bcbf26ab60dcd984542ea | 57,114 |
import requests
def get_ts_declaration():
"""Gets the existing f5-telemetry-streaming declaration"""
return requests.get(
'http://localhost:8100/mgmt/shared/telemetry/declare',
auth=('admin', '')
) | bf374ba399664b9a147d43a1957023a818da0eab | 57,115 |
def scheme_eval(expr, env, _=None): # Optional third argument is ignored
"""Evaluate Scheme expression EXPR in environment ENV.
>>> expr = read_line('(+ 2 2)')
>>> expr
Pair('+', Pair(2, Pair(2, nil)))
>>> scheme_eval(expr, create_global_frame())
4
"""
# Evaluate atoms
if scheme_sym... | 79037095249692ba9c9816e9a38dfb2a924165b1 | 57,116 |
import os
def init_dwi_preproc_wf(scan_groups,
output_prefix,
ignore,
b0_threshold,
motion_corr_to,
b0_to_t1w_transform,
hmc_model,
hmc_transform,
... | 2f0b0798f7644fbecdd9ea1fffe4feacc7ea793d | 57,117 |
import helper_functions
def psql_engine(tunnel=None):
"""
Create a sqlalchmey engine used for creating the database connection.
Args:
tunnel (sshtunnel.SSHTunnelForwarder, optional): Connect using an opened ssh
tunnel if needed. Defaults to None.
Returns:
Engine: The SQLA... | f6e6a058c182541aa0acd710000c4ad8530a22db | 57,118 |
def solve(lines, target="shiny gold"):
"""Solve the problem."""
containers = set()
contained_by, _ = parse_rules(lines)
queue = list(contained_by[target])
while queue:
bag = queue.pop(0)
# print(f"{bag} {containers}")
containers.add(bag)
queue.extend(contained_by[ba... | e9e608211c427d60a5498477e12ed47153cb4ec7 | 57,119 |
def interp(x_values, y_values):
"""linear interpolation for y = a*x + b. returns a,b"""
xbar = x_values.mean()
ybar = y_values.mean()
SSxy = np.dot(x_values,y_values) - x_values.size*xbar*ybar
SSxx = np.dot(x_values,x_values) - x_values.size*xbar**2
a = SSxy/SSxx
b = ybar - a*xbar
return a,b | ddfe34a5fc5836d93d84adeeffaf2b26de5bb231 | 57,120 |
def getFuelLatticeCell(cellNum, surfaceNum, assemblyUniverse, latticeUniverse, comment):
"""Create a hexagonal lattice cell."""
cellCard = "{} 0 -{} u={} fill={} imp:n=1 {}".format(cellNum, surfaceNum, assemblyUniverse, latticeUniverse,
comment)
asser... | 50b68170d7aface170c34fca95b32291f4b55bb4 | 57,121 |
def wasserstein_loss(y_true, y_pred):
"""Calculates the Wasserstein loss for a sample batch.
The Wasserstein loss function is very simple to calculate. In a standard GAN, the discriminator
has a sigmoid output, representing the probability that samples are real or generated. In Wasserstein
GANs, howeve... | 1674954bd76ccc5243c526e5712a24b465a3ec30 | 57,122 |
from typing import Sequence
def scalable(unit_a, unit_b):
"""
Checks whether units are scalable versions of the same SI unit.
Method works on two lists and compares the corresponding units in both
lists.
:param unit_a: List of unit strings.
:param unit_b: List of unit strings.
:returns: ... | f646f34bc496188fd82082ef8908b3b2c2016fdf | 57,123 |
from typing import Tuple
def get_new_blob_move_file_path(blob_container: str, blob_file_path: str, no_retry: bool = False) -> Tuple[str, str]:
""" Get the new blob move container and path depends on current trigger blob path """
retry_times = get_blob_retry_times(blob_file_path)
retry_folder_pattern = 're... | 3613f69da10b90c0f49281fc5aeef8e7d4e3473e | 57,124 |
import os
def path_exists_and_is_directory(path):
"""
Check if a path exists and is a directory
:param path: Path to check
:return: True or False
"""
sanitized_path = sanitize_filename(path, abspath=True)
if os.path.exists(sanitized_path):
if os.path.isdir(path):
ret... | dd035572643a486692c6cf162ae25925c2a41d77 | 57,125 |
def load_bike_data(data_path):
"""
load bike data
"""
rides = pd.read_csv(data_path)
dummy_fields = ['season', 'weathersit', 'mnth', 'hr', 'weekday']
for each in dummy_fields:
dummies = pd.get_dummies(rides[each], prefix=each, drop_first=False)
rides = pd.concat([rides, dumm... | 8dde9038cd844836ca7d6755a7074d876aceb8cd | 57,126 |
def filterParameter(binSize, frequencyBand, filterBand, samplingRate):
"""
Intermediate computation used by the mfcc function.
Compute the filter parameter for the specified frequency and filter bands
"""
filterParameter = 0
boundary = (frequencyBand * samplingRate) / float(binSize) # k * Fs / N... | 0d5f8393d919778e65e2eef814f64b8c15aad229 | 57,127 |
def EncodeRadioRowCol(container, row, col):
"""
:param container:
:param row:
:param col:
"""
RadValue = container * 100000 + row * 1000 + col
return RadValue | 92d9c8842432fded1b1b5e526ad735a9900cc219 | 57,128 |
from sys import path
import sqlite3
import tqdm
def convert_categories_from_sqlite(source_filename: str,
df: 'pd.DataFrame',
categories: list,
db_file: str = "categories.db",
reg... | fc3e66134d33415ae35c2414f8b232017cccbf77 | 57,129 |
import torch
def load_weights(checkpoint_path, model):
"""Loads weights from a checkpoint.
Args:
checkpoint_path (str): path to a .pt or .pth checkpoint
model (torch.nn.Module): <-
Returns:
Model with loaded weights and in train() mode
"""
try:
# catalyst weights... | a415d6cdd6682d257685fa680a5238a3a0c0fe5a | 57,130 |
def softmax_last_hidden(nr_class, *, exclusive_classes=True, **cfg):
"""Select features from the class-vectors from the last hidden state,
mean-pool them, and softmax to produce one vector per document.
The gradients of the class vectors are incremented in the backward pass,
to allow fine-tuning.
""... | 91bd7f7517afb3c04c6436f133b76f1cdb84c63a | 57,131 |
import tqdm
def cyclomatic(graph, radius=5, name="cyclomatic", distance=None, verbose=True):
"""
Calculates cyclomatic complexity for subgraph around each node if radius is set, or for
whole graph, if ``radius=None``.
Subgraph is generated around each node within set radius. If ``distance=None``,
... | e0ae94b2dcee7832f1a80bbbedc7449ea405c050 | 57,132 |
import jsonschema
def read_config_file(url: str) -> dict:
"""Read a solitude configuration from YAML or JSON.
:param url: URL or path of configuration; if `url` ends with '.yaml',
the configuration file is interpreted as YAML, otherwise it is assumed
to be JSON.
:return: configuration dic... | 2e57adc7a82871f458c90cf03d8a643c470a1ab6 | 57,133 |
def get_elevation(bot, guild=None, user_id=None, member=None):
"""Returns the given user's elevation level.
Member is given as a discord.Member or discord.User. If given, will
bypss guild and user_id.
"""
if member:
user_id = member.id
guild = getattr(member, 'guild', None)
is_... | c7aee272e34508ff78887cf679e55a40bc5ee224 | 57,134 |
def get_data_ts_onh_mac(mask_onhrnfl_disc=True, filter_missing_vft=True, fold_seed=4, suffix=''):
"""
Generates the synced onh and macular thicness maps + vft in time series format and splits into three groups
:return:
"""
print("HHYU get_data_ts_onh_mac: fold_seed=", fold_seed)
maps, vd, [dx_in... | ea3270c2844a04f398cac10216e4a1d264104586 | 57,135 |
def metade(preco=0, formatado=False):
"""
Função com o objetivo de calcular a metade do
valor parametrizado.
:param preco: Valor a ser calculado
:param formatado: Valor será apresentado com o formato(R$00,00) ou não?
:return: Valor calculado, formatado ou não.
"""
resposta = preco / 2... | dc7a8e4e38e6c9ed2b8b6bf2a5f971152304ff6f | 57,136 |
import numpy
def chev_points(n:int, lower:float = -1, upper:float = 1):
"""
Generates a set of chebychev points spaced in the range [lower, upper]
:param n: number of points
:param lower: lower limit
:param upper: upper limit
:return: a list of multipressison chebychev points that are in the r... | a0fb62a17421dae2ddccdd8ef885c925fa2e44e5 | 57,137 |
def set_ogr_connection_pg_database(settings):
""" Establishes the db connection. """
db_conn = (
"PG: dbname={dbname_value} user={user_value} "
"host={host_value} password={password_value}".format(
dbname_value=settings.database,
user_value=settings.username,
... | 391216cdf7c2f7878cb9b2420d43657517990fc2 | 57,138 |
def tensor(X, Y, X_treat=None, Y_treat=None, grad_splits=None, **kwargs):
""" Presents a unified api for ct_v_matrix and loo_v_matrix
"""
# PARAMETER QC
try:
X = np.float64(X)
except ValueError:
raise ValueError("X is not coercible to float64")
try:
Y = np.float64(Y)
... | c8c33cc57de09b0219bf0e9313c0e8e9e21b7fd4 | 57,139 |
def correlation2Stocks(stock1,stock2,startDate="",endDate="",movingAvg=5):
"""
stock1/stock2: pd.DataFrame with Date(index), Open/High/Low/Close/Volume(Columns)
startDate: "YYYY-MM-DD"
endDate: "YYYY-MM-DD"
movingAvg: num
"""
if movingAvg>len(stock1)-1:
return "Movin... | e99153ecbbea98f17635250e17b35ad93d572168 | 57,140 |
import getpass
def get_user(prompt=None):
"""
Prompts the user for his login name, defaulting to the USER environment
variable. Returns a string containing the username.
May throw an exception if EOF is given by the user.
:type prompt: str|None
:param prompt: The user prompt or the default o... | fc392cfacc931ee915bb218a80e5db46245f2a1f | 57,141 |
from pygments import highlight
from pygments.lexers import PythonTracebackLexer
from pygments.formatters import HtmlFormatter
import email
def wrap_traceback(traceback):
"""
For internal use only (until further notice)
"""
if email().format == 'html':
try:
with_pygments = True
... | e75fd7f15a2cc153d494f1973c5fe86f01bfca48 | 57,142 |
def img(sourceDir,
destinationDir,
removeStale=True):
"""Process all image files from sourceDir.
This task will look for changes in the source directory, and process/copy
files in the destination directory.
It will handle jpg, png and svg files.
"""
def outputCB(relativePath):
... | 7c3d2b5b8cfa536c7d0edc8f960dc56bf2e0b80c | 57,143 |
def find_cgroup(pid):
""" Returns cgroup_path relative to 'cpu' subsystem based on /proc/{pid}/cgroup
with leading '/'"""
with open(f'/proc/{pid}/cgroup') as f:
for line in f:
_, subsystems, path = line.strip().split(':')
subsystems = subsystems.split(',')
if CGR... | 4ce38fa292d711b315a647c25e3632338d1bd348 | 57,144 |
from collections import OrderedDict
import os
import torch
import copy
def load_checkpoint(cfg, checkpoint_file, model, optimizer=None, active_sampling=False):
"""Loads the checkpoint from the given file."""
assert os.path.exists(checkpoint_file), "Checkpoint '{}' not found".format(
checkpoint_file
... | bc788bbd6f802ac839424d041122a77afff2fb25 | 57,145 |
import json
def load_commands(filename="commands.json"):
""" load all known command """
with open(filename) as file_:
commands = json.load(file_)
return commands | 66d90ecbcc0fcee182c0e7f25b1ff66d26c54145 | 57,146 |
def menu_item_flag(context, flag_type='', flag_iso='', flag_style='', flag_classes='', **kwargs):
"""
Templatetag menu_item_flag
:param context: Getting context
:param flag_type: Default empty, It accepts the string 'square'
:param flag_iso: Default empty, ISO language country code
:param flag_... | 2520a67ea2436743a1b5dec5a7d0321c68f31221 | 57,147 |
def _handle_minutes_prop(values, # type: Sequence[Tuple[int, int, int]]
minutes, # type: Sequence[int]
context # type: _TimeContext
):
# type: (...) -> Sequence[int, int, int]
"""Processes the given minutes."""
freq = context.fr... | a5e20fbccd268bc0a69b285ee8effdc9eb09f046 | 57,148 |
from typing import Union
from typing import Any
import os
import json
def read_json_file(fpath: Union[str, "os.PathLike[str]"]) -> Any:
"""Load dictionary from JSON file.
Args:
fpath: Path to JSON file.
Returns:
Deserialized Python dictionary.
"""
with open(fpath, "rb") as f:
... | 0101577f65a655cb0520f2d98792a058a9a62a0b | 57,149 |
def code_link_nodes(links):
"""Add code to link nodes to each other."""
linkcode = ""
for link in links:
fromnode = link.from_node
fromsock = link.from_socket
tonode = link.to_node
tosock = link.to_socket
if not fromnode: continue
if skip_node(tonode)... | a0a46b4ce3fc39c218b1cbbf9509f7457832d7b9 | 57,150 |
import re
def get_mmss_from_time(text: str) -> (int, int):
"""
Returns the minutes and seconds from `[TIME: MM:SS]`.
:param text: Text in the form `[TIME: MM:SS]`
:return: Minutes and seconds as ints.
"""
matches = [m.span() for m in re.finditer("([0-9]){2}", text)]
if len(matches) != 2:
prin... | a333ad2a4eb44f5ef33a60093f83bf9a4e793555 | 57,151 |
def wh_(w: int, h: int, /) -> Shape2d:
"""Shape from width/height."""
return Shape2d(x=w, y=h) | 116c51f85b6f186aa89aa37cfd44d00566a0be35 | 57,152 |
from typing import Any
def update_user_me(
*,
db: Session = Depends(deps.get_db),
password: str = Body(None),
full_name: str = Body(None),
email: EmailStr = Body(None),
current_user: models.user.User = Depends(deps.get_current_user),
) -> Any:
"""
Update own user.
"""
current_u... | 35af80c03cfeb639eb2fd7818d0b2e9ec60a8556 | 57,153 |
def _full_link(provider, word):
"""Return a website link for dictionary provider and word."""
return 'http://' + provider + word | 56681e50523910a0519e29f7446355a20d932284 | 57,154 |
def is_username_taken(username):
"""Checks if the given username is taken."""
return user_models.UserSettingsModel.is_normalized_username_taken(
UserSettings.normalize_username(username)) | 81b76db282329b9fb96980b7ed70fc756ec8c2df | 57,155 |
def element_text(member_elt, elt_name):
"""Extract all `para` text from (`elt_name` in) `member_elt`."""
text = []
if elt_name:
elt = member_elt.find(elt_name)
else:
elt = member_elt
if elt:
paras = elt.findAll('para')
for p in paras:
text.append(p.getText(separator=u' ').strip())
ret... | 13ff356e1a584bcaa9c905c93dcafaa787ca936f | 57,156 |
import os
def getCbPath(lang):
"""
Return the path to the callbacks.py module in python notation.
For the language 'cpp' the function return '..plugins.cpp.callbacks.py'.
Return None if no such module exists.
Arguments:
lang -- the name of the language
"""
path = '/'.join([os.path.di... | b09a07baf6457d577ebfb77d834619b6bb91d38f | 57,157 |
def is_object_dtype(arr_or_dtype) -> bool:
"""
Check whether an array-like or dtype is of the object dtype.
Parameters
----------
arr_or_dtype : array-like
The array-like or dtype to check.
Returns
-------
boolean
Whether or not the array-like or dtype is of the object ... | bee2aa83492af750744cd49d04f9d08d4cdc3caf | 57,158 |
def pubmed_authors(bs4_object, target_class="full-name"):
"""
:param bs4_object: An object of class Beautiful Soup
:param target_class: Target class where the authors are found.
:return: Pubmed authors, abbreviated.
"""
res = bs4_object.find_all("a", {'class': target_class})
# Delete duplica... | a4ab357e1a5170b7dd04ceb79925fe5de88b4da8 | 57,159 |
import os
import tqdm
def _gen_wfedrift_coeff(self, force=False, save=True, wfe_list=[0,1,2,5,10,20,40],
return_results=False, return_raw=False, **kwargs):
""" Fit WFE drift coefficients
This function finds a relationship between PSF coefficients in the
presence of WFE drift. Fo... | f1fc05e78049acd4aed7e521bc680687436f7fcd | 57,160 |
def flagtable_summary(ft: FlagTable):
"""Return string summarizing the FlagTable
:param ft: FlagTable
:return: string
"""
return "%d rows" % (len(ft.data)) | 4bd2d1c4d3bf66ba1342d21c86f8c56f5ff4c1b8 | 57,161 |
import warnings
def deprecated(func, name=None, advice=""):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used."""
if advice:
advice = ": %s" % advice
if name is None:
name = func.__name__
... | 29570008fe7f28b20b4c8389f920b47f6f28be4a | 57,162 |
def ipfp_homoskedastic_solver(
Phi: np.array,
men_margins: np.array,
women_margins: np.array,
tol: float = 1e-9,
gr: bool = False,
verbose: bool = False,
maxiter: int = 1000,
) -> IPFPResults:
"""Solves for equilibrium in a Choo and Siow market with singles,
given systematic surplus ... | d77e14fa5481ecef20ffb31f7a8e5847884d502f | 57,163 |
def groupby(f, coll):
""" Group a collection by a key function
>>> from tompkins.util import groupby
>>> names = ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank']
>>> groupby(len, names)
{3: ['Bob', 'Dan'], 5: ['Alice', 'Edith', 'Frank'], 7: ['Charlie']}
"""
d = dict()
for item in co... | 101917cff08823ee29938963e47418e86eec5389 | 57,164 |
def nonfixated_camera_pose( filename ):
"""
Return two 6DOF camera pose vectors for two images of nonfixated view.
Filename is in the format:
'/{PATH_TO_DATA_ROOT}/{MODEL_ID}/{domain}
/point_{POINT_ID}_view_{VIEW_ID}_domain_{DOMAIN_NAME}.png'
Parameters:
----------
... | 7705ac506b3a935c584457ebc7cb8f22d426fb8a | 57,165 |
import torch
def to_device(data, device):
"""Move data to device
Arguments:
data {TupleTree, tensor} -- Tensors that should be moved to device.
device {str, torch.device} -- Device data is moved to.
Returns:
TupleTree, tensor -- Data moved to device
"""
if type(da... | 9e0661951e7793a92d7f1953bfb481ccf4ec4ca9 | 57,166 |
def build_equality_testcase(name, f, manifest):
"""
A builder for a unittest TestCase class that asserts equality
name
The name of the TestCase subclass that will be created
f
The function to be tested
manifest
An iterable of 3-tuples of strings, of:
- label, will b... | fecde9d29d98c338bea98ab63fe56482deb84a76 | 57,167 |
def mod(sequence):
"""
This is a not implemented function. It is a fix for ProtParam.ProteinAnalysis().protein_scale and the DIWV scale.
As the latter requires knowldge of the preceeding amino acid it will fail.
>>> p = ProtParam.ProteinAnalysis(sequence)
>>> p.protein_scale(ProtParamData.DIWV, wind... | e61016cd39f1a14f01b48d2ee1f373b5e74921f0 | 57,168 |
import itertools
def show_chain(*chains, **kw):
"""Show a chain (or several chains) of object references.
Useful in combination with :func:`find_ref_chain` or
:func:`find_backref_chain`, e.g.
>>> show_chain(find_backref_chain(obj, inspect.ismodule))
You can specify if you want that chain tr... | dee0587f34a6b26d055915607cd0fd0243302755 | 57,169 |
def get_gmt_date():
"""
Generated a GMT formatted Date
:return: current date
"""
return formatdate(timeval=None, localtime=False, usegmt=True) | 5ffab5c577305f7c4459ea84f4171201b86a7b63 | 57,170 |
import struct
def get_flac_duration(filename: str) -> float:
"""Returns the duration of a FLAC file in seconds.
From: https://gist.github.com/lukasklein/8c474782ed66c7115e10904fecbed86a
"""
def bytes_to_int(bytes: list) -> int:
result = 0
for byte in bytes:
result = (res... | 977cf3833945a1f85f2505e88f18580034412a3b | 57,171 |
import six
def _validate_iterable(iterable_type, value):
"""Convert the iterable to iterable_type, or raise a Configuration
exception.
"""
if isinstance(value, six.string_types):
msg = "Invalid iterable of type(%s): %s"
raise ValidationError(msg % (type(value), value))
try:
... | aee71c0b2bf0457161b325d816bc22c5934397a3 | 57,172 |
import os
def lookUpDirTree(fileName):
"""
This is called when we are using a default name for either the
FontMenuNameDB or the GlyphOrderAndAliasDB files.
These are often located several dir levels above the font file,
as they are shared by the font family.
"""
MAX_LEVELS = 4
path = ... | 350622e51187284eaadd1ed0a588fa0efaf181d3 | 57,173 |
from typing import Optional
from typing import Dict
from typing import Tuple
import pathlib
import os
def compile_solidity_json(sol_filename: str, libs: Optional[Dict[str, str]] = None, optimizer_runs: int = -1,
output_selection: Tuple = ('metadata', 'evm.bytecode', 'evm.deployedBytecode'),
... | c7aa830291af07d31ac3d2c624c091ac873f6571 | 57,174 |
def get_legends(ax: plt.Axes = None) -> list:
"""
returns all legends on a given axis, useful if you have a secaxis
:param ax: %(ax_in)s
:return: list of legends
"""
if ax is None:
ax = plt.gca()
return [_ for _ in ax.get_children() if isinstance(_, Legend)] | 4729677331bb8e63c0b4cdb2721091f42f48a4e2 | 57,175 |
def TList(val):
"""Checks if the given value is a list.
"""
return isinstance(val, list) | 057cbde8da75a96b859288f86451aa42afe5c288 | 57,176 |
def generation_production(pop_size, iterations):
"""
This function produces generation after generation,
to get the DVFS coefficients that sufficiently minimize the energy.
pop_size: The size of initial population given for further optimization.
iterations: The number of iterations that a generati... | c8aca0471ecfde630aba39c76bdc624fdbdc847c | 57,177 |
import argparse
import os
def get_args():
"""Get arguments."""
parser = argparse.ArgumentParser(description="""
This application translates your articles on Qiita into English ones with googletrans, and
upload them to Qiita automatically.
Requirements:
googletrans, Qiita access token(Se... | 117e638e7ad542db5a89a6e100f3e70848b4c3f3 | 57,178 |
def _convert_line(line):
"""
Parameters
----------
line: str
Returns
-------
list
"""
line = line.upper().split()
tmp = []
for i in line:
if '.' in i:
try:
tmp.append(float(i))
except:
tmp.append(i)
el... | 179b4ea803160679399195da15f147d2ff311d5f | 57,179 |
def get_pairs(triangles):
"""
Return list of start and end point pairs for array of triangle simplices
For example, triangles [['A', 'B', 'C'], ['B', 'C', 'D']] gives
[('A', 'B'), ('B', 'C'), ('C', 'A'), ('B', 'C'), ('C', 'D'), ('D', 'B')]
:param triangles: list of triangles
"""
r = []
... | 5fbc5098eada50081022d0148b50156661063223 | 57,180 |
def delete_play(play_id):
"""
Delete the play with the given id
:param play_id: The id of the play to delete
"""
mscores = get_mscores()
play = mscores.get_play(play_id)
if play:
if play.created_by == flask_login.current_user.get_id():
play.delete()
return jso... | 03a6f956d03f4abefe13e6e553d4b2dbb684374b | 57,181 |
async def async_discover():
"""
Discover all Denon AVR devices in LAN zone.
Returns a list of dictionaries which includes all discovered Denon AVR
devices with keys "host", "modelName", "friendlyName", "presentationURL".
By default SSDP broadcasts are sent once with a 2 seconds timeout.
"""
... | d3076336ac15f6715b5cfa311742d4b4536f91b5 | 57,182 |
def cache_header(max_age, versioned=False, refresh_period=0, **ckwargs):
"""
Add Flask cache response headers based on max_age in seconds.
If max_age is 0, caching will be disabled.
Otherwise, caching headers are set to expire in now + max_age seconds
Example usage:
@app.route('/map')
@ca... | 7452e02bf63a17f9e497a79367dd56f1f8fb487f | 57,183 |
def paginator_by_label(title: str,
df_items_labels: pd.DataFrame,
df_labels: pd.DataFrame,
on_sidebar: bool = True,
item_col: str = 'img_fpath',
item_id_col: str = 'img_id',
label_id... | 960863d1f9aa6c5606ff7aeabca4b085fce4dfc0 | 57,184 |
def transform(vol, loc_shift, interp_method='linear', indexing='ij',phase_encoding='RL'):
"""
transform (interpolation N-D volumes (features) given shifts at each location in tensorflow
Essentially interpolates volume vol at locations determined by loc_shift.
This is a spatial transform in the sense th... | 61b231676807aa90111d5105ea11c00a28547a3c | 57,185 |
def vgg_cnn(scaled_images, **kwargs):
"""
Three-block VGG-style architecture
:param scaled_images: (TensorFlow Tensor) Image input placeholder
:param kwargs: (dict) Extra keywords parameters for the convolutional layers of the CNN
:return: (TensorFlow Tensor) The CNN output layer
"""
conv1_1... | b57b4d6a8f32fddcb96a56e8460874cc62ff529b | 57,186 |
def cumprod(x, axis=None):
"""Cumulative prod of array elements over a given axis.
Args:
x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
:class:`cupy.ndarray`):
Elements to calculate the cumulative prod.
axis (int or None):
Axis along which the cu... | 0384a826ea899a1d2cdbf5bbad65a4cd1af769f7 | 57,187 |
import tokenize
def flair_tag(s: str, tag_type: str = "flair/upos-english-fast") -> dict:
"""
Tags a `flair` `Sentence` object using `flair` tagger.
tag_type:
"upos-english-fast": fast universal part-of-speech tagging model for English
"ner-large": large named entity recognition model for... | be5a4646711984a9370ea754e97e375a26be6258 | 57,188 |
def get_update_token(access_token):
""" Return the public token needed to update
an item """
client = create_client()
response = client.Item.public_token.create(access_token)
return response['public_token'] | a622c621c096fd38177047c0d76530205e7c04a2 | 57,189 |
from memory.rstorage import RedisStorage
import requests
import ast
def get_game():
""" Get Game with IP counting """
deck = request.args.get('deck', default='mini', type=str)
if authorize_request(request, RedisStorage):
url = "http://cards/game?deck="+deck
resp = requests.get(url)
... | db9e6710ed75c603f5773d2e86370dbb25351874 | 57,190 |
def set_random_nans(arr, p=0.5, from_col=1):
"""Set sequential right-hand-side elements of rows (selected with probability `p`) of a 2-d array to NaN.
Elements in columns <= `from_col` will not be set.
"""
if arr.shape[1] == from_col:
return arr
else:
rand_bool_idx = np.random.choice... | 335107a8c010750cd9f1cf90cd04efa1ea03a7ad | 57,191 |
def word_list_to_string(word_list, delimeter=" "):
"""Creates a single string from a list of strings
This function can be used to combine words in a list into one long sentence
string.
Args:
word_list (list/tuple): A list (or other container) of strings.
delimeter (str, Optional): A st... | 040479df7e0d5aadda0b12dc944a53d4b380f044 | 57,192 |
import os
def tool_path(tool_name):
"""
Return the path to a tool used by this pipeline.
:param str tool_name: name of the tool (e.g., a script file_name)
:return str: real, absolute path to tool (expansion and symlink resolution)
"""
return os.path.join(os.path.dirname(os.path.dirname(__fil... | a5acbdfb9f0023b6aab35606ac2f88396b7b3dc8 | 57,193 |
import warnings
def findmaxlag_quad(
thexcorr_x,
thexcorr_y,
lagmin,
lagmax,
widthlimit,
edgebufferfrac=0.0,
threshval=0.0,
uthreshval=30.0,
debug=False,
tweaklims=True,
zerooutbadfit=True,
refine=False,
maxguess=0.0,
useguess=False,
fastgauss=False,
lag... | a5b102910032cb181a983708cc379efec21e25ee | 57,194 |
def force_func(cell1,cell2,a,xi):
""" the native force function between two positions """
x1 = cell1.pos
x2 = cell2.pos
disp = x1 - x2
mod_disp = norm(disp)
force = 2 * a**4 * ( 2 * xi**2 - 3 * xi * mod_disp + mod_disp**2 )/( xi**2 * mod_disp**6 ) * disp
return force | 43723db5f7ef2a95a3471aaffaa5004cfc96c242 | 57,195 |
from re import T
def protonation_energy(pka, pH):
"""Calculate the free energy of protonation while considering the
pH of the system.
Parameters
----------
pka : floating point pka value for a residue
pH : pH of the system.
Returns
-------
DG : floating point free energy of ... | 49fb9c9d4eb341e3a36ea1d46fba013b7cf7233c | 57,196 |
def validate_params(params):
"""
Validates that the input parameters specify a PDB file to download.
Parameters
----------
params : libtbx.phil.scope_extract
Returns
-------
bool
Raises
------
Sorry
Raised if a pdb file is not specified to be fetched within params.
"""
if (params.fetc... | 960ea9fa5b7a530ac2e0aacdf9ce054c0e5ac2ff | 57,197 |
def format_el(el):
"""returns TeX for a BeautifulSoup element el.
This dispatches based on LATEX_FORMATTERS.
"""
ELEMENT_STACK.append(el.name)
try:
return LATEX_FORMATTERS[el.name](el)
finally:
ELEMENT_STACK.pop() | 75bf1d9e0edcfb702c3d99088856bcb42db3957b | 57,198 |
def _xml_add_crop_filter(xml, wkt):
""" Add cropping polygon as Filter Element and return """
fxml = etree.SubElement(xml, "Filter", type="filters.crop")
etree.SubElement(fxml, "Option", name="polygon").text = wkt
return fxml | 707035d650e074191fd77f95ca591ab8d1b00fdc | 57,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.