content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def run_spacytagger( string ):
"""
Runs spacy on `string` and returns a list of
:class:`quepy.tagger.Word` objects.
"""
assert_valid_encoding(string)
# For now, at least, perform our own pre-processing
# --to ensure terms like "presynaptic" are easily found later.
string = ' '.join( str... | bdb0b0575484fc2c34fa7d4f8937f12ca7616bbd | 3,603,493 |
def sequence_labeling_counts(true, predicted, equality_fn):
"""
Return FP, FN, and TP counts
"""
unique_classes = _get_unique_classes(true, predicted)
d = {
cls_: {"false_positives": [], "false_negatives": [], "true_positives": []}
for cls_ in unique_classes
}
for i, (true_... | 539594559072a3bdb4a37cedb46ee142f642e66e | 3,603,494 |
from display.tkinter import tkinter_led_strip_factory
from display.adafruit_ws2801 import adafruit_led_strip_factory
def create_application(
command_line_args,
num_leds,
brightness_schedule,
transition_length,
pattern_factories,
direction=LedDirection.START_TO_END):
"""Creates an Application instance.... | 970f198b52e31530774a2afc47580d149da2e302 | 3,603,495 |
def q_splitting_bar(z):
"""Returns quark 'reduced' splitting function"""
return q_splitting(z) + q_splitting(1-z) | 39f76c313c7e53ccd0d1d505332fd0f2230d8158 | 3,603,496 |
def usefull_function(a):
""" """
return a * a | 5a95e1f50a94f949d8aa2f4260edaed4941f42b1 | 3,603,497 |
def is_bspfile(filename):
"""Quickly see if a file is a bsp file by checking the magic number.
The filename argument may be a file for file-like object.
Args:
filename: File to check as string or file-like object.
Returns:
True if given file's magic number is correct.
"""
retu... | 0d5b64b48ec1409a4982acc2540dc1398ba5e843 | 3,603,498 |
def crop_image(img, bboxes, input_size):
"""
Crop a 500x500 patch from the image, taking care for smaller images.
bboxes is the np.array of all bounding boxes [x1, y1, x2, y2]
"""
# randomly pick a cropping window for the image
# We keep the second arg to randint at least 1 since randint is [low... | f1d424a627c161bbbdc1e42d624c387ee21864f7 | 3,603,500 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Loop Energy Sensor from a config entry."""
domain_data = hass.data.setdefault(DOMAIN, {})
unique_id = entry.unique_id
api = LoopEnergyApi(hass, unique_id, entry.data)
domain_data[unique_id] = api
await api.a... | fc3ba4f1d817963b80287d724be90c994a7a91bc | 3,603,501 |
def decode_many(comments: str) -> list:
"""Decode base64 string into many comments.
:param comments: The base64-encoded list of comments.
:return: The decoded list o comments [(text, timestamp)].
"""
return [decode(comment) for comment in comments.split(';')] | fe346ca0c403390e9cd0d7174eb8bc655cb009af | 3,603,502 |
import logging
def _setup_test(api_client, run_label):
"""Create the namespace for the test.
Returns:
test_dir: The local test directory.
"""
api = k8s_client.CoreV1Api(api_client)
namespace = k8s_client.V1Namespace()
namespace.api_version = "v1"
namespace.kind = "Namespace"
namespace.metadata =... | 9697d69cf1bdb5c44e2e001502352158ef5a2e3b | 3,603,503 |
def singularValuesFromWotfList(Hr_list, Hi_list, eps=None, support=None, method='direct'):
"""Returns a list of the singular values squared which are > epsilon.
Parameters
----------
Hr_list : list of arrays
List of real WOTFs
Hi_list : list of arrays
List of... | d5da02594fd12d82dda8eb7df85625443ba612b8 | 3,603,504 |
def read_all_accacia():
"""Load ACCACIA tracks as `pandas.DataFrame`"""
def _date_parser(x):
return pd.datetime.strptime(x, "%Y%m%d%H%M")
df = pd.read_csv(
mypaths.acctracks,
delimiter="\t",
names=["N", "time", "lon", "lat"],
parse_dates=["time"],
date_parse... | efc836bf13c5b35a5f47cff2138982f55ef85cda | 3,603,505 |
def get_total_volume():
"""
Calculate the total volume in bytes of files that need to be published.
:return: volume in bytes.
"""
amip_expts = ['highresSST-present', 'highresSST-future']
coupled_expts = ['spinup-1950', 'hist-1950', 'control-1950',
'highres-future']
stre... | 1036fa7a16fee5ba115edc50cdbd90eebb7cfdc1 | 3,603,506 |
def is_nan(var) -> bool:
"""
Simple check if a variable is a numpy NaN
based on the simple check where (nan is nan) gives True but (nan == nan) gives False
"""
return not var == var | 0f91829f9b5ee3dfb22944d956066069b4a3f606 | 3,603,507 |
def load_instances(model, primary_keys):
"""Load model instances preserving order of keys in the list."""
instance_by_pk = model.objects.in_bulk(primary_keys)
return [instance_by_pk[pk] for pk in primary_keys] | 21f26f66047fc2b2871f77447035ba15fbf78fa7 | 3,603,508 |
def gen_scatter_1d_thrust(data, indices_sorted, updates_sorted, axis, out, _):
"""Generate scatter ir for 1d inputs, using a sorting based approach.
By sorting indices and comparing neighboring two indices, we can tell which
of elements in the indices tensor can scatter its update value into the output.
... | 1de9401eca6f76829545696b0a5fc5dc3de8b3e8 | 3,603,509 |
def aln_has_translocations(aln):
"""Return True if input aln has translocation tags."""
return aln.has_tag(TRANSLOCATION_TAG_NAME) and len(aln.get(TRANSLOCATION_TAG_NAME)) | 798af339e9b4c3dd651ba3bae4f628cf35218dcf | 3,603,510 |
def plugin_init(config):
""" Initialise the plugin.
Args:
config: JSON configuration document for the device configuration category
Returns:
handle: JSON object to be used in future calls to the plugin
Raises:
"""
handle = config['gpiopin']['value']
return handle | 2eb63502ab8331691253b3c30150acc79395889c | 3,603,511 |
def _create_interaction(
example_id,
question_text,
answer_groups,
table,
):
"""Creates an interaction instance that corresponds to some short answer."""
interaction = interaction_pb2.Interaction()
question = interaction.questions.add()
main_answer_index = None
for answer_group_index, answers... | 20c642c3c31aad502ce30f27b60899aa2108be10 | 3,603,514 |
def cos_sim(vector_a, vector_b):
"""
:return: sim
"""
vector_a = np.mat(vector_a)
vector_b = np.mat(vector_b)
num = float(vector_a * vector_b.T)
denom = np.linalg.norm(vector_a) * np.linalg.norm(vector_b)
cos = num / denom
sim = 0.5 + 0.5 * cos
return sim | fce0f85db4aef9079302da4b7512e21f37e773e9 | 3,603,515 |
def define_stopwords():
"""
default: combine SKLEARN, NLTK, and SPACY stopwords -> 'sns_set'
alternative: set custom 'additional_words' and 'unstop' words (to ignore)
function returns a list: 'stopwords'
"""
# corpus-specific stop words [OPTIONAL]
# add 'stop.txt' to local directory, pass as argument 2
... | e096ce431586473f07c3e5818ee3eb4cd783c030 | 3,603,516 |
from IPython.display import Image # type: ignore
import typing
import pathlib
def view_block_diagram(system: typing.Union[System, typing.Type[System]],
ipython_notebook=False):
"""convenience function to quickly view a system composition"""
plot_fname = f".pub-sub-plot.png"
# plot c... | a4e5354fdd9fe319711ecf3e85bc91b7b1d72242 | 3,603,517 |
def int_pr(pars, d_max, nslice):
"""
Integral of P(r).
:param pars: c-parameters.
:param d_max: d_max.
:param nslice: nslice.
:return: Integral of P(r).
"""
nslice_d = np.float64(nslice)
i_r = np.arange(nslice)
r = d_max/nslice_d * i_r
values = pr(pars, d_max, r)
tota... | 5338a98bb7cb6e11abe6db6cee5e642eacddbbd4 | 3,603,519 |
import pickle
import logging
def get_motifs_by_cluster(clusters, data_layer, k_for_motifs=5, number_of_samples=1000, output_file='./results/motifs_by_cluster.pickle'):
""" A way to take in a group of GitHub project clusters and output their most common motifs. For each cluster, get most common subgraphs
... | d253e5659eeab7eca838e123cf7a1922110e79ad | 3,603,520 |
from datetime import datetime
from bs4 import BeautifulSoup
import re
def parse_unibet(url):
"""
Retourne les cotes disponibles sur unibet
"""
selenium_init.DRIVER["unibet"].get(url)
match_odds_hash = {}
is_sport_page = len([x for x in url.split("/") if x]) == 4
match = ""
today = date... | ce61debab873302107241877c317cce05aeb440c | 3,603,521 |
def walk(path):
"""
@param path: The item where the walk should start.
@type path: C{unicode}
@raise ItemSupportError: Raised when an error occurred.
@see: L{walk<datafinder.core.item.visitor.base.ItemTreeWalkerBase.walk>} method to add further post-processing.
"""
cwr = repos... | 2c6a11fa32f91d859bc891bbd6ae6f7366e5ca6e | 3,603,522 |
import scipy
def leastsqFit(func, x, params, y, err=None, fitOnly=None,
verbose=False, doNotFit=[], epsfcn=1e-7,
ftol=1e-5, fullOutput=True, normalizedUncer=True,
follow=None):
"""
- params is a Dict containing the first guess.
- fits 'y +- err = func(x,params... | 693d060c4621ac95db15b827b389316e61398178 | 3,603,524 |
def _merge_ns(base, override):
"""we can have several namespaces in properties and in call"""
new_ns = {}
for ns in base:
new_ns[ns] = base[ns]
for ns in override:
new_ns[ns] = override[ns]
return new_ns | 935a5703b42c92104bff543da57183895cd11bf2 | 3,603,525 |
def GetHotlistRoleName(effective_ids, hotlist):
"""Determines the name of the role a member has for a given hotlist."""
if not effective_ids.isdisjoint(hotlist.owner_ids):
return 'Owner'
if not effective_ids.isdisjoint(hotlist.editor_ids):
return 'Editor'
if not effective_ids.isdisjoint(hotlist.follower... | 0c03460d3e4190d4964a60a2753d31e1732b6e44 | 3,603,526 |
def cmap_toggle_log(event_coll, event):
"""Switch between linear and logarithmic scales"""
if event_coll.scene.data_logged:
print("Data is logged already, can't toggle scale to linear")
return False
if not event_coll.camera.cmap_log:
event_coll.camera.cmap_max = np.log10(event_coll.... | f0bdc7183086e09ef00df8a058900e4320441a57 | 3,603,527 |
import torch
def mat_from_diag_triu_tril(diag, tri_upp, tri_low):
"""Build matrix from given components.
Forms a matrix from diagonal, strictly upper triangular and
strictly lower traingular parts.
Parameters
----------
diag : array_like, shape=[..., n]
tri_upp : array_like, shape=[..., ... | fb9ad7bb6d739446a102adff654767b4b2688865 | 3,603,528 |
import glob
import logging
def generate_pairs(path_pattern_imgs, path_pattern_lnds, mode):
""" generate the registration pairs as reference and moving images
:param str path_pattern_imgs: path to the images and image name pattern
:param str path_pattern_lnds: path to the landmarks and its name pattern
... | c9c591995e6acc9d0977590b8259814779b43ac8 | 3,603,529 |
from unittest.mock import Mock
from unittest.mock import patch
def mock_gateway_fixture(gateway_id):
"""Mock a Tradfri gateway."""
def get_devices():
"""Return mock devices."""
return gateway.mock_devices
def get_groups():
"""Return mock groups."""
return gateway.mock_gro... | 6404cb18ce9dd0e97b33958958d7851ee5739bed | 3,603,531 |
from typing import Sequence
def pirates_binary(bets_indices: Sequence[ValidIndex]) -> int:
""":class:`int`: Returns the bet-binary representation of bet indices.
Turns something like (1, 2, 3, 4, 2) for example into 0b10000100001000010100, a bet-binary number.
This is fundamentally the inverse of binary... | c9d299cdf777085597cbc3795b55482bdad1bab6 | 3,603,532 |
def add_outliers(X, n_outliers, dist_factor=10, replace=True,
inplace=False, random_state=None, return_index=False):
"""
add outliers to a given data set: add large random shifts to some of the data in X
:param X: array of shape=(n_samples, n_features)
:param n_outliers:
:param dist... | c585cf2fa5a2a6849fac00035988be02fa5ecbb3 | 3,603,533 |
import re
def create_contents(text, obsidian=False):
"""create a contents table from parsed headers
obsidian flag indicates single file mode is being used (see file_converter) and markdown format over PDF"""
if obsidian:
contents = "## Contents"
else:
contents = "# Contents"
head... | 8011d0e2118497917e99a217fb7bfa025658cc35 | 3,603,534 |
def format_number(column, d=2):
"""
Formats numeric column x to a format like '#,###,###.##', rounded to d decimal places,
and returns the result as a string column.
* If d is 0, the result has no decimal point or fractional part.
* If d < 0, the result will be null.
"""
return _wit... | faadf942229db088cb835c034948bc9b4013f516 | 3,603,535 |
def process_image(img):
"""
Process tilted images
"""
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)
pts = cv2.findNonZero(threshed)
ret = cv2.minAreaRect(pts)
(cx,cy), (w,h), ang = ret
if w>h:
w,h = h,w
an... | 355f86aee9b408c6edbc906b2a4e72c318faca9a | 3,603,536 |
def application_list(request, club_name):
"""Shows all the pending applications to club management"""
current_club = Club.objects.get(club_name=club_name)
applications = Application.objects.filter(club=current_club, status='P')
applications_count = applications.count()
return render(request, 'applic... | f5d59ed9052b94a6b032bdd19904ca3081783f2e | 3,603,539 |
import psutil
def get_memory_status():
"""\
内存信息
:return: 系统总计内存、 系统已经使用内存、 系统空闲内存、 swap内存信息
"""
mem = psutil.virtual_memory() # 实例化内存对象
return mem.total, mem.used, mem.free, psutil.swap_memory() | 0929672295f42b8addef38c21e55b6999a5a258a | 3,603,540 |
from datetime import datetime
def ModelPredictionView(request):
"""
Retrieve the stop to stop model result
"""
try:
# print(request.query_params)
start_stop = request.query_params.get('start_stop').lower()
end_stop = request.query_params.get('end_stop').lower()
route_nu... | 3af2c7c0844681989a621e83fde679a91d7ed3bc | 3,603,542 |
def upsample_block(l0, f, activation='relu'):
"""
Upsampling block.
:param l0: input layer
:param f: number of feature maps
:param activation: activation name
:return: the last layer of the upsampling block
"""
l = UpSampling2D(size=2)(l0)
l = Conv2D(f,... | ecfa56304b79c6931666a904a8b5bb69379cda7f | 3,603,543 |
def seed_org(unused_request, i):
"""Returns the properties for a new org entity.
"""
_, current_user = ensureUser()
gsoc2009 = Program.get_by_key_name('google/gsoc2009')
if not gsoc2009:
raise Error('Run seed_db first')
properties = {
'key_name': 'google/gsoc2009/org_%d' % i,
'link_id': '... | 98f72aba1dca916b4399ea076e4f44d0a6e4803f | 3,603,544 |
import requests
def get_session_key(
user,
password,
url='https://localhost:8089',
verify=False,
ssl_options=None):
"""get_session_key
This will get a user session key and throw for any errors
:param user: username
:param password: password
:param url: spl... | b9a7e45d58f98f8609b5ec751ca0baf15d096d80 | 3,603,545 |
def _get_single_osc_power(osc_cens, osc_pows, osc_bws):
"""Return the highest power oscillation in a given range.
Parameters
----------
osc_cens : 1d array
Vector of oscillation centers.
osc_pows : 1d array
Vector of oscillation powers.
osc_bws : 1d array
Vector of oscil... | 01e40d0bdcf8bf4ece3bfcc2367e443da362a2a2 | 3,603,546 |
def read_binary_esi_header(filename):
"""
Docstring
"""
# SyNCoPy raw binary dtype-codes
dtype = {
1 : 'int8',
2 : 'uint8',
3 : 'int16',
4 : 'uint16',
5 : 'int32',
6 : 'uint32',
7 : 'int64',
8 : 'uint64',
9 : 'float32',
... | 311cc4a90a4f776ad4df246e28e5697b67fa35f2 | 3,603,547 |
import random
def rand_dictionary(dic, k):
"""
функция создает случайный словарь
из исходного словаря
:param dic: исходный словарь
:param k: размер нового словаря
:return: случайный словарь из dic размера k
или размера исходного при k более
размера исходного
"""
# формируем с... | b2ce6fd2c29a8b4d9d4a054bac40a77a6056c5f6 | 3,603,548 |
import six
import struct
def pack_list(from_, pack_type):
""" Return the wire packed version of `from_`. `pack_type` should be some
subclass of `xcffib.Struct`, or a string that can be passed to
`struct.pack`. You must pass `size` if `pack_type` is a struct.pack string.
"""
if isinstance(pack_typ... | 32861a19341dccc43e1aad8ba5a4d6baf07b8965 | 3,603,549 |
def s3_bucket_ddb_items():
"""
Retrieve and format S3 buckets for cache storage.
"""
items = []
for bucket in s3_buckets():
arn = "arn:aws:s3:::{}".format(bucket["Name"])
service = "s3"
items.append(node_to_ddb_item(arn, service, "global", bucket))
return items | 1167be9681d4fa96f20244c6ea1c292532c39e37 | 3,603,551 |
def add_to_bag(request, item_id):
"""
Add a quantity of the specified
event to the shopping bag and
display success message.
"""
event = get_object_or_404(Event, pk=item_id)
quantity = int(request.POST.get("quantity"))
redirect_url = request.POST.get("redirect_url")
bag = request.s... | d0ea69523490cff2fbce9dacebe0d1e944725806 | 3,603,553 |
def WaitForDeleteDeploymentOperation(operation):
"""Waits for the given "delete deployment" LRO to complete.
Args:
operation: the operation to poll.
Raises:
apitools.base.py.HttpError: if the request returns an HTTP error
Returns:
An Operation.ResponseValue instance
"""
client = GetClientInst... | 866ee1205431e4ec0b3a0eb359dfa5d2a372eff2 | 3,603,555 |
def add_noise_indicator_lines(ax,
noise_level,
color,
linewidth=DEFAULT_NOISE_INDICATOR_LINEWIDTH,
alpha=0.75,
show_hminus=True,
show_hplus=... | c94a8c2f846ec510574018ed5c2ce5c2d6d0ce48 | 3,603,557 |
import pandas
def prepare_and_plot_cumulative_incidence(df: pandas.DataFrame, trait_code: str,
data_column_name: str, output_path: str, sex: str = 'both',
ancestry: str = 'All'):
"""Prepares data for plotting cumulative incidence ... | 7c4bfbd9c8ab0a3f93b358ee5d8ddac048f1f279 | 3,603,558 |
from typing import Any
def function_sig_key(
name: str,
arguments_matter: bool,
skip_ignore_cache: bool,
*args: Any,
**kwargs: Any,
) -> int:
"""Return a unique int identifying a function's call signature
If arguments_matter is True then the function signature depends ... | bfec647db5d819fb87cf3a227927acd5cd6dda10 | 3,603,559 |
def bloq_bifurcacao(tab, jogador):
"""
Faz o bloqueio da bifurcacao do adversario.
"""
posis = bifurcacao(tab, -jogador)
if posis == 0:
return 0
if len(posis) == 1:
return posis[0]
elif 1 < len(posis): # se o numero de bifurcacoes for maior que 1, joga-se para forcar o adv... | 9da7f676c760244ccc41800c88283242b7c9faeb | 3,603,560 |
def nword(word: str, k: int) -> tuple:
"""
concatenates k consecutive words into a tuple
Parameters
----------
word
k
Returns
-------
tuple of strings
Examples
--------
>>> nword('this that the other', 2)
('thisthat', 'thatthe', 'theother')
"""
parts = spli... | e2e8d2ffc8bbbcc14cc7b51d0dc2720e47eca4d3 | 3,603,561 |
def encrypt(data):
"""
静态方法,data是要加密的数据,为bytes类型
返回依次为: 公钥,私钥,签名证书,均为bytes类型
"""
if not isinstance(data, bytes):
raise TypeError("data type must bytes")
pub_key, pri_key = rsa.newkeys(1024)
signature = rsa.sign(data, pri_key, 'SHA-1')
return pub_key.save_pkcs1(), pri_key.save_pk... | 249f150aaef8283daf228b9f7b8c64c331c97359 | 3,603,563 |
def tenary_pass_through(*args):
"""Pass-through method for a list of argument values.
Parameters
----------
args: list of scalar
List of argument values.
Returns
-------
scalar
"""
return args | edbf7123bb2088b51aa27e72e0007c2f30f24d7b | 3,603,564 |
def create_pressure(data) -> Pressure:
"""
Creates a new pressure record in the database.
:param data: JSON data for a new Pressure object.
:return: Pressure
"""
value = data.get('value')
value_units = data.get('value_units')
value_error_range = data.get('value_error_range')
latitud... | 598a94b9a26c725ec0ca94a7ac2e73bdc8838f4e | 3,603,565 |
def get_patches(x,
y,
p_size,
s_size,
rate,
padding):
"""
This function gets reformated image patches with the reshaped labels
Note: If y is the mask, then we perform logic to get labels from patches
x (np.... | 7d237966a1102e454dd58c794ce365e81493908c | 3,603,566 |
def use_date_dir():
"""write files to separate directory?"""
return __CONF['date_dir'] | fe82e3d8a308e608c262a99d0945354a0ef15109 | 3,603,567 |
def create_submenu(title, exit_title, parent_menu_item=None):
"""
This method is used to create a sub-menu that is associated
with a given menu item.
Args:
title: The title that will be displayed for
this sub-menu
exit_title: The title th... | 0027276c4def2b1f733ed0f5f1fdd0e31dc75971 | 3,603,568 |
def mni_to_tal_meyer_lindenberg98(*args, **kwargs):
"""
Due to Andreas Meyer-Lindenberg
Taken from
http://imaging.mrc-cbu.cam.ac.uk/imaging/MniTalairach
"""
return Linear(
np.array(
[
[0.88, 0, 0, -0.8],
[0, 0.97, 0, -3.32],
[0... | 28f462cb4cb4cecfec900811a1e091db9e2de254 | 3,603,569 |
def get_filtered_users(db, query_filter, start = 0, count = 50):
"""
Get a filtered list of user rows starting at the given position. If the start index is out of bounds
an empty list will be returned. If there are as many users as the given 'count' the list will
be filled with as many as there is.
... | 150bf5a314b5d6e08de319099840f912810b32b7 | 3,603,570 |
def clustering(matrix, sv_reads, bp_id):
"""
creates clustering matrix by calling make_clustering_matrix(). Clusters most similar reads and sends
result to judge_clustering to be evaluated. Result comes back and is returned.
:param matrix:
:param sv_reads:
:param bp_id:
:return phasing resul... | dc054ae8420f648a9584aaa917e362c7fb5cad00 | 3,603,571 |
import numpy
def scores_vs_time(timeseries, numerator = 'fractionmatched'):
"""Process a timeseries as read by load_trajectory and return the fraction of each reference atom type found at each time.
Parameters
----------
trajectory : dict
Trajectory information as output by load_trajectory
... | 17ec9d243425366ae92b15c0d4894379a9d8f2dc | 3,603,572 |
def volume(
media_server,
level: float = None,
relative: bool = False,
zone: Zone = Zone(),
return_display_string: bool = False,
) -> float:
"""Get or set the playback volume.
level: The level as a value between 0 and 1. If left to None, volume is
returned unchanged.
re... | 1cc2eedff047b080f300e354f0582cf65b2c5141 | 3,603,573 |
def call_hartmann(
params: dict[str, float], train_inputs_dict: dict[str, np.ndarray],
train_targets_dict: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
"""
6-dim hartmann benchmark func
1. minimization
2. global minimum: -3.32237
3. x* = [(0.20169, 0.150011, 0.476874... | be17d3ba20b73cadec94a1ab5e8e92221fa39aba | 3,603,574 |
import warnings
def soft_check_1d(y, y_numeric, estimator):
"""Check if y is numeric, finite and one-dimensional."""
context = _get_context(estimator)
CHANGE_y = _check_column_or_1d(y)
ALL_FINITE = _check_all_finite(y)
if not ALL_FINITE:
CHANGE_y = True
msg = ("%sNot all elements... | 1e75abc7fe1e331ee210e2ea31894b8fd82a193a | 3,603,576 |
def BRepBlend_HCurveTool_LastParameter(*args):
"""
:param C:
:type C: Handle_Adaptor3d_HCurve &
:rtype: float
"""
return _BRepBlend.BRepBlend_HCurveTool_LastParameter(*args) | acb49f99aac401602dcfb3f1dc932e5ad7036717 | 3,603,577 |
def arch_recursion_python(
parameters: Float64Array,
resids: Float64Array,
sigma2: Float64Array,
p: int,
nobs: int,
backcast: float,
var_bounds: Float64Array,
) -> Float64Array:
"""
Parameters
----------
parameters : ndarray
Model parameters
resids : ndarray
... | c7639e6b94f5465abdd18ec016870f7706342bed | 3,603,578 |
from bs4 import BeautifulSoup
import requests
def fetch_events_vet(base_url='https://www.vet.upenn.edu/veterinary-hospitals/NBC-hospital/news-events/new-bolton-event'):
"""
Fetch events for Veterinary Hospitals, New Bolton Center Hospital
"""
events = []
page_soup = BeautifulSoup(requests.get(
... | d9764da7276b479648e452c8fd889c91f298e168 | 3,603,579 |
import json
def search_batch(request):
"""
Quick search for batch with a exact or partial name and layout of descriptor.
The filters can be :
- name: value to look for the name field.
- method: for the name 'ieq' or 'icontains' for insensitive case equality or %like% respectively.
... | b67c63b0a53c4a7ad4d0a61d5ec2d36a1a2c32e5 | 3,603,581 |
def do_kcsd(ele_pos, pots, **params):
"""
Function that calls the KCSD1D module
"""
num_ele = len(ele_pos)
pots = pots.reshape(num_ele, 1)
ele_pos = ele_pos.reshape(num_ele, 1)
Lamb = [-9, -3]
lambdas = np.logspace(Lamb[0], Lamb[1], 50, base=10)
k = KCSD1D(ele_pos, pots, **params)
... | 315aa129f023b5c4f847891c8801686f74fff0c6 | 3,603,582 |
def dipoleI(R0, Bm):
"""
Return the second invariant value in dipole field.
Parameters
----------
R0 : float
Equatorial distance to the guiding line (meters)
Bm : float
Mirror field strength. (Tesla)
Returns
-------
float
The second invariant :math: ... | b32413f80f7c3285d906a45e5402d1b0b776eb89 | 3,603,583 |
def uniform(
expression_vectorized,
num_vals,
min_x,
max_x,
err_std_x=0,
err_std_y=0):
"""Provides specified number of values (x, y),
linked with specified relation, using the following scheme:
x* is a uniform value from [min_x, max_x)
y* = expr... | 7a5d2314fa9058919c1cd9c8f7c4df7bc51d293c | 3,603,584 |
def calc_zchi2(target_ids, target_data, dtemplate, progress=None):
"""Calculate chi2 vs. redshift for a given PCA template.
Args:
target_ids (list): targets IDs.
target_data (list): list of Target objects.
dtemplate (DistTemplate): distributed template data
progress (multiproces... | 3be4a9f5b83b8372fd758701a3da73bfee8f475b | 3,603,585 |
def servicestore_factory(registry, database=None):
"""
Creates a service store with the interface of :class:`twitcher.store.ServiceStore`.
By default the mongodb implementation will be used.
:return: An instance of :class:`twitcher.store.ServiceStore`.
"""
database = database or 'mongodb'
i... | 401d0374559d88b1836486763f3af4f292cf0cc9 | 3,603,586 |
from pyvipr.pysb_viz.static_viz import PysbStaticViz
def sp_comm_asyn_fluidc_view(model, k, max_iter=100, random_state=None, layout_name='fcose'):
"""
Render a visualization of the interactions between the species in a model.
The species nodes are grouped by the communities detected by the
asynchronou... | 4c0f04c6aff69bddfe3cc1a297d5f2ab978c5c25 | 3,603,588 |
def _aliquot_from_response(response):
"""
Parameters
----------
response : dict
Returns
-------
ContainerAliquot
"""
return ContainerAliquot(
aliquot_id=response["id"],
volume_ul=response["volume_ul"],
concentration_um=response["concentration_um"],
ma... | c020855da9ee91aa73b6043bec2c7906eb24aeb1 | 3,603,589 |
import pyaudio
def play_array(snd_array, sr=44100, rescale='normalize', pyaudio_params={}, ignore_warning=False):
"""Play the provided sound array using pyaudio.
Args:
snd_array (array): The array containing the sound data.
sr (number): Sampling sr for playback; defaults to 44,100 Hz.
Will be overrid... | 8adf638641f1bf02bab45a30dee234d0e841907f | 3,603,590 |
def brent_fwhm(t, amp, retall=False, shift=True):
"""Obtain FWHM using brent's method to find half max crossings.
This will not behave well if more than two halfmax crossings are present.
"""
assert np.all(np.diff(t) > 0)
if shift:
amp = amp - np.min(amp)
amp /= np.max(amp)
ampf = U... | 8db7a07c83650d96f5e3481ea6f18efded8ad529 | 3,603,591 |
def pkg_datadir():
"""Return a data path inside the package's structure (i.e., small, empty files)."""
return data_dir | 9fd04ce131a5e7513e9089a388356cd3147f4878 | 3,603,592 |
import time
def date_file_name(name):
"""Generate file name with date suffix."""
time_str = time.strftime("%Y%m%d-%H%M%S")
return name + "_" + time_str | 40e37e2a5dbc0208421f797bc2ae349414b05e4e | 3,603,593 |
def generate_coefficients(path_to_fasta, DNA_WEIGHT_FRACTION=1):
"""
Generates a dictionary of metabolite:coefficients for the 4 DNA bases from the organism's
DNA fasta file and the weight percentage of DNA in the cell.
:param path_to_fasta: a path to the DNA fasta file of the organism, format should b... | 56e3f6ddc7760799dff0bd9b6a8d1858629bf086 | 3,603,594 |
def linkEntropy(linkograph, listNumber=[1,2], delta=None,
restrict=False, lowerBound=None, upperBound=None,
lineNumbers=False):
"""Calculates total link, backlink, and forelink entropies.
This function returns a list of link entropies for each node
considered. Given a node, ... | 475e5f85a72b4946c353d80ff74a3ffd88786c56 | 3,603,595 |
def read_image(filename, representation):
"""
Reads an image file and converts it into a given representation
:param filename: the filename of an image on disk
:param representation: representation code, either 1 or 2 defining whether the output should be a
grayscale image (1) or an RGB image (2)
... | e71e895b3549957ce3d5adf6d66d810a38a0e557 | 3,603,596 |
import click
def do_download_dependencies(dev=False, only=False, bare=False):
""""Executes the download functionality."""
# Load the Lockfile.
lockfile = split_vcs(project._lockfile)
if not bare:
click.echo(crayons.yellow('Downloading dependencies from Pipfile...'))
# Install default de... | 7e532e86e494167dacf331c5e7a86bbb70e9d8a0 | 3,603,597 |
def compute_efficiency_gap(partition):
"""
Input is a gerrychain.Partition object
with voteshare and population data.
It is assumed that `add_population_data` and
`add_voteshare_data` have been called on
the given partition's GeoDataFrame.
Returns the efficiency gap of
the distri... | 2982fe1b2f570c8eca27fade8915e9b117397cd1 | 3,603,598 |
def round_filters(filters, width_coefficient=None, depth_divisor=None):
"""Calculate and round number of filters based on width multiplier.
Use width_coefficient, depth_divisor of global_params.
Args:
filters (int): Filters number to be calculated.
global_params (namedtuple): Global para... | a5e0709755f765b722aa4c68f21a9c358b25c593 | 3,603,599 |
import torch
def get_bilstm_minus(batch_seq_encoder_repr, span_list, seq_lens):
"""This function gets span representation using bilstm minus
Arguments:
batch_seq_encoder_repr {list} -- batch sequence encoder representation
span_list {list} -- span list
seq_lens {list} -- sequence leng... | ca689a49a037b9dbd35305445f7f53fd07dd079c | 3,603,600 |
def create_pixel_vector(file):
"""Takes count and decimal vectors, then returns the pixel vector.
Args:
count_vector ([int]): Number of the counts of the bytes.
decimal_vector ([type]): Vector of the bytes in file.
Returns:
np.array: RGB pixel vector as np.array type.
"""
c... | 78e061782eb9e0c7b8e014e61485bebe9c02229b | 3,603,601 |
def run(align_bams, items, ref_file, assoc_files, region, out_file):
"""Run strelka2 variant calling, either paired tumor/normal or germline calling.
region can be a single region or list of multiple regions for multicore calling.
"""
call_file = "%s-raw.vcf.gz" % utils.splitext_plus(out_file)[0]
s... | 4422446ce0a68b72ce4f51e64ef0f573088019d4 | 3,603,602 |
def create_meandering_path(params):
"""
Returns a meander path based on input parameters
"""
deg_to_rad = 2 * pi / 360
radius = params.get('radius')
theta = params.get('theta')
width = params.get('trace-width')
number = params.get('bus-width') or 1
pitch = params.get('pitch') or 0... | 19dc35cf2f2836e618455287eb9de1e7b4571623 | 3,603,603 |
from hdl21.primitives import IdealCapacitor as C
def Ro(params: RoParams) -> h.Module:
""" Create a parametric oscillator """
ro = h.Module()
ro.ctrlb = h.Input(width=params.stages * params.rows, desc="Control code")
ro.osc = h.Output(width=params.stages, desc="Primary Oscillator Output")
ro.VDD,... | 6df84546a2b4ce1cf547dc29e9565135be1f4bcc | 3,603,604 |
import zipfile
def extract_csv_from_zip(filename):
"""Function to extract the csv file contained within the zip file."""
try:
with zipfile.ZipFile(filename, 'r') as zf:
contents = zf.namelist()
if len(contents) != 1:
raise zipfile.BadZipFile('There is more than ... | 9c3e32bc2d6966c9d295233e6aef6a3129f0242f | 3,603,605 |
import requests
import json
def updateData(url):
"""
Returns the symbol and the price of an asset.
Parameters
-----------
url: url used for information retrieval
Returns
-----------
tuple
(symbol name, symbol price)
"""
res = requests.get(url);
text = res... | b458dee9da7700f5c4f82a182724bba007c7a05f | 3,603,606 |
def sdc_pandas_dataframe_loc(self):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.loc
Limitations
-----------
- Loc always returns Dataframe.
- Parameter ``idx`` is supported only to be a single value, e.g. :o... | 6033e34cfa128da00af9dc1e37c8252d47242e2c | 3,603,607 |
def get_ast(module_path, python_version):
"""Get the AST for the code in a file.
Args:
module_path: pathlib.Path to the file containing the code.
python_version: Python version as a "MAJ.MIN" string.
Returns: The parso parse tree for the code in `module_path`.
"""
with module_path.... | b7bf0ebef52ac77f470378145938d954557f2a46 | 3,603,610 |
def formatPublisher(publisher):
"""The publisher's name. """
return publisher | 713cede34a67351d249439d83982331c60b26dcc | 3,603,611 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.