content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import skimage.transform
def subdivide_array(shape: tuple[int, ...], count: int) -> np.ndarray:
"""
Create indices for subdivison of an array in a number of blocks.
If 'count' is divisible by the product of 'shape', the amount of cells in each block will be equal.
If 'count' is not divisible, the amo... | 9eb314837f06d67f805894188a96ffb630aad3db | 3,622,000 |
def __hidden(element: Element) -> bool:
"""Element is hidden"""
return element.hidden | ebc9ff1c3e08a84eab9deb8bcad76303b76f7db1 | 3,622,001 |
from typing import List
def average(runs: List[TrecRun], depth: int = None, k: int = None):
"""Perform fusion by averaging on a list of ``TrecRun`` objects.
Parameters
----------
runs : List[TrecRun]
List of ``TrecRun`` objects.
depth : int
Maximum number of results from each inpu... | 69b3f7d9fe092b0ec50d2a840a889f040fb4a9a1 | 3,622,002 |
def rpca(table: biom.Table,
rank: int=3,
min_sample_count: int=500,
min_feature_count: int=10,
iterations: int=5) -> (
skbio.OrdinationResults,
skbio.DistanceMatrix):
""" Runs RPCA with an rclr preprocessing step"""
# filter sample to min depth
def samp... | 91a4d4c1f7a023bf4238c84040d10fbdc3bf1dd5 | 3,622,003 |
def obsweight(obs_id, ra, dec, iq, cc, bg, wv, elev_const, i_wins, band, user_prior, AM, HA, AZ, latitude, prog_comp,
obs_comp, skyiq, skycc, skybg, skywv, winddir, windvel, wra, verbose = False, debug = False):
"""
Calculate observation weights.
Parameters
----------
obs_id : string... | 672d182ac1f60387d2f8f3bbe6627b34f79cd811 | 3,622,004 |
def create_latency_update_runner(
*,
start_after: float = 10,
interval: float = 60 * 5,
target: str = f"http://127.0.0.1:{Config['port']}",
method: str = "GET",
header: dict[str, str] = None,
) -> Thread:
"""
Creates a thread which automatically updates the latency displayed on statuspag... | 1a88ee8470ecaa8e8094b7201c6858bb552aa520 | 3,622,005 |
import os
def check_for_finished_jobs(input_dirs):
""" Checks each experiment directory for a stdout.txt file and a opt_acts_0.npy action file.
Returns a list of experiment directories that are missing either of these.
"""
finished_jobs, failed_jobs = [], []
for exp_dir in input_dirs:
... | fc21d5cb323ad794df5c24798911d6b7b669a213 | 3,622,006 |
def comp_periodicity(self):
"""Compute the periodicity factor of the lamination
Parameters
----------
self : LamSlotWind
A LamSlotWind object
Returns
-------
per_a : int
Number of spatial periodicities of the lamination
is_antiper_a : bool
True if an spatial ant... | 4bc2111ad3f97631bbb12c7c28bfdcf53fba57ac | 3,622,007 |
def _attack(params):
"""
Test the target URL with requests.
Intended for use with multiprocessing.
"""
print 'Bee %i is joining the swarm.' % params['i']
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if params['gnuplot_... | 20464af4036ad13d0f56e0276533bd1c79b99132 | 3,622,008 |
def extract_entity_ids(hass, service):
"""
Helper method to extract a list of entity ids from a service call.
Will convert group entity ids to the entity ids it represents.
"""
entity_ids = []
if service.data and ATTR_ENTITY_ID in service.data:
group = get_component('group')
# ... | f259a29c2c5d4fd88101c3dd66ca97e9d0115bb3 | 3,622,009 |
def submit_batch(batches):
"""Submit transaction batches using default client URL"""
batch_list = create_batch_list(batches)
client = RestClient(sawtooth_rest_host())
return client.send_batches(batch_list) | 77bb9708ee7e5cb50a1206a9cc13d3cd81fddb1d | 3,622,010 |
def tp53():
"""Create a TP53 fixture."""
params = {
'concept_id': 'ensembl:ENSG00000141510',
'symbol': 'TP53',
'label': 'tumor protein p53',
'previous_symbols': [],
'aliases': [],
'xrefs': ['hgnc:11998'],
'symbol_status': None,
'location_annotation... | 94966b192984052f6c446428b60492530528cc21 | 3,622,011 |
from sopel.tests import pytest_plugin
def get_example_test(*args, **kwargs):
"""Get a function that calls ``tested_func`` with fake wrapper and trigger.
.. deprecated:: 7.1
This is now part of the Sopel pytest plugin at
:mod:`sopel.tests.pytest_plugin`.
"""
return pytest_plugin.get_... | d07d5a6ebbeba45a56f41f0b35cc46b35fdb5987 | 3,622,012 |
def _epoch_ctrl(eva=None, stage="game"):
"""
:param eva:
:param stage: must be one of "game", "confirm", "retrain"
:return:
"""
if stage == "game":
cur_epoch = NAS_CONFIG['eva']['search_epoch']
elif stage == "confirm":
cur_epoch = NAS_CONFIG['eva']['confirm_epoch']
elif ... | 67dbde8ada80b20daad66b008faa860d7a58b929 | 3,622,013 |
import sys
def _renamed_class_loader(module_name, class_name):
"""Return a class object for class class_name, loaded from module_name.
The trick here is we look in _CLASS_RENAME_MAP before doing
the loading. So even if the class has moved to a different module
since when this pickled object was crea... | 4d26b649553fc8282f9e78da6c9605c23753fb13 | 3,622,014 |
from typing import Sequence
from typing import Any
def list_namespaced_applications(
kube_client: KubeClient, namespace: str, application_types: Sequence[Any]
) -> Sequence[Application]:
"""
List all applications in the namespace of the types from application_types.
Only applications with complete set... | a6ea1096bf5860b076d6bd0c5bbd49e473addbc9 | 3,622,015 |
def _train_step(model: _FlaxPenguinModel, optimizer: flax.optim.OptimizerDef,
inputs: _InputBatch, labels: _LabelBatch):
"""Train for a single step, given a batch of inputs and labels."""
def loss_fn(params):
logits = model.apply({'params': params}, inputs)
loss = _categorical_cross_entropy... | 10644ee8f4635e26ec060e6a082d1be58c6e0070 | 3,622,016 |
from distributed import Executor
def dsubmit(*a, args=(), kwargs=None, rtn="", **kw):
"""Returns a distributed submission context manager, DSubmitter(),
with a new executor instance.
Parameters
----------
args : Sequence of str, optional
A tuple of argument names for DSubmitter.
kwarg... | 1a767558ef71e8a8ba9406d5b04142b4c7932c97 | 3,622,017 |
import os
def get_folder(cfg, experiment, check = False):
"""Returns the experiment folder. Creates it if necessary."""
folder = get_raw_folder(cfg)
utils.checkFolder(folder)
# add experiment subfolder
folder = os.path.join(folder, get_name('exp', experiment))
if check:
utils.checkFol... | 02bf85f774a4f19ddafa270582ec1e04166f1655 | 3,622,018 |
def isNumber(n):
"""retorna true si 'n' es un numero"""
return all(n[i] in "0123456789" for i in range(len(n))) | 40541c759357fe2706fb453947e55dabab513040 | 3,622,019 |
def import_data():
"""Import data
Parameters
----------
none
Returns
-------
df_listings: DataFrame
df_prices: DataFrame
df: DataFrame
"""
# Import listings data
url_listings = "http://data.insideairbnb.com/italy/emilia-romagna/bologna/2021-12-17/data/listings.... | 3572d6ff5773f4ef14b7af7ee05f5e4c712789d3 | 3,622,020 |
def cmap_to_mayavi(colormap: Colormap) -> np.ndarray:
"""
Convert a matplotlib colormap to mayavi format.
Args:
colormap: A matplotlib colormap object.
Returns:
The equivalent mayavi colormap, as a (255, 4) numpy array.
"""
return (colormap(np.linspace(0, 1, 255)) * 255).astype... | 4e75738d8e5c0d1f8f4c3e36ff5ec93218774c97 | 3,622,021 |
def show_task(project_id):
"""shows the tasks of a project that are stored in the database, given the project_id"""
return render_template("project_tasks.html", project=Project.query.filter_by(project_id=project_id).first(),
tasks=Task.query.filter_by(project_id=project_id).all()) | 41eee9ca596b0a69b3bacf1eaace315cd6a9498c | 3,622,022 |
def get_fig_pv_combined(pv: PV, example_index: int):
"""
Create a combined plot
1. Plot the pv intensity in time
2. Plot the pv intensity with coords and animate in time
"""
traces_pv_intensity_in_time = get_trace_all_pv_systems(
pv=pv, example_index=example_index, center_system=False
... | 96ddbdef52ac5f31b45fde3b7a4eb1f57770dfec | 3,622,023 |
def data_frame_empty_typed(column_types: dict):
"""Creates and empty DataFrame with dtypes for each column given
by the dictionary.
Arguments:
column_types (dict): A key, dtype pairs
Returns:
DataFrame: An empty dataframe with the typed columns
"""
df = pd.DataFrame()
for n... | 879aa4d87719efe59234d7f93651bf717d1ef43d | 3,622,024 |
def are_periodic_neighbors(world_size, a, b):
"""
Given the world size and two ranks, return wether two ranks are periodic
neighbours (i.e. they are in opposite borders of the grid).
"""
nrows, ncols = get_grid_size(world_size)
pos = get_node_pos(world_size, False)
if (ncols > 2) and (pos[a... | 65065bb7edbaad78266ff94efdd638dcf65e297d | 3,622,025 |
def file_content_to_list(file):
"""
Append each line of the file to a theèlist
:param file: The file to transform into a theèlist
:return: The the list
"""
lst = []
with open(file) as file_alias:
for line in file_alias:
lst.append(line)
return lst | cee015f6e7121fc513c8944c61cfd225ee0dcf12 | 3,622,026 |
def ceph_health_check_base(namespace=None):
"""
Exec `ceph health` cmd on tools pod to determine health of cluster.
Args:
namespace (str): Namespace of OCS
(default: config.ENV_DATA['cluster_namespace'])
Raises:
CephHealthException: If the ceph health returned is not HEALTH... | 72ace3629d2eff03c91b030dd4f0ebcb86369f24 | 3,622,027 |
from typing import Sequence
def _hash_layer(layer: Sequence[Hash32]) -> Sequence[Hash32]:
"""Calculate the layer on top of another one."""
return tuple(_calc_parent_hash(left, right) for left, right in partition(2, layer)) | a417addc58a0585c1c5e5757d21983540d4acd10 | 3,622,028 |
import os
def RNN_classification(dataset, filename, save_model=False):
"""
Classification of data with a recurrent neural
network, followed by plotting of ROC and PR curves.
Parameters
---
dataset: the input dataset, containing training and
test split data, and the corresponding labels... | a962b1eff31acf342e65c2fee0a834ee952e959b | 3,622,029 |
def get_sample_names(exprs_fname, start, end):
"""Loads PANDA input expression matrix to extract sample names from TSV.
Args:
exprs_fname (str): PANDA input expression matrix TSV
start (int): start index (1-based inclusive)
end (end): end index (1-based inclusive)
Returns:
... | 3fe86bbdc928be8f490c070c7a28186f2fcf0b13 | 3,622,030 |
def get_users(uid=1, dl=0):
"""Method to get county coordinators emails."""
try:
emails = []
sql = QUERY[uid]
df = run_query(sql)
data = df.values.tolist()
for dt in data:
val = dt[0]
if dl > 0:
val = {dt[0]: dt[1]}
emai... | 1c3440b7f8d45ef0584b5db6d422878fe5fd8bad | 3,622,031 |
def make_function(match):
"""Returns a Function JSON Object"""
return {
'type': 'f', #f for function
'name': match.group('name'),
'return_type': match.group('return_type'),
'parameters': get_parameters(match.group('parameters'))
} | a0fd0d3aaca707852cfc08cdb663317ae2e7b659 | 3,622,032 |
import random
def Decimal_to_Binary(x : str) -> str:
"""
It Converts the Given Decimal Number into Binary Number System of Base `2` and takes input in `str` form
Args:
x `(str)` : It is the Positional Argument by order which stores the Decimal Input from User.
Returns (str): The ... | 8555e0bb983ab30dbfd737f9babfaa67193db620 | 3,622,033 |
import numpy
import sys
def find_blobs(image, mask, border=0, maxblobs=300, maxblobsize=100, minblobsize=0, maxmoment=None, method="central", summary=False):
"""
find blobs with particular features in a map
"""
shape = image.shape
### create copy of mask since it will be modified now
tmpmask = numpy.array(mask... | be9b1e92fc3245489051005819e2adefc19dddaa | 3,622,034 |
def register_and_center_via_speckles(cube_sci, cube_ref=None, AlignmentIterations = 5, gammaval = 1,
min_spat_freq = 0.5, max_spat_freq = 3, fwhm = 8., debug = False , NegFit = True, recenter_median = True, subframesize = 151, imlib='opencv',interpolation='bilinear'):
""" Registers frames based on the median speckl... | 0647c72b075a3845258b5cfe23552c5ce7173633 | 3,622,035 |
import torch
def sample_tv_signal(
n,
j_min=10,
j_max=20,
min_dist=5,
bound=5,
min_height=0.2,
n_seed=None,
t_seed=None,
):
""" Creates a random piecewise constant signal.
Creates a piecewise constant signal of shape (n,) with a random number of
"jumps" (discontinuities).
... | 7a080ba600c3cb706d66f9567cd633c4ee3de77e | 3,622,036 |
def float32_variable_storage_getter(getter, name, shape=None, dtype=None,
initializer=None, regularizer=None,
trainable=True, *args, **kwargs):
"""Custom variable getter that forces trainable variables to be stored in
float32 precision a... | db004fa14d6e7f7b898c2ca29f62138c59976dd2 | 3,622,037 |
def _squad_em(pred_data, ref_data):
"""EM score for reading comprehension task"""
em_score = eval_exact_match_score(pred_data, ref_data)
return em_score | ce5b77bf88692a2e3aebd01c6e35e4924f372a6e | 3,622,038 |
def add_slash(text: str):
"""returns the same text with slash at the end"""
return text + '/' | a87c204dfc163f5ee814fbda92ad7a8368346893 | 3,622,039 |
from typing import Tuple
def parse_response(text: str) -> Tuple[bool, str]:
"""
Parses a CommCare HQ Submission API response.
Returns (True, success_message) on success, or (False,
failure_message) on failure.
>>> text = '''
... <OpenRosaResponse xmlns="http://openrosa.org/http/response">
... | afdfc6479323d38c13f45a25b40246ea286633d0 | 3,622,040 |
def launch(context, service_id, subscription, every=EVERY):
""" Initialize the module. """
return MeasRepUe(context=context, service_id=service_id, every=every,
subscription=subscription) | f5954d6fa62d640898ca95ad7df3e85b41a2bb8d | 3,622,041 |
import re
def __detect_str_type(data) -> str:
"""
:column_type str
:rtype str
"""
r = re.search("[^=]+=[^&]*&*", data) # application/x-www-form-urlencoded pattern
if r:
return "application/x-www-form-urlencoded"
else:
return "plain/text" | 6dda59aa570070538b54738b83fc69ba129637f0 | 3,622,042 |
def iterable(x):
"""Check if the input is iterable, stolen from numpy.iterable()"""
try:
iter(x)
return True
except:
return False | edd9f4cc369c0f53470d7323aacfccbd32b0e4d7 | 3,622,043 |
def conv2d_input_grad_wrap(input_size, weight, grad_output, stride, padding,
dilation, groups):
"""Wrap of conv2d_input_grad for pytorch."""
input_size = tuple(i.item() for i in input_size)
stride = tuple(_x.item() for _x in stride)
padding = tuple(_x.item() for _x in padding)... | 5ce20be791e6a7be52be377a85636c087013b05e | 3,622,044 |
def sort_key(entry):
"""Get the value for a key"""
return entry[ds] | 932003d76e959adba187df7f7c6b7f0517d3e779 | 3,622,045 |
def estimation_error_rate(y_true, y_pred):
"""
Compute estimation error rate score
Estimation error rate represents the mean absolute error computed between true
and predicted labels, expressed as a percentage, i.e. mae / range(y_true). It
is defined as follows:
eer = mae / range(y_true)
m... | d5a2927f785b8a90e1d91daab6a540d622a7e3a3 | 3,622,046 |
def ldns_resolver_new_frm_fp(*args):
"""LDNS buffer."""
return _ldns.ldns_resolver_new_frm_fp(*args) | 03e47cb19506e9ec6a0121db2c737ba7c6a66204 | 3,622,047 |
from typing import Tuple
from typing import List
import asyncio
from pathlib import Path
async def _populate_downloads(executor, dataset: Dataset,
destination: str, prefix: str, recursive: bool) -> Tuple[List[ObjectState], int]:
"""function to concurrently check if the list of files ... | 68189ba19b051316c7bcb50c8b669f3573a1f073 | 3,622,048 |
def requires_roles(roles):
"""
Assert the user has one of the required roles.
:param list roles: the list of role names to verify
:raises freshmaker.errors.Forbidden: if the user is not in the role
"""
def wrapper(f):
@wraps(f)
def wrapped(*args, **kwargs):
if any(us... | a7a5471bfc038b79d9930ac6c1f07f3d318ac59a | 3,622,049 |
import random
def cull_gammas(x, y, mRNA_to_miRNA: np.ndarray) -> np.ndarray:
"""
Removes gammas (sets them to 0) in such a way that the network remains connected. Currently very hacky: uses
DFS to ensure connectivity. Would work better using a min-cut algorithm.
"""
legal = False
while not le... | 69de118949537dc15f490fdd4174b283628ff3a5 | 3,622,050 |
def primality_test(n: PositiveInt) -> bool:
"""Determine whether a number is a prime."""
# Optimization 1: Test from 2 to sqrt(n) only, since a factor will appear twice when we test from 2 to n.
# Optimization 2: Do not test even numbers except 2, since all even numbers is divisible by 2.
# Optimizati... | f49b8caffc7d462111337a7c1251c965467e192e | 3,622,051 |
import requests
import os
import urllib
import cgi
import tempfile
def download_data(urls):
"""Download the binaries from a URL and return the destination filename
Retry downloading if either server or connection errors occur on a SSL
connection
urls: list of several urls (mirror servers) or single u... | 975e86036efb5fba0bb9d7e5ae87647353690c58 | 3,622,052 |
def diffusion_coeff(t, sigma):
"""Compute the diffusion coefficient of our SDE.
Args:
t: A vector of time steps.
sigma: The $\sigma$ in our SDE.
Returns:
The vector of diffusion coefficients.
"""
return sigma**t | e0b1e1c76f7773a85562adb327c18863c715917a | 3,622,053 |
def get_step_chart(simulation_objects):
"""Get the step chart of the container levels."""
fig = plt.figure(figsize=(14, 7))
for obj in simulation_objects:
df = get_log_dataframe(obj)
container_list = obj.container.container_list
for container in container_list:
if hasatt... | 5acbf66c67214a97b4c40bcb9ebe692df86afd40 | 3,622,054 |
def byte_xor(b: bytes, i: int) -> bytes:
"""
Calculate 'b XOR i'
"""
return int(bytes_to_int(b) ^ i).to_bytes(len(b), 'big') | 3341137ca93bb2c3262579a446a3874cc04c87cc | 3,622,055 |
def get_file_name(f_size):
"""
Returns file name whose filesize correstponds with the files size passed in as parameter.
"""
for x,(z,y) in movie_dict.items():
if z == f_size :
return x | 589255cb011113eebf52312e9c2bb1d4d3baf9a2 | 3,622,056 |
from typing import OrderedDict
def get_form_errors(form):
"""
Django form errors do not obey natural field order,
this template tag returns non-field and field-specific errors
:param form: the form instance
"""
return {
'non_field': form.non_field_errors(),
'field_specific': Or... | 056597492d24dc406c9d952f5cb56c14d0a75fff | 3,622,057 |
def query_db(db, query, args=(), one=False):
"""
Queries the database and returns a list of dictionaries.
https://flask-doc.readthedocs.org/en/latest/patterns/sqlite3.html#easy-querying
"""
with db.cursor() as cur:
logger.debug(f"Query: {query}")
cur.execute(query, args)
rv ... | a85950c47a527bb94058f6c8dcb27e534cf03dd4 | 3,622,058 |
def is_valid_url(url: str) -> bool:
"""Evaluate whether or not a URL is acceptible for retrieval."""
return current_session().is_valid_url(url) | bcb8517ce5ed613bebef5753e3dad13fcf2f7447 | 3,622,059 |
def plot_poly(x,y,degree, *args):
""" Plot the data with given degree of polynomial.
Example:
plot_poly(x,y,3)
plot_poly(x,y,3,'x','y','title')
Returns: p
Usage:
x_value = 100
p(x_value) gives the polynomial fit of x_value
"""
plt.figure(figsize=(12,8))
pl... | ba39412dd401e7321adceca665baf8f23a2833ed | 3,622,060 |
import json
import logging
def get_kube_res_by_name(namespace, kube_res, res_name):
"""
A Wrapper of kubectl which parses resources from json
:param res_name: The name of the resource
:type res_name: str
:param namespace:
:type namespace: str
:param kube_res: statefullset, deployment ...
... | 033832910ac0ee7a7406aea8353abe0d7a551f66 | 3,622,061 |
import torch
import logging
def __graph_initialization(module: MaxPooling, x: torch.Tensor, pos: torch.Tensor, edge_index: Adj = None) -> Data:
"""Graph initialization for asynchronous update.
Both the input as well as the output graph have to be stored, in order to avoid repeated computation. The
input ... | 3806a6d6aeb698141d100240d347cd80aaf70224 | 3,622,062 |
def comment_exists_in_blogpost(func):
"""Checks to make sure the comment exists or renders a 404"""
def wrapper(self, blog_id, comment_id, *args, **kwargs):
blog_post = BlogPost.get_by_id(int(blog_id), parent=BLOG_KEY)
int_comment_id = int(comment_id)
comment = Comment.get_by_id(int_comm... | 5c5c9e3c003d0ed12c11b4b65ef0fdd1fcba468a | 3,622,063 |
import torch
def log_sum_exp(tensor, dim=-1):
""" Safe log-sum-exp operation """
return torch.logsumexp(tensor, dim) | 5b6154be4c12576941f7e8d97a26296149982e1b | 3,622,064 |
from typing import List
from typing import Dict
def get_vrf_group(files_list: List[str]) -> Dict[str, List[str]]:
"""
Group files by VRF name.
"""
groups = {}
for filename_path in files_list:
filename_path = filename_path.replace("\\", "/")
# print(filename_path)
if "show" i... | 348f1c10f4bd054ca2f45f36b5420a971b52e4cf | 3,622,065 |
def get_legislator_political_positions_by_slug(slug):
"""
Get just this legislator's political positions
https://github.com/INN/maine-legislature/issues/82
"""
copy = get_copy()
political_positions = {}
leg_id = get_legislator_id_by_slug(slug)
for row in copy['position_political']:
... | e6ea3e7efa63bf5424f0eb4ec293f10fb7a96b4d | 3,622,066 |
def config_bgp_neighbor_properties(dut, local_asn, neighbor_ip, family=None, mode=None, **kwargs):
"""
:param dut:
:param local_asn:
:param neighbor_ip:
:param family:
:param mode:
:param kwargs:
:return:
"""
st.log("Configuring the BGP neighbor properties ..")
properties = ... | 8d36549020ec14533bb28424076c00b7859e5795 | 3,622,067 |
def scr_total(
bscr,
scr_op
):
""" This function simply adds the SCR_Op to the BSCR """
return bscr + scr_op | 7d1711f75abae59b79cf62f6e64daeb7e4c556eb | 3,622,068 |
def _eval_bernstein_dd(x, fvals):
"""Evaluate d-dimensional bernstein polynomial given grid of valuesv
experimental
Parameters
----------
x : array_like
Values at which to evaluate the Bernstein polynomial.
fvals : ndarray
Grid values of coefficients for Bernstein polynomial ba... | c28efdbe8772f6acad83f45de7d33447d7437cee | 3,622,069 |
import re
import six
def load_tff_dat(fname, processor=None):
"""Read a tff.dat or dff.dat files generated by tff command
Parameters
----------
fname : file or str
File, or filename
processor: callable or None
A final output processor, by default a tuple of tuples is returned
... | 55f9ba3915c2d31cb83b8ea26de996f8f29e5e43 | 3,622,070 |
from typing import List
def is_luhn(string: str) -> bool:
"""
Perform Luhn validation on input string
Algorithm:
* Double every other digit starting from 2nd last digit.
* Subtract 9 if number is greater than 9.
* Sum the numbers
*
>>> test_cases = [79927398710, 79927398711, 7992739871... | 92253489a18efc902198d5eb3fb93a06a74a3246 | 3,622,071 |
import os
from datetime import datetime
import tempfile
def create(type_id='', path=''):
"""Create a document or directory"""
if g.level < 2:
return abort(401)
inherited_level = 1
type_item=None
path = path[:-1] if path.endswith('/') else path
if type_id:
type_item = mongo.db.... | 05ea674984a9a79f7c5f983b6a0ebd1075130b66 | 3,622,072 |
from typing import Optional
def latest_date_for_day(
start_date: datetime_.date, end_date: datetime_.date, day_of_month: int
) -> Optional[datetime_.date]:
"""
Given an integer day of a month, return the latest date with that day of the month,
bounded by the supplied start_date and end_date. If no suc... | 38a6dee698fd41083acadec6ac7cefc1a8217368 | 3,622,073 |
import sqlite3
def handle_artist(command):
"""
Process the artist command
"""
conn = sqlite3.connect('myjazzalbums.sqlite')
cur = conn.cursor()
if command [-1] == "?":
artist_name = command[6:-1].strip().title()
else:
artist_name = command[6:].strip().title()
if ar... | 4395b4d3a25f3ea5e10accd938a51df342913e17 | 3,622,074 |
def generate_lda_distance(df, model, dictionary):
"""
计算 LDA 主题模型距离
"""
def compute_topic_distances(row):
q1_bow = dictionary.doc2bow(row['cleaned_question1'].split())
q2_bow = dictionary.doc2bow(row['cleaned_question2'].split())
q1_topic_vec = np.array(model.get_document_topics... | f653b557d846bad1c36b0ac85926cb05050d4793 | 3,622,075 |
def build_get_request(base, service_name, operation_name=None, params=None):
"""
Builds a get request out of a service/operation and optional params.
operation_name may be left blank if going to a custom url.
"""
urlarr = [base, service_name]
if operation_name is not None:
urlarr.append(... | e2afb6c40f08fca3a38b54ab36b996533e7f2c8e | 3,622,076 |
import tempfile
import os
import subprocess
import shutil
def rsys2graph(rsys, fname, output_dir=None, prog=None, save=False, **kwargs):
"""
Convenience function to call `rsys2dot` and write output to file
and render the graph
Parameters
----------
rsys : ReactionSystem
fname : str
... | 07d72bfec89301110599cf224f6bb666fabe5ec2 | 3,622,077 |
import os
def upload_file(target_filepath, metadata, access_token, datatypes=None,
base_url=OH_BASE_URL, remote_file_info=None,
project_member_id=None, max_bytes=MAX_FILE_DEFAULT):
"""
Upload a file from a local filepath using the "direct upload" API.
To learn more about th... | 2ce43c0737d7ddde6f74acd86eb340fd9bf32429 | 3,622,078 |
def dense(n_prev, n, *, activation="relu"):
"""Creates a dense, fully-connected layer.
Args:
n_prev: number of inputs from the previous layer
n: number of nodes for this layer
activation: activation function for this layer,
one of {sigmoid, tanh, relu}
"""
unit = _nn... | c29365310b2df9913d61702d515a3aa7189b1456 | 3,622,079 |
from typing import Tuple
import json
def load_poses(pose_path: str, skip_params: bool) -> Tuple[tf.Tensor, tf.Tensor, float]:
"""Loads poses from file."""
with open(pose_path) as pose_file:
pose_dict = json.load(pose_file)
poses = []
parameters = []
for pose in pose_dict['frames']:
... | 8529e181cec4cc04f6b6d4fe3517ad0ba01e1b4c | 3,622,080 |
import glob
def patternMatch(pattern, dir='./'):
"""
:pattern: A file pattern to match the desired output. Input to a glob, so use traditional unix wildcarding.
:dir: The directory to search.
:returns: list of matching files in the target directory
"""
files = []
files = glob.glob(dir+pa... | d5e9b1d531cdfa3ebca3baea2b8e273621df3357 | 3,622,081 |
def add_histogram_summary(tensor, name=None, prefix=None):
"""Adds a histogram summary for the given tensor.
Args:
tensor: A variable or op tensor.
name: The optional name for the summary.
prefix: An optional prefix for the summary names.
Returns:
A scalar `Tensor` of type `string` whose content... | 6ca0ee04fa1e35d030f38a4d969d2b992341674f | 3,622,082 |
def tasks_page():
""" Tasks and completions page: tasks.html
"""
project = project_get_or_create()
label_config = open(project.config['label_config']).read() # load editor config from XML
task_ids = project.get_tasks().keys()
completed_at = project.get_completed_at(task_ids)
num_workers= ... | 7a857c0eea1f7b5e5b931761251ff64a098d8a1e | 3,622,083 |
def cors_middleware(
*,
allow_all: bool = False,
origins: UrlCollection = None,
urls: UrlCollection = None,
expose_headers: StrCollection = None,
allow_headers: StrCollection = DEFAULT_ALLOW_HEADERS,
allow_methods: StrCollection = DEFAULT_ALLOW_METHODS,
allow_credentials: bool = False,
... | bb8bd0ce8e2b766e557277cbd90c7769b8387256 | 3,622,084 |
def trim_matrix(mat, i):
"""
Trims a matrix by deleting both a row and a column in a matrix (warning: inefficient)
:param mat: matrix
:param i: row index
:return:
"""
mat = mat.copy()
mat = mat.tocsr()
delete_row_csr(mat, i)
mat = mat.transpose()
mat = mat.tocsr()
delete... | 16806bbde767f709786a15dc06d0f84de2191d27 | 3,622,085 |
def removeBottomMargin(image, padding):
"""Remove the bottom margin of width = padding from an image
Args:
image (PIL.Image.Image): A PIL Image
padding (int): The padding in pixels
Returns:
PIL.Image.Image: A PIL Image
"""
return image.crop((0, 0, image.width, image.height - padding)) | 69cd12d6c3ed0b857bae3f42c34e9754fa3620f3 | 3,622,086 |
def num(val):
"""Return val as an int, float, or bool, depending on what it most
closely resembles."""
if isinstance(val, (float, int)):
return val
elif val in ('True', 'False'):
return val == 'True'
elif isinstance(val, str):
try:
return int(val)
except ... | 552219ed6e97013c0b367542f68ae2e5e9f98300 | 3,622,087 |
def get_alerts_request(has_share_mode=None, resolution=None, agent_id=None, host_name=None,
condition_id=None, limit=None, offset=None, sort=None, min_id=None,
event_at=None, alert_id=None, matched_at=None, reported_at=None, source=None):
"""
returns the response ... | 3eeba32fe59d7450b6a5cd0a099c04f1f0ca81db | 3,622,088 |
def log2_graph(x):
"""Log2'nin Uygulanması. TF'nin yerel bir uygulaması yoktur."""
return tf.log(x) / tf.log(2.0) | f56107fadd0c880f351523d22c869fc16e90b3c5 | 3,622,089 |
import os
import json
import time
from datetime import datetime
def train_cnn():
"""Step 0: load sentences, labels, and training parameters"""
create_test = params["create_test"]
# load train, cat and and other path configurations from parameter file
train_file = params['train_file']
# cat_file ... | 89dabebdf6b04d897d2efba79229d840e9542548 | 3,622,090 |
def readUniformElementTopologyFromXdmf(elementTopologyName,Topology,hdf5,topologyid2name,topology2nodes):
"""
Read xmdf element topology information when there are uniform elements in the mesh
Type of element given by elementTopologyName
Heavy data stored in hdf5
topologyid2name -- lookup for number... | 39c99a9ab46c47aac0fdecf88cbd2d1bba0f8281 | 3,622,091 |
def ranknode(
data, out_path, entry_point, node_num, topk_path=60, prob_thres=0.4, num_sel_node=1
):
"""Rank node according to pearson correlation
"""
# region select X nodes from path
path_node_count = defaultdict(int)
# select only first topk paths with prob >= threshold
for i in out_path[... | 2f6020c7e36c9078a7d80b83fc6800ef56944e28 | 3,622,092 |
def fib(id):
"""
id: index (zero-based)
returns: Fibonacci number for the given index
id: 0 1 2 3 4 5 6 7
Fib: 0 1 1 2 3 5 8 13
"""
if id < 0:
return 0
if id == 0:
return 0
if id == 1:
return 1
first = 0
second = 1
counter = 2
fib_num = 0... | fc5c58c364417cdfd6c5276da644d259258af613 | 3,622,093 |
def montecarlo_coupled(model,T,func,delta,voxel,ode_method,sample_rate,
min_samples,max_samples,output_file):
""" Obtains statistics of model using a coupled monte carlo esimator. """
M0 = 10
Mmax = 10e5
samples = np.zeros((Mmax,model.dimension))
event_count = 0.
standdev = np.zeros(Mmax... | 9d696f5c4b7956a8c62f8528f070e4feebba061a | 3,622,094 |
def plot_trajectory_by_hour(
move_data,
start_hour,
end_hour,
id_=None,
legend=True,
n_rows=None,
lat_origin=None,
lon_origin=None,
zoom_start=12,
base_map=None,
tile=TILES[0],
save_as_html=False,
color="black",
filename="plot_trajectory_by_hour.html",
):
"""
... | 4342e6af550a9743292db90fef8f860262d71064 | 3,622,095 |
def adaptive_approximate_multi_index_sparse_grid(fun, variable, options):
"""
A light weight wrapper for building multi-index approximations.
Some checks are made to ensure certain required options have been provided.
See :func:`pyapprox.approximate.adaptive_approximate_sparse_grid` for more
detail... | 241c19a6ab5f23e40c2b8dd33baf11e6f6dfbfe0 | 3,622,096 |
def conv_from_weights(x, weights, bias=None, padding=True, name=""):
""" weights is a numpy array """
k = C.parameter(shape=weights.shape, init=weights)
y = C.convolution(k, x, auto_padding=[False, padding, padding])
if bias:
b = C.parameter(shape=bias.shape, init=bias)
y = y + bias
... | cfdf2f3c2999d5cdf6141b17a0b4eef31b1adf98 | 3,622,097 |
def GenerateOutputList(context, resource_list):
"""Returns list of outputs generated by this module."""
vm_res = resource_list[0]
outputs = [{
'name': 'internalIP',
'value': '$(ref.%s.networkInterfaces[0].networkIP)' % vm_res['name'],
}]
external_ips = context.properties.get(EXTERNAL_IPS, [])
if... | bcec45fd25b5f20ede22937a03f2f46ca865311c | 3,622,098 |
def execute_job(request):
"""
执行磁盘容量查询作业
"""
biz_id = request.POST.get('biz_id')
ip = request.POST.get('ip')
job_id = request.POST.get('job_id')
# 调用作业平台API,或者作业执行实例ID
client = get_client_by_request(request)
# client.set_bk_api_ver('v2')
result, job_instance_id = get_job_instan... | 85c8e91f9dca8f8f40dd2b1ff7be955b39a7a8db | 3,622,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.