text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def subscribe(self, peer_jid):
"""
Request presence subscription with the given `peer_jid`.
This is deliberately not a coroutine; we don’t know whether the peer is
online (usually) and they may defer the confirmation very long, if they
confirm at all. Use :meth:`on_subscribed` t... | 0.00367 |
def listdir(self, folder_id='0', offset=None, limit=None, fields=None):
'Get Box object, representing list of objects in a folder.'
if fields is not None\
and not isinstance(fields, types.StringTypes): fields = ','.join(fields)
return self(
join('folders', folder_id, 'items'),
dict(offset=offset, limit=l... | 0.02924 |
def b58decode_int(v):
'''Decode a Base58 encoded string as an integer'''
v = v.rstrip()
v = scrub_input(v)
decimal = 0
for char in v:
decimal = decimal * 58 + alphabet.index(char)
return decimal | 0.004405 |
def Then5(self, f, arg1, arg2, arg3, arg4, *args, **kwargs):
"""
`Then5(f, ...)` is equivalent to `ThenAt(5, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
"""
args = (arg1, arg2, arg3, arg4) + args
return self.ThenAt(5, f, *args, **kwargs) | 0.010169 |
def _to_bz2file(self, file_generator):
"""Convert file to bz2-compressed file.
:return: None
:rtype: :py:obj:`None`
"""
with bz2.BZ2File(file_generator.to_path, mode="wb") as outfile:
for f in file_generator:
outfile.write(f.writestr(file_generator.to_... | 0.005935 |
def insert(queue, items):
'''
Add an item or items to a queue
'''
handle_queue_creation(queue)
with _conn(commit=True) as cur:
if isinstance(items, dict):
items = salt.utils.json.dumps(items)
cmd = str('''INSERT INTO {0}(data) VALUES('{1}')''').format(queue, items) ... | 0.002595 |
def get_maintainer(self):
# type: () -> hdx.data.user.User
"""Get the dataset's maintainer.
Returns:
User: Dataset's maintainer
"""
return hdx.data.user.User.read_from_hdx(self.data['maintainer'], configuration=self.configuration) | 0.014035 |
def _add_nodes(self, features):
""" Adds a node to the graph for each item in 'features' using
the GraphNodes from the editor factory.
"""
graph = self._graph
if graph is not None:
for feature in features:
for graph_node in self.factory.nodes:
... | 0.007737 |
def is_shaped(self):
"""Return description containing array shape if exists, else None."""
for description in (self.description, self.description1):
if not description:
return None
if description[:1] == '{' and '"shape":' in description:
return des... | 0.004684 |
def export_hmaps_csv(key, dest, sitemesh, array, comment):
"""
Export the hazard maps of the given realization into CSV.
:param key: output_type and export_type
:param dest: name of the exported file
:param sitemesh: site collection
:param array: a composite array of dtype hmap_dt
:param co... | 0.00198 |
def fuzz(p, _inplace=0):
"""Transform a layer into a fuzzy layer by replacing some default values by random objects""" # noqa: E501
if not _inplace:
p = p.copy()
q = p
while not isinstance(q, NoPayload):
for f in q.fields_desc:
if isinstance(f, PacketListField):
... | 0.001389 |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Checksum(key)
if key not in Checksum._member_map_:
extend_enum(Checksum, key, default)
return Checksum[key] | 0.007576 |
def _ReadPresetsFromFileObject(self, file_object):
"""Reads parser and parser plugin presets from a file-like object.
Args:
file_object (file): file-like object containing the parser and parser
plugin presets definitions.
Yields:
ParserPreset: a parser preset.
Raises:
Malf... | 0.005906 |
def onMessage(self, payload, isBinary):
"""
Send the payload onto the {slack.[payload['type]'} channel.
The message is transalated from IDs to human-readable identifiers.
Note: The slack API only sends JSON, isBinary will always be false.
"""
msg = self.translate(unpack(... | 0.003717 |
def amen_mv(A, x, tol, y=None, z=None, nswp=20, kickrank=4,
kickrank2=0, verb=True, init_qr=True, renorm='direct', fkick=False):
'''
Approximate the matrix-by-vector via the AMEn iteration
[y,z]=amen_mv(A, x, tol, varargin)
Attempts to approximate the y = A*x
with accuracy TO... | 0.000847 |
def update_frame(self, key, ranges=None, plot=None):
"""
Updates an existing plot with data corresponding
to the key.
"""
element = self._get_frame(key)
text, _, _ = self.get_data(element, ranges, {})
self.handles['plot'].text = text | 0.00692 |
def _set_mpls_reopt_lsp(self, v, load=False):
"""
Setter method for mpls_reopt_lsp, mapped from YANG variable /brocade_mpls_rpc/mpls_reopt_lsp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_reopt_lsp is considered as a private
method. Backends looking to ... | 0.00615 |
def process_results(self, results=None, **value):
"""take results list of all events and return first dict"""
for res in results:
if 'mask' in res:
res['mask'] = utils.IrcString(res['mask'])
value['success'] = res.pop('retcode', None) != '486'
value.up... | 0.005714 |
def find_funcs_called_with_kwargs(sourcecode, target_kwargs_name='kwargs'):
r"""
Finds functions that are called with the keyword `kwargs` variable
CommandLine:
python3 -m utool.util_inspect find_funcs_called_with_kwargs
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
... | 0.001597 |
def start_update(self, layer_id):
"""
A shortcut to create a new version and start importing it.
Effectively the same as :py:meth:`koordinates.layers.LayerManager.create_draft` followed by :py:meth:`koordinates.layers.LayerManager.start_import`.
"""
target_url = self.client.get_u... | 0.008163 |
def register():
"""Uses the new style of registration based on GitHub Pelican issue #314."""
signals.initialized.connect(initialized)
try:
signals.content_object_init.connect(detect_content)
signals.all_generators_finalized.connect(detect_images_and_galleries)
signals.article_writer_... | 0.006494 |
def destripe_plus(inputfile, suffix='strp', stat='pmode1', maxiter=15,
sigrej=2.0, lower=None, upper=None, binwidth=0.3,
scimask1=None, scimask2=None,
dqbits=None, rpt_clean=0, atol=0.01,
cte_correct=True, clobber=False, verbose=True):
r"""Cali... | 0.000261 |
def delete(self, request, bot_id, id, format=None):
"""
Delete existing Messenger Bot
---
responseMessages:
- code: 401
message: Not authenticated
"""
return super(MessengerBotDetail, self).delete(request, bot_id, id, format) | 0.010033 |
def isexception(obj):
"""Given an object, return a boolean indicating whether it is an instance
or subclass of :py:class:`Exception`.
"""
if isinstance(obj, Exception):
return True
if isclass(obj) and issubclass(obj, Exception):
return True
return False | 0.003413 |
def get_bit_series(self, bits=None):
"""Get the `StateTimeSeries` for each bit of this `StateVector`.
Parameters
----------
bits : `list`, optional
a list of bit indices or bit names, defaults to all bits
Returns
-------
bitseries : `StateTimeSeriesD... | 0.001898 |
def img_box(img, box):
"""
Selects the sub-image inside the given box
:param img: Image to crop from
:param box: Box to crop from. Box can be either Box object or array of [x, y, width, height]
:return: Cropped sub-image from the main image
"""
if isinstance(box, tuple):
box = Box.f... | 0.003891 |
def simxUnpackFloats(floatsPackedInString):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
b=[]
for i in range(int(len(floatsPackedInString)/4)):
b.append(struct.unpack('<f',floatsPackedInString[4*i:4*(i+1)])[0])
return b | 0.013333 |
def read_units(self, fid):
"""Read units from an acclaim skeleton file stream."""
lin = self.read_line(fid)
while lin[0] != ':':
parts = lin.split()
if parts[0]=='mass':
self.mass = float(parts[1])
elif parts[0]=='length':
... | 0.012146 |
def diffstore(self, dest, *others):
"""
Store the set difference of the current set and one or more
others in a new key.
:param dest: the name of the key to store set difference
:param others: One or more :py:class:`Set` instances
:returns: A :py:class:`Set` referencing ... | 0.003968 |
def lookup(self, pathogenName, sampleName):
"""
Look up a pathogen name, sample name combination and get its
FASTA/FASTQ file name and unique read count.
This method should be used instead of C{add} in situations where
you want an exception to be raised if a pathogen/sample comb... | 0.002307 |
def timestamp_insert(sender, frames):
"""
Timestamp the created and modified fields for all documents. This method
should be bound to a frame class like so:
```
MyFrameClass.listen('insert', MyFrameClass.timestamp_insert)
```
"""
for frame in frames:
... | 0.006772 |
def is_disconnected(self, node_id):
"""Check whether the node connection has been disconnected or failed.
A disconnected node has either been closed or has failed. Connection
failures are usually transient and can be resumed in the next ready()
call, but there are cases where transient ... | 0.003003 |
def decktape():
'''Install DeckTape.
DeckTape is a "high-quality PDF exporter for HTML5 presentation
frameworks". It can be used to create PDFs from reveal.js presentations.
More info:
https://github.com/astefanutti/decktape
https://github.com/hakimel/reveal.js/issues/1252#issuecomment-19... | 0.000688 |
def generate(env):
"""Add Builders and construction variables for swig to an Environment."""
c_file, cxx_file = SCons.Tool.createCFileBuilders(env)
c_file.suffix['.i'] = swigSuffixEmitter
cxx_file.suffix['.i'] = swigSuffixEmitter
c_file.add_action('.i', SwigAction)
c_file.add_emitter('.i', _sw... | 0.008895 |
def show(dataset_uri, overlay_name):
"""
Show the content of a specific overlay.
"""
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
try:
overlay = dataset.get_overlay(overlay_name)
except: # NOQA
click.secho(
"No such overlay: {}".format(overlay_name),
... | 0.0016 |
def multipublish(self, topic, messages):
"""Publish an iterable of messages to the given topic over http.
:param topic: the topic to publish to
:param messages: iterable of bytestrings to publish
"""
self.send(nsq.multipublish(topic, messages)) | 0.006993 |
def distance_to_point(self, p):
'''Returns the distance from the point to the interval. Zero if the point lies inside the interval.'''
if self.start <= p <= self.end:
return 0
else:
return min(abs(self.start - p), abs(self.end - p)) | 0.010714 |
def get_strain_label(entry, viral=False):
"""Try to extract a strain from an assemly summary entry.
First this checks 'infraspecific_name', then 'isolate', then
it tries to get it from 'organism_name'. If all fails, it
falls back to just returning the assembly accesion number.
"""
def get_strai... | 0.000951 |
def file_envs(self, load=None):
'''
Return environments for all backends for requests from fileclient
'''
if load is None:
load = {}
load.pop('cmd', None)
return self.envs(**load) | 0.008368 |
def __draw_constant_line(self, value_label_style):
"Draw a constant line on the y-axis with the label"
value, label, style = value_label_style
start = self.transform_output_coordinates((0, value))[1]
stop = self.graph_width
path = etree.SubElement(self.graph, 'path', {
'd': 'M 0 %(start)s h%(stop)s' % loca... | 0.030132 |
def squash_dates(obj):
"""squash datetime objects into ISO8601 strings"""
if isinstance(obj, dict):
obj = dict(obj) # don't clobber
for k,v in obj.iteritems():
obj[k] = squash_dates(v)
elif isinstance(obj, (list, tuple)):
obj = [ squash_dates(o) for o in obj ]
elif is... | 0.012658 |
def _dict_seq_locus(list_c, loci_obj, seq_obj):
"""
return dict with sequences = [ cluster1, cluster2 ...]
"""
seqs = defaultdict(set)
# n = len(list_c.keys())
for c in list_c.values():
for l in c.loci2seq:
[seqs[s].add(c.id) for s in c.loci2seq[l]]
common = [s for s in ... | 0.003304 |
def read_namespaced_pod_preset(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod_preset # noqa: E501
read the specified PodPreset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True... | 0.001409 |
def begin(self):
"""Load variables from checkpoint.
New model variables have the following name foramt:
new_model_scope/old_model_scope/xxx/xxx:0 To find the map of
name to variable, need to strip the new_model_scope and then
match the old_model_scope and remove the suffix :0.
"""
variable... | 0.001708 |
def isPIDValid(self, pid):
""" Checks if a PID is associated with a running process """
## Slightly copied wholesale from http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid
## Thanks to http://stackoverflow.com/users/1777162/ntrrgc and http://stacko... | 0.005638 |
def loop_through_editors(self, backward=False):
"""
Loops through the editor tabs.
:param backward: Looping backward.
:type backward: bool
:return: Method success.
:rtype: bool
"""
step = not backward and 1 or -1
idx = self.Script_Editor_tabWidge... | 0.003442 |
def get_contents(self, el, no_iframe=False):
"""Get contents or contents in reverse."""
if not no_iframe or not self.is_iframe(el):
for content in el.contents:
yield content | 0.009217 |
def start(self):
"""
Starts this QEMU VM.
"""
with (yield from self._execute_lock):
if self.is_running():
# resume the VM if it is paused
yield from self.resume()
return
if self._manager.config.get_section_config("... | 0.004946 |
def border(self):
"""Region formed by taking border elements.
:returns: :class:`jicimagelib.region.Region`
"""
border_array = self.bitmap - self.inner.bitmap
return Region(border_array) | 0.008811 |
def build(self, input_path, output_paths):
"""Should be extended by subclasses to actually do stuff. By default
this will copy `input` over every file in the `outputs` list."""
for output in output_paths:
shutil.copy(input_path, output_paths) | 0.007194 |
def clean(self):
"""Deallocates the fortran-managed memory that this ctype references.
"""
if not self.deallocated:
#Release/deallocate the pointer in fortran.
method = self._deallocator()
if method is not None:
dealloc = static_symbol("ftypes_... | 0.009009 |
def interp_like(self, other, method='linear', assume_sorted=False,
kwargs={}):
"""Interpolate this object onto the coordinates of another object,
filling out of range values with NaN.
Parameters
----------
other : Dataset or DataArray
Object with ... | 0.001529 |
def cpu():
'''
Tests for the CPU performance of minions.
CLI Examples:
.. code-block:: bash
salt '*' sysbench.cpu
'''
# Test data
max_primes = [500, 1000, 2500, 5000]
# Initializing the test variables
test_command = 'sysbench --test=cpu --cpu-max-prime={0} run'
resul... | 0.001639 |
def remote_ssh(self, host):
""" Execute a command on SSH. Takes a paramiko host dict """
logger.info('Starting remote execution of task {0} on host {1}'.format(self.name, host['hostname']))
try:
self.remote_client = paramiko.SSHClient()
self.remote_client.load_system_host... | 0.003019 |
def create_aws_clients(region, profile, *clients):
"""
Create boto3 clients for one or more AWS services. These are the services used within the libs:
cloudformation, cloudfront, ec2, iam, lambda, route53, waf
Args:
region: the region in which to create clients that are region-specific (all but IAM)
p... | 0.012419 |
def on_patch(resc, req, resp, rid):
""" Deserialize the payload & update the single item """
signals.pre_req.send(resc.model)
signals.pre_req_update.send(resc.model)
props = req.deserialize()
model = find(resc.model, rid)
from_rest(model, props)
goldman.sess.store.update(model)
props... | 0.001942 |
def log_player_ends_turn(self, player):
"""
:param player: catan.game.Player
"""
seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds()
self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta)))
self._latest_timestamp = ... | 0.011662 |
def copy(self):
"""Copy text to clipboard"""
clipboard = QApplication.clipboard()
clipl = []
for idx in self.selectedIndexes():
if not idx.isValid():
continue
obj = self.delegate.get_value(idx)
# Check if we are trying to copy a... | 0.002509 |
def compute_distance(m, l):
'''Compute distance between two trajectories
Returns
-------
numpy.ndarray
'''
if np.shape(m) != np.shape(l):
raise ValueError("Input matrices are different sizes")
if np.array_equal(m, l):
# print("Trajectory ... | 0.006186 |
def FetchDiscoveryDoc(discovery_url, retries=5):
"""Fetch the discovery document at the given url."""
discovery_urls = _NormalizeDiscoveryUrls(discovery_url)
discovery_doc = None
last_exception = None
for url in discovery_urls:
for _ in range(retries):
try:
conten... | 0.001071 |
def filter(self, *args, **kwargs):
"""
Apply filters to the existing nodes in the set.
:param kwargs: filter parameters
Filters mimic Django's syntax with the double '__' to separate field and operators.
e.g `.filter(salary__gt=20000)` results in `salary > 20000`.
... | 0.002327 |
def onRightDown(self, event=None):
""" right button down: show pop-up"""
if event is None:
return
# note that the matplotlib event location have to be converted
if event.inaxes is not None and self.popup_menu is not None:
pos = event.guiEvent.GetPosition()
... | 0.004158 |
def get_third_order_displacements(cell,
symmetry,
is_plusminus='auto',
is_diagonal=False):
"""Create dispalcement dataset
Note
----
Atoms 1, 2, and 3 are defined as follows:
Atom 1: The first disp... | 0.000272 |
def set_burnstages_upgrade_massive(self):
'''
Outputs burnign stages as done in burningstages_upgrade (nugridse)
'''
burn_info=[]
burn_mini=[]
for i in range(len(self.runs_H5_surf)):
sefiles=se(self.runs_H5_out[i])
burn_info.append(sefiles.burnstage_upgrade())
... | 0.038806 |
def shape(self) -> Tuple[int, int]:
"""Required shape of |NetCDFVariableAgg.array|.
For the default configuration, the first axis corresponds to the
number of devices, and the second one to the number of timesteps.
We show this for the 1-dimensional input sequence |lland_fluxes.NKor|:
... | 0.001715 |
def Compile(self, filter_implementation):
"""Compile the expression."""
arguments = [self.attribute]
for argument in self.args:
arguments.append(argument.Compile(filter_implementation))
expander = filter_implementation.FILTERS['ValueExpander']
context_cls = filter_implementation.FILTERS['Conte... | 0.004808 |
def find_stars(self, data, mask=None):
"""
Find stars in an astronomical image.
Parameters
----------
data : 2D array_like
The 2D image array.
mask : 2D bool array, optional
A boolean mask with the same shape as ``data``, where a
`Tru... | 0.000554 |
def parse(self, path, args=None, unsaved_files=None, options = 0):
"""Load the translation unit from the given source code file by running
clang and generating the AST before loading. Additional command line
parameters can be passed to clang via the args parameter.
In-memory contents fo... | 0.005981 |
def GetStructByteOrderString(self):
"""Retrieves the Python struct format string.
Returns:
str: format string as used by Python struct or None if format string
cannot be determined.
"""
if not self._data_type_definition:
return None
return self._BYTE_ORDER_STRINGS.get(
... | 0.005464 |
def _ends_in_doubled_cons(self, term):
"""Return Porter helper function _ends_in_doubled_cons value.
Parameters
----------
term : str
The word to check for a final doubled consonant
Returns
-------
bool
True iff the stem ends in a doubled... | 0.003731 |
def ellipse_from_second_moments_ijv(i,j, image, labels, indexes, wants_compactness = False):
"""Calculate measurements of ellipses equivalent to the second moments of labels
i,j - coordinates of each point
image - the intensity at each point
labels - for each labeled object, derive an ellipse
... | 0.007946 |
def parseerror(self, msg, line=None):
"""Emit parse error and abort assembly."""
if line is None:
line = self.sline
error('parse error: ' + msg + ' on line {}'.format(line))
sys.exit(-2) | 0.008696 |
def _batch_gvcfs(data, region, vrn_files, ref_file, out_file=None):
"""Perform batching of gVCF files if above recommended input count.
"""
if out_file is None:
out_file = vrn_files[0]
# group to get below the maximum batch size, using 200 as the baseline
max_batch = int(dd.get_joint_group_s... | 0.003559 |
def _ParseLeak(
self, parser_mediator, cache_directories, msiecf_item, recovered=False):
"""Extract data from a MSIE Cache Files (MSIECF) leak item.
Every item is stored as an event object, one for each timestamp.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
... | 0.002125 |
def merge_grad_list(all_grads, all_vars):
"""
Args:
all_grads (K x N): gradients
all_vars(K x N): variables
Return:
K x N x 2: list of list of (grad, var) pairs
"""
return [list(zip(gs, vs)) for gs, vs in zip(all_grads, all_vars)] | 0.003636 |
def _apply_shadow_vars(avg_grads):
"""
Create shadow variables on PS, and replace variables in avg_grads
by these shadow variables.
Args:
avg_grads: list of (grad, var) tuples
"""
ps_var_grads = []
for grad, var in avg_grads:
assert var.na... | 0.002525 |
def get_record(self):
"""Override the base get_record."""
self.update_system_numbers()
self.add_systemnumber("CDS")
self.fields_list = [
"024", "041", "035", "037", "088", "100",
"110", "111", "242", "245", "246", "260",
"269", "300", "502", "650", "65... | 0.002187 |
def generate_sentence(self, chain):
"""
!DEMO!
Demo function that shows how to generate a simple sentence starting with
uppercase letter without lenght limit.
Args:
chain: MarkovChain that will be used to generate sentence
"""
def weighted_choice(cho... | 0.003275 |
def maybeDeferred(f, *args, **kw):
"""
Copied from twsited.internet.defer and add a check to detect fibers.
"""
try:
result = f(*args, **kw)
except Exception:
return fail(failure.Failure())
if IFiber.providedBy(result):
import traceback
frames = traceback.extract... | 0.001462 |
def send(self, conn):
''' Send the message on the given connection.
Args:
conn (WebSocketHandler) : a WebSocketHandler to send messages
Returns:
int : number of bytes sent
'''
if conn is None:
raise ValueError("Cannot send to connection None... | 0.005587 |
def _isint(string):
"""
>>> _isint("123")
True
>>> _isint("123.45")
False
"""
return type(string) is int or \
(isinstance(string, _binary_type) or isinstance(string, _text_type)) and \
_isconvertible(int, string) | 0.015267 |
def _printStats(self, graph, hrlinetop=False):
""" shotcut to pull out useful info for interactive use
2016-05-11: note this is a local version of graph.printStats()
"""
if hrlinetop:
self._print("----------------", "TIP")
self._print("Ontologies......: %d" % len(grap... | 0.006719 |
def _validate_datetime(cls, value):
"""
validate datetime value
:param value: datetime value
:return: None or validators.Invalid or MlbAmException
"""
datetime_check = validators.Int()
datetime_check.to_python(value)
if len(value) != 8:
raise M... | 0.007335 |
def search(self):
"""Handle the search request."""
search = self.document_class().search() # pylint: disable=not-callable
search = self.custom_filter(search)
search = self.filter_search(search)
search = self.order_search(search)
search = self.filter_permissions(search)... | 0.003322 |
def _resolve_by_callback(request, url, urlconf=None):
"""
Finds a view function by urlconf. If the function has attribute
'navigation', it is used as breadcrumb title. Such title can be either a
callable or an object with `__unicode__` attribute. If it is callable, it
must follow the views API (i.e.... | 0.000728 |
def read_loom(filename: PathLike, sparse: bool = True, cleanup: bool = False, X_name: str = 'spliced',
obs_names: str = 'CellID', var_names: str = 'Gene', dtype: str='float32', **kwargs) -> AnnData:
"""Read ``.loom``-formatted hdf5 file.
This reads the whole file into memory.
Beware that you... | 0.006211 |
def rewrite_refs( targets, old,new, index, key='refs', single_ref=False ):
"""Rewrite key in all targets (from index if necessary) to replace old with new"""
for parent in targets:
if not isinstance( parent, dict ):
try:
parent = index[parent]
except KeyError, err... | 0.023697 |
def set_option(name, value):
"""
Set package option
Parameters
----------
name : str
Name of the option
value : object
New value of the option
Returns
-------
old : object
Old value of the option
"""
d = globals()
if name in {'get_option', 'set_... | 0.001965 |
def _jq_format(code):
"""
DEPRECATED - Use re.escape() instead, which performs the intended action.
Use before throwing raw code such as 'div[tab="advanced"]' into jQuery.
Selectors with quotes inside of quotes would otherwise break jQuery.
If you just want to escape quotes, there's escape_quotes_if... | 0.001366 |
def _validate_filters(cls, filters):
"""Raise a TypeError if ``filters`` contains any keys inappropriate to
this event class."""
for k in iterkeys(filters):
if k not in cls.filters:
# Mirror "unexpected keyword argument" message:
raise TypeError("%s go... | 0.004914 |
def Run(self):
"""Run the iteration."""
count = 0
for count, input_data in enumerate(self.GetInput()):
if count % 2000 == 0:
logging.debug("%d processed.", count)
args = (input_data, self.out_queue, self.token)
self.thread_pool.AddTask(
target=self.IterFunction, args=args... | 0.010165 |
def files(self) -> List[str]:
"""
Obtain the list of the files (excluding .git directory).
:return: List[str], the list of the files
"""
_all = []
for path, _, files in os.walk(str(self.path)):
if '.git' in path:
continue
for name ... | 0.004963 |
def _get_classifier(self, prefix):
""" Construct a decoder for the next sentence prediction task """
with self.name_scope():
classifier = nn.Dense(2, prefix=prefix)
return classifier | 0.009174 |
def get_locations_list(self, lower_bound=0, upper_bound=None):
"""
Return the internal location list.
Args:
lower_bound:
upper_bound:
Returns:
"""
real_upper_bound = upper_bound
if upper_bound is None:
real_upper_bound = self.... | 0.00641 |
def add_row(self, data: list):
"""
Add a row of data to the current widget
:param data: a row of data
:return: None
"""
# validation
if self.headers:
if len(self.headers) != len(data):
raise ValueError
if len(data) != self.num... | 0.002717 |
def update_properties_cache(sender, instance, action, reverse, model, pk_set, **kwargs):
"Property cache actualization at POI save. It will not work yet after property removal."
if action == 'post_add':
instance.save_properties_cache() | 0.011952 |
def get_pod_for_build(self, build_id):
"""
:return: PodResponse object for pod relating to the build
"""
pods = self.os.list_pods(label='openshift.io/build.name=%s' % build_id)
serialized_response = pods.json()
pod_list = [PodResponse(pod) for pod in serialized_response["... | 0.003419 |
def read_configuration(config='DEFAULT'):
"""
Read LAtools configuration file, and return parameters as dict.
"""
# read configuration file
_, conf = read_latoolscfg()
# if 'DEFAULT', check which is the default configuration
if config == 'DEFAULT':
config = conf['DEFAULT']['config']
... | 0.002141 |
def validate(self, value, redis):
''' hash passwords given via http '''
value = super().validate(value, redis)
if is_hashed(value):
return value
return make_password(value) | 0.009174 |
def _lexsorted_specs(self, order):
"""
A lexsort is specified using normal key string prefixed by '+'
(for ascending) or '-' for (for descending).
Note that in Python 2, if a key is missing, None is returned
(smallest Python value). In Python 3, an Exception will be
rais... | 0.003009 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.