content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import requests
def get_resource_from_manager(resource_path,
base_url=None,
base_urls=None):
"""Get resource from the manager file server.
:param resource_path: path to resource on the file server
:param base_url: The base URL to manager file se... | 72fdd1ede9c0182f02d4ea4621831777a43ff797 | 66,791 |
def reindex_like(self, other, **kwargs):
""" reindex_like : re-index like another dimarray / axes instance
Applies reindex_axis on each axis to match another DimArray
Parameters
----------
other : DimArray or Axes instance
**kwargs :
Returns
-------
DimArray
Notes
-----
... | 16dceb6dadf4b7ce6b8d6311b26c773fd15b1588 | 66,792 |
def create_plotly_blob(data_list, xlabel, ylabel, title):
"""
Create plotly line plot object, useful for jupyter plots or generation of interactive html plots
E.G.
import plotly.graph_objects as go
blob = create_plotly_blob([(xdata1, ydata1, label1, True), (xdata2, ydata2, label2, False)], 'x', ... | a19ece2ba0a1fc6a1db6a167b266d1b3099927c1 | 66,793 |
import socket
def get_internal_ipv4_address(host="8.8.8.8", port=80) -> IPv4Address | None:
"""Find local IPv4 address."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect((host, port))
ip_address = IPv4Address(s.getsockname()[0])
except Exception as e:
base_... | a18c5959ada6bb506f2af57b8d8ed2924df6df1e | 66,794 |
from bolero.optimizer import fmin
def fmin_cma(objective_function, x0, xL, xU, sigma0=0.01, maxfun=1000):
""" Minimize objective function in hypercube using CMA-ES.
This function optimizes an objective function in a search space bounded by
a hypercube. One corner of the hypercube is given by xL and the o... | 1dce18400c3f784ae544d7c8d8bd9b55a215aaf7 | 66,795 |
from typing import Any
def get_init_value(attr: XmlAttr, node_globals: InheritedDict) -> Any:
"""Evaluates attribute value and returns it"""
stripped_value = attr.value.strip() if attr.value else ''
if is_expression(stripped_value):
body = parse_expression(stripped_value)[1]
parameters = n... | ed7247af31b5a5d4d3f15746a6287471cf8c4188 | 66,796 |
def set_bmc_use_attack_path_axioms(ctx, engine, source, target):
"""
set_bmc_use_attack_path_axioms(Int_ctx ctx, Int_engine_bmc engine, Int_net source, Int_net target)
Parameters
----------
ctx: Int_ctx
engine: Int_engine_bmc
source: Int_net
target: Int_net
"""
return _api.set_... | 13e456bcc536920a26be3e7f344972353f42d5c3 | 66,797 |
def not_found_error(error):
"""
404 error route
:param error: error description
:return: redirect to page route for 404
"""
return page('excludes/404'), 404 | 0874682a09fc1cba4ca217358d8f8049b50f2a16 | 66,798 |
def commit(request):
"""See connection.Datastore.commit."""
return get_default_connection().commit(request) | 364532b6c96348d9e050710fb25d92d809aa7fb2 | 66,800 |
def pareto_rank_NSGA2(costs):
"""Algorithm from the NSGA-II paper."""
n_costs, n_objectives = costs.shape
dominated_by = [set() for i in range(n_costs)]
domination_counter = np.zeros(n_costs, dtype=np.int_)
ranks = np.zeros(n_costs, dtype=np.int_)
domination_counter2 = np.zeros(n_costs, dtype... | 4d015dded9e5c94403cc65e3545b8d170888f778 | 66,801 |
import json
def _GetPatchsetRevision(patchset, change_details):
"""Gets the corresponding revision of a given patchset.
Args:
patchset (int): The patchset number.
change_details (dict): The format conforms to the ChangeInfo object:
https://gerrit-review.googlesource.com/Documen... | e7dcb2612c95a2eb7deee68a1506381a00929904 | 66,802 |
def mult_intersection(sfg_list, sim_name_list):
"""
Return the intersection of graphs contained in sfg_list. sim_name_list
contains list of similar strings. Each string at index i corresponds to
the graph at index i of sfg_list
"""
res = sfg_list[0]
index = 1
while index < len(sfg_list):... | 65b2c0e40ac0750e5f691942d2b6a7bbce94979c | 66,803 |
def mll_helper(objective, dataloaders, epoch, agg):
"""Estimate marginal log likelihoods."""
# First estimate MLL on the validation set.
tic = perf_counter()
mll = estimate_marginal_log_like(objective, dataloaders['valid'])
toc = perf_counter()
agg['valid_mll'].append(mll)
agg['valid_mll_epoch'].append(epoch)
p... | 2345eabe4d94b8156843017cabfb5a14815b2be2 | 66,804 |
def markov_forward(p0, A):
"""Calculate the forward predictive distribution in a discrete Markov chain
Args:
p0 (numpy vector): a discrete probability vector
A (numpy matrix): the transition matrix, A[i,j] means the probability to
switch FROM i TO j
Returns:
p1 (numpy vector): ... | 818c3ddf11baf83690e8d0e5b3481f867b6d3645 | 66,806 |
def getDrowAnnotationLine(ann):
""" levels: 0: eye state (right)
1: eye state(left) """
bodyAnnId = ann[0]
a1Ann = 0
if bodyAnnId == 0: # open
a1Ann = 0
elif bodyAnnId == 1: # close
a1Ann =1
elif bodyAnnId == 2: # opening
a1Ann= 2
elif bodyAnnId == 3: # cl... | 3403bd63f3fa16aad4f713edb16954fbd1d7e20a | 66,808 |
def select_angular_grid(lebedev_order):
"""find closest Lebedev grid of requested order"""
n_lebedev = abs(np.array(Lebedev_Lmax) - lebedev_order).argmin()
Lmax = Lebedev_Lmax[n_lebedev]
if lebedev_order != Lmax:
print( "No grid for order %s, using grid which integrates up to Lmax = %s exactly i... | 9bc645a56a39cfb23586a3640667be49cf46548f | 66,809 |
from typing import Sequence
from typing import Union
from typing import Tuple
from typing import Optional
def send_email( # noqa
recipients: Sequence[Union[str, Tuple[str, str]]],
subject: str,
text: str = "",
html: str = "",
sender: Union[str, Tuple[str, str]] = "",
files: Optional[Sequence[... | 95a3e653fa6d35661ac3e17e504cf3c8a7eddbe2 | 66,810 |
def api_get_threads(board_id):
"""Returns a list of threads"""
# parse args
arg_limit = request.args.get('limit', default=10, type=int)
arg_offset = request.args.get('offset', default=0, type=int)
# validate args
if arg_limit <= 0 or arg_limit > config['MAX_THREADS_PER_PAGE']:
arg_limit = config['MAX_... | fddb714f329c051ca5d6ba6fe46baf6e29a379db | 66,811 |
from bigflow import schema_pcollection
def _ret_dict_handler(ret_dict, record_val):
""" 内部函数 """
inter_type_keys = []
inter_type_values = []
inter_type_flag = False
ptype_keys = []
ptype_values = []
ptype_flag = False
for key, value in ret_dict.items():
if isinstance(value, pt... | e3a6139eceee2b389b3d2e63f2d1ae504dec8ba1 | 66,812 |
import io
def usgs_ma_call(*, resp, year, **_):
"""
Convert response for calling url to pandas dataframe, begin parsing df
into FBA format
:param url: string, url
:param resp: df, response from url call
:param args: dictionary, arguments specified when running
flowbyactivity.py ('year'... | e546500906c44b42e1bb5e87abe792fa741be6dc | 66,813 |
def make_collision_events(sorting, delta):
"""
Similar to count_matching_events but get index instead of counting.
Used for collision detection
Parameters
----------
sorting: SortingExtractor
The sorting extractor object for counting collision events
delta: int
Numb... | 7ed149a0c7b60d6b8539612ea376260278109fb7 | 66,814 |
def bookOOF():
"""Book OOF day"""
# check if POST used
if request.method == "POST":
# store OOF details in variables
startDate = request.form.get("startDate")
endDate = request.form.get("endDate")
halfDay = request.form.get("halfDay")
oofType = request.form.get("oofT... | a7c32cf9db2a3349375f07e4afb42b68031b17fe | 66,816 |
def get_movie_title(movie_id):
"""
Author: Alexander Dahl
Date: 2017-11-01
Last update: 2017-11-13
Purpose: returns the movie title from a movie id input
:param movie_id:
:return: movie name as string
"""
return RetrieveMovie().retrieve_movie(movie_id).title | 68949d4e06d1610a4305bcf2da62d480e2d7c1c3 | 66,817 |
def get_indices_of_A_in_B(A, B):
"""Return the set of indices into B of the elements in A that occur in B
Parameters
----------
A : list
The "needles"
B : list
The "haystack"
Returns
-------
list
Indices into B of elements in A occuring in B
"""
s = s... | 88948acd14d7979f7e5ce067776c847e1d0b2a24 | 66,818 |
def evaluate_arithmetic_expression(expression):
"""
Evaluate an arithmetic expression using Dijkstra's two stack algorithm.
The function assumes that each subexpression is enclosed in parenthesis.
e.g. ( 1 + ( 2 * ( 3 / 7 ) ) )
It is also assumed that at least one operator and two operands are pr... | c8f994cb7d73828202084e7eec084a9b061461fe | 66,819 |
def load_proposal_roidb(dataset_name, image_set_name, root_path, dataset_path, result_path=None,
proposal='rpn', append_gt=True, flip=False):
""" load proposal roidb (append_gt when training) """
imdb = eval(dataset_name)(image_set_name, root_path, dataset_path, result_path)
gt_roid... | 8b7bd2de4562736bb7cc451d5351b876b21cdc00 | 66,820 |
from typing import Type
from typing import Callable
from typing import Iterable
from re import T
from typing import AsyncGenerator
def catch(
exc_type: Type[TException], handler: Callable[[TException], Iterable[T]]
) -> StreamGenerator[T, T]:
"""
Catches any raised exception that is an instance of the giv... | e39773e0cdb3edefc8872670748f71799e8d9aa6 | 66,821 |
def cvp_from_torch_fn():
"""Create CVPConv2d from Conv2d."""
torch_layer = torch_fn()
return CVPConv2d.from_torch(torch_layer) | 6467b6f30281c238bb83e233d5a4427a653233b3 | 66,822 |
def format_md(text: str) -> str:
"""
Format MarkDown with mdformat.
"""
return mdformat.text(
text,
options={
"wrap": 79,
},
) | 697e6e201452895fbc9865c991f0dc3281fc74b9 | 66,823 |
def stable_non_blocking_container_selector(available_containers,
box,
packer=None,
packed_boxes=None,
all_boxes=None, **kwargs):
"""
Selects... | b6a300226317e3409e079c2ed551a54d42c8e9dd | 66,824 |
def size_str(size):
"""
size: number of bytes
Return a human-readable string.
"""
if size is None:
return None
for unit in ('', 'k', 'm', 'g', 't'):
if size < 100 and size != int(size):
return '%.1f%s' % (size, unit)
if size < 1024:
return '%d%s' ... | f90e5196c21a8ce0f179043cf1cc16171da62bd0 | 66,825 |
def chord_symbol_root(chord):
"""
Return the midi pitch associated to the chord root.
Args:
chord (str or ChordalPy.Chord): a representation of a chord symbol for
which the root is extracted. It can be either a string or a
ChordalPy.Chord instance if the chord has already b... | 8fb7a59183a2e261771b65ad26a3228e25b492f9 | 66,826 |
def get_instructions(content_tree, namespaces):
"""find all text links that have a py3o
"""
xpath_expr = "//text:a[starts-with(@xlink:href, 'py3o://')]"
return content_tree.xpath(
xpath_expr,
namespaces=namespaces
) | c527cf9bb4b97ac3207ee2cf5ed9ffb3febdf7ab | 66,827 |
def _proto_lens_fields_file(path):
"""The fields file from `proto-lens-protoc` when run on the given `path`.
"""
path = path[:-len(".proto")]
result = "/".join([_camel_case(p) for p in path.split("/")]) + "_Fields.hs"
return "Proto/" + result | 5dfed1ffa96535efccd739afe03cbf279ec1476a | 66,828 |
def api_instances(request):
"""Test utility."""
auth = get_auth(request)
obj = Instances(auth=auth)
check_apiobj(authobj=auth, apiobj=obj)
return obj | ed53e6c8cbdafaabe3be6b99c555b38725e6100d | 66,829 |
import torch
def sample_px_locations_uniformly(
batch_domain_indices: torch.Tensor,
unique_domain_idxs: np.ndarray,
w: int,
h: int,
initial_sample_num: int
):
"""
We are given a list of which batch examples belong to which domains.
We first sample an array of uniformly r... | 22afd0d992b9b8c880c8ccb127e9022e50e4142c | 66,830 |
from astropy.convolution import Box1DKernel
def write_vmax(cubein,
outfile=None,
errorfile=None,
rms=None,
channel_correlation=None,
overwrite=True,
unit=None,
window=None,
return_products=True):
... | f822b0958b0f302cbf69c7dabceadef610ac5842 | 66,831 |
def harmonic_frequencies(freqs):
""" write harmonic frequencies (cm^-1) to a string (cm^-1)
"""
assert list(freqs) == sorted(freqs)
return _frequencies(freqs) | 3203854aace5c37b3866b641a5f6b3d95f708887 | 66,832 |
def _attach(name):
"""
:param name: name of cluster
:type name: str
:rtype: None
"""
c = cluster.get_cluster(name)
if not c:
raise DCOSException("Cluster [{}] does not exist".format(name))
if c.get_status() == cluster.STATUS_UNCONFIGURED:
return setup(c.get_url(), provi... | 06c9282addbf84fb0d8005c71483e98946e77c66 | 66,833 |
def get_ce_alexnet():
"""Returns Corruption Error values for AlexNet"""
ce_alexnet = dict()
ce_alexnet['Gaussian Noise'] = 0.886428
ce_alexnet['Shot Noise'] = 0.894468
ce_alexnet['Impulse Noise'] = 0.922640
ce_alexnet['Defocus Blur'] = 0.819880
ce_alexnet['Glass Blur'] = 0.826268
ce_ale... | e23f902cafb45eeeca9009971c143d00095617c8 | 66,834 |
import torch
def ridge_one_hot_encoding(s, length, vocab=vocab):
"""one hot encodes seqs for ridge regression"""
#ll_train = list(ds)
#seq = [i[0] for i in all_train]
#target = [i[1] for i in all_train]
#tokenizer = Tokenizer(vocab) # tokenize
#s = [torch.tensor(tokenizer.tokenize(i)).view(-1... | 607e4ca4a615fa71a500e230a76be908948ef915 | 66,835 |
def step_rmd(model, decoder, reconstructor, xs, ys,
optimizer,
l_rec_coeff=1.0,
l1_coeff=0.0):
"""One optimization step."""
# xs - observations + actions
# ys - next observations
# converting dtype
xs = np.array(xs, dtype=np.float32)
ys = np.array(ys, dtype=np.float32... | 4eceaf3d5bc6957b2681ead25643a951341341c6 | 66,836 |
import string
def safe_id(id):
"""
Make sure meeting-ids are safe
We try to keep meeting IDs to a safe subset of characters.
Not sure if Jitsi requires this, but I think it goes on some
URLs so easier to be safe.
"""
return escape(id, safe=string.ascii_letters + string.digits + '-') | d648c7c0e8c1143287f153b9cbb83f590cb8639e | 66,837 |
from typing import List
from typing import Tuple
def _compute_stats(values: List[float]) -> Tuple[float, float, float, float]:
"""
compute mean, std, min, max from a list of float
"""
np_values = np.array([value['value'] for value in values])
return np_values.mean(), np_values.std(), np_values.min... | 545fed8a7080d6d03f0f0251f1b3fb62aaaa8115 | 66,838 |
import numpy
def get_gfa_centre(rot, boresight, observatory='apo', r1=None, r2=None):
"""Determines the coordinates of the centre of a GFA.
Parameters
----------
rot : float
The rotation of the GFA, with respect to the boresight, in degrees.
boresight : tuple
A tuple with the righ... | 50c2d2429489c19201b82b683ddad0e7cc5802f1 | 66,839 |
def get_scheduler(args, optimizer):
"""
Initialize and return scheduler object. FixMatch uses a learning rate scheduler, which applies a cosine learning
rate decay over the course of the training process.
Parameters
----------
args: argparse.Namespace
Namespace that contains all command... | 31813f34c5e82e1837af4c6f5ed6ae03c61ae0fc | 66,840 |
def view_top_blocks(number, state):
"""
View a number of top blocks for a given state.
:param number: Number of blocks
:param state: difficulty | elapsed_time | block_reward | hash_power | height | nonce | number_of_transaction
:return: HTML
"""
# Reverse order to display latest ones to olde... | 9c722385534adfcbcdcf383b1ad7931196fbc5a4 | 66,841 |
import torch
import scipy
def masks_to_flows_gpu(masks, device=None):
""" convert masks to flows using diffusion from center pixel
Center of masks where diffusion starts is defined using COM
Parameters
-------------
masks: int, 2D or 3D array
labelled masks 0=NO masks; 1,2,...=mask labe... | f5eef08eac693aa3ba4a3bf715c8b110363bedb6 | 66,842 |
def get_version():
"""
Return a string with the current version of the library.
:rtype: ``string``
:return: Library version (e.g., "0.1.0").
"""
return __version__ | 1c0c5594a70e73e3af3fae81c73b0973d2549658 | 66,843 |
import re
def is_excludable(request):
"""
Test if the user is know (using its key)
"""
meta = request.META
excluded = Exclude.objects.all()
excludable = excluded.filter(exclude_IP=meta.get('REMOTE_ADDR')).only('id').count() > 0
excludable |= View.objects.filter(session_key=request.session.... | 4e2bc2ca7b06ec14acb0f2e2057620b020f5b9ba | 66,844 |
def gan_loss(logits, is_real=True):
"""Computes standard gan loss between logits and labels
Arguments:
logits {[type]} -- output of discriminator
Keyword Arguments:
isreal {bool} -- whether labels should be 0 (fake) or 1 (real) (default: {True})
... | c638f3dbacd26167234ee7bc1a0ea89b54d9c132 | 66,846 |
import pickle
def retest_model(
savepickleas,
features,
df,
obj,
test_model_start,
test_model_end):
"""This function tests the model for the sensor of interests (obj)
on data that may or may not be calibrated,
in the date range constrained by test_model_star... | d5f4861165ca227527de6a86aa0556337032270c | 66,848 |
import signal
def log_likelihoodJoint(theta, x, y, data, var, size):
"""
Logarithm of the likelihood function for joint fitting. Not really sure if this is right...
"""
#unpack the parameters
#[xpos, ypos]*images) +[amplitude, radius, focus])
images = len(theta[:-5]) / 2
peak, radius, focu... | d63e2cd6ecec7bcb2b8dc0ec11b70dcba55f91ef | 66,849 |
from typing import OrderedDict
def parse_resource(ctx, property_name, parent_object):
""" Parse and extract resource with name.
Parsing happens in a separate function(this) because resource's
parsing requires additional actions to decide what to parse/not
parse (when parsing methods).
:param ct... | 8f626cd9cbf7559fb6cece4d86e96991557ece66 | 66,850 |
def est_n_crews(m, sites):
""" Estimate the number of mobile crews required to survey all sites within a campaign. This
function will find estimate number of crews based on an estimate of sites per day a single
crew is able to accomplish. If the function fails (usually non mobile method) n_crews of 1
wi... | 800dde3286e3d30f329600549ee4494db776cf10 | 66,852 |
import logging
def get_n_patients(df, n=1):
"""
Select n random patients
Filter the data frame by this patients
Use the Fold 0 split as default
Override the modality for all random selected patients to "train"
return filtered df
:param df:
:param n:
:param fold:
:return:
""... | 3d50aaede8bb25bf21f1fed4d5fe9f3b22255ec4 | 66,853 |
def get_usrid_from_league(league):
"""
get user id from a league and put them into a list
:param league: LeagueDto: an object contains league information
:return: usrid
"""
entries = league['entries']
usrid = []
for entry in entries:
usrid.append(entry['playerOrTeamId'])
usri... | ce91f7f1f0afcc064b8f59c90721b60be47ab4b9 | 66,854 |
from openeye import oechem
def score(molecule, field='Hybrid2'):
"""Return the docking score"""
value = oechem.OEGetSDData(molecule, field)
return float(value) | a4a53f85532ef32899a432003f234f82354380ea | 66,855 |
def num_connected_components(g):
"""
Given a graph, count connected components.
:param g: input graph
:return: number of connected component sub-graphs
"""
return len(set(label_components(g)[0])) | ec9f7f6a0442510d1942d0334277cd899d6a08c8 | 66,857 |
from typing import Sequence
from typing import Any
from typing import Callable
from typing import Tuple
from typing import Optional
def distance_in_list(
list_data: Sequence[Any],
start_index: int,
direction: int,
filter_function: Callable[[Any], bool],
) -> Tuple[Optional[int], Optional[int]]:
""... | 3b3ff58c0c68da40a8dab47e300a36fad5d95336 | 66,858 |
def svn_ra_check_path(*args):
"""
svn_ra_check_path(svn_ra_session_t session, char path, svn_revnum_t revision,
apr_pool_t pool) -> svn_error_t
"""
return _ra.svn_ra_check_path(*args) | 56e43462dd4171d492d90c751193cf8b7b05810d | 66,859 |
def _fill_zeros(result, x, y, name, fill):
"""
if this is a reversed op, then flip x,y
if we have an integer value (or array in y)
and we have 0's, fill them with the fill,
return the result
mask the nan's from x
"""
if fill is not None:
if name.startswith('r'):
x... | 337c6d77af9bd0844e7b6f9101d30a9dc4137d24 | 66,860 |
def shake_n_bake_safe_init(A_mat, b_vec, feas_pt):
"""
Projects a feasible point to a random facet.
"""
m, n = A_mat.shape
ix = np.random.choice(m)
a_row = A_mat[ix] + np.random.randn(n) * RTOL
bd_pt = get_next_bd_pt(A_mat, b_vec, feas_pt, a_row)
assert is_bd(A_mat, b_vec, bd_pt), 'SB in... | 227137cec05e40a27e3e21cd18bddfbc00e6b9f2 | 66,862 |
import math
def polar_2_car_1(phi_list):
"""
Function:
Convert polarization coordinate to euclidean
Refer:
三维空间中直角坐标与球坐标的相互转换
https://www.cnblogs.com/hans_gis/archive/2012/11/21/2755126.html
没有讲高维空间的坐标转换,也找不到其他的博客,只能模仿这个
paper0 Eq 1
paper1 Eq 1
... | e3166c62bebf99ba8fdde1f61de6be48750332dc | 66,863 |
def temperature(mesh):
"""Mean annual temperature. Currently assumes a temperate latitude
Returns
-------
float
Mean annual temperature in C
"""
norm_el = mesh.elevation - np.percentile(mesh.elevation[mesh.water == 0], 2)
norm_el /= norm_el.max()
minimum = 0
maximum = 24
... | f3d5eac7ae78b27a21fb0be7a924261269fde1ee | 66,864 |
from typing import List
def build_callbacks(cfg: ListConfig, *args: Callback) -> List[Callback]:
"""Instantiate the callbacks given their configuration.
Args:
cfg: a list of callbacks instantiable configuration
*args: a list of extra callbacks already instantiated
Returns:
the co... | b28ac2ee75c3e44fbb269d80da6be5bdd2e548e6 | 66,865 |
from typing import List
def public_user_permissions(info, user_pk: int) -> List[BasePermissionEnum]:
"""Resolve permission for access to public metadata for user.
Customer have access to own public metadata.
Staff user with `MANAGE_USERS` have access to customers public metadata.
Staff user with `MAN... | 3cd0a2d3184c1f863a0d787447a2fb5de6c35b91 | 66,866 |
import math
from typing import List
def standard_env() -> Env:
"""Create the standard top-level environment (variable namespace) with some Scheme standard procedures."""
env = Env()
env.update(vars(math)) # sin, cos, sqrt, pi, ...
env.update({
'+':op.add, '-':op.sub, '*':op.mul, '/':op.truediv... | d3ab63837cafe2dc21b9160892c93937e70de788 | 66,867 |
def keep(tweet):
"""in goes one tweet parsed json
returns True/False do we want it or not"""
htags=set(h["text"].lower() for h in tweet["entities"]["hashtags"])
return htags&focus_h_tags | c08396c334e3a1954996e83f7208a1ff54005785 | 66,868 |
def humanized_time_interval_to_milliseconds(interval: str) -> int:
"""Converts a human readable time interval to milliseconds.
:param interval: A human readable time interval.
:returns: Time interval in milliseconds.
"""
interval = interval.lower()
try:
int(interval)
except ValueEr... | 4edb5eea2a9862cc5b4ff276f22137bd65960d3a | 66,869 |
from typing import Match
def _get_body():
"""Return the body used by MultipartRequest message."""
return AggregateStatsRequest(match=Match()) | af021daa1699299115542f4f5d9dee46e97b3418 | 66,871 |
def clean(path):
"""
clean latex generated temporary files
"""
removed_list = []
files = os.listdir(path)
for file_name in files:
f = os.path.abspath(os.path.join(path, file_name))
if os.path.isfile(f):
ext = os.path.splitext(f)[-1]
if (ext in TOBE_RM) or (ext.endswith("~")):
print '** Remove file ... | c70eec6e13be48bf922388e5d2d804198604d29a | 66,872 |
def Irradiance(*args):
"""
(read) Get the present value of the Irradiance property in W/sq-m
(write) Set the present Irradiance value in W/sq-m
"""
# Getter
if len(args) == 0:
return lib.PVSystems_Get_Irradiance()
# Setter
Value, = args
lib.PVSystems_Set_Irradiance(Value) | d71b2921f0675ec97dd6567020fe6bb4b6556e3d | 66,873 |
import string
def apply_object_attributes_to_template(template, value_object):
"""Generate a string from the template by applying values from the given object.
If the template provided is not a template (not have any placeholders), this will not have any effect and template
will be returned unchanged.
... | 266085845a4e4283d9ffa897b4b0b7d2f8669001 | 66,874 |
def reply_message(from_number, text="Thanks, we've received your message.", to_number=_SERVICE_NUMBER):
"""
:param from_number: get who send this message
:param text: this is the default message
:param to_number: here, we just have 1 service number, if the app need send many messages, maybe have more th... | 5a3808b2bdef5ae60d06e2e5c508124d62a76bbe | 66,876 |
def create_model():
"""Constructs a model."""
model_ = tf.keras.Sequential(
[
tf.keras.layers.Conv2D(32, 3, activation="relu"),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(64, 3, activation="relu"),
tf.keras.layers.MaxPooling2D(),
tf... | 104b603acdab531716396f7d4ce6766eafb32f8a | 66,877 |
def filter_closing(ws, cutoff, size=5):
""" 3D morphological closing filter (i.e. erosion first and then dilation).
:param ws: input workspace
:type ws: Workspace
:param cutoff: cutoff to binarize image
:type cutoff: tuple(int, int)
:param size: size of the spherical windows used
:type size... | 556abb7226aae11ee089120e5facc77ae9c79054 | 66,878 |
def app(request):
"""Session-wide test `Flask` application."""
app = create_app('config.TestingConfig')
ctx = app.app_context()
ctx.push()
def tearDown():
ctx.pop()
request.addfinalizer(tearDown)
return app | b46c80c5bbe5823e2572cfaa7026d24ee6f95e8c | 66,879 |
from datetime import datetime
def file_download_event_builder(event, sender_app, obj=None, **kwargs):
"""Build a file-download event."""
event.update(dict(
# When:
timestamp=datetime.datetime.utcnow().isoformat(),
# What:
bucket_id=str(obj.bucket_id),
file_id=str(obj.fi... | b26d2d0cb6a1b6bd11a9325c78eedf45cbd7c566 | 66,880 |
def daily_file_paths_in_date_range(hemisphere, start_date, end_date, search_paths):
"""Return a list of filenames containing data for the given hemisphere within
the inclusive range defined by the given start and end dates.
"""
period_index = pd.period_range(start_date, end_date, freq='D')
return _... | 9de86bad74323d66eeba1451d2fc3c7085796636 | 66,881 |
from typing import Optional
def get_log(log_group_id: Optional[str] = None,
log_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetLogResult:
"""
This data source provides details about a specific Log resource in Oracle Cloud Infrastructure Logging se... | bd6c80b746a6cec32a78b504cbd538e878414ef3 | 66,882 |
def _create_graph_def_circle() -> tf.GraphDef:
""" -> Relu --
/ \ # noqa: W605
px -> Add -> Mul Mul -> Relu
/ / \ /
py - c - -> ABS --
"""
g = tf.Graph()
dtype = np.float32
shape = [... | 6e3227257a70efa7c32c1677d70b05a26434e9bf | 66,883 |
def get_settings(connection, id, include_access=False, offset=0, limit=-1, error_msg=None):
"""Update the governing setting of the user group id.
Args:
connection: MicroStrategy REST API connection object
id (string): ID of user group containing your required privileges
include_access (... | e3fbbcbae396c53b3e06373f3f7768f1d0d64472 | 66,885 |
def create_enrollment_track_partition(course):
"""
Create and return the dynamic enrollment track user partition.
If it cannot be created, None is returned.
"""
used_ids = {p.id for p in course.user_partitions}
if ENROLLMENT_TRACK_PARTITION_ID in used_ids:
log.warning(
"Can'... | c967b77206e73098ba374f7c5020e03f134b68a7 | 66,886 |
def get_html_mouseover():
"""html content for mouseover mode.
Returns:
mouseover html
"""
return """<!DOCTYPE HTML><html lang="en-us">
<head>
<meta name="ad.size" content="width=[[width]],height=[[collapsedHeight]]">
<script>
var clickTag = "[[clicktag_url]]";
var ads = { };
ads.receiveMessage = functi... | 2bbb4d69f944b5556a472ab16cdf1bed32a22018 | 66,887 |
def urlconf(patterns, do_not_autogenerate=True):
"""
A custom url configuration for this action, just like in Django's urls.py.
The custom urlconf applies after the urlconf for the controller, unless erase is true.
Example: `["/user/(?P<user_id>\d+)/"]`
:param patterns: a url pattern or a list of ... | 1d6f8c9e840979cbaab54112b3203eebebed5f82 | 66,888 |
def note2ratio(note, cents=0):
""" Converts semitones to a frequency ratio. """
ratio = 2 ** ((note + cents / 100) / 12)
return ratio | 1c78697d3978d122d8be39e406bc8be8b7684f9d | 66,889 |
def indexmod(a, b, span=None):
"""Compute the remainder of indexdiv. a and b are non-negative.
Parameters
----------
a : PrimExpr
The left hand operand, known to be non-negative.
b : PrimExpr
The right hand operand, known to be non-negative.
span : Optional[Span]
The l... | 106ff12315a9e03aa8d3919cc4ec4dae1f4735b6 | 66,891 |
def list_of_dict_to_list(data, key):
"""
Given a list of dicts, return a list of values for a given key.
Crashes badly if the key is not present in each dict entry.
@param data: the list of dicts
@type data: list of dict
@param key: the key to look for in the dict
@type key: str
@retur... | 5ae1ab4b53874425a51d71941d90c18637ee2152 | 66,892 |
def process_modifications(cfg):
"""
Process modifications to an configuration composition.
Parameters
-----------
cfg : :class:`dict`
Configuratiion dictionary.
Returns
--------
cfg : :class:`dict`
Configuratiion dictionary.
"""
if "modifychem" in cfg:
m... | c94d3425c4ae34242911ca0caecb830293cd8230 | 66,893 |
def parseEccuEvents(json_object, fromTimeStamp, eventsSelector):
""" Parse a JSON object with a list of events obtained from ECCU Event API.
:param json_object: a JSON object that contains the array of events as returned by ECCU API
:type json_object: a native Python JSON object
:param fromTimeStamp: timestamp to s... | 479dc5ef71f0f129b36110a61b5d171bdb109068 | 66,894 |
def get_cifar10():
"""
Retrieve the CIFAR dataset and pre-process data.
"""
# Set defaults
num_classes = 10
batch_size = 64
input_shape = (3072,)
# Get the data.
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = x_train.reshape(50000, 3072)
x_test = x_test... | 32e70981116f2c8303b29e97d3f7bd7ef639fa23 | 66,895 |
import aiohttp
import json
import asyncio
async def gelbooru(ctx, tag, page='1'):
"""Searchs gelbooru. Usage: gelbooru [tag]"""
if not ctx.channel.is_nsfw():
await ctx.send("Please run this command on an nsfw channel.", delete_after=5)
return 1
if not page or page == '' or page == ' ' or ... | 7aca8df80a4525ceac985226fe1fb8571a9576e1 | 66,896 |
def to_sdp(passage, test=False, tree=False, mark_aux=False, *args, **kwargs):
""" Convert from a Passage object to a string in SemEval 2015 SDP format (sdp)
:param passage: the Passage object to convert
:param test: whether to omit the top, head, frame, etc. columns. Defaults to False
:param tree: whet... | 07ca4028923026f27fda7edb72633fe3992337e3 | 66,897 |
import json
def experimentExport(request, experiment_id):
"""
Exports an experiment to a JSON file
"""
json_data = ExperimentAdmin.exportToJSON(experiment_id)
response = HttpResponse(json.dumps(json_data), content_type='application/json')
response['Content-Disposition'] = 'attachment; filename... | 96cc1457ac5a03710faeac56724b4da0c3d3a803 | 66,898 |
def brepgprop_LinearProperties(*args):
"""
* Computes the linear global properties of the shape S, i.e. the global properties induced by each edge of the shape S, and brings them together with the global properties still retained by the framework LProps. If the current system of LProps was empty, its global prope... | eadb0c396dead2e92321470d7f4596aa64d50a0a | 66,899 |
from typing import Callable
from typing import Tuple
from typing import Mapping
from typing import Union
from typing import Sequence
def _find_all_tree(tree: dict,
func: Callable,
args: Tuple,
kwargs: Mapping
) -> Union[Sequence[dict], None]:... | e06917b6e2bd773570e84dd42928cd044393cfd0 | 66,900 |
def loginview(request):
"""Login view."""
email = request.POST.get('email')
context = basecontext(request, 'login')
result, user = None, None
if email is not None:
password = request.POST.get('password')
user = authenticate(username=email, password=password)
if user is No... | 1ef6686af4564adbf1526adcd1f9e04d29a97925 | 66,901 |
def prompt(message, validator=lambda x: True, input_to_option=lambda x: x, default_value=None, options_to_print=None):
"""
Prompt the user a message with optionally some options.
:param message: the message to show to the user
:param validator: a function that predicates if the input is correct
:pa... | 3dcb9ab47330dfb0ea52b8c9704d22b02b245174 | 66,903 |
import tokenize
import jinja2
import math
def result_sort_key(tokens):
"""
The sort key function for the search results
Input:
response_item: the tuple of (code, snippet)
output:
sortable value, the greatest first
"""
def similarity(tokens, snippet):
target_tokens = lem... | 3846a3163f14d22a60bfb39adf1fbf33333162c0 | 66,904 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.