content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def _get_top_left_coordinates(height, width, patch_size):
"""Calculate coordinates of top-left corners for patches."""
n_h = math.ceil(height / patch_size)
n_w = math.ceil(width / patch_size)
tops = np.linspace(0, height - patch_size, n_h, dtype=int)
lefts = np.linspace(0, width - pat... | b825f4829d49ab648484a6ebcfb0af1094f613b7 | 3,624,800 |
def create_stream(data_type, transaction_id):
"""
Construct a 'createStream' message to issue a new stream on which data can travel through.
:param data_type: int the RTMP datatype.
:param transaction_id: int the transaction id in which the message will be sent on.
"""
msg = {'msg': data_type,
... | 6ceb6f259c590bdb21589c57ba053fad5c7e1851 | 3,624,801 |
import math
def pdg_case ( error ) :
"""Classify according to PDG prescription
- see http://pdg.lbl.gov/2010/reviews/rpp2010-rev-rpp-intro.pdf
- see section 5.3 of doi:10.1088/0954-3899/33/1/001
The basic rule states that
- if the three highest order digits of the error lie between 100 and 35... | d43d4b3aed3c814d77ba0477e856f9ec04486fd1 | 3,624,802 |
def _version_string_to_tuple(version_string):
"""Convert a version_string to a tuple (major, minor, patch) of integers."""
return (int(n) for n in version_string.split('.')) | d2fe2a3d9f6f23d1d80c2808436386c18893828f | 3,624,803 |
import os
import logging
def load_environmental_variables(file) -> bool:
"""Populates the environment with variables from a .env file.
:param file: path to the file with environmental variables.
:returns: ``True`` if variables have been successfuly loaded.
"""
if os.path.isfile(file):
... | 8f2d8b40ec47b28668a3fbd1436c6159cb6974c6 | 3,624,804 |
def build_averaged_flowgram(flowgrams):
"""Builds an averaged flowgram from a list of raw signals."""
result=[]
if(len(flowgrams)==1):
return flowgrams[0]
for tuple in map(None, *flowgrams):
k=0
sum=0
for element in tuple:
if (element!=None):
... | f2ea94478280d51139b64badcbb98cfece3b61d0 | 3,624,805 |
def request_extra_time_dialog(request):
""" TODO: add doc string
"""
logger.debug('request_extra_time_dialog starts')
task_id = request.matchdict.get('id')
task = Task.query.filter_by(id=task_id).first()
action = '/tasks/%s/request_extra_time' % task_id
came_from = request.params.get('cam... | 3e6585bd7f5f02d39fce462ab6d4f5643f157fa1 | 3,624,806 |
def flatten(request, root, write):
"""
Incrementally write out a string representation of C{root} using C{write}.
In order to create a string representation, C{root} will be decomposed into
simpler objects which will themselves be decomposed and so on until strings
or objects which can easily be co... | c92d8bb889d58ab382b207185f9190566bfcda9d | 3,624,807 |
def get_dates(dates):
"""Returns a list of dates
date format: yyyy-mm-dd
input can be a single date or a list of two (start and end date)
"""
ans_list = []
if not isinstance(dates, (list, tuple)):
dates = [dates]
if len(dates) == 1:
try:
validate_date(dates... | 212d4c18032f661831b24ac794525efbce5b1999 | 3,624,808 |
from typing import OrderedDict
def drawImpactScale(lossdict, ranges, losstype, debug=False):
"""Draw a loss impact scale, showing the probabilities that estimated losses fall into one of many bins.
:param lossdict:
Dictionary containing either 'TotalFatalities' or 'TotalDollars', depending on losstype.... | 80e9d3bfac8a70177e1858cc7fab3414f24d87f2 | 3,624,809 |
def register_op_attr(op_name, attr_key, value=None, level=10):
"""Register an operator property of an operator by name.
Parameters
----------
op_name : str
The name of operator
attr_key : str
The attribute name.
value : object, optional
The value to set
level : in... | ef469099d7b27956a9b123c5b368efb561a9c30b | 3,624,810 |
def posix_mkfifo(space, fname, mode):
""" posix_mkfifo - Create a fifo special file (a named pipe) """
try:
os.mkfifo(fname, mode)
return space.newbool(True)
except OSError, e:
space.set_errno(e.errno)
return space.newbool(False) | 921ea6c6b11546428611f4a94aa66eec8caf452f | 3,624,811 |
import os
def check_file_exists(base, path, ftype="markdown"):
"""Check if the target file exists.
NOTE: We build a normalized path using 'base' and 'path' values. Suppose
the resulted path string is 'foo/bar', we check if 'foo/bar.md' exists,
AND we check if 'foo/bar/_index.md' exists.
:param b... | 9132a4c0c1b3f2e75916fe856019d8c585504cb8 | 3,624,812 |
def validateProof(target_hash, proof):
"""Core validation utility
Validates the inserted proof by comparing to the provided target hash, modifies the proof's
status as ``True`` or ``False`` according to validation result and returns this result
:param target_hash: the hash to be presumably attained at... | 8538d0d5d1b1b27d2668cb127a9451d328fa786f | 3,624,813 |
import re
def get_major_version(version):
"""
Enable checking that 2 versions are within the same
major version
"""
components = re.findall(r"\d+", version)
major = components[0]
return major | b3d017b3dbe49b0a30d9919272906e8936c14f83 | 3,624,814 |
def calc_intersection_PAL(xy_1_a, xy_1_b, xy_2_a, xy_2_b):
"""
Calculates intersection points of the polygonal audience lines
This function is necessary for the handling of gaps in the audience lines and
is used to create the non-audience lines.
Calculation of the intersection of two adjacent sectio... | f1ec81b1ac973c7c80427e386d919d6a47c04729 | 3,624,815 |
import json
def delete(rt_info):
"""
删除rt的mysql存储相关配置
:param rt_info: rt的配置信息
:return: rt的mysqls存储清理结果
"""
# 对于mysql中表删除,考虑通过rename表名,在尾部标记to_delete,然后定期清理的方式
mysql = rt_info[STORAGES][MYSQL]
physical_tn = mysql[PHYSICAL_TABLE_NAME]
ptn_arr = physical_tn.split(".")
conn_info = ... | 2612e2bd529398176c56398804bf7c654066bb7d | 3,624,816 |
def create_person_ruler(nlp: Language) -> EntityRuler:
"""Create entity ruler that extracts person name with regex.
Notes:
This component must be used with `camphr.lang.mecab.Japanese`.
In order to imporove accuracy, it is recommended to create a Mecab user dictionaly. See scripts/mecab_person_... | d217fda4c20827f42c9ef56f2a7021d58f571b13 | 3,624,817 |
def to_pixel_samples(img):
""" Convert the image to coord-RGB pairs.
img: Tensor, (3, H, W)
"""
coord = make_coord(img.shape[-2:])
rgb = img.view(3, -1).permute(1, 0)
return coord, rgb | 1a63e6e1b533608949921d247d90bb967365c924 | 3,624,818 |
def inverse_transform(X, scaler, trend=None):
"""
:param X: the data
:param scaler: the scaler that have been used for transforming X
:param trend: the trebd values that has been removed from X. None if no detrending has been used.
It has to be the same dim. as X.
:return:
X with tre... | aebb52543896dc551329f57ea8e389d93f376d36 | 3,624,819 |
def get_available_snapshots(session, identifier, snapshot_type=None):
"""Returns snapshots in the available state for a given DB or Cluster `identifier`.
Args:
session (:class:`boto.rds2.layer1.RDSConnection`): The RDS api connection
where the database is located.
identifier (str): T... | 046e5949c73542ea73d51b90b91cf1d676ab7778 | 3,624,820 |
from typing import Any
def is_action(value: Any) -> bool:
"""Returns ``True`` if the value is an action."""
return isinstance(value, dict) and "action" in value | 46c691c7afd221c0f77869428535f6b943332905 | 3,624,821 |
def get_parse_args_definitions(wanted=None):
"""
Parse the args the script neeeds
:param: wanted: list of args the application will use
:returns: A list with the options for the wanted args
"""
definitions = {
'kolibri_dev': [
'-kd', '--kolibri-dev', {
'requir... | 9215b13917652fe23c053f24ec3ce42b1a9fd924 | 3,624,822 |
import base64
import re
def _create_machine_azure(conn, key_name, private_key, public_key,
machine_name, image, size, location, cloud_init,
cloud_service_name, azure_port_bindings):
"""Create a machine Azure.
Here there is no checking done, all parameters a... | 5fb31ef31da7b547418f12556fdf9b1c4091808a | 3,624,823 |
def euclidean_distance(q1, q2):
"""Returns Euclidean distance between arrays q1 and q2."""
diff = ravel(q1 - q2)
return sqrt(sum(diff*diff, axis=0)) | 7383e1fb8e561c5c1ad598f0262bb89e4ba9a3be | 3,624,824 |
def merge(root, *others):
"""Combine a bunch of dictionaries and return the result"""
cp = clone(root)
[cp.update(other) for other in others]
return cp | 7efd17ca14c320d282921e63cdcd8ad063d64fb0 | 3,624,825 |
import pickle
import os
def load_WADE_data(year,datadir='/ocean/eolson/MEOPAR/obs/WADE/ptools_data/ecology'):
""" This function automatically loads the nutrient bottle data from WADE for a given year
specified by the user. The output is a pandas dataframe with all of te necessary
columns and grou... | eec09bbce19890555e7cbbadfb2af0317e92458d | 3,624,826 |
import os
def expand_path(path):
"""Get the canonical form of the absolute path from a possibly relative path
(which may have symlinks, etc.)"""
return os.path.expandvars(os.path.expanduser(path)) | d1e58069f5547e8f5452a5c0a5888c08475033c5 | 3,624,827 |
from typing import OrderedDict
def read_config(config_file, default_config=None):
"""
Return a dictionary with subdictionaries of all configFile options/values
"""
config = SafeConfigParser()
config.optionxform = str
config.read(config_file)
sections = config.sections()
dict1 = Ordered... | e115d4912e33d689cb1a8e633a7a0c1c0949641c | 3,624,828 |
def source_status(request):
"""
Source availability status endpoint for Platform Sources to get cost management source status.
Parameter:
source_id corresponds to the table api_sources
Returns:
status (Dict): {'availability_status': 'unavailable/available',
'ava... | 07d949e609e67497b378a34a5f0d0935675c6b8a | 3,624,829 |
import os
def get_path_rel_to_proj(full_path):
"""
"""
#| - get_path_rel_to_proj
subdir = full_path
PROJ_dir = os.environ["PROJ_irox_oer"]
ind_tmp = subdir.find(PROJ_dir.split("/")[-1])
path_rel_to_proj = subdir[ind_tmp:]
path_rel_to_proj = "/".join(path_rel_to_proj.split("/")[1:])
... | f575a0725ab090ea55091ce74610df2f1ab62010 | 3,624,830 |
def name_to_components(name):
"""Converts a name to a list of components.
Arguments:
name - Name in the format /name1=value1/name2=value2/..
Returns: list of (name, value) tuples
"""
ret = []
components = [x for x in name.split('/') if x]
components = [x.split('=') for x in componen... | 5683e3c4fdce53b53431484a46cd23c8959d20a2 | 3,624,831 |
def flow2img(flow_data):
"""
convert optical flow into color image
:param flow_data:
:return: color image
"""
# print(flow_data.shape)
# print(type(flow_data))
u = flow_data[:, :, 0]
v = flow_data[:, :, 1]
UNKNOW_FLOW_THRESHOLD = 1e7
pr1 = abs(u) > UNKNOW_FLOW_THRESHOLD
... | f7a4b471cb989b19ae5e2aea2a0a0308eeaba15e | 3,624,832 |
def multiple_testing_correction(ps, alpha=0.05, method='benjamini-hochberg', **kwargs):
""" correct pvalues for multiple testing and add corrected `q` value
:param ps: list of pvalues
:param alpha: significance level default : 0.05
:param method: multiple testing correction method [bonferroni|benjamini... | cf853a9e7369550d1986b3139ea0e5131dd21437 | 3,624,833 |
def detect_format(filename):
"""Return the name of the format based on the start of the file."""
enough_bytes = 0x1000
with open(filename, 'rb') as f:
data = f.read(enough_bytes)
if isinstance(data, bytes):
data = data.decode(errors='replace')
if data.startswith('DRCOV VERSION: 2'):... | ab66158c19cb99150d0b01ed57613bd26c8006c2 | 3,624,834 |
from typing import Optional
import readline
def clear_tab_complete_vocabulary() -> None:
"""
Resets vocabulary used for tab completion. It's important to either use the cleanup argument in tab_complete,
or call this function after setting a vocabulary. This will prevent irrelevant options displaying when ... | 2014e996474742d956566cc95887ba4c868398a6 | 3,624,835 |
from datetime import datetime
def _cache_filename(url):
"""yyyy-mm-url-slug.json"""
today = datetime.utcnow().strftime("%Y-%m")
slug = slugify(url)
filename = CACHE_DIR / f"{today}-{slug}.json"
return filename | 43cce02ff72d890382219fdc6fdf08cb95cfcc03 | 3,624,836 |
import re
def fixupAnchor(anchor):
"""Miscellaneous fixes to the anchors before I start processing"""
# This one issue was annoying
if anchor.get("title", None) == "'@import'":
anchor["title"] = "@import"
# css3-tables has this a bunch, for some strange reason
if anchor.get("uri", "").st... | ba352cc5b18f82000be3943cf03db8ebcb41ddff | 3,624,837 |
def deep_merge(base, updates):
""" apply updates to base dictionary
"""
for key, value in updates.iteritems():
if key in base and isinstance(value, dict):
base[key] = deep_merge(base[key] or {}, value)
else:
base[key] = value
return base | 6add1c048368f1547aa6ce5ebea1fe17b373fb87 | 3,624,838 |
def load_vocab_dict(vocab_file):
"""Returns a dictionary and the vocabulary size."""
def count_lines(filename):
"""Returns the number of lines of the file :obj:`filename`."""
with open(filename, "rb") as f:
i = 0
for i, _ in enumerate(f):
pass
... | 2331e3472af1b538defef9a41539da2b1ae687c3 | 3,624,839 |
import collections
def with_concurrency_limit(
bucket_id: str,
/,
*,
error_message: str = "This resource is currently busy; please try again later.",
) -> collections.Callable[[CommandT], CommandT]:
"""Add the hooks used to manage a command's concurrency limit through a decorator call.
.. war... | e51801c21667fd72b532429a4c82412333e59d84 | 3,624,840 |
def request_oauth_token():
""" Prompts user for credentials and returns Oauth token from GitHub """
print "Requesting an oauth token from GitHub."
print "Your username and password will not be stored."
username = raw_input("GitHub Username: ")
password = getpass.getpass("GitHub Password: ")
try:
g = ... | 4312944dbe9c3cb6c32920a625aacbed29f646a7 | 3,624,841 |
def preprocessor(normalization="auto", assume_immutability=False, renormalize=False):
""" Wrapper function that generates lambda expressions for the method to_sparse_matrix.
Args:
normalization: Normalization parameter for `to_sparse_matrix` (default is "auto").
assume_immutability: If True, th... | fdf207ba55bf2679a7a22aba482d1d90e1f09212 | 3,624,842 |
def bar_facets_from_pivoted_df(not_pivoted_df, plot_x, plot_y, order_list,
color_list, filename=None, portrait=True):
"""
General function to produce faceted plots (O2 vs rep or vice versa)
given already-pivotd data.
:param not_pivoted_df: a dataframe that will be pivoted... | c62e86efbdff9a3c0217db85bdec882d13ee4cd3 | 3,624,843 |
def jax_issue_role(name, rawtext, text, lineno, inliner, options=None,
content=()):
"""Generate links to jax issues or PRs in sphinx.
Usage::
:jax-issue:`1234`
This will output a hyperlink of the form
`#1234 <http://github.com/google/jax/issues/1234>`_. These links work even
for PR... | 6830183d70c8aa85da7a5775e22b32efacf92066 | 3,624,844 |
def planckwavenum(waven, Temp):
"""
input: wavenumber (m^{-1}), Temp (K)
output: planck function in W/m^2/m^{-1}/sr
"""
Bwaven = c1 * waven**3. / (np.exp(c2 * waven / Temp) - 1)
return Bwaven | 96e179b280c96d7939deb9f3f2e9f82e862786bb | 3,624,845 |
from typing import Dict
def validate_name_request(filing: Dict, filing_type='registration') -> list:
"""Validate name request."""
nr_path = f'/filing/{filing_type}/nameRequest/nrNumber'
nr_number = get_str(filing, nr_path)
msg = []
# ensure NR is approved or conditionally approved
try:
... | 0019af0fea14869afd1634ee480ed77986548227 | 3,624,846 |
def wasserstein_hinge_discriminator_loss(
discriminator_real_outputs,
discriminator_gen_outputs,
real_weights=1.0,
generated_weights=1.0,
real_hinge=1.0,
generated_hinge=1.0,
scope=None,
loss_collection=tf.compat.v1.GraphKeys.LOSSES,
reduction=tf.compat.v1.losses.Reduction.SUM_BY_NON... | 30ee18fee8b7aaaaebcce8100f03fd2f8b719b01 | 3,624,847 |
from typing import Dict
from typing import List
def dict_to_hfdataset(dic: Dict[str, List]) -> HFDataset:
"""helper function to convert to huggingface's dataset class
"""
return HFDataset.from_dict(dic) | ea777577f5c5922b21891c21cfdb990838e2f5a5 | 3,624,848 |
from pathlib import Path
def experiment_fixture():
"""'experiment--test' in tmpdir. Returns Experiment object."""
exp_path = Path(__file__).parent / "fixtures" / "experiment--test"
return Experiment(str(exp_path)) | 7278c2c14327907795f00e43c637a647161afaab | 3,624,849 |
import subprocess
def check_call(cmd, *args, **kw):
"""Like `run_process` above but treat failures as fatal and exit_with_error."""
print_compiler_stage(cmd)
try:
return run_process(cmd, *args, **kw)
except subprocess.CalledProcessError as e:
exit_with_error("'%s' failed (%s)", shlex_join(cmd), return... | b56f5fef29c1ac696489689ee3d2d050cb3eba55 | 3,624,850 |
def PostScriptDC_GetResolution(*args):
"""
PostScriptDC_GetResolution() -> int
Return resolution used in PostScript output.
"""
return _gdi_.PostScriptDC_GetResolution(*args) | 2d8fb7f1a2ebc39e737b763a1736898648cd5307 | 3,624,851 |
def find_indices(x, y):
"""
Find the index of every element of y in x
"""
# indices that would sort x (length x)
index = np.argsort(x)
sorted_x = x[index]
# index of every element of y in sorted x (length y)
# can't plug this into either x or y:
# it's too short for x (being leng... | 37c46ae07b1d48a7e5e3e0e89b18976342ea6679 | 3,624,852 |
def load_data(filepath) -> DataFrame:
"""Load dataset from file. Extract datasets and category names
Args:
filepath (str): user level file path
Return:
df (DataFrame): DateFrame
"""
df = spark.read.csv(filepath, header=True, inferSchema=True)
return df | 570d562eb53acfa39d7a4080780e137fe4e4e66e | 3,624,853 |
def get_storage_type(storage_path):
"""Get storage type for a storage path (local and supported remote storages)"""
for storage_type in storage_prefex_config:
if storage_path.startswith(storage_prefex_config[storage_type]):
return storage_type
raise StorageNotSupported("Storage path type... | c2163556d3b2fc8f09ed994d5fd91f4cd7c829df | 3,624,854 |
import os
def get_file_size(item_container, is_protected=False):
""" liefert die Dateigroesse """
filename = get_file_name(item_container, is_protected)
try:
st = os.stat(filename)
return st[6]
except:
return -1 | 4078b9d0c691bdfb13e3ba5ba5939276e1c4f6bc | 3,624,855 |
def delete_article(id):
"""
A view function for administrators to delete an articles.
"""
article = Article.query_by_id(id)
article.delete()
flash(f"Article id {id} deleted", "success")
current_app.logger.info(f"{str(article)} deleted.")
return render_template("result.html", url=url_for(... | 5113e782a8dbf91dd30448808b61a4d700b46e94 | 3,624,856 |
def smooth_serie(dfi):
"""Smooth a serie by doing a time_average 2 times"""
df = time_average(dfi, months=12, center=True)
return time_average(df, months=6, center=True) | e13a8d34625a73d42e871c815065442c3213f621 | 3,624,857 |
def create_ast_dict(commits, repo_path, repo_name, g):
"""
Creates a dictionary mapping the SHA1 of each version in `commits` to a node
object that contains the abstract syntax trees of all the Python code in that
version.
:param commits: the list of commits in a repo
:type commits: Git.Commit ... | d952d7db704887845fb0662b3cefcf49a5ad7a8d | 3,624,858 |
import sys
def rotgliquad_fit(dra, ddc, dra_err, ddc_err, ra, dc, ra_dc_cor=None,
fit_type="full", pos_in_rad=False,
num_iter=100, **kwargs):
"""VSH degree 02 fit and return rotation, glide, &quadrupolar vectors
Parameters
----------
dra/ddc : array of float
... | 1f467044e5aeddb9018cf1bcc39f2d9d830f1777 | 3,624,859 |
from typing import Optional
def get_license(license: Optional[str] = None,
project: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetLicenseResult:
"""
Returns the specified License resource. *Caution* This resource is intended for use only by t... | 370f1cba868c448746220512c38ea3e31d22a780 | 3,624,860 |
def tjmaxx(tjmaxx_url: str) -> dict:
"""Scrape product information from Tjmaxx
Keyword arguments:
tjmaxx_url -- a product url from tjmaxx.tjx.com
"""
tjmaxx_product = _tjmaxx._tjmaxx(tjmaxx_url)
return tjmaxx_product | d319a6ec195db7b518dd51b200e66b96c2461f18 | 3,624,861 |
def _top_N_similar(source_inds, source_mat, target_mat, n,
exclude_mat_sp=None, source_biases=None, target_biases=None,
simil_mode='cosine'):
"""
for each row in specified inds in source_mat calculates top N similar items in target_mat
:param source_inds: indices into s... | 6bd5e7db4bc1ed717db3504535babc7b9be84704 | 3,624,862 |
import io
def spawn_compressor(exe, filename, mode, buffering=-1, encoding=None, errors=None, newline=None):
"""Spawn a subprocess to run a (de)compressor like gzip or bzip2.
Args:
exe (str): executable file name (must be fully qualified or found on the current PATH)
filename (str or file obj... | d8b8390ac2002d7b408db41c7df180578a815a1a | 3,624,863 |
import os
def train_word2vec(sentence_matrix,
vocabulary_inv,
num_features=100,
min_word_count=1,
context=10):
"""
Trains, saves, loads Word2Vec model
Returns initial weights for embedding layer.
inputs:
sentence_matrix #... | 422994c02da2b9d1194dc0fe215b6242b3a7d9dc | 3,624,864 |
def rgrids(radii=None, labels=None, angle=None, fmt=None, **kwargs):
"""
Get or set the radial gridlines on the current polar plot.
Call signatures::
lines, labels = rgrids()
lines, labels = rgrids(radii, labels=None, angle=22.5, fmt=None, **kwargs)
When called with no arguments, `.rgrids` ... | a7e4c936994ba89474751c3837ffd78c53f800d6 | 3,624,865 |
def connect_to_cloudfiles(region=None, public=None):
"""Creates a client for working with CloudFiles/Swift."""
if public is None:
is_public = not bool(get_setting("use_servicenet"))
else:
is_public = public
ret = _create_client(ep_name="object_store", region=region,
public=is... | 47aa0b3c34918744844754754d3685180a0d3e7a | 3,624,866 |
def vec_init(seq, amino_acid):
"""
This function is for initialize feature stats table
"""
bi_gram = {}
for acid_1 in amino_acid:
for acid_2 in amino_acid:
temp_1 = acid_1 + acid_2
bi_gram[temp_1] = 0
pos_list = pos_init(seq, amino_acid)
for pos_motif in pos... | 16418e67cd216c657ccc5668c58dd4e153c02891 | 3,624,867 |
import os
import tqdm
def prepare_for_tokenizer(
lmdb_path: str,
):
"""
Convert a LMDB-stored paragraphs set into a plain text for use with tokenizer.
The plain text file will be removed if any exception occurs while creating it.
"""
pt_filename = os.path.join(lmdb_path, 'all_paragraphs.tx... | bcdf5bda329799b8d5ae8724ff487813c743bb7b | 3,624,868 |
from mappings import JobStatusAnalyzer
import logging
def querycondorlib(remotecollector=None, remoteschedd=None, extra_attributes=[], queueskey='match_apf_queue'):
"""
queries condor to get a list of ClassAds objects
We query for a few specific ClassAd attributes
(faster than getting everything)
... | 35d712643eb735b7153d1c87f7c64238c3ba3b47 | 3,624,869 |
def has_trailing_character_return(str_multiline: str) -> bool:
"""
>>> has_trailing_character_return('jhgjh\\n')
True
>>> has_trailing_character_return('jhgjh\\ntestt')
False
"""
if len(str_multiline) and str_multiline[-1] == '\n':
preserve_trailing_linefeed = True
else:
... | 21e6a7c9bb76e37ee05ed61b2012ec3a92413540 | 3,624,870 |
def get_short_help_from_long(val):
""" Extracts 100% of the help - except for the details section within
option descriptions.
Rules:
1. Sections of options are defined by having the string "Options: " within the first
thirty characters of the line. The section ends with a blank ... | 60d77f119dffaa68e81b7743da309a6a5ecd1912 | 3,624,871 |
from typing import Any
from typing import List
import importlib
def decorate_function_view(view: Any, decorators: List[str] = None) -> Any:
"""
Similar to :func:`.decorate_class_view`, but for function based views
"""
if not decorators:
decorators = []
for decorator in decorators:
... | d4ecf01d3220e425288d0faf9b7e587b57fcc181 | 3,624,872 |
def linenos(f):
# type: (FunctionType) -> Set[int]
"""Get the line numbers of a function."""
return {instr.lineno for instr in Bytecode.from_code(f.__code__) if hasattr(instr, "lineno")} | 80e518d08d635b920098599787b6b8a8f401e727 | 3,624,873 |
from typing import Callable
def firm_up(t: Callable[[np.ndarray], np.ndarray], alpha: float=0.5) -> Callable[[np.ndarray], np.ndarray]:
"""converts given nonexpansive mapping into a firmly nonexpansive mapping whose fixed point coincides with the given one.
This implementation is based on the property of the ... | b5577d5b2d0d92a1763584efac86c7d6263414e8 | 3,624,874 |
def proposal_trusted(proposal_appid: Expr, trust_assetid: Expr):
"""
Check that the proposal is trusted (has been assigned a Trust token)
"""
trusted = AssetHolding.balance(appaddr(proposal_appid), trust_assetid)
return Seq([
trusted,
Return(And(trusted.hasValue(), trusted.value() > ... | a62572e519583ebcbb66b0bfe3aca673fc977d1d | 3,624,875 |
def get_genotype(read, ref_position, snp_position, cigar_tuple):
"""
Input read position, read sequence, SNP position, cigar
Return the base in read that is aligned to the SNP position
"""
cigar = { # alignement code, ref shift, read shift
0: ["M", 1, 1], # match, progress both
1: ["... | bf6b212b318ab8425124bbdd40d5ab54d05e8858 | 3,624,876 |
def inc_preemptible_resource(preemptible_resource_port, expr, stream_port):
"""Increase the count of available resource by the specified number, invoking the awaiting and preempted processes according to their priorities as needed."""
r = preemptible_resource_port
e = expr
s = stream_port
expect_pre... | 0929100e9a5e1e584f9bf47dad2fb50afaa8644c | 3,624,877 |
def selu(a: TensorLikeType, inplace: bool = False) -> TensorLikeType:
"""
Reference implementation of torch.nn.functional.selu
"""
if inplace:
raise NotImplementedError
alpha = 1.6732632423543772848170429916717
scale = 1.0507009873554804934193349852946
rhs = refs.mul(alpha, refs.e... | 25e0401d22e75615f7e6b565a92716173fe005a0 | 3,624,878 |
def get_blowout_properties():
"""
Return the properties for the base blowout case
Return the fluid properties and initial conditions for the base case of
a blowout from the Model Inter-comparison Study for the case of
20,000 bbl/d, 2000 m depth, GOR of 2000, and 30 cm orifice.
"""
... | 1521c62fac787e10ca6e7beaa356c82914043cc8 | 3,624,879 |
def strtobool(val: str) -> bool:
"""Convert a string representation of truth to True or False.
True values are 'y', 'yes', 't', 'true', 'on', and '1'.
False values are 'n', 'no', 'f', 'false', 'off', '0' and ''.
Raises ValueError if 'val' is anything else.
"""
match val.lower():
case "y... | f78c8aed3b9be896847c9a56de59de550b3f5381 | 3,624,880 |
import random
def clustering_kmember(data, k=25):
"""
Group record according to NCP. K-member
"""
clusters = []
# randomly choose seed and find k-1 nearest records to form cluster with size k
r_pos = random.randrange(len(data))
r_i = data[r_pos]
while len(data) >= k:
r_pos = fi... | 8e8daaf6c9e952617def89124b62fdda4f6731f2 | 3,624,881 |
import torch
def box_refinement(box, gt_box):
"""Compute refinement needed to transform box to gt_box.
box and gt_box are [N, (y1, x1, y2, x2)]
"""
height = box[:, 2] - box[:, 0]
width = box[:, 3] - box[:, 1]
center_y = box[:, 0] + 0.5 * height
center_x = box[:, 1] + 0.5 * width
gt_h... | a10380c4a80de52bf7145fe134e12e49b5cf66a6 | 3,624,882 |
def ibis_schema_apply_to(schema, df):
"""Applies the Ibis schema to a pandas DataFrame
Parameters
----------
schema : ibis.schema.Schema
df : pandas.DataFrame
Returns
-------
df : pandas.DataFrame
Notes
-----
Mutates `df`
"""
for column, dtype in schema.items():
... | df54134f77923a23c65cf5cbcf33bad1fa23cce8 | 3,624,883 |
def featurenet_3D_backbone(input_tensor=None, input_shape=None,
n_filters=32, **kwargs):
"""Construct the deepcell backbone with five convolutional units
Args:
input_tensor (tensor): Input tensor to specify input size
n_filters (int): Number of filters for convolution... | 2e6d6e210713ce70368b06cafb3a998ad216d1b0 | 3,624,884 |
def policy_document(policy_document_id):
"""
Policy Document
"""
logger.debug("policy-document page called")
policy_document = load_from_api('policy-document', policy_document_id)
logger.debug(policy_document)
return render_template(
'policy_document_detail.html',
policy_docu... | 5334485fef0800a5f489f8ae6545b51f7654225c | 3,624,885 |
def clean_setting(
name: str,
default_value: object,
min_value: int = None,
max_value: int = None,
required_type: type = None,
choices: list = None,
):
"""cleans the input for a custom setting
Will use `default_value` if settings does not exit or has the wrong type
or is outside def... | cba1424a52cfd3b25326963a9c82451e253aa39f | 3,624,886 |
import os
import logging
def download_file(source, dest):
"""Attempt to download a file to the destination."""
# determine the file name
fname = os.path.basename(source)
local_path = os.path.join(dest, fname)
try:
logger.info("Downloading {0}".format(source))
response = urlopen(so... | 2e6c45a14f8f6dc41981a3ec78a8de6a4d38448b | 3,624,887 |
def get_namespaces(objects=None):
"""
Get a list of all namespaces within objects or of the entire scene
Args:
objects (unicode, list): List of objects to get namespaces from
Returns:
List of namespaces
"""
# if no objects were specified
if not objects:
# get all nam... | 2b0097c63d9d0218c4faadf91c3ddcafef3eb777 | 3,624,888 |
from typing import Dict
from typing import Optional
def exec_file(
ctx: Context, file: str, inout_env: Dict[str, bytes], *, gate: FlagDelegate, stack: Optional[Stack] = None
) -> int:
"""
This function never raises exceptions in response to invalid syntax or a programmable error.
Instead, it uses exit... | 273e2c6ef9e069da426f57f3accd99aeb81e312f | 3,624,889 |
def WDRMSE(obs, mod, axis=None):
""" Wind Direction Root Mean Square Error (model unit)"""
return np.ma.sqrt(((circlebias(mod - obs)) ** 2).mean(axis=axis)) | 5586ba084200abb3cae047b580db4fe37883d048 | 3,624,890 |
def corners_2d(dims, origin=0.5):
"""generate relative 2d box corners based on length per dim and
origin point.
Args:
dims (float array, shape=[N, 2]): array of length per dim
origin (list or array or float): origin point relate to smallest point.
dtype (output dtype, optional): Def... | 39ebce8faefc7c55706dc2a3e0eabf608b39d88a | 3,624,891 |
from pathlib import Path
import os
def disk_usage(path: Path, human=False):
"""Return disk usage statistics about the given path."""
DiskUsage = namedtuple('DiskUsage', 'total used free')
st = os.statvfs(path)
free = st.f_bavail * st.f_frsize
total = st.f_blocks * st.f_frsize
used = (st.f_bloc... | 3a15e2c41a2d85f1ca51b65c2b7468e619b824fb | 3,624,892 |
def thrush(x, f):
"""
Applies function M{f} to value M{x}
@type x: Any
@type f: function
@rtype: Any
"""
return f(x) | 7819bfa4e0b394ac94acbd057c6d69e449fb18dc | 3,624,893 |
import argparse
def _init_args():
"""
:return:
"""
parser = argparse.ArgumentParser()
parser.add_argument('--net', type=str, default='xception')
parser.add_argument('--dataset', type=str, default='ilsvrc_2012')
return parser.parse_args() | 68fbb00a704968ce082fd8495d0d9a9fe5ee875a | 3,624,894 |
def draw_point_cloud(input_points, canvasSize=500, space=240, diameter=10,
xrot=0, yrot=0, zrot=0, switch_xyz=[0, 1, 2], normalize=True):
""" Render point cloud to image with alpha channel.
Input:
points: Nx3 numpy array (+y is up direction)
Output:
gray ... | a1101ecb861528b1757024d97d427258e3c0e3d6 | 3,624,895 |
def find_sha256_hash(db, url):
"""
Similar to find_script(), but returns only the sha256 hexdigest (if found)
"""
script, url_id = find_script(db, url, want_code=False)
if script:
return (script.get('sha256'), url_id)
return (None, None) | 169a519798c8d35ce80165ceb0682ce6bc940de1 | 3,624,896 |
import select
def getCommandOutput(command = None, inChild = None, returnError = False, returnCode = False):
"""
Runs the given command, returning the standard output.
If inChild is specified, no command is executed, but the already existing child process is read.
If returnError is True, then return ... | a77e1a959a6c47d6e9ddf5af4f475c48762f25ae | 3,624,897 |
def get_latent_vector_generator():
"""
create a function mapping from actor to the latent space
Note: the model must be trained beforehand
:return: the latent vectors generator of actors, and the list of actor ids
"""
encoder = load_encoder_model()
actors_adjacency, actors_feature, actors_i... | c4f05542a31ce7334a1463d7fe4f093351fe893d | 3,624,898 |
def ngram_to_points(ngram, A, log=False):
"""
Convert ngram like aab to steps. For example
A = {a:0.2, b:0.3, c:0.5}
steps = [0.2, 0.2*0.3, 0.2*0.3+0.5]
Or if log=True
steps = [log(0.2), log(0.2)+log(0.3), log(0.2)+log(0.3)+log(0.5)]
:param ngram: n-gram
:param A: a dictionary... | 5f03dbe5dfa92812fc3324933a81944dd94b1ef2 | 3,624,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.