content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def histogram(name, tensor, max_bins):
""" 转换直方图数据到potobuf格式 """
values = make_np(tensor)
sum_sq, bucket_limit, bucket = make_histogram(values.astype(float), max_bins)
hist = HistogramProto(min=values.min(), max=values.max(), num=len(values.reshape(-1)),
sum=values.sum(), sum_s... | 9f9d04b281f018ea02276c29ae4b8c83b4790799 | 3,632,100 |
def max_pool_1d(input_tensor, pool_sizes=(2), stride_sizes=(1), paddings='same', names=None):
"""[summary]
Arguments:
input_tensor {[float, double, int32, int64, uint8, int16, or int8]} -- [A Tensor representing prelayer values]
Keyword Arguments:
pool_size {tuple} -- [Size of kern... | 9124428ba21d8108fd95b95cf36c97f147f2c1dc | 3,632,101 |
import base64
import gzip
import json
def decompress_metadata_string_to_dict(input_string): # pylint: disable=invalid-name
"""
Convert compact string format (dumped, gzipped, base64 encoded) from
IonQ API metadata back into a dict relevant to building the results object
on a returned job.
Parame... | c521da786d2a9f617c560916cc5f058b20cb3e21 | 3,632,102 |
import subprocess
import re
import tempfile
import os
def call_ck(i):
"""
Input: {
Input for CK
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0... | 06aaf0f4d3b740160312bd7fcb1d65b179c9a3e3 | 3,632,103 |
import struct
import socket
def inet_atoni(ip):
"""Like inet_aton() but returns an integer."""
return struct.unpack('>I', socket.inet_aton(ip))[0] | 3bd18b7aecf9a5a45033c7873163ee1387cb8a13 | 3,632,104 |
from typing import Optional
import warnings
def align_method_FRAME(
left, right, axis, flex: Optional[bool] = False, level: Level = None
):
"""
Convert rhs to meet lhs dims if input is list, tuple or np.ndarray.
Parameters
----------
left : DataFrame
right : Any
axis: int, str, or Non... | 77e30224e3d1e0077bc8b2fbac3cddc405b724b6 | 3,632,105 |
import re
def rep_unicode_in_code(code):
""" Replace unicode to str in the code
like '\u003D' to '='
:param code: type str
:return: type str
"""
pattern = re.compile('(\\\\u[0-9a-zA-Z]{4})')
m = pattern.findall(code)
for item in set(m):
code = code.replace(item, chr(int(item[2... | 70e28ea741f0347190628876b59e27a56a5c0ccf | 3,632,106 |
def delete_bucket_on_project(current_session, project_name, bucket_name):
"""
Remove a bucket from a project, both on the userdatamodel
and on the storage associated with that bucket.
Returns a dictionary.
"""
response = pj.delete_bucket_on_project(current_session, project_name, bucket_name)
... | 13ce8ef1b98bddbbed9cacecce9495914e2f723d | 3,632,107 |
def redir(url, text=None, target='_blank'):
"""Links to a redirect page
"""
text = text or url
html = '<a href="%(url)s" target="%(target)s">%(text)s</a>' % {
'url' : redir_url(url),
'text' : text,
'target' : target,
}
html = mark_safe(html)
return html | f1b5930887b3e0f2cce4751d2368dd2b4df6d5a2 | 3,632,108 |
def notifier_limit_over_checker(username, language_code, hard_limit):
"""
Function that takes a username and checks if they're above a hard monthly limit. This is currently UNUSED.
True if they're over the limit, False otherwise.
:param username: The username of the person.
:param language_code: Th... | a6e939f04a6b1598241d00a2c6dc6399df629d60 | 3,632,109 |
def lateral_steering_transform(steering, camera_position):
"""
Transform the steering of the lateral cameras (left, right)
Parameters:
steering (numpy.float): Original steering
Returns:
out (numpy.float): New steering
"""
if (camera_position == LEFT):
steering += ... | 7530b91fc4c59427f5a8fe22714ee48718bfed5f | 3,632,110 |
def fv_creator(fp, df, F, int_fwm):
"""
Cretes frequency grid such that the estimated MI-FWM bands
will be on the grid and extends this such that to avoid
fft boundary problems.
Inputs::
lamp: wavelength of the pump (float)
lamda_c: wavelength of the zero dispersion wavelength(ZDW) (... | 315dcc82fa3cd39937d905092f3b47de807d4e9f | 3,632,111 |
def calc_F1_score(scores, changepoints, tolerance_delay, tuned_threshold=None, div=500, both=True):
"""
Calculate F1 score. If tuned_threshold is None, return the tuned threshold.
Args:
scores: the change scores or change sign scores
changepoints: changepoints or starting points of gradual ... | 50865a03b47c30feb43352f6131c2e867318b1a0 | 3,632,112 |
def mul_pt_exn(pt, curve, k):
"""Computes point kP given point P, curve and k using Montgomery Ladder.
Args:
pt (tuple(int, int)): Point P.
curve (tuple(int, int, int)): Curve.
k (int): Multiplier.
Raises:
InverseNotFound: Thrown when point kP is the point at infinity.
... | 236dc176a2cf644a5c93054a93cc02535b4b77ef | 3,632,113 |
def get_enter_room_url():
"""
swagger-doc: 'schedule'
required: []
req:
course_schedule_id:
description: '课节id'
type: 'string'
res:
url:
description: '访问地址'
type: ''
"""
course_schedule_id = request.json['course_schedule_id']
with session_scop... | 53f55d5fc5b2e789f25561b0f02291317370fec0 | 3,632,114 |
def get_scene_nodes():
"""
Returns al nodes in current scene as GamEX nodes
:return: list<gx.dcc.DCCNode>
"""
node_list = list()
_append_children(get_root(), node_list)
return node_list, len(node_list) | 264bd1920f43aa4caaf07f17dbfbb3ca6bf1d2e1 | 3,632,115 |
import pdb
def interpolate(src_codes, dst_codes, step=5):
"""Interpolates two sets of latent codes linearly.
Args:
src_codes: Source codes, with shape [num, *code_shape].
dst_codes: Target codes, with shape [num, *code_shape].
step: Number of interplolation steps, with source and target inc... | e8c1e813e3445c03cfb0f841b0ae60eacfedb27f | 3,632,116 |
def get_flavored_transforms(penalty, kind):
"""
Gets the tranformation functions for all flavored penalties.
Parameters
----------
penalty: PenaltyConfig, PenaltyTuner
The penalty configs/tuner whose flavored penalties we want.
kind: str
Which kind of flavor we want; ['adaptive... | 2d70b1da646aea7fe5dd1f1957e0e5b31f0644de | 3,632,117 |
def f(spam, eggs):
"""
:type spam: list of string
:type eggs: (bool, int, unicode)
"""
return spam, eggs | 7d315898332b099eb1105f77b08bfe69e29c051e | 3,632,118 |
def GetAllowedGitilesConfigs():
"""Returns the set of valid gitiles configurations.
The returned structure contains the tree of valid hosts, projects, and refs.
Please note that the hosts in the config are gitiles hosts instead of gerrit
hosts, such as: 'chromium.googlesource.com'.
Example config:
{
... | 57dd75b253ed77585f23f06a095c2f1c0bcbf23a | 3,632,119 |
import requests
def cbsodatav3_to_gcs(id, third_party=False, schema="cbs", credentials=None, GCP=None, paths=None):
"""Load CBS odata v3 into Google Cloud Storage as Parquet.
For given dataset id, following tables are uploaded into schema (taking `cbs` as default and `83583NED` as example):
- ``cbs.8... | 6283163698925cf3743660810464b359f3719720 | 3,632,120 |
def process_chunk_of_genes(packed_args):
""" Control flow of compute coverage of pangenome per species and write results """
species_id, chunk_id = packed_args[:2]
if chunk_id == -1:
global semaphore_for_species
num_of_genes_chunks = packed_args[2]
tsprint(f" MIDAS2::process_chun... | a2f5d515a4695f1ab76bc3407241a16f99739e9f | 3,632,121 |
def get_Up(N=16, dt=0.1):
"""
INPUTS
N (int): is the length of the preview horizon;
dt (float): time step size;
OUTPUTS
Up: size [N, N] matrix;
"""
Up = np.tril(np.ones((N, N)), 0) * (1 / 6)
for i in range(N):
Up += np.diag(np.ones(N - i) * i, k=-i) / 2
Up += np.dia... | b10ed27076ba0c27ec3cb80777c01f6082a3f9a6 | 3,632,122 |
def print_person(first, last, middle=None):
"""Prints out person's names
This funciton prints out a person's name. It's not too useful
Args:
first (str): This person's first name
last (str): This person's last name
middle (str): Optional. This person's middle name
"""
middl... | 643ce351ec13a076c9fd36af39c97505084f1437 | 3,632,123 |
def get_governing_regions(strict=True):
"""! Creates a sorted list of governing regions which may simply be
federal states or intermediate regions which themselves are a real
subset of a federal state and to which a certain number of counties
is attributed.
Governing regions are generally denoted b... | c1d85343381f065d95862d6c4a71ea3ef2af80d0 | 3,632,124 |
def _chomp_element(base, index, value):
"""Implementation of perl = and chomp on an array element"""
if value is None:
value = ''
base[index] = value.rstrip("\n")
return len(value) - len(base[index]) | 66cfde7c8d8f2c92f0eebb23f717bf50b676ca31 | 3,632,125 |
def write_primitive(group, name, data, ds_kwargs):
"""Note: No dataset chunk options (like compression) for scalar"""
data_type = type(data)
# Write dataset
if data_type == np.ndarray:
ds = group.create_dataset(name, data=data, **ds_kwargs) # enable compression for nonscalar numpy array
el... | 531dd9190bb94b6bde3f70a80170bfbcd62c75c8 | 3,632,126 |
def measurecrime(gps, radius):
"""Measures crime around a given location"""
latitude, longitude = gps
minlat = latitude - radius
maxlat = latitude + radius
minlong = longitude - radius
maxlong = longitude + radius
baseurl = (DATABASE + WHERE + LAT + GT + str(minlat) + AND + LAT + LT +
... | 3a216b56744b32ec846a4edc590dd7ff72f4e69c | 3,632,127 |
def _weights(name, shape, mean=0.0, stddev=0.02):
""" Helper to create an initialized Variable
Args:
name: name of the variable
shape: list of ints
mean: mean of a Gaussian
stddev: standard deviation of a Gaussian
Returns:
A trainable variable
"""
var = tf.get_variable(
name, shape,
... | a9e378cebaec6aa45b52d393a73d032e742df594 | 3,632,128 |
def packed_function(function):
"""returns a function with a single input"""
# needed in python 3.x since lambda functions are not automatically unpacked
# as they were in python 2.7
if hasattr(function, '__code__'):
if function.__code__.co_argcount > 1:
return pack(function)
retu... | eb6996ed0215a2e4f33509665aed754731626316 | 3,632,129 |
from bs4 import BeautifulSoup
import re
async def read_ratings(session, archive_url, archive_timestamp, archive_content):
"""
Extract a movie rating from its imdb page
:raise: A ScrapeError if the rating could not be extracted
:return:
"""
try:
soup = BeautifulSoup(archive_content, 'ht... | 074203a533d6ef650f221ec825f16e85ed63d60d | 3,632,130 |
import time
def generate_nonce():
"""
Generates nonce for signature
Returns:
nonce (int) : timestamp epoch
"""
return int(time.time() + 100) | c439fc6598b4f5359d71bde8865afacb6162df19 | 3,632,131 |
def dense(x, inp_dim, out_dim, name = 'dense'):
"""
Used to create a dense layer.
:param x: input tensor to the dense layer
:param inp_dim: no. of input neurons
:param out_dim: no. of output neurons
:param name: name of the entire dense layer.i.e, variable scope name.
:return: tensor with sh... | dda9c6deb6cc2c270bfa3a53b7b771dbaa61c77e | 3,632,132 |
def read_observation_time_range(observation_id):
"""Get the time range of values for a observation.
Parameters
----------
observation_id: string
UUID of associated observation.
Returns
-------
dict
With `min_timestamp` and `max_timestamp` keys that are either
dt.dat... | c0f45341bf36c40e0cf97710cb593372b058219c | 3,632,133 |
import ray
def compute_mean_image(batches):
"""Computes the mean image given a list of batches of images.
Args:
batches (List[ObjectID]): A list of batches of images.
Returns:
ndarray: The mean image
"""
if len(batches) == 0:
raise Exception("No images were passed into `compute_mean_image`.")
... | c6d43fb36e207a890f83965a1491e30597c54b44 | 3,632,134 |
def get_sevt(r: Request, resp: Response):
"""
SEVT web server route for GET request.
:param r Request object, provides access to method, headers & cookies:
:param resp Response Object used for modification of status code:
:return returns the content of the internal resources response... | f27d3412526aaee37dd1d8350ee91b04fc7e1215 | 3,632,135 |
def mse(actual, predicted):
"""
https://ml-cheatsheet.readthedocs.io/en/latest/linear_regression.html#cost-function
MSE = the mean of (actual_outcome - predicted_outcome) squared
"""
return np.mean(np.power(actual - predicted, 2)) | cf514e2dbd126806f8921d479b9813cd1b3a08c5 | 3,632,136 |
import sys
def get_type_hints(fn):
"""Gets the type hint associated with an arbitrary object fn.
Always returns a valid IOTypeHints object, creating one if necessary.
"""
# pylint: disable=protected-access
if not hasattr(fn, '_type_hints'):
try:
fn._type_hints = IOTypeHints()
except (Attribut... | f654fe79d224b91916888ac942a74c5ab3bd0e69 | 3,632,137 |
import tempfile
import os
def notebook_to_md(notebook):
"""Convert a notebook to its Markdown representation, using Pandoc"""
tmp_file = tempfile.NamedTemporaryFile(delete=False)
tmp_file.write(ipynb_writes(notebook).encode('utf-8'))
tmp_file.close()
pandoc(u'--from ipynb --to markdown -s --atx-h... | 3c77654b509aa790726effd518d4a49df758c972 | 3,632,138 |
import os
def is_windows() -> bool: # pragma: no cover
"""
Returns True if the host operating system is Windows.
"""
return os.name == "nt" | 6205ceafa1b176a64a530f997d31d5b0d210201f | 3,632,139 |
def topsorted(outputs):
"""
Topological sort via non-recursive depth-first search
"""
assert isinstance(outputs, (list, tuple))
marks = {}
out = []
stack = [] # pylint: disable=W0621
# i: node
# jidx = number of children visited so far from that node
# marks: state of each node,... | e6d0204784f7b8169092a9fb6f56044f3be365be | 3,632,140 |
import pisa.utils.log as log
import sys
import pkg_resources
def open_resource(resource, mode='r'):
"""Find the resource file (see find_resource), open it, and return a file
handle.
Parameters
----------
resource : str
Resource path; can be path relative to CWD, path relative to
... | 37d2350996582a112c448d106a85a24bd27e5020 | 3,632,141 |
from scipy.spatial.distance import cdist
def merge_small_enclosed_subcavs(subcavs, minsize_subcavs = 50, min_contacts = 0.667, v = False):
"""
The watershed algorithm tends to overspan a bit, even when optimizing seeds.
This function aims at identifying small pockets (< minsize_subcavs)
that are heavily in contac... | 4f9b5e2cef4ffc7d64912bc31b18d3639ec62c26 | 3,632,142 |
import ast
def is_py3(file_path):
"""Check if code is Python3 compatible."""
# https://stackoverflow.com/a/40886697
code_data = open(file_path, "rb").read()
try:
ast.parse(code_data)
except SyntaxError:
return False
return True | 78a48bdcc682108ce4fbe6fffe4a235898beec1c | 3,632,143 |
import time
def getDate():
"""获得时间"""
return time.localtime() | 6f4f127b96ab6f754cc20e76219a54d039938320 | 3,632,144 |
import os
def modify_rsp(rsp_entries, other_rel_path, modify_after_num):
"""Create a modified rsp file for use in bisection.
Returns a new list from rsp.
For each file in rsp after the first modify_after_num files, prepend
other_rel_path.
"""
ret = []
for r in rsp_entries:
if is_path(r):
if m... | 473e785f110590e5b15f4359fcee168d3eb49e69 | 3,632,145 |
def wordEncrypt(word):
"""
Encrypt a word into list of keys using the cipher in file_cipher.
Definition
----------
def wordEncrypt(word):
Input
-----
word string
Output
------
list with numeric keys
Examples
... | 4b8abcd86bb77b3997fd856f0a47fd928e9e8c49 | 3,632,146 |
def is_special_identifier_char(c):
"""
Returns `True` iff character `c` should be escaped in an identifier
(i.e. it is a special character).
"""
return c in (
ESCAPEMENT_SYM, OLD_COMMENT_SYM, FILE_INCLUSION_SYM, UNIT_START_SYM,
UNIT_END_SYM, ALIAS_SYM, SLOT_SYM, INTENT_SYM,
C... | 762c5b2441753bb5f8f770092a56e48f5299d886 | 3,632,147 |
def delete_board(request):
"""
Removes the saved game board from user's profile.
User must be authenticated, i.e. must have the matching token.
Game board in the user's profile identified by game_id must exist.
user_id: unique user identifier (same as username).
token: authentication token that ... | 768968b7d3e3a220f1915d2286aaede7a29b3a2b | 3,632,148 |
import os
def showPlot(surface, save = True, folderName = '', fileName = '', file_format = 'PNG', showImage = True):
"""
Display the diagram and save it to the local.
Args:
surface: skia.Surface.
fileName: str-the name for the generated file: either the input filename or
... | 2478f329febd346c1e728b4564dc772cc1673372 | 3,632,149 |
def test_module(client: Client) -> str:
"""Tests API connectivity and authentication'
Returning 'ok' indicates that the integration works like it is supposed to.
Connection to the service is successful.
Raises exceptions if something goes wrong.
:type client: ``Client``
:param Client: RubrikPo... | 2f0662bacec47a30464ab36bbe162c69c32b129a | 3,632,150 |
import logging
def cnn_v0(state,
num_actions,
scope,
channels=32,
activation_fn=None,
is_training=True,
reuse=False,
use_timestep=True):
"""CNN architecture for discrete-output DQN.
Args:
state: 2-Tuple of image and timestep tensors... | e5769dc5bffdc1e0a6e3d415c83238e5682e4c9a | 3,632,151 |
def get_collections(expand=False, as_dataframe=False):
"""Get available collections.
Collections are folders on the local disk that contain downloaded or
created data along with associated metadata.
Args:
expand (bool, Optional, Default=False):
include collection details and format... | 45bce659dbd62a3f28d7d1d48f32e6503d11c3bd | 3,632,152 |
def jsonable_safe(obj):
"""Convert to JSON-able, if possible.
Based on fastapi.encoders.jsonable_encoder.
"""
try:
return jsonable_encoder(obj, exclude_none=True)
except:
return obj | 5c9a8e4e6ab11ddb0735a122eabe9c28649c7371 | 3,632,153 |
def classify_segment(data: list, no_of_outliers: int, acceptable_outlier_percent: float = .34) -> object:
"""
:param data: A list of Datapoints-current window
:param no_of_outliers: The number of datapoints in the current window assigned as outliers
:param acceptable_outlier_percent: The acceptable out... | 0ca846244ff8137e7dd145dd76c1cd35f276e641 | 3,632,154 |
def nearest_neighbor(v, candidates, k=1):
"""
Input:
- v, the vector you are going find the nearest neighbor for
- candidates: a set of vectors where we will find the neighbors
- k: top k nearest neighbors to find
Output:
- k_idx: the indices of the top k closest vectors in sorted fo... | 77cf4a84a3b6150e0e46d3a3c42f033600fad785 | 3,632,155 |
def reverse(x):
"""
:type x: int
:rtype: int
"""
new_str = str(x)
i = 1
rev_str = new_str[::-1]
if rev_str[-1] == "-":
rev_str = rev_str.strip("-")
i = -1
if (int(rev_str)>=2**31):
return 0
return (int(rev_str)) * i | 5775fe83f500ac844fa9fc94a4d71fc3bb6f165b | 3,632,156 |
def create_request(
service: str,
request: str,
settings: list = None,
ovrds: list = None,
append: dict = None,
**kwargs,
) -> blpapi.request.Request:
"""
Create request for query
Args:
service: service name
request: request name
setti... | 9a10ca81cb0ae773293a9ed3abeb1bd4914f3195 | 3,632,157 |
def delete_byID(iid):
""" Delete an item by ID
"""
global conn, curs
try:
sql = "DELETE FROM tbl_inc_exp WHERE id={}".format(iid)
curs.execute(sql)
conn.commit()
return True
except:
return False | 88174e4c216d4e6a716b38a2ab2651c53ba4565e | 3,632,158 |
import tempfile
import os
def _get_required_checks_and_statuses(pr, cfg):
"""return a list of required statuses and checks"""
ignored_statuses = cfg.get(
'bot', {}).get(
'automerge_options', {}).get(
'ignored_statuses', [])
required = ["linter"]
with tempfile.Tempo... | bbe9bbff4dab206eed7b7783f4583433163d2a10 | 3,632,159 |
def get_props(adapter=None,
device=None,
service=None,
characteristic=None,
descriptor=None):
"""
Get properties for the specified object
:param adapter: Adapter Address
:param device: Device Address
:param service: GATT Service UUID
:par... | 3dc1bd3cdab5520d7edc1770682da5ad6b95a643 | 3,632,160 |
def table_entry_pretty_print(entry, indent, line_wrap=-1):
###############################################################################
"""Create and return a pretty print string of the contents of <entry>"""
output = ""
outline = "<{}".format(entry.tag)
for name in entry.attrib:
outline += "... | 9ecf205fcdb9a3c2e3eaf97c8fe31dc97cb2d90e | 3,632,161 |
def part_1(input_data: list[int]) -> int:
"""Count the number of times a depth measurement increases from the previous measurement.
Args:
input_data (str): depths
Returns:
int: number of depth increases
"""
inc_count = 0
for i, depth in enumerate(input_data):
if i != 0 a... | 3ee506aca019f9393c93ced75e430d53b31a9fc2 | 3,632,162 |
from typing import Optional
def find_base_split_commit(split_dir, base_commit) -> Optional[str]:
""" Return the hash of the base commit in the specified
split repository derived from the specified monorepo base commit. """
mono_base_commit = git_output('rev-list', '--first-parent', '-n', '1', '--grep'... | 47c347f86936446c61cc368b646aa4bdedfedeed | 3,632,163 |
def evaluate(roughness, eta, wo, wi, dist):
# return brdf value (didn't multiply cos)
"""Evaluate BRDF and PDFs for Walter BxDF."""
# eta is assumed > 1, and it is the refractive index of the side of the
# surface facing away from the normal.
rGain = 1.0
boostReflect = 1.0
tAlbedo = np.arr... | cda0b86434456647e21dd3622cdf6331d267112d | 3,632,164 |
def round_floats(number):
"""A function which converts float values of comparison scores into floats
with no more than two decimal figures. No precision is lost this way - the
point is to convert numbers like 1.7499999999 into 1.75.
Arguments:
number (float): the value of a comparison score
... | a9603b6a4ee30385d320f73b3a769704008197f0 | 3,632,165 |
async def async_create_entities(hass, config):
"""Create the template binary sensors."""
sensors = []
for device, device_config in config[CONF_SENSORS].items():
value_template = device_config[CONF_VALUE_TEMPLATE]
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_t... | 2a978648f6db6aebf0c56eea92e5deb30cf9f05b | 3,632,166 |
import aiohttp
async def fetch_user(bearer: str) -> dict:
"""Fetch information about a user from their bearer token."""
headers = {"Authorization": f"Bearer {bearer}"}
async with aiohttp.ClientSession(headers=headers, raise_for_status=True) as sess:
resp = await sess.get(f"{API_BASE}/users/@me")
... | 8f5132f261f518bd3d9e05d7acfb5ed893f63a55 | 3,632,167 |
import os
def select_model(model_path):
""" select model """
model_str = os.path.basename(model_path)
model_str = model_str.split('.py')[0]
import_root = ".".join((model_path.split(os.path.sep))[:-1])
exec("from %s import %s as model" % (import_root, model_str))
model.EXP_NAME = model_str
... | e7c0dd35abeded088020876b7f14984c426ccfca | 3,632,168 |
def single_varint(data, index=0):
"""
The single_varint function processes a Varint and returns the
length of that Varint.
:param data: The data containing the Varint (maximum of 9
bytes in length as that is the maximum size of a Varint).
:param index: The current index within the data.
:ret... | 55b052300cc0cf5ac2fd8f7451ac121b408c1313 | 3,632,169 |
def dict_from_corpus(corpus):
"""
Scan corpus for all word ids that appear in it, then construct and return a mapping
which maps each `wordId -> str(wordId)`.
This function is used whenever *words* need to be displayed (as opposed to just
their ids) but no wordId->word mapping was provided. The res... | f9bbe1677ec1abc93c5f47095dc5f93e32278d42 | 3,632,170 |
import os
def read_fastspecfit(fastfitfile, fastphot=False, rows=None, columns=None):
"""Read the fitting results.
"""
if os.path.isfile(fastfitfile):
if fastphot:
ext = 'FASTPHOT'
else:
ext = 'FASTSPEC'
hdr = fitsio.read_header(fastfitfile, ex... | aa33ed33b41d91843653b27fe9197ce5a1fa7d60 | 3,632,171 |
def mat2dict(matobj):
"""
A recursive function that constructs nested dictionaries from matobjects
"""
dictionary = {}
for strg in matobj._fieldnames:
elem = matobj.__dict__[strg]
if isinstance(elem, scio.matlab.mio5_params.mat_struct):
dictionary[strg] = mat2dict(elem)
... | 948b1640d2fc67f712f81a5e6a2655fe58df3b66 | 3,632,172 |
import random
def build_stop_sign():
"""
This function creates a stop sign with GLabel
:return: object, sign
"""
random_x = random.randint(0, 640)
random_y = random.randint(30, 500)
sign = GLabel('Stop Clicking !!! ', x=random_x, y=random_y)
sign.color = 'firebrick'
sign.font = 'Ti... | bcfb44fbe7259ffa0a14b2511f99cf001a2f42c2 | 3,632,173 |
def name_atom(atom):
"""->symbol
Return the atom symbol for a depiction. Carbons atoms
in general are not returned"""
symbol = "%s"%(atom.symbol,)
weight = atom.weight
charge = atom.charge
hcount = atom.hcount
explicit_hcount = atom.explicit_hcount
out_symbol = symbol
# pyrole ... | 5b6661046720f10ca2f28196f2c76a4732dc9d96 | 3,632,174 |
import os
import tempfile
import getpass
def preview_convert(file_in, command, size, gm_or_im):
"""
preview generation
file_in - fullname image file
dir_temp - fullname temporary directory
command - additional command for imagemagick or space
--
return: fullname preview file and size
"... | e4240be329c964ef7ce434880e16b310cd6df39d | 3,632,175 |
import math
def rot3D(x, r):
"""perform 3D rotation
Args:
x (np.array): input data
r (float): rotation angle
Returns:
np.array: data after rotation
"""
Rx = np.array([[1, 0, 0], [0, math.cos(r[0]), -math.sin(r[0])], [0, math.sin(r[0]), math.cos(r[0])]])
Ry = np.array([[... | df37aa011e3291a87309ceb72d11f8a531475a5e | 3,632,176 |
def perform_move(move: Move, attacking_creature: BattleCreature, defending_creature: BattleCreature, static_game_data: StaticGameData):
"""
Performs the move by the attacking creature on the defending_creature.
This can change both the attacking creature, the defending creature and
cause me... | b0198f364b08c7eeaf0cc7b83bdf5f867d1c15e8 | 3,632,177 |
def _shake_shake_layer(x,
output_filters,
num_blocks,
stride,
is_training):
"""Builds many sub layers into one full layer."""
for block_num in range(num_blocks):
curr_stride = stride if (block_num == 0) else 1
x =... | 246ddba479735b94d2c94ba02bdb5c571a68bbc2 | 3,632,178 |
from typing import Optional
def filter_nan_values(data: DataFrame, used_cols: Optional[list[str]] = None):
"""
Filter NaNs in columns that are used for futher calculations
:param data: Dataframe with full dataset
:type data: DataFrame
:param used_cols: Columns to check, None checks al... | 95296587ff765c48c5e3f3f9db911a9971f50984 | 3,632,179 |
def dropout(inputs,
is_training,
scope,
keep_prob=0.5,
noise_shape=None):
""" Dropout layer.
Args:
inputs: tensor
is_training: boolean tf.Variable
scope: string
keep_prob: float in [0,fv_noise]
noise_shape: list of ints
Returns:... | 738553ae4e958e34a3daea680bd5736f288609d2 | 3,632,180 |
def test_trained_model(test_data,
clf_name,
model_dir_path = '',
iteration_number = 0,
is_abnormal = False,
threshold_value = 0):
"""
Test any model.
:param test_data:
:param clf_name:
... | 7e1692e17590c1c8d3718073793e52ad5f07f055 | 3,632,181 |
import glob
def tumor_list(version):
"""
version: cross validation version and train or val
"""
path_list = []
for i in version:
paths = sorted(glob.glob(f'./data/tumor_-150_150/{i}/label_*/*.npy'))
path_list.extend(paths)
return path_list | da390686072613177a4f3f5b483d980640090d1c | 3,632,182 |
def roles_allowed(roles):
"""Takes a list of roles allowed to access decorated endpoint.
Aborts with 403 status if user with unauthorized role tries to access
this endpoint.
:param list roles: List of roles that should have access to the endpoint.
"""
def roles_allowed_decorator(fn):
@... | 8d039b09529f65b2d1123c8dffd634d2d6873404 | 3,632,183 |
from typing import List
from typing import Optional
def get_offsets(
text: str,
tokens: List[str],
start: Optional[int] = 0) -> List[int]:
"""Calculate char offsets of each tokens.
Args:
text (str): The string before tokenized.
tokens (List[str]): The list of the strin... | 08a300d7bbc078b40c44fdb75baeafff50c6907b | 3,632,184 |
def get_content_ref_if_exists_and_not_remote(check):
"""
Given an OVAL check element, examine the ``xccdf_ns:check-content-ref``
If it exists and it isn't remote, pass it as the return value.
Otherwise, return None.
..see-also:: is_content_href_remote
"""
checkcontentref = check.find("./{%... | 5232813333fff299e4afd8dadc1e6e700441f5b0 | 3,632,185 |
def sat_pass(sats, t_arr, index_epoch, location=None):
"""Find when a satellite passes above the horizon at a gps location.
Calculate the :samp:`Altitude` & :samp:`Azimuth` of a
:class:`~skyfield.sgp4lib.EarthSatellite` object from
:func:`~embers.sat_utils.sat_ephemeris.load_tle` at
every instant o... | 5f68fa486533dec605fe084f8848b836177920d2 | 3,632,186 |
def get_logit_model(x_train: pd.DataFrame, y_train: pd.Series) -> LogisticRegression:
"""
Train and return a logistic regression model
"""
lr = LogisticRegression(penalty='l2',
solver='lbfgs',
fit_intercept=False,
interc... | c267769bdab34bc6fb272fc2376e56c0c28f2964 | 3,632,187 |
from typing import Dict
from typing import Any
from typing import Tuple
def makearglists(args: Dict[str, Any]) -> Tuple[str, str]:
"""
Returns the python code for argument declaration and argument passing to
the function that does the work
Parameters
----------
args: dict
Arg info for... | 4cbcb1f3fbff72f12249bc7c952120e84bbda644 | 3,632,188 |
def task1():
"""Task1 function of API3
Returns:
[str]: [Return string]
"""
logger.info("In API3 task1 function")
return "task1 success!" | 2d506d97ed116704f85cb335b5e324c974b28087 | 3,632,189 |
def _METIS_PartGraphKway(nvtxs, ncon, xadj, adjncy, vwgt, vsize,
adjwgt, nparts, tpwgts, ubvec, options, objval, part):
"""
Called by `part_graph`
"""
return _METIS_PartGraphKway.call(
nvtxs, ncon, xadj, adjncy, vwgt, vsize, adjwgt, nparts, tpwgts, ubvec,
options... | 35965ed224058372e0831a10040065fde7c1b558 | 3,632,190 |
def parse_ocr_result(ocr_result, drms):
"""
Parses and extract data from the OCR document result string by
using a DRM (Document Regexp Model) that matches this OCR string.
Args:
ocr_result (str): OCR result string;
drms (dict): list of all DRMs dicts found in the DRM directory folder.
... | 7016654ba83d49ca81c0628db4a265398eb98a2a | 3,632,191 |
def payment_insert(conn, payment_info):
"""
Inserts a row in 'payment' table with the values passed in 'payment_info'
Parameters:
conn: Connection object
payment_info: a tuple of values to insert
"""
try:
sql = " INSERT into payment(payment_id, user_id, payment_method, paymen... | ad763dae5d8f313f34ebea7909097d558abc0565 | 3,632,192 |
def plot_pareto_frontier(
frontier: ParetoFrontierResults,
CI_level: float = DEFAULT_CI_LEVEL,
show_parameterization_on_hover: bool = True,
) -> AxPlotConfig:
"""Plot a Pareto frontier from a ParetoFrontierResults object.
Args:
frontier (ParetoFrontierResults): The results of the Pareto fro... | e36389fc64801af71302f70ebc74600b34e9a7d1 | 3,632,193 |
def filenames(
directory, file_stem, file_ext=DEFAULT_FILE_EXT, stamp_regex=DEFAULT_STAMP_REGEX
):
"""Generate all filenames with matching stem
Parameters
----------
directory : pathlib.Path
Path to directory holding file
file_stem : str
File stem, filename without timestamp and... | 81f27c939ae2934d4e58079fcc3ac53c2b2228a1 | 3,632,194 |
from typing import Optional
def add_vqsr_eval_jobs(
b: hb.Batch,
dataproc_cluster: dataproc.DataprocCluster,
combined_mt_path: str,
rf_annotations_ht_path: str,
info_split_ht_path: str,
final_gathered_vcf_path: str,
rf_result_ht_path: Optional[str],
fam_stats_ht_path: Optional[str],
... | 16baacc4bdb0fa5aab5c0413dcc4734ea79f6238 | 3,632,195 |
import os
def is_readable(path):
"""
This function checks to see if a file or a directory can be read.
This is tested by performing an operation that requires read access
on the file or the directory.
"""
if os.path.isdir(path):
try:
os.listdir(path)
except (OSError... | d3f8c65afe1d07d2b8cf1c9240c67c4638136710 | 3,632,196 |
def interpolate(r, g, b):
""" Interpolate missing values in the bayer pattern
by using bilinear interpolation
Args:
red, green, blue color channels as numpy array (H,W)
Returns:
Interpolated image as numpy array (H,W,3)
"""
#
# You code here
#
'''
rb各四分之一
... | cab347871f4b0ebc71f82cb6776976f9e0756aee | 3,632,197 |
def heatmap(pois, sample_size=-1, kwd=None, tiles='OpenStreetMap', width='100%', height='100%', radius=10):
"""Generates a heatmap of the input POIs.
Args:
pois (GeoDataFrame): A POIs GeoDataFrame.
sample_size (int): Sample size (default: -1; show all).
kwd (string): A keyword to filter... | f099aeb54a0b3bc300a8c335c9663da63e6b53b7 | 3,632,198 |
from typing import Tuple
def _color_int_to_rgb(integer: int) -> Tuple[int, int, int]:
"""Convert an 24 bit integer into a RGB color tuple with the value range (0-255).
Parameters
----------
integer : int
The value that should be converted
Returns
-------
Tuple[int, int, int]:
... | df3eb5ad92d9383b0e6fe5c1603e0caec0df5c45 | 3,632,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.