content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def parse_user_next_stable(user):
"""
Parse the specified user-defined string containing the next stable version
numbers and returns the discretized matches in a dictionary.
"""
try:
data = re.match(user_version_matcher, user).groupdict()
if len(data) < 3:
rai... | 3d5de92fdb119a85bc6b5e87a8399cc07e6c9ee8 | 14,772 |
import tqdm
def interp_ADCP_2D(
sadcp,
mask,
depth,
lon,
lat,
time,
time_win=360.0,
rmax=15.0,
vmax=2.0,
range_min=4.0,
):
"""
This is essentially a loop over the interp_ADCP function with some additional NaN handling.
Assume data is of the form D[i, j] where each ... | ec092d203ef1cfee176bdf9ae05021fd876d444a | 14,773 |
def extract_p(path, dict_obj, default):
"""
try to extract dict value in key path, if key error provide default
:param path: the nested dict key path, separated by '.'
(therefore no dots in key names allowed)
:param dict_obj: the dictinary object from which to extract
:param default: a default r... | 1a563212e229e67751584885c5db5ac19157c37f | 14,774 |
def default_lscolors(env):
"""Gets a default instanse of LsColors"""
inherited_lscolors = os_environ.get("LS_COLORS", None)
if inherited_lscolors is None:
lsc = LsColors.fromdircolors()
else:
lsc = LsColors.fromstring(inherited_lscolors)
# have to place this in the env, so it is appl... | 0ad54d1220308a51194a464a2591be6edcc8d0ff | 14,775 |
import logging
def get_indices_by_sent(start, end, offsets, tokens):
"""
Get sentence index for textbounds
"""
# iterate over sentences
sent_start = None
sent_end = None
token_start = None
token_end = None
for i, sent in enumerate(offsets):
for j, (char_start, char_end) ... | 7ce90b69c63b18ee1c025970f5a645f5f4095d3b | 14,776 |
def get_server_object_by_id(nova, server_id):
"""
Returns a server with a given id
:param nova: the Nova client
:param server_id: the server's id
:return: an SNAPS-OO VmInst object or None if not found
"""
server = __get_latest_server_os_object_by_id(nova, server_id)
return __map_os_serv... | 384a5481c41937dfb7fcfdfdcc14bf0123db38a7 | 14,777 |
from xml.dom.minidom import parseString
import attr
def parse_string(xml):
""" Returns a slash-formatted string from the given XML representation.
The return value is a TokenString (see mbsp.py).
"""
string = ""
dom = parseString(xml)
# Traverse all the <sentence> elements in the XML.
... | e3ccf32bcc148b2c6b9b44259d881f336720fde5 | 14,782 |
def join_ad_domain_by_taking_over_existing_computer_using_session(
ad_session: ADSession, computer_name=None, computer_password=None, old_computer_password=None,
computer_key_file_path=DEFAULT_KRB5_KEYTAB_FILE_LOCATION) -> ManagedADComputer:
""" A fairly simple 'join a domain' function using pre-cre... | a9fea1126fd775c85cf9a354044315eef03a4ffb | 14,783 |
def peak_sound_pressure(pressure, axis=-1):
"""
Peak sound pressure :math:`p_{peak}` is the greatest absolute sound pressure during a certain time interval.
:param pressure: Instantaneous sound pressure :math:`p`.
:param axis: Axis.
.. math:: p_{peak} = \\mathrm{max}(|p|)
"""
return np.ab... | e3beb4d67dc414fa7aabdc7a9c4a06a5ddb371ab | 14,784 |
def field_filter_query(field, values):
"""Need to define work-around for full-text fields."""
values = ensure_list(values)
if not len(values):
return {'match_all': {}}
if field in ['_id', 'id']:
return {'ids': {'values': values}}
if len(values) == 1:
if field in ['names', 'ad... | 54d3b394e8dc38b2a0ead3b9d5a81da9f5f6915a | 14,785 |
import logging
def compute_investigation_stats(inv, exact=True, conf=0.95, correct=True):
"""
Compute all statistics for all protected features of an investigation
Parameters
----------
inv :
the investigation
exact :
whether exact tests should be used
conf :
ove... | 08bf8ab5c4e985c33fdb0bd0d9dfc1dc949f4d83 | 14,786 |
def group_bars(note_list):
"""
Returns a list of bars, where each bar is a list of notes. The
start and end times of each note are rescaled to units of bars, and
expressed relative to the beginning of the current bar.
Parameters
----------
note_list : list of tuples
List of not... | 3b12a7c7e2395caa3648abf152915ece4b325599 | 14,787 |
def get_vmexpire_id_from_ref(vmexpire_ref):
"""Parse a container reference and return the container ID
The container ID is the right-most element of the URL
:param container_ref: HTTP reference of container
:return: a string containing the ID of the container
"""
vmexpire_id = vmexpire_ref.rspl... | e90c34c8489d91fb582a4bf15f874bcb2feaea82 | 14,788 |
def create_A_and_B_state_ligand(line, A_B_state='vdwq_q'):
"""Create A and B state topology for a ligand.
Parameters
----------
line : str
'Atom line': with atomtype, mass, charge,...
A_B_state : str
Interactions in the A state and in the B state.
vdwq_vdwq: ligand fully inte... | 3ac16da60de68013b20ea3f1a6ce3173cd4871a1 | 14,789 |
def clean_params(estimator, n_jobs=None):
"""clean unwanted hyperparameter settings
If n_jobs is not None, set it into the estimator, if applicable
Return
------
Cleaned estimator object
"""
ALLOWED_CALLBACKS = (
"EarlyStopping",
"TerminateOnNaN",
"ReduceLROnPlateau... | da639b03ea7dec534130105571c1623128e99143 | 14,790 |
def getValidOauth2TxtCredentials(force_refresh=False, api=None):
"""Gets OAuth2 credentials which are guaranteed to be fresh and valid."""
try:
credentials = auth.get_admin_credentials(api)
except gam.auth.oauth.InvalidCredentialsFileError:
doRequestOAuth() # Make a new request which should... | ff29fe312fe6ca875e53c56482033ca5ccceb71c | 14,791 |
import itertools
def get_combinations_sar(products, aoi):
"""Get a dataframe with all possible combinations of products and calculate
their coverage of the AOI and the temporal distance between the products.
Parameters
----------
products : dataframe
Search results with product identifier... | 045fcf59e9dae17a17d77cb945d2fe63af01e7ae | 14,792 |
import re
def sample(s, n):
"""Show a sample of string s centered at position n"""
start = max(n - 8, 0)
finish = min(n + 24, len(s))
return re.escape(s[start:finish]) | 565f69224269ed7f5faa538d40ce277714144577 | 14,793 |
def getNeededLibraries(binary_filepath):
"""
Get all libraries given binary depends on.
"""
if False:
return getNeededLibrariesLDD(binary_filepath)
else:
return getNeededLibrariesOBJDUMP(binary_filepath) | 40fcb08fac7877f97cb9fa9f6f198e58c64fe492 | 14,794 |
from typing import List
def load_transformer(input_paths:List[str], input_type:str=None) -> Transformer:
"""
Creates a transformer for the appropriate file type and loads the data into
it from file.
"""
if input_type is None:
input_types = [get_type(i) for i in input_paths]
for t i... | 55eab62cdf5293ad03441fc91663383adcf12da7 | 14,795 |
from ocs_ci.ocs.platform_nodes import AWSNodes
def delete_and_create_osd_node_aws_upi(osd_node_name):
"""
Unschedule, drain and delete osd node, and creating a new osd node.
At the end of the function there should be the same number of osd nodes as
it was in the beginning, and also ceph health should ... | c376b8b499a9897723962e5af30984eb4d9f06fa | 14,796 |
import math
def encode_integer_compact(value: int) -> bytes:
"""Encode an integer with signed VLQ encoding.
:param int value: The value to encode.
:return: The encoded integer.
:rtype: bytes
"""
if value == 0:
return b"\0"
if value < 0:
sign_bit = 0x40
value = -v... | daf9ed4a794754a3cd402e8cc4c3e614857941fe | 14,797 |
def kin_phos_query(kin_accession):
"""
Query to pull related phosphosites using kinase accession
:param kin_accession: string kinase accession
:return: Flask_Table Phosphosite_results object
"""
session = create_sqlsession()
q = session.query(Kinase).filter_by(kin_accession= kin_accession)
... | 94f5f7d987dface90ff5d061525d2277173ed271 | 14,798 |
def max_surplus(redemptions, costs, traders):
"""
Calculates the maximum possible surplus
"""
surplus = 0
transactions = 0.5 * traders
for redemption, cost in zip(redemptions, costs):
if redemption >= cost:
surplus += ((redemption - cost) * transactions)
return surplus | 6dd452de1b8726c475c9b95d8c24a2f57fe71516 | 14,799 |
import string
def generate_create_account_key():
"""
Generates a random account creation key. Implementation is very similar to
generate_reset_key().
"""
chars = string.ascii_lowercase + string.digits
return misc_utils.generate_random_string(constants.CREATE_ACCOUNT_KEY_LENGTH,
chars=chars) | e52405a325b787b9473da5530c909bfdcff0d9b4 | 14,800 |
import re
def parse_dblife(file):
"""Parse an DBLife file, returning a tuple:
positions: list of (x,y) co-ordinates
comments: all comments in file, as a list of strings, one per line.
"""
lines = file.split("\n")
comments = []
positions = []
x = 0
y = 0
dblife_patte... | b2d54240280b657c82d8a70da9e9f0ce47a92c7a | 14,801 |
from typing import Any
from typing import Callable
def db_handle_error(logger: Logger, default_return_val: Any) \
-> Any:
"""Handle operational database errors via decorator."""
def decorator(func: Callable) -> Any:
def wrapper(*args, **kwargs): # type: ignore
# Bypass attempt to ... | 1a807bc7a49abc9b50970145c520e823103f3607 | 14,802 |
from typing import Iterable
from typing import Optional
from typing import List
from pathlib import Path
def climb_directory_tree(starting_path: PathOrStr, file_patterns: Iterable[str]) -> Optional[List[Path]]:
"""Climb the directory tree looking for file patterns."""
current_dir: Path = Path(starting_path).a... | 80f036da4cf5564a2b96359ea67db19602333420 | 14,803 |
def serve_file(request, token, require_requester=True, verify_requester=True, signer=None):
"""Basic view to serve a file.
Uses ``evaluate_request`` under the hood. Please refer to that function to view information about exceptions.
:param request: the file request
:type request: bgfiles.models.FileRe... | 98bfae971e141130e94932afb8fdee2a285f2a5a | 14,804 |
def d2_rho_heterodyne(t, rho_vec, A, args):
"""
Need to cythonize, docstrings
"""
M = A[0] + A[3]
e1 = cy_expect_rho_vec(M, rho_vec, 0)
d1 = spmv(M, rho_vec) - e1 * rho_vec
M = A[0] - A[3]
e1 = cy_expect_rho_vec(M, rho_vec, 0)
d2 = spmv(M, rho_vec) - e1 * rho_vec
return [1.0 / np... | 6628c1a7299ee7842a839fd63b00857808bcd3ec | 14,805 |
from pathlib import Path
def get_venv():
"""Return virtual environment path or throw an error if not found"""
env = environ.get("VIRTUAL_ENV", None)
if env:
return Path(env)
else:
raise EnvironmentError("No virtual environment found.") | 44dd4660198a8f5538cbe91ffe52468adc8ee0e8 | 14,806 |
def load_user(user_id):
"""Login manager load user method."""
return User.query.get(int(user_id)) | 40d5f35aa88163a6ab69c1da7bad6634225f2cf3 | 14,808 |
def test_interpolate_energy_dispersion():
"""Test of interpolation of energy dispersion matrix using a simple dummy model."""
x = [0.9, 1.1]
y = [8., 11.5]
n_grid = len(x) * len(y)
n_offset = 1
n_en = 30
n_mig = 20
clip_level = 1.e-3
# define simple dummy bias and resolution model u... | 73c60f2b01d20b6e399dfb15da2c3c4b8622a90c | 14,809 |
def _transpose_list_array(x):
"""Transposes a list matrix
"""
n_dims = len(x)
assert n_dims > 0
n_samples = len(x[0])
rows = [None] * n_samples
for i in range(n_samples):
r = [None] * n_dims
for j in range(n_dims):
r[j] = x[j][i]
rows[i] = r
return ro... | 8815526c6485475aeaf791c2b1350449730b94f6 | 14,810 |
def load_businessgroup(request):
""" Business Group Dependent/Chained Dropdown List """
business_type_id = request.GET.get('business_type')
business_group_list = BusinessGroup.objects.filter(
business_type_id=business_type_id).order_by('name')
context = {'business_group_list': business_group_li... | 8801fbd6ae99ed939721d94bd7f3539b5b050d0a | 14,811 |
def seed_normalization(train_X, train_Y, test_X, testY, nor_method=0, merge=0, column=0):
"""
0 for minmax 1 for standard, 2 for nothing
:param nor_method:
:param merge:是否训练集测试集一起归一化
:return:
"""
# imp_mean = SimpleImputer(missing_values=np.nan, strategy="mean")
imp_mean = KNNImputer(n_n... | bae1181b6cca53444f09a69abaa3958e8500f71c | 14,812 |
import pathlib
def combine_matrix_runs(path, runs, pacc_file):
"""Combine a set of transition matrix files.
Args:
path: The base path containing the data to combine.
runs: The list of runs to combine.
pacc_file: The name of the file to combine.
Returns:
A TransitionMatrix... | dee47a3f4bfb6229a5c6aec531a0b50df5275a0b | 14,813 |
import json
def get_pkg_descr(package, version=None, last_modified=None):
"""
Get package description from registry
"""
json_data = fetch_page('http://registry.npmjs.org/%s' % package, last_modified=last_modified)
if json_data is None: # NB: empty string is not None but will fail the check
... | 9be485ee3e63f25da995b6d454a8dd15de4b7a66 | 14,814 |
def has_pattern(str_or_strlist):
"""When passed a string, equivalent to calling looks_like_pattern.
When passed a string list, returns True if any one of the strings looks like a pattern,
False otherwise."""
strlist = [str_or_strlist] if isinstance(str_or_strlist, str) else str_or_strlist
retu... | 902069f01a59b5e42c25635271dc27375732437b | 14,815 |
def update_hidden_area(*args):
"""update_hidden_area(hidden_area_t ha) -> bool"""
return _idaapi.update_hidden_area(*args) | 19739a98283203ece9f29d4fe073633318c0c2a4 | 14,816 |
def after_update_forecast_datasets(msg, config, checklist):
"""Calculate the list of workers to launch after the
update_forecast_datasets worker ends.
:arg msg: Nowcast system message.
:type msg: :py:class:`nemo_nowcast.message.Message`
:arg config: :py:class:`dict`-like object that holds the nowc... | 3ef9a6d37f871900e96f6227fea2f7678843acca | 14,817 |
def index(request):
"""Homepage for this app.
"""
with open('index.html') as fp:
return HttpResponse(fp.read()) | b9ce38f59443e38e5d27ff7f153a834e1c11b429 | 14,818 |
def SECH(*args) -> Function:
"""
The SECH function returns the hyperbolic secant of an angle.
Learn more: https//support.google.com/docs/answer/9116560
"""
return Function("SECH", args) | 594921375aaa7d4fb409e1a4792a6752f81b6bb2 | 14,819 |
def read_ATAC_10x(matrix, cell_names='', var_names='', path_file=''):
"""
Load sparse matrix (including matrices corresponding to 10x data) as AnnData objects.
read the mtx file, tsv file coresponding to cell_names and the bed file containing the variable names
Parameters
----------
matrix: spa... | 9f2073d7582f93db2f714f401fc0fb5e0762a2fc | 14,820 |
def get_html_subsection(name):
"""
Return a subsection as HTML, with the given name
:param name: subsection name
:type name: str
:rtype: str
"""
return "<h2>{}</h2>".format(name) | 2e0f37a7bb9815eda24eba210d8518e64595b9b7 | 14,821 |
def compute_norms(items):
"""
Compute the norms of the item vectors provided.
Arguments:
items -- a hashmap which maps itemIDs to the characteristic vectors
"""
norms = {}
for item in items:
norms[item] = np.sqrt(np.sum(np.square(items[item])))
return... | ff0a805b6a143b7b52c653226b69aed8319eb5ce | 14,822 |
def do_part_1():
"""
Solves part 1
"""
digested_lines = list(map(digest_line, input_lines(2)))
# Poor man's partial
doubles = sum(map(lambda l: contains_nple(l, reps=2), digested_lines))
triples = sum(map(lambda l: contains_nple(l, reps=3), digested_lines))
print(doubles * triples)
r... | 75fa72804d8721b4332d74f00c0bea4d82bcdd02 | 14,823 |
import torch
def create_Rz_batch(a):
"""
Creates a batch of rotation matrices about z of angles a.
Input (batch)
Output (batch, 3, 3)
"""
return torch.stack([
torch.stack([torch.cos(a),
torch.sin(a),
torch.zeros_like(a)],
di... | 7abed1ef608c9985605096679d28c86f5fabab8e | 14,824 |
import torch
def get_upsample_filter(size):
"""Make a 2D bilinear kernel suitable for upsampling"""
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
filter = (1 - abs(og[0] - center) / factor) * \
... | 8c286e6c20f3400c5206f3f15514a65dc8f3b0b5 | 14,825 |
import math
def lst2gmst(longitude,
hour,
minute=None,
second=None,
longitudeDirection='W',
longitudeUnits='DEGREES'):
"""
Converts Local Sidereal Time to Greenwich Mean Sidereal Time.
Parameters
----------
longitude : float (any nu... | 4e651dde2b5dadb1af5d00bc1813272190f07cdf | 14,826 |
import ast
def filter_funcs(node) -> bool:
"""Filter to get functions names and remove dunder names"""
if not isinstance(node, ast.FunctionDef):
return False
elif node.name.startswith('__') or node.name.endswith('__'):
return False
else:
return True | 022181afa887965af0f2d4c5ec33de07b8a3c089 | 14,827 |
from typing import Optional
def create_api_token(
creator_id: UserID,
permissions: set[PermissionID],
*,
description: Optional[str] = None,
) -> ApiToken:
"""Create an API token."""
num_bytes = 40
token = token_urlsafe(num_bytes)
db_api_token = DbApiToken(
creator_id, token, p... | 044d041bd013cb5b0ebc9c534b8c0162c3996172 | 14,829 |
from typing import Tuple
def match_image_widths(
image_i1: Image, image_i2: Image
) -> Tuple[Image, Image, Tuple[float, float], Tuple[float, float]]:
"""Automatically chooses the target width (larger of the two inputs), and
scales both images to that width.
Args:
image_i1: 1st image to match... | 86f043a3069202b2dfc3eb24f9ac10e9077b2237 | 14,831 |
from typing import Optional
from typing import Union
from typing import Any
from typing import Dict
import copy
def get_parameter_value_and_validate_return_type(
domain: Optional[Domain] = None,
parameter_reference: Optional[Union[Any, str]] = None,
expected_return_type: Optional[Union[type, tuple]] = Non... | 9cdd3106a0397a63a13d71b1c0ce5815a41e47ed | 14,832 |
def diff_tags(list_a, list_b):
"""
Return human readable diff string of tags changed between two tag lists
:param list_a: Original tag list
:param list_b: New tag list
:return: Difference string
"""
status_str = text_type("")
tags_added = [tag for tag in list_b if tag not in list_a]
... | e9f69bcdee0e2cb6fd260c56f8bbfe5f568afc63 | 14,833 |
import numpy
def distance_on_great_circle(start_point, direction, distance):
"""compute the location of a point a specified distance along a great circle
NOTE: This assumes a spherical earth. The error introduced in the location
is pretty small (~15 km for a 13000 km path), but it totall screws with
... | e39c62435c208cb2ea4e951b91b641cfbfcd45a8 | 14,834 |
def construct_tree_framework(bracket):
"""Given the tree in bracket form, creates a tree with labeled leaves
and unlabeled inner nodes."""
if type(bracket)==int: #base case, creates leaf
return Node(tree)
else: #recursive step, inner nodes
root = Node(None, construct_tree_framework(brac... | a54651fcc5604f46985b11d0d783c76f4368a9d0 | 14,835 |
def eckart_transform(atommasses, atomcoords):
"""Compute the Eckart transform.
This transform is described in https://gaussian.com/vib/.
Parameters
----------
atommasses : array-like
Atomic masses in atomic mass units (amu).
atomcoords : array-like
Atomic coordinates.
Retu... | 833b18ecdb299d3183da24c3b9d40227e387a385 | 14,836 |
def as_java_array(gateway, java_type, iterable):
"""Creates a Java array from a Python iterable, using the given p4yj gateway"""
java_type = gateway.jvm.__getattr__(java_type)
lst = list(iterable)
arr = gateway.new_array(java_type, len(lst))
for i, e in enumerate(lst):
jobj = as_java_objec... | d8a14a6506a0cbde6f09b4d071f6968da3e4d17d | 14,837 |
import scipy
def match(a: np.ndarray, b: np.ndarray) -> np.ndarray:
"""Finds the matrix R that minimizes the frobenius norm of RA - B, where
R is orthonormal.
Args:
a (np.ndarray[samples, features]): the first matrix to match
b (np.ndarray[samples, features]): the second matrix to match
... | 461f3f05ab1164bfbac3f9e8f6ccd5622791a6ff | 14,838 |
import time
import requests
import json
def macro_cons_silver_amount():
"""
全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今
:return: pandas.Series
2006-04-29 263651152
2006-05-02 263651152
2006-05-03 445408550
2006-05-04 555123947
2006-05-05 574713264
... | d60bac23a480c056d237dda6b16eb267b2f54ee5 | 14,839 |
import random
def shuffle(answers):
"""
Returns mixed answers and the index of the correct one,
assuming the first answer is the correct one.
"""
indices = list(range(len(answers)))
random.shuffle(indices)
correct = indices.index(0)
answers = [answers[i] for i in indices]
return an... | e597b4aeb65fecf47f4564f2fddb4d76d484707a | 14,840 |
from typing import Union
from pathlib import Path
def annotations_to_xml(annotations_df: pd.DataFrame, image_path: Union[str, Path],
write_file=True) -> str:
"""
Load annotations from dataframe (retinanet output format) and
convert them into xml format (e.g. RectLabel editor / Label... | 68ab235299da7026b77feb715e260f3e1749ec3b | 14,841 |
def depth(sequence, func=max, _depth=0):
"""
Find the nesting depth of a nested sequence
"""
if isinstance(sequence, dict):
sequence = list(sequence.values())
depth_list = [
depth(item, func=func, _depth=_depth + 1)
for item in sequence
if (isinstance(item, dict) or u... | 84b6e7ccaa0f7924fa4a775eca41edf8422222d0 | 14,842 |
def tei_email(elem_text):
"""
create TEI element <email> with given element text
"""
email = etree.Element("email")
email.text = elem_text
return email | cd3d6cf53f7ea5a29c4a02a4ea0d0a2d2144645c | 14,843 |
from typing import List
from pathlib import Path
def get_requirements(req_file: str) -> List[str]:
"""
Extract requirements from provided file.
"""
req_path = Path(req_file)
requirements = req_path.read_text().split("\n") if req_path.exists() else []
return requirements | 3433cd117bbb0ced7ee8238e36f20c69e15c5260 | 14,845 |
def get_gmail_account(slug):
"""
Return the details of the given account - just pass in the slug
e.g. get_account('testcity')
"""
service = get_gapps_client()
if not service:
return None
try:
return service.users().get(userKey=make_email(slug)).execute()
except HttpError... | 959685e6f40b8333103e47f9ce8c50050ca95961 | 14,847 |
def unisolate_machine_command():
"""Undo isolation of a machine.
Returns:
(str, dict, dict). Human readable, context, raw response
"""
headers = ['ID', 'Type', 'Requestor', 'RequestorComment', 'Status', 'MachineID', 'ComputerDNSName']
machine_id = demisto.args().get('machine_id')
commen... | d981005753030a1be50a3c0ff40022241096ea2f | 14,848 |
def func(*listItems):
"""
1、遍历所有的列表元素
2、遍历所有的列表元素里面的所有元素放进去一个列表里面
3、排序这个列表,返回最大的那个元素
"""
tmp_list=[]
for item in listItems:
if isinstance(item,list):
for i in item:
tmp_list.append(i)
tmp_list=list(filter(lambda k:isinstance(k,int),tmp_list))
tmp... | adbef2744871f1d8f714cbf2a71d4321e3fb72f5 | 14,849 |
def factory(name: str):
"""Factory function to return a processing function for
Part of Speech tagging.
Parameters:
-----------
name : str
Identifier, e.g. 'spacy-de', 'stanza-de', 'flair-de', 'someweta-de',
'someweta-web-de'
Example:
--------
import nlptasks ... | 9166613ba98beeb56dcc5766217d951ff13f9b38 | 14,850 |
def align_dataframes(framea, frameb, fill_value = 0.0):
"""Use pandas DataFrame structure to align two-dimensional data
:param framea: First pandas dataframe to align
:param frameb: Other pandas dataframe to align
:param fill_value: default fill value (0.0 float)
return: tuple of aligned frames
... | 86a5e8c399ab47a10715af6c90d0901c2207597c | 14,852 |
def flip_ud(img):
"""
Expects shape to be (num_examples, modalities, depth, width, height)
"""
return np.flip(img.copy(), 3) | f7a14641a89f5a170cb3d19b412acdbcbe3ac2f3 | 14,853 |
def data_context_service_interface_pointuuid_otsi_service_interface_point_spec_otsi_capability_get(uuid): # noqa: E501
"""data_context_service_interface_pointuuid_otsi_service_interface_point_spec_otsi_capability_get
returns tapi.photonic.media.OtsiCapabilityPac # noqa: E501
:param uuid: Id of service-in... | 99b3ed0e843f0dd405cd0d0b618a4da92fbdcf55 | 14,854 |
def _get_trial_event_times(events, units, trial_cond_name):
"""
Get median event start times from all unit-trials from the specified "trial_cond_name" and "units" - aligned to GO CUE
:param events: list of events
"""
events = list(events) + ['go']
event_types, event_times = (psth.TrialCondition... | c7198fdba392d7b5301109175408d3c0d95adbb9 | 14,855 |
from typing import Iterable
def select_region(selections, positions, region):
"""
selection in region from selections
"""
if not region:
return selections
region = list(region) + [None, None]
assert all([x is None or isinstance(x, Iterable) and len(x) == 2
for x in regi... | b9efc393b7d60773554130ded49d9dc9e00081e5 | 14,857 |
def summarize_center_and_dispersion(
analysis_layer,
summarize_type=["CentralFeature"],
ellipse_size=None,
weight_field=None,
group_field=None,
output_name=None,
context=None,
gis=None,
estimate=False,
future=False):
"""
.. image::... | a1fc44cb1781bb11f39dda597fe884552ec07a99 | 14,858 |
def length_entropy(r: np.ndarray, minlen: int = 2) -> float:
"""Calculate entropy of diagonal lengths in RQ matrix.
Args:
r (np.ndarray[bool, bool]): Recurrence matrix
minlen (int): Minimum length of a line
Returns:
float: Shannon entropy of distribution of segment lengths
"""
... | fe20e36aade8bae5e8a2fc139ad887495818f336 | 14,859 |
def rotate(posList, axis, angle):
"""Rotate the points about a given axis by a given angle."""
#normalize axis, turn angle into radians
axis = axis/np.linalg.norm(axis)
angle = np.deg2rad(angle)
#rotation matrix construction
ux, uy, uz = axis
sin, cos = np.sin(angle), np.cos(angle)
rotMa... | 0719bf548f5d952e78f0b2551f2edcd9510b1eca | 14,861 |
def _make_frame_with_filename(tb, idx, filename):
"""Return a copy of an existing stack frame with a new filename."""
frame = tb[idx]
return FrameSummary(
filename,
frame.lineno,
frame.name,
frame.line) | c775b77c3c282ed598adc25996fb418a9b85529e | 14,862 |
def median(X):
"""
Middle value after sorting all values by size, or mean of the two middle values.
Parameters
----------
X : np.array
Dataset. Should be a two-dimensional array.
Returns
-------
a: np.array
One-dimensional array that contains the median for each feature... | 232d1ce560c4030b01b048cb9087d5e8c49b39ec | 14,863 |
def _filter_none_values(d: dict):
"""
Filter out the key-value pairs with `None` as value.
Arguments:
d
dictionary
Returns:
filtered dictionary.
"""
return {key: value for (key, value) in d.items() if value is not None} | bed2629e4fa96a391e15b043aa3a0d64c75d6ed0 | 14,864 |
def new_project(request):
"""
if this is a new project, call crud_project without a slug and
with action set to New
"""
return crud_project(request, slug=None, action="New") | fc224a23fb2ecc39fce20a927c57be0ff74ed9d1 | 14,865 |
def get_Simon_instance(simon_instance):
"""Return an instance of the Simon family as a `Cipher`."""
if simon_instance == SimonInstance.simon_32_64:
default_rounds = 32
n = 16
m = 4
z = "11111010001001010110000111001101111101000100101011000011100110"
elif simon_instance == Sim... | 41ce1cdfdb58b15af8167f5e0d03fcd0beb94c80 | 14,866 |
def clamp(val: float) -> int:
"""Clamp a number to that expected by a reasonable RGB component
This ensures that we don't have negative values, or values exceeding one byte
Additionally, all number inputs are rounded
Args:
val (float): Raw float value to clamp
Returns:
int: Clamped... | b908afd06f8e5bf9b98f2729424e0b007c62a18a | 14,868 |
import scipy
def componental_mfpt(trans: np.ndarray, **kwargs) -> np.ndarray:
"""Compute Markov mean first passage times per connected component of the chain."""
n_comps, comp_labels = scipy.sparse.csgraph.connected_components(
trans, **kwargs
)
hier_trans = transition_matrix(trans)
absorb... | 76c9ade340668e5f564b874bc808170b2d0903cb | 14,869 |
def atleast_1d(*arys):
"""
Convert inputs to arrays with at least one dimension.
Scalar inputs are converted to 1-dimensional arrays, whilst
higher-dimensional inputs are preserved.
Parameters
----------
array1, array2, ... : array_like
One or more input arrays.
Returns
--... | 440782c7c5a5b231425cc1c1282110e983dd8dc2 | 14,871 |
def lines2str(lines, sep = "\n"):
"""Merge a list of lines into a single string
Args:
lines (list, str, other): a list of lines or a single object
sep (str, optional): a separator
Returns:
str: a single string which is either a concatenated lines (using
a custom or the ... | a9209bd8eda92f42a287725aaeccfcb35dab24cd | 14,872 |
def evaluate(board):
"""
Evaluates chess board
input parameter(s):
board --> The chess board to be evaluated
return parameter(s):
score --> The board evaluation
"""
score = 0
for i in range(len(board)):
for j in range(len(board[i])):
# Add p... | 6b02f085ab47d241f7639143d82570e97891975a | 14,874 |
def get_atom(value):
"""atom = [CFWS] 1*atext [CFWS]
An atom could be an rfc2047 encoded word.
"""
atom = Atom()
if value and value[0] in CFWS_LEADER:
token, value = get_cfws(value)
atom.append(token)
if value and value[0] in ATOM_ENDS:
raise errors.HeaderParseError(
... | f7d93daabfc96138e79443eb2e5c7e7a9b28fbbc | 14,875 |
def create_page():
"""新增页面"""
tags = dbutils.get_tags()
return render_template('edit.html', title='新建', edit=False, tags=tags) | 48c14aabc76ff3c4886b2ff7f1340035936d81ce | 14,876 |
def calculate_class_weights():
"""
:return: class-wise true-label-area / false-label-area as a dictionary
"""
df = collect_stats()
df = df.fillna(0)
df = df.pivot(index = 'Class', columns = 'ImageId', values = 'TotalArea')
df = df.sum(axis=1)
df = df / (2500. - df)
return df.to_dict... | 42d006daee27d1400d76e9233e64e4d09683573c | 14,877 |
def get_data_layer(roidb, num_classes):
"""return a data layer."""
if cfg.TRAIN.HAS_RPN:
if cfg.IS_MULTISCALE:
layer = GtDataLayer(roidb)
else:
layer = RoIDataLayer(roidb, num_classes)
else:
layer = RoIDataLayer(roidb, num_classes)
return layer | 32035fc837b402949a5fb75af0ad5dbe26a2e129 | 14,878 |
def split_on_first_brace(input,begin_brace = "{",end_brace = "}",error_replacement="brace_error"):
"""
input: string with {Something1} Something2
output: tuple (Something1,Something2)
"""
if error_replacement=="chapter_error":
print(input[:20])
input = remove_empty_at_begin(input)
if... | 201f6789f9db65aa98b857c923e3ed0484aaea89 | 14,879 |
import warnings
def check_count(value, total_count, dimension_type):
"""check the value for count."""
value = validate(value, "count", int)
if value > total_count:
raise ValueError(
f"Cannot set the count, {value}, more than the number of coordinates, "
f"{total_count}, for... | aed0b31e041c3c8ca791533697c2ad9e292a8fcc | 14,881 |
import json
def request_certificate(request):
"""Request the on-demand creation of a certificate for some user, course.
A request doesn't imply a guarantee that such a creation will take place.
We intentionally use the same machinery as is used for doing certification
at the end of a course run, so th... | 73605a4d02d515656ddbd4cb63e1c810d65f5f2e | 14,882 |
def get_useable_checkers():
"""
列出可用插件列表
:return:
"""
useable_checkers = list()
for (checker_name, checker_instance) in CHECKER_INSTANCE_DICT.items():
if checker_instance.useable:
useable_checkers.append(checker_instance)
return useable_checkers | 9548c4423f2176081e59957a823afb986f134c7a | 14,883 |
def get_training_roidb(imdb):
"""Returns a roidb (Region of Interest database) for use in training."""
if cfg.TRAIN.USE_FLIPPED:
print 'Appending horizontally-flipped training examples...'
imdb.append_flipped_images()
print 'done'
print 'Preparing training data...'
wrdl_roidb.pr... | adec6258d6ffa810aef475ec5257ef92a762f1fa | 14,884 |
def _used_in_calls(schedule_name: str, schedule: ScheduleBlock) -> bool:
"""Recursively find if the schedule calls a schedule with name ``schedule_name``.
Args:
schedule_name: The name of the callee to identify.
schedule: The schedule to parse.
Returns:
True if ``schedule``calls a ... | 9d6ff0b3a415047252ef2148aa6e59e229531ef7 | 14,885 |
def font_size_splitter(font_map):
"""
Split fonts to 4 category (small,medium,large,xlarge) by maximum length of letter in each font.
:param font_map: input fontmap
:type font_map : dict
:return: splitted fonts as dict
"""
small_font = []
medium_font = []
large_font = []
xlarge_... | d047e182df8d9015997c2debd6269012cb779df5 | 14,886 |
def dm2skin_normalizeWeightsConstraint(x):
"""Constraint used in optimization that ensures
the weights in the solution sum to 1"""
return sum(x) - 1.0 | 79024cb70fd6cbc3c31b0821baa1bcfb29317043 | 14,888 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.