text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def make_parser(parser_creator=None, **kwargs):
"""Returns a base argument parser for the ray.tune tool.
Args:
parser_creator: A constructor for the parser class.
kwargs: Non-positional args to be passed into the
parser class constructor.
"""
if parser_creator:
pars... | 0.000199 |
def is_prettytable(string):
""" returns true if the input looks like a prettytable """
return type(string).__name__ in {'str','unicode'} and (
len(string.splitlines()) > 1
) and (
all(string[i] == string[-i-1] for i in range(3))
) | 0.007634 |
def getNetworkFragmentID(self):
"""get current partition id of Thread Network Partition from LeaderData
Returns:
The Thread network Partition Id
"""
print '%s call getNetworkFragmentID' % self.port
if not self.__isOpenThreadRunning():
print 'OpenThread is... | 0.004124 |
def get_manylinux_wheel_url(self, package_name, package_version):
"""
For a given package name, returns a link to the download URL,
else returns None.
Related: https://github.com/Miserlou/Zappa/issues/398
Examples here: https://gist.github.com/perrygeo/9545f94eaddec18a65fd7b5688... | 0.002869 |
def breakable_units(s):
"""
Break a string into a list of substrings, breaking at each point that it is
permissible for `wrap(..., break_long_words=True)` to break; i.e., _not_
breaking in the middle of ANSI color escape sequences.
"""
units = []
for run, color in zip(
re.split('(' +... | 0.003497 |
def query(self, query=None):
"""
If query is given, modify the URL correspondingly, return the current
query otherwise.
"""
if query is None:
return self.url.query
self.url.query = query | 0.00813 |
def get_channels(self):
"""Get the selected channel(s in order). """
selectedItems = self.idx_chan.selectedItems()
selected_chan = [x.text() for x in selectedItems]
chan_in_order = []
for chan in self.chan:
if chan in selected_chan:
chan_in_order.appen... | 0.005602 |
def classification(request):
"""
Adds classification context to views.
"""
ctx = {
'classification_text': getattr(settings, 'CLASSIFICATION_TEXT', 'UNCLASSIFIED'),
'classification_text_color': getattr(settings, 'CLASSIFICATION_TEXT_COLOR', 'white'),
'classification_background_co... | 0.008518 |
def init(self):
"Initialize the message-digest and set all fields to zero."
self.length = 0
self.input = []
# Initial 160 bit message digest (5 times 32 bit).
self.H0 = 0x67452301
self.H1 = 0xEFCDAB89
self.H2 = 0x98BADCFE
self.H3 = 0x10325476
sel... | 0.005935 |
def _listFilesWin(self) -> ['File']:
""" List Files for Windows OS
Search and list the files and folder in the current directory for the
Windows file system.
@return: List of directory files and folders.
"""
output = []
for dirname, dirnames, filenames in os.wa... | 0.003546 |
def set_membership(self, membership):
""" Set membership. """
_c_leiden._MutableVertexPartition_set_membership(self._partition, list(membership))
self._update_internal_membership() | 0.010417 |
def unmix(a, D, M, M0, h0, reg, reg0, alpha, numItermax=1000,
stopThr=1e-3, verbose=False, log=False):
"""
Compute the unmixing of an observation with a given dictionary using Wasserstein distance
The function solve the following optimization problem:
.. math::
\mathbf{h} = arg\min_\m... | 0.006299 |
def intersects_any(self,
ray_origins,
ray_directions):
"""
Check if a list of rays hits the surface.
Parameters
----------
ray_origins: (n,3) float, origins of rays
ray_directions: (n,3) float, direction (vector) of rays
... | 0.006568 |
def delete_view(self, request, object_id, extra_context=None):
"""
Overrides the default to enable redirecting to the directory view after
deletion of a folder.
we need to fetch the object and find out who the parent is
before super, because super will delete the object and make... | 0.001534 |
def _wrap_thing(self, thing, kind):
"""Mimic praw.Submission and praw.Comment API"""
thing['created'] = self._epoch_utc_to_local(thing['created_utc'])
thing['d_'] = copy.deepcopy(thing)
ThingType = namedtuple(kind, thing.keys())
thing = ThingType(**thing)
return thing | 0.006329 |
def cache(cache_directory_path):
"""Display / set / update the dtool cache directory."""
if not cache_directory_path:
click.secho(dtool_config.utils.get_cache(
CONFIG_PATH,
))
else:
click.secho(dtool_config.utils.set_cache(
CONFIG_PATH,
cache_direc... | 0.002941 |
def weekday(when, weekday, start=mon):
"""Return the date for the day of this week."""
if isinstance(when, datetime):
when = when.date()
today = when.weekday()
delta = weekday - today
if weekday < start and today >= start:
delta += 7
elif weekday >= start and today < start:
... | 0.002674 |
def rrs(ax, b):
r"""
Compute relative residual :math:`\|\mathbf{b} - A \mathbf{x}\|_2 /
\|\mathbf{b}\|_2` of the solution to a linear equation :math:`A \mathbf{x}
= \mathbf{b}`. Returns 1.0 if :math:`\mathbf{b} = 0`.
Parameters
----------
ax : array_like
Linear component :math:`A \mat... | 0.001603 |
def sorensen(seq1, seq2):
"""Compute the Sorensen distance between the two sequences `seq1` and `seq2`.
They should contain hashable items.
The return value is a float between 0 and 1, where 0 means equal, and 1 totally different.
"""
set1, set2 = set(seq1), set(seq2)
return 1 - (2 * len(set1 & set2) / float(le... | 0.029326 |
def marks(value):
"""list or KeyedList of ``Mark`` : Mark definitions
Marks are the visual objects (such as lines, bars, etc.) that
represent the data in the visualization space. See the :class:`Mark`
class for details.
"""
for i, entry in enumerate(value):
_... | 0.005391 |
def get(self, key, default=None):
"""
Returns the input with the given key from the section that was
passed to the constructor. If either the section or the key
are not found, the default value is returned.
:type key: str
:param key: The key for which to return a value.... | 0.002692 |
def save_log(self, filename = None):
"""
save log to file
Returns:
"""
if filename is None:
filename = self.filename('-info.txt')
filename = self.check_filename(filename)
# filename = self.check_filename(filename)
# windows can't deal with lon... | 0.008403 |
def _group_same_samples(ldetails):
"""Move samples into groups -- same groups have identical names.
"""
sample_groups = collections.defaultdict(list)
for ldetail in ldetails:
sample_groups[ldetail["name"]].append(ldetail)
return sorted(sample_groups.values(), key=lambda xs: xs[0]["name"]) | 0.003155 |
def last_timestamp(self, event_key=None):
"""Obtain the last timestamp.
Args:
event_key: the type key of the sought events (e.g., constants.NAN_KEY). If
None, includes all event type keys.
Returns:
Last (latest) timestamp of all the events of the given type (or all
event types if... | 0.00813 |
def get_connection(self, command_name, *keys, **options):
"""
Get a connection, blocking for ``self.timeout`` until a connection
is available from the pool.
If the connection returned is ``None`` then creates a new connection.
Because we use a last-in first-out queue, the existi... | 0.000888 |
def finishConnection(self, accept=True):
"""
Finishes the active connection. If the accept value is \
true, then the connection requested signal will be emited, \
otherwise, it will simply clear the active connection \
data.
:param accept <bool>
... | 0.007614 |
def route_tables_list(resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all route tables within a resource group.
:param resource_group: The resource group name to list route
tables within.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_table... | 0.001179 |
def _read_datasets(self, dataset_nodes, **kwargs):
"""Read the given datasets from file."""
# Sort requested datasets by reader
reader_datasets = {}
for node in dataset_nodes:
ds_id = node.name
# if we already have this node loaded or the node was assigned
... | 0.001679 |
def startAll(self):
"""
Start all registered Threads.
"""
self.logger.info("Starting all threads...")
for thread in self.getThreads():
thr = self.getThread(thread)
self.logger.debug("Starting {0}".format(thr.name))
thr.start()
self.logger.info("Started all threads") | 0.038062 |
def peek_openssl_error():
"""
Peeks into the error stack and pulls out the lib, func and reason
:return:
A three-element tuple of integers (lib, func, reason)
"""
error = libcrypto.ERR_peek_error()
lib = int((error >> 24) & 0xff)
func = int((error >> 12) & 0xfff)
reason = int(e... | 0.00274 |
async def CreateSpaces(self, spaces):
'''
spaces : typing.Sequence[~CreateSpaceParams]
Returns -> typing.Sequence[~ErrorResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='DiscoverSpaces',
request='CreateSpaces',
... | 0.004283 |
def __set_default_ui_state(self, *args):
"""
Sets the Widget default ui state.
:param \*args: Arguments.
:type \*args: \*
"""
LOGGER.debug("> Setting default View state!")
if not self.model():
return
self.expandAll()
for column in ... | 0.012136 |
def metric_detail(slug, with_data_table=False):
"""Template Tag to display a metric's *current* detail.
* ``slug`` -- the metric's unique slug
* ``with_data_table`` -- if True, prints the raw data in a table.
"""
r = get_r()
granularities = list(r._granularities())
metrics = r.get_metric(s... | 0.001669 |
def override_params(opening_char='{', closing_char='}', separator_char='|'):
"""
Override some character settings
@type opening_char: str
@param opening_char: Opening character. Default: '{'
@type closing_char: str
@param closing_char: Closing character. Default: '}'
@type separator_char: s... | 0.001852 |
def ToPhotlam(self, wave, flux, **kwargs):
"""Convert to ``photlam``.
.. math::
m = -0.4 \\; (\\textnormal{ST}_{\\lambda} + 21.1)
\\textnormal{photlam} = \\frac{10^{m} \\lambda}{hc}
where :math:`h` and :math:`c` are as defined in
:ref:`pysynphot-constants`.
... | 0.002853 |
def _create_table(self, packet_defn):
''' Creates a database table for the given PacketDefinition
Arguments
packet_defn
The :class:`ait.core.tlm.PacketDefinition` instance for which a table entry
should be made.
'''
cols = ('%s %s' % (defn.nam... | 0.011321 |
def _get_service_config(self):
"""
Will get configuration for the service from a service key.
"""
key = self._get_or_create_service_key()
config = {}
config['service_key'] = [{'name': self.name}]
config.update(key['entity']['credentials'])
return config | 0.00627 |
def allpass(self, frequency, width_q=2.0):
'''Apply a two-pole all-pass filter. An all-pass filter changes the
audio’s frequency to phase relationship without changing its frequency
to amplitude relationship. The filter is described in detail in at
http://musicdsp.org/files/Audio-EQ-Cook... | 0.001866 |
def check_auth():
"""
Check are we authorised
:return: True if we authorised
False if no auth provided
exception if provided auth is wrong
"""
if get_oauth_token():
auth_info = get_auth_info()
if not auth_info:
raise MissingTokenInfoException("Could not ge... | 0.001408 |
def fine_tune_model_from_file_paths(model_archive_path: str,
config_file: str,
serialization_dir: str,
overrides: str = "",
extend_vocab: bool = False,
... | 0.004705 |
def fastrcnn_outputs(feature, num_classes, class_agnostic_regression=False):
"""
Args:
feature (any shape):
num_classes(int): num_category + 1
class_agnostic_regression (bool): if True, regression to N x 1 x 4
Returns:
cls_logits: N x num_class classification logits
... | 0.002227 |
def format_query_results(self, r, prop_nr):
"""
`r` is the results of the sparql query in _query_data and is modified in place
`prop_nr` is needed to get the property datatype to determine how to format the value
`r` is a list of dicts. The keys are:
item: the subject. the i... | 0.00446 |
def get_library_value(self, key: str) -> typing.Any:
"""Get the library value for the given key.
Please consult the developer documentation for a list of valid keys.
.. versionadded:: 1.0
Scriptable: Yes
"""
desc = Metadata.session_key_map.get(key)
if desc is n... | 0.006303 |
def get_local_file(file):
"""
Get a local version of the file, downloading it from the remote storage if
required. The returned value should be used as a context manager to
ensure any temporary files are cleaned up afterwards.
"""
try:
with open(file.path):
yield file.path
... | 0.001427 |
def fpost(self, url, form_data):
"""
To make a form-data POST request to Falkonry API server
:param url: string
:param form_data: form-data
"""
response = None
if 'files' in form_data:
response = requests.post(
self.host + url,
... | 0.003958 |
async def get_token(cls, host, **params):
"""
POST /oauth/v2/token
Get a new token
:param host: host of the service
:param params: will contain :
params = {"grant_type": "password",
"client_id": "a string",
"client_secret": "a string... | 0.002656 |
def _is_override(meta, method):
"""Checks whether given class or instance method has been marked
with the ``@override`` decorator.
"""
from taipan.objective.modifiers import _OverriddenMethod
return isinstance(method, _OverriddenMethod) | 0.007246 |
def validate(config):
'''
Validate the beacon configuration.
'''
# Must be a list of dicts.
if not isinstance(config, list):
return False, 'Configuration for napalm beacon must be a list.'
for mod in config:
fun = mod.keys()[0]
fun_cfg = mod.values()[0]
if not isi... | 0.00316 |
def transform_timeseries4pypsa(timeseries, timerange, column=None):
"""
Transform pq-set timeseries to PyPSA compatible format
Parameters
----------
timeseries: Pandas DataFrame
Containing timeseries
Returns
-------
pypsa_timeseries: Pandas DataFrame
Reformated pq-set tim... | 0.001515 |
def get_stack(f, t, botframe, proc_obj=None):
"""Return a stack of frames which the debugger will use for in
showing backtraces and in frame switching. As such various frame
that are really around may be excluded unless we are debugging the
sebugger. Also we will add traceback frame on top if that
e... | 0.003766 |
def WriteTaskCompletion(self, aborted=False):
"""Writes task completion information.
Args:
aborted (Optional[bool]): True if the session was aborted.
Raises:
IOError: if the storage type is not supported or
when the storage writer is closed.
OSError: if the storage type is not ... | 0.002959 |
def search_topics(self, keyword, sort='relevance', start=0):
"""
搜索话题
:param keyword: 关键字
:param sort: 排序方式 relevance/newest
:param start: 翻页
:return: 带总数的列表
"""
xml = self.api.xml(API_GROUP_SEARCH_TOPICS % (start, sort, keyword))
return b... | 0.008086 |
def sync_proxy(self, mri, block):
"""Abstract method telling the ClientComms to sync this proxy Block
with its remote counterpart. Should wait until it is connected
Args:
mri (str): The mri for the remote block
block (BlockModel): The local proxy Block to keep in sync
... | 0.001348 |
def early_stopping(stopping_rounds, first_metric_only=False, verbose=True):
"""Create a callback that activates early stopping.
Note
----
Activates early stopping.
The model will train until the validation score stops improving.
Validation score needs to improve at least every ``early_stopping_... | 0.00329 |
def get_generated_vcl_html(self, service_id, version_number):
"""Display the content of generated VCL with HTML syntax highlighting."""
content = self._fetch("/service/%s/version/%d/generated_vcl/content" % (service_id, version_number))
return content.get("content", None) | 0.021583 |
def readkmz(self, filename):
'''reads in a kmz file and returns xml nodes'''
#Strip quotation marks if neccessary
filename.strip('"')
#Open the zip file (as applicable)
if filename[-4:] == '.kml':
fo = open(filename, "r")
fstring = fo.read()
... | 0.012618 |
def read_file(file_path, default_content=''):
"""
Read file at the specified path.
If file doesn't exist, it will be created with default-content.
Returns the file content.
"""
if not os.path.exists(file_path):
write_file(file_path, default_content)
handler = open(file_path, 'r')
... | 0.002475 |
def parse_dates(tree_to_parse, xpath_map):
"""
Creates and returns a Dates Dictionary data structure given the parameters provided
:param tree_to_parse: the XML tree from which to construct the Dates data structure
:param xpath_map: a map containing the following type-specific XPATHs:
multiple, ... | 0.003444 |
def __getitem_slice(self, slce):
"""Return a range which represents the requested slce
of the sequence represented by this range.
"""
scaled_indices = (self._step * n for n in slce.indices(self._len))
start_offset, stop_offset, new_step = scaled_indices
return newrange(se... | 0.004651 |
def to_utc(self, dt):
"""Convert any timestamp to UTC (with tzinfo)."""
if dt.tzinfo is None:
return dt.replace(tzinfo=self.utc)
return dt.astimezone(self.utc) | 0.010256 |
def update(*args, **kwds):
'''Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which')
>>> c.update('witch') # add elements from another iterable
>>> d = Counter('watch'... | 0.002145 |
def percolating_continua(target, phi_crit, tau,
volume_fraction='pore.volume_fraction',
bulk_property='pore.intrinsic_conductivity'):
r'''
Calculates the effective property of a continua using percolation theory
Parameters
----------
target : OpenPN... | 0.000739 |
def fetch_by_ids(TableName,iso_id_list,numin,numax,ParameterGroups=[],Parameters=[]):
"""
INPUT PARAMETERS:
TableName: local table name to fetch in (required)
iso_id_list: list of isotopologue id's (required)
numin: lower wavenumber bound (required)
numax: ... | 0.013524 |
def write(self, config_dir=None, config_name=None, codec=None):
"""
writes config to config_dir using config_name
"""
# get name of config directory
if not config_dir:
config_dir = self._meta_config_dir
if not config_dir:
raise IOError("con... | 0.00333 |
def fields_to_dtypes(schema):
"""Maps table schema fields types to dtypes separating date fields
:param schema:
"""
datetime_types = ['date', 'datetime']
datetime_fields = {
f['name']: _TABLE_SCHEMA_DTYPE_MAPPING.get(f['type'], 'object')
for f in schema['fields']
if f['type'... | 0.001742 |
def date_decimal_hook(dct):
'''The default JSON decoder hook. It is the inverse of
:class:`stdnet.utils.jsontools.JSONDateDecimalEncoder`.'''
if '__datetime__' in dct:
return todatetime(dct['__datetime__'])
elif '__date__' in dct:
return todatetime(dct['__date__']).date()
elif '__decimal... | 0.002481 |
def pack(self):
"""
Pack the frame into a string according to the following scheme:
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) ... | 0.001863 |
def config(client, key, value):
"""Get and set Renku repository and global options."""
if value is None:
cfg = client.repo.config_reader()
click.echo(cfg.get_value(*_split_section_and_key(key)))
else:
with client.repo.config_writer() as cfg:
section, config_key = _split_s... | 0.002364 |
def on_close(self, ws):
""" Called when websocket connection is closed
"""
log.debug("Closing WebSocket connection with {}".format(self.url))
if self.keepalive and self.keepalive.is_alive():
self.keepalive.do_run = False
self.keepalive.join() | 0.006711 |
def movie(args):
"""
%prog movie test.tour test.clm ref.contigs.last
Plot optimization history.
"""
p = OptionParser(movie.__doc__)
p.add_option("--frames", default=500, type="int",
help="Only plot every N frames")
p.add_option("--engine", default="ffmpeg", choices=("ffmpeg... | 0.000438 |
def ttensor(self,R,z,phi=0.,t=0.,eigenval=False):
"""
NAME:
ttensor
PURPOSE:
Calculate the tidal tensor Tij=-d(Psi)(dxidxj)
INPUT:
R - Galactocentric radius (can be Quantity)
... | 0.035375 |
def _get_arguments(): # pragma: no cover
""" Handle the command line arguments given to this program """
LOG.debug('Parse command line argument')
parser = argparse.ArgumentParser(
description='Command line interface for the MQ² program')
parser.add_argument(
'-z', '--zipfile', dest='in... | 0.000766 |
def inflect(self):
"""Return instance of inflect."""
if self._inflect is None:
import inflect
self._inflect = inflect.engine()
return self._inflect | 0.010204 |
def alchemy_to_dict(obj):
"""
Transforms a SQLAlchemy model instance into a dictionary
"""
if not obj:
return None
d = {}
for c in obj.__table__.columns:
value = getattr(obj, c.name)
if type(value) == datetime:
value = value.isoformat()
d[c.name] = val... | 0.002985 |
def _get_useful_callpoint_name():
""" Attempts to find the lowest user-level call into the pyrtl module
:return (string, int) or None: the file name and line number respectively
This function walks back the current frame stack attempting to find the
first frame that is not part of the pyrtl module. Th... | 0.001594 |
def add_raster_data(self, image, second_image=None):
"""
Add the image data to the instructions.
The provided image has to be binary (every pixel
is either black or white).
:param PIL.Image.Image image: The image to be converted and added to the raster instructions
:para... | 0.003655 |
def _opts_to_dict(*opts):
'''Convert a tuple of options returned from getopt into a dictionary.'''
ret = {}
for key, val in opts:
if key[:2] == '--':
key = key[2:]
elif key[:1] == '-':
key = key[1:]
if val == '':
val = True
ret[key.replace('-','_')] = val
return ret | 0.045296 |
def trimmed_mean(self, p1, p2):
"""
Computes the mean of the distribution between the two percentiles p1 and p2.
This is a modified algorithm than the one presented in the original t-Digest paper.
"""
if not (p1 < p2):
raise ValueError("p1 must be between 0 and 100 a... | 0.003493 |
def _load_entries(self, func, count, page=1, entries=None, **kwargs):
"""
Load entries
:param function func: function (:meth:`.API._req_files` or
:meth:`.API._req_search`) that returns entries
:param int count: number of entries to load. This value should never
b... | 0.002455 |
def mirror(self: BaseBoardT) -> BaseBoardT:
"""
Returns a mirrored copy of the board.
The board is mirrored vertically and piece colors are swapped, so that
the position is equivalent modulo color.
"""
board = self.transform(flip_vertical)
board.occupied_co[WHITE... | 0.007126 |
def create(self, subject, displayName, issuerToken, expiration, secret):
"""Create a new guest issuer using the provided issuer token.
This function returns a guest issuer with an api access token.
Args:
subject(basestring): Unique and public identifier
displayName(base... | 0.001217 |
def fix_command(known_args):
"""Fixes previous command. Used when `thefuck` called without arguments."""
settings.init(known_args)
with logs.debug_time('Total'):
logs.debug(u'Run with settings: {}'.format(pformat(settings)))
raw_command = _get_raw_command(known_args)
try:
... | 0.001406 |
async def webhook_handle(self, request):
"""
aiohttp.web handle for processing web hooks
:Example:
>>> from aiohttp import web
>>> app = web.Application()
>>> app.router.add_route('/webhook')
"""
update = await request.json(loads=self.json_deserialize)
... | 0.005195 |
def update_frame(self, key, ranges=None):
"""
Update the internal state of the Plot to represent the given
key tuple (where integers represent frames). Returns this
state.
"""
ranges = self.compute_ranges(self.layout, key, ranges)
for coord in self.layout.keys(ful... | 0.003466 |
def autosave(self):
"""
Autosaves the currently stored data, but only if autosave is checked!
"""
# make sure we're suppoed to
if self.button_autosave.is_checked():
# save the file
self.save_file(_os.path.join(self._autosave_directory, "%04d " % (self.num... | 0.006652 |
def get_request_headers(self):
"""Return request headers that will be sent to upstream.
The header REMOTE_USER is set to the current user
if AuthenticationMiddleware is enabled and
the view's add_remote_user property is True.
.. versionadded:: 0.9.8
"""
request... | 0.003086 |
def p_include_once_fname(p):
""" include_once : INCLUDE ONCE FILENAME
"""
p[0] = []
if ENABLED:
p[0] = include_once(p[3], p.lineno(3), local_first=False)
else:
p[0] = []
if not p[0]:
p.lexer.next_token = '_ENDFILE_' | 0.003774 |
def send_frame(self, cmd, headers=None, body=''):
"""
Encode and send a stomp frame
through the underlying transport:
:param str cmd: the protocol command
:param dict headers: a map of headers to include in the frame
:param body: the content of the message
"""
... | 0.003717 |
def __read_answer(self):
"""!
@brief Read information about proper clusters and noises from the file.
"""
if self.__clusters is not None:
return
file = open(self.__answer_path, 'r')
self.__clusters, self.__noise = [], []
index_point =... | 0.00431 |
def _Nroot(self, L, M=None):
"""
NAME:
_Nroot
PURPOSE:
Evaluate the square root of equation (3.15) with the (2 - del_m,0) term outside the square root
INPUT:
L - evaluate Nroot for 0 <= l <= L
M - evaluate Nroot for 0 <= m <= M
OUTPUT... | 0.020356 |
def choices_validator(choices):
"""Return validator function that will check if ``value in choices``.
Args:
max_value (list, set, tuple): allowed choices for new validator
"""
def validator(value):
if value not in choices:
# note: make it a list for consistent representatio... | 0.002198 |
def domain_delete(auth=None, **kwargs):
'''
Delete a domain
CLI Example:
.. code-block:: bash
salt '*' keystoneng.domain_delete name=domain1
salt '*' keystoneng.domain_delete name=b62e76fbeeff4e8fb77073f591cf211e
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(... | 0.002703 |
def score(self, X, y):
"""
Draws a confusion matrix based on the test data supplied by comparing
predictions on instances X with the true values specified by the
target vector y.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix o... | 0.001455 |
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': OrderedDict(
(field, fo... | 0.002331 |
def frag_check(*args, protocol, func=None):
"""Check if arguments are valid fragments."""
func = func or inspect.stack()[2][3]
if 'IP' in protocol:
_ip_frag_check(*args, func=func)
elif 'TCP' in protocol:
_tcp_frag_check(*args, func=func)
else:
raise FragmentError(f'Unknown f... | 0.002841 |
def parse_table(table, flatten=True, footer=False):
"""Parses a table from sports-reference sites into a pandas dataframe.
:param table: the PyQuery object representing the HTML table
:param flatten: if True, flattens relative URLs to IDs. otherwise, leaves
all fields as text without cleaning.
... | 0.000183 |
def gen_challenge(self, state):
"""returns the next challenge and increments the seed and index
in the state.
:param state: the state to use for generating the challenge. will
verify the integrity of the state object before using it to generate
a challenge. it will then modify... | 0.002577 |
def _media(self):
"""
The medias needed to enhance the admin page.
"""
def static_url(url):
return staticfiles_storage.url('zinnia_markitup/%s' % url)
media = super(EntryAdminMarkItUpMixin, self).media
media += Media(
js=(static_url('js/jquery.mi... | 0.002535 |
def all_package_versions(package):
""" All versions for package """
info = PyPI.package_info(package)
return info and sorted(info['releases'].keys(), key=lambda x: x.split(), reverse=True) or [] | 0.013761 |
def split_dmap_overlay(obj, depth=0):
"""
Splits a DynamicMap into the original component layers it was
constructed from by traversing the graph to search for dynamically
overlaid components (i.e. constructed by using * on a DynamicMap).
Useful for assigning subplots of an OverlayPlot the streams th... | 0.000835 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.