content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from datetime import datetime
import time
def get_ttl(ttl_days, start_date=datetime.datetime.today()):
"""Get ttl value epoch format to insert into DDB TTL field
Arguments:
ttl_days {int} -- Number of days to keep the record
Keyword Arguments:
start_date {datetime} -- Starting timestamp ... | 7af4baa1e9d02f230487131ae23808496acd0ff0 | 63,300 |
def layout_bounding_boxes(canvas_x, canvas_y, canvas_width, line_height,
space_widths, y_space, sizes):
"""Layout token bounding boxes on canvas with greedy wrapping.
Args:
canvas_x: x coordinate of top left of canvas
canvas_y: y coordinate of top left of canvas
canvas_width: ... | 057eb7976849444efa27d51d2ec1209e0f95eaa8 | 63,301 |
def closing():
"""HTML boilerplate."""
return """</tr></table>\n<div align='center' style='margin-top: 10px'>
<button type="button" id="btn" class="btn btn-primary" onclick='create_playlist()'">Create Playlist</button>
</div>\n</html>""" | 51556490c82c04e43182923e3e779f8d3fcc392f | 63,302 |
def compute_trust_values(dsk, do_plot=False):
"""
Compute trust values following formula 6
k:= number of blendshapes
n:= num_features (num_markers*3)
:param dsk: delta_sk vector (k, n)
:param do_plot: decide if we want to plot the between-correlation matrix
:return: trust values vector (k,... | 5bd8b66ada3699b8426410aa1a1cfe410f23bdc3 | 63,303 |
def make_query(user_id=None, tenant_id=None, resource_id=None,
user_ids=None, tenant_ids=None, resource_ids=None):
""" Returns query built form given parameters.
This query can be then used for querying resources, meters and
statistics.
:Parameters:
- `user_id`: user_id, has a priority o... | 43a551a50f19d49a963c5a2f855a9df6e3fbe595 | 63,304 |
def get_valid_new_slug(slug_base: str, path: str) -> str:
"""
Given a slug to act as a base/prefix, returns a slug that will satisfy unique constraints,
adding/incrementing a numerical suffix as necessary.
"""
starter_qset = WebsiteStarter.objects.exclude(path=path)
slug_exists = starter_qset.fi... | ff45cff0627af600faaf855585e7797ec28535bc | 63,305 |
from typing import List
def fat_cross_perform_df(arr_list: List[ArrivalDistribution],
ser_list: List[ConstantRateServer],
opt_method: OptMethod,
perform_param_list: PerformParamList) -> pd.DataFrame:
"""Compute delay standard_bound for T i... | 76eaf2ee7e8fbed7a09741d48d3c0c08e5939a0a | 63,306 |
def estacionesFromXML(element: xmlElement, text:str) -> list:
"""
devuelve la lista de estaciones de un elemento xml
"""
estacionesElements = element.findall(text)
estaciones = [estacion.text.strip() for estacion in estacionesElements]
if len(estaciones) == 0:
raise ValueError('no se han... | c049b9fb9a4d55310156084683ea32873f3eea71 | 63,307 |
import copy
import uuid
def create_record(data):
"""Create a test record."""
with db.session.begin_nested():
data = copy.deepcopy(data)
rec_uuid = uuid.uuid4()
pid = record_pid_minter(rec_uuid, data)
record = ExampleRecord.create(data, id_=rec_uuid)
return pid, record | 72204912d6b15e1bfbf0bb0150b6710f8cb4501e | 63,308 |
def ldns_rdf2buffer_wire(*args):
"""LDNS buffer."""
return _ldns.ldns_rdf2buffer_wire(*args) | 9450f7016a56c53003b85898c6009ae6946d22d7 | 63,309 |
def calc_E_SH(type, tatekata, region, sol_region, A_A, A_MR, A_OR, ENV, mode_H, mode_C, NV_MR, NV_OR, H_MR, H_OR):
"""暖房設備の設計一次エネルギー消費量
Args:
type(str): description]
tatekata(str): 建て方
region(int): 省エネルギー地域区分
sol_region(int): 年間の日射地域区分(1-5)
A_A(float): 床面積の合計 (m2)
A_MR(float... | cd505866a0fa86e6e2b54165197f8035a9c45690 | 63,310 |
def get_rostime():
"""Returns current ROS1 time, as rospy.Time."""
return rospy.get_rostime() | aa35257b07b8d33e5f8b268709df344b3008c3f7 | 63,311 |
def lnlike2(theta, xi, yi, ei):
""" Model with LSS variance modeled by a power law as a
function of redshift"""
f0, t0, gamma, var_a, var_b = theta
if 0 <= f0 < 3 and -10 <= t0 < -2 and 1 <= gamma < 7 and \
0.001 <= var_a < 1 and 1 <= var_b < 5:
model = f0 * np.exp(-np.exp(t0) * (1 + xi... | 8a128652c35dde95aeae6ed5e59ce0343e7cd354 | 63,312 |
import torch
def clone(x):
"""
Clones all torch tensors and numpy arrays in nested dictionary or list
or tuple and returns a new nested structure.
Args:
x (dict or list or tuple): a possibly nested dictionary or list or tuple
Returns:
y (dict or list or tuple): new nested dict-li... | 85b44aee8be9cb9b199201bee0ad2234cc4063c9 | 63,313 |
def route_not_found(e):
""" Api/Route not found
"""
return render_template("error/404.html"), 404 | 8b9b57d7e9a226f1bd708df8bd0831f8f676afca | 63,314 |
from sys import version
def options_sanitation(por, loc=""):
"""Checks to make sure the port and destination ip are both valid.
Launches error windows if there are any issues.
"""
global root
if version == 2:
por = unicode(por)
if isCLI:
root = 0
if not por.isnumeric():
... | 7e1dacc45c1cd40cacdcffc49de69433fddb5999 | 63,315 |
def compute_modularity_density(adj, c, conn_clusters, cluster_labels,
total_weight, dict_bool):
"""Determines modularity density of a set of communities.
Parameters
----------
adj : SciPy sparse matrix (csr or csc)
The N x N Adjacency matrix of the graph of intere... | 810ef02788206662e2f8ec32673c74f2aadde55a | 63,316 |
def chisquare_binning_boundary(input_df, feat_name, label_name, k_part):
"""Calculate binning threshold list by chisqure binning method.
Parameters
----------
input_df : DataFrame
Sample set.
feat_name : str
Feature name.
label_name : str
Label name.
k_part : int
... | 7452a08899f555f125149c14404822b53564837c | 63,317 |
def index():
""" The home page has a list of prior translations and a form to
ask for a new translation.
"""
return '<h1> Dedicated server (python) is on. </h1>' | 3bab9b4ce6ed30c5a265b88581ce7557c8fa5e8d | 63,318 |
def lm_loss_fn(transformer, vocab_size: int, params, rng, data):
"""Compute the loss on data wrt params."""
batch_token_ids = jnp.array(data['transformer/encoder_input:0']) # obs
batch_labels = jnp.array(data['transformer/decoder_input:0']) # target
logits = transformer(params, rng, data)
targe... | eebe4290311e5c660c3bd01c2c9a85046cf90eee | 63,319 |
from typing import Tuple
from typing import List
def process_response(response: dict) -> Tuple[List[dict], dict]:
"""Process response with entries."""
entries = process_data(response)
pagination = response['meta']['pagination']
return entries, pagination | 6809aba42ebfae81b7c1b0d75109d1be47ad83e5 | 63,320 |
def second_moment_loss(tt: np.array, mu: np.array, sigma: np.array, logp: np.array) -> float:
"""
Because log-price likelihood is Gaussian, standardizing the test data should give a second moment (i.e. squared
expectation plus variance) of 1.
Parameters
----------
tt: np.array
Array of ... | 532338c75eb402261c2fe697877a04ced4bd171e | 63,321 |
def unpack_query_results(columns, results):
"""
Unpacks the result of a SELECT query into a list of Python dicts.
:param columns: The columns that map to the fields in each result record. These
must be in the same order as the fields in the result records,
and are re... | 9415f99dec8875d31d3ee090d163e4688f848cd5 | 63,322 |
def integer(bits=None):
"""
Correspond to an integer.
:param bits: The bits for the integer.
:return: An instance of Integer.
"""
global csp
check_engine()
csp.variables.append(csp.int(size=bits))
return csp.variables[-1] | e49f1e38ed2ce12f5ae03b795595be1c60513bc6 | 63,323 |
import os
import logging
def combine_mash_sketches(sketches, etd_db_dir, cores):
"""
Combine all the mash sketches using paste
"""
card_prev_msh_fp = os.path.join(etd_db_dir, 'card_prev.msh')
if os.path.exists(card_prev_msh_fp):
logging.info(f"Removing previous combined mash sketch: {card... | 2fa9d91166194651fdfe8abbc7a96e453b6a46ce | 63,324 |
def ExponentialSearch(arr, item):
""" If item is in array, Returns the index of first occurence of the item in the array; Else Returns False.
Searches for an item using 'Exponential Search' algorithm; Requires a Sorted Array.
Time Complexity :-
Best Case : Ω(1)
Worst Case : O... | 525016aaec7820513f91ecd61802f87dab33cce5 | 63,325 |
import itertools
def complete_structure_mask(image_array: np.array, mask_array: np.array, debug=False) -> np.array:
"""This funtion takes an image (array) and an array containing the masks (shape: x,y,n where n is the amount of masks and x and y are the pixel coordinates).
It detects objects on the contours o... | fe723b89d4e1613d531fbce573ecb05af7ada124 | 63,326 |
def build_gdrive_bridge():
""" Похоже можно ужать вызов и удалить ключи из кода
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
"""
# Copy your credentials from the APIs Console
CLIENT_ID = '105447427029.apps.googleusercontent.com'
CLIENT_SECRET = 'azmcKEseppjZvu... | d40fe8f581c4ef39a7f0618e6abfe03846e7b92c | 63,327 |
import functools
def pass_defaults(func):
"""Decorator that returns a function named wrapper.
When invoked, wrapper invokes func with default kwargs appended.
Parameters
----------
func : callable
The function to append the default kwargs to
"""
@functools.wraps(func)
def wra... | 0a6ef20daea604e056e53df24dae5c76da84a16f | 63,328 |
def data_set_cls(
types=(),
subtypes=False,
checked=None,
module=None,
factory=None,
serialized=True,
serializer=None,
deserializer=None,
represented=True,
compared=True,
qual_name=None,
unique=False,
):
"""
Make auxiliary interactive set data class.
:param ... | 91248019bf8becf05ff01d6abc9966d93ea9e09c | 63,329 |
from typing import Tuple
from typing import Union
from typing import List
from typing import Dict
from typing import Iterable
import requests
import json
def microservice_api_rest_seldon_message(
method: str = "predict",
microservice_endpoint: str = "localhost:5000",
shape: Tuple = (1, 1),
data: objec... | 5ed167f0dfc89015f24a090b49a446f27e2b8f3b | 63,330 |
def new_article():
"""文章资源post请求处理"""
article = Article.from_json(request.json)
article.author = g.current_user
db.session.add(article)
db.session.commit()
return jsonify(article.to_json()), 201, \
{'Location': url_for('api.get_article', id=article.id)} | e89a5ca858ca7e43669fc2ff89db37ff01547e29 | 63,331 |
def align_iterators(func, *iterables):
"""
This generator takes a bunch of iterables that are ordered by func
It sends out ordered tuples::
(func(row), [rows from all iterators matching func(row)])
It is used by :func:`matplotlib.mlab.recs_join` to join record arrays
"""
class myiter:
... | ad7d816c43ddfa57a5a3a6c14e4209f44d0b1408 | 63,332 |
def x1x2(farm_id):
"""
>>> x1x2(1), x1x2(2), x1x2(3), x1x2(4), x1x2(5)
('x1x6', 'x2x7', 'x3x8', 'x4x9', 'x5x0')
"""
i = int(str(farm_id)[-1]) - 1
x1 = str(i - 5 * (i / 5) + 1)[-1]
x2 = str(i - 5 * (i / 5) + 6)[-1]
return 'x%sx%s' % (x1, x2) | b0da6f8e92551247ca0ef6f017adbe03c429487b | 63,333 |
def make_figure(
node_name,
grid_T_hr,
dev_grid_T_hr,
timezone,
mesh_mask,
dev_mesh_mask,
figsize=(8, 10),
theme=nowcast.figures.website_theme,
):
"""Plot the temperature and salinity time series of observations and model
results at an ONC VENUS node.
:arg str node_name: Oce... | 4d1400251ba5d3519396c0fa9f280d00a8722343 | 63,334 |
import random
def load_data(use_test, model_loc):
"""
Load the data into a train/val/test set that allows for easy access.
@return bag-of-word representation of training, validation, test sets (with labels).
"""
t_ids = set(list(preprocessor.train_document_ids()))
te_ids = set(list(prepr... | 15f9b1a5d28cd9e0cf12be9e954dd850329749c4 | 63,335 |
def filter_tests(test_kind, selector_config, test_file_explorer=_DEFAULT_TEST_FILE_EXPLORER):
"""Filter the tests according to a specified configuration.
Args:
test_kind: the test kind, from _SELECTOR_REGISTRY.
selector_config: a dict containing the selector configuration.
test_file_exp... | bfc914c6304173831755291fb9acba29a7b03860 | 63,336 |
def best(equations=None):
"""Return the equation with the best score, in sympy format.
By default this uses the last equation file.
"""
if equations is None: equations = get_hof()
best_sympy = best_row(equations)['sympy_format']
return best_sympy.simplify() | 3b10c37c3f2b751889154e0eff51d1c94023658f | 63,337 |
def batchify(fn, chunk):
"""
Constructs a version of 'fn' that applies to smaller batches.
Function from NeRF: https://github.com/bmild/nerf
"""
# chunck = batch size
if chunk is None:
return fn
def ret(inputs):
return tf.concat([fn(inputs[i:i+chunk]) for i in range(0, input... | badf68a4f7481658a713be49af83b4032807ca72 | 63,338 |
def nice_number_pt(number, speech, denominators=range(1, 21)):
""" Portuguese helper for nice_number
This function formats a float to human understandable functions. Like
4.5 becomes "4 e meio" for speech and "4 1/2" for text
Args:
number (int or float): the float to format
speech (boo... | 73c8f61eff5a98ed4d9e0810369eec05122f018c | 63,339 |
def shear_x(image, level):
"""Equivalent of PIL Shearing in X dimension."""
# Shear parallel to x axis is a projective transform
# with a matrix form of:
# [1 level
# 0 1]
image = image_transform.transform(
wrap(image), [1., level, 0., 0., 1., 0., 0., 0.])
return unwrap(image) | 00d621f87521e25691892180d9892730f47e1884 | 63,340 |
from typing import Optional
def compute_true_measure(measure: BaseMeasure, true_label_dist: ndarray, labels: Optional[ndarray] = None):
"""Compute the measure given the (unknown) oracle response
Parameters
----------
measure : instance of activeeval.measures.BaseMeasure
Evaluation measure... | 53bd37d91f6bb1b6979be134fd726e36124fac40 | 63,341 |
def func_insert_array_parameter_node( node_id, name, value, unit = None, description = None ):
"""
Define function call to insert array parameter associated to node into the database.
"""
if not isinstance( node_id, int ):
raise TypeError( 'parameter \'node_id\' must be of type \'int\'' )
i... | 419ec57e92e6232d1aa00babcd4178b8a88b29b8 | 63,342 |
import random
from re import X
import math
def minimax(board):
"""
Entrypoint for _minimax recursive function
Returns None is board is in terminal state.
Otherwise returns the utility of the resulting board
and action.
"""
if terminal(board):
return None
possible_actions = l... | 912f092bf7642f6967e09131e342d62ddff5f32f | 63,343 |
import re
def split_verses(verses):
""" With a string of multiple verses, split on verses
>>> split_verses("[1] Verse1 [2] Verse2")
["Verse1", "Verse2"]
"""
verses_list = re.split("\[\d+\]", verses)
verses_list = [verse.strip() for verse in verses_list if verse.strip()]
return ... | f965c8a59db21c2c31e9a017d9226e430043c272 | 63,344 |
from datetime import datetime
import pytz
def read_gpgga(sentence, timestamp, do_print=False):
""" Read and parse GPGGA message"""
values = sentence.split('*')[0].split(',')
result = {}
# Linux timestamp
try:
result['linux_stamp'] = int(timestamp)
except:
result['linux_stamp']... | 2612770ed46030bbd36d313cb06b2ffd340c6bb3 | 63,345 |
def energy(prog, method, output_string):
""" Retrieves the desired electronic energy.
"""
assert prog in energy_programs()
assert method in energy_program_methods(prog)
module = _import_module(prog)
energy = module.ENERGY_READERS[method](output_string)
return energy | 9dc76952dd7a13ab500859b5bb77160a3ff7b876 | 63,346 |
def translate_avl_body(suave_body):
""" Translates body geometry from the vehicle setup to AVL format
Assumptions:
None
Source:
None
Inputs:
body.tag [-]
suave_wing.lengths.total ... | 987366bb8f9bb482b869c3bd538b39e757983b6a | 63,347 |
def write_intro_end_slides(conn, command_args, orig_file_id, duration, size_x,
size_y):
"""
Uses an original file (jpeg or png) to add frames to the movie.
Scales and pads to fit size_x, size_y.
@param orig_file_id: Original File (png or jpeg) ID
@param duration: ... | 21f16d4b8e6c5373533d547737c5ed66d6045982 | 63,348 |
from typing import List
import os
def json_files(path) -> List[str]:
"""List all json files under a dir recursively."""
paths = []
for root, _, files in os.walk(datapath):
for file in files:
if ".json" in file:
absolute = os.path.join(root, file)
relativ... | 74590622e745ba20f1beca8dc302c838f04396c2 | 63,349 |
def cape_timing(rolling_window, neutral_wt, freq, static_wts, fac_names,
start_date='19260731'):
"""
Function to implement CAPE Valuation Timing
Args:
rolling_window (int): lookback in months used for evaluating CAPE
levels
neutral_wt (float): weight assigned to mar... | e192f49d4dab82dd023659ddbf04d341e38d80a2 | 63,350 |
def ServerClass(cls):
"""Decorate classes with for methods implementing OSC endpoints.
This decorator is necessary on your class if you want to use the
`address_method` decorator on its methods, see
`:meth:OSCThreadServer.address_method`'s documentation.
"""
cls_init = cls.__init__
def __i... | f28760b2a138f1b95405f95dc122881b6d95d2e0 | 63,351 |
def read_dataset():
"""
Karateclub library requires nodes to be named with consecutive Integer numbers. After running the library, we take
as output the embeddings in ascending order. So in this function, we need to reassign each ASN to its own embedding.
:return: A dataframe containing tha AS number an... | cbc33472975e1178c9a1b7348f03b17668570767 | 63,352 |
from .simplify import bottom_up
def _gamma_as_comb(expr):
"""
Helper function for combsimp.
Rewrites expression in terms of factorials and binomials
"""
expr = expr.rewrite(factorial)
def f(rv):
if not rv.is_Mul:
return rv
rvd = rv.as_powers_dict()
nd_fa... | c6175f647fbba2438a956a4fc7cb2e4519a107ce | 63,353 |
def conformers_combinations_by_lowest_conformer(label, mol, base_xyz, multiple_tors, multiple_sampling_points,
len_conformers=-1, force_field='MMFF94s', max_combination_iterations=25,
torsion_angles=None, multiple_sampling_p... | 81ae029f98f38feb837be08188c7632c6dbb464c | 63,354 |
from operator import add
def make_network(input_shape, kernel_size=11):
"""Create the neural network model.
Parameters:
input_shape (tuple of ints): the shape of the input tensor
kernel_size (int): size of convolution kernel
Returns:
Keras model
"""
first = True
input... | 987bfe10d7964908f35c7876293cb00cddcaa498 | 63,355 |
def _tf_tensors_nonngram(reader, shuffling_queue_capacity, min_after_dequeue):
"""A tensorflow data adapter for non ngrams. Return value is a named tuple with tensorflow tensors supplying
the data directly into a Tensoflow graph. See `tf_tensor` documentation for input/output arguments meaning."""
# TODO: implem... | c10ea585ce6bcf6d64ddf4ebf52c9501e349a154 | 63,356 |
def select_features_by_keyword(keywordList, features):
"""
Select feature columns by keywords
"""
selected_features_list = []
for word in keywordList:
selected_features = [col for col in features.columns if word in col]
con_list = selected_features_list + selected_features
se... | 5dc16571fd8d48b78edc2cb204938db42c54bd69 | 63,357 |
def find_pointsII(gt_rectangle, w_p, h_p):
"""Find the rectangles at the top-left most-, bottom-left most, top-right
most- and bottom-right most corners that have a JI equal to 1/2 to the
ground truth rectangle.
! The rectangle needs to be a top-left Rectangle for this function!
This is done wit... | 0ce75fd7d1aad536a9477af79475e31dd0040fd2 | 63,358 |
def include_tagcanvas(element_id, width, height, url_name='tagcanvas-list',
forvar=None, limit=3):
"""
Args:
element_id - str - html id
width - int - pixels width
height - int - pixels height
url_name - if url_name=='' then no links. Default: tagcanvas-list
... | ec861bac56c7031e41915c7102c9474accd9a33b | 63,359 |
def measure_corrs_mean(corrs, params=None):
"""Measure based on computing the mean of the non-auto correlation values.
Parameters
----------
corrs: np.ndarray
the correlation matrix.
params: optional (default=None)
the parameters needed to compute the output measure.
Returns
... | 3476fd1a0bc70d9fac13f6c094d7f563a58bc620 | 63,360 |
from typing import Callable
from typing import Tuple
from typing import Any
from typing import Dict
import functools
def wrap_for_agg(
function: Callable,
args: Tuple[Any, ...],
kwargs: Dict[str, Any],
) -> Callable:
"""Wrap a function for use with Pandas `agg`.
This includes special logic that w... | 7152ae610c2dea177758bf0c3337f4425c8d86c5 | 63,361 |
def path_as_list(path: dict):
"""Get sequence of vertices from path[s, t] = v
return as list for each searcher s
path[s] = [v0, v1, v2...vh]"""
pi = dict()
h = get_h_from_tuple(path)
m = get_m_from_tuple(path)
T = get_set_time_u_0(h)
S = get_set_searchers(m)[0]
# loop through time... | 67c17f907a2509c770d6cdc8fbc7840c523746da | 63,362 |
def bisect(changelog, state):
"""find the next node (if any) for testing during a bisect search.
returns a (nodes, number, good) tuple.
'nodes' is the final result of the bisect if 'number' is 0.
Otherwise 'number' indicates the remaining possible candidates for
the search and 'nodes' contains the ... | e807709e825fb984314e1954296c9ae6afef6de6 | 63,363 |
def _sanitize_bin_name(name):
""" Sanitize a package name so we can use it in starlark function names """
return name.replace("-", "_") | 37e9a09cf60f83c087734b74ccf0ba7d3c46fea6 | 63,364 |
def _line(x, a, b):
"""
Dummy function used for line fitting
:param x: independent variable
:param a, b: slope and intercept
"""
return a*x + b | e883689fb39c51064b1f1e0a34d1ab03cc11efb9 | 63,365 |
from functools import reduce
def getattrd_last_but_one(obj, name: str, default=NoDefaultProvided):
"""Same as getattrd(), but leaves out last ".foo" part.
e.g. name="branch.apple.color" obj = tree -> tree.branch.apple
"""
try:
return reduce(getattr, name.split(".")[:-1], obj)
except (Attr... | b390324da6f5750bdebf974071221f095f47d03f | 63,366 |
import zipfile
import os
def make_zip(file_dir_in:str, file_name_out:str) -> None:
"""Write all files in a directory and/or it's subdirectories make it a zipfile"""
with zipfile.ZipFile(file_name_out, 'w', zipfile.ZIP_DEFLATED) as myzip:
for root, dirs, files in os.walk(file_dir_in):
for file in files:
m... | 219ef22c3035d435b1a58230b9a9ce4a02672f07 | 63,367 |
import torch
def init_vuz(A, D, x, v0=None, inv_A=None, device='cpu', force_numpy=False):
""" Initialize v, u and z. """
# cast into tensor
x = check_tensor(x, device=device)
# get useful dimension
n_samples, _ = x.shape
n_atoms, _ = A.shape
# XXX will break if D is not (n_atoms, n_atoms ... | 01e55f3d247e5d3da6e808d79ff708e0514c22a6 | 63,368 |
def embed(markdown: str, **kwargs) -> Embed:
"""渡されたマークダウンの文字列をタイトルと説明とフィールドが設定されている`discord.Embed`に変換します。
見出しは三段階設定することができ、一段でタイトルで二段でフィールドそして三段で`**#** ...`のようになります。
もしフィールドの`inline`を`False`にしたい場合は`## !`のようにしてください。
Parameters
----------
markdown : str
変換するマークダウンです。
kwargs : dic... | 0bf6b5514a89f7dc7fae7e1d6b43bd94e190ea90 | 63,369 |
import os
from sys import path
def load_hs13_dyn_RGG_params():
"""Load the standard parameters to generate SocioPatterns HS13
surrogate networks using the dynamic RGG model.
Returns
-------
:obj:`dict`
The `kwargs` to pass to :func:`tacoma.dynamic_RGG`.
"""
fn = os.path.join(path... | b210286adcd2b21c6089853a983d39ca73c8c00f | 63,370 |
def tw_connect(keys):
"""Connect to Twitter API using Tweepy.
Parameters
----------
keys : dict
Dictionary object containing keys app_public, app_secret, per_public,
and per_secret.
Returns
-------
api : object
Authenticated Tweepy API object.
"""
auth = tw... | 641814c5d16cdcf9ee4330837b98c71ef311af9d | 63,371 |
def and_s(*args):
"""Simplifying Boolean And operator."""
num, c_bxs = _convert_args(args)
return _bx(lib.boolexpr_and_s(num, c_bxs)) | 1f66aa129964e783b85d3e9cb7b95986b42f6535 | 63,372 |
def d_y_diffr_dx(x, y):
"""
derivative of d(y/r)/dx
equivalent to second order derivatives dr_dxy
:param x:
:param y:
:return:
"""
return -x*y / (x**2 + y**2)**(3/2.) | 696a5b4a5ff8e6483b5082cb394b3ac4bca83313 | 63,373 |
def get_fitter(n_mcsim, generator, model):
"""Here is where the parameters (particularly priors) are specified
for each fitting model.
"""
if model == "LN2Stationary":
fitter = LN2Stationary(
synthetic=generator,
n_mcsim=n_mcsim,
mu_sd=1.5,
mu_mean... | 789180cafb4bab1160854d1c3380080e77e8ff08 | 63,374 |
import os
def read_image(path):
"""
Read an image to RGB uint8.
Read with opencv (cv) and covert from BGR colorspace to RGB.
:param path: The path to the image.
:return: RGB uint8 image.
"""
assert os.path.isfile(path), "File not found"
im = cv.imread(path)
# Convert from cv2 stan... | 2f257864091a66013c38ef8e109898be2507fa0c | 63,375 |
from typing import Optional
from typing import Union
def create_digit_recognition_task(
train_client_spec: client_spec.ClientSpec,
eval_client_spec: Optional[client_spec.ClientSpec] = None,
model_id: Union[str, DigitRecognitionModel] = 'cnn_dropout',
only_digits: bool = False,
use_synthetic_data: ... | 97006f9586912bafaa10a2848e0428053b6d18cb | 63,376 |
def xmlescape(data):
"""
"""
return escape(data, entities={
"'": "'",
"\"": """
}) | 261f2df33839a975d8878c9231d746ada1d79337 | 63,377 |
def direct_ft_maximise(obj, bounds, max_evals, *args, **kwargs):
"""
A wrapper for maximising a function which calls direct_ft_minimise. See arguments
under direct_ft_minimise for more details.
"""
min_obj = lambda x: -obj(x)
min_val, max_pt, history = direct_ft_minimise(min_obj, bounds, max_evals,
... | 557ba8347c10933ad67e73654e04d8a54d65091a | 63,378 |
from typing import Tuple
def splat_bilateral_grid (input: Tensor, guide: Tensor, grid_size: Tuple[int, int, int]) -> Tensor:
"""
Splat an image into a homogenous bilateral grid.
Parameters:
input (Tensor): Input image with shape (N,C,H,W).
guide (Tensor): Splatting guide map with shape (N... | e9c61ab0c872df9abe5a74b3c909c7b9d30b29e9 | 63,379 |
def yeet(yeetee_width, grid_width, enter_from="right"):
"""
Work out the array indeces needed to slide a grid across a grid.
Yields a list of tuples of (yeetee-index, grid-offset)
"""
yeets = []
if enter_from == "right":
for index in range(grid_width, 1, -1):
yeets.append((... | 62ca3ee33ed1e06000bc50ef4dd927eda9b886f1 | 63,380 |
def add(moment):
"""Return the moment that is a gigasecond after given moment."""
gigaseconds = timedelta(seconds=1E9) # 1E9 == 1_000_000_000
return moment + gigaseconds | 75e036e2c1765fe497277cb10a90cec439c6c636 | 63,381 |
from enum import Enum
from datetime import datetime
def custom_asdict_factory():
"""
Return a custom dict factory to use with dataclasses' :func:`asdict`. Custom
behavior include:
* Serialize Enums with their value
* Omit fields whose value is OmitNone() (e.g. `foo: str = OmitNone()`)
This i... | fc1b49c9e9128702d752bdb2ee0856f517d5d223 | 63,382 |
import types
from typing import Any
def invoke(boto3_function: types.FunctionType, **kwargs: Any) -> Boto3Result:
"""Call a function and return the response as a Boto3Result.
Arguments:
boto3_function: A callable to be called. Typically this will be a
function in the boto3 module.
... | e019ab82ddb192e666565a9ac8e58abeae1a933b | 63,383 |
def get_mass_mdot(tracers,
nbins_theta=5,
nbins_time=100):
"""Calculates total mass in wind and Mdot_wind
as a function of time and angular bin.
"""
theta_range,t_range,_,mtots,_ = spacetime_bins(tracers,
nbin... | da5c7e5fdb01cce9ce23b0cfa307aaa9dfa12e3d | 63,384 |
def parse_v2_cards(cardstring):
"""Extract card objects from a v2 url encoded list of cards
Args:
cardstring: Deckbuilder card string (multiple cards)
Returns: List of Card objects
Note: Card string is a concatenate (with no delimiter) set of 3-4 characters with the the format:
XYZ
... | 3d45f5f28f175b032a42ddbcfe20f783c4c0faf6 | 63,385 |
def get_discoverable_groups_view(request):
# type: (Request) -> HTTPException
"""
List all discoverable groups (publicly available to join).
"""
public_groups = ru.get_discoverable_groups(request.db)
public_group_names = ax.evaluate_call(lambda: [grp.group_name for grp in public_groups],
... | af39241fe87946bd916c36569c3d6e80ebea3a20 | 63,386 |
def filter_rewards(rewards: np.ndarray, dones: np.ndarray) -> np.ndarray:
"""
Filter rewards based on done flags, all rewards after a done are set to 0.
:param rewards: The rewards to filter (num_envs, num_steps) or (num_steps,)
:param dones: The done flags (num_envs, num_steps) or (num_steps,)
:ret... | dab1bb5366e87755ebb98c2d9c103a173fdf1aa3 | 63,387 |
def normalise_line_tail(line):
"""Replace white-space characters at the end of the line with a newline character"""
return line.rstrip() + '\n' | 25c22c0c39a73d5b9a449f202433f77bd0e1bb3b | 63,388 |
def le(h): # (int) -> Sequence[int]
"""
Little-endian, takes a 16b number and returns an array arrange in little
endian or [low_byte, high_byte].
"""
h &= 0xffff # make sure it is 16 bits
return [h & 0xff, h >> 8] | 8f4b6e7eaf638e1317a9610da68a2e1ce74151ae | 63,389 |
def fast_minor_method(matrix):
"""
Тот же метод миноров, но с предварительной триангуляцией (сокращение до 50% работы метода миноров)
(метод Гаусса) ТОЧНОСТЬ НИЖЕ, ЧЕМ У МЕТОДА МИНОРОВ
Returns:
float: определитель матрицы
Raises:
ArithmeticError: если матрица не является квадратной... | 6300003469381fd23adb8dc808a0b3f79f9caff9 | 63,390 |
def build_versioned_operator_directory(
operators_directory: str, operator_name: str, operator_git_tag: str
) -> str:
"""Returns a versioned operator directory for the "operators collection"
repository.
e.g., /kudobuilder-operators/repository/cassandra/3.11
"""
match = RELEASE_TAG_PATTERN.match... | 6b738bdf5a51c5d82ecf399872fb5160d394148c | 63,391 |
def load_facets():
"""This loads the facets stored in the corresponding file"""
return file_utils.load_dictionary_from_file(config_params.SHODAN_FACETS_FILE) | 1bec48c34f09c554f651ae1e82ea599d3b549013 | 63,392 |
def get_topseller_for_category(category, limit=5):
"""Returns products with the most sales withing given category. Limited by
given limit.
"""
# TODO: Check Django 1.1's aggregation
cache_key = "%s-topseller-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, category.id)
topseller = cache.get(cache_k... | 9259ec795ebdc3a70b42dbaa59c1e4cc460a0e73 | 63,393 |
def Srinit(Srrat,Rbrat,age):
"""
Calculate initial 87Sr/86Sr.
Paramters:
Srrat: Measured 87Sr/86Sr ratio
Rbrat: Measured 87Rb/86Sr ratio
age: Age of sample in Ma
Returns:
Sri: initial 87Sr/86Sr ratio
"""
lambdaRb = 1.39e-11 # Rb-87 decay constant
... | d085413b906e6fed70f4a6fd7fcb3531374a7f14 | 63,394 |
def reduce2scalar( mv, vid=None, gw=True, weights=None, season=seasonsyr, region=None ):
"""averages mv over the full range all axes, to a single scalar.
Uses the averager module for greater capabilities
Latitude weights may be provided as 'gw'. The averager's default is reasonable, however.
If weights... | 1ad0f73435210270620d19be062a28f446385f4b | 63,395 |
from typing import Mapping
def dict_update(orig, updates):
"""Recursively merges two objects"""
for key, val in updates.items():
if isinstance(val, Mapping):
orig[key] = dict_update(orig.get(key, {}), val)
else:
orig[key] = updates[key]
return orig | 0322b0742b4cc725d5935c94adbe11da3ef13d62 | 63,396 |
def request(method, route, status_code=200, content_type='text/html',
data=None, data_content_type=None, follow_redirects=True):
"""
Create the test_client and check status code and content_type.
"""
response = method(route, content_type=data_content_type, data=data,
f... | dd895f9cc4e655153d5bcb5748a94adddb446c81 | 63,397 |
import functools
def file_mock(func):
"""Create pseudo file object."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
content = '\n'.join(f"{i},{i}" for i in range(6))
with mock.patch('lib.image_data.open',
mock.mock_open(read_data=content)) as f_mock:
... | d341d14f728b16029f5e43678861bcb50e3e290e | 63,398 |
async def install_admin_user() -> bool:
"""Retrieve the admin from AUth0 and assign it to the Author."""
api = AuthAPI()
users = api.list_users()
for user in users:
if user.user_id == ADMIN_ID:
await Author.objects.get_or_create(
username="8area8",
ema... | 942e703e22bff537c328f229b7767a21af983265 | 63,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.