content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def split_validation(dataset, val_fraction, _rnd):
"""Randomly split a dataset into two non-overlapping new datasets.
Arguments:
dataset (Dataset): Dataset to be split
val_fraction: Fraction of dataset that should be in the validation
split
_rnd: Random state to determine sp... | 59e084a9b434e6890d24c74df9104a949528f85d | 3,618,700 |
import sys
import struct
def get_file_format(infile):
"""
get cap file format by magic num.
return file format and the first byte of string
:type infile:io.BufferedReader
"""
buf = infile.read(4)
if len(buf) == 0:
# EOF
print("empty file", file=sys.stderr)
sys.exit(... | 6d6879464a25a23e2e591f09050affb518ab8228 | 3,618,701 |
def pl_to_eng(unit: str) -> str:
"""Converts Polish terminology to English"""
switcher = {
"pikinier": "spear",
"miecznik": "sword",
"topornik": "axe",
"lucznik": "archer",
"zwiadowca": "spy",
"lekki kawalerzysta": "light",
"lucznik na koniu": "marcher",
... | 7d9634c554cc84663b1c7fb787b070d535747d36 | 3,618,702 |
def is_meta_resource_type_mutable(context, meta_resource_type):
"""Return True if the meta_resource_type is mutable in this context."""
if context.is_admin:
return True
if context.owner is None:
return False
# (lakshmiS): resource type can exist without an association with
# namesp... | 54e6e1333c8e3875efd2f1c049eb92962a2fe3e9 | 3,618,703 |
def has_at_least_one_key(*keys):
"""Validator that at least one key exists."""
def validate(obj):
"""Test keys exist in dict."""
if not isinstance(obj, dict):
raise vol.Invalid('expected dictionary')
for k in obj.keys():
if k in keys:
return obj
... | f9744c73616915881487104752d647fd31740478 | 3,618,704 |
import glob
import os
def count_files_in_dir(dir_name):
"""
After do_activity, check the directory contains a zip with ds_zip file name
"""
file_names = glob.glob(dir_name + os.sep + "*")
return len(file_names) | 6d53c430c55a0b8dbf98df0845b3e742639218d2 | 3,618,705 |
import requests
from datetime import datetime
import pandas
def get_site_data(site_code, parameter_code, as_dataframe=True,
start_date=None, end_date=None, dam_site_location='head'):
"""Fetches site's parameter data
Parameters
----------
site_code : str
The LCRA site code (fo... | 0138f1bee656e7731fea1d6c12559656ddb9416c | 3,618,706 |
from matplotlib.patches import Rectangle
def mosaic(data, index=None, ax=None, horizontal=True, gap=0.005,
properties=lambda key: None, labelizer=None,
title='', statistic=False, axes_label=True,
label_rotation=0.0):
"""Create a mosaic plot from a contingency table.
It allows... | 6a2793490d630d8fd694d1be2e7af4c50dac41db | 3,618,707 |
def get_auth_realm(url, auth_info, scheme=None):
"""Determine an authentication realm identifier from a HTTP response.
Examples
--------
Robustly determine a realm identifier for any URL::
>>> url, props = probe_url('https://fz-juelich.sciebo.de/...')
>>> get_auth_realm(url, props.get('a... | ec8000ae28c8d8a52afbba8004937a709980f59b | 3,618,708 |
def is_ok(resp: Response) -> bool:
"""
is_ok returns True is the API responded with 200
and the content type is JSON.
"""
return (
resp.headers["content-type"] == "application/json"
and resp.status_code == codes.ok
) | 08690068ed3da58b030373afb9e86f0196504511 | 3,618,709 |
def pretty_size(size, sep: str = ' ',
lim_k: int = 1 << 10, lim_m: int = 10 << 20,
plural: bool = True, floor: bool = True) -> str:
"""Convert a size into a more readable unit-indexed size (KiB, MiB)
:param size: integral value to convert
:param sep: the separator char... | 3357067ed4686ab450e90e64257104d143481805 | 3,618,710 |
def export_summary(request, qid, answer_filter=None):
"""
For a given questionnaire id, generate a CSV containing a summary of
answers for all subjects.
qid -- questionnaire_id
answer_filter -- custom filter for the answers. If this is present, the filter must manage access.
"""
if answer_fi... | 2227f006907d0ab47f2fe44c178eb2323e3bab98 | 3,618,711 |
def get_net(config):
"""Given the configuration, call a function to create the network object."""
if 'Six_Bus' in config.env_name:
return six_bus(config.vn_high, config.vn_low, config.length_km,
config.std_type, config.battery_locations, config.init_soc,
con... | 71eaedc994d8b77331140c16e4346d2afcee63e6 | 3,618,712 |
from typing import List
import tokenize
def last_bracket(tokens: List[tokenize.TokenInfo], index: int) -> bool:
"""Tells whether the given index is the last bracket token in line."""
return only_contains(
tokens[index + 1:],
NEWLINES.union({tokenize.COMMENT}),
) | a6114e4a3e8a604a6e971e0e874bfa498236c1db | 3,618,713 |
from typing import Tuple
import time
def run_kernel_pca(X_train: np.ndarray,
X_test: np.ndarray,
kernel: str,
d: int,
sigma: float ) -> Tuple[np.ndarray, float]:
"""
Run Kernel PCA experiment.
Parameters
-------... | 6dec1fc9a3de6db8b4a25a803b180c4dec600dac | 3,618,714 |
def lint(path_list, excludes=''):
"""Runs pylint on all files in path list and returns results dictionary
CATCHES:
AssertionError - raised or thrown by _lint_file due to unexpected
pylint output
Args:
path_list ------ a list of pathlib.Path objects representin... | 7bf708fbc37fe4e9598c19ee65c8b4549096ce36 | 3,618,715 |
import warnings
def reduce_array(x, reduction='mean', axis=2, weights=None):
"""
Auxiliary method to perform one of the following operations:
nanmean, nanmax, nanmedian, nanmin, nanstd, and, or, wmean.
Args:
----
x: `ndarray`
input array in which to perform the operation
reduction... | 6ef06a5aeceeda598c8101569c741a996172c274 | 3,618,716 |
def jacobi_weights(roots, n, alpha, beta):
"""Calculate the weight of each root
Args:
n: the order of the polynomial
alpha: the alpha parameter in Jacobi polynomials
beta: the beta parameter in Jacobi polynomials
"""
jacobi_check(n, alpha, beta)
jacobi_roots_check(roots, n, ... | 59b19b6915b4d7510b5e618bb2363365f3326069 | 3,618,717 |
def _get_current_unhelpful(old_formatted):
"""Gets the data for the past week and formats it as return value."""
final = {}
cursor = connection.cursor()
cursor.execute(
"""SELECT doc_id, yes, no
FROM
(SELECT wiki_revision.document_id as doc_id,
SUM(limitedvo... | 370106bb07235cfe3c46abb0ae10339933660afd | 3,618,718 |
import re
def enforceStringFormat(prompt, regex = None, minLength = None, maxLength = None):
"""
Enforces a string at a prompt
Args:
prompt: String for user input prompt
regex: regular expression the string should conform to
minLength: minimum valid string length
maxValue:... | cbf9f98bd82a1237b168fec58665cd7cad03300f | 3,618,719 |
def render_hist(
df: pd.DataFrame, x: str, meta: ColumnMetadata, plot_width: int, plot_height: int,
) -> Figure:
"""
Render a histogram
"""
if is_dtype(meta["dtype"], Nominal()):
tooltips = [
(x, "@x"),
("Count", "@count"),
("Label", "@label"),
]
... | a9808fe2fb4b3e2c052ada04cf30f60e685de818 | 3,618,720 |
import os
def build_new_list(source_path, list_title='Empty Name', recursive=False, show_source=False):
"""
Searches for image files on your hard drive and creates a list with their names and properties.
:param source_path: Search directory
:param list_title: File list name
:param recursive: Enab... | f0045d20622da764d5e28fd871bf2507f46ff6ff | 3,618,721 |
def describe(a, axis=0, ddof=0, bias=True):
"""
Computes several descriptive statistics of the passed array.
Parameters
----------
a : array_like
Data array
axis : int or None, optional
Axis along which to calculate statistics. Default 0. If None,
compute over the whole ... | 2024bd904227bb8a0b1c298afb3430c58a4cda1e | 3,618,722 |
import typing
def get_translated_text(
text: typing.Optional[typing.Union[str, typing.Dict[str, str]]],
language_code: typing.Optional[str] = None,
default: str = ''
) -> str:
"""
Return the text in a given language from a translation dictionary.
If the language does not exist in ... | 31f87023edc8bb8103a3b48b5dd515f75c9d00a8 | 3,618,723 |
import requests
import re
def proc_imgur_url(starturl):
"""
Process an imgur link
"""
# If imgur is not in the link, skip it
if "imgur.com" not in starturl:
return starturl
finishedurl = []
regex = r"href\=\"https://i\.imgur\.com\/([\d\w]*)(\.jpg|\.png|\.gif|\.mp4|\.gifv)"
tr... | 0a026c2473ebfd827439049c1a50e5678c26a638 | 3,618,724 |
def handler(service, action):
""" Handler method for service operations. """
cmd = 'systemctl {} {}'.format(action, service)
return sudo(cmd, pty=False) | daefe974fa3b1c02ff926ae682b50ebc95d82399 | 3,618,725 |
def classification(training_df: DataFrame, test_df: DataFrame, clusterer: Clustering, job: Job) -> (dict, dict):
"""main classification entry point
train and tests the classifier using the provided data
:param clusterer:
:param training_df: training DataFrame
:param test_df: testing DataFrame
... | e032fc8543ab1206a81fe2fd3ae57e69ac4749fb | 3,618,726 |
from typing import Dict
from typing import List
from pathlib import Path
import yaml
def write_commands_instructions(
commands_instructions: Dict[str, List[str]], scene_path: Path, index: int
) -> Path:
"""*Deprecated, use `write_yaml_instructions` instead.*
Writes a command instruction `yaml` file.
... | 1a0cc75b9bcf269133b799f1abe4b507b2f42c16 | 3,618,727 |
import re
def replace_simultaneous(s: str, r0: str, r1: str) -> str:
"""
Replace all instances of `r0` in `s` with `r1` and vice versa.
This method does the replacements simultaneously so that, e.g.,
if you call `replace_simultaneous("apple banana", "apple", "banana")`
the result will be `"banana... | bcfe2d13fb3b0c3156e866954d6ddf1a0a02e9fc | 3,618,728 |
import os
def _is_sound_file(name):
"""Return: True if name is the name of an font file"""
if type(name) != str:
return False
return os.path.exists(SOUND_PATH+'/'+name) | dd475e2a78bd0b82cc5fe3871913f96916a9e335 | 3,618,729 |
def multiple_best_intervals(arg, duration, number):
"""Compute multiple best intervals
TODO: This function should return a list of {'start_index': v, 'stop_index': v, 'index': v, 'value': v}
Parameters
----------
arg : pd.Stream
duration : number
number : int
Returns
-------
nd... | da16c26068e2533c57da9cb99721a2f8fd345ae6 | 3,618,730 |
def ransac_fundamental_matrix(matches_a, matches_b):
"""
Find the best fundamental matrix using RANSAC on potentially matching
points. Your RANSAC loop should contain a call to
estimate_fundamental_matrix() which you wrote in part 2.
If you are trying to produce an uncluttered visualization of epip... | 3bf38dab243a07dfd5287f55e88782c14fd15385 | 3,618,731 |
def statement_uri_query(db, needle):
"""Filter Statements by searching for mathich uris.
Return value can be used as subquery.
"""
Statement = db.entities["Statement"]
query = orm.select(st for st in Statement for uri in st.uris if uri.uri == needle)
return query | c188c968bd705295f111dd06f2ee69e909b799bc | 3,618,732 |
def partition_into_cells(mesh):
""" Resolve all-intersections of the input mesh and extract cell partitions
induced by the mesh. A cell-partition is subset of the ambient space where
any pair of points belonging the partition can be connected by a curve
without ever going through any mesh faces.
A... | 73bb6d9fab212399ae7c9f30431e1ec97aacfdd4 | 3,618,733 |
def reshape_2d_scan_for_axis(scan, axis):
"""Reshape 2d scan for given axis into an actual 2d object.
This reshapes images with shape `(398, 1, 430)` into shape `(398, 430)` etc."""
axis = axis_str_to_int(axis)
scan = np.copy(scan)
if axis == 1:
scan = scan.reshape((scan.shape[0],
... | 8c246df3f6dad749f31c7b79bf253626d7ea4d83 | 3,618,734 |
from typing import Optional
from typing import List
from typing import Collection
def get_positive_samples_in_source_plate(source_plate_uuid: str) -> Optional[List[SampleDoc]]:
"""Attempt to get a source plate's Result=Positive samples.
Arguments:
source_plate_uuid {str} -- The source plate UUID for ... | aa47759dd04cd7283de78b068c845c60c26ca8ce | 3,618,735 |
def server_is_exception(server, new_channel):
"""
Check if server is an exception
"""
if smtools.CONFIGSM['maintenance']['exception_sp']:
for key, value in smtools.CONFIGSM['maintenance']['exception_sp'].items():
if key == new_channel:
for server_exception in value:
... | 741a29c92a80a31c65a7a278523ef9dc540319ea | 3,618,736 |
def get_coin_symbol_by_index(coin_index):
"""
Retrieves a coin SYMBOL when passed a coin INDEX
Returns:
String
"""
coin_symbol = coin_symbol_by_index.get(coin_index)
if coin_symbol is not None:
return coin_symbol
# need to do a real lookup
coins_reverse = global_enum... | d77ceec886bfa1d437c1b99a62b018c743aa9bf7 | 3,618,737 |
from dateutil import tz
def _parse(data):
"""Recursively convert a json into python data types"""
if not data:
return []
elif isinstance(data, (tuple, list)):
return [_parse(subdata) for subdata in data]
# extract the nested dict. ex. {"tournament": {"url": "7k1safq" ...}}
d = {i... | ebc3c61f358d80f08db506a0465f47f4b449211f | 3,618,738 |
def get_speed(x, y):
"""
Compute speed at each frame from XY coordinates, somehow
its missing for paws in database
"""
rawspeed = (
np.hstack([[0], np.sqrt(np.diff(x) ** 2 + np.diff(y) ** 2)]) * 60
)
return convolve_with_gaussian(rawspeed, 9) | 4159e1e5d92f9f7278963d177d4d8a22ac2874a3 | 3,618,739 |
def calculate_iv_curve(effective_irradiance, temperature, module_parameters,
ivcurve_pnts=200):
"""
:param effective_irradiance:
:param temperature:
:param module_parameters:
:param ivcurve_pnts:
:return:
"""
photocurrent, saturation_current, resistance_series, re... | ca9ace009ad2564f7d678695aa29170cbb86d579 | 3,618,740 |
import os
def gz_file(request):
""" get the full path of the test fixture """
return os.path.join(request.fspath.dirname, 'source/mc3/tcga_gz-test.maf.gz') | 314e6df4954be2cff148d95a732b153369ac3cea | 3,618,741 |
def fsa(C,u10,SP,T,*,slp=1.0,gas=None,param="W14",rh=1):
"""
DESCRIPTION
-------------
Diffusive gas flux across the air-sea interface in mol m-2 s-1
F = k (C - Ceq_slp)
INPUTS:
----------
C Surface dissolved gas concentration [mol m-3 == mmol L-1]
u10... | 45c4110c59103e278fb0b4b69b6c1735a6adfa2b | 3,618,742 |
import os
def get_train_img():
"""
获取输入数据
:return:
"""
cwd=os.getcwd()
mi_dir=cwd+'/dataset/train/mi/'
shu_dir=cwd+'/dataset/train/shu/'
file1=os.listdir(mi_dir)
file0=os.listdir(shu_dir)
# file1.sort(key=lambda x: int(x[:-4]))
# file0.sort(key=lambda x: int(x[:-4]))
mi... | a4c8c433e1fad9e2b010604161861d4343bb7877 | 3,618,743 |
def calc_cos(v_i,v_j):
"""
Calculate the cos theta between two vectors
"""
return np.dot(v_i/np.linalg.norm(v_i),v_j/np.linalg.norm(v_j)) | 243e43a20a25ec5a162344f4e10c5df9f2d1d66e | 3,618,744 |
def _add_ema(model, decay):
"""Create ops needed to track EMA when training.
:param model: The model with a `.sess` we want to track.
:param decay: float, Decay to use in the EMA
:returns:
ema_op: The update op. This applies the ema to each variable. Should be
set as a control depen... | 5980a87c9d055a01d7ba4a5f8439554443c0f047 | 3,618,745 |
def retry_http(response):
"""Retry on specific HTTP errors:
* 429: Rate limited to 50 reqs/minute.
Args:
response (dict): Dynatrace API response.
Returns:
bool: True to retry, False otherwise.
"""
retry_codes = [429]
code = int(response.get('error', {}).get('code', 200))
... | f45f6e9239d78cfa6ad0ec397e3a5b4a58a655f5 | 3,618,746 |
def _box_cox_transform(values, standard=True):
"""
Performs the Box-Cox transformation, over different ranges, picking the optimal one w. respect to normality.
"""
a = sp.array(values)
if standard:
vals = (a - min(a)) + 0.1 * sp.var(a)
else:
vals = a
sw_pvals = []
lambdas... | 1d56fe5cc9a985d5092198fb4d5a8d4f49e3e4d4 | 3,618,747 |
def bst_check(now=None):
"""
Determine whether the specified date lies within the British Summer Time period.
Args:
n (tuple): An 8-tuple indicating the request date
(see http://docs.micropython.org/en/latest/library/utime.html?highlight=localtime#utime.localtime).
Returns:
... | 41c54bb8b717ec1999ae234e4eaa626e699c3caf | 3,618,748 |
def local_genus_symbol(self, p):
"""
Returns the Conway-Sloane genus symbol of 2 times a quadratic form
defined over ZZ at a prime number p. This is defined (in the
Genus_Symbol_p_adic_ring() class in the quadratic_forms/genera
subfolder) to be a list of tuples (one for each Jordan component
p^... | 5b2068a074bd13f0931e84ab29c8c7071abc2235 | 3,618,749 |
def extract_events(line, ngram_base = 'words', ngram_size = 1, outcomes_provided = True,
not_symbol_pattern = not_symbol_pattern_en, remove_weird_words = False,
sep_words = "#", sep_ngrams = '_', mark_word_boundary = True,
lowercase = True, remove_duplicates =... | cfae4a2ba22e0428f7cbca7ee97b3ab0230e75bb | 3,618,750 |
from typing import List
import re
def reduce_parenthesis(text_in: str) -> List[str]:
""" reduce parenthesis
Called recursively.
Removes one layer of parenthesis and breaks the string into parts.
Parameters
----------
text_in: str
Returns
-------
list_text: list[str]
Example... | 6d86d6b8140b55658df2efc51131059006935493 | 3,618,751 |
import types
from typing import Any
def set_obj_from_module(module: types.ModuleType, obj_name: str, value: Any) -> Any:
"""Traverses the object name and returns the last (rightmost) python object."""
if obj_name == '':
return module
obj = module
parts = obj_name.replace('/', '.').split(".")
last = part... | 3058b6b8a414bea00004db9edde4f1d19fc013ef | 3,618,752 |
def _sparsify_matrix_kernel(matrix_input, epsilon=1):
"""
The matrix sparsification procedure. See https://www.researchgate.net/publication/221462839_A_Fast_Random_Sampling_Algorithm_for_Sparsifying_Matrices
:param matrix_input: a matrix to be sparsified
:param epsilon: approximation constant.
:ret... | 21c8d7becdcc88881639544065b3c7ba9976cf75 | 3,618,753 |
def __bit_string_to_int(BitStr):
"""Transforms a string of the form '01001001' into an integer
which represents this byte.
TESTED <frs>
"""
BitStr = BitStr.replace(".", "")
BitArray = map(lambda x: x, BitStr)
BitArray.reverse()
n = 0
sum = 0
for bit in BitArray:
if bit... | ca6a4f420c3d2a8f9bb200384b4a7318db6daa44 | 3,618,754 |
import os
import concurrent
def map_samples(options, reference_gbk_file, input_dir, outdir):
"""
"""
## set it as variable
contig_option = False
pd_samples_retrieved_merge = pd.DataFrame()
pd_samples_retrieved = pd.DataFrame()
## all_data // only_project_data
if (options.all... | a8f988befe741d19a6e97fc0bcd0e4aa1e701092 | 3,618,755 |
import getopt
import sys
def parse_args(args):
"""
Parses command line arguments and sets global options
:returns: operands (list of regexes)
"""
global ignore_case
try:
options, arguments = getopt.getopt(
args,
'vhi',
["version", "help", "ignore-ca... | f5681a52f9c519384da6f56614acc909491cae40 | 3,618,756 |
def expensesByTail(update: Update, context: CallbackContext):
"""
Start the flow for listing the previous N expenses
"""
text = ("Please select an option or type in the number of most recently recorded expenses to show.")
reply_markup = reply_markups.backnHomeInlineMarkup
context.bot.send_me... | ccb52af03fc29c11b1adab7e42ea8fbeccbcaeb1 | 3,618,757 |
def include_categories(f):
"""Return an object with all categories (decorator)."""
@wraps(f)
def decorated_function(*args, **kwargs):
categories = c.query(Category).all()
# pass along the categories object to the next function
kwargs['categories'] = categories
return f(*args,... | eccf595221d785065b2eaa7780fe7e776215e7e9 | 3,618,758 |
def shuffle_array(*args):
"""
Shuffle the given data. Keeps the relative associations arr_j[i] <-> arr_k[i].
Params
------
args: (numpy arrays tuple) arr_1, arr_2, ..., arr_n to be shuffled.
Return
------
X, y : the shuffled arrays.
"""
# Assert that there is at least on... | 119ab466ca5b73964d248cd3689b6583b859b066 | 3,618,759 |
def circular_wetted_perimeter(angle, diameter):
"""Returns circle wetted perimeter.
:param angle: angle in radians from angle_in_partial_filled_pipe function
:param diameter: diameter of pipe [m]
"""
return angle * diameter | e24cc0839eb3bf78e65f6b9b99b34bf87f77b2cf | 3,618,760 |
import re
def openapi_endpoint_name_from_rule(rule):
"""Utility function to generate the Open API endpoint name.
It replace '/users/<user_id>' with the OpenAPI standard: '/users/{user_id}'.
"""
name = rule.rule
for argument in rule.arguments:
openapi_name = f"{{{argument}}}"
name... | 262ad76302e76017bb88cf469add1c71e0452ea0 | 3,618,761 |
def _fix_axes(tensors, axes, allow_negative):
"""Makes all axes positive and checks for out of bound errors."""
axes = [
axis + tensor.shape.ndims if axis < 0 else axis
for tensor, axis in zip(tensors, axes)
]
if not all(
((allow_negative or
(not allow_negative ... | f3861809c2150e3d069fdba6930ef8a1e7f870da | 3,618,762 |
import os
def get_monthly_biasfile(yyyy, mm, ccdid):
"""
format: cal/bias/yyyy/mm/ztfin2p3_yyyymm_000000_bi_ccdid_bias.fits
"""
filestructure = f"ztfin2p3_{yyyy:04d}{mm:02d}_000000_bi_c{ccdid:02d}_bias.fits"
return os.path.join(BIAS_DIR, f"{yyyy:04d}",f"{mm:02d}",
f... | 9c4bae15efc0a75bd104f98488e1dc3b8fa7f4fb | 3,618,763 |
import yaml
def yaml_loader(filepath: str) -> dictionary:
"""
Loads a yaml file specified by the filepath and returns it as a dictionary
:param filepath: A string containing the filepath to load
:return: A dictionary containing the contents of the yaml file
"""
with open(filepath, 'r') as file... | f7a18969604a612d006326e7ce8639150c72c3af | 3,618,764 |
import torch
def new_deit_tiny_patch16_224(pretrained=False, **kwargs):
"""
the same as vit_base_patch16_224
"""
default_kwargs = {
'embed_dim': 192,
'num_heads': 3,
}
default_kwargs.update(_cfg)
default_kwargs.update(kwargs)
vit = VisionTransformer(**default_kwargs)
... | c61810b371de6ec442030e8300a1500e5f0f316c | 3,618,765 |
def calc_rgb_each_hue_dEz_base(
hue, cusp, focal_point_l, chroma_num, delta_Ez,
color_space_name, luminance):
"""
Parameters
----------
hue : float
hue angle (0.0-360)
focal_point_l : float
lightness value of the focal_point.
chroma_num : int
the number of... | 233acbd65cbd366ef324154037cc0219dc24cd4a | 3,618,766 |
def page_not_found(error):
"""Error 404: Page not found
"""
return render_template('page_not_found.html'), 404 | 2514700e2a920bdaa58e7d9b559cc37bcde85b0a | 3,618,767 |
def bigram(words, score_fn=BigramAssocMeasures.likelihood_ratio, n=500,freq=1):
"""
tmp_words=[]
for w in words:
tmp_words.append(w)
words=tmp_words
"""
if len(words)<=0:
return {}
tmp_dict={}
for w in words:
tmp_dict[w]=1
if len(tm... | eef36c1153d50e8a22e6d4ecff7ca8622682ad2b | 3,618,768 |
def sample(sample_type="const", a=None, b=None, *, random_state: np.random.RandomState = None):
"""
Example
-------
>>> sample(sample_type="const",a=5,random_state=np.random.RandomState())
5
>>> isinstance(sample(sample_type="randint",a=1,b=10,random_state=np.random.RandomState()),int)
True
... | f6c0c4e64bea83a88f9dc0debff9cdf1c2caa2ed | 3,618,769 |
def adam_consensus(trees):
"""Search Adam Consensus tree from multiple trees.
:Parameters:
trees : list
list of trees to produce consensus tree.
"""
clades = [tree.root for tree in trees]
return BaseTree.Tree(root=_part(clades), rooted=True) | 44c80015c2ac437168c3cd3b03ea1fe101e9cdcb | 3,618,770 |
from shapely import wkb
from shapely import wkt
def decode_geometry(ewkb):
"""Decode encoded wkb into a shapely geometry"""
# it's already a shapely object
if hasattr(ewkb, 'geom_type'):
return ewkb
if ewkb:
try:
return wkb.loads(ba.unhexlify(ewkb))
except Exceptio... | 24a714618e243281cc13e05056ec0d9280c19ce3 | 3,618,771 |
def mask():
"""Example mask for testing."""
filename = '$GAMMAPY_EXTRA/datasets/exclusion_masks/tevcat_exclusion.fits'
return SkyImage.read(filename, hdu='EXCLUSION') | 1a339f1ff8db704a73183ebc52123b49710ef691 | 3,618,772 |
import click
import tqdm
import requests
import sys
def main(url: str, local: bool):
"""Test the API."""
url = url.rstrip("/")
if local:
url = "http://localhost:5000"
click.echo(f"Testing resolution API on {url}")
failure = False
prefixes = tqdm(bioregistry.read_registry())
for pr... | ccd4eb653cb65bd1a5fa5b25f2bfaffb8a54735b | 3,618,773 |
def parse_filepaths(fp, studies=None):
"""
Summary
-------
Function to parse filepath and optional study names into a format readable
for the calsim_toolkit read/write functions.
"""
# Check that inputs provided are compatible and zip data into list.
if isinstance(fp, str) and (isinstan... | 17e6a14967aea1275bf1562ca691dfdb2c1f16d0 | 3,618,774 |
def is_dunder(attr_name: str) -> bool:
"""
Retuns whether the given attr is a magic/dunder method.
:param attr_name:
"""
return attr_name.startswith("__") and attr_name.endswith("__") | b3a1f10e9fc7fd5c7dbb930be977a814e6b0c37d | 3,618,775 |
from textwrap import dedent
def doc(descriptor, indent=0):
"""
Format ``doc`` attribute of ``descriptor``.
If doc is ``None`` returns warning admonition. If ``indent`` argument
is specified, the result will be indented by the number of spaces.
"""
if descriptor.doc is None:
result = dedent("""
... | da03ecbce1ee740e00ccee0f260827a29b106a62 | 3,618,776 |
def draw_box(im, np_boxes, labels, threshold=0.5):
"""
Args:
im (PIL.Image.Image): PIL image
np_boxes (np.ndarray): shape:[N,6], N: number of box,
matix element:[class, score, x_min, y_min, x_max, y_max]
labels (list): labels:['class1', ..., 'classn']
... | d3aa7dbee52a75ff32beda069762faeb07e81854 | 3,618,777 |
def get_mnist_default_transform():
""" The default transform come with data augmentation """
return transforms.Compose([
transforms.Pad(2),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
]) | e89fe8c8568122de8acb605a994c8292ad3feb94 | 3,618,778 |
def HideUnusedScalarBars(view=None):
"""Hides all unused scalar bars from the view. A scalar bar is used if some
data is shown in that view that is coloring using the transfer function
shown by the scalar bar."""
if not view:
view = active_objects.view
if not view:
raise ValueError (... | 2d00e824b756878d0f7d8630f76ee3d341f24514 | 3,618,779 |
def rename(name, new_name):
"""
.. versionadded:: 2017.7.0
Renames a container. Returns ``True`` if successful, and raises an error if
the API returns one. If unsuccessful and the API returns no error (should
not happen), then ``False`` will be returned.
name
Name or ID of existing con... | ce90a6222c2bc08ea756ef4bf495e0ccb4ea57f5 | 3,618,780 |
def validate_serial(req_data):
"""Verify serial in data validates
Args:
req_data (dict): request with serial and possibly models
Returns:
object: None if all ok, or json response (bad)
"""
with _global_lock:
sim_type = sirepo.template.assert_sim_type(req_data['simulationTyp... | d67c11fac10e48677910927b0b0c0267d9f24318 | 3,618,781 |
from typing import Iterable
import logging
def bisect_trajectory(
env: "CompilerEnv", # noqa: F821
hypothesis: Hypothesis = environment_validation_fails,
reverse: bool = False,
flakiness: int = 1,
) -> Iterable["CompilerEnv"]: # noqa: F821
"""Run a binary search to remove the suffix or prefix of... | b84013f696cf36e9cf39a56fb85688203f157bbd | 3,618,782 |
def read_megares_annotations(annotations_file):
"""Read MEGARes annotations.
"""
annotations = pd.read_csv(annotations_file, index_col=0)
return annotations.to_dict() | 94011a9f3fa9a298e7204f93dd5ca844621306b7 | 3,618,783 |
def risings_and_settings(ephemeris, target, topos,
horizon_degrees=-34.0/60.0, radius_degrees=0): #?
"""Build a function of time that returns whether a body is up.
This returns a function taking a :class:`~skyfield.timelib.Time`
argument returning ``True`` if the body’s altazimuth ... | 5a39a904f496d83287b2c03a7d09fc5301eef8e9 | 3,618,784 |
from metric import all_metrics
def get_all_metric_names():
"""Return a list of all metric names."""
return all_metrics.keys() | facfd75c7ff4368522a8b204532b26f80180a9d1 | 3,618,785 |
def __get_weather_message_at_location(bot: SopelWrapper, location: dict) -> str:
"""
Gets the formatted weather message at a location based on a supplied location dictionary
"""
log.debug(
"Getting weather message for location '%s'", construct_location_name(location)
)
is_location_best... | 5783c8f665e86021d7e828cc2b575406ecc493cd | 3,618,786 |
def getRootLogger():
"""
Return the root logger. Note that getLogger('') now does the same thing,
so this function is deprecated and may disappear in the future.
"""
return root | 78f350cdb4ecb0beeb31a4e8e2af0b5ea8974bd7 | 3,618,787 |
def trajectories_and_new_observations_steps(
traj_not_updated,
remaining_new_observations,
next_nid,
return_trajectories_queue,
sep_criterion,
mag_criterion_same_fid,
mag_criterion_diff_fid,
angle_criterion,
orbfit_limit,
max_traj_id,
ram_dir,
store_kd_tree,
run_metri... | 035a23058e626a4856c80ccea96cdef9568794ec | 3,618,788 |
def steiner_echo_gen_source(ext, build_dir):
"""
Add Steiner echo classifier source if Fortran 90 compliler available,
if not compiler is found do not try to build the extension.
"""
try:
config.have_f90c()
return [join(config.local_path, '_echo_steiner.pyf'),
join(co... | 9e3b514e2d1e8d92c17a07484805031719faf565 | 3,618,789 |
import torch
def ft_flow(flow: nn.ModuleList, x: torch.Tensor):
"""Pass `x` through (forward) through each layer in `flow`."""
# if torch.cuda.is_available():
# f = f.cuda()
for layer in flow:
x, logdet = layer.forward(x)
return x.detach() | 0aeb522e2789e74156be8e51798fdf388bebc50a | 3,618,790 |
def recurse():
"""return (sum, value)"""
child_count = next(it)
metadata_count = next(it)
if child_count == 0:
total_value = total_sum = sum(islice(it, metadata_count))
return total_sum, total_value
total_sum = total_value = 0
child_values = []
for _ in range(child_count):
... | 3c3bbf7156785b7bad7c5936ac86aec489bd3cb9 | 3,618,791 |
def load_yaml(filename='config.yml', logger=None):
"""
Convenience wrapper around toolchest.yaml::parse to allow you to parse a
file by path+name
:param filename: A yaml file to be parsed
:param logger: Optional logger for potential errors
:return: A dictionary formed out of the yaml data
"... | 0a5dd7160247a0cb2476a1cdbb25ea3a2698a587 | 3,618,792 |
from typing import Tuple
import os
def generate(path=None) -> Tuple[np.ndarray, np.ndarray]:
"""
Description: Outputs the daily price of bitcoin from 2013-04-28 to 2018-02-10
"""
data = pd.read_csv(
path or os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../data/crypto.csv")
... | 8df9ec53d7d6c1a6fbcde41744b0158bba491ac0 | 3,618,793 |
def generate_seq(length):
"""
Generates a sequence of given length using black magic
Sequence is a string of AGCT
"""
global VALUES
seq = []
intseq = np.floor(np.random.rand(length) * 4)
for i in range(length):
seq.append(VALUES[intseq[i]])
return ''.join(seq) | c87d64a9f5461a928ad08f1aaed3031b219c41c8 | 3,618,794 |
def find_roles(dbs, role_name=None, page_no=1, filter_sys=False):
"""
角色列表
:param dbs:
:param role_name:
:param page_no:
:param filter_sys:
:return:
"""
roles = dbs.query(SysRole.role_id,
SysRole.role_name,
SysRole.role_desc,
... | f5139998847762a611fbda95e15ccd17242d8a11 | 3,618,795 |
def invalid_data_response(request_serializer):
"""
Returns the error message depending on missing/invalid data in serializer.
"""
return Response({'detail': request_serializer.errors,
'data': {}}, status=status.HTTP_400_BAD_REQUEST) | 8703c851968879fdccb65f637c9c13b258d121bb | 3,618,796 |
from .plugin import run
def plugin( script, **kwargs ):
""" Run external plugins written in R or Python.
Run python code file in parameter `script` or run R code (or code file) given in parameter `script` using rpy2.
You can provide the R code python variables in kwargs and those are automatically... | 161a018a059d89eae363d9666a51061cab0109ca | 3,618,797 |
def FNV64HashString (string: str) -> int:
"""
Hash string using the 64 bit Fowler-Noll-Vo hash function.
:type string: str
:return: Returns hashed string in integer form. Use the ConvertIntegerToHexadecimal function to get it in a base 16 format.
:rtype: int
"""
if not isinstance(string, str):
raise Exception... | 4ed1681afc464935e35f19027983c2ac3c879833 | 3,618,798 |
def index_generation_with_scene_list(crt_i, max_n, N, scene_list, padding='replicate'):
"""Generate an index list for reading N frames from a sequence of images (with a scene list)
Args:
crt_i (int): current center index
max_n (int): max number of the sequence of images (calculated from 1)
... | 157c7838600b36d3cddaa3e3c20afff2cc4e8484 | 3,618,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.