content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def replace_special_whitespace_chars(text: str) -> str:
"""It's annoying to deal with nonbreaking whitespace chars like u'xa0'
or other whitespace chars. Let's replace all of them with the standard
char before doing any other processing."""
text = re.sub(r"\s", " ", text)
return text | 17be082a827039264cd75fb7459fc31eb7f617dd | 3,606,169 |
def _extract_missing(values):
"""Extract missing values from `values`.
Parameters
----------
values: set
Set of values to extract missing from.
Returns
-------
output: set
Set with missing values extracted.
missing_values: MissingValues
Object with missing valu... | ad3661fa7e77a37792f864fc1acf404c23abca4d | 3,606,170 |
import re
def processSets(results):
"""Process set results to be displayed in the set selection window
:param List[Dict[str, Union[int, str, Dict[str, str]]]] results: A list of raw set results
:return: A list of processed results in table form
:rtype: List[Union[str, int]]
"""
rows = []
... | bf050015474691402d2d992070c487b45cc34a42 | 3,606,171 |
def min(a):
"""
Returns the minimum value of an array
"""
try:
return _onp.min(a)
except TypeError:
return _cas.mmin(a) | 9cadece2ff36ab06b2a3b11bf954aa45c4d3c874 | 3,606,172 |
def tf_fidelity(A, B):
"""Calculates the fidelity between tensors A and B.
Args:
A, B (tf.Tensor): List of tensors (hilbert_size, hilbert_size).
Returns:
float: Fidelity between A and B
"""
sqrtmA = tf.matrix_square_root(A)
temp = tf.matmul(sqrtmA, B)
temp2 = tf.matmul(temp... | 02cabadfde5fec73614d39c58fb77c49837b07eb | 3,606,173 |
def test(dir: str, endpoint: str):
"""Pipeline of validation the test using the files present in dir"""
dataset_id = load_dataset(dir, endpoint)
events = get_events_of_interest(dir, endpoint, dataset_id)
clean_server(endpoint, dataset_id)
return evaluate(events, dir) | dfd2942da1460136c5b6814009c787e2da45aa63 | 3,606,174 |
def 查找文件或目录(名称, 路径=None, 精确=False):
"""
# list(查找文件或目录('ping', exact=True))
# list(查找文件或目录('bin'))
# list(查找文件或目录('bin'))
# list(查找文件或目录('*cc*'))
# list(查找文件或目录('cmake*'))
"""
return ub.find_path(名称, 路径, 精确) | 5e14e7950e8107e280924538614243cb2735d11a | 3,606,175 |
def get_aliases(record):
"""
Get all aliases associated with this DID / GUID
"""
# error handling done in driver
aliases = blueprint.index_driver.get_aliases_for_did(record)
aliases_payload = {"aliases": [{"value": alias} for alias in aliases]}
return flask.jsonify(aliases_payload), 200 | e0643198a3b34afc69e758b651f35b7e46225dc3 | 3,606,176 |
def _create_internal_transaction_type(row) -> TransactionType:
"""Create a suitable transaction type according to the given row."""
return TransactionType.from_row(row, is_internal=True) | eb6453a9c5a2ccbcce157b66456132255a43c676 | 3,606,177 |
def handle_update_lessons(lesson_id):
"""Handle updating an existing lesson log"""
updateform = UpdateLesson()
form = NewLesson()
if updateform.validate_on_submit():
lesson_id = updateform.lesson_id.data
lesson_time = updateform.lesson_time.data
updateform.lesson_time.data = ''
... | 9e948c6d1cc9998b3ba9db5b4f6c971ad0c77f07 | 3,606,180 |
import json
def read_transcripts(src_bucket, guid):
"""Get the transcripts JSON file from the S3 bucket.
Args:
src_bucket (str): A string containing the S3 source bucket.
guid (str): A string containing the unique ID.
Returns:
spoken_text (str): A string with the text the custome... | 61430b62d78ccefad578bdc27004d55622988572 | 3,606,181 |
def preprocess():
"""
数据准备阶段
:return:
"""
# 1. 加载数据文件
x_text, y = load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file)
# 文本进行向量化
sentences, max_document_length = padding_sentences(x_text, '<PAD>')
x = np.array(embedding_sentences(sentences, FLAGS.word2vec_fname... | c39adc82e6ce1e3bd4d70638246ce77e1dac9134 | 3,606,182 |
def umfpack_dl_triplet_to_col(*args):
"""
umfpack_dl_triplet_to_col(SuiteSparse_long n_row, SuiteSparse_long n_col, SuiteSparse_long nz, SuiteSparse_long const [] Ti,
SuiteSparse_long const [] Tj, double const [] Tx, SuiteSparse_long [] Ap,
SuiteSparse_long [] Ai, double [] Ax, SuiteSparse_long ... | 7d1f910c581e23843020dce8621577aa9117a6b2 | 3,606,183 |
def two_sequences_in_parallel(sequence1, sequence2):
"""
Demonstrates iterating (looping) through TWO sequences in PARALLEL.
This particular example assumes that the two sequences are of equal
length and returns the number of items in sequence2 that are bigger
than their corresponding item in sequ... | c5dbce5f99d5c2efeee4048ec1451ea63f404fef | 3,606,184 |
def find_middle(arr: list) -> int:
"""
checks if the size of the list is odd, and will be sorted by the order_int_list()
function, and return the median number
Args:
arr (list): if the size of the list is even, will return an raise ValueError
Returns:
int: the median number of the ... | edab12bfcb9ff77249a51137fc5a8bb0778c5ac8 | 3,606,185 |
def GetHostTuple():
"""Returns compiler tuple for the host system."""
return portage.settings['CHOST'] | 8a741c6cae7b1e8faec774b5e7fa57f5a6258747 | 3,606,186 |
def str_to_tag(in_str: str) -> BaseTag:
"""Convert string representation to pydicom Tag
The string can be a keyword, or two numbers separated by a comma
"""
if in_str[0].isupper():
res = tag_for_keyword(in_str)
if res is None:
raise ValueError("Invalid element ID: %s" % in_s... | 54f58de4f3769b31f7419964f83ed1e35cefcd49 | 3,606,187 |
def plot_out_csv(data):
"""Uncomment everything you want to have on a plot
"""
columns = ['time',
'cwnd1',
'cwnd2',
'cwnd3',
'rtt1',
'rtt2',
'rtt3',
'bytes1',
'bytes2',
'byt... | 26ae9e475440fb651bbc759294ca4681606e337b | 3,606,188 |
def meta_seq_number(num):
"""
Creates a sequence number meta message.
Parameters
----------
num : byte
The sequence number
"""
msb = num & (0x7F << 7)
lsb = num & 0x7f
return [kMetaMsg, kSeqNumber, 2, msb, lsb] | f428479ffdcc6f552f36d03b317538230c80c3e1 | 3,606,189 |
import yaml
def get_all_comments():
"""
すべての項目名と項目名コメント取得する
Returns
-------
comments_list : dict
{項目名: [項目名コメント, ...], ...}
"""
with open(COMMENTS_YAML, "r") as f:
comments_yaml = yaml.safe_load(f)
tables = comments_yaml["comments"]
comments_list = {}
... | 44dcfb524bdeb4a32204c5ef6a2b33f449f3b747 | 3,606,190 |
def vime_semi(x_train, y_train, x_unlab, x_test, parameters,
p_m, K, beta, file_name):
"""Semi-supervied learning part in VIME.
Args:
- x_train, y_train: training dataset
- x_unlab: unlabeled dataset
- x_test: testing features
- parameters: network parameters (hidden_dim, batch_siz... | 9e57f4c99f8c2c2dc27d118207f6ff3efdad8490 | 3,606,191 |
def no_aug_generator(data, target, batch_size=32, gradient=False):
"""Custom image generator that manipulates image/target pairs to prevent
overfitting in the Convolutional Neural Network.
Parameters
----------
data : array
Input images.
target : array
Target images.
batch_si... | 984ce538d0a660fc34c20cca81d741ed2a38c34d | 3,606,192 |
def image_crop(src, x1, y1, x2, y2):
"""
Crop image from (x1, y1) to (x2, y2).
Parameters
----------
:param src: Input image in BGR format
:param x1: Initial coordinates for image cropping
:param y1: Initial coordinates for image cropping
:param x2: End coordinates of image cropping
... | 6ab70dc644d0d7054ea70fadcf7ec0ca381918d8 | 3,606,193 |
def gm_variance(W, A, s):
"""
Calculate the maximum variance for a single query in workload W.
Parameters
----------
s is the privacy cost
"""
m, n = A.shape
mI = np.eye(m)
# pseudoinverse of matrix A
pA = np.linalg.inv(A)
sigma = np.sqrt(1/s)
Var = W @ pA
BXB = Var ... | d1d1dc12ae402b2e6f307d717bf367e8df03ec95 | 3,606,194 |
from typing import NamedTuple
import pydantic
def settings_env_names(
settings_class: CommonSettings = CommonSettings,
) -> NamedTuple:
"""
returns the current environment variable names for the settings class and
value
"""
try:
_ = SettingsClassName.validate(settings_class)
except... | c84f0fd067728288c4253f546d391ae838bf9590 | 3,606,195 |
import array
def parse_siemens_b_matrix(value: bytes) -> np.ndarray:
"""
Parses the Siemens B matrix header field value.
Parameters
----------
value : bytes
Raw B matrix header field value
Returns
-------
np.ndarray
Parsed B matrix
"""
raw = list(array.array("... | 462df1b3dd78e37365a1d515e931dde47471c86a | 3,606,196 |
from typing import Union
import asyncio
def maybe_defer(inter: disnake.Interaction, *, delay: Union[float, int] = 2.0, **options) -> asyncio.Task:
"""Defer an interaction if it has not been responded to after ``delay`` seconds."""
loop = inter.bot.loop
if delay <= 0:
return loop.create_task(inter.... | e64d2fded53559de7344e77a3d42f421a4c481ba | 3,606,197 |
def block1(x,
filters,
bottleneck=False,
stride=1,
expansion=1,
normalization='bn',
activation='relu',
name=None):
"""A basic residual block.
Args:
x: input tensor.
filters: integer, filters of the bottleneck layer.
bottleneck... | ef3bb272fc66f1108f6ecf7f2408fd1418b76b0a | 3,606,198 |
def build_dense_decoder_model(
*, original_dim, latent_dim, dense_dims, activation="relu", verbose=False, **kwargs
):
"""
Builds dense decoder network for 1-d xrd data
Parameters
----------
original_dim: int
original dimensionality of xrd data (i.e. the length of any one sample)
lat... | cfb492765449d4021531f84443b0897dada0b89b | 3,606,199 |
from typing import Dict
def scatter_elements(node: NodeWrapper,
params: Dict[str, np.ndarray],
xmap: Dict[str, XLayer]):
""" ONNX ScatterElements to XLayer AnyOp conversion function """
logger.info("ONNX ScatterElements -> XLayer AnyOp")
assert len(node.get_outp... | a1a3dcc00520ed8a47223501c4f2e5458b4d241f | 3,606,200 |
def get_latest_jointarget_information():
"""
Retrieve recent JoinTarget Information from the database.
If recent information is not available in the db, use the WorldMap API and store
the new information in the db.
"""
# ---------------------------------
# (1) Is available JoinTarget info f... | 44d76ed571f81bdc0cf076631985d1a42c457db7 | 3,606,201 |
def folder_get_all_filenames_as_list(strFolderPath="",extension='all'):
"""
Get all the files of the given folder in a list.
Parameters:
strFolderPath (str) : Location of the folder.
extension (str) : extention of the file. by default all the files will be listed regarless of the exte... | f150a3f306219acebc5f8041fa55bc4dbc6b2e43 | 3,606,202 |
from vistrails.core.vistrail.pipeline import Pipeline
def get_workflow_diff(vt_pair_1, vt_pair_2):
"""get_workflow_diff( tuple(Vistrail, id), tuple(Vistrail, id) ) ->
Pipeline, Pipeline, [tuple(id, id)], [tuple(id, id)],
[id], [id], [tuple(id, id, list)]
Return a difference between t... | 4d7199e4caa015155b83102170f37811aab8f3e4 | 3,606,203 |
def parse_repo_and_name(image) -> (str, str):
""" parse image to (repo, name)
:param image: one of
- k8s.gcr.io/pause
- gcr.io/ml-pipeline/api-server
- quay.io/metallb/controller
- gcr.io/knative-releases/knative.dev/eventing/cmd/webhook
:return (repo, name): one of
... | 4599f42748a50a19c1c3561b6e7f976038572e3d | 3,606,207 |
def in_roi(experiment=None, ex_id=None, bounds=None):
"""
Generate a dataframe with True/False for each blob ID if the bounding
box centroid lies within the ROI.
Must provide either experiment or (ex_id and bounds). Optionally
experiment and bounds dataframe can be provided to save some load time.
... | f0accea9ba9542f0e0d26f23cbd3ce7d92339064 | 3,606,208 |
from pprint import pprint
def check():
"""Prints app status"""
print("Extensions.")
pprint(app.extensions)
print("Modules.")
pprint(app.blueprints)
print("App.")
return app | 5769a0a79252d91a6ab2c17e499becea88dfac73 | 3,606,209 |
def url(feature):
"""
Get the URL for the given Enesmbl feature.
"""
return URL.format(transcript=transcript(feature)) | 810ad621cdd47b646f4df0763c34a1044c45fbec | 3,606,210 |
def _datacopied(arr, original):
"""
Strict check for `arr` not sharing any data with `original`,
under the assumption that arr = asarray(original)
"""
if arr is original:
return False
if not isinstance(original, np.ndarray) and hasattr(original, '__array__'):
return False
ret... | f2194bb116fca4fea2e56bb0ae213095e2419d9b | 3,606,211 |
def parse_vendor_ramdisk_args(args, args_list):
"""Parses vendor ramdisk specific arguments.
Args:
args: An argparse.Namespace object. Parsed results are stored into this
object.
args_list: A list of argument strings to be parsed.
Returns:
A list argument strings that a... | 1d986d367336906e3970d32dd3739f2402155b68 | 3,606,212 |
def parseXyzFile(xyzFile):
""" Extract geometry from xyz file into a unit cell
Args:
xyzFile: (str) Path to the .xyz file
Returns
outCell: (plato_pylib UnitCell object) This contains the cartesian co-ordinates in outCell.cartCoords. Also contains a unit-cell, which will be cubic
"""
fileAsList = _loa... | c6e718c1bbe85c9021da4a1109f88e6081738302 | 3,606,213 |
def draw_memmap(mapstr, lc=None, ax=None, **kwargs):
"""Draw memmap str using matplotlib
mapstr is like:
0x7f2a76000000, 2211840, 1, 256;0x7f2a7621c000, 8200192, 0, 1024;
"""
if ax is None:
_, ax = plt.subplots()
ax.set_xlim([0, 17179869184])
ax.set_ylim([-0.2, 0.2])
... | b8ba20ef2d090896a2b7a9d14823fb4be41d8360 | 3,606,214 |
import functools
def get_move_matrix3_n_move_vector_from_df_by_crystalID(crystalID):
"""
Input crystalRC later because multi systems to handle.
Usage:
get_move_matrix3_n_move_vector_from_df_by_crystalID(34)(crystalRC)
"""
def _get_move_matrix3_n_move_vector_from_df_by_crystalID(crystalID, cry... | e564e511b02631757a2a174d82f0bb062d37a3da | 3,606,215 |
def get_all_round_info():
"""Returns a dictionary containing all the round information.
example: {"rounds": {"Round 1": {"start": start_date, "end": end_date,},},
"competition_start": start_date,
"competition_end": end_date}
"""
return settings.COMPETITION_ROUNDS | 3dbdc7bbffe038aba796071ad4b866f952548989 | 3,606,217 |
def find_sound_times(snd, sfreq, win_size):
"""Find groups of sound times by clustering in time.
Parameters
----------
snd : array (type bool)
A boolean array of sound timepoints, often
created with a cutoff
sfreq : int
The sampling frequency of snd
win_size : float
... | 16fa2e37bf307dfae7acdc435abe96b6ce8909b3 | 3,606,218 |
def get_topics_per_page(user):
"""
Gets the number of Topics which should be displayed per page, based
on the given User.
"""
if user.is_authenticated():
forum_profile = ForumProfile.objects.get_for_user(user)
return forum_profile.topics_per_page or \
app_settings.DEFA... | 053f9e7a31325e95a10e6b3230b60731dac0f29a | 3,606,219 |
def get_factors(n):
"""
Return a list of integer factors for a number.
Parameters
----------
n: int or float
Number to factor
Returns
-------
sorted: list
A list of sorted factors.
"""
factors = []
sqrt_n = int(round(np.sqrt(n) + 0.5))
i = 1
while i... | 2c1eee1b15c7f3f474ceb46a198256c162ad0236 | 3,606,221 |
def add(ui, repo, *pats, **opts):
"""add the specified files on the next commit
Schedule files to be version controlled and added to the
repository.
The files will be added to the repository at the next commit. To
undo an add before that, see :hg:`forget`.
If no names are given, add all files... | ad992ef49ae5836573482b704f1484010f16d25f | 3,606,222 |
from typing import Optional
def deepest_depth(tn: Optional[TreeNode], value: int) -> Optional[int]:
"""Returns the depth of the deepest node of a certain value."""
if tn is None:
return None
elif tn.value != value:
return opt_max(
opt_increment(deepest_depth(tn.left, value)),
... | aa09d7660c8d23e9f036dc051ff21563bafb9cdc | 3,606,223 |
import re
def get_doc(src) :
"""get comments from Python source code
Parameter
--------------
src@str - the source code
"""
pat = re.compile(r'((?:def|class)\s+[^\n]*\s*)"""(.*?)"""',re.MULTILINE|re.DOTALL)
return [gs for gs in pat.findall(src)] | bb9716a9f7b3c99d5ea3e468b7f69f893773feda | 3,606,224 |
def get_creation_operator(size):
"""
Construct the creation operator with the given matrix size.
Arguments:
size :: int - This is the size to truncate the operator at. This
value should be g.t.e. 1.
Returns:
creation_operator :: ndarray (size, size)
- The creation operator at l... | 7e8dd08d1753dbab6a8662e6c4a86a30dc314326 | 3,606,225 |
import numpy as np
import lib.operations as ops
import lib.test as test
def build_spectrum_limb_resolved(wl,fx_list,mu_list,wlmin,wlmax,x,y,vel_grid):
"""WRITE THIS.
Parameters
----------
"""
#I copy paste as much as possible from above. The roles of wlc and wlc_wide have
#changed bec... | 7d50600b7f61569c5eb8ff7f56257bf3c67341f3 | 3,606,226 |
def _GetBinaryName(client):
"""Gets the GRR binary name on the client."""
client_data = client.Get().data
return client_data.agent_info.client_binary_name | c363a4a42e81184ce2cb74bfdc9c2fd01a746cb1 | 3,606,227 |
def _searchsorted(a, v):
"""Returns where `v` can be inserted so that `a` remains sorted."""
def cond(state):
low_idx, high_idx = state
return low_idx < high_idx
def body(state):
low_idx, high_idx = state
mid_idx = (low_idx + high_idx) // 2
mid_v = a[mid_idx]
low_idx = np.where(v > mid_v... | f2682f732a5d149028229daea81edd59045917b6 | 3,606,228 |
def map_get_by_value_range(bin_name, value_start, value_end, return_type, inverted=False):
"""Creates a map_get_by_value_range operation to be used with operate or operate_ordered
The operation returns items, with values between value_start(inclusive) and
value_end(exclusive) from the map
Args:
... | e3dec52e5c591b307e38d2e882f586fbb6291f43 | 3,606,229 |
def prepare_writer_info(slack_team_id, slack_user_id, jama_base_url, use_at_user):
"""
Using the requester's Slack email to find the Jama information of the requester. Then prepare
a piece of html code that we can post on Jama to reflect the requester.
Args:
slack_team_id (string): Slack team id... | 9fa6bdb87c73d9b5828afb428ecaec402a6a8b90 | 3,606,231 |
from pydantic import BaseModel # noqa: E0611
def field_getter(subject: object, field_name: str, default: any = None):
"""
Gets a field value from a dict or object
"""
value = None
if type(subject) is dict and field_name in subject:
value = subject.get(field_name, default)
if ha... | ebe9c4255fc063d95c0309b70e84b109b5b5d60c | 3,606,232 |
import statistics
def get_inhouse_results(date: str=get_inhouse_dates()[-1]) -> tuple:
""" Returns a tuple of a list of tuples sorted by average and a list of scrambles. """
return (sorted(list(map(\
lambda x: [statistics.ao(list(map(parse_time, [t if t != "DNF" else "" for t in x.split(NAME_DELIM)[1].spl... | 8b79d54b845fd043c1ad99361a4007c1bcc1e24e | 3,606,233 |
def askForCommand(command):
"""Asks the user for a command to send to the gripper."""
currentCommand = 'Simple OnRobot RG Controller\n-----\nCurrent command:'
currentCommand += ' rGFR = ' + str(command.rGFR)
currentCommand += ', rGWD = ' + str(command.rGWD)
currentCommand += ', rCTR = ' + str(comma... | 8f678c084b10dbb75d75c47b65e76c7c2a5a41d7 | 3,606,235 |
def fill_with_gauss(df, w=12):
"""
Fill missing values in a time series data using gaussian
"""
return df.fillna(
df.rolling(window=w, win_type="gaussian", center=True, min_periods=1).mean(
std=2
)
) | fdfdedaf7968f617ff98df586b89c30053a6c886 | 3,606,236 |
def construct_azel_target(az, el):
"""Convenience function to create unnamed stationary target (*azel* body type).
The input parameters will also accept :class:`ephem.Angle` objects, as these
are floats in radians internally.
Parameters
----------
az, el : string or float
Azimuth / ele... | 1714ca59c22dd8db8dc3c99c84c5c2c9d5d79eda | 3,606,237 |
from typing import List
from typing import Optional
import torch
def conv_transpose(x: Tensor, kernel: Tensor, stride: List[int],
opad: List[int]) -> Tensor:
"""ND transposed convolution
x : (B, Ci, *inspatial) tensor
kernel : (Ci, Co, *kernel_size) tensor
stride : List{dim}[int]
... | 4ecc3769b8f3979120e673825676c9cc43cd62fb | 3,606,238 |
def gdisconnect():
""" Sign out from Google account. """
url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % \
session['access_token']
h = httplib2.Http()
result = h.request(url, 'GET')[0]
if result['status'] == '200':
return 'Successfully disconnected.'
else:
... | 132c01e33becfb7066cbb5f798f5720722574936 | 3,606,239 |
def opt(args=None, version=None, out=None, err=None):
"""runs opt"""
return mx.run([findLLVMProgram('opt', version)] + args, out=out, err=err) | 47f745c3c3c5c2686236ebcabd21a1003af68f0f | 3,606,240 |
from typing import Set
from typing import Tuple
def _calculate_mass_center(electrode: Set[Tuple[int, int, int]]):
"""Calculate the mass center of the electrode"""
return np.array(list(electrode)).mean(axis=0) | 32b4997e4a3de2be8517a4fefa75f7181f4589bf | 3,606,241 |
import functools
def decfunc(func):
"""" Decorator function to test _create_argument_value_pairs function """
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""
Wrapper function that creates the argument dictionary and returns a
ret_func, which in turn just returns the argume... | dee0ce80bf35fbac6e1a92fcaead653afd376c70 | 3,606,242 |
import types
def _construct_many_to_many_relationship_property_artifacts():
"""Construct many-to-many relationship artifacts."""
return schemas_artifacts.types.ManyToManyRelationshipPropertyArtifacts(
type=types.PropertyType.RELATIONSHIP,
schema={}, # type: ignore
sub_type=types.Relat... | b6058a43fdef8979e30e464ea03260b8722df737 | 3,606,243 |
def directivity(guide_height, horn_width, horn_effective_length, frequency):
"""
Calculate the directivity for the H-plane horn.
:param guide_height: The height of the waveguide feed (m).
:param horn_width: The width of the horn (m).
:param horn_effective_length: The effective length of the horn (m)... | 5c02e4f8869bc91b36e4a24f8d00fa9bb3345f57 | 3,606,244 |
from typing import Iterable
from typing import Tuple
import numpy
def _create_contiguity(
p: DatasetAssembler,
product_list: Iterable[str],
resolution_yx: Tuple[float, float],
timedelta_product: str = "nbar",
timedelta_data: numpy.ndarray = None,
):
"""
Create the contiguity (all pixels va... | faeda18c85579e6b14fa296bc09da5aba6e6bd3a | 3,606,246 |
def oneway_chains(funcs, inits, times):
"""
Return result of chain.
funcs is a sequence of 2-tuple of functions.
i-th tuple's func[0] have 2*(i+1) arguments, and func[1] 2*(i+1)-1.
The funcs[1] is another function satisfying:
funcs[i+1][1](a_{i+1}, *p) == funcs[i+1][0](a_{i+1}, a_{i+1}, *p),
... | c944fe69298dc360a58148a3b22e7b500ef8c8e3 | 3,606,247 |
def swap(heights_list, index01, index02):
"""swap two positions in a list at given indexes
Args:
heights_list (list): iterable in which swapping occurs
index01 (int): index of first element
index02 (int): index of second element
Returns:
list: list with element positions s... | f7add4a06a79837766b5840840d17c3247b0bcae | 3,606,248 |
import requests
import logging
import json
def get_env_data(env_settings):
"""Fetches the environment data from the Arduino and Wio Terminal.
Returns the parsed JSON object or an empty dictionary on failure."""
# Read Arduino
try:
resp = requests.get(env_settings['arduino_url'])
except Con... | bbd7023a00e0f8cbe9b6186707ca0f551de660fc | 3,606,249 |
def indexed_moving_average (s, n, central = False) :
"""Generator for indexed moving average of `n` data points over sequence `s`.
>>> def show (ma_s, fmt = "(%d, %.1f)") :
... print ("[" + ", ".join (fmt % (i, v) for i, v in ma_s) + "]")
>>> show (indexed_moving_average (range (10), 2))
[(1, ... | 7ad417dc6e1cc79551dd402513ed2775b7cce40d | 3,606,251 |
import csv
def ReadData(filename=FILENAME):
"""Reads a CSV file of data from HERI's CIRP survey.
Args:
filename: string filename
Returns:
list of (score, number) pairs
"""
fp = open(filename)
reader = csv.reader(fp)
res = []
for t in reader:
try:
year... | 854a6af3ff635cf96540c9f6e995a5cfbf4e9f89 | 3,606,253 |
def calibrate_seq(cigar_seq, sequence, md_seq, ref_positions):
"""
making cigar seq and seq as same length
with Deletions as '-'
"""
new_sequence = ''
new_pos = []
new_cigar = ''
new_md = ''
seq = iter(sequence)
pos = iter(ref_positions)
md = iter(md_seq)
current_positio... | b149587d8f61a4e7c82d4bde94e62512a5682346 | 3,606,254 |
def annotate_pfam(alignment):
""" Loop over sequences and fill in annotations using Pfam. """
for record in alignment:
if not record.id:
header = get_annotations_no_pfamid(
str(record.seq).replace("-", "")
)
record.id = header
else:
... | faf10185d27cb5bdcbf2c2873e131a9375604839 | 3,606,255 |
import struct
def read(fp: FileLike, format_str: str):
"""read data from `fp` specified by `format_str`"""
num_bytes = struct.calcsize(format_str)
byts = fp.read(num_bytes)
ans = struct.unpack(format_str, byts)
return ans if len(ans) > 1 else ans[0] | 74ee010aa609ad4d1b1111bd9b3284299e747cd3 | 3,606,256 |
import pkg_resources
def bcipy_version() -> str:
"""BciPy Version.
Gets the current bcipy version. If the current instance of bcipy is a
git repository, appends the current abbreviated sha hash.
"""
version = pkg_resources.get_distribution('bcipy').version
sha_hash = git_hash()
return f'... | 77960a393bffc9152c6eb3b41c021ceec815dbef | 3,606,257 |
def compute_separators_morph(binary, scale, max_blackseps=0, widen_blackseps=10):
"""Finds vertical black lines corresponding to column separators.
"""
d0 = int(max(5, scale/4))
d1 = int(max(5, scale))+widen_blackseps
thick = morph.r_dilation(binary, (d0, d1))
vert = morph.rb_opening(thick, (10*... | 16427ad8b5921f8abc9c8035b4a2c6d67f46fc08 | 3,606,258 |
def create_first_n_1_bits_mask(n, k):
""" Return a binary mask of first n bits of 1, k bits of 0s"""
if n < 0 or k < 0:
raise ValueError("n and k cannot be negative number")
if n == 0:
return 0
mask = (2 << n) - 1
return mask << k | 5a9b637a8973f004da2330c8ebb06ea63fd542c3 | 3,606,259 |
def prepare_data(seqs_x, chardict, n_chars=1000):
"""
Prepare the data for training - add masks and remove infrequent characters
"""
seqsX = []
for cc in seqs_x:
seqsX.append(
[
chardict[c] if c in chardict and chardict[c] <= n_chars else 0
for c i... | 6d85b799ca74ab3874b50280edbce2d13de1bf6d | 3,606,261 |
def chexdump(packet, dump=False, to_list=False):
"""
Return a chexdump base on packet
:param packet: String or Scapy object
:param dump: True if you want to dump instead of print
:param to_list: True if you want a list of hex instead of a string
:return: None or Str or List
"""
def _add... | 3a72503010be829feb854fdd6a6fb63b2abb5207 | 3,606,262 |
from typing import List
from typing import Tuple
def entity_confusion_matrix(
utterances: List[str],
entity_predictions: List[List[dict]],
y_trues: List[List[str]],
) -> Tuple[np.ndarray, List[str]]:
"""Confusion Matrix for Evaluating Entity Predictions
Preprocess a list of raw en... | 25173048f4478d7d71b33105e2c06cd75ccf5649 | 3,606,263 |
import numba
def read_boolean(position, block):
"""Read a single byte whose value is either 0 (false) or 1 (true).
Returns:
Tuple[int, numba.uint8]:
(new position, boolean)
"""
# We store bool as a bit array. Return 0xff so that we can bitwise AND with
# the mask that says wh... | 243f3f93e94310e57beb9551f7e609f407d0aedb | 3,606,264 |
def new_candidate():
"""Create a new candiate."""
form = NewCandidateForm()
if form.validate_on_submit():
demographic = Demographic(
race=form.demographic.race.data,
gender=form.demographic.gender.data,
age=form.demographic.age.data,
sexual_orientation... | 290b1c5978a892f6656f89f6a158b9369a0509fb | 3,606,265 |
from typing import Union
import copy
def merge_config(conf: Config, merge: Union[dict, Config]) -> Config:
"""
Merge config object with a dictionary, or a Config object,
same keys in the ``conf`` will be overwritten by keys
in ``merge``.
"""
new_conf = copy.deepcopy(conf)
if isinstance(mer... | 416f9e74707bdb897bcc79813b1bd8ddf3f9da46 | 3,606,266 |
def parse_args():
"""
Helper function parsing the command line options
@retval ArgumentParser
"""
parser = ArgumentParser(description="This is a script for launching PyTorch training and inference on Intel Xeon CPU "
"with optimal configurations. Now, single i... | 3c0444f18e9319d06a2610a4660d7c2a626023dc | 3,606,268 |
import re
def clean_str(string):
"""
Strip and replace some special characters.
"""
msg = str(string)
msg = msg.replace("\n", " ")
msg = re.sub(r"\s+", r" ", msg)
msg = re.sub(r"^\s", r"", msg)
msg = re.sub(r"\s$", r"", msg)
return msg | 50132d2c56498f4590fcba7837deb791500f3110 | 3,606,269 |
def watchlist(request, response_format='html'):
"""Displays all objects a User is subscribed to"""
profile = request.user.profile
watchlist = profile.subscriptions.all()
context = {'profile': profile, 'watchlist': watchlist}
return render_to_response('account/watchlist', context,
... | f9855bd4fe9d07b04049f3fb30933a603c9ddf43 | 3,606,270 |
def connect(database_name="tournament"):
"""Connect to the PostgreSQL database. Returns a database connection."""
try:
db = psycopg2.connect("dbname={}".format(database_name))
c = db.cursor()
return db, c
except TypeError:
print("Couldn't connect to DB") | 6d87933ce18d30cb4521a560c7a8fe9ddf7733e4 | 3,606,272 |
def filter_1031(osurl, splitos, device):
"""
Modify URLs to reflect changes in 10.3.1.
:param osurl: OS URL to modify.
:type osurl: str
:param splitos: OS version, split and cast to int: [10, 3, 2, 2876]
:type splitos: list(int)
:param device: Device to use.
:type device: int
"""
... | 472c8e852254806c18f0515c4647a57d645786ce | 3,606,273 |
def prepare_plane_to_curved_spherical_arbitrary(k, rs_support, num_pointss, z, xo, yo, roc_xo, roc_yo, rs_center=(0, 0),
qs_center=(0, 0), ro_centers=None, kz_mode='local_xy'):
"""Prepare spherical wavefront propagator from uniformly sampled plane to arbitrarily sampl... | 947a9ac6a2793c7a62660d5d45e81cd25b9758e8 | 3,606,274 |
def char_to_ix(chars):
"""
Make a dictionary that maps a character to an index
Arguments:
chars -- list of character set
Returns:
dictionary that maps a character to an index
"""
return {ch: i for i, ch in enumerate(chars)} | 8bfc5b99c7f5aef6d88276fe4b3ad005ce9a017e | 3,606,275 |
def define_G(input_nc, output_nc, ngf, netG, norm='batch', use_dropout=False,
init_type='normal', init_gain=0.02, gpu_ids=[]):
"""load a generator
Parameters:
input_nc (int) -- the number of channels in input images
output_nc (int) -- the number of channels in output images
... | 1ada180a82c56c42b21d434f1ec73c90a6a50a8b | 3,606,276 |
def get_genomiccoord2num_targeted(genes,
gene2transcript,
transcriptcodon2trinucleotides,
source_maf_id2target_intervals,
source_maf_id2center,
source... | a7536d89bf3acdde5fdc911f917f320c751ac308 | 3,606,277 |
def bool_tag(name, value):
"""Create a DMAP tag with boolean data."""
return name.encode('utf-8') + \
b'\x00\x00\x00\x01' + \
(b'\x01' if value else b'\x00') | dc914d262a20eed0732e477f75641daa4811fd9f | 3,606,278 |
def read_client_realtime(file_name):
"""读取实时探测主机信息"""
cf = ConfigParser.ConfigParser()
cf.read(file_name)
ip = cf.get("http_client_realtime", "ip")
port = cf.getint("http_client_realtime","port")
return ip, port | b9c69bb65e3ae3f2eac438ed9022ee276b370314 | 3,606,280 |
def _concat(*lists):
"""Concatenates the items in `lists`, ignoring `None` arguments."""
concatenated = []
for list in lists:
if list:
concatenated += list
return concatenated | a1eea1c074fe1eee1ca454899bf9dec2719a333e | 3,606,281 |
def rbf(x, y, sigma=100):
"""
Radial basis functions kernel
"""
return np.exp(-(np.sum((x-y)**2))/(sigma**2)) | 7b7c3de9d0a567de777ad240a21f986c2181b9a8 | 3,606,282 |
def fit_beta_prior(data):
"""
Fit the parameters of a beta prior given probability data.
Arguments:
data (numpy array):
Values ranging 0 to 1, representing the population level data.
Returns:
List of beta distribution parameters
"""
alpha, beta, _, _ = scs.beta.fit(d... | 27fde4b53cca63ee50f56a0e4ea5b07c3694f744 | 3,606,283 |
def _migrate1to2(previous: SettingsMap) -> SettingsMap:
"""
Migration to version 2 of the feature flags file. Adds the
disableLogAggregation config element.
"""
newmap = {k: v for k, v in previous.items()}
newmap["disableLogAggregation"] = None
return newmap | 690c6407c9ac7ec326f59c7d0c5977a0a17bc3ba | 3,606,284 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.