content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def ReadBlackList(path):
"""Read a blacklist of forbidden directories and files.
Ignore lines starting with a # so we can comment the datafile.
Args:
path: file to load the blacklist from.
Returns:
dictionary of path:True mappings
"""
blacklist_file = open(path, 'r')
catalog = []
for entry in ... | 694b9bd8c09385677d49e8563ac8f08b923cadb0 | 35,800 |
def height_water_critical(FlowRate, Width):
"""Return the critical local water height.
:param FlowRate: flow rate of water
:type FlowRate: u.m**3/u.s
:param Width: width of channel (????????)
:type Width: u.m
:return: critical water height
:rtype: u.m
"""
ut.check_range([FlowRate.m... | 39602709854f04e007533fe133a47edf722e6a5a | 35,801 |
import requests
import time
import warnings
def getRBPartInfo(api_key, part_id):
"""
Get part information from rebrickable.com.
FIXME: Could be issues with too many requests per second? We are
sending two requests per part.
"""
urls = ["https://rebrickable.com/api/v3/lego/parts/" + str... | c6482d4282c69ff409543fb8d00c9051fe7b2938 | 35,802 |
def author_number_of_files_owned(results):
""" Number of files owned by author.
:param results: results from author_file_owned()
:return: {author: number of files owned}
:rtype: dict
"""
authors = defaultdict(int)
for item in results:
authors[item.name] += 1
return authors | 7a4b07f58bc0f4898408a16353c7b5a7f2108904 | 35,803 |
def updateBounds(bounds, (x, y), min=min, max=max):
"""Return the bounding recangle of rectangle bounds and point (x, y)."""
xMin, yMin, xMax, yMax = bounds
return min(xMin, x), min(yMin, y), max(xMax, x), max(yMax, y) | 5e77fd6b422a252a5c8fc1b22a642ce05e5caf82 | 35,804 |
import urllib
def check_link(link, attempts):
"""
Check if the link is online trying to open it
:param link: the link to check
:param attempts: the max number of attempts
:return: True if the link is online, False otherwise
"""
i = 0
for i in range(0, attempts):
try:
... | 883ccf88777aeffaaf25f13d9d92fc30c27e745a | 35,805 |
def prepare_metadata(devkit_archive):
"""Extract dataset metadata required for HDF5 file setup.
Parameters
----------
devkit_archive : str or file-like object
The filename or file-handle for the gzipped TAR archive
containing the ILSVRC2012 development kit.
Returns
-------
... | 3d0e7cd536983c6f505bf5d62d5a8be4e50ab167 | 35,806 |
import io
def optimize_results(sample_names,
control_samples,
FPs_per_genome,
plot_roc=False,
plot_tuning_curve=False,
filtered_results_file=None,
output_dir=None,
mutatio... | add62fbf94e7f984d883957801b59dca022287a6 | 35,807 |
from datetime import datetime
def get_detections(
args,
config: DictConfig,
module: ModuleType,
model: nn.Module,
geoscreens_data: LightningDataModule,
video_id: str,
):
"""
Returns:
Dict: keys = frame index, value = a dict of detections that looks something like::
... | 3c28598b6b9bd465434932ee8809e73cecedf698 | 35,808 |
import os
def _append_build_id(base_name):
"""Returns base_name with BQ-friendly `GITHUB_SHA` appended"""
build_id = os.environ.get("GITHUB_SHA", None)
if not build_id:
raise Exception("Unable to get build id; env var GITHUB_SHA not set")
# valid BQ table names only allow underscores and alp... | 5a9a7c3cd5412a1ea27c1fe25a656eaea2e4bbcf | 35,809 |
def gen_format_string(a: np.array):
"""
Generates a matrix format in the shape of a.
>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(gen_format_string(a))
┌ ┐
|{:>2}{:>2}{:>2} |
|{:>2}{:>2}{:>2} |
|{:>2}{:>2}{:>2} |
└ ┘
The template can be rendered with the help of... | c975ab9c99b75f14757f8fecc5c1215180af3f98 | 35,810 |
import logging
from typing import OrderedDict
from typing import Counter
def learn_categories(links, **kwargs):
""" learns word categories (clusters)
:param links: pd.DataFrame(columns = ['word', 'link', 'count'])
:param kwargs: disclosed below in kwa(...)
:return: (categories, re)
"""
... | b71a92ed0461426dcbddcfeb026aca26e404dde2 | 35,811 |
def create_quantum_model():
"""Create a QNN model circuit and readout operation to go along with it."""
data_qubits = cirq.GridQubit.rect(4, 4) # a 4x4 grid.
readout = cirq.GridQubit(-1, -1) # a single qubit at [-1,-1]
circuit = cirq.Circuit()
# Prepare the readout qubit.
circuit.append(cirq.... | c7dcc577f3ef7a5ced1dd4b9bf08be4e5065d315 | 35,812 |
def get_completeness_coef(iocs_per_feed: int, total_iocs: int) -> float:
"""
This function wrapper is intended for
calculate feed completeness factor
Parameters:
iocs_per_feed: int — Number of IoCs in the CTI feed
total_iocs: int — Number of IoCs across all CTI feeds
... | 9f677549f90b8e8d6eb2d328eb91068ea32920bf | 35,813 |
def valid_model(model):
"""Check if the model is valid."""
if model is None:
raise ValueError("The SaraBotTagger model can not be None")
path_to_model = f'{absolute_path}/bot_model/{model}'
model = load(path_to_model)
return True | 8e00d0907e31f1370bd52532ae06df6f7458737a | 35,814 |
def getApi(token_path):
""" Логинится в вк и возвращает готовую к работе сессию """
with open(token_path) as f:
token = f.read().strip()
session = vk_api.VkApi(token=token, api_version="5.52")
return session.get_api() | 143b11a9e2612bc10bf41b716d21adcf14bdc60d | 35,815 |
import re
def projects():
"""
General purpose provider of paths to test projects with the conventional layout
"""
base_path = PROJECT_ROOT / "tests" / "fixtures"
projects = {
re.match(r"^([_\w]+)_project", path.name).groups()[0]: path.resolve()
for path in base_path.glob("*_project... | 250473fbb89f65d8163e7d2f6085cc7217ea2860 | 35,816 |
def qair2rh(qair: xr.DataArray, temp: xr.DataArray, pres: xr.DataArray) -> xr.DataArray:
"""
Get the relative humdity from the specific humidity.
Args:
qair (xr.DataArray): The specific humidity (dimensionless).
temp (xr.DataArray): The temperature (kelvin).
pres (xr.DataArray): The... | 3e230a3c79d8106486f3eb3b67a1459705bbfb89 | 35,817 |
import re
def read_trees(input_dir, features, signals, backgrounds, selection=None,
negative_weight_treatment="passthrough",
equalise_signal=True, branch_w="EvtWeight",
col_w="MVAWeight", col_target="Signal"):
"""
Read in Ttrees.
Files in the input directory s... | 88e27750eb84173f0505533da4c0e3e44d80a9cf | 35,818 |
def package_form(request):
"""
Upload a new package
"""
return render(request, 'packages/package_form.html', {
'form': PackageForm(),
}) | f57c92fcdbf67a4d410af6ca20f44e3d0bdb72a5 | 35,819 |
from typing import List
def destory(list_id):
"""Delete list."""
list = db_session.query(List).filter(List.id == list_id).first()
if(list.user_id != login_session['user_id']):
flash("This list does not belong to your account")
return redirect(url_for('list.index'))
db_session.delete(li... | 54899380c4a80d076815b9fe3f835fc44fb5d911 | 35,820 |
def specs_to_ir(specs, version='0.1b1', debug=False, route_whitelist_filter=None):
"""
Converts a collection of Stone specifications into the intermediate
representation used by Stone backends.
The process is: Lexer -> Parser -> Semantic Analyzer -> IR Generator.
The code is structured as:
... | 049cd86b028216a83f7d40c76a4de67975df4405 | 35,821 |
import os
def expectedtime(fn):
"""Calculate the expected time for conversion.
Based on my machine, the average conversion speed is 75 kiB/s. The range is between
60 kiB/s and 90 kiB/s.
Arguments:
fn: file path.
Returns:
A 3-tuple of datetime.timedelta objects representing the m... | 35cdaab1e728b97ae54573453ae452afbc4609a1 | 35,822 |
def categorize_os():
"""
Categorize operating system by its parent distribution.
Args:
None
Raises:
None
Returns:
None
"""
os_name = get_system_name()
if os_name in ["ubuntu", "kali", "backtrack", "debian"]:
return "debian"
# elif some other OS, add... | 84df15c78e3e9c40294e6ad77afbac857df3e29e | 35,823 |
def has_names_directive(block: FencedBlock) -> bool:
"""Does the code block have a share-names or clear-names directive."""
assert block.role == Role.CODE, "must be a Python code block."
return block.has_directive(Marker.SHARE_NAMES) or block.has_directive(
Marker.CLEAR_NAMES
) | cd70019e724c4f0370fa1c3c9db8d52c22c80e3f | 35,824 |
import math
def make_reber_classification(n_samples, invalid_size=0.5,
return_indeces=False):
"""
Generate random dataset for Reber grammar classification.
Invalid words contains the same letters as at Reber grammar, but
they are build whithout grammar rules.
Paramet... | c38627651ed2fb3f18bbebbefe3e06801c1accf5 | 35,825 |
def batchify(X, size):
"""
```
Splits X into separate batch sizes specified by size.
Args:
X(list): elements
size(int): batch size
Returns:
list of evenly sized batches with the last batch having the remaining elements
```
"""
return [X[x : x + size] for x in rang... | d3e4ad015eb3b8bb4cdbaa6bf87a2bc1989c4614 | 35,826 |
def _single_entity_stmt(
start_day: dt,
end_day: dt,
event_types: tuple[str, ...],
entity_id: str,
entity_id_like: str,
) -> StatementLambdaElement:
"""Generate a logbook query for a single entity."""
stmt = lambda_stmt(
lambda: _select_events_without_states(start_day, end_day, event... | 0cbc33f1715b65cfbd803ab9674c6264d73a096e | 35,827 |
def listtoslides(data):
"""Checks if format is correct + adds img and durration elements"""
slides = []
for slide in data:
slide = slide[:2]
slide[0] = slide[0][:25]
slide[1] = slide[1][:180]
slide.append("imgpath")
slide.append(0)
slides.append(slide)
ret... | b4b7180fc5755eff6a32ff8b448f1dfd65ad6f75 | 35,828 |
def clean_data(sample):
"""
整体清洗函数,为了方便多线程使用
Args:
sample: 一个元组,包含正文内容和标题内容
Returns:
"""
(content, title) = sample
sample = dict()
# 清洗数据
sample["title"] = clean_weibo_title(title.strip())
sample["content"] = clean_weibo_content(content.strip())
return sample | 268f98dfc8e8aaeb7f6a10887278964b6deb56db | 35,829 |
def read_cat_as_dataframe(fichero_cat, tipo_registro, columns=None):
"""
Devuelve un pandas.DataFrame con los registros del el tipo deseado
- fichero_cat: fichero .cat, puede estar comprimido.
- tipo_registro: Tipo de registro, p.ej.: '11', '15'
- columns: Lista con los nombres de l... | 47a25aa147bcf00ff3aa45abc4c5ef524a11761a | 35,830 |
def init_cppn_from_img(image: np.array, color: bool = True, sim_threshold: float = 0.6, max_optim_iter: int = 10000,
init_stop_bound: int = 100) -> CPPN:
"""
Initializes a CPPN using the given image by optimizing the SSIM score between the CPPNs output and the image.
This is done by t... | bb97754776dfceb05d144e7f125d5eda2008a5bd | 35,831 |
def unwind_create_nodes_query(data, labels=None, keys=None):
""" Generate a parameterised ``UNWIND...CREATE`` query for bulk
loading nodes into Neo4j.
:param data:
:param labels:
:param keys:
:return: (query, parameters) tuple
"""
return cypher_join("UNWIND $data AS r",
... | 3c0c444ecd1497399c27607bf0deb3026f017a03 | 35,832 |
def _scalePoints(points, scale=1, convertToInteger=True):
"""
Scale points and optionally convert them to integers.
"""
if convertToInteger:
points = [
(int(round(x * scale)), int(round(y * scale)))
for (x, y) in points
]
else:
points = [(x * scale, y ... | 3ce3fedfbf7c428386af1571cc1a770bd9f66018 | 35,833 |
def get_customer_tax_rate(request, product):
"""Returns the specfic customer tax for the current customer and product.
"""
cache_key = 'cached_customer_tax_rate_%s' % product.pk
if request and hasattr(request, cache_key):
return getattr(request, cache_key)
customer_tax = get_first_valid(requ... | 64491092626f0bb12c9a8a0522fc81acfe55846c | 35,834 |
def iscoroutinepartial(coro):
"""
Function returns True if function it's a partial instance of coroutine. See additional information here_.
:param coro: Function
:return: bool
.. _here: https://goo.gl/C0S4sQ
"""
while True:
parent = coro
coro = getattr(parent, 'func', No... | dace8744f79475518a0c52f488c17d9b685fae07 | 35,835 |
import os
import stat
def write_key(key):
"""Write the key to a file so it can me used to make a secure connection.
To enhance security a bit, the file is firstly opened, written, closed,
chmodded to enhance security a bit, and then the key is written to the file.
string key
return string path_t... | 11fb3a9d2154db5a7d0bf423cbbc7b2cc0754178 | 35,836 |
def AppendFchunk(funcea, ea1, ea2):
"""
Append a function chunk to the function
@param funcea: any address in the function
@param ea1: start of function tail
@param ea2: end of function tail
@return: 0 if failed, 1 if success
@note: If a chunk exists at the specified addresses, it must hav... | 709c1790d6dd1e472ab97efdab84eeef9a87ab8f | 35,837 |
def testing_audio():
"""Load data for the tests."""
return sf.read(TEST_WAVEFILE_PATH, always_2d=True, dtype='float32') | c61f3429bcb1ed7745ae07282b65e0b0b0a6cfb8 | 35,838 |
def linr(xdata, ydata):
"""Return the linear regression coefficients a and b for (x,y) data.
Returns the y-intercept and slope of the straight line of the least-
squared regression line, that is, the line which minimises the sum of
the squares of the errors between the actual and calculated y values.
... | 0761004020d5a4b723e39f9988a4e379a64506cd | 35,839 |
def album_sticker_get(client, album, sticker):
"""Gets a sticker associated with an album."""
# I am pretty sure that MPD only implements stickers for songs, so
# the sticker gets attached to the first song in the album.
tracks = client.find("album", album)
if len(tracks) == 0:
return
... | 4fd02292c1d7be672de9ccc926f5880c7b831503 | 35,840 |
def print_confusion_matrix(confusion_matrix, class_names, filename, normalize = True, figsize = (5,5), fontsize=16):
"""Prints a confusion matrix, as returned by sklearn.metrics.confusion_matrix, as a heatmap.
Arguments
---------
confusion_matrix: numpy.ndarray
The numpy.ndarray object retu... | bfb7cfd33a35d5e1b1a08255c2e777c26d45c566 | 35,841 |
from typing import Optional
import os
def parse_zpe(path: str) -> Optional[float]:
"""
Determine the calculated ZPE from a frequency output file
Args:
path (str): The path to a frequency calculation output file.
Returns: Optional[float]
The calculated zero point energy in kJ/mol.
... | 24a935fcde5a98b32fbd143e1e3a5ec1bba46f8d | 35,842 |
from re import T
def group():
""" RESTful CRUD controller """
tablename = "pr_group"
table = s3db[tablename]
response.s3.filter = (table.system == False) # do not show system groups
s3mgr.configure("pr_group_membership",
list_fields=["id",
"p... | 110e7c17dc8a4a3f129845f278e1a4d9760da8c3 | 35,843 |
import torch
def colorization_inference(model, img):
"""Inference image with the model.
Args:
model (nn.Module): The loaded model.
img (str): File path of input image.
Returns:
np.ndarray: The predicted colorization result.
"""
# cfg = model.cfg
device = next(model.p... | 8d47cfb2c5242e23ebd4e57952badb3d41bec450 | 35,844 |
def std_ver_minor_mixedinst_valid_fullsupport(request):
"""Return an valid minor version number that has full support in pyIATI.
Todo:
Add decimal representations where possible.
"""
return request.param | 37b3e9d769b9dbbfac65eaa3ba37d22c8516dd69 | 35,845 |
def load_templates_from_dir(directory: str) -> Environment:
"""Produce an Environment targeted at a directory."""
return Environment(loader=FileSystemLoader(directory)) | 8d2e8062164d4fa02be41c059253524e5da86b92 | 35,846 |
def merge_schemas(a, b, path=None):
"""Recursively zip schemas together
"""
path = path if path is not None else []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_schemas(a[key], b[key], path + [str(key)])
elif ... | 8915f5e6fa0c352379852b088a9fe111fc27a719 | 35,847 |
def resample_dataarray2d_to_vertex_grid(da_in, gridprops=None,
xyi=None, cid=None,
method='nearest',
**kwargs):
"""resample a 2d dataarray (xarray) from a structured grid to a new
dataaraay of... | f2dacc6cad1fa10ee9014668b4aab853ab60f01f | 35,848 |
import argparse
def parse_arguments():
"""
Basic argument parsing using python's argparse
return: Argparse parser object
"""
parser = argparse.ArgumentParser("Rfam fasta file generation handler")
parser.add_argument('--seq-db', help="Sequence database in fasta format",
... | 60facf1af6361c867938ba567749294b6a02e9f4 | 35,849 |
from sys import path
def load_alexa(limit=None, is_test=False):
"""
Reads top @limit number of popular domains based on alexa.com
"""
alexa_domains = set()
alexa_top_1m = data_folder
if not path.exists(alexa_top_1m):
if is_test:
alexa_top_1m = fetch_alexa_data(url=top_100_... | 56e4831542fa86d212b0d015497417aa73a0b53e | 35,850 |
def an_capabilities(b: bytes) -> list:
""" Decode autonegotiation capabilities
Args:
b: coded ***
Returns:
human readable ***
"""
cap: list = []
i: int = (b[0] << 8) + b[1]
cap_list = ['1000BASE-T (full duplex mode)',
'1000BASE-T (half duplex mode)',
... | 1e8b60582ad27ab6c1feafaac3992c4dc0550bbf | 35,851 |
def peer_count(interface_name: str) -> int:
"""Number of peers in the mesh"""
with mesh_client() as client:
return len(client.getPeers(interface_name)) | 1caa3f916344a6fc919dbe18559e6f4606f53316 | 35,852 |
def german_words():
"""Provides same known words list as used by the main script."""
return get_dictionary(language="de") | 4a87fed3c451fa481373c209b788d1032e3bf7c0 | 35,853 |
import os
def get_source_feed_from_folder_name(dir_path):
"""
get_source_feed_from_folder_name
Get source feed from tf record name
:param dir_path: TFRecord folder name
:return: Source feed name
"""
if os.path.isdir(dir_path):
dir_name = os.path.basename(dir_path)
source... | aba61f7363fe82a5b2a70fd9c8d83651e2f82706 | 35,854 |
def result():
"""Get results when ready regarding a previously submitted task."""
# Retrieve JSON parameters data.
data = request.get_json() or {}
data.update(dict(request.values))
tid = data.get("tid")
if not tid:
raise abort(400, "missing 'tid' data")
# Get the result (if exists a... | 809ac8bc762fee45e4fcfb237085a4b998b328e9 | 35,855 |
def pushWPStoArray(aln, halfWPSwindow, start, end, tssWindow, isize, wpsWindow):
"""
for a given alignment, compute the regions that can be fully aligned and not
e.g. [-1, -1 , -1, 1 , 1, 1, 1, 1, 1, -1, -1, -1] for a wps window -f 6 (halfwindow 3 )
this will be added to the defined transcription start ... | 2f94dfa762f9997793a9a0d11bc47a375a06283f | 35,856 |
import logging
import sys
def stdout_handler(level: int = logging.INFO) -> logging.Handler:
"""標準出力用ログハンドラ."""
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(level=level)
formatter = logging.Formatter(
"[%(asctime)s] [%(process)d] [%(name)s] [%(levelname)s] %(message)s"
)
... | 451d5534acb42a5b4dbc064bf08680e303f1f721 | 35,857 |
def usgs_lithium_parse(*, df_list, source, year, **_):
"""
Combine, parse, and format the provided dataframes
:param df_list: list of dataframes to concat and format
:param source: source
:param year: year
:return: df, parsed and partially formatted to flowbyactivity
specifications
"... | 17da5e3f8f25b2a2477f6eea4656ad28c307b760 | 35,858 |
import collections
def convert_keys_to_string(dictionary):
""" Recursively converts dictionary keys to strings.
Utility to help deal with unicode keys in dictionaries created from json requests.
In order to pass dict to function as **kwarg we should transform key/value to str.
"""
if isins... | 01f15be1419d21758e215216b41819e5c4dbcf0f | 35,859 |
def detectron2_available() -> bool:
"""
Returns True if Detectron2 is installed
"""
return bool(_DETECTRON2_AVAILABLE) | 16531363e7728b02fb5639d93d66f82cc7647b8b | 35,860 |
from operator import or_
def delete_user_by_id_and_name(id):
""" username 或者id 删除用户 """
user = User.query.filter(or_(User.id.like(id), User.username.like(id))).first_or_404()
user.delete()
return user | d23485963e1b2b54957532aa8ea3ccb7575e0d07 | 35,861 |
def branch(default='master'):
"""used in the `git.latest` state for the `branch` attribute.
If a specific revision exists DON'T USE THE BRANCH VALUE.
There will always be a branch value, even if it's the 'master' default"""
if cfg('project.revision'):
return '' # results in a None value for git... | f1e1cbe73e27955c4e571115a72108aba9ba7b00 | 35,862 |
import requests
def instance_types(gvar):
"""
List EC2 instance types for the specified cloud.
"""
mandatory = ['-cn']
required = []
optional = ['-CSEP', '-CSV', '-g', '-H', '-h', '-itc', '-itf', '-itmn', '-itmx', '-itos', '-itp', '-itpm', '-NV', '-ok', '-r', '-s', '-V', '-VC', '-v', '-v', '-... | 676282fa68986a7545ff000f935714e3cae65dca | 35,863 |
import math
def math_logsumexp(data):
"""
achieve logsumexp by numpy
Args:
data: float array
Returns:
Float
"""
res = []
for i in data:
res.append(math.exp(i))
return math.log(sum(res)) | 44a056d2aaa0298c62cc21ae2e224a974956ed8b | 35,864 |
def only_numbers(iterable):
"""Returns whether the given iterable contains numbers (or strings that
can be converted into numbers) only."""
return not any(lenient_float(item) is None for item in iterable) | d73735ed69aa85bd3982eade6a15de1bf76afcf4 | 35,865 |
def gaussian(birth, pers, mu=None, sigma=None):
""" Optimized bivariate normal cumulative distribution function for computing persistence images using a Gaussian kernel.
Parameters
----------
birth : (M,) numpy.ndarray
Birth coordinate(s) of pixel corners.
pers : (N,) numpy.ndarray
... | 1c5321b31b7efdc501df72ee77fad17fbcc34056 | 35,866 |
def login():
"""
TASKS: write the logic here to parse a json request
and send the parsed parameters to the appropriate service.
return a json response and an appropriate status code.
"""
data = request.get_json()
user = User.objects(username=data.get('username')).first()
... | 3a8e2c385d77705c5823e771c36311856bce2cae | 35,867 |
import time
def server_reachable_by_credentials_with_retry(server_url, user, password):
"""
@param server_url: Basic server url to connect and log in
@param user: User for Ambari REST API authentication
@param password: Password for the user used to authenticate the Ambari REST API call
"""
retry_counter ... | 1b348650e9cfdade3aacd6487f792cdd43de3ed3 | 35,868 |
def _process_rules_list(rules, match_rule):
"""Recursively walk a policy rule to extract a list of match entries."""
if isinstance(match_rule, policy.RuleCheck):
rules.append(match_rule.match)
elif isinstance(match_rule, policy.AndCheck):
for rule in match_rule.rules:
_process_ru... | 67ffaac731e709e39b3120fd32ee3a0ad8dae299 | 35,869 |
def get_memoryview_and_address(data):
"""Get a memoryview for the given data and its memory address.
The data object must support the buffer protocol.
"""
# To get the address from a memoryview, there are multiple options.
# The most obvious is using ctypes:
#
# c_array = (ctypes.c_uint8 ... | 7898bb5d79e8b839b1009ff549eb58ee8c2f71ed | 35,870 |
def get_inv_dist_mat(node_list):
"""
Get pairwise distance matrix for specified nodes in node list.
Args:
node_list (list): Nodes for which to compute the pairwise distances
Returns:
(numpy.ndarray): Matrix of pairwise distances
"""
# Initialize array.
dist_mat = np.ze... | 27b600ef8ce03a0ea3a8c791e6cedcd7091e3a5b | 35,871 |
import torch
def stableSoftMax(x):
"""
stableSoftMax computes a normalized softmax
:param x: Tensor List
:return: Tensor List
"""
x = torch.exp(x - torch.max(x))
return x/torch.sum(x) | fa1e017812b7fd0c4e964eafb3fd59eae141203b | 35,872 |
def is_item(var):
"""
is this a single item
"""
return is_str(var) or (not is_iterable(var)) | 3a56cb9832a77c77271087b5f653a9ef7b1a40a9 | 35,873 |
def _str_plot_fields(val, f, field_filter):
"""
get CSV representation of fields used by _str_plot
:returns: list of fields as a CSV string, ``str``
"""
s = _sub_str_plot_fields(val, f, field_filter)
if s is not None:
return "time,"+s
else:
return 'time,' | 2d1be13fb801ea03ec34ef3810d6cc6dd11782b9 | 35,874 |
def cypher_repr(value, **kwargs):
""" Return the Cypher representation of a value.
This function attempts to convert the supplied value into a Cypher
literal form, as used in expressions.
"""
encoder = CypherEncoder(**kwargs)
return encoder.encode_value(value) | 7e0a986206236399901c77d467c1c726573a1b33 | 35,875 |
def compareResultByTimeTupleRangesAndFlags(result, check, dateOnly=False):
"""
Ensures that flags are an exact match and time tuples a close match when
given data in the format ((timetuple), (timetuple), flag)
"""
return (_compareTimeTuples(result[0], check[0], dateOnly) and
_compareTime... | e2be1b7bdec5dcdaef8746349b4e7a56d54c8c19 | 35,876 |
def check_valid_title(title):
"""Checks if the title contains valid content"""
title_issues = TitleIssues(title_contains_nsfw=title_contains_nsfw(title))
return title_issues | 39bc77dce1a9136a7ab70c802bb90416655043b8 | 35,877 |
from typing import Any
import typing
from typing import Dict
def ValueWidget(value: Any = None, on_value: typing.Callable[[Any], Any] = None) -> Element[ipywidgets.widgets.valuewidget.ValueWidget]:
"""Widget that can be used for the input of an interactive function
:param value: The value of the widget.
"... | 6317cdb731902f9ae24435ad290e136f75680005 | 35,878 |
def list_all_volumes():
"""Lists all available issues and volumes from the VA registry webpage. Only returns
volumes that are available on HTML.
Returns
-------
volumes : dict
A dictionary where the volumes are the keys and the issues are list entries.
"""
volumes = set()
html =... | 5dea8c7db1089a427282c7c76f780d37895f689f | 35,879 |
def get_distribution(dist):
"""Return a PyMC distribution."""
if isinstance(dist, str):
if hasattr(pm, dist):
dist = getattr(pm, dist)
else:
raise ValueError(f"The Distribution '{dist}' was not found in PyMC")
return dist | fe8f120be29690d3ae33dfb974369b9f068cb325 | 35,880 |
import subprocess
import sys
import difflib
def enforce_cpp_formatting(
filename: str, contents: str, cursor: int, fix_issues: bool) -> int:
"""
Validator function that tests whether the style of the C++
source file follows that dictated by `.clang-format`.
"""
# Opening a pipe with Clang... | 4389c5436c6d6135a4a098efd9840e5ae7825d17 | 35,881 |
from datetime import datetime
def login_required(f):
"""
Validates the JWT and ensures that is has not expired and the user is still active.
:param f:
:return:
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not request.headers.get("Authorization"):
response... | e5582f78afa7acb0d2f7a8875d6f15bf2d9b73b1 | 35,882 |
from typing import List
from typing import Dict
def single__intent_topk_accuracy_score(
intent_prediction: List[Dict[str, str]],
y_true: List[str],
k: int = 1,
) -> float:
"""Compute the Accuracy of a single utterance with multi-intents
Accuracy of a single utterance is defined as... | c3a1c79692ef2031efc41cf6eb00c1e7139e0b20 | 35,883 |
def safeCellValue(cell, level=warning):
"""
셀 객체로부터 값을 안전하게 얻기 위한 함수
- 안전하지 않은 경우, 공백 문자열을 반환
"""
cellType = type(cell)
if cellType is openpyxl.cell.Cell or cellType is ReadOnlyCell:
noneSpaceString = str(cell.value).strip()
if noneSpaceString not in kIgnoreCharacters:
return noneSpaceString
else:
#... | df7e636d269c29180faec548d7acf308fed4351d | 35,884 |
def _get_port(config):
"""Get the server's port from configuration."""
if not config.has_option("server", "port"):
return None
port = config.getint("server", "port")
return port | bee579fcfc82ea80c593dc7bd93ff3d39e63ef7b | 35,885 |
def add_rectangular_plane(
center_loc=(0, 0, 0), point_to=(0, 0, 1), size=(2, 2), name=None):
"""Adds a rectangular plane specified by its center location, dimensions,
and where its +z points to.
Args:
center_loc (array_like, optional): Plane center location in world
coordinates... | 66d5410949d6702284e5b8027150129006691e86 | 35,886 |
def locations_3d_to_view(locations, extrinsic_matrix, intrinsic_matrix):
""" Transforms 3D locations to 2D camera view."""
world_points = np.ones((4, len(locations)))
for i in range(len(locations)):
world_points[0][i] = locations[i].x
world_points[1][i] = locations[i].y
world_points... | fc5f3c781641366a840bcd1db72704ff804b17c2 | 35,887 |
def superkeyword_presence(document, superkeywords):
"""Return 1 if document contains any superkeywords, 0 if not."""
for word in superkeywords:
if word in document.split():
return True
return False | 4b3223190651873d27562cc475ff623aa4cb5b47 | 35,888 |
def runTest(numClients, numServers, scripts, numFailures, runIndex):
"""
Run a single test of the Fault Tolerant SimpleFileLockService
This takes numClients, numServers, and the test scripts to run.
It SSHs into the requested number of servers and starts up the
Fault Tolerant SimpleFileLockService o... | f8de155564d415e327589bd1d551e3353faca22c | 35,889 |
import torch
def get_tensorrt_backend_config_dict():
""" Get the backend config dictionary for tensorrt backend
NOTE: Current api will change in the future, it's just to unblock experimentation for
new backends, please don't use it right now.
"""
# dtype configs
weighted_op_qint8_dtype_config ... | b43bea0d7421c39ea7005e40439b6ff66a8cd85e | 35,890 |
def shuf_device_inclusive_scan(data, temp):
"""
Args
----
data: scalar
input for tid
temp: shared memory for temporary work, requires at least
threadcount/wavesize storage
"""
tid = roc.get_local_id(0)
lane = tid & (_WARPSIZE - 1)
warpid = tid >> 6
roc.barrier()
... | a45d889202804493ebb653fce4cf66c3b58a941d | 35,891 |
def chicago(return_X_y=True):
"""Chicago air pollution and death rate data
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pand... | 5e31c114f1e935927c052f7ff3fecee4222f33ab | 35,892 |
def Normalize(normThisData: np.array,toThisData: np.array):
"""Normalize one dataset to another to produce a unitless output.
Args:
normThisData (np.array):
toThisData (np.array):
Returns:
np.array: normalized_data
Notes:
Currently only works for 1D arrays shape=[m,] ?????true? and returns same shape 1D a... | 2867d1835caf183b51e7c5dae0766cf6703312ea | 35,893 |
def bbiboll(df, n=10, k=3):
"""
BBI多空布林线 bbiboll(10,3)
BBI={MA(3)+ MA(6)+ MA(12)+ MA(24)}/4
标准差MD=根号[∑(BBI-MA(BBI,N))^2/N]
UPR= BBI+k×MD
DWN= BBI-k×MD
"""
# pd.set_option('display.max_rows', 1000)
_bbiboll = pd.DataFrame()
_bbiboll['date'] = df.date
_bbiboll['bbi'] = (_ma(df.... | 26b6d83f50ebeecee0f7d671ba896dbc89df0a33 | 35,894 |
import os
def find_file_bottom_up(name, from_dir=None):
"""Find the specified file/dir from from_dir bottom up until found or failed.
Returns abspath if found, or empty if failed.
"""
if from_dir is None:
from_dir = get_cwd()
finding_dir = os.path.abspath(from_dir)
while True:
... | 05659a296551e5d5307600df080527d0ba8e5af3 | 35,895 |
def calc_distance(y1, x1, y2, x2):
"""
Calculate distance between two locations using great circle distance.
Notes:
y1 = lat1, x1 = long1
y2 = lat2, x2 = long2
all assumed to be in decimal degrees
if (and only if) the input is strings
use the following conversions
... | 6fbe2a02e1e3fa196e138bcbb28e676a55461cce | 35,896 |
import unittest
def suite():
"""suite of unittest"""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestDBManager))
return suite | 9c0a313f137fc2c9530ea3f1a7ce8ad64d4f4a8f | 35,897 |
def convert_size_string_to_bytes(size):
"""
Convert the given size string to bytes.
"""
units = [item.lower() for item in SIZE_UNITS]
parts = size.strip().replace(' ', ' ').split(' ')
amount = float(parts[0])
unit = parts[1]
factor = units.index(unit.lower())
if not factor:
... | 5763a4cc266a66e64f63d5bbe8d73f10edf0a397 | 35,898 |
def dumps(data, expires):
"""加密"""
# 创建对象
serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, expires)
# 加密
token = serializer.dumps(data).decode()
return token | d38daca8895e544acea0de22e5e76926c21b34b5 | 35,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.