content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def export_account_json(request):
"""Export an account as JSON"""
subdomains = []
for subdomain in Subdomain.objects.filter(user=request.user):
subdomains.append({'name': subdomain.name, 'ip': subdomain.ip,
'ipv6': subdomain.ipv6, 'updated': subdomain.updated})
return ... | 58,000 |
def calc_lat(hours_daylight, delta):
"""
Latitude is estimated from equation (1.6.11) in:
Duffie, John A., and William A. Beckman. Solar engineering of thermal
processes. New York: Wiley, 1991.
:param hours_daylight: daylight hours as calculated by calculate_hours_daylight or calculate_hours_daylig... | 58,001 |
def remainder(numbers):
"""Function for finding the remainder of 2 numbers divided.
Parameters
----------
numbers : list
List of numbers that the user inputs.
Returns
-------
result : int
Integer that is the remainder of the numbers divided.
"""
ret... | 58,002 |
def get_logical_test_file_paths(test_file, output_dir):
""" Given the full path to logical test file, return all the paths to the expected output and gold result files.
This depends on the logical tests main directory having 2 levels of subdirectories
eg tdvt/logicaltests/setup/calcs
and td... | 58,003 |
def branin(x):
"""
A standard 2-dimensional global optimization test function with a long, shallow valley.
f(x) = (x2 - 4 * 5.1 (x1 / pi)^2 + 5 x1 / pi - 6)^2 + 10 (1 - (8 pi)^-1 ) cos (x1) + 10
(The general form doesn't specify coefficients.)
There is a global minimum at [[-pi, 12.275], [pi, 2.275], [9.4247... | 58,004 |
def connect_to_cloud(
account: str,
password: str,
appkey=DEFAULT_APPKEY,
appid=DEFAULT_APP_ID,
appname: str = None,
hmackey=DEFAULT_HMACKEY,
iotkey=DEFAULT_IOTKEY,
api_url=DEFAULT_API_SERVER_URL,
proxied=DEFAULT_PROXIED,
sign_key=DEFAULT_SIGNKEY,
) -> MideaCloud:
"""Connects... | 58,005 |
def init(*args, path: List[str] = None, include_optaplanner_jars: bool = True, log_level='INFO'):
"""Start the JVM. Throws a RuntimeError if it is already started.
:param args: JVM args.
:param path: If not None, a list of dependencies to use as the classpath. Default to None.
:param include_optaplanne... | 58,006 |
def generate_strings_file(swift_variables, output_file):
"""Generate a complete Swift strings file from variables and save it.
Args:
swift_variables: An array of Swift variables.
output_file: The file to write to.
"""
generated = GENERATED_STRINGS_TEMPLATE.substitute({
"strings" : "\n ".join(swi... | 58,007 |
def get_cfg_value(config, section, option):
"""Get configuration value."""
try:
value = config[section][option]
except KeyError:
if (section, option) in MULTI_OPTIONS:
return []
else:
return ''
if (section, option) in MULTI_OPTIONS:
value = split_m... | 58,008 |
def getItemSpecs(session_id, guid):
"""Get specs of a certain item
:param session_id: token for current user session
:param guid: unique id of an item
:return: :class:'Response <Response>' object
:rtype: requests.Response
"""
url = base_url + "/items/{guid}?includeEmptyAdditionalAttrib... | 58,009 |
def _calculate_noise_by_substitution(below_thresh_positions: pd.DataFrame, sample_id: str) -> pd.DataFrame:
"""
Use the below_threhold_positions data frame to calculate noise of each substitution type
:param below_thresh_positions: pd.DataFrame
:param sample_id: str - sample ID for first column
:re... | 58,010 |
def get_sorted_fields(doctype, custom_fields):
"""sort on basis of insert_after"""
fields_dict = frappe.get_meta(doctype).get("fields")
standard_fields_count = frappe.db.sql("""select count(name) from `tabDocField`
where parent=%s""", doctype)[0][0]
newlist = []
pending = [d.fieldname for d in fields_dict]
m... | 58,011 |
def test_load_file_to_table(database_table_fixture):
"""Load a file to a SQL table"""
database, target_table = database_table_fixture
filepath = str(pathlib.Path(CWD.parent, "data/sample.csv"))
database.load_file_to_table(File(filepath), target_table)
df = database.hook.get_pandas_df(f"SELECT * FRO... | 58,012 |
def mk_gparams_register_modules_internal(component_src_dirs, path):
"""
Generate a ``gparams_register_modules.cpp`` file in the directory ``path``.
Returns the path to the generated file.
This file implements the procedure
```
void gparams_register_modules()
```
... | 58,013 |
def staffing_agency_employee_factory(db):
"""
Fixture to get the factory used to create staffing agency employees.
"""
return StaffingAgencyEmployeeFactory | 58,014 |
def get_nodeid(get_path, send_path):
"""[get nodeid into file]
Arguments:
get_path {[file]} -- [description]
send_path {[file]} -- [description]
Raises:
MCError -- [description]
"""
LOGGER.info("get_nodeid start! get path is %s", get_path)
LOGGER.info("get_nodeid start... | 58,015 |
def parse_dburi(url:str, uppercase:bool=False) -> dict:
"""Parse a given URL or URI string and return the component parts relevant for database connectivity.
These come in the general UNIX form:
engine://[user:pass@]host[:port]/database[?options]
"""
uri = URI(url)
parts = {
'engine': str(uri.scheme),... | 58,016 |
def _complete_dict_with_iterable_of_required_keys(
to_complete: dict, complete_with: Iterable
):
"""Complete `to_complete` (in place) with `complete_with`
`complete_with` contains values that must be covered by `to_complete`
Those values that are not covered will be inserted in to_complete,
with key... | 58,017 |
def relativize(home_domain, web_root_path, html_file_path, link_attr_value):
"""
:param home_domain: Domain that originally hosted the file
:param web_root_path: Path of the web root on the local filesystem
:param html_file_path: Path of html file containing the links we are working on
:param link_attr_value: Link... | 58,018 |
def compute_dataflow(program):
"""
compute the program data flow
"""
# compute the stencil accesses
analyze_offsets(program)
# compute input and output sets
dependencies = set(program["OUTPUTS"])
dependencies0 = dependencies.copy()
for group0 in reversed(program["TILING"]["GROUPS"]):... | 58,019 |
def train_classifier(input_raster,
input_training_sample_json,
classifier_parameters,
segmented_raster=None,
segment_attributes="COLOR;MEAN",
*,
gis=None,
future=False,
... | 58,020 |
def _get_wanted_channels(wanted_sig_names, record_sig_names, pad=False):
"""
Given some wanted signal names, and the signal names contained in a
record, return the indices of the record channels that intersect.
Parameters
----------
wanted_sig_names : list
List of desired signal name st... | 58,021 |
def test_func(args):
"""
main function for testing
param args: global arguments
return: None
"""
print(args)
global network_type
if args.cuda:
print("=====> use gpu id: '{}'".format(args.gpus))
os.environ["CUDA_VISIBLE_DEVICES"] = args.gpus
if not torch.cuda.i... | 58,022 |
def plot_avg_graph(graphs, eigenfunc, graph_states, outdir=None, data_points=None):
"""
Plot average graphs for each state.
Parameters
----------
graphs: array, (n_graphs, n_nodes, n_nodes)
Snapshots of the time-dependent graph.
eigenfunc: array
Eigenfunction of transfer ooperat... | 58,023 |
def get_image_filename(file_name, list_of_image_files):
"""Compare an ALTO XML file name with a list of image file names and try to find a pair
:param file_name: absolute path to an ALTO XML file
:param list_of_image_files: list of image file names
:type file_name: str
:type list_of_image_files: li... | 58,024 |
def make_cmsweb_prod_request(query_url, data=None, timeout=90, keep_open=True):
"""
Make a request to https://cmsweb-prod.cern.ch
"""
return make_request('https://cmsweb-prod.cern.ch:8443', query_url, data, timeout, keep_open) | 58,025 |
def logpdf_multivariate_normal(x:np.ndarray, mean:np.ndarray, cov:np.ndarray):
"""
Calculate \log p(x|w) = \sum_{j=1}^M \log(\frac{\sqrt{s_j}}{2\pi} 1/cosh(\sqrt{s_j}/2(x_j - b_j)))
Input:
+ x: n*M
+ mean: M
+ cov :M * M
Output:
+ n*M
"""
return(multivariate_normal.logpdf(x, ... | 58,026 |
def plot_qa(data, outroot, outformat="pdf", labels=False):
"""Make plots of QA data.
"""
set_matplotlib_pdf_backend()
# Imported here, to ensure that the backend has been set.
from matplotlib.patches import Patch
hw = load_hardware()
tile_radius = hw.focalplane_radius_deg
fontpt = 1
... | 58,027 |
def get_thumbnail_options(file_, thumb_options=None):
"""
Get all options of thumbnail, including default ones.
"""
options = thumb_options.copy() if thumb_options else {}
if settings.THUMBNAIL_PRESERVE_FORMAT:
options.setdefault('format', sorl_backend._get_format(file_))
for key, valu... | 58,028 |
def subset_sum(numbers: list, target: int, partial=[], results=[]) -> list:
"""
Determine all combinations of list items that add up to the target
:param numbers: A list of values
:type numbers: list
:param target: The total that the values need to add up to
:type target: int
:param partial... | 58,029 |
def walk_nodes(nodes, depth_first=True):
"""
Traverse all child nodes of given nodes.
"""
stack = list((n, 0) for n in nodes)
while stack:
node, depth = stack.pop(0 if depth_first else -1)
yield node, depth
stack[0:0] = ((n, depth +1) for n in node.childNodes()) | 58,030 |
def aug_image(filename: str, df: pd.DataFrame, config, folder: str, augmentations: int, img_ext: str = 'jpg') -> (list, list):
"""
This function will:
1. load the image based on the filename from the given folder
2. load all given bounding boxes to that image from the given DataFrame
3. apply aug... | 58,031 |
def oneTimeJob(func):
"""
Decorator that causes the given scheduled function to run only once.
As a bonus, it also logs the subsequent job to be ran.
NOTE: This decorator suppresses any returned results by the given function.
:param func: function, the function to be wrapped.
:return: function... | 58,032 |
def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Argparse Python script',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'positional', metavar='DIR', nargs='+', help='DIR')
parser.add_argument(
... | 58,033 |
def getTimezone(profile):
"""
Returns the pytz timezone for a given profile.
Arguments:
profile -- contains information related to the user (e.g., email address)
"""
try:
return timezone(profile['timezone'])
except:
return None | 58,034 |
def test_gtlink():
""" Test that we can build a `Gtlink` sub class """
class Gtlink_scrmaps(Gtlink):
""" Gtlink sub-class for testing """
appname = 'gtsrcmaps'
linkname_default = 'gtsrcmaps'
usage = '%s [options]' % (appname)
description = "Link to run %s" % (appname)
... | 58,035 |
def ret_int(potential):
"""Utility function to check the input is an int, including negative."""
try:
return int(potential)
except:
return None | 58,036 |
def card_component(
title, context, highlight_start,
highlight_end, score, url,
key=None):
"""Create a new instance of "my_component".
Parameters
----------
title: ...
context: ...
highlight_start: ...
highlight_end: ...
score: ...
url: ...
key: str or None
A... | 58,037 |
def generate_html_major(output_file, tabs, title):
"""Generates the output forecast report with the provided tabs and
title. generate_data is used for generating the JSON data files
used by this report.
Parameters
----------
output_file : str
Name of output html file
tabs : dict
... | 58,038 |
def read_file(file_name):
"""Read contents of file."""
with open(file_name, encoding='utf8') as file:
return file.read().rstrip().lstrip() | 58,039 |
def mean_squared(array):
"""Returns the mean squared value of an array
"""
# We need to handle both real and complex cases
sqr = jnp.conj(array) * array
mean_sqr = jnp.mean(sqr)
# Make sure that we are down to float data type
return jnp.abs(mean_sqr) | 58,040 |
def create_plankton_dataset(start: int, end: int) -> dict:
"""Function to create dataset for plankton experiment.
Uses data from experiments C1 to C4 from [1].
A series of ten chemostat experiments was performed, constituting a total of 1,948 measurement days (corresponding to 5.3 years of measurement) an... | 58,041 |
def series_quatrot_inverse(x, y, z, q0, q1, q2, q3, rot_name=""):
"""Given pandas series x-z and quaternion q0-q4, compute reversed rotated vector x_r, y_r, z_r.
Arguments:
x,y,z -- vector to be rotated
q0-q4 -- quaternion entries. The vector is being rotated with the inverse of that quaternion
Ke... | 58,042 |
def frexp102str(x):
"""
Convert to mantesa exponent form in txt
"""
m, exp = frexp10(x)
txt = r"%.2f$\times 10^{%d}$" % (m, exp)
return txt | 58,043 |
def test_get_master_listener_invalid_listeners(get_os):
"""If the structure of the lb.listeners dict changes, return None"""
conn, lb = get_os
mock_lb = default_data()
mock_lb.listeners = ["a", "b", "c"]
conn.load_balancer.find_load_balancer.return_value = mock_lb
assert lb._get_master_listener... | 58,044 |
def post_theme(config, storage_url, parameters, files):
"""
POST the theme zip file to the provided storage url
:param config: context config
:param storage_url: the storage url provided by import job response
:param parameters: the parameters provided by the import job response
:param files: th... | 58,045 |
def get_data(sequence_length):
""" Get all the notes and chords from the midi files in the ./midi_songs directory """
vocab = set()
sequence_in = list()
sequence_out = list()
all_notes = list()
for file1 in data_dir.glob("simpl*.txt"):
notes = None
with open(file1, "r") as f:
... | 58,046 |
async def async_operations(record, servers, results):
"""
Performs the same function as it's synchronous sibling function found in
consistency_checker.py - except 100x faster due to the power of async.
Executes the main program logic. Actions undertaken include:
1. Loops through the list of records... | 58,047 |
def model(dataset, model_type, *, forecast_steps=None):
"""
Bayesian regression model of lineage portions as a function of mutation features.
This function can be run in two different modes:
- During training, ``forecast_steps=None`` and the model is conditioned on
observed data.
- During pre... | 58,048 |
def pipeline_lightcurve(d, l1=0, m1=0, segments=[], scan=-1):
""" Makes lightcurve at given (l1, m1)
l1, m1 define phase center. if not set, then image max is used.
"""
if scan == -1: scan = d['scan']
if segments == []: segments = range(d['nsegments'])
d = set_pipeline(d['filename'], scan, fil... | 58,049 |
def registry_sources(sntype, subclassName=None):
"""
get a list of sources in the SNCosmo registry that are of the supernova type
sntype, and also of the same subclass if subclassName is not None
Parameters
----------
sntype: string, mandatory
string used to denote a particular supernov... | 58,050 |
def test_nested_move_multiple(qapp, sources, dest, expectation):
"""Test that models stay in sync with complicated moves.
This uses mimeData to simulate drag/drop operations.
"""
root = _recursive_make_group([0, 1, [20, [210, 211], 22], 3, 4])
qt_tree = QtNodeTreeModel(root)
model_indexes = [qt... | 58,051 |
def transform_mne_ica2data(sources, ica, idx_zero=None, idx_keep=None):
"""
performs back-transformation from ICA to Data space using
rescaling as used as in MNE-Python
sources: shape [n_chan, n_samples]
ica: ICA object from MNE-Python
idx_zero: list of components to remove (optiona... | 58,052 |
def hadoop_fs_rmr(*args):
"""Implements hadoop fs -rmr."""
if len(args) < 1:
sys.stderr.write('Usage: java FsShell [-rmr [-skipTrash] <src>]')
if args[0] == '-skipTrash':
args = args[1:]
failed = False
for path in args:
real_path = hdfs_path_to_real_path(path)
if os... | 58,053 |
def test_access_denied_invalid_token(client):
# pylint: disable=C0301
"""Make sure access is denied with an invalid token"""
rv = client.get('/api/auth',
headers={'Authorization': 'Bearer eyK0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1OTc4NTQ4OTQsIm5iZiI6MTU5Nzg1NDg5NCwianRpIjoiZmI4NjZ... | 58,054 |
def get_fans_or_followers_ids(user_id, crawl_type):
"""
Get followers or fans
:param user_id: user id
:param crawl_type: 1 stands for fans,2 stands for follows
:return: lists of fans or followers
"""
# todo check fans and followers the special users,such as writers
# todo deal with cond... | 58,055 |
def RGB2HEX(color):
"""In: RGB color array
Out: HEX string"""
return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2])) | 58,056 |
def updateBenchmarkInfo(AllInfo, CurInfo, nRepeat, **kwargs):
""" Aggregate information about different experiments into one dict.
"""
for method in CurInfo:
tvec = np.asarray([
CurInfo[method][r]['telapsed'] for r in range(nRepeat)])
key = 't_' + method
loc = np.flatnonz... | 58,057 |
async def infer_type_tail(engine, tup):
"""Infer the return type of tail."""
tup_t = await tup['type']
if not isinstance(tup_t, Tuple):
raise MyiaTypeError('tail of non-tuple')
if not len(tup_t.elements) >= 1:
raise MyiaTypeError('tail on empty tuple')
return Tuple(tup_t.elements[1:]... | 58,058 |
def search() -> dict:
""" Parses the user's search. Can be POST or GET method. """
form = forms.SearchForm()
if form.validate_on_submit():
query = form.query.data
elif flask.request.args.get("query", None) is not None:
query = flask.request.args["query"]
else:
return {}
r... | 58,059 |
def getMetrics(predictions, ground):
"""Given predicted labels and the respective ground truth labels, display some metrics
Input: shape [# of samples, NUM_CLASSES]
predictions : Model output. Every row has 4 decimal values, with the highest belonging to the predicted class
ground : Ground t... | 58,060 |
def register_blueprints(application):
"""
Registers application blueprints
:param application: Current flask application
"""
from app.mod_blockchain import block
logging.debug(f"Registering blueprint {block}")
application.register_blueprint(block) | 58,061 |
def tgos(location, **kwargs):
"""TGOS Provider
:param location: Your search location you want geocoded.
:param language: (default=taiwan) Use the following:
> taiwan
> english
> chinese
:param method: (default=geocode) Use the following:
> geocode
API Reference
... | 58,062 |
def test_get_resolved_config_defaults_to_egrc():
"""
When no command line options are passed, we should prefer those in the
egrc.
"""
egrc_config = _create_dummy_egrc_config()
# The second level of priority for editor_cmd is the environment variable,
# so we include that here rather than fr... | 58,063 |
def read(source_file, *args, **kwargs):
"""
Read an input file of various formats.
Arguments:
source_file:
The first argument is a structure file of some format.
The remaining args and kwargs are passed to the methods called to read the
structure.
If the structure name con... | 58,064 |
def snap_flow_mapper(product_set, snap_function, config, mount=None, rebuild=False):
"""Run a single set of products through the workflow.
Inputs
------
product_set : list of N-tuple
Something like...
[(s1), (s1_2)...]
[(s1, s2), (s1_2, s2_2)...]
[(s1_old, s1... | 58,065 |
def _parse_selection(*selection):
"""
Parser for *selection* strings used in :py:func:`join_root_selection` and
:py:func:`join_numexpr_selection`.
"""
_selection = []
for s in flatten(selection):
if isinstance(s, (int, float)):
# special case: skip ones
if s == 1:... | 58,066 |
def prompt_download():
"""
Ask the user if they want to download the object
"""
while True:
result = raw_input('Download? [y/n]')
if result == 'y' or result == 'Y':
return True
elif result == 'n' or result == 'N':
return False
else:
pri... | 58,067 |
def blk_chol_mtimes(A, B, x, lower = True, transpose = False):
"""
Evaluate Cx = b, where C is assumed to be a
block-bi-diagonal matrix ( where only the first (lower or upper)
off-diagonal block is nonzero.
Inputs:
A - [T x n x n] tensor, where each A[i,:,:] is the ith block diagonal matrix
... | 58,068 |
def signed_area(contour):
"""Return the signed area of a contour.
Parameters
----------
contour: sequence of x,y coordinates, required
Returns
-------
area: :class:`float`
Signed area of the given closed contour. Positive
if the contour coordinates are in counter-clockwise... | 58,069 |
def payload_too_large(error) -> BaseErrorType:
"""Payload is too large."""
return BaseRequestException(413, error, request.path), 413 | 58,070 |
def get_mean_centroids_coords_distances(df):
"""
Creates a features array. For each address (each row), calculate the \
mean distances between the corresponding centroid coords and the coords \
suggested from different services.
Args:
df (pandas.DataFrame): Contains data points for which th... | 58,071 |
def rmsd(native, p, loops_as_strings, ca_only = False, all_atom=False):
"""
Prints + Returns RMSD for Full Protein, as well as any loops in loops_as_strings.
"""
rms = ""
if ca_only:
rms = CA_rmsd(native, p)
print("C-Alpha:")
print("%.3f RMSD"%rms)
elif all_atom:
... | 58,072 |
def _optimize_commodity(
physical_network,
k,
extended_nodes,
extended_arcs,
current_t,
inventory_shape,
inf_capacity=9000000,
):
"""
Returns:
cost: Total cost of the optimization for this commodity
transport_movements: Arc flows moving from DC to DC
all_move... | 58,073 |
def unlinked_objects(self: JSONClassObject) -> dict[str, list[JSONClassObject]]:
"""Unlinked objects of this jsonclass object.
"""
return self._unlinked_objects | 58,074 |
def sleep():
"""
Pump window to the end of config.minimum_presplash_time.
"""
if not (window or renpy.mobile):
return
end_time = start_time + renpy.config.minimum_presplash_time
while end_time - time.time() > 0:
pump_window() | 58,075 |
def ChooseFunction(title):
"""
Ask the user to select a function
Arguments:
@param title: title of the dialog box
@return: -1 - user refused to select a function
otherwise returns the selected function start address
"""
f = idaapi.choose_func(title, idaapi.BADADDR)
return... | 58,076 |
def collect_nodes(trees):
"""
Collect node information(token, left child, right child, label) of trees by starting from lower part of trees and moving to the top
Param:
------
trees: list of tree
Return:
------
list of tuple, (token, left child token, right child token,... | 58,077 |
def new_page(args):
"""Add new page to the site"""
site_configs = config.read(args.site_root)
sites = (Site(args.site_root, data=config.data) for config in site_configs)
if not hasattr(args, 'site'):
print('What site would you like to add a new page to?')
count = 0
for site in si... | 58,078 |
def conv2d(
inputs,
filters,
training,
batchnorm=constants.BN,
activation=tf.nn.relu,
padding=constants.SAME,
data_format='channels_last',
kernel_size=3,
strides=1,
kernel_initializer=None,
name=None):
"""Buils a 2d convolutional layer with batch normalization.
Args:
... | 58,079 |
def natr(
client,
symbol,
timeframe="6m",
highcol="high",
lowcol="low",
closecol="close",
period=14,
):
"""This will return a dataframe of normalized average true range for the given symbol across
the given timeframe
Args:
client (pyEX.Client): Client
symbol (str... | 58,080 |
async def validation_handler(request, exc):
"""Handle Pydantic validation errors raised by FastAPI."""
error = exc.errors()[0]
return JSONResponse(
{"output": error["msg"], "level": "error", "keywords": error["loc"]},
status_code=422,
) | 58,081 |
def common_args(*, under_test=False, include_x_modules=False):
"""Construct default ArgumentParser parent.
Args:
under_test (Boolean): When true, create an argument parser subclass
that raises an exception instead of calling exit.
include_x_modules (Boolean): When true, include "--x... | 58,082 |
def tex_cii(tcii, tau_cii, tbg):
"""
"""
return tstar/np.log(1. + tstar*(1. - np.exp(-tau_cii))/(tcii + J(tbg))) | 58,083 |
def call(args, **kwargs):
"""Execute the command and return its output or raise a
ReplayGainError on failure.
"""
try:
return command_output(args, **kwargs)
except subprocess.CalledProcessError as e:
raise ReplayGainError(
"{} exited with status {}".format(args[0], e.retu... | 58,084 |
def debug(func):
"""Decorator for logging debug messages.
"""
def wrapped(*args, **kws):
logger.debug(u'{}: args={}, kws={}'.format(
func_name(func),
UNICODE_TYPE(args),
UNICODE_TYPE(kws)
))
f_result = func(*args, **kws)
logger.debug(u'{}: ... | 58,085 |
def initDriver(browser):
"""
Funcion para crear una instancia de un navegador web
para realizar las pruebas automaticas usando Selenium
:param browser: navegador a usar firefox o chrome (firefox no sirve la captura de logs)
:type browser: String
:return: driver Selenium
"""
if browser =... | 58,086 |
def search(request):
"""Handling search request
"""
if 'q' in request.GET:
q = request.GET['q']
# results = SearchItem.objects.all()
results = search_request(q)
return render(request, 'search/result.html', {'results': results, 'query': q}) | 58,087 |
def nufft1d1(x,c,isign,eps,ms,f,debug=0,spread_debug=0,spread_sort=2,fftw=0,modeord=0,chkbnds=1,upsampfac=2.0):
"""1D type-1 (aka adjoint) complex nonuniform fast Fourier transform
::
nj-1
f(k1) = SUM c[j] exp(+/-i k1 x(j)) for -ms/2 <= k1 <= (ms-1)/2
j=0
Args:
x (float[nj]... | 58,088 |
def valid_topic(value: Any) -> str:
"""Validate that this is a valid topic name/filter."""
value = cv.string(value)
try:
raw_value = value.encode("utf-8")
except UnicodeError as err:
raise vol.Invalid("MQTT topic name/filter must be valid UTF-8 string.") from err
if not raw_value:
... | 58,089 |
def parse_agent_uri(uri: str) -> typing.Tuple[str, Dict[str, Optional[str]]]:
"""
Parse an agent uri and return the settings
:attr uri: The uri to parse
:return: (scheme, config)
"""
parts = urllib.parse.urlparse(uri)
config: Dict[str, Optional[str]] = {}
scheme = "local"
if parts.... | 58,090 |
def callo(args):
"""Call a program, and capture its output
"""
return subprocess.check_output(args) | 58,091 |
def register_slycat_plugin(context):
"""Called during startup when the plugin is loaded."""
import cherrypy
import datetime
import time
import os
import json
import slycat.web.server
import threading
import sys
import traceback
import numpy
import re
import couchdb
... | 58,092 |
def light_vgg():
"""
this model is inspired by vgg net, but lighter
CV_Accuracy ~75% in 10 epoch, 12s per epoch
"""
model = Sequential([
# Block 1: in:100x100x3, out:50x50x16
layers.Conv2D(16, (3, 3), activation='relu', padding='same', name='b1_conv1'),
layers.Conv2D(16, (3,... | 58,093 |
def plot_2d_contour(x, y, data,
ax = None, ax_labels = None,
**plot_opts):
"""
Generic command to plot a 2-dimensional field
"""
if ax is None:
ax = plt.axes()
if ax_labels is None:
ax_labels = {"title" : "", "xlabel" : "", "ylabel" : ""}
cs = ax.c... | 58,094 |
def previous_primary_owners(transaction_executor, vin):
"""
Find previous primary owners for the given VIN in a single transaction.
In this example, query the `VehicleRegistration` history table to find all previous primary owners for a VIN.
:type transaction_executor: :py:class:`pyqldb.execution.execu... | 58,095 |
def initialize(
config: Union[dict, str, Path]
) -> Tuple[
List[PatientAgent],
Dict[
Union[str, int],
Union[AandEEnvironmentAgent, EnvironmentAgent, GPEnvironmentAgent],
],
Dict[str, Callable],
Callable,
List[Union[str, int]],
dict,
int,
int,
bool,
Optiona... | 58,096 |
def get_range(start_id, end_id):
"""Get all messages between the start and end ids, inclusive.
:param start_id: id of first message in range
:param end_id: id of last message in range
:return: generator yielding messages
"""
if end_id < start_id:
raise ValueError('End must come after s... | 58,097 |
def get_job_details(name):
"""Return job details (properties + instances)."""
if is_job(name):
props = get_job_properties(name)
props.update({'instances': get_instance_properties(name)})
return props
else:
return None | 58,098 |
def buttonPress(value):#parameter = 메개변수
"""value이라는 변수 (1, 2, 3, + , / ...)을 받고 display.inser("end", value)"""
display.insert(END, value) | 58,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.