content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def ruru_old_log_checker(s):
"""
古いログ形式ならTrue、そうでないならFalseを返す
:param s:
:return:
"""
time_data_regex = r'[0-9]{4}\/[0-9]{2}\/[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}'
# るる鯖新ログ形式なら1つ目のdiv:d12150で時刻が取得可能。そうでないなら取得不可
time_data = re.search(time_data_regex, str(s.find('div', class_='d... | 54f6a94dab98ef6947496b8e1f95401d99424ee2 | 2,500 |
def get_user_map_best(beatmap_id, user, enabled_mods=0):
"""
gets users best play on map
:param beatmap_id: beatmap id
:param user: username
:param enabled_mods: mods used
:return: list of plays
"""
response = OSU_API.get('/get_scores', {"b": beatmap_id, "u": user, "mods": enabled_mods}... | 545ede7ef7d1133bbbcab9640a9e3edcdcca111f | 2,501 |
def scale_z_by_atom(z, scale, copy=True):
"""
Parameters
----------
z_ : array, shape (n_trials, n_atoms, n_times - n_times_atom + 1)
Can also be a list of n_trials LIL-sparse matrix of shape
(n_atoms, n_times - n_times_atom + 1)
The sparse activation matrix.
scale : arra... | b87368c1ea8dcd18fcbfd85ef8cde5450d5fcf33 | 2,502 |
def index():
"""
example action using the internationalization operator T and flash
rendered by views/default/index.html or views/generic.html
if you need a simple wiki simply replace the two lines below with:
return auth.wiki()
"""
if auth.is_logged_in():
# # if newly registered us... | d48d29ee65ddf064dc2f424f2be9f46da23cbd4a | 2,503 |
def compute_classification_metrics_at_ks(is_match, num_predictions, num_trgs, k_list=[5,10], meng_rui_precision=False):
"""
:param is_match: a boolean np array with size [num_predictions]
:param predicted_list:
:param true_list:
:param topk:
:return: {'precision@%d' % topk: precision_k, 'recall@... | 189a6491e1b5d8e3bf8869586b69667eb1b9d9c9 | 2,504 |
def coordinatesOfPosition(shape, distance):
"""Compute the point at a given distance from the beginning of a shape.
The shape is a list of points. A point is a sequence of two floats.
The returned point is the x- and y-coordinate of the point that has
the given distance along the line of the shape... | 7ae8c53468d5c8be8fe2daca1d0dfe358ad6c24e | 2,505 |
def compute_dose_median_scores(null_dist_medians, dose_list):
"""
Align median scores per dose, this function return a dictionary,
with keys as dose numbers and values as all median scores for each dose
"""
median_scores_per_dose = {}
for dose in dose_list:
median_list = []
for ... | ec23f186c10a6921cdae9d4965a51343dc78011e | 2,506 |
def generate_converter(name, taskdep, **options) :
"""
taskdep 是执行该程序之前应该执行的任务
task_html_generator 表示的是能够生成html的任务,我们需要从这个任务中提取result
taskname是生成的任务名
"""
converter = options.get('converter',
Pandoc("-f", "html", "-t", "markdown", "--wrap=none"))
flowdep = options.g... | 3e60abfcdabfb0c35ff8b9692b21b27af2300da8 | 2,507 |
def symmetric_product(tensor):
"""
Symmetric outer product of tensor
"""
shape = tensor.size()
idx = list(range(len(shape)))
idx[-1], idx[-2] = idx[-2], idx[-1]
return 0.5 * (tensor + tensor.permute(*idx)) | 4f96ab5f0bd41080352b1e5e806b6a73b3506950 | 2,508 |
import torch
def prep_image(img, inp_dim):
"""
Function:
Prepare image for inputting to the neural network.
Arguments:
img -- image it self
inp_dim -- dimension for resize the image (input dimension)
Return:
img -- image after preparing
"""
... | 4f32717cb06b32cab2e0b92d3a24a9a665baf27b | 2,509 |
async def auth_check(request):
"""
No-op view to set the session cookie, this is used by websocket since the "Set-Cookie" header
doesn't work with 101 upgrade
"""
return json_response(status='ok') | 60419c8d32bbc41525ebf44d4d7bcabe8a117df0 | 2,510 |
def check_constraint(term_freq,top_terms,top_terms_test_freq):
"""
Check the constraint 12%-30% for the test set
term_freq is the dictionnary of all term frequencies
top_terms is the list of terms we care about (first 300?)
top_terms_freq is an array of frequency of top terms in test set.
RETURN... | d2b31c68d1a8cd1a7d8471818cc46de943496aaa | 2,511 |
import os
def create_LSTM_model(patient_idx, time_steps, save_model=False, plot_loss=False):
"""
Trains an LSTM model over a patient
@param patient_idx: number
@param time_steps: number of concatenated heartbeats per datapoint
@param save_model: whether to save the model to h5 file
@param plot... | 8a32e6106602f949000c57445317d7f0ec83102b | 2,512 |
def get_supported_providers() -> list[str]:
"""
Return the list of supported discussion providers
TODO: Load this from entry points?
"""
providers = [
'legacy',
'piazza',
]
return providers | bea650b51447734ae83949f0d792f850aa3d0aa3 | 2,513 |
import pytz
def predict_split(history, prediction_length=7*24, hyperparameters={}):
"""
This function predicts a time series of gas prices by splitting it into a
tren and a residual and then applying a feature pipeline and predicting
each of them individually.
Keyword arguments:
history -- th... | 025d4b753754ad18a04b46f95002f9ab54ccd9bd | 2,514 |
def SFRfromLFIR(LFIR):
"""
Kennicut 1998
To get Star formation rate from LFIR (8-1000um)
LFIR in erg s-1
SFR in Msun /year
"""
SFR = 4.5E-44 * LFIR
return SFR | 4adf401bbf2c6547cea817b52eb881531db8c798 | 2,515 |
def inc_group_layers(n_list, d_list, c_list):
"""
Helper function for inc_tmm. Groups and sorts layer information.
See coh_tmm for definitions of n_list, d_list.
c_list is "coherency list". Each entry should be 'i' for incoherent or 'c'
for 'coherent'.
A "stack" is a group of one or more cons... | 1b25975169839e54feae58f98b5de98916c51541 | 2,516 |
def get_heater_device_json():
""" returns information about the heater in json """
return '{\n "state" : "' + _pretty_state_identifier(brew_logic.heater_state) + '",\n "overridden" : "' + str(brew_logic.heater_override).lower() + '"\n }' | 3997e9eee7cbb058adf4900b571c8458e2464e19 | 2,517 |
def rfc_deploy():
"""This function trains a Random Forest classifier and outputs the
out-of-sample performance from the validation and test sets
"""
df = pd.DataFrame()
for pair in pairs:
# retrieving the data and preparing the features
dataset = gen_feat(pair)
dataset.drop(['Open', 'High', '... | 86c4aa5f44d23cce83f6cc9993c0e10cd124c423 | 2,518 |
def get_block(block_name):
"""Get block from BLOCK_REGISTRY based on block_name."""
if not block_name in BLOCK_REGISTRY:
raise Exception(NO_BLOCK_ERR.format(
block_name, BLOCK_REGISTRY.keys()))
block = BLOCK_REGISTRY[block_name]
return block | 10b86c5045496a865907ef2617b2994d03f1312d | 2,519 |
from pathlib import Path
import yaml
def _determine_role_name(var_file: Path) -> str:
"""
Lookup role name from directory or galaxy_info.
"""
if var_file.is_file():
role_path: Path = var_file.parent / ".."
name = str(role_path.resolve().name)
meta_path: Path = role_path / 'meta... | 59e6d60234cc7988fe6c3005176f1c89cac5b60d | 2,520 |
import six
import os
def load_table(file_path, metadata_ext='.pklmetadata'):
"""
Loads a pickled DataFrame from a file along with its metadata.
This function loads a DataFrame from a file stored in pickle format.
Further, this function looks for a metadata file with the same file name
but with a... | ca931b895474e83877d17ca4a9e4054a595acf40 | 2,521 |
import os
import uvicorn
import logging
def main() -> int:
"""Ensure runtime environment is ready, and start the server."""
app.utils.setup_runtime_environment()
for safety_check in (
app.utils.ensure_supported_platform, # linux only at the moment
app.utils.ensure_local_services_are_runn... | 6aa408cc6e3ef223a63ca073ddad3b3e5325df85 | 2,522 |
def coco17_category_info(with_background=True):
"""
Get class id to category id map and category id
to category name map of COCO2017 dataset
Args:
with_background (bool, default True):
whether load background as class 0.
"""
clsid2catid = {
1: 1,
2: 2,
... | f64be8c09b3372ad75826a6bfdc8a2f0bc4f9e25 | 2,523 |
def _parse_parameters(paramdoc):
"""Parse parameters and return list of (name, full_doc_string)
It is needed to remove multiple entries for the same parameter
like it could be with adding parameters from the parent class
It assumes that previously parameters were unwrapped, so their
documentation ... | 0a580476cf7aa7c84f2081af7b3bbc224f9c3390 | 2,524 |
def example_miller_set(example_crystal):
"""Generate an example miller set."""
ms = miller.set(
crystal_symmetry=example_crystal.get_crystal_symmetry(),
indices=flex.miller_index([(1, 1, 1)] * 8 + [(2, 2, 2)]),
anomalous_flag=False,
)
return ms | 516eca404544d8f8af8dd664488006c67bef03b8 | 2,525 |
async def get(req):
"""
Get a complete analysis document.
"""
db = req.app["db"]
analysis_id = req.match_info["analysis_id"]
document = await db.analyses.find_one(analysis_id)
if document is None:
return not_found()
sample = await db.samples.find_one({"_id": document["sample... | e52598d27b73dd9ef5d24aba196f97f85fb47214 | 2,526 |
from typing import Union
from typing import Mapping
from typing import Any
def get_cube_point_indexes(cube: xr.Dataset,
points: Union[xr.Dataset, pd.DataFrame, Mapping[str, Any]],
dim_name_mapping: Mapping[str, str] = None,
index_name_pa... | b1f5eb134ab7119589b54c45b95065c2f57348dc | 2,527 |
def auto_add():
"""
自动添加
1 查找所有amis文件
2 更新记录
3 记录按照app组织,生成dict
4 为每个app生成auto_urls.py
:return:
"""
amis_json_file_list = get_amis_files()
cnt = update_rcd(amis_json_file_list)
aml_app_dict = get_rcd_by_app_name()
add_needed_auto_urls(aml_app_dict)
add_urls_needed(... | 17b6026f56793f3a6f76446145b7f65a6fe29a5a | 2,528 |
from pathlib import Path
from typing import Optional
def _get_configs(cli_args: CLIArgs, project_root: Path) -> Configs:
"""
Deal with extra configs for 3rd party tool.
Parameters
----------
cli_args
Commandline arguments passed to nbqa
project_root
Root of repository, where .... | d9ef190a99b06f2d17bbc336ace86061ea215d97 | 2,529 |
import os
def run_gx_test(dataset_path, output_dir, dist_types, ex_config, mp_args):
"""
The start and end parameter together make an interval that contains the datasets to be included in this experiment
:param mp_args: the configuration of the multiprocess backend,
go to this site https://doc... | 4d581dfc979a02d429ac02156e0b7b6cf3d108b5 | 2,530 |
import os
import ctypes
def _load_lib():
"""Load libary in build/lib."""
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
lib_path = os.path.join(curr_path, '../../build/lib/')
path_to_so_file = os.path.join(lib_path, "libc_runtime_api.so")
lib = ctypes.CDLL(path_to_so_fi... | e7f41afbad42ee485c3a65acc9c9d91f4ab56f97 | 2,531 |
from sklearn.preprocessing import RobustScaler
def robust_standardize(df: pd.DataFrame, excluded_colnames: list = None) -> pd.DataFrame:
"""
Applies the RobustScaler from the module sklearn.preprocessing by
removing the median and scaling the data according to the quantile
range (IQR). This transforma... | 0727ce390e773405a221c6fb3248ddd5d40445b2 | 2,532 |
import math
def meanStdDev( valueList, scale ):
"""Compute the mean and standard deviation of a *non-empty* list of numbers."""
numElements = len(valueList)
if numElements == 0:
return(None, 0.0)
mean = float(sum(valueList)) / numElements
variance = 0
for value in valueList:
variance += math.pow( value - ... | 2970ae1e4382092eb67219373aa26b9ca75226a3 | 2,533 |
def audience_filter(digest, audience):
"""Check whether the current audience level should include that digest."""
return get_split(
digest,
[
{
"key": "audience_{}".format(idx),
"size": 1.0
} for idx in range(0, 100)
]
) < audie... | 811e4e94e68901bfeaedabfec5e16a30de55408c | 2,534 |
def request_specific_data2num(batch_data):
"""
input: next_batch_requestable request_specific_data[slot].
change the data into processable type for tensorflow
:param batch_data: 一个 batch 的训练数据
:return: 直接输入request-specific tracker 模型计算的数据
"""
batchsize_request = len(batch_data)
x_usr = ... | e8a5b414f00e43755719dfadc0b089177cb67152 | 2,535 |
def points_from_x0y0x1y1(xyxy):
"""
Constructs a polygon representation from a rectangle described as a list [x0, y0, x1, y1]
"""
[x0, y0, x1, y1] = xyxy
return "%s,%s %s,%s %s,%s %s,%s" % (
x0, y0,
x1, y0,
x1, y1,
x0, y1
) | 8a7d766145dc31e6619b290b8d96a95983f9cc01 | 2,536 |
def get_columns(invoice_list, additional_table_columns):
"""return columns based on filters"""
columns = [
_("Invoice") + ":Link/Sales Invoice:120", _("Posting Date") + ":Date:80", _("Status") + "::80",
_("Customer") + ":Link/Customer:120", _("Sales Person") + ":Link/Sales Person:100",
_("AR Status") + "::75", ... | c9849e62d401ec5cc8de52d266a39eccf4b4dbe8 | 2,537 |
def one_norm(a):
"""
Return the one-norm of the matrix.
References:
[0] https://www.mathworks.com/help/dsp/ref/matrix1norm.html
Arguments:
a :: ndarray(N x N) - The matrix to compute the one norm of.
Returns:
one_norm_a :: float - The one norm of a.
"""
return anp.max(anp.... | c3e1c83d3776dda8ffa82b9b36d26866f390f6cc | 2,538 |
def remove_nan_inf(df, reindex=True):
"""
Removes all rows that have NaN, inf or -inf as a value, and then optionally
reindexes the dataframe.
Parameters
----------
df : pd.DataFrame
Dataframe to remove NaNs and Infs from.
reindex : bool, optional
Reindex the dataframe ... | 3b9339f2ee1315eac458925e5be5279e147d5c7d | 2,539 |
def contingency_table(seg, gt, ignore_seg=[0], ignore_gt=[0], norm=True):
"""Return the contingency table for all regions in matched segmentations.
Parameters
----------
seg : np.ndarray, int type, arbitrary shape
A candidate segmentation.
gt : np.ndarray, int type, same shape as `seg`
... | 47284bb5aaa492b6cbc50794c8ccd8a1e63676b4 | 2,540 |
def get_basic_track_info(track):
"""
Given a track object, return a dictionary of track name, artist name,
album name, track uri, and track id.
"""
# Remember that artist and album artist have different entries in the
# spotify track object.
name = track["name"]
artist = track['artists'... | 925f7bb00482e946ad7a6853bac8b243d24145c7 | 2,541 |
def demander_nombre(mini: int = None, maxi: int = None) -> int:
"""
Demande un nombre à l'utilisateur, situé entre min et max.
:param mini: le minimum
:param maxi: le maximum
:return: le nombre entrée par l'utilisateur
"""
message = 'Veuillez rentrer un nombre:'
if mini is not None and m... | ac5b949af1ad4ede2f956c7da5d4c2136dc47b15 | 2,542 |
from typing import OrderedDict
import yaml
def ordered_load(stream, merge_duplicate_keys=False):
"""
Parse the first YAML document in a stream and produce the corresponding
Python object, using OrderedDicts instead of dicts.
If merge_duplicate_keys is True, merge the values of duplicate mapping keys
... | d863d1026e1a8b1048668a6e9e95e732fc361ffa | 2,543 |
from datetime import datetime
def temporal_filter(record_date_time, time_or_period, op):
"""
Helper function to perform temporal filters on feature set
:param record_date_time: datetime field value of a feature
:type record_date_time: :class:`datetime.datetime`
:param time_or_period: the time ins... | 9f76d6a6eb96da9359c4bbb80f6cfb1dfdcb4159 | 2,544 |
from typing import Union
from pathlib import Path
import os
import shutil
def package_conda_env(folder: Union[str, Path]) -> Path:
"""Creates a .rar file of the current conda environment for use in jobs.
For efficiency, existing tarred env are not updated.
Parameter
---------
folder: str/Path
... | 6f711ef5fed7c81b87fee0b82d19f8ca660b8960 | 2,545 |
import os
def get_couchbase_superuser_password(manager, plaintext: bool = True) -> str:
"""Get Couchbase superuser's password from file (default to
``/etc/gluu/conf/couchbase_superuser_password``).
To change the location, simply pass ``GLUU_COUCHBASE_SUPERUSER_PASSWORD_FILE`` environment variable.
:... | 4103733c39c8ac63c022179a19ea988093380604 | 2,546 |
import sys
import os
def GetAvailableDialogs():
"""Returns available dialogs in a list"""
list_path = sys.path
found = 0
for i in range (0,len(list_path)):
if os.path.exists(list_path[i]+"/dialogs"):
found = 1
break
if found == 0:
print ("Could not find /di... | e5e0b5aeb8ff04b0c640527d8273fc443e046270 | 2,547 |
def convert_rgb2gray(image, convert_dic):
"""convert rgb image to grayscale
Parameters
----------
image: array
RGB image. Channel order should be RGB.
convert_dic: dict
dictionary key is str(rgb list), value is grayscale value
Returns
-------
image_gray: array
Grayscale im... | 0132719ef88d139d1d3da4e52312faef25443efd | 2,548 |
def get_external_storage_path():
"""Returns the external storage path for the current app."""
return _external_storage_path | a33704c5b3267a7211c94b5a3a8d8d73b3889d68 | 2,549 |
def blur(old_img):
"""
:param old_img: a original image
:return: a blurred image
"""
blur_img = SimpleImage.blank(old_img.width, old_img.height)
for x in range(old_img.width):
for y in range(old_img.height):
if x == 0 and y == 0: # Upper left cor... | 771a6e906ea8b485d4166de311c17a441f469158 | 2,550 |
import re
def generate_table_row(log_file, ancestry, official_only, code):
""" Takes an imported log and ancestry and converts it into a properly formatted pandas table.
Keyword arguments:
log_file -- output from import_log()
ancestry -- a single ancestry code
official_only -- a boolean indica... | c72bdef2aafbc15c54b80337c80f03ae8d8f1e00 | 2,551 |
def read_preflib_file(filename, setsize=1, relative_setsize=None, use_weights=False):
"""Reads a single preflib file (soi, toi, soc or toc).
Parameters:
filename: str
Name of the preflib file.
setsize: int
Number of top-ranked candidates that voters approve.
... | 6feec6e786e47cdc11021021ffa91a1f96597567 | 2,552 |
def get_row(client, instance, file_=None):
"""Get one row of a family table.
Args:
client (obj):
creopyson Client.
instance (str):
Instance name.
`file_` (str, optional):
File name. Defaults is currently active model.
Returns:
(dict):
... | c8e8c90a81d553d06ce9f78eb1be582e5b034ac6 | 2,553 |
def hospitalization_to_removed(clip_low=2, clip_high=32.6, mean=8.6, std=6.7):
"""
Returns the time for someone to either get removed after being
hospitalized in days within range(clip_low, clip_high),
of a truncated_norm(mean, std).
"""
return sample_truncated_norm(clip_low, clip_high, mean, st... | e1da5283e32b5734927436af72fdbd002c0844b1 | 2,554 |
def test_inheritance():
"""
test inheritance from different module
"""
# test module
test_data = doc.MatObject.matlabify('test_data')
test_submodule = test_data.getter('test_submodule')
sfdm = test_submodule.getter('super_from_diff_mod')
ok_(isinstance(sfdm, doc.MatClass))
eq_(sfdm.b... | 0f29de2ef67318010feed25ea0ffc08e2dc44162 | 2,555 |
from collections import Counter
def split_mon_unmon(data, labels):
"""
Splits into monitored and unmonitored data
If a data point only happens once, we also consider it unmonitored
@return monitored_data, monitored_label, unmonitored_data
"""
occurence = Counter(labels)
monitored_data, u... | b1d0cac2e12f4386bf04eb355811f230b18f38ca | 2,556 |
import contextlib
import os
def supress_stdout(func):
"""Wrapper, makes a function non-verbose.
Args:
func: function to be silenced
"""
def wrapper(*a, **ka):
with open(os.devnull, "w") as devnull:
with contextlib.redirect_stdout(devnull):
func(*a, **ka)
... | a617f776df873086c3033416f6ce7bc783fd640b | 2,557 |
def sum_and_count(x, y):
"""A function used for calculating the mean of a list from a reduce.
>>> from operator import truediv
>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> truediv(*reduce(sum_and_count, l)) == 20.11111111111111
True
>>> truediv(*fpartial(sum_and_count)(l)) == 20.11111111111111... | d43cc8dc39fb35afae4f6a4e32d34221d525f5d3 | 2,558 |
def animTempCustom():
"""
Temporarily play a custom animation for a set amount of time.
API should expect a full `desc` obect in json alongside a timelimit, in ms.
"""
colorList = request.form.get('colors').split(',')
colorsString = ""
for colorName in colorList:
c = Color(colorName... | 2d9cea92d7c1c93d73fcf9b325b7b58225b4ba13 | 2,559 |
from unittest.mock import Mock
def mock_stripe_invoice(monkeypatch):
"""Fixture to monkeypatch stripe.Invoice.* methods"""
mock = Mock()
monkeypatch.setattr(stripe, "Invoice", mock)
return mock | a88923ba6d4a6dda9bf3b2fcda3bb717efe36cee | 2,560 |
def read_project(output_dir):
"""Read existing project data
"""
try:
yaml = YAML()
with open(project_yaml_file(output_dir), encoding='utf-8') as project:
project_data = yaml.load(project)
for key, value in project_data.items():
if value == None:
... | 90cfd7d143176925d8a99f4d577bc7de9eb360e2 | 2,561 |
def bytes_to_int(byte_array: bytes) -> int:
""" Bytes to int """
return int.from_bytes(byte_array, byteorder='big') | 442452faeb1a4e7c346b6f4355095f179701f8f1 | 2,562 |
def ask(query, default=None):
"""Ask a question."""
if default:
default_q = ' [{0}]'.format(default)
else:
default_q = ''
inp = input("{query}{default_q}: ".format(query=query, default_q=default_q)).strip()
if inp or default is None:
return inp
else:
return defaul... | 54564ee00749ddb2e5c409d781552f3ca5fcd847 | 2,563 |
def _clean_kwargs(keep_name=False, **kwargs):
"""
Sanatize the arguments for use with shade
"""
if "name" in kwargs and not keep_name:
kwargs["name_or_id"] = kwargs.pop("name")
return __utils__["args.clean_kwargs"](**kwargs) | 326d849b030a11ebc21e364f6a05eef9ab019637 | 2,564 |
import os
def transfer_file(user, source_endpoint, source_path,
dest_endpoint, dest_path, label):
"""
:param user: Must be a Django user with permissions to initiate the
transfer
:param source_endpoint: Source Endpoint UUID
:param source_path: Source path, including the filename... | cf3fe2031fac2b06766c213c8c6d5cad477320a9 | 2,565 |
def calculate_pnl_per_equity(df_list):
"""Method that calculate the P&L of the strategy per equity and returns a list of P&L"""
pnl_per_equity = [] # initialize the list of P&L per equity
for df in df_list: # iterates over the dataframes of equities
pnl = df['Strategy Equity'].iloc[-1] - df['Buy and... | 4f6ac1b9f6a949215c6b805f05a65897393f3288 | 2,566 |
import http
def search(q_str: str) -> dict:
"""search in genius
Args:
q_str (str): query string
Returns:
dict: search response
"""
data = {'songs': [], 'lyric': []}
response = http.get(
'https://genius.com/api/search/multi?per_page=5', params={'q': q_str}, headers=hea... | 7421220e43415fb17b29db26f1fc6902e88144a4 | 2,567 |
def build_shed_app(simple_kwargs):
"""Build a Galaxy app object from a simple keyword arguments.
Construct paste style complex dictionary. Also setup "global" reference
to sqlalchemy database context for tool shed database.
"""
log.info("Tool shed database connection: %s", simple_kwargs["database_c... | 4443d24f4f4341baa3aea22d6f30c6b38eb8af72 | 2,568 |
def geocode(level=None, names=None, countries=None, states=None, counties=None, scope=None) -> NamesGeocoder:
"""
Create a `Geocoder`. Allows to refine ambiguous request with `where()` method,
scope that limits area of geocoding or with parents.
Parameters
----------
level : {'country', 'state'... | 25ab4ff7887d09a41c19b6ec8ee9057151483b2e | 2,569 |
def fpAbs(x):
"""
Returns the absolute value of the floating point `x`. So:
a = FPV(-3.2, FSORT_DOUBLE)
b = fpAbs(a)
b is FPV(3.2, FSORT_DOUBLE)
"""
return abs(x) | d69f5f07b651ed4466ff768601c77f90232b8827 | 2,570 |
from io import StringIO
import json
def volumes(container:str) -> list:
"""
Return list of 'container' volumes (host,cont)
"""
buf = StringIO()
_exec(
docker, 'inspect', '-f', "'{{json .Mounts}}'", container, _out=buf
)
res = buf.getvalue().strip()
vols_list = json.loads(res[... | 5191df9ab4aa58a80fba90872da6091bc58f8be2 | 2,571 |
def names():
"""Return stock summary information"""
helper = SQLHelper()
conn = helper.getConnection()
repo = robinhoodRepository(conn)
stockInfo = repo.getAllStocks()
return json_response(stockInfo, 200) | d543ab5254e95e903e8b74db1ab5b0266859b083 | 2,572 |
def get_bot_group_config(bot_id):
"""Returns BotGroupConfig for a bot with given ID.
Returns:
BotGroupConfig or None if not found.
Raises:
BadConfigError if there's no cached config and the current config at HEAD is
not passing validation.
"""
cfg = _fetch_bot_groups()
gr = cfg.direct_matches... | 025b2a9a91f2a744668fd6c438db0f5c4edd0a98 | 2,573 |
def add_utm(url_, campaign, source='notification', medium='email'):
"""Add the utm_* tracking parameters to a URL."""
return urlparams(
url_, utm_campaign=campaign, utm_source=source, utm_medium=medium) | d428daf58db7b0b5d5dabfd4bac6f70e900bd311 | 2,574 |
def is_forest(G):
"""Return True if the input graph is a forest
Parameters
----------
G : NetworkX Graph
An undirected graph.
Returns
-------
True if the input graph is a forest
Notes
-----
For undirected graphs only.
"""
for graph in nx.connected_component_subg... | 6aade3d2407b8af1cd8662b9efdc604d304341fe | 2,575 |
def package_to_pretty_string(package):
""" Given a PackageMetadata instance, returns a pretty string."""
template = "{0.name} {0.version}"
constraint_kinds = (
(ConstraintKinds.install_requires, package.install_requires),
(ConstraintKinds.conflicts, package.conflicts),
(ConstraintKin... | e3c2432560309057996dcef2296b18572df82a35 | 2,576 |
def parse_uri(uri):
""" This implies that we are passed a uri that looks something like:
proto://username:password@hostname:port/database
In most cases, you can omit the port and database from the string:
proto://username:password@hostname
Also, in cases with no username, you c... | 5204d803a5d0f6995c49883a892bc6b22cef9443 | 2,577 |
def pwgen(pw_len=16):
"""Generate a random password with the given length.
Allowed chars does not have "I" or "O" or letters and
digits that look similar -- just to avoid confusion.
"""
return get_random_string(
pw_len, 'abcdefghjkmnpqrstuvwxyz' 'ABCDEFGHJKLMNPQRSTUVWXYZ' '23456789'
) | 3c5a07440a6d3eee7c1bc9162089c434cfe6c45d | 2,578 |
import os
def absolute_path(secured_filename: str, curr_file: str = __file__) -> str:
"""
Prepend `secured_filename` with the current path.
Args:
secured_filename (str): Safe file name. Can be a sub path without the first '/'.
curr_file (str): File name of the module.
Returns:
... | 6378df580550438e727240924ad2092167ca5394 | 2,579 |
def compute_tree_distances(tree):
"""
Computes the matrix of pairwise distances between leaves of the tree
"""
num_leaves = len(get_leaves(tree)) - 1
distances = np.zeros([num_leaves, num_leaves])
for leaf in range(num_leaves):
distance_dictionary, tmp = nx.multi_source_dijkstra(tree.to_... | b4bdd81e0f4c8d5577813f6e68ece9f0a8992e19 | 2,580 |
def create_rndm_backgr_selections(annotations, files, length, num, no_overlap=False, trim_table=False):
""" Create background selections of uniform length, randomly distributed across the
data set and not overlapping with any annotations, including those labelled 0.
The random sampling is performe... | 01eac8bc0a624b56d419ce3cb75744792af1472f | 2,581 |
import methylprep
import time
from pathlib import Path
def to_BED(stats, manifest_or_array_type, save=True, filename='', genome_build=None, columns=None):
"""Converts & exports manifest and probe p-value dataframe to BED format.
- https://en.wikipedia.org/wiki/BED_(file_format)
- BED format: [ chromosome ... | 6ce2272c6a20c69e4a0e6e5568d2105a8e2dd82b | 2,582 |
def GetPartition(partition_name, target_os):
"""Return the partition to install to.
Args:
partition_name: partition name from command-line
{'primary', 'secondary', 'other'}
target_os: 'fiberos' or 'android'
Returns:
0 or 1
Raises:
Fatal: if no partition could be determined... | b3f030779bd29bbe695ba3769372f4af700d7cb7 | 2,583 |
import aiohttp
import json
async def call_dialogflow(message, config, lang=DEFAULT_LANGUAGE):
"""Call the Dialogflow api and return the response."""
async with aiohttp.ClientSession() as session:
payload = {
"v": DIALOGFLOW_API_VERSION,
"lang": lang,
"sessionId": me... | e670748dc4d0318d047b0f0ded6d857597112d49 | 2,584 |
def gettgd(sat, eph, type=0):
""" get tgd: 0=E5a, 1=E5b """
sys = gn.sat2prn(sat)[0]
if sys == uGNSS.GLO:
return eph.dtaun * rCST.CLIGHT
else:
return eph.tgd[type] * rCST.CLIGHT | c7231769b0e9be5287b2b2f76c8dcdc7bd409a89 | 2,585 |
def random_sign_uniform(shape,
minval=None,
maxval=None,
dtype=dtypes.float32,
seed=None):
"""Tensor with (possibly complex) random entries from a "sign Uniform".
Letting `Z` be a random variable equal to `-1` and `1` w... | b942253c14438c72c19d648a0d0358d8cd280bd0 | 2,586 |
def ones_v(n):
"""
Return the column vector of ones of length n.
"""
return matrix(1, (n,1), 'd') | 46936660025c1b5bd533b78143301d1218b568d7 | 2,587 |
def test_encrypt_and_decrypt_two(benchmark: BenchmarkFixture) -> None:
"""Benchmark encryption and decryption run together."""
primitives.decrypt = pysodium.crypto_aead_xchacha20poly1305_ietf_decrypt
primitives.encrypt = pysodium.crypto_aead_xchacha20poly1305_ietf_encrypt
def encrypt_and_decrypt() -> b... | 1b632ae28f147fa4d98dcdda982bf3d17b2c17dd | 2,588 |
import os
def truncate(fh, length):
"""Implementation of perl $fh->truncate method"""
global OS_ERROR, TRACEBACK, AUTODIE
try:
if hasattr(fh, 'truncate'):
fh.truncate(length)
else:
os.truncate(fh, length)
return True
except Exception as _e:
OS_ER... | c18ede642efcb37de905bf2a88bb3e1be023c1d7 | 2,589 |
def get_fy_parent_nucl(fy_lib):
"""Gets the list of fission parents from a fission yield dictionnary.
Parameters
----------
fy_lib: dict
A fission yield dictionnary
"""
fy_nucl = get_fy_nucl(fy_lib)
fy_parent = []
sample_zamid = fy_nucl[0]
sample = fy_lib[sample_zamid]
... | feb2ec2adfda4d9df4993cc89545564e4c0d1a54 | 2,590 |
from functools import partial
import array
def initialize ( is_test, no_cam ) :
"""job machine Tableをもとに個体、世代の初期設定"""
jmTable = getJmTable ( is_test )
MAX_JOBS = jmTable.getJobsCount()
MAX_MACHINES = jmTable.getMachinesCount()
# makespan最小化
creator.create ( "FitnessMin", base.Fitness, weights=(-1.0,) )
# 個体はジョ... | f306cf9b5400ea92b92709bc6986d6b87ea909b2 | 2,591 |
def perform_variants_query(job, **kwargs):
"""Query for variants.
:param job: API to interact with the owner of the variants.
:type job: :class:`cibyl.sources.zuul.transactions.JobResponse`
:param kwargs: See :func:`handle_query`.
:return: List of retrieved variants.
:rtype: list[:class:`cibyl.... | c779080e2ef8c1900c293f70996e17bae932b142 | 2,592 |
import torch
def get_model(share_weights=False, upsample=False): # pylint: disable=too-many-statements
""" Return a network dict for the model """
block0 = [{'conv1_1': [3, 64, 3, 1, 1]},
{'conv1_2': [64, 64, 3, 1, 1]}, {'pool1_stage1': [2, 2, 0]},
{'conv2_1': [64, 128, 3, 1, 1... | 364050799adc3312e4a46081e4a82338407f177b | 2,593 |
def bootstrap(config_uri, request=None, options=None):
""" Load a WSGI application from the PasteDeploy config file specified
by ``config_uri``. The environment will be configured as if it is
currently serving ``request``, leaving a natural environment in place
to write scripts that can generate URLs an... | 608629eb380765ebafa4009946a30b9f46de6ff9 | 2,594 |
def readSegy(filename) :
"""
Data,SegyHeader,SegyTraceHeaders=getSegyHeader(filename)
"""
printverbose("readSegy : Trying to read "+filename,0)
data = open(filename).read()
filesize=len(data)
SH=getSegyHeader(filename)
bps=getBytePerSample(SH)
ntraces = (filesize-3600)/(SH['ns']*bps+240)
# ntraces = 100... | 5e3920255aa49c70e0e898b2d3915c05afc7f869 | 2,595 |
def planar_transform(imgs, masks, pixel_coords_trg, k_s, k_t, rot, t, n_hat, a):
"""transforms imgs, masks and computes dmaps according to planar transform.
Args:
imgs: are L X [...] X C, typically RGB images per layer
masks: L X [...] X 1, indicating which layer pixels are valid
pixel_coords_trg: [...... | 18f90706b996ee9ba81ab7142313dcaa761cf773 | 2,596 |
def convertDynamicRenderStates(data, builder):
"""
Converts dynamic render states. The data map is expected to contain the following elements:
- lineWidth: float width for the line. Defaults to 1.
- depthBiasConstantFactor: float value for the depth bias constant factor. Defaults to 0.
- depthBiasClamp: float valu... | 5c27ebd4401d8b6c0388bfe6f1973c137404ddf5 | 2,597 |
def binary_search(a, search_value):
"""
@name binary_search
@param a array
"""
N = len(a)
l = 0
r = len(a) - 1
while(True):
try:
result = binary_search_iteration(a, l, r, search_value)
l, r = result
except TypeError:
return -1 if not re... | 5fc2748a76d89c2559cda8bc9dacd16d90b2aa5e | 2,598 |
from typing import Dict
from typing import Any
from typing import cast
def _key_match(d1: Dict[str, Any], d2: Dict[str, Any], key: str) -> bool:
"""
>>> _key_match({"a": 1}, {"a": 2}, "a")
False
>>> _key_match({"a": 1}, {"a": 2}, "b")
True
>>> _key_match({"a": 2}, {"a": 1}, "a")
False
... | 8e76ee70c6209b357b13890a9fcf2b0b7d770c1b | 2,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.