content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import gc
def test_harvest_lost_resources(pool):
"""Test unreferenced resources are returned to the pool."""
def get_resource_id():
"""
Ensures ``Resource`` falls out of scope before calling
``_harvest_lost_resources()``.
"""
return id(pool.get_resource()._resource)
... | 04b8b29520c2ae9c2c47cef412659e9c567c6a8a | 3,659,424 |
def __call__for_keras_init_v1(self, shape, dtype=None, partition_info=None):
""" Making keras VarianceScaling initializers v1 support dynamic shape.
"""
if dtype is None:
dtype = self.dtype
scale = self.scale
scale_shape = shape
if partition_info is not None:
scale_shape = partition_info.full_shape
... | 860dc27ecd133b5bb193c4856736f9bb1a52d243 | 3,659,425 |
def create_line(net, from_bus, to_bus, length_km, std_type, name=None, index=None, geodata=None,
df=1., parallel=1, in_service=True, max_loading_percent=nan):
""" create_line(net, from_bus, to_bus, length_km, std_type, name=None, index=None, \
geodata=None, df=1., parallel=1, in_serv... | 218a3a16bce0d746465991c0992f614bddf98892 | 3,659,426 |
def get_initmap(X, A=None, standardize=False, cov_func=None):
""" Give back parameters such that we have the L U decomposition of the
product with A (if given, or the PCA scores if not).
That is we will get back:
X[:, perm]*L*U + b = ((X-meanvec)/stdvec)*A
where A are PCA directions if not g... | 53ec26f8efe4c0869b4e4423419db32ed08128e0 | 3,659,427 |
def read_FQ_matlab(file_open):
""" Opens FISH-quant result files generated with Matlab (tab-delimited text file).
Args:
file_open (string): string containing the full file name.
Returns:
dictionary containing outlines of cells, and if present the detected spots.
"""
# Open file
... | 01c2c2263573e754c216c69496f648a883bb1843 | 3,659,428 |
def create_default_reporting_options(embedded=True, config={}):
"""
config must follow this scheme:
{
`table_name`: {
`option1`: `value1`
}
}
The different options will depend on the table role.
- for ALL tables:
{n
'data' : {
'remove_... | cc7d341a0d63979bbf3223a241c5707acf057547 | 3,659,429 |
def get_patient_note(state, patient_id, note_id, *args, **kwargs):
"""
Return a note for a patient.
---
tags: ["FHIR"]
parameters:
- name: patient_id
in: path
description: ID of the patient of interest
required: true
schema:
type: string
... | 399212c31d2ae34b96a5617ca73063745c22621c | 3,659,430 |
def _html_build_item(tag: str, text: str, attributes: map = None, include_tags=True) -> str:
"""Builds an HTML inline element and returns the HTML output.
:param str tag: the HTML tag
:param str text: the text between the HTML tags
:param map attributes: map of attributes
:param bool include_ta... | 13b165a98679c2ebaf9a1dec7619a3297c729a63 | 3,659,431 |
from typing import Dict
from typing import Optional
import random
def sim_sample(
out_prefix: str,
sample_id: int,
chrom_start: int = 0,
chrom_end: int = 10000,
start_rate: float = 0.001,
end_rate: float = 0.01,
mut_rate: float = 0.01,
) -> Dict[str, File]:
"""
Simulate sequencing ... | d8a858b3f8099dd57cdc7abb4f1473e238038536 | 3,659,432 |
def vif_col(X, y, col_name):
"""计算vif
计算具体一个column的vif,
一般阈值在5或者10,超过这个数字则表明有
共线性。
Attributes:
X (pd.DataFrame): 自变量
y (pd.Series): 因变量
col_name (str): 需要判断的列
References:
James, Gareth, Daniela Witten, Trevor Hastie, and Robert Tibshirani.
An Introduct... | 6d9c88d928934d60182b597a89c6da6d1f7d1194 | 3,659,433 |
def get_mesh_stat(stat_id_start_str, attr_value, xmin, ymin, xmax, ymax):
"""
地域メッシュの統計情報を取得する
@param stat_id_start_str 統計IDの開始文字 この文字から始まるIDをすべて取得する.
@param attr_value cat01において絞り込む値
@param xmin 取得範囲
@param ymin 取得範囲
@param xmax 取得範囲
@param ymax 取得範囲
"""
rows = database_proxy.ge... | 9a861925436c2cf10eb4773be9dfa79c901d43f4 | 3,659,434 |
def babel_extract(fileobj, keywords, comment_tags, options):
"""Babel extraction method for Jinja templates.
.. versionchanged:: 2.3
Basic support for translation comments was added. If `comment_tags`
is now set to a list of keywords for extraction, the extractor will
try to find the best... | 35ee7c05ee91afc1ccf7c752bdff72e3c3d30d78 | 3,659,435 |
import numpy
def onedthreegaussian(x, H, A1, dx1, w1, A2, dx2, w2, A3, dx3, w3):
"""
Returns two 1-dimensional gaussian of form
H+A*numpy.exp(-(x-dx)**2/(2*w**2))
"""
g1 = A1 * numpy.exp(-(x-dx1)**2 / (2*w1**2))
g2 = A2 * numpy.exp(-(x-dx2)**2 / (2*w2**2))
g3 = A3 * numpy.exp(-(x-dx3)**2 /... | f93ea1339fe1498fdaeaee91f75b7ba316455646 | 3,659,437 |
from typing import Optional
from typing import Union
def confusion_matrix_by_prob(true: np.ndarray,
predicted_prob: np.ndarray,
thresholds: Optional[Union[list, tuple, np.ndarray]] = None,
pos_label: Union[bool, str, int] = _DEFAUL... | 29bc8808ae1f35f13e52ac26e4e1993c423c6dc6 | 3,659,439 |
from typing import Sequence
from typing import Mapping
import itertools
def group_slaves_by_key_func(
key_func: _GenericNodeGroupingFunctionT,
slaves: Sequence[_GenericNodeT],
sort_func: _GenericNodeSortFunctionT = None,
) -> Mapping[_KeyFuncRetT, Sequence[_GenericNodeT]]:
""" Given a function for gro... | c3e286d2ff618758cd86c16f1b6685faea4b4d7a | 3,659,440 |
def init_clfs():
""" init classifiers to train
Returns:
dict, clfs
"""
clfs = dict()
# clfs['xgb'] = XGBClassifier(n_jobs=-1)
clfs['lsvc'] = LinearSVC()
return clfs | 4725656eda4e6991cc215bcd5a209ff23171eea6 | 3,659,441 |
def get_field_types():
"""Get a dict with all registration field types."""
return get_field_definitions(RegistrationFormFieldBase) | a9fe05535a541a7a5ada74dc9138a6c2ab29f528 | 3,659,442 |
def get_md_links(filepath):
"""Get markdown links from a md file.
The links' order of appearance in the file IS preserved in the output.
This is to check for syntax of the format [...](...).
The returned 'links' inside the () are not checked for validity or
subtle differences (e.g. '/' vs no '/' at... | 3076f77802965cb281101530f4ab360e5996f627 | 3,659,443 |
def get_reactor_logs(project_id, application_id, api_key=None, **request_kwargs):
"""
Get the logs of a Reactor script.
:param project_id: The Project of the Application.
:type project_id: str
:param application_id: The Application to get the script logs for.
:type application_id: str
:para... | 82743619292f387708e7b1dc3fe93c59e232d1cf | 3,659,445 |
def summation_i_squared(n):
"""Summation without for loop"""
if not isinstance(n, int) or n < 1:
return None
return int(((n*(n+1)*(2*n+1))/6)) | dec0aba274bcaf3e3a821db5962af51d39835438 | 3,659,447 |
def str_to_number(this):
"""
Convert string to a Number
"""
try:
return mknumber(int(this.value))
except ValueError:
return mknumber(float(this.value)) | e67df9c0de5a5cdbc76a3026f7e31cd3190013c4 | 3,659,448 |
def plotTSNE(Xdata, target = None, useMulti=True, num=2500, savename=None, njobs=4, size=4, cmap=None, dim=(12,8)):
"""
Plot TSNE for training data
Inputs:
> Xdata: The training feature data (DataFrame)
> target: The training target data (Series)
> num (2500 by default): The number o... | 9751f861df2d67516e93218000d23e23ba0ad4fe | 3,659,450 |
def adjust_contrast(img, contrast_factor):
"""Adjust contrast of an Image.
Args:
img (PIL Image): PIL Image to be adjusted.
contrast_factor (float): How much to adjust the contrast. Can be any
non negative number. 0 gives a solid gray image, 1 gives the
original image while 2 increases the contr... | aedd8bb489df64138189626585228ffc086e2428 | 3,659,452 |
def matplotlib_view(gviz: Digraph):
"""
Views the diagram using Matplotlib
Parameters
---------------
gviz
Graphviz
"""
return gview.matplotlib_view(gviz) | 9eb0a686c6d01a7d24273bbbc6ddb9b4ee7cb9ac | 3,659,453 |
def shuf_repeat(lst, count):
""" Xiaolong's code expects LMDBs with the train list shuffled and
repeated, so creating that here to avoid multiple steps. """
final_list = []
ordering = range(len(lst))
for _ in range(count):
np.random.shuffle(ordering)
final_list += [lst[i] for i in or... | fea9478aaa37f5b1c58d4a41126055d9cfa4b035 | 3,659,454 |
def create_query(table_name, schema_dict):
"""
see datatypes documentation here:
https://www.postgresql.org/docs/11/datatype.html
"""
columns = db_schema[table_name]
return (
f"goodbooks_{table_name}",
[f"{column} {value}" for column, value in columns.items()],
) | 3b330d57f45ca053cfbe90952adc7aa1658ab76d | 3,659,455 |
import requests
def delete_repleciation(zfssrcfs, repel_uuid):
"""ZFS repleciation action status
accepts: An exsistng ZFS action uuid (id).
returns: the ZFS return status code.
"""
r = requests.delete(
"%s/api/storage/v1/replication/actions/%s"
% (url, repel_uuid), auth=zfsauth, ve... | f62ad1ec3e31ac7c54cf749982690631bb7b72d2 | 3,659,457 |
import aiohttp
def get_logged_in_session(websession: aiohttp.ClientSession) -> RenaultSession:
"""Get initialised RenaultSession."""
return RenaultSession(
websession=websession,
country=TEST_COUNTRY,
locale_details=TEST_LOCALE_DETAILS,
credential_store=get_logged_in_credential... | 87a5a439c5ca583c01151f340ce79f2f4a79558c | 3,659,459 |
def __getStationName(name, id):
"""Construct a station name."""
name = name.replace("Meetstation", "")
name = name.strip()
name += " (%s)" % id
return name | daab36ed8020536c8dd2c073c352634696a63f3e | 3,659,460 |
def post_url(url):
"""Post url argument type
:param str url: the post url
:rtype: str
:returns: the post url
"""
url = url.strip()
if len(url) == 0:
raise ArgumentTypeError("A url is required")
elif len(url) > Url.URL_LENGTH:
raise ArgumentTypeError("The url length is o... | 65d3c670580d6abfcfefcc8bcff35ca4e7d51f5c | 3,659,462 |
def create_planner(request):
"""Create a new planner and redirect to new planner page."""
user = request.user
plan = Plan.objects.create(author=user)
plan.save()
return HttpResponseRedirect(reverse('planner:edit_plan', args=[plan.id], )) | ab22dfa950208b44c308690dcff6e0f228faa406 | 3,659,463 |
def rule_matching_evaluation(df, model, seed_num, rein_num, eval_num, label_map, refer_label, lime_flag=True, scan_flag=False
, content_direction='forward', xcol_name='text', n_cores=20):
"""A integrated rule extraction, refinement and validation process.
On the dataset, sample base... | 9ed0d5653797544de384c41ef6d9e402d2a57403 | 3,659,464 |
def login():
""" Typical login page """
# if current user is already logged in, then don't log in again
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first... | e4114979a6b5b5845f32442bb66ee0798357f4e7 | 3,659,465 |
def create_timeperiod_map(
start: spec.Timestamp = None,
end: spec.Timestamp = None,
length: spec.Timelength = None,
) -> spec.TimeperiodMap:
"""create Timeperiod with representation TimeperiodMap
## Inputs
- start: Timestamp
- end: Timestamp
- length: Timelength
## Returns
- T... | c8087ea252e86b97c55376bfb21b93c2b50e3b19 | 3,659,466 |
import requests
async def patched_send_async(self, *args, **kwargs):
"""Patched send function that push to queue idx of server to which request is routed."""
buf = args[0]
if buf and len(buf) >= 6:
op_code = int.from_bytes(buf[4:6], byteorder=PROTOCOL_BYTE_ORDER)
# Filter only caches opera... | c78c9b437547266b4bfa82627c45e3c7c6450049 | 3,659,467 |
from datetime import datetime
def add_event_records(df, event_type, event_date):
"""Add event records for the event type."""
log(f'Adding {DATASET_ID} event records for {event_type}')
this_year = datetime.now().year
df = df.loc[df[event_date].notnull(), :].copy()
df['event_id'] = db.create_ids(df,... | d3e804d9b24274e5a87e1e470f1f758214e1f805 | 3,659,468 |
def _renderPath(path,drawFuncs,countOnly=False,forceClose=False):
"""Helper function for renderers."""
# this could be a method of Path...
points = path.points
i = 0
hadClosePath = 0
hadMoveTo = 0
active = not countOnly
for op in path.operators:
if op == _MOVETO:
if f... | 17a2fc3224b2ba80de9dee0110468c4d934281b7 | 3,659,469 |
def _search_focus(s, code=None):
""" Search for a particular module / presentation.
The search should return only a single item. """
if not code:
code = input("Module code (e.g. TM129-17J): ")
results = _search_by_code(s, code)
if not len(results):
print('Nothing found for "{}"... | 8eec36dbe48c1825d742c9834776a7a0705429b6 | 3,659,470 |
def parse_line(sample):
"""Parse an ndjson line and return ink (as np array) and classname."""
class_name = sample["word"]
inkarray = sample["drawing"]
stroke_lengths = [len(stroke[0]) for stroke in inkarray]
total_points = sum(stroke_lengths)
np_ink = np.zeros((total_points, 3), dtype=np.float3... | 19d20f7e67b58d699c0aea47f1f03095a957f757 | 3,659,471 |
def evalRPN(self, tokens):
# ! 求解逆波兰式,主要利用栈
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for item in tokens:
# print(stack)
if item.isdigit():
stack.append(int(item))
if item[0] == '-' and len(item) > 1 and item[1:].isdigit():
stack... | 6b2050f6f635324878116371cd81a6d25ea31240 | 3,659,472 |
def _validate_flags():
"""Returns True if flag values are valid or prints error and returns False."""
if FLAGS.list_ports:
print("Input ports: '%s'" % (
"', '".join(midi_hub.get_available_input_ports())))
print("Ouput ports: '%s'" % (
"', '".join(midi_hub.get_available_output_ports())))
... | 812791a8c71cc354a1ebe32f3fa9a3cc0f1c0182 | 3,659,473 |
def proto_test(test):
"""
If test is a ProtoTest, I just return it. Otherwise I create a ProtoTest
out of test and return it.
"""
if isinstance(test, ProtoTest):
return test
else:
return ProtoTest(test) | 3326ea07ae5e4f90d3ae49cedee7b16aa97a3c65 | 3,659,474 |
def get_frames():
"""Get frames for an episode
Params:
episode: int
The episode for which the frames shall be returned
Returns:
frames: dict
The frames for an episode per timestep
"""
episode = int(request.args.get('user'))
frames = data_preprocessor.get_f... | 1180c38175ef07f5e58ce8b77d748f6c1c1ab17b | 3,659,475 |
def remove(s1,s2):
"""
Returns a copy of s, with all characters in s2 removed.
Examples:
remove('abc','ab') returns 'c'
remove('abc','xy') returns 'abc'
remove('hello world','ol') returns 'he wrd'
Parameter s1: the string to copy
Precondition: s1 is a string
Parameter ... | 089107767063309d1cc34360ae290e7fa74133e7 | 3,659,476 |
def get_issuer_plan_ids(issuer):
"""Given an issuer id, return all of the plan ids registered to that issuer."""
df = pd.read_csv(PATH_TO_PLANS)
df = df[df.IssuerId.astype(str) == issuer]
return set(df.StandardComponentId.unique()) | b41b36b70000736acde63673961f92231a62f9a4 | 3,659,478 |
def parse_coords(lines):
"""Parse skbio's ordination results file into coords, labels, eigvals,
pct_explained.
Returns:
- list of sample labels in order
- array of coords (rows = samples, cols = axes in descending order)
- list of eigenvalues
- list of percent variance explained
F... | fec53839f5f995f94f07120cac5bab1ba66f7b4c | 3,659,480 |
def run_ann(model, train, test, params_save_path, iteration, optimizer, loss, callbacks=None, valid=None,
shuffle_training=True,
batch_size=16,
num_epochs=30):
"""
Run analog network with cross-validation
:param batch_size: batch size during training
:param model: ref... | 9df68d8c6cdf6df08177bd1cc5d3116c10ae073e | 3,659,481 |
def get_sector(session, sector_name=None, sector_id=None):
""" Get a sector by it's name or id. """
return get_by_name_or_id(session, Sector, model_id=sector_id, name=sector_name) | 69de99bbdd630fb0cc5412c2b3124dff819287ed | 3,659,482 |
def is_valid_pre_6_2_version(xml):
"""Returns whether the given XML object corresponds to an XML output file of Quantum ESPRESSO pw.x pre v6.2
:param xml: a parsed XML output file
:return: boolean, True when the XML was produced by Quantum ESPRESSO with the old XML format
"""
element_header = xml.f... | 80bda73addc68a88b2a1dc5828c0553cbaf7e6f2 | 3,659,483 |
import warnings
def exportdf (df =None, refout:str =None, to:str =None, savepath:str =None,
modname:str ='_wexported_', reset_index:bool =True):
"""
Export dataframe ``df`` to `refout` files. `refout` file can
be Excell sheet file or '.json' file. To get more details about
the `wr... | 0bc6d2750f236c5f3e529b2489be47658ddbf2d9 | 3,659,484 |
def clean_bpoa_seniority_list(csv):
"""Clean a digitized BPOA seniority list."""
dirty = pd.read_csv(csv)
clean = pd.DataFrame()
clean["job_title"] = dirty["Rank"]
clean["last_name"] = dirty["Last name"]
clean["first_name"] = dirty["First Name"]
clean = clean.apply(correct_name, axis=1)
... | b1af748d92c4cdced4a77fd3799dada318c0f57e | 3,659,485 |
def addMovieElement(findings, data):
""" Helper Function which handles unavailable information for each movie"""
if len(findings) != 0:
data.append(findings[0])
else:
data.append("")
return data | af3c45c8b8d4c0cb7ba1cac4925d0f5998affe93 | 3,659,487 |
from typing import Optional
def get_bst_using_min_and_max_value(preorder: list) -> Node:
"""
time complexity: O(n)
space complexity: O(n)
"""
def construct_tree(min_: int, max_: int) -> Optional[Node]:
nonlocal pre_index
nonlocal l
if pre_index >= l:
return No... | 809c74967e73c82a428f317d8551432bb392d5ea | 3,659,488 |
import math
def qwtStepSize(intervalSize, maxSteps, base):
"""this version often doesn't find the best ticks: f.e for 15: 5, 10"""
minStep = divideInterval(intervalSize, maxSteps, base)
if minStep != 0.0:
# # ticks per interval
numTicks = math.ceil(abs(intervalSize / minStep)) - 1
... | 57d1c4140e32dbf4a8bd0e306b9c10d4e9dae9bd | 3,659,489 |
def get_trimmed_glyph_name(gname, num):
"""
Glyph names cannot have more than 31 characters.
See https://docs.microsoft.com/en-us/typography/opentype/spec/...
recom#39post39-table
Trims an input string and appends a number to it.
"""
suffix = '_{}'.format(num)
return gname[:31... | a5e90163d15bd4fc0b315414fffd2ac227768ab0 | 3,659,490 |
def vmatrix(ddir, file_prefix):
""" generate vmatrix DataFile
"""
name = autofile.name.vmatrix(file_prefix)
writer_ = autofile.write.vmatrix
reader_ = autofile.read.vmatrix
return factory.DataFile(ddir=ddir, name=name,
writer_=writer_, reader_=reader_) | b9303e08f10e0604fde7b40116b74e66aac553dc | 3,659,491 |
import ast
from typing import Callable
from typing import MutableMapping
from typing import Union
import inspect
def get_argument_sources(
source: Source,
node: ast.Call,
func: Callable,
vars_only: bool,
pos_only: bool
) -> MutableMapping[str, Union[ast.AST, str]]:
"""Get t... | 1ab344b5ccf9754ade06210e74540db51fe8c671 | 3,659,493 |
def rivers_by_station_number(stations,N):
"""function that uses stations_by_rivers to return a dictionary that it then
itterates each river for, summing the number of stations on the river into tuples"""
stationsOfRivers = stations_by_rivers(stations)
listOfNumberStations = []
for river in stationsO... | ca159843f10cbadf5a35529c45656121672972e0 | 3,659,495 |
import itertools
def generate_itoa_dict(
bucket_values=[-0.33, 0, 0.33], valid_movement_direction=[1, 1, 1, 1]):
"""
Set cartesian product to generate action combination
spaces for the fetch environments
valid_movement_direction: To set
"""
action_space_extended = [bucket_values if... | b8264174857aeb9d64226cce1cd1625f7e65b726 | 3,659,496 |
import dateutil
from datetime import datetime
def try_convert(value, datetime_to_ms=False, precise=False):
"""Convert a str into more useful python type (datetime, float, int, bool), if possible
Some precision may be lost (e.g. Decimal converted to a float)
>>> try_convert('false')
False
>>> try... | 59f8a16310e4ac6604a145dcff1ff390df259da9 | 3,659,497 |
def signin(request, auth_form=AuthenticationForm,
template_name='accounts/signin_form.html',
redirect_field_name=REDIRECT_FIELD_NAME,
redirect_signin_function=signin_redirect, extra_context=None):
"""
Signin using email or username with password.
Signs a user in by combinin... | 6a8536fb3a0c551ae4cdb7f01de622c012d0734c | 3,659,498 |
import random
def run_syncdb(database_info):
"""Make sure that the database tables are created.
database_info -- a dictionary specifying the database info as dictated by Django;
if None then the default database is used
Return the identifier the import process should use.
"""
... | 19da3e97226363fbee885ff8ee24c7abe0489d3c | 3,659,499 |
def autoclean_cv(training_dataframe, testing_dataframe, drop_nans=False, copy=False,
encoder=None, encoder_kwargs=None, ignore_update_check=False):
"""Performs a series of automated data cleaning transformations on the provided training and testing data sets
Unlike `autoclean()`, this function... | 37b8221193c05db97dde355e06313a9372cd8193 | 3,659,500 |
import asyncio
def make_coroutine_from_tree(tree, filename="<aexec>", symbol="single",
local={}):
"""Make a coroutine from a tree structure."""
dct = {}
tree.body[0].args.args = list(map(make_arg, local))
exec(compile(tree, filename, symbol), dct)
return asyncio.corout... | cbf4e0b0278abc0e929f4ed8b2a9c421b4e8f3c6 | 3,659,501 |
def update_Sigmai(Yi, Es, Vars):
"""
Return new Sigma_i: shape k
"""
return np.mean((Yi - Es) ** 2, axis=1) + np.mean(Vars, axis=1) | f2cb1fa7f5e6b48f033207ee6bb84b8e865c863c | 3,659,502 |
def gather_indexes(sequence_tensor, positions):
"""Gathers the vectors at the specific positions over a minibatch."""
sequence_shape = get_shape_list(sequence_tensor, expected_rank=3)
batch_size = sequence_shape[0]
seq_length = sequence_shape[1]
width = sequence_shape[2]
flat_offsets = tf.resha... | 583ed7ce925ace45dd2a6c9a78efd0360bd141e0 | 3,659,503 |
import typing
def check_sub_schema_dict(sub_schema: typing.Any) -> dict:
"""Check that a sub schema in an allOf is a dict."""
if not isinstance(sub_schema, dict):
raise exceptions.MalformedSchemaError(
"The elements of allOf must be dictionaries."
)
return sub_schema | b64313b28ab63b8342de7b0422cc8c9087a28462 | 3,659,504 |
def get_proto_root(workspace_root):
"""Gets the root protobuf directory.
Args:
workspace_root: context.label.workspace_root
Returns:
The directory relative to which generated include paths should be.
"""
if workspace_root:
return "/{}".format(workspace_root)
else:
r... | 35cff0b28ee6c1893e5dba93593126c996ba72cc | 3,659,505 |
def bwimcp(J, K, x, tr=.2, alpha=.05):
"""
Multiple comparisons for interactions
in a split-plot design.
The analysis is done by taking difference scores
among all pairs of dependent groups and
determining which of
these differences differ across levels of Factor A
using trimmed means. ... | 82d2b77464e5bc37fc101624ed0d88205ab11ff9 | 3,659,506 |
def trigger_decoder(mode: str, trigger_path: str=None) -> tuple:
"""Trigger Decoder.
Given a mode of operation (calibration, copy phrase, etc) and
a path to the trigger location (*.txt file), this function
will split into symbols (A, ..., Z), timing info (32.222), and
targetness (target... | e4d19203e655173f638dc38c0123f88c7342aed1 | 3,659,507 |
def method_comparison(filename=None, extension="png", usetex=False,
passed_ax=None, **kwargs):
"""
Create a plot comparing how estimated redshift changes as a
function of dispersion measure for each DM-z relation.
Parameters
----------
filename: string or None, optional
... | 8c3714cca3aac5f0f7893dc981b68265bf6cea9f | 3,659,508 |
def logCompression(pilImg):
"""Does log compression processing on a photo
Args:
pilImg (PIL Image format image): Image to be processed
"""
npImg = PILtoNumpy(pilImg)
c = 255 / (np.log10(1 + np.amax(npImg)))
for all_pixels in np.nditer(npImg, op_flags=['readwrite']):
all_pixels[.... | d6ab559182e7c836823d4c51fb6af395c1cd875f | 3,659,509 |
def quantile_turnover(quantile_factor, quantile, period=1):
"""
Computes the proportion of names in a factor quantile that were
not in that quantile in the previous period.
Parameters
----------
quantile_factor : pd.Series
DataFrame with date, asset and factor quantile.
quantile : i... | 6c7b2afdd4c4f0a2dbf38064d2d8664a25370ca2 | 3,659,510 |
def dmp_div(f, g, u, K):
"""
Polynomial division with remainder in ``K[X]``.
Examples
========
>>> from sympy.polys import ring, ZZ, QQ
>>> R, x,y = ring("x,y", ZZ)
>>> R.dmp_div(x**2 + x*y, 2*x + 2)
(0, x**2 + x*y)
>>> R, x,y = ring("x,y", QQ)
>>> R.dmp_div(x**2 + x*y, 2*x +... | 1b8f2b2b9d57899862234233a70e7e76100b86be | 3,659,511 |
def is_designated_holiday(timestamp):
"""
Returns True if the date is one of Piedmont’s "designated holidays":
- New Years Day (January 1st)
- Memorial Day (last Monday of May)
- Independence Day (July 4th)
- Labor Day (First Monday of September)
- Thanksgiving Day (4th Thursday in November)... | e6137ac2c3258a3e51294ff432971c04f56137ec | 3,659,512 |
def check(val, desc=None, as_warn=False) -> SimpleAssertions:
"""
function based assertion call
:param val: val to check
:param desc: optional, description of val
:param as_warn: if set, convert assertion error to warning message
:return: assertionClass
"""
return SimpleAssertions(as_wa... | 2115a0b16387cea0fef483a26a6c27daaf72387e | 3,659,513 |
def ChangeExtension(filename, newExtension):
"""ChangeExtension(filename, newExtension) -> str
Replaces the extension of the filename with the given one.
If the given filename has no extension, the new extension is
simply appended.
arguments:
filename
string correspondi... | 0909060e01226520280aeabde906ab9a8f0dfc5d | 3,659,514 |
def file_based_input_fn_builder(input_file,
seq_length,
is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([se... | 733ddf8b7add0cf9c610537cab0c31172260f0de | 3,659,515 |
def synchrotron_thin_spectrum(freqs, ne, te, bfield):
"""Optically thin (unobsorbed) synchrotron spectrum.
Units of erg/cm^3/s/Hz
NY95b Eq 3.9
"""
const = 4.43e-30 # erg/cm^3/s/Hz
theta_e = K_BLTZ * te / (MELC * SPLC * SPLC)
v0 = QELC * bfield / (2*np.pi*MELC*SPLC)
xm = 2*freqs/(3*v0... | 1334cf0382eecd298472b4717b220a7ac3e96d0e | 3,659,516 |
import base64
def create_message(service, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
... | 6c6df7b1825c13cb8016840527b4dd81ac26d266 | 3,659,518 |
def numpy_ndarray(nb_arr):
"""Return a copy of numba DeviceNDArray data as a numpy.ndarray.
"""
return nb_arr.copy_to_host() | d6ee1c62428783344fe6232ef229a6dabc8f2a2f | 3,659,519 |
def convert_to_dict(my_keys, my_values):
"""Merge a given list of keys and a list of values into a dictionary.
Args:
my_keys (list): A list of keys
my_values (list): A list corresponding values
Returns:
Dict: Dictionary of the list of keys mapped to the list of values
"""
... | e00690d27770539e6b9d2166835f6bd1b9c11c5a | 3,659,520 |
def add_vit(request):
"""
Add a new vit with API, currently image and video are not supported
"""
user = KeyBackend().authenticate(request)
if request.method == "POST":
if request.user.is_authenticated:
form = VitForm(request.POST)
if form.is_valid():
... | 726776e036678cb79051d6ac800d5d883b947320 | 3,659,521 |
def long_control_state_trans(active, long_control_state, v_ego, v_target, v_pid,
output_gb, brake_pressed, cruise_standstill, min_speed_can):
"""Update longitudinal control state machine"""
stopping_target_speed = min_speed_can + STOPPING_TARGET_SPEED_OFFSET
stopping_condition = (v_eg... | f13a5db692ce92fe36204eade10ebb2d54b9caed | 3,659,522 |
def load_group_to_namedtuple(group: h5py.Group):
"""Returns namedtuple with name of group and key: values of group attrs
e.g. srs1 group which has gpib: 1... will be returned as an srs1 namedtuple with .gpib etc
"""
# Check it was stored as a namedTuple
if group.attrs.get('description', None) != 'Na... | e33c0e1b367ddd2ebb745397d473c00452ba853f | 3,659,523 |
import json
def export_json(blocks=None, subsections=False):
"""
Returns JSON representation of parsed config structure
:param blocks: List of blocks to export
:param subsections: Export all subblocks
:return: JSON-dumped string
"""
if blocks is not None:
blocks = [_canonicalize_bl... | 90ae2ee10d6d23f091d079bd87478fa10d3a4083 | 3,659,524 |
def get_dummy_message(text):
"""Get a dummy message with a custom text"""
return botogram.objects.messages.Message({
"message_id": 1,
"from": {"id": 123, "first_name": "Nobody"},
"chat": {"id": -123, "type": "chat", "title": "Something"},
"date": 1,
"text": text,
}) | 0f39712381157b46aed345ef6b46c6b3cfe32d95 | 3,659,525 |
import time
def list_ga4_entities(admin_api):
"""Get a dictionary of GA4 entity settings based on type.
Args:
admin_api: The Admin API object.
Returns:
A dictionary of GA4 entity setting lists.
"""
entities = {
'ga4_account_summaries': [],
'ga4_accounts': [],
'ga4_properties': []... | 83b11c1a001a593da07f6aeb4333bad623bb7ee4 | 3,659,526 |
def print_sig(expr):
"""
Arguments:
- `expr`:
"""
return "{0!s} × {1!s}".format(expr.dom, expr.body) | be8d6fb1ad2256e2a825e383859f72db93318864 | 3,659,528 |
def is_grounded_concept(c: Concept) -> bool:
""" Check if a concept is grounded """
return (
"UN" in c.db_refs
and c.db_refs["UN"][0][0].split("/")[1] != "properties"
) | 2447b289cec20efc2aa359f37a795fd231004030 | 3,659,529 |
def _get_form(app, parent_form, factory_method, force_disable_csrf=False):
"""Create and fill a form."""
class AForm(parent_form):
pass
with app.test_request_context():
extra = _update_with_csrf_disabled() if force_disable_csrf else {}
RF = factory_method(AForm)
rf = RF(**... | b109d983dcf123812ede664719ab56f5462e84d4 | 3,659,530 |
def get_root_disk_size():
""" Get size of the root disk """
context = pyudev.Context()
rootfs_node = get_rootfs_node()
size_gib = 0
for device in context.list_devices(DEVTYPE='disk'):
# /dev/nvmeXn1 259 are for NVME devices
major = device['MAJOR']
if (major == '8' or major =... | 4c01e189dfb4460d118fbd9b94c6a07e420c3bb1 | 3,659,531 |
import numpy
def convert_to_premultiplied_png(file):
"""
http://stackoverflow.com/questions/6591361/method-for-converting-pngs-to-premultiplied-alpha
"""
logger.info("converting to premultiplied alpha")
im = Img.open(file).convert('RGBA')
a = numpy.fromstring(im.tobytes(), dtype=numpy.uint8)
... | 2a2ebf9e3d1152e2d143ba799aab0ff0927653a8 | 3,659,532 |
def DSQuery(dstype, objectname, attribute=None):
"""DirectoryServices query.
Args:
dstype: The type of objects to query. user, group.
objectname: the object to query.
attribute: the optional attribute to query.
Returns:
If an attribute is specified, the value of the attribute. Otherwise, the
... | 2dea68b5897a46c90d2f8cf24e42519c272e70f1 | 3,659,533 |
def calculate_offset(lon, first_element_value):
"""
Calculate the number of elements to roll the dataset by in order to have
longitude from within requested bounds.
:param lon: longitude coordinate of xarray dataset.
:param first_element_value: the value of the first element of the longitude array ... | a55eee1dd11b1b052d67ab1abadfc8087c1a2fe0 | 3,659,534 |
def min_mean_col(m: ma.MaskedArray) -> int:
"""Calculate the index of the column with the smallest mean.
"""
if ma.count_masked(m) == m.size:
return -1
col_mean = np.nanmean(m, axis=0)
return np.argmin(col_mean) | 499b7d5db38edc222aac6517d87d9df30285cb37 | 3,659,535 |
def test_data_alignment(role_value, should_pass, check_model):
"""Test a custom model which returns a good and alignments from data().
qtmodeltest should capture this problem and fail when that happens.
"""
class MyModel(qt_api.QAbstractListModel):
def rowCount(self, parent=qt_api.QtCore.QModel... | 4ebed3384cf5c694d72235e703b6f9594de5ff7b | 3,659,539 |
def cov(a, b):
"""Return the sample covariance of vectors a and b"""
a = flex.double(a)
b = flex.double(b)
n = len(a)
assert n == len(b)
resid_a = a - flex.mean(a)
resid_b = b - flex.mean(b)
return flex.sum(resid_a*resid_b) / (n - 1) | 94505852671e4652f96daa7b8e61f759aeca1dda | 3,659,540 |
from bs4 import BeautifulSoup
import re
def beautify(soup: BeautifulSoup, rich_terminal: bool = True) -> str:
"""
Cleans up the raw HTML so it's more presentable.
Parse BeautifulSoup HTML and return prettified string
"""
beautifiedText = str()
for i in soup:
if rich_terminal:
... | df79666ad0ec9592e1a24325813b59e2d9711636 | 3,659,541 |
def design_complexity(design: Design) -> int:
"""Returns an approximation of the design's complexity to create."""
diversity = 3 * len(design.required)
abundance = 2 * sum(design.required.values())
return diversity + abundance + design.additional | b5be6336ce037d010bbb274dc6ce5538ac6ecae8 | 3,659,542 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.