content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def feedback_reply():
"""
反馈回复
"""
if request.method == "GET":
feedback_id = request.args.get("feedback_id")
page = request.args.get("page")
if feedback_id:
feedback = None
try:
feedback = FeedBack.query.get(feedback_id)
except... | aab76ef9191066cd546a8e9e7fab62f1331aea6c | 3,603,384 |
from typing import Optional
def subcommand(
name: Optional[str] = None, description: Optional[str] = None
) -> SlashSubCommandConstructor:
"""Build a subcommand for within a group."""
return SlashSubCommandConstructor(
parent=None,
name=name,
description=description,
) | a5defe20061533e00b7c0b87c82f43e5777bf030 | 3,603,385 |
import random
def genRandomStructure():
"""
Generates a random neural network structure.
"""
s = []
# Input layer has either 2 or three nodes.
if random.uniform(0, 1) > 0.5:
s.append(3)
else:
s.append(2)
p = 1.0
while p > 0.5:
# Add a new layer of random si... | efd1ea11e27cdea9222052ac7f12dbed89f5ac44 | 3,603,386 |
def pix(cm_value, dpi=600):
"""Function to convert figure sizes in cm to pixels based on a dpi requirement"""
return int(np.round((cm_value/2.54)*dpi)) | 27ac1059441438b4c68497f3968ca602fbff1c74 | 3,603,387 |
import logging
def distribution_plot(data,
title="Distribution", fig_size=(5, 5), c="red",
save_as=None, logger=None):
""" Build, save, and return a heat map plot.
:param pandas.DataFrame data: A pandas DataFrame containing data for the plot
:param str title: O... | 3db1d1bc1c126e54c5ee48e12a6124594fd144ed | 3,603,388 |
from pathlib import Path
def get_lon_lat_path(ax, transform, lon_lat):
"""
Draw a curve, taking into account discontinuities.
Parameters
----------
ax : ~matplotlib.axes.Axes
The axes in which to plot the grid
transform : transformation class
The transformation between the wor... | c9d48b36e1d5bdee955fc93befdabc39c3424935 | 3,603,389 |
def get_keck_osiris_filt(name):
"""
Define keck osiris filters as pysynphot object
"""
try:
t = Table.read('{0}/keck_osiris/{1}.txt'.format(filters_dir, name), format='ascii')
except:
raise ValueError('Could not find keck_osiris filter {0} in {1}/keck_osiris'.format(name, filters_dir... | 4d918a21fb40d4e39843653a95e6367b5a935be4 | 3,603,390 |
from datetime import datetime
def parse_time_from_schedule(str_time, parsed_time_is_future):
"""
Given a string time in the format of SCHEDULE_TIME_FORMAT = '%H:%M'
and a boolean value stating if that time is in the future or not, convert
that string into a datetime object.
Some examples, assuming... | 665e8e31785c05c0536ad643afc22f7895c550e8 | 3,603,391 |
def validate_boxes(boxes, image_size=None, min_area=None, box_format='corner', normalized=False):
"""
Checks if the given boxes are valid.
:param boxes: array of boxes with shape (#boxes, 4)
:param image_size: If set check for each box if it is in the image
:param min_area: if set check for each box... | 6658fed8b2cba457968220142e86e64492353716 | 3,603,392 |
def get_short_long_labels_from_qval_dict(qval_dict, geometry="saxs"):
"""Y.G. 2016, Dec 26
Get short/long labels from a qval_dict
Parameters
----------
qval_dict, dict, with key as roi number,
format as {1: [qr1, qz1], 2: [qr2,qz2] ...} for gi-saxs
format as {... | 883ed4fdbd9ccbd367830a73502d99b816be1306 | 3,603,393 |
def get_number_of_hangars_to_visit() -> int:
"""
Function loads the number of stops/hangars to visit
"""
nr_of_hangars_to_visit = input().rstrip()
while not is_number_of_stops_ok(nr_of_hangars_to_visit):
print('Incorrect value!')
nr_of_hangars_to_visit = input().rstrip()
return... | 48ffb96ee3978b67b1da049271d7a2309b8d0b3a | 3,603,394 |
def filter_errors(seq, errors):
"""Helper for filter_keys.
Return singleton list of error term if only errors are in sequence; else
return all non-error items in sequence.
Args
seq: list of strings
errors: dict representing error values
Returns
List of filtered items.
"""... | 93f44cd933e48974c393da253b7f37057ea7de19 | 3,603,395 |
def state_to_df(statefile):
"""Transform state file into pandas dataframe
"""
return pd.read_csv(statefile,
compression='gzip',
sep=' ',
skiprows=[1,2]
) | 995bb5a3695c4bc25a54d629dadbcae78f5c80e7 | 3,603,396 |
import torch
def train_torch_model(network, config, data_iterator, new_weights=False):
"""Main function to run the optimization.
Parameters
----------
network : class
A pytorch network class.
config : yaml
The configuration file.
data_iterator : dict
A data iterator wi... | 8ac02cb370ccee07909ced8c321795eb4ba3e05d | 3,603,397 |
def _offset(x, y, xoffset=0, yoffset=0):
"""Return x + xoffset, y + yoffset."""
return x + xoffset, y + yoffset | a6c88b2ee3172e52f7a538d42247c0fdc16352f8 | 3,603,398 |
import psutil
def net_stat_recv(x, interface=None):
""" Get the number of bytes received. """
if not interface:
interface = get_netiface()
if interface:
return psutil.net_io_counters(pernic=True)[interface].bytes_recv
else:
return 0 | 4d829d3ef493d0437bdfae479778f4f7d2587ce9 | 3,603,399 |
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 |
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 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 |
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 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 |
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 |
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 |
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 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.