content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def dashifyHeadline(line):
"""
Takes a header line from a Markdown document and
returns a tuple of the
'#'-stripped version of the head line,
a string version for <a id=''></a> anchor tags,
and the level of the headline as integer.
E.g.,
>>> dashifyHeadline('### s... | fa168c52bf5ceb994b88347cc941f6c88742eead | 3,620,500 |
import os
def setpos(fh, off):
"""Implementation of perl $fh->setpos method"""
global OS_ERROR, TRACEBACK, AUTODIE
try:
fh.seek(off, os.SEEK_SET)
return True
except Exception as _e:
OS_ERROR = str(_e)
if TRACEBACK:
cluck(f"setpos({off}) failed: {OS_ERROR}",s... | e2e5206d72809eb6a457c63c5a2f258a58edcfbe | 3,620,501 |
def check_game_has_finished(player, game):
"""
Checks if the game has finished
:param player: (Player object) Current player
:param game: current game being played
:return: (boolean) True if the game has finished, else False
"""
finished_game = False
# Check if game has finished
if ... | 07eef0bcffc1069c1679c492afa96b1f7e297e09 | 3,620,502 |
def nullspace_relative_norm(A, x, tol=1e-12):
"""Compute the ratio between the norm of components of `x` that are in the
nullspace of `A` and the norm of `x`.
Args:
A (torch.Tensor): A matrix.
x (torch.Tensor): A certain vector.
tol (float): The tolerance level for determining what ... | e9e190951ed91d6f08aa3f4ac8edd6d889df00d4 | 3,620,503 |
def get_filter(df, alt_list, mach_list, aos_list, aoa_list):
""" Get a dataframe filter for a set of parameters lists. """
filt = pd.Series(True, index=df.index)
if alt_list:
filt &= df["altitude"].isin(alt_list)
if mach_list:
filt &= df["machNumber"].isin(mach_list)
if aos_list:... | bf85eef9d6235016db64387903f60d291cdc7bdc | 3,620,504 |
import binascii
def inet_ntoa(address):
"""Convert a network format IPv6 address into text.
@param address: the binary address
@type address: string
@rtype: string
@raises ValueError: the address isn't 16 bytes long
"""
if len(address) != 16:
raise ValueError("IPv6 addresses are ... | 6aa8e3a2f04cc17ca12b6dc68282659d78c65e9a | 3,620,505 |
def parseOutputForAllowedKeys(ml, allowed_keys=None):
""" Parses the given vclient output, while accepting only
known (or allowed) keys.
Also handles void states, where line occur that are neither
a key nor a value.
"""
data = {}
# When explicit keys are defined, start in void mo... | 44d0cf0a72759fd8087b1df240a1d25d75ac99c0 | 3,620,506 |
import requests
import traceback
def getAnyRun(sha256):
"""
Retrieves information from AnyRun Service
:param sha256: hash value
:return info: info object
"""
info = {'anyrun_available': False}
if sha256 == "-":
return info
try:
response = requests.get(URL_ANYRUN % sha25... | d61bb152494b90c3608f8c2e125acd5760fb2042 | 3,620,507 |
def explore_run_save_data_path(run_data_path):
"""Save run data path
Save run data path for next load in run stage
:param run_data_path: str, represent result evaluate path
:return: bool, represent save result
"""
explore_run_inst.run_data_path = run_data_path
return True | c7e0bf601043ea41510b1f76276f174615f04d7e | 3,620,508 |
def add_alias(alias: str, id: str) -> bool:
"""
This function assigns a desired alias of the user to its id.
Parameters
----------
alias : str
The alias name of the user
id : str
The id of the user
Returns
-------
bool
True if new alias has been added, otherw... | 9318625f1a55a678003465fd62a050f23015c16f | 3,620,509 |
from typing import List
def multi_scale_retinex(image: np.ndarray, sigma_list: List) -> np.ndarray:
"""
Performs multi-scale retinex by wrapping single-scale retinex
Parameters
-----------------------------
image: np.ndarray,
Image to be enhanced
sigma_list: List
Recommended s... | a85ac8e0dc934ca792d15a2cd25c850f0093052f | 3,620,510 |
import json
def craft_unknown_asset_message(
username, emoji, channel, launch_time, cloud_provider, vps_name, tags
):
"""Function to craft a nicely formatted Slack message using blocks
for cloud assets not found in Ghostwriter.
"""
UNKNOWN_ASSET_MESSAGE = {
"username": username,
"i... | fea3e96b93bfaba8971680fd0af52eccd543e0f0 | 3,620,511 |
def nevow_adapter_resource(interceptors=v()):
"""
Create a Nevow ``IResource`` that executes a context and avoids as much
Nevow machinery as possible.
A ~`fugue.interceptors.nevow.nevow` interceptor will be attached to the
front of the queue to facilitate the interaction with Nevow.
"""
_im... | 4180e753d8118c2749f8e57840d46057c87ba1da | 3,620,512 |
def make_division_term_lookup() -> pd.DataFrame:
"""DataFrame giving salient keywords for each division.
Combines the two sources of salient terms.
"""
# Match trend terms to divisions (combining the two sources of salience data)
division_term_lookup1 = _division_term_lookup_v1()
division_ter... | 5f3bb4eff2db1c7bcc48f32a8cd98837c0f3cd51 | 3,620,513 |
def address_has_changed(instance) -> bool:
"""
Check that the newly saved address
is different from the already saved
"""
return (instance.address != get_user_model()
.objects.get(id=instance.id).address) | 06cea06faac7ee5f9e2d3cbe73e3984cc4b9107f | 3,620,514 |
import re
def condition(string: str) -> str:
"""Turn variable conditions into `if score`"""
def equal_int(match: re.Match) -> str:
groups = match.groups()
return f'score {groups[0]} __variable__ matches {groups[1]}'
string, success = re.subn(
f'^{Re.var}\s*(?:==|=)\s*{Re.integer}$'... | 9c2214a7b5020510a6f41c60459234111e7064f1 | 3,620,515 |
import logging
def setup_logger():
"""Set up logging."""
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(name)24s %(levelname)8s: %(message)s")
... | 0eeb8c1694fcff286720ab0149690dd8e57bf23c | 3,620,516 |
def tilted_L1(u, quantile=0.5):
"""
tilted_L1(u; quant) = quant * [u]_+ + (1 - quant) * [u]_
"""
return 0.5 * abs(u) + (quantile - 0.5) * u | ff7a3fe97d79e4c848797c79a2a7c14b449ad6b6 | 3,620,517 |
import re
import sys
def get_abs_path(path: str) -> str:
"""
Gets the fully evaluated absolute path for a given path.
This function uses a horrific workaround for an issue where CMD and Powershell 5 provide incorrect arguments
when called with a path with spaces which ends in a backslash, like ".\my ... | fe7e01afab7bfba1d1211a94b2fb74890ba6253b | 3,620,518 |
from rfpipe import source, search, reproduce, candidates
def prep_and_search(st, segment, data, indexprefix='new', returnsoltime=False):
""" Reproduces rfpipe.search.prep_and_search but calculates and
indexes noises.
"""
ret = source.data_prep(st, segment, data, returnsoltime=returnsoltime)
if r... | 795626ad0992c51dd1e94659381d15f4299813a2 | 3,620,519 |
def update_entity(id):
"""
Update a story from the provided json
:param intent_id:
:param json:
:return:
"""
json_data = loads(request.get_data())
entity = Entity.objects.get(id=ObjectId(id))
entity = update_document(entity, json_data)
entity.save()
return 'success', 200 | e7642a6bf50a26b7c4bcac018b5ea44f92f6d42d | 3,620,520 |
import random
def data_augmentation(original_samples, original_labels, original_groups, augmentation_factor=2, x_coord=0, y_coord=1, c_coord=2):
"""
Pass original_samples after interpolation as a constant shape of (n_samples, NUM_FRAMES, n_keypoints, xyc)
"""
org_num_samples, org_num_frames, org_num... | 2f06d34ddcdcd09901f74d976f3983d67266bd86 | 3,620,521 |
def get_sectors():
"""Get all sectors in Yahoo Finance data. [Source: Finance Database]
Returns
-------
list
List of possible sectors
"""
return fd.show_options("equities", "sectors") | f3f6c1c095ba8c59d5ae0f5ed77cf98ee352265a | 3,620,522 |
def getId(collection):
""" Get the ImageCollection id.
**CLIENT SIDE**
:type collection: ee.ImageCollection
:return: the collection's id
:rtype: str
"""
return collection.limit(0).getInfo()['id'] | ad08535eb838cfa4d7153efd476b6dac14d118bc | 3,620,523 |
def _process_data_ascii(raw, metadata, verbose_acquistion=True):
"""Process raw comma separated ascii data to time values and y voltage
values as received from :func:`Oscilloscope.capture_and_read_ascii`
Parameters
----------
raw : str
From :func:`~keyoscacquire.oscilloscope.Oscilloscope.ca... | 6d6e02828e5783630bd247469f4edcf4ba2ae21e | 3,620,524 |
def predict_batch(model, dataset_batcher: Batcher):
"""Predict the values using the given batcher
Parameters
----------
model: SKLearn model
dataset_batcher : Batcher
Returns
-------
np.array
Predictions array
"""
y_pred = []
for X, y in dataset_batcher:
y_... | 0ac39f2eac8f2b74c1e42d2408e7a35be5eba98b | 3,620,525 |
import shutil
def migrate_file_target(target: FileTarget, copy: bool = False) -> FileTarget:
"""Apply a move, or copy of the FileTarget from source to new destination."""
_ensure_target_directory(target.target_move_path)
target = _check_existing_target_file(target)
if target.file_path == target.targe... | 0f0d1d5819b430afc1ac57c8f0c33a288df7757e | 3,620,526 |
def bytes_to_human(size, digits=2, binary=True):
"""Convert a byte value to the largest (> 1.0) human readable size.
Args:
size (int): byte size value to be converted.
digits (int, optional): number of digits used to round the converted
value. Defaults to 2.
binary (bool, op... | 22367220a122e399658a0dd42b52083ccc29df6f | 3,620,527 |
import requests
import toml
def get_stellar_toml(domain, allow_http=False):
"""Retrieve the stellar.toml file from a given domain.
Retrieve the stellar.toml file for information about interacting with
Stellar's federation protocol for a given Stellar Anchor (specified by a
domain).
:param str do... | 665ff032834d3bb501e1ff9a8591d54d6d3bb5a8 | 3,620,528 |
def parseReplyBlock(s):
"""Return a new ReplyBlock object for an encoded reply block.
Raise ParseError on failure.
"""
block, length = _parseReplyBlock(s)
if length > len(s):
raise ParseError("Misformatted reply block: extra data.")
return block | 18e750ad42aa8e1216722d837b95d803ea6a9dc6 | 3,620,529 |
def _validate_method(method, where):
"""Helper for get_params()"""
if method is None:
return None
if method not in ['signal', 'thread']:
raise ValueError('Invalid method %s from %s' % (method, where))
return method | dbf7194f50a43dc3fd944f8923ddfec5aed3bbe7 | 3,620,530 |
import yaml
from yaml import CLoader as Loader
from yaml import Loader
def load_yaml(s: Union[bytes, IO, IO[bytes], Text, IO[Text]]):
"""Load a Yaml document.
This is a helper function which tries to use the fast ``CLoader``
implementation and falls back to the native Python version on failure.
"""
... | 5b0a70cd9a1bcb2596c9fccaf6566f3968a5c5e1 | 3,620,531 |
def _get_specs_and_amplitude_traces(all_audio, fs, spec_params):
"""
Return spectrograms and amplitude traces given a list of audio.
Parameters
----------
all_audio : list of numpy.ndarray
List of audio.
fs : int
Audio samplerate
spec_params : dict
Contains keys `'nperseg'`, `'noverlap'`, `'min_freq'`, `'... | df12742968e3c0a75fff967c21a1738905dfce20 | 3,620,532 |
from typing import Mapping
from typing import Callable
def make_index(
all_modules: Mapping[str, pdoc.doc.Module],
is_public: Callable[[pdoc.doc.Doc], bool],
default_docformat: str,
) -> list[dict]:
"""
This method compiles all currently documented modules into a pile of documentation JSON objects... | e6cc170e2aa967530e99e3bc07e9919964d629d8 | 3,620,533 |
import pathlib
def parent(path: str) -> str:
"""Get path's parent
e.g
j.sals.fs.parent("/home/rafy/testing_make_dir/test1") -> '/home/rafy/testing_make_dir'
Args:
path (str): path to get its parent
Returns:
str: parent path.
"""
return str(pathlib.Path(path).parent) | 8ed409fde19dcd74d3fb2c169946680a0c46543b | 3,620,534 |
def slugify(text):
"""
Turn the text content of a header into a slug for use in an ID
"""
non_safe = [c for c in text if c in non_url_safe]
if non_safe:
for c in non_safe:
text = text.replace(c, '')
# Strip leading, trailing and multiple whitespace, convert remaining whitespa... | a70c896e83c135822dfebb53ced8525380c1d33d | 3,620,535 |
def _getText(nodelist):
""" returns collected and stripped text of textnodes among nodes in nodelist """
rc = ""
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc = rc + node.data
return rc.strip() | 37548ebf34f0f26cc4166e95621ee1ec0f3a3f71 | 3,620,536 |
import re
def strip_html(text):
"""See http://stackoverflow.com/a/9662362"""
return re.sub('<[^<]+?>', '', text) | 94747883a5df06b70fb3513e82e610d981582bbb | 3,620,537 |
def sampling(DAG, n=1000, verbose=3):
"""Generate sample(s) using forward sampling from joint distribution of the bayesian network.
Parameters
----------
DAG : dict
Contains model and adjmat of the DAG.
n : int, optional
Number of samples to generate. The default is 1000.
verbos... | 60d49dae888507d8b5da6c6b847084bf0fd0b73c | 3,620,538 |
def from_json(json_data, key):
"""Extract values from JSON data.
:arg dict json_data: The JSON data
:arg str key: Key to get data for.
:Returns: The value of `key` from `json_data`, or None if `json_data`
does not contain `key`.
"""
if key in json_data:
return json_data[key]
... | 2e5a97176c771c1c363fd7fbf86d8bf7b598f4ab | 3,620,539 |
def weights_dask(weights):
"""
Weighting array by cosine of the latitude.
"""
return weights.chunk() | d1b4259b806665760506b43cf072ceb61fcb2d8d | 3,620,540 |
import os
import binascii
def get_secure_random_string(size):
"""
Return a string of ``size`` random bytes. Returned string is suitable for
cryptographic use.
:param size: Size of the generated string.
:type size: ``int``
:return: Random string.
:rtype: ``str``
"""
value = os.ura... | fde036e0183b4ec7920e1dffefc6097c93752d58 | 3,620,541 |
def is_not_json(bytestring):
"""
:param bytes bytestring: A candidate byte string to inspect.
:return bool: ``False`` if and only if ``bytestring`` is JSON encoded.
"""
try:
loads(bytestring)
except:
return True
return False | 5af6f6b901caf79a4f8dc2e1180f83824c579193 | 3,620,542 |
def get_ingredients():
"""Find all available ingredients.
Returns:
list(IngredientDto): A list of all ingredients.
"""
ingredient_entities = IngredientEntity.query.all()
return [ingredient_entity_to_dto(entity, entity.availability) for entity in ingredient_entities] | 57e01f9b9f59f2929bba1ea35fe311b2e38a6764 | 3,620,543 |
def add_stock(request):
"""
This view renders Create brand Page """
prod_obj = Product.objects.all()
if not request.user.is_viewer :
context = {
"title": "Create Stock",
"products": prod_obj
}
return render(request, 'add_stock.html',context)
else:
... | dbd2869d4b41ce014fec08a807d44c0e9d290dda | 3,620,544 |
def project(a):
""" De-homogenize vector """
return a[:-1] / float(a[-1]) | 68074a4fb9c5021f7e727654e699d823d093c3a6 | 3,620,545 |
def add_presentations_sheet(supervisor, modified_df):
"""Adding the Presentations sheet with all Presentations according to the talk order on the presentation day"""
src_grading_wb = load_workbook('DataSources/Foik_GradingSheetSeminar.xlsx')
print("The available sheets in the xlsx file")
print(src_gradi... | b563e87a3080088c2c2fcc32db5234874a03edc6 | 3,620,546 |
import os
def ospathjoin(*args, **kwargs):
"""
Simple ``o.path.join`` for a specific platform.
@param args list of paths
@param kwargs additional parameters, among them,
*platform* (win32 or ...)
@return path
"""
def build_... | 025c4f5dc352df00d3aa8586a2cde88c63518eaa | 3,620,547 |
def load_obj(filename: str, default_mtl='default_mtl', triangulate=False) -> WavefrontOBJ:
"""Reads a .obj file from disk and returns a WavefrontOBJ instance
Handles only very rudimentary reading and contains no error handling!
Does not handle:
- relative indexing
- subobjects or groups
- line... | 2a09fd8eb0aef78564d616d8b42e090c62ed73ac | 3,620,548 |
def get_car(shape):
"""Get car image as input."""
return get_img(shape, "car.JPEG", np.float32, should_scale=True) | 232522a6324b92db4b0b3f7031b0ef16a3d35b7d | 3,620,549 |
import select
def get_total(session, Model):
"""Should be made in a context manager"""
stmt = select(func.count(Model.id))
_total = session.execute(stmt)
total = _total.scalar()
return total | 1b9ade37da64ce5ca34b3a6da70c230768b5cb0b | 3,620,550 |
def temp_c_2_f(temp):
"""
translate Celsius to Fahrenheit
T(°F) = (T(°C) * 1.8) + 32
"""
tc = (Decimal("%s" % temp) * Decimal("1.8")) + 32
return tc | 3d5793d0f058378291ea8491a3f0cf9ffbdea18b | 3,620,551 |
def CLT2_ci(mean_log, std_log, n, ci=0.95):
""" Returns the error margin for the geometric mean based
on the central limit theorem and the t-statistics.
Parameters
----------
mean_log : scalar, float
the arithmetic mean of the log-transformed data
std_log : scalar, float
the st... | b55becf2f8ef3dddc77a057c3d4a78075f6b916e | 3,620,552 |
import sys
def create_and_wait_kfp_run(pipeline_id: str,
version_id: str,
run_name: str,
experiment_name: str = "Default",
api_version: str = KATIB_API_VERSION_V1BETA1,
**kwargs)... | 5781b6514d0c9ce98f3e26916f679238a680e904 | 3,620,553 |
def coraldistancemap(edgemask,x_mesh,y_mesh):
""" Function generating an array with the minimum distances to a coral object
The edgemask object should be a boolean array with the same shape as the x- and y-meshes.
It is True where the edges of the coral objects are located and False everywhere else
"""
... | 02e31f0db1f9aa02a508ea1d55789334a2b27a04 | 3,620,554 |
def conditional_entropy(xs, ys, bx=0, by=0, b=2.0, local=False):
"""
Compute the (local) conditional entropy between two time series.
This function expects the **condition** to be the first argument.
The bases *bx* and *by* are inferred from their respective time series if
they are not pro... | 03487b0b67e78359650001495cbb8ad975e69a6c | 3,620,555 |
def screen_aos(mol, active_atoms, den_mat_a, ovlp, trunc_lambda):
"""Screen AOs for truncation"""
include = [False] * mol.nbas
active_aos = []
for shell in range(mol.nbas):
aos_in_shell = list(range(mol.ao_loc[shell], mol.ao_loc[shell + 1]))
if mol.bas_atom(shell) not in active_atoms: ... | b4856265441d1a51d09d3c261b39ec655cf202e4 | 3,620,556 |
def setup_decision_tree_classifier(training_data,
training_target,
testing_data,
features = "preprocessed",
method = "count",
ngrams=(1,1)):
... | 9beac2b60c6e57ef15c37f49485fca352921962b | 3,620,557 |
def doubleMetaphone(field):
"""TODO.
Examples:
.. code:: python
> print(doubleMetaphone('John Woodward'))
> {'ANTRT', 'JNTRT'}
"""
return {metaphone for metaphone in doublemetaphone(field) if metaphone} | 1a0aec21e142000d39ad39c8f88db6c66cfe3a7f | 3,620,558 |
def find_nearest(data, target, align='start', max_time_diff=None):
"""Finds the index of the nearest row in `data` to `target` time.
Args:
* data (pd.Series or pd.DataFrame): if `align==back` then `data` must
have an `end` column.
* target (pd.Timeseries or timestamp)
* align (str): `... | 849fca02f6757aa4487e38fd5b551bc543046b56 | 3,620,559 |
def clipped_error(x):
"""
# Huber loss (delta = 1)
L(a) = if abs(a) < delta -> 0.5*a*a
else -> delta*(abs(a) - 0.5*delta)
"""
# function where return the coordination of the values which is meet for the condition
# where(condition, x, y) 根据condition返回x或y中的元素
return tf.... | 9cba0097c4f90a31ef7b6fb11e3df86a154b64a5 | 3,620,560 |
def _rotate_affine(affine, shape, rotation):
"""
Work in progress. Does not work yet.
:param affine:
:param shape:
:param rotation:
:return:
"""
assert_affine_is_diagonal(affine)
# center the image on (0, 0, 0)
temp_origin = (affine.diagonal()[:3] * np.asarray(shape)) / 2
tem... | 5b24fc2450150d3f8e31576c70b5ad3bc17ee0d7 | 3,620,561 |
import torch
def b_inv(b_mat):
"""
inverse function for 2x2 matrix
:param b_mat: [M, 2, 2]
:return: [M, 2, 2]
"""
b00 = b_mat[:, 0, 0]
b01 = b_mat[:, 0, 1]
b10 = b_mat[:, 1, 0]
b11 = b_mat[:, 1, 1]
det = (b00 * b11 - b01 * b10)
b00 = b00 / (det + eps)
b01 = b01 / (det +... | e3a282a8cd24be31ae377c6c54e97f9daaa4afcc | 3,620,562 |
def right_bit_shift(lhs, rhs, ctx):
"""Element ↳
(num, num) -> a << b
(str, num) -> a.rjust(b, " ")
(num, str) -> b.rjust(a, " ")
(str, str) -> a.rjust(len(b)-len(a), " ")
"""
ts = vy_type(lhs, rhs)
return {
(NUMBER_TYPE, NUMBER_TYPE): lambda: int(lhs) >> int(rhs),
(str, ... | 246a6287baf3ad1b80e4ad56c7d41116dc00fb00 | 3,620,563 |
def spell_check(text, spell):
"""Fix misspelled words"""
suggestions = spell.lookup_compound(text, 2)
if suggestions:
return suggestions[0].term
else:
return text | 6ada77bbc6d691fa0e650f27f9a1e09885e70c14 | 3,620,564 |
def get_favicon():
"""
Function used internally to send static files from the static
folder to the browser
内部使用send_static_file方法将静态文件夹中的图片数据发送到浏览器
"""
# 找到网站图片的静态资源并返回
return current_app.send_static_file("news/favicon.ico") | fd85af2ffb65e1f0118b4b92d087112455f4e7ac | 3,620,565 |
def adagrad(lr, epsilon, weight_decay):
"""\
Adagrad optimizer.
Adagrad is an optimizer with parameter-specific learning rates, which are
adapted relative to how frequently a parameter gets updated during
training. The more updates a parameter receives, the smaller the learning
rate. See: http:... | ba441ca1cf064d8d84c8d7a37223daeafc1de9c5 | 3,620,566 |
from typing import List
from typing import Dict
from typing import Counter
def layout_agnostic_vocabulary_vector(
results: List[Dict],
number_of_words: int
) -> List[str]:
"""Create a layout agnostic vocabulary vector
Finds the most popular words out of a bag comprised of all layouts
... | d5bd370293e34c8a792f7dff11a56f36675dceea | 3,620,567 |
def getTriangularVertices(n,
rotationAngles = [0, 0, 0],
phi_start = 0,
phi_end = np.pi,
plotIt = False):
""" Triangular approximation of a sphere
Two angular sweeps are necessary. One is theta that goes arou... | 8c8c25ef2aadec4dd33c39d6a438e066af2d33ec | 3,620,568 |
def _get_role_prefix(node):
"""Calculates the node role prefix used for grouping nodes in the graph"""
try:
role_prefix = node['role'][0].split("_")[0]
if role_prefix == REPO['EXCLUDE_ROLE_PREFIX']:
role_prefix = 'none'
role_prefix = node['role'][1].split("_")[0]
... | 0dafae13bd7c2530070809c16eb115556664dbee | 3,620,569 |
from typing import Optional
from typing import Union
from typing import Dict
from typing import List
def check_message(
message_id,
parameter: Optional[Union[str, Dict]],
level_type: Optional[Union[str, List[str]]],
level: Optional[Union[int, List[int], Dict]],
**kwargs,
) -> b... | 8d258e2bb8ac7874f113c6cac544370ab9f36fee | 3,620,570 |
from typing import TextIO
def process(fh: TextIO) -> FastaInfo:
""" Process a file """
if lengths := [len(rec.seq) for rec in SeqIO.parse(fh, 'fasta')]:
return FastaInfo(filename=fh.name,
min_len=min(lengths),
max_len=max(lengths),
... | 66cdd2766b9bf2c7a4e98c06f24db1bf6161c5ce | 3,620,571 |
import re
def cln_info(record):
"""Annotates pathogenicity using ClinVar
Args:
record (tuple): vcf line with fields separated in tuple
Returns:
significance + '|' + disease (str): pathogenicity and disease name implicated
"""
try:
significance = re.search(r"(CLNSIG=)([... | 8d201c77b00373d2e5ae7866d6c15b704105a344 | 3,620,572 |
from operator import inv
def n_clinic_to_unit_cube(x_array,box):
"""
---Inputs---
x_array : {2 mode numpy array}
array defining the "real" coordinate(s) at which to calculate values of
basis functions
shape (n_points, d)
dimension of first mode gives number of points
... | d55dd6f99047935df395dde174b4525a2f6b9bcd | 3,620,573 |
def permission_request_delete_link(context, perm):
"""
Renders a html link to the delete view of the given permission request.
Returns no content if the request-user has no permission to delete foreign
permissions.
"""
user = context['request'].user
if user.is_authenticated():
link_k... | 2212b61e2a5dafc9b486c8345e728c09461a4f29 | 3,620,574 |
def dummies(data):
"""
Manually creates labels for property type. sklearn label encoder was breaking the model shape.
"""
data['Property_Area'] = data['Property_Area'].replace('Rural', 0, regex=True)
data['Property_Area'] = data['Property_Area'].replace('Semiurban', 1, regex=True)
data['Property... | 607da5c4a023c789a3a6da27d0ddfe4bfafa7d3a | 3,620,575 |
from fsm.fsmspec import FSMSpecification
def get_specs():
"""
Get FSM specifications stored in this file.
"""
spec = FSMSpecification(
name='faq',
hideTabs=True,
title='Take the courselet core lessons',
pluginNodes=[
START,
SHOW_FAQS,
... | 2f4b522ad699a866d047acf09e21e68fe7b967b1 | 3,620,576 |
from typing import Union
from typing import Optional
from typing import List
from typing import Tuple
def render(
markup: str,
style: Union[str, Style] = "",
emoji: bool = True,
emoji_variant: Optional[EmojiVariant] = None,
) -> Text:
"""Render console markup in to a Text instance.
Args:
... | 06b0e6e135aa35661d089c86002d6e796dd92bd4 | 3,620,577 |
def get_namespaced_custom_object_with_retries(namespace, name):
"""Call get_namespaced_customer_object API with retries.
Args:
namespace: namespace for the workflow.
name: name of the workflow.
"""
# Due to https://github.com/kubernetes-client/python-base/issues/59,
# we need to recreate the API clie... | 54a269189371271e54c76e4a6587aa1ec3c9f5a8 | 3,620,578 |
def info_colon_to_dict(value):
"""
Simple function to convert colon separated string to dict
"""
return info_to_dict(value, ":") | 264b05c130b41eca746c5fb30f6a591535151331 | 3,620,579 |
def parse_markdown(filename):
""" Takes a .md file and returns a parsed version in HTML.
Parses a markdown file using mistune, returns a string which
contains the parsed information in HTML.
Args:
filename: the file to be parse, must be a .md file.
Returns:
Variable which ... | 1d13da92f4c15a2cc7cad990b05b64bff4738f9b | 3,620,580 |
import time
def query_task_until_finished(task_id):
"""Blocks until an iControl LX task finishes or fails"""
max_attempts = 60
while max_attempts > 0:
max_attempts -= 1
status = get_task_status(task_id)
LOG.debug("task: %s returned status %s", task_id, status)
if status and... | bb51a677be489f63cc2608a82385c0e04d88f319 | 3,620,581 |
def create_full_example() -> model.DictObjectStore:
"""
Creates an :class:`~.aas.model.provider.DictObjectStore` which is filled with an example
:class:`~aas.model.aas.Asset`, :class:`~aas.model.submodel.Submodel`, :class:`~aas.model.concept.ConceptDescription`
and :class:`~aas.model.aas.AssetAdministra... | 935f1ed998d3f490e6ff46f550203faad3847f6d | 3,620,582 |
def filter_kmeans_segmentation(np_img, compactness=10, n_segments=800):
"""
Use K-means segmentation (color/space proximity) to segment RGB image where each segment is
colored based on the average color for that segment.
Args:
np_img: Binary image as a NumPy array.
compactness: Color proxim... | 6ebc0a18072646f8af87fae1f4d6e6679c7ad691 | 3,620,583 |
from typing import Optional
from typing import List
def _pytd_signature(
function: ast3.AST,
is_async: bool,
exceptions: Optional[List[pytd_node.Node]] = None
) -> pytd.Signature:
"""Construct a pytd signature from an ast.FunctionDef node."""
name = function.name
args = function.args
pos_params = ... | 46dc2a960e7f72636fdf5d2b6d45b2a8043e5a81 | 3,620,584 |
import seaborn as sns
def anno_heat(X, row_anno=None, col_anno=None,
row_order_ids=None, col_order_ids=None,
xticklabels=False, yticklabels=False,
row_cluster=False, col_cluster=False,
**kwargs):
"""
Heatmap with column or row annotations. Based on seab... | 812f8c9057094efd8718b9c40238e367b88dc73d | 3,620,585 |
from unittest.mock import Mock
def dao_exchange_rate_mock():
"""
:return: Mock of gold_digger.database.DaoExchangeRate
"""
return Mock(DaoExchangeRate) | 22683a22e860a95199388f9d4d15539cc1f019a2 | 3,620,586 |
from typing import Optional
from typing import Tuple
import itertools
import os
import stat
def find_exec(executable: str, compat: Optional[str] = None, root: str = '/') \
-> Tuple[str, str]:
"""Search an executable in the system
Uses the ``PATH`` environment variable.
:param executable: Executa... | ba8ebde9d2beb11db72d7dc18deae8478843d48c | 3,620,587 |
import six
def _repr_odict(dumper, data):
"""
Represent OrderedDict in yaml dump.
Source: https://gist.github.com/weaver/317164
License: Unspecified
>>> data = OrderedDict([('foo', 'bar'), ('mumble', 'quux'), ('baz', 'gorp')])
>>> yaml.dump(data, default_flow_style=False) # doctest: +SKIP
... | 6c141e7c2db180fc07041955ed7f4b49eadc56c6 | 3,620,588 |
def _update_inventory(context, rp, inventory):
"""Update an inventory already on the provider.
:raises `exception.ResourceClassNotFound` if inventory.resource_class
cannot be found in either the standard classes or the DB.
"""
_ensure_rc_cache(context)
rc_id = _RC_CACHE.id_from_string(i... | 02af39181ad73da7c21c1526308f571001860ae7 | 3,620,589 |
def assert_all_loaded(pairs, raise_=True):
"""
Returns True if all SleepStudy objects in 'pairs' have the 'loaded'
property set to True, otherwise returns False.
If raise_ is True, raises a NotImplementedError if one or more objects are
not loaded. Otherwise, returns the value of the assessment.
... | d211b77c2d16fafaff5555701af66d0144fb0b73 | 3,620,590 |
def max_pool(x, ksize, stride, name):
"""
Create a max pooling layer
:param x: input to max-pooling layer
:param ksize: size of the max-pooling filter
:param stride: stride of the max-pooling filter
:param name: layer name
:return: The output array
"""
return tf.nn.max_pool(x,
... | eed9b1a7334b4dbafa0f360aabaa0614b21f5596 | 3,620,591 |
def _check_robot_postproc_compatibility(robot, processor):
"""
Verify the compatibility of the selected robot and the processor.
:return:
"""
warning = ''
robot_type = mimic_utils.get_robot_type(robot)
processor_type = processor.type_robot
# Always return without a warning if the p... | 186b6953aed40c01b879717966cb39e82ead8c8c | 3,620,592 |
def flush(hand):
"""Return True if there is a flush"""
suits = [s for r,s in hand]
return len(set(suits)) == 1 | 75f5542b5a187e6bf3e3b59f961357d0921c6a76 | 3,620,593 |
from typing import List
def filter_by_name(candidates: List[Element], query: EdifactStackQuery) -> List[Element]:
"""
returns those elements that have the given name (in the query)
"""
filtered_by_names = [
x
for x in candidates
if are_similar_names(x.attrib["name"], query.name... | 4c6e405b932e4c53e60d474352a14723200aa7e1 | 3,620,594 |
import os
def expand_params(params_to_env):
"""
Given a dictionary like:
{
"AwsAccessKeyId": "AWS_ACCESS_KEY_ID",
"AwsSecretAccessKey": "AWS_SECRET_ACCESS_KEY",
"KeyNukerOrg": "KEYNUKER_ORG",
}
Convert to a string like:
--param KeyNukerOrg default --param AwsAccessKe... | 37833e73a0f6375689cad5bfd114e1ce1431c47f | 3,620,595 |
def remote_shortname(socket):
"""
Obtains remote hostname of the socket and cuts off the domain part
of its FQDN.
"""
return socket.gethostname().split('.', 1)[0] | e52ec17a36800029a9889dc1b5e567567b9c9340 | 3,620,596 |
def MakePlot(specWithCuts, specWithoutCuts, options):
"""
Creating the final plot. The plot will be a two panel plot:
1st panel shows the comparison of the spectra.
2nd panel shows the ratio of the normalised spectra with and
without pileup rejection (as without/with)
... | 27a206b538347b4657aa924f93e8f1d428da1dae | 3,620,597 |
def network_instance_list(network=None, host=None):
"""
Retrieves information about all resources.
Parameter *kind*:
If *kind* is set, only resources with a matching kind will be returned.
Return value:
A list with information entries of all matching network_instances. Each list
entry contains exactly th... | 7eab3046a89662ce1b0f13fa6ee93481bbf7f51c | 3,620,598 |
def formatParagraphLine(text, width):
"""
:return: array of rows
"""
words = text.split()
tail = words
result = []
buf = ''
while len(tail):
curWord, tail = tail[0], tail[1:]
if len(buf) + len(curWord) + 1 > width:
if buf == '':
row = curWord
... | 14672342e24706df117425d5e59f9d2c762faab2 | 3,620,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.