content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Union
from typing import List
def has_transparency(colour: Union[ColorType, List[ColorType]]):
"""
Returns True if the colour is not fully opaque.
Where a list of colours is passed, returns True if any
colour is not fully opaque.
"""
def has_alpha(col):
return rgb(c... | d2c127703db1a8e0c2bf1c09177e326d075e02c5 | 3,603,400 |
import os
def download_file(save_dir, filename, url, md5=None):
"""
Download the file from the url to specified directory.
Check md5 value when the file is exists, if the md5 value is the same as the existed file, just use
the older file, if not, will download the file from the url.
Args:
... | df0b0a1580ddd3e5b6027e3aed6bb65ff6afeac7 | 3,603,401 |
from typing import List
def input_grid(grid: List[str] = None) -> List[str]:
"""
Inputting grid and splitting it to list of strings
:param grid: (optional) predefined grid
:return: grid
"""
if grid is None:
print("Please enter grid as strings, divided by commas")
in_grid = inpu... | 5b7ae98fbf81e3fafd487562198dbd704167e31d | 3,603,402 |
from unittest.mock import Mock
def setup_save_failure(set_many):
"""
Set up tests for when there's a save error in the underlying KeyValueStore
"""
field_data = MagicMock(spec=FieldData)
field_data.get = lambda block, name, default=None: 99 # pylint: disable=C0322
field_data.set_many = set_m... | a4b81b55ee8ef42e13ded2ddfe5270114e1ff860 | 3,603,403 |
def savedata_tomat(
fname,
params,
vmin,
vmax,
nvox,
write=True,
data=None,
num_markers=20,
tcoord=True,
tcoord_scale=True,
addCOM=None,
):
"""Save pickled data to a mat file.
From a save_data structure saved to a *.pickle file, save a matfile
with useful var... | b3ca6599f34d13d0604b11be437f5cd403e33c68 | 3,603,404 |
def users_update(user_id):
"""Handle form submission for updating an existing user"""
user = User.query.get_or_404(user_id)
user.first_name = request.form['first_name']
user.last_name = request.form['last_name']
user.image_url = request.form['image_url']
db.session.add(user)
db.session.com... | 53afa93ce7a5fc1916c25656b647a6971e8af45a | 3,603,405 |
def clean_and_merge_zomato(zomato_file_path, country_codes_file_path):
"""
Loads, cleans, processes, and wrangles zomato.csv and Country-Code.xlsx
Arguments:
zomato_file_path - (str) the file path for the zomato.csv
country_codes_file_path - (str) the file path for the Country-Code.xlsx
... | 0d6aad19e56b3ea5454984438aaeeda30c2d7e02 | 3,603,406 |
def _user_get_direct_regions(user, org):
"""Return org regions user has direct permission for."""
def calculate():
# org admins have implicit access to all regions
if user.is_admin_for(org):
return Region.get_all(org)
else:
return user.regions.filter(is_active=Tru... | 261383c6ee9ab0dc3cdee1c859e94dd1385b46df | 3,603,407 |
def interaction(adj_matrix, users_as_nodes=True):
"""Creates interaction matrix.
Args:
adj_matrix: Numpy array representing the adjacency matrix of the
user-item bipartite graph.
users_as_nodes: Bool indicating which interaction matrix to generate. If
True (False), generates a user-user (item-i... | 3d31fc1a2cc87265c853799ec33ceaa156427cde | 3,603,408 |
from pathlib import Path
def full_processing(song_file, sheet, sa, df_liking, df_striking, only_song_results=False):
"""
"""
song_file = Path(song_file)
if song_file.is_file():
# Step 1
tokens_raw, tokens = tokenize_song(song_file, sheet)
# Step 2
... | 985b6d89b44bb0aedeb08655ce18d2f29f2d0226 | 3,603,409 |
def Main(operation, args):
"""
:param operation:
:param args:
:return:
"""
if operation == 'name':
return Name()
if operation == 'totalSupply':
return TotalSupply()
if operation == 'init':
return Init()
if operation == 'symbol':
return Symbol()
if... | be21feac86fcfc8dc91d0dcd8b936ffbb3f5590f | 3,603,410 |
def tukey53H(x):
"""Spike test Tukey 53H from Goring & Nikora 2002
"""
N = len(x)
u1 = ma.masked_all(N)
for n in range(N - 4):
if x[n : n + 5].any():
u1[n + 2] = ma.median(x[n : n + 5])
u2 = ma.masked_all(N)
for n in range(N - 2):
if u1[n : n + 3].any():
... | f26f2ddeb15249984f2828022b83d5b98e72c37f | 3,603,411 |
def gwgrad_partial(C1, C2, T):
"""Compute the GW gradient. Note: we can not use the trick in :ref:`[12] <references-gwgrad-partial>`
as the marginals may not sum to 1.
Parameters
----------
C1: array of shape (n_p,n_p)
intra-source (P) cost matrix
C2: array of shape (n_u,n_u)
i... | d45b99531f0b052a7b0f6b041e948b6e8ee7f0d8 | 3,603,412 |
def filter_to_be_staged(position):
"""Position filter for Experiment.filter() to include only worms that still need to be
stage-annotated fully."""
stages = [timepoint.annotations.get('stage') for timepoint in position]
# NB: all(stages) below is True iff there is a non-None, non-empty-string
# anno... | df771b0856c91c8663ad06cacf86bf3389df04c5 | 3,603,413 |
import os
def gen_thumb(video_path, thumb_path):
"""
Generate thumb image for the given video, and grabs duration from output
:return: (success, duration)
"""
if os.path.isfile(thumb_path):
os.remove(thumb_path)
global THUMB_SIZE
cmd = ['ffmpeg', '-itsoffset', '-5', '-i', video_pa... | e9a3728e92487eb3a6962210855a31d0cf603f47 | 3,603,414 |
import json
import requests
def udf_inventory_transformer(uckey, days):
# udf for traffic in gucdocs.
"""
request body sample:
{
"targetingChannel": {
"a": [1],
"g": ["g_m"]
},
"days": [
{
"ed": "2020-07-10",
"... | 7bc2a60314c53fd32953debb4e3b1a7575e60846 | 3,603,415 |
import types
import copy
from typing import Any
def _ParseExample(extracts: types.Extracts, eval_config: config.EvalConfig):
"""Parses serialized tf.train.Example to create additional extracts.
Args:
extracts: PCollection containing serialized examples under tfma.INPUT_KEY.
eval_config: Eval config.
R... | 03bb4011b1f75c9a8608cfa9723e5af69d891ddd | 3,603,416 |
def classify(text, verbose=True):
"""Classify the input text into categories. """
language_client = language_v1.LanguageServiceClient()
document = language_v1.Document(
content=text, type_=language_v1.Document.Type.PLAIN_TEXT
)
response = language_client.classify_text(request={"document": ... | f8a6742966f3aa2b7f44fa001553bccbaa93cb93 | 3,603,417 |
def get_raster_pixels(raster_path):
"""Takes string path to raster (produced by create_annual_raster; pixel value is either 1 or NoData) and calculates total pixels of value == 1
"""
raster_pixels = arcpy.SearchCursor(raster_path).next().count
return raster_pixels | 7d83d7f7704374740f80179a0bbbf955f5744132 | 3,603,418 |
import math
def gpt_gelu(x):
"""
Args:
x (np.ndarray): input tensor.
Returns:
(np.ndarray): output tensor and have same shape with x.
"""
return 0.5 * x * (1 + np.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * np.pow(x, 3)))) | 17734efcf2216111a26366cf66642753233eaee7 | 3,603,419 |
def separate_businesses(all_biz: pd.DataFrame, city_zips, county_zips, county_names):
"""
Returns a dataframe of registered active businesses in LA City
Returns a dataframe of registered active businesses in LA County (excluding LA City)
Returns a dataframe of registered active businesses outside LA Cou... | c4acbe57f3f927967c116ba326fa68ccef6646b6 | 3,603,420 |
import sys
def import_module(module_name):
"""
Improt module and return it.
"""
__import__(module_name)
module = sys.modules[module_name]
return module | 5b74e1c4f0442b8bf37a3e4145d212698fd49c60 | 3,603,421 |
def leja_growth_rule(level):
"""
The number of samples in the 1D Leja quadrature rule of a given
level. Most leja rules produce two point quadrature rules which
have zero weight assigned to one point. Avoid this by skipping from
one point rule to 3 point rule and then increment by 1.
Parameters... | b93fe05a3bf9b8c016b92a00078dce8ef156a8c4 | 3,603,422 |
import six
from io import StringIO
def ObjStrImpl(obj, include_methods=False):
"""\
def __str__(self):
return CommonEnvironment.ObjStrImpl(self)
"""
d = ObjectToDict(obj)
if not include_methods:
for k in list(six.iterkeys(d)):
if callable(d[k]):
del d[k... | 3703f37ca2909639cad49fefb4bb2d466d9dd8ce | 3,603,423 |
def load_config(settings, user_settings=None, src_files=None):
"""
Negotiate a group of settings from the global defaults, the user-provided
values and config files. The keys in the `settings` argument are the only
settings that are considered valid.
The priority of the values is:
user_set... | 4a3cec584e984e65dbddbcc24c71e3475eba4eb0 | 3,603,424 |
def global_pf_input(temperatures=(),
temp_step=100, ntemps=30,
rel_temp_inc=0.001, atom_dist_min=1.13384):
""" Writes the global keywords section of the MESS input file by
formatting input information into strings a filling Mako template.
:param temperatures:... | bfb05443aeb3af3d237dbdfae86de0b190affcd3 | 3,603,425 |
def generate_core_dynamic_client(*args, **kwargs) -> CoreDynamicClient:
"""生成测试用的 DynamicClient"""
config = FakeKubeConfigurationService().make_configuration()
discoverer_cache = DiscovererCache(cache_key=f"osrcp-cluster_id.json")
return CoreDynamicClient(client.ApiClient(config), cache_file=discoverer_... | c310f9adc1b5332449e3841c5dc9ee9f8e91bec5 | 3,603,426 |
import os
import time
import pickle
import shutil
def prepare_job_submission(command_args, num_created_jobs, shared_job_array):
"""Handle preparation for job submission. Set flag for parent process
to check and submit the job.
:param command_args: list, arguments from the command line.
:param num_cre... | a0ef9fe48f9a75ba1bbd13941acbc8ff664d3774 | 3,603,427 |
import lirc
def setup(hass, config):
"""Set up the LIRC capability."""
# blocking=True gives unexpected behavior (multiple responses for 1 press)
# also by not blocking, we allow hass to shut down the thread gracefully
# on exit.
lirc.init('home-assistant', blocking=False)
lirc_interface = Li... | aa0c93d39b17247e9d55b53f281269999b143583 | 3,603,428 |
def pew_read_tioband(fil, ifnofilout='empty', nrow=1):
"""
obj.TiO.band.dat: time series of TiO indices
Description of file: obj.TiO.band.dat
-------------------------------------------------------------------------
Col Format Units Label Explanations
-------------------------------... | 6035a6f6bfa357b54c7ee44a0ec8a28f55f2914f | 3,603,429 |
def _calc_cr(rjp, rj, rjm, vel):
"""
Calculates cr value used in superbee advection scheme
"""
eps = 1e-20 # prevent division by 0
return npx.where(vel > 0.0, rjm, rjp) / npx.where(npx.abs(rj) < eps, eps, rj) | b5c268ba9964a1ac82654b2cadc6c2bf66340505 | 3,603,430 |
from typing import Optional
def get_emnist_datasets(client_batch_size: int,
client_epochs_per_round: int,
max_batches_per_client: Optional[int] = -1,
only_digits: Optional[bool] = False):
"""Loads and preprocesses EMNIST training and testing se... | 292985eb82a89d87c7ab037e11d22b9522c06997 | 3,603,431 |
def pentagon(linelist, numsrch, maxlin):
"""
see trigon and tetragon for an example docstring
"""
nptn = 5 # Number of lines used to create a pattern
sz_l = linelist.shape[0]
# Count the number of patterns that will be created
cnt = 0
for l in range(0, sz_l - nptn + 1):
nup = ... | 0a9e59f2e17d12194613124284233a1999f68a22 | 3,603,432 |
def simhash(line, restrictiveness, ngram=0):
"""Realiza simhash
:param line: texto
:param restrictiveness
:param ngram: numero de ngramas
:return:
"""
if(ngram < 0):
bag = BagOfWords(text=line)
if len(bag) == 0:
return None
hashes = calculate_hashes(bag.v... | e501c4e77540943c161f13740072ae900e8dc38a | 3,603,433 |
import math
def MakeIntegralBands(dR):
"""
Divide a range into integral bands
:param: dR - [min, max] the range that is to be covered by the bands.
:return: A List consisting of [min, midpoint, max] for each band.
"""
bands = list()
if dR[1] < dR[0]:
return bands
x = list(dR)
... | e520e97cd45b584e90c91fce945aad57556b3b0e | 3,603,434 |
from weaver.processes.wps_package import check_package_instance_compatible, get_process_definition
def _validate_deploy_process_info(process_info, reference, package, settings, headers):
# type: (JSON, Optional[str], Optional[CWL], SettingsType, Optional[AnyHeadersContainer]) -> JSON
"""
Obtain the proces... | 2d9369670895871092101e43244d2be7ef1f9e2d | 3,603,435 |
import os
def __get_mime_types(path, extension, mimetype, method, ignore_empty,
maximum):
"""
Recursively get the MIME type of all files from a directory and its
sub-directories.
"""
files_checked = []
files_mismatch = []
is_maximum = False
if not extensio... | e2fe3331f3f5e4bb2921ec9b59a12de1937da08b | 3,603,436 |
def log_prob_from_logits(x):
""" numerically stable log_softmax implementation that prevents overflow """
axis = len(x.get_shape())-1
m = tf.reduce_max(x, axis, keep_dims=True)
return x - m - tf.log(tf.reduce_sum(tf.exp(x-m), axis, keep_dims=True)) | 6dc92f97ad757b1a35c47d3e10eaf34e90e18914 | 3,603,437 |
def combination4(question):
"""
Combining default processing
"""
question = default_processing(question)
return question | bd0a455e10e7badb361af1bfa02c20f126eb01a2 | 3,603,438 |
import tqdm
def main():
"""
Main method for the script.
"""
def mean_absolute_percentage_error(gt_y, pred_y):
return 100*np.mean(np.abs(np.divide(np.array(gt_y)-np.array(pred_y), np.array(gt_y))))
def run_on_b_data():
all_mapes = []
num_folds = online_b_data.get_specific_w... | a4aefee92d0fb6d05da52c9bc995a5602dae0ce9 | 3,603,439 |
def dissect(s, graph):
"""
Decodes a path through a cyclic directed graph as described by the hash string s.
:param s: The input string.
:param graph: A set of vertex pairs which make up the graph.
:return: A set of vertex pairs which make up the graph.
"""
return _dissect(s, track=[], sta... | 1540a5e022cd469a72243cbd350a89d100025418 | 3,603,440 |
import array
def mreplace(s, chararray, newchararray):
""" Replace occurences of chars in
chararray in string 's' with elements in
newchararray """
slist=list(s)
dlist=list(chararray)
rlist=list(newchararray)
for x in range(0, len(slist)):
charitem=slist[x]
if charitem in... | 0c2fe8229c27c237e3283343d4477a1f71b46fc1 | 3,603,441 |
def delete(resource_kind, namespace, name, mod_revision=None):
"""Delete a Calico v3 resource from etcdv3.
- resource_kind (string): E.g. WorkloadEndpoint, Profile, etc.
- namespace (string): The namespace to delete the resource in.
- name (string): The resource's name, which is used to form its etcd... | c25ed2b79e0e6ec64696dacfeb96ae2ea739e89e | 3,603,442 |
from typing import List
from typing import Tuple
def list_all_datasets() -> List[Tuple[str, str]]:
"""Calculate all existing cached analyses
Returns:
List[Tuple[str,str]]: List of all (model, dataset) caches available to serve to the frontend
"""
return [p.stem.split(pf.ANALYSIS_DELIM) for p ... | 49e1826f6a1a1fd1ac9368296def60358f13ff6a | 3,603,443 |
def nastran_replace_inline(big_string, old_string, new_string):
"""Find a string and replace it with another in one big string.
In ``big_string`` (probably a line), find ``old_string`` and replace
it with ``new_string``. Because a lot of Nastran
is based on 8-character blocks, this will find the 8-char... | f9955d40a74fc57674e79dd6aeea3872ffc2c87d | 3,603,444 |
def _p9_to_svg(plotnine_plot):
"""Convert a plotnine plot to an svg string (for inclusion in html output)."""
matplotlib_plot = plotnine_plot.draw()
buffer = BytesIO()
matplotlib_plot.savefig(buffer, format='svg', bbox_inches='tight')
plt.close(matplotlib_plot)
return buffer.getvalue().decode() | 6026399370f4f235680c129c444f389971268f25 | 3,603,445 |
def condition(etag_func=None, last_modified_func=None):
"""
Decorator to support conditional retrieval (or change) for a view
function.
The parameters are callables to compute the ETag and last modified time for
the requested resource, respectively. The callables are passed the same
parameters ... | cc3e71f2b66ac79ece315c96380c38109fbd16fc | 3,603,446 |
import io
def reindent_code(codestr):
"""
Given code string, reindent it in the same way that the
Github dataset was indented
"""
codestr = io.StringIO(codestr)
ret = io.StringIO()
run_reindent(
codestr,
ret,
config = {
"dry-run": False,
"... | e50a8dcce45e7ce53bc3e0a22f9ee70a7336456f | 3,603,447 |
def get_packet(packet_str):
"""
Converting packet string to numeric object
- time_str: Packet string in iperf format (1M, 1m, 2K, 5T, 1000b, 12B, etc)
- return: Packet object
"""
return DataPacket(packet_str) | b8c9ccb9def00337bdcbccd1a9d93614e8aac201 | 3,603,448 |
async def query_data_agreement_instances(request: web.BaseRequest):
"""
Request handler for querying data agreement instances.
"""
# Context
context = request.app["request_context"]
# Get query string parameters
tag_filter = {}
# Thread ID
if "data_agreement_id" in request.query a... | e104d56559dac50a91f08f761cc9bbaffdf8d213 | 3,603,449 |
def get_2d_visualization_plugins():
""" A list of all 2D visualization plugins """
return get_plugins_of_type(VisualizationPlugin2D) | 896e45ebb4fd822de857c8a6aa017cdea2d70cd2 | 3,603,450 |
import requests
def delete_request_assert(base, endpoint, validation_file, endpoint_params={}):
"""
Send a DELETE request and assert response meets expectations.
"""
r = requests.delete(full_request_url(base, endpoint, endpoint_params))
assertions(r, endpoint, validation_file)
return r | d44bb7cf800c39d54f8a6c77949b28d262e3ace6 | 3,603,451 |
def post(id):
"""New post function"""
title = "New post"
post_form = PostForm()
if post_form.validate_on_submit():
title = post_form.title.data
category = post_form.category.data
post = post_form.post.data
new_post = Post(title=title, category=category, post=post, user=c... | 3f9d71200d04b86b699684fbbae6d23ef49b9304 | 3,603,452 |
def get_hspec(sim, snap, snr=0., box = 25):
"""Get a spectra object, possibly from the cache"""
halo = myname.get_name(sim, True, box=box)
#Load from a save file only
try:
hspec = hspec_cache[(halo, snap)]
except KeyError:
hspec = ps.VWPlotSpectra(snap, halo, label=labels[sim], snr=s... | a57e63db49cb08c322f6a75c9a43d3b8c56eb483 | 3,603,453 |
import re
def does_support_ssl(ip):
"""Check if IP supports SSL.
Has aba sequence outside of the bracketed sections and corresponding
bab sequence inside bracketed section.
Examples:
- aba[bab]xyz supports SSL (aba outside square brackets with
corresponding bab within square brackets).
... | f46dda13d53717352fe27446d9fa3d0292d75c26 | 3,603,454 |
def place_t_as_idaplace_t(*args):
"""
place_t_as_idaplace_t(p) -> idaplace_t
"""
return _ida_kernwin.place_t_as_idaplace_t(*args) | 517cda999d79637ad3c9c1587f9ff947104eb2c4 | 3,603,455 |
def _proxLowRank(X, mu):
"""Summary
Args:
X (TYPE): Description
mu (TYPE): Description
Returns:
TYPE: Description
"""
U, w, V = np.linalg.svd(X, full_matrices=True)
ind = np.where(np.abs(w) < mu)[0]
w[ind] = 0.0
ind = np.where(np.abs(w) > mu)[0]
w[i... | d2f0d1aaec331b99767179afcc3c245f0e36202d | 3,603,456 |
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import calendar
import os
import requests
def RetrieveData_monthly(Date, args):
"""
This function retrieves GLDAS monthly data for a given date.
Keyword arguments:
Date -- 'yyyy-mm-dd'
args -- A list of parameters defined in ... | ae82b5f88331accde9294422c927a69ad9ea54d5 | 3,603,457 |
import sys
def purge_mq_queue(mq_queue_name):
""" function purges
:param mq_queue_name: <string> name of the message queue
:return: number of purged messages
"""
conn = None
chan = None
try:
conn = Connection()
chan = conn.connection.channel()
n = chan.queue_purge(m... | 54f8553dfddb3e5b2b148263ce77a0de6a8d247d | 3,603,458 |
def search():
"""Render search page."""
if not (current_user.is_admin or current_user.is_bartender):
flash("You don't have the rights to access this page.", 'danger')
return redirect(url_for('main.dashboard'))
if not g.search_form.validate():
return redirect(url_for('main.dashboard')... | ea7a999b1fb8dc14c89ef6a3a20c8691b1a7582a | 3,603,459 |
import six
import json
def meta_serialize(metadata):
"""
Serialize non-string metadata values before sending them to
Nova.
"""
return dict((key, (value if isinstance(value,
six.string_types)
else json.dumps(value))
... | a2ef8762c9d1b3d78dc401996392df0985c1c226 | 3,603,460 |
def milestone_add_typed(request, project_id=None, response_format='html'):
"""Milestone add to preselected project"""
project = None
if project_id:
project = get_object_or_404(Project, pk=project_id)
if not request.user.profile.has_permission(project, mode='x'):
project = None
... | bf1a1d6aabf2051b8b88ab808c210b919ef3d43b | 3,603,461 |
def xml_to_dict(root):
"""
Converts an XML file or ElementTree Element to a dictionary
"""
if not isinstance(root, Document):
raise TypeError, 'Expected ElementTree.Element or file path string'
return _xml_to_dict_helper(root) | 2a5fae1c9eec475e4c398bba58534a2c29c14be1 | 3,603,462 |
import json
def module_list(request, pk):
"""
模块列表
:param request:
:param pk: str or int:当前页
:return:
"""
account = request.session["now_account"]
if request.is_ajax():
module_info = json.loads(request.body.decode('utf-8'))
if 'mode' in module_info.keys(): # del module... | 484fe367159e41d742fee89e566a620a78201235 | 3,603,463 |
def copy_all_logs(stringified_parameters, slaves):
"""
Assembles all of the logs from running an experiment into a single directory, and returns the path
to that directory.
Args:
stringified_parameters: A list of strings that were parameters to the experiment. Used
in naming the resulting directory.
... | d862e451ac22ede62687e251f112cba2ab96f3f7 | 3,603,464 |
def is_punctuation(ref_word):
"""
:param ref_word:
:return: 0 if not a punctuation
1 if brackets, 2 if colon, 3 if comma, 4 if dot, 5 if parenthesis,
6 if quotes (both single and double), 7 if num sign, 8 if hypen, 9 if forward slash,
10 if semicolon
"""
found... | a735f0bbd702005a8abe39e8bea829fdeec80d13 | 3,603,465 |
import os
def _get_full_path(*rel_path):
"""Make absolute path to a file or directory in the project folder ml_subtitle_align.
Arguments:
*rel_path: List of path elements.
Returns:
`str`: Absolute path to requested file or directory.
"""
path = os.path.abspath(__file__) # `.../ml_subtitle_al... | dd17f6b8353cabda3eccd0498b4b29a06998a9d0 | 3,603,466 |
def enum_assemble(node, neighbors, prev_nodes=None, prev_amap=None):
"""Enum assemble."""
if not prev_nodes:
prev_nodes = []
if not prev_amap:
prev_amap = []
all_attach_confs = []
singletons = [nei_node.get_node_id()
for nei_node in neighbors + prev_nodes
... | b82d4a76c80ffdbeb8de97298d845f1658a17122 | 3,603,467 |
def keep_merge(walkers, keep_idx):
"""Merge a set of walkers using the state of one of them.
Parameters
----------
walkers : list of objects implementing the Walker interface
The walkers that will be merged together
keep_idx : int
The index of the walker in the walkers list that wil... | b029bd14cab4aec2cdf8edf27a9d63c2ffbbe61e | 3,603,468 |
def is_point_behind_plane(point, plane, tol=1e-6):
"""Determine if a point lies behind a plane.
Parameters
----------
point : [float, float, float] | :class:`compas.geometry.Point`
A point.
plane : [point, normal] | :class:`compas.geometry.Plane`
A plane.
tol : float, optional
... | 37c83cfc320efe110f68937c1ac2d3e60b6dbd72 | 3,603,469 |
def var_annotations_filter(node: nc.NodeNG) -> nc.NodeNG:
"""Filter annotated function variable assigns.
This accounts for deferred evaluation.
"""
# pylint: disable=too-many-branches
# pylint: disable=too-many-nested-blocks
if using_future_annotations(node):
# Future behavior:
... | 41f6e5ead64f1ae70866d1fdedc1d5726f313acd | 3,603,470 |
def draw_kamada_kawai(G, **kwargs):
"""Draw networkx graph with circular layout.
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See hvplot.networkx.draw() for a description of optional
keywords, with the exception of the pos parameter which is not
... | 7795c69c8ab75cbe21a775538b8d00f4f2f4279e | 3,603,471 |
import aiohttp
import asyncio
async def findFallBackAsync(verbose: bool = True):
"""Same as findFallBackSync, but just async."""
if not aiohttp:
raise RuntimeError("You need to install aiohttp to be able to use findFallBackAsync.")
async with aiohttp.ClientSession() as session:
n = 0
... | 0ed25ae50060cb2c54ce51f72b14dab89b988d4d | 3,603,472 |
def get_md5_checksum_from_response(upload_response):
"""
Comparing the checksum of the local file with the returned checksum/Etag
stored in the upload response.
"""
etag = upload_response.headers.get('Etag', '')
upload_checksum = etag.replace('"', '')
return upload_checksum | ffb9287066aed803f79a406224c54d9035e57fc3 | 3,603,473 |
def read_txt_xyz(pathname):
"""
read a point cloud from txt file
"""
try:
pcd = np.loadtxt(pathname,delimiter=';').astype(np.float32)
except:
pcd = np.loadtxt(pathname,delimiter=',').astype(np.float32)
return pcd | 70cf2b48bb34f279facf05ace6bb576aab2eda3b | 3,603,474 |
def nbinom_dist(bin_values, K, M):
"""
Negative Binomial (Poisson-Gamma) distribution function
Parameters
----------
bin_values : array
scattering bin values
K : int
number of photons
M : int
number of coherent modes
Returns
-------
nbinom : array
... | 399ea786cbdb6af9141f5441243a5517a951959a | 3,603,475 |
from typing import Dict
def _get_package_version(package_data: Dict) -> str:
"""Get package version.
This function returns the non-development version for a development version.
It removes the .dev part and return x.y.z-1 version if it is a dev version.
"""
version = package_data.get('Version')
... | a38ae1e527be94948995fcf3aafee1cdc82fddb0 | 3,603,476 |
def check_config(config):
"""
Check all subcluster definitions in an entire config
:type config: ConfigParser.ConfigParser
:return: True if there are any subcluster definitions, False otherwise
"""
has_sc = False
for section in config.sections():
lsection = section.lower()
if... | 1464439f05c2aaf36afd1eca744721a03f280a6e | 3,603,477 |
def top_3_acc(output, target):
"""
Computes the top 3 accuracy
"""
return top_k_acc(output, target, k=3) | 798e8fa649c17fd4ed7491e534b25afc8398f3d7 | 3,603,478 |
def _reformat_polygons(polygons):
"""Convert polygons to a MulitPolygon
Accepts one more more sequence of 2- or 3-element sequences or a sequence
of shapely Polygon objects.
Parameters
----------
polygons : sequence of 2- or 3-element coordinates or sequence of Polygons
Polygon(s) to be ... | b573e22dacd5b01ba9aa240e7a1b9f5a73d3ae63 | 3,603,479 |
def ajax_required(f):
"""验证是否为AJAX请求"""
@wraps(f)
def wrap(request, *args, **kwargs):
# request.is_ajax() 方法判断是否是 ajax 请求
# 参考:https://code.ziqiangxuetang.com/django/django-ajax.html
if not request.is_ajax():
return HttpResponseBadRequest("不是AJAX请求!")
return f(r... | a7db3af1c50c0ee47e2bbfc9448de5cfd8bab5f2 | 3,603,480 |
def process(filename, model, args):
"""Process a file."""
# Load the data
music = muspy.load(filename)
# Get note and predicted labels
notes, predictions = predict(
music,
model,
args.dataset,
max_len=args.max_len,
use_duration=args.use_duration,
use_... | 2bdf485a05b8188508287312e0576724fe5e2598 | 3,603,481 |
import os
def test_infer_fail_generate_analyze_fail_dat():
"""
Feature: test dump analyze_fail.dat.
Description: test dump analyze_fail.dat if infer failed.
Expectation: success.
"""
class Net(nn.Cell):
def __init__(self):
super().__init__()
self.add = ops.Add(... | 5d41956750a5a9fa44667a834bfb839d7f9a14ee | 3,603,482 |
def truncate_string(s, length=200, end="…"):
""" A simplified version of Jinja2's truncate filter. """
if len(s) <= length:
return s
result = s[: length - len(end)].rsplit(" ", 1)[0]
return result + end | 4d97b31d0b9e6ee9eb0c14be88318271ebd1b3bb | 3,603,483 |
import ast
def unreachable_except(node, db):
"""Except statement is unreachable due to a more broad except.
```py
try:
raise ValueError
except Exception:
pass
except ValueError:
pass
```
"""
handlers = [
handler.type.id
for handler in node.hand... | 6e4fd49b2f7ab650d80ca6b97ad333aa5deb1290 | 3,603,484 |
import re
import string
def remove_more_punct(text):
"""
Parameters
----------
text : str
String containing text we want to lowercase, remove puncuation, and tokenize.
Returns
-------
Tokenized list of words from passed string.
"""
punct = set(string.punctuation)
tex... | 992824627b35ef8a572d4e7e722cc2385cbd22c4 | 3,603,485 |
def _round_log10_exp(x, rnd='up', decimals=1):
"""Rounds a log10 number to the nearest value
such that it can be cleanly written as A*10**y
Parameters:
x (float): Input number in log10.
rnd (str): Round 'up' or 'down'.
decimals (int): Number of decimals to round to.
Returns:
... | b2a12a4d05b3edc1dd33c2d260c6f8c984b296b9 | 3,603,486 |
def kou_log_chf(t, u, *, x0=1., mu=0., sigma=1., lam=1., a=0.5, b=0.5, pa=0.5):
"""
kou_log_chf(t, u, *, x0=1., mu=0., sigma=1., lam=1., a=0.5, b=0.5, pa=0.5)
Characteristic function of the probability distribution of values
at time t of the logarithm of a Kou jump-diffusion process,
(as per the ko... | f6e865163b37b1653e7950641d20a3a12e94bad9 | 3,603,487 |
def divide_data(n_data: int, split_config: dict = _default_split_config) -> dict:
"""
Divides data into subsets, according to the configuration split_config
n_data: total number of
Returns: Dict of {subset: mask}
e.g. {
'private/train': [0, 0, 0, 1, 0],
'private/heldout': [0, 0, 0, ... | 571c1c3849d6db010367ca1ba6b9bca48b3f5271 | 3,603,488 |
def get_prng(dev_random=False, fortuna=False, fortuna_seed_bytes=None,
fortuna_reseed_period=None):
"""
Create an instance of the requested pseudo-random number generator.
"""
fallback = bool(int(common.global_config(["KeyGenerator", "General"],
... | f3474c70e97ecfd623fdb9ef8e4e03316d8273bc | 3,603,489 |
def initialize_analyticsreporting():
"""Initializes an analyticsreporting service object.
Returns: analytics an authorized analyticsreporting service
object.
"""
credentials = ServiceAccountCredentials.from_p12_keyfile(
settings.SERVICE_ACCOUNT_EMAIL,
settings.KEY_FILE_LOCATION,... | 702eac632a768b11c98ba3a5dae5b14137cd6569 | 3,603,490 |
def _format_header(headers=None):
"""
format the headers that self define
convert the self define headers to lower.
"""
if not headers:
headers = {}
tmp_headers = {}
for k in headers.keys():
# if isinstance(headers[k], unicode):
# headers[k] = convert_utf8(headers... | 998584842010896f5d2a6327f79fba3add5898c7 | 3,603,491 |
def read_tech_staff_salary_sched():
"""
Reads data from "Tech Staff Salary Sched" sheet in staff_salaries.xlsx, which gives us information about tech staff
hourly wage by hour and years of experience---function currently only looks at the "year6_hourly_wage" column.
:return: Dict with the following for... | efbc6fb968eeef40e4e762bfc0f805a7a2c7d9c0 | 3,603,492 |
def run_spacytagger( string ):
"""
Runs spacy on `string` and returns a list of
:class:`quepy.tagger.Word` objects.
"""
assert_valid_encoding(string)
# For now, at least, perform our own pre-processing
# --to ensure terms like "presynaptic" are easily found later.
string = ' '.join( str... | bdb0b0575484fc2c34fa7d4f8937f12ca7616bbd | 3,603,493 |
def sequence_labeling_counts(true, predicted, equality_fn):
"""
Return FP, FN, and TP counts
"""
unique_classes = _get_unique_classes(true, predicted)
d = {
cls_: {"false_positives": [], "false_negatives": [], "true_positives": []}
for cls_ in unique_classes
}
for i, (true_... | 539594559072a3bdb4a37cedb46ee142f642e66e | 3,603,494 |
from display.tkinter import tkinter_led_strip_factory
from display.adafruit_ws2801 import adafruit_led_strip_factory
def create_application(
command_line_args,
num_leds,
brightness_schedule,
transition_length,
pattern_factories,
direction=LedDirection.START_TO_END):
"""Creates an Application instance.... | 970f198b52e31530774a2afc47580d149da2e302 | 3,603,495 |
def q_splitting_bar(z):
"""Returns quark 'reduced' splitting function"""
return q_splitting(z) + q_splitting(1-z) | 39f76c313c7e53ccd0d1d505332fd0f2230d8158 | 3,603,496 |
def usefull_function(a):
""" """
return a * a | 5a95e1f50a94f949d8aa2f4260edaed4941f42b1 | 3,603,497 |
def is_bspfile(filename):
"""Quickly see if a file is a bsp file by checking the magic number.
The filename argument may be a file for file-like object.
Args:
filename: File to check as string or file-like object.
Returns:
True if given file's magic number is correct.
"""
retu... | 0d5b64b48ec1409a4982acc2540dc1398ba5e843 | 3,603,498 |
import os
def env(*args, **kwargs):
"""Returns the first environment variable set.
if none are non-empty, defaults to '' or keyword arg default.
"""
for v in args:
value = os.environ.get(v)
if value:
return value
return kwargs.get('default', '') | 2cebd2036a2d183d82a7754594a4b9ec90db9c41 | 3,603,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.