text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _notify_change(self):
""" After all changes have settled, tell Java it changed """
d = self.declaration
self._notify_count -= 1
if self._notify_count == 0:
#: Tell the UI we made changes
self.adapter.notifyDataSetChanged(now=True)
self.get_context(... | 0.005249 |
def is_list_of_list(item):
"""
check whether the item is list (tuple)
and consist of list (tuple) elements
"""
if (
type(item) in (list, tuple)
and len(item)
and isinstance(item[0], (list, tuple))
):
return True
return False | 0.003521 |
def res(self):
"""Get all target values found and corresponding parametes."""
params = [dict(zip(self.keys, p)) for p in self.params]
return [
{"target": target, "params": param}
for target, param in zip(self.target, params)
] | 0.007067 |
def get_logger(level=None, name=None, filename=None):
"""
Create a logger or return the current one if already instantiated.
Parameters
----------
level : int
one of the logger.level constants
name : string
name of the logger
filename : string
name of the log file
... | 0.002083 |
def step(self, actions):
"""Makes a step in all environments.
Does any preprocessing and records frames.
Args:
actions: Batch of actions.
Returns:
(obs, rewards, dones) - batches of observations, rewards and done flags
respectively.
Raises:
ValueError: when the data for c... | 0.005852 |
def _dopost(url, params=None, payload=None, progress_cb=None):
"""Do a HTTP post to upload some data. If progress_cb is not None, it
should be a callable which takes two arguments: the total number of bytes
to upload and the number of bytes which have been uploaded. The callable is
called periodically t... | 0.001829 |
def items(self):
"""
A generator yielding ``(key, value)`` attribute pairs, sorted by key name.
"""
for key in sorted(self.attrs):
yield key, self.attrs[key] | 0.014925 |
def plot_divers(self, iabscissa=1, foffset=1e-19):
"""plot fitness, sigma, axis ratio...
:param iabscissa: 0 means vs evaluations, 1 means vs iterations
:param foffset: added to f-value
:See: `plot()`
"""
from matplotlib.pyplot import semilogy, hold, grid, \
... | 0.003257 |
def mapping_match(uri, mapping):
"""Determine whether the given URI matches one of the given mappings.
Returns True if a match was found, False otherwise.
"""
try:
val = mapping_get(uri, mapping)
return True
except KeyError:
return False | 0.003534 |
def set_var_log_arr(self, value):
''' setter '''
if isinstance(value, np.ndarray):
self.__var_log_arr = value
else:
raise TypeError() | 0.01105 |
def create_img():
"""Creates an image, as a `peri.util.Image`, which is similar
to the image in the tutorial"""
# 1. particles + coverslip
rad = 0.5 * np.random.randn(POS.shape[0]) + 4.5 # 4.5 +- 0.5 px particles
part = objs.PlatonicSpheresCollection(POS, rad, zscale=0.89)
slab = objs.Slab(zpos... | 0.009242 |
def check_passwd(guess, passwd):
"""
Tests to see if the guess, after salting and hashing, matches the
passwd from the database.
@param guess: incoming password trying to be used for authentication
@param passwd: already encrypted password from the database
@returns: boolean
"""
m = sh... | 0.001767 |
def getservers(self, vhost = None):
'''
Return current servers
:param vhost: return only servers of vhost if specified. '' to return only default servers.
None for all servers.
'''
if vhost is not None:
return [s for s in self.connection... | 0.014742 |
def _recv(self, rm_colon=False, blocking=True,
expected_replies=None, default_rvalue=[''],
ignore_unexpected_replies=True, rm_first=True, recur_limit=10):
"""
Receives and processes an IRC protocol message.
Optional arguments:
* rm_colon=False - If True:
... | 0.00399 |
def setLevel(self, level):
r"""Overrides the parent method to adapt the formatting string to the level.
Parameters
----------
level : int
The new log level to set. See the logging levels in the logging module for details.
Examples
-------... | 0.013655 |
def from_str(cls, version_str: str):
"""
Alternate constructor that accepts a string SemVer.
"""
o = cls()
o.version = version_str
return o | 0.010695 |
def cli(env):
"""Server order options for a given chassis."""
hardware_manager = hardware.HardwareManager(env.client)
options = hardware_manager.get_create_options()
tables = []
# Datacenters
dc_table = formatting.Table(['datacenter', 'value'])
dc_table.sortby = 'value'
for location i... | 0.000668 |
def parse_bulk_delete(prs, conn):
"""Delete bulk_records.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_delete = prs.add_parser(
'bulk_delete', help='delete bulk records of specific zone')
set_option(prs_delete, 'infile')
... | 0.001938 |
def get_overlapping_ranges(self, collection_link, partition_key_ranges):
'''
Given a partition key range and a collection,
returns the list of overlapping partition key ranges
:param str collection_link:
The name of the collection.
:param list partition_key_... | 0.011628 |
def _set_extended(self, v, load=False):
"""
Setter method for extended, mapped from YANG variable /overlay/access_list/type/vxlan/extended (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_extended is considered as a private
method. Backends looking to populate ... | 0.004061 |
def next_offsets(self):
# type: (Descriptor) -> Offsets
"""Retrieve the next offsets
:param Descriptor self: this
:rtype: Offsets
:return: download offsets
"""
resume_bytes = self._resume()
with self._meta_lock:
if self._chunk_num >= self._tota... | 0.002593 |
def get_port_profile_status_output_port_profile_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_status = ET.Element("get_port_profile_status")
config = get_port_profile_status
output = ET.SubElement(get_port_profile_status, ... | 0.003503 |
def add(message, level=0, user=None, message_short=None,log_file_name='%s/pyscada_daemon.log' % settings.BASE_DIR,):
"""
add a new massage/error notice to the log
<0 - Debug
1 - Emergency
2 - Critical
3 - Errors
4 - Alerts
5 - Warnings
6 - Notification (webnotice)
7 - Information... | 0.011657 |
def add_to_public_members(self, public_member):
"""
:calls: `PUT /orgs/:org/public_members/:user <http://developer.github.com/v3/orgs/members>`_
:param public_member: :class:`github.NamedUser.NamedUser`
:rtype: None
"""
assert isinstance(public_member, github.NamedUser.Na... | 0.007984 |
def staged_predict_proba(self, test_data):
"""
Predict class probabilities at each stage of an H2O Model (only GBM models).
The output structure is analogous to the output of function predict_leaf_node_assignment. For each tree t and
class c there will be a column Tt.Cc (eg. T3.C1 for t... | 0.0092 |
def _update_physical_disk_details(raid_config, server):
"""Adds the physical disk details to the RAID configuration passed."""
raid_config['physical_disks'] = []
physical_drives = server.get_physical_drives()
for physical_drive in physical_drives:
physical_drive_dict = physical_drive.get_physica... | 0.0025 |
def _runAuction(self, gteeOfferPrice, gteeBidPrice, haveQ):
""" Clears an auction to determine the quantity and price for each
offer/bid.
"""
pOffers = [offer for offer in self.offers if not offer.reactive]
pBids = [bid for bid in self.bids if not bid.reactive]
# Cle... | 0.002933 |
def find_django_migrations_module(module_name):
""" Tries to locate <module_name>.migrations_django (without actually importing it).
Appends either ".migrations_django" or ".migrations" to module_name.
For details why:
https://docs.djangoproject.com/en/1.7/topics/migrations/#libraries-third-party-apps... | 0.003115 |
def get_content(self, force_download=False):
""" Retrieve the content for this Document from the server
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: String
:returns: the content data... | 0.004292 |
def unzip_from_uri(uri, layer_zip_path, unzip_output_dir, progressbar_label):
"""
Download the LayerVersion Zip to the Layer Pkg Cache
Parameters
----------
uri str
Uri to download from
layer_zip_path str
Path to where the content from the uri should be downloaded to
unzip_o... | 0.00327 |
def run_main():
"""run_main
Get Splunk Service Token
"""
parser = argparse.ArgumentParser(
description=(
'AntiNex - '
'Get Token from Splunk'))
parser.add_argument(
'-u',
help='username',
required=False,
de... | 0.000242 |
async def _fair_get_in_peer(self):
"""
Get the first available available inbound peer in a fair manner.
:returns: A `Peer` inbox, whose inbox is guaranteed not to be
empty (and thus can be read from without blocking).
"""
peer = None
while not peer:
... | 0.001483 |
def _get_macd(df):
""" Moving Average Convergence Divergence
This function will initialize all following columns.
MACD Line (macd): (12-day EMA - 26-day EMA)
Signal Line (macds): 9-day EMA of MACD Line
MACD Histogram (macdh): MACD Line - Signal Line
:param df: d... | 0.002567 |
def get_objective_admin_session_for_objective_bank(self, objective_bank_id):
"""Gets the ``OsidSession`` associated with the objective admin service for the given objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` of the
objective bank
return: (osid.learning.Obje... | 0.004108 |
def pd_plot_data(self):
"""
Plot data for phase diagram.
2-comp - Full hull with energies
3/4-comp - Projection into 2D or 3D Gibbs triangle.
Returns:
(lines, stable_entries, unstable_entries):
- lines is a list of list of coordinates for lines in the PD.... | 0.000819 |
def _read_interleaved(self, f, data_objects):
"""Read interleaved data that doesn't have a numpy type"""
log.debug("Reading interleaved data point by point")
object_data = {}
points_added = {}
for obj in data_objects:
object_data[obj.path] = obj._new_segment_data()
... | 0.002448 |
async def listWorkers(self, *args, **kwargs):
"""
Get a list of all active workers of a workerType
Get a list of all active workers of a workerType.
`listWorkers` allows a response to be filtered by quarantined and non quarantined workers.
To filter the query, you should call t... | 0.008412 |
def _get_json(self,
path,
params=None,
base=JIRA_BASE_URL,
):
"""Get the json for a given path and params.
:param path: The subpath required
:type path: str
:param params: Parameters to filter the json query.
... | 0.007491 |
def stream(self, opNames=[], *args, **kwargs):
""" Yield specific operations (e.g. comments) only
:param array opNames: List of operations to filter for
:param int start: Start at this block
:param int stop: Stop at this block
:param str mode: We here have the ch... | 0.001787 |
def periodic_corr1d(sp_reference, sp_offset,
fminmax=None,
naround_zero=None,
norm_spectra=False,
plottitle=None,
pdf=None,
debugplot=0):
"""Periodic correlation between two spectra, implemented u... | 0.00012 |
def ed25519_public_key_from_string(string):
"""Create an ed25519 public key from ``string``, which is a seed.
Args:
string (str): the string to use as a seed.
Returns:
Ed25519PublicKey: the public key
"""
try:
return Ed25519PublicKey.from_public_bytes(
base64.b... | 0.00404 |
def apply(query, collection=None):
"""Enhance the query restricting not permitted collections.
Get the permitted restricted collection for the current user from the
user_info object and all the restriced collections from the
restricted_collection_cache.
"""
if not collection:
return que... | 0.002421 |
def get(*dataset, **kwargs):
'''
Displays properties for the given datasets.
dataset : string
name of snapshot(s), filesystem(s), or volume(s)
properties : string
comma-separated list of properties to list, defaults to all
recursive : boolean
recursively list children
de... | 0.002222 |
def save_results(self, output_dir='.', prefix='', prefix_sep='_',
image_list=None):
""" Write out any images generated by the meta-analysis.
Args:
output_dir (str): folder to write images to
prefix (str): all image files will be prepended with this string
... | 0.002732 |
def symorth(S):
"Symmetric orthogonalization"
E,U = np.linalg.eigh(S)
n = len(E)
Shalf = np.identity(n,'d')
for i in range(n):
Shalf[i,i] /= np.sqrt(E[i])
return simx(Shalf,U,True) | 0.028302 |
def from_native(cls, t):
""" Convert from a native Python `datetime.time` value.
"""
second = (1000000 * t.second + t.microsecond) / 1000000
return Time(t.hour, t.minute, second, t.tzinfo) | 0.009091 |
def power_off(self, si, logger, session, vcenter_data_model, vm_uuid, resource_fullname):
"""
Power off of a vm
:param vcenter_data_model: vcenter model
:param si: Service Instance
:param logger:
:param session:
:param vcenter_data_model: vcenter_data_model
... | 0.006101 |
def signal_optimiser(self, analytes, min_points=5,
threshold_mode='kde_first_max',
threshold_mult=1., x_bias=0,
weights=None, filt=True, mode='minimise'):
"""
Optimise data selection based on specified analytes.
Identifi... | 0.005644 |
def users(self, params):
"""
This is a private API and requires whitelisting from Twitter.
This endpoint will allow partners to add, update and remove users from a given
tailored_audience_id.
The endpoint will also accept multiple user identifier types per user as well.
... | 0.005821 |
def convert(self, element):
"""Convert an element to a chainlink"""
if isinstance(element, self.base_link_type):
return element
for converter in self.converters:
link = converter(element)
if link is not NotImplemented:
return link
raise... | 0.005249 |
def counter(self, position=None, **kwargs):
"""
Args:
position(int): Line number counting from the bottom of the screen
kwargs(dict): Any additional :py:term:`keyword arguments<keyword argument>`
are passed to :py:class:`Counter`
Returns:
:py:... | 0.003507 |
def get_distance(
self, l_motor: float, r_motor: float, tm_diff: float
) -> typing.Tuple[float, float]:
"""
Given motor values and the amount of time elapsed since this was last
called, retrieves the x,y,angle that the robot has moved. Pass these
values to :meth:`... | 0.004203 |
def generate_local_url(self, js_name):
"""
Generate the local url for a js file.
:param js_name:
:return:
"""
host = self._settings['local_host'].format(**self._host_context).rstrip('/')
return '{}/{}.js'.format(host, js_name) | 0.010638 |
def copyTargets(self, arr):
"""
Copies the targets of the argument array into the self.target attribute.
"""
array = Numeric.array(arr)
if not len(array) == self.size:
raise LayerError('Mismatched target size and layer size in call to copyTargets()', \
... | 0.009982 |
def users_profile_get(self, **kwargs) -> SlackResponse:
"""Retrieves a user's profile information."""
self._validate_xoxp_token()
return self.api_call("users.profile.get", http_verb="GET", params=kwargs) | 0.013216 |
def rgb_to_vector(image):
"""
Convert an RGB ANTsImage to a Vector ANTsImage
Arguments
---------
image : ANTsImage
RGB image to be converted
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni_rg... | 0.003708 |
def insert(self, val):
"""\
Inserts a value and returns a :class:`Pair <Pair>`.
If the generated key exists or memcache cannot store it, a
:class:`KeyInsertError <shorten.KeyInsertError>` is raised (or a
:class:`TokenInsertError <shorten.TokenInsertError>` if a token
exists or... | 0.020525 |
def combine_hex(data):
''' Combine list of integer values to one big integer '''
output = 0x00
for i, value in enumerate(reversed(data)):
output |= (value << i * 8)
return output | 0.00495 |
def distribute_javaclasses(self, javaclass_dir, dest_dir="src"):
'''Copy existing javaclasses from build dir to current dist dir.'''
info('Copying java files')
ensure_dir(dest_dir)
for filename in glob.glob(javaclass_dir):
shprint(sh.cp, '-a', filename, dest_dir) | 0.006515 |
def scan(self, search_path=None):
"""Scan `search_path` for distributions usable in this environment
Any distributions found are added to the environment.
`search_path` should be a sequence of ``sys.path`` items. If not
supplied, ``sys.path`` is used. Only distributions conforming to
... | 0.003413 |
def remove(self, fieldspec):
"""
Removes fields or subfields according to `fieldspec`.
If a non-control field subfield removal leaves no other subfields,
delete the field entirely.
"""
pattern = r'(?P<field>[^.]+)(.(?P<subfield>[^.]+))?'
match = re.match(pattern... | 0.001934 |
def mask_xdata_with_shape(self, shape: DataAndMetadata.ShapeType) -> DataAndMetadata.DataAndMetadata:
"""Return the mask created by this graphic as extended data.
.. versionadded:: 1.0
Scriptable: Yes
"""
mask = self._graphic.get_mask(shape)
return DataAndMetadata.DataA... | 0.008671 |
def traverse_dict_and_list(data, key, default=None, delimiter=DEFAULT_TARGET_DELIM):
'''
Traverse a dict or list using a colon-delimited (or otherwise delimited,
using the 'delimiter' param) target string. The target 'foo:bar:0' will
return data['foo']['bar'][0] if this value exists, and will otherwise
... | 0.001244 |
def filter_query(key, expression):
"""Filter documents with a key that satisfies an expression."""
if (isinstance(expression, dict)
and len(expression) == 1
and list(expression.keys())[0].startswith('$')):
compiled_expression = compile_query(expression)
elif callable(expressi... | 0.001129 |
def show_inventory(self, pretty=False):
"""
Satisfies the ``--list`` portion of ansible's external inventory API.
Allows ``bang`` to be used as an external inventory script, for example
when running ad-hoc ops tasks. For more details, see:
http://ansible.cc/docs/api.html#extern... | 0.002918 |
def filter(self, f: Callable[[A], B]) -> 'List[T]':
"""doufo.List.filter: filter this `List` obj with input `f` function
Args:
`self`:
f (`Callable[[A],B]`): function that tells `True` or `False`
Returns:
return (`List[T]`): Filtered List
R... | 0.01995 |
def get_default_classes(self):
"""Returns a list of the default classes for the tab.
Defaults to and empty list (``[]``), however additional classes may
be added depending on the state of the tab as follows:
If the tab is the active tab for the tab group, in which
the class ``"... | 0.002751 |
def _native_size(self):
"""
A (width, height) 2-tuple representing the native dimensions of the
image in EMU, calculated based on the image DPI value, if present,
assuming 72 dpi as a default.
"""
EMU_PER_INCH = 914400
horz_dpi, vert_dpi = self._dpi
width_... | 0.004132 |
def vgremove(vgname):
'''
Remove an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgremove vgname
salt mymachine lvm.vgremove vgname force=True
'''
cmd = ['vgremove', '-f', vgname]
out = __salt__['cmd.run'](cmd, python_shell=False)
return out.s... | 0.003067 |
def _reg_sighandlers(self):
""" Registers signal handlers to this class.
"""
# SIGCHLD, so we shutdown when any of the child processes exit
_handler = lambda signo, frame: self.shutdown()
signal.signal(signal.SIGCHLD, _handler)
signal.signal(signal.SIGTERM, _handler) | 0.009375 |
def bulk_update(cls, files, api=None):
"""
This call updates the details for multiple specified files.
Use this call to set new information for the files, thus replacing
all existing information and erasing omitted parameters. For each
of the specified files, the call sets a new ... | 0.00184 |
def get_unique_constraints(self, connection, table_name,
schema=None, **kw):
"""
Return information about unique constraints in `table_name`.
Overrides interface
:meth:`~sqlalchemy.engine.interfaces.Dialect.get_unique_constraints`.
"""
cons... | 0.003367 |
def longest_run(da, dim='time'):
"""Return the length of the longest consecutive run of True values.
Parameters
----------
arr : N-dimensional array (boolean)
Input array
dim : Xarray dimension (default = 'time')
Dimension along which to calculate consecutive run... | 0.001862 |
def split_page_artid(page_artid):
"""Split page_artid into page_start/end and artid."""
page_start = None
page_end = None
artid = None
if not page_artid:
return None, None, None
# normalize unicode dashes
page_artid = unidecode(six.text_type(page_artid))
if '-' in page_artid:
... | 0.001014 |
def _results(self, scheduler_instance_id):
"""Get the results of the executed actions for the scheduler which instance id is provided
Calling this method for daemons that are not configured as passive do not make sense.
Indeed, this service should only be exposed on poller and reactionner daemo... | 0.007825 |
def init_app(state):
"""
Prepare the Flask application for Flask-Split.
:param state: :class:`BlueprintSetupState` instance
"""
app = state.app
app.config.setdefault('SPLIT_ALLOW_MULTIPLE_EXPERIMENTS', False)
app.config.setdefault('SPLIT_DB_FAILOVER', False)
app.config.setdefault('SPLI... | 0.001018 |
def filter_for_probability(key: str, population: Union[pd.DataFrame, pd.Series, Index],
probability: Array, index_map: IndexMap=None) -> Union[pd.DataFrame, pd.Series, Index]:
"""Decide an event outcome for each individual in a population from probabilities.
Given a population or its... | 0.005141 |
def resolve_extensions(bot: commands.Bot, name: str) -> list:
"""
Tries to resolve extension queries into a list of extension names.
"""
if name.endswith('.*'):
module_parts = name[:-2].split('.')
path = pathlib.Path(module_parts.pop(0))
for part in module_parts:
pa... | 0.002174 |
def get_plugin_client_settings(self):
settings = {}
user_path = self.get_plugin_settings_path("User")
def_path = self.get_plugin_settings_path("MavensMate")
'''
if the default path for settings is none, we're either dealing with a bad client setup or
a new client... | 0.009881 |
def validate(self, value):
"""
Validate the I{value} is of the correct class.
@param value: The value to validate.
@type value: any
@raise AttributeError: When I{value} is invalid.
"""
if value is None:
return
if len(self.classes) and not isins... | 0.004444 |
def random_markov_chain(n, k=None, sparse=False, random_state=None):
"""
Return a randomly sampled MarkovChain instance with n states, where
each state has k states with positive transition probability.
Parameters
----------
n : scalar(int)
Number of states.
k : scalar(int), option... | 0.000631 |
def _validate_params(self):
"""
method to sanitize model parameters
Parameters
---------
None
Returns
-------
None
"""
self.distribution = NormalDist(scale=self.scale)
super(LinearGAM, self)._validate_params() | 0.006689 |
def build_overviews(source_file, factors=None, minsize=256, external=False,
blocksize=256, interleave='pixel', compress='lzw',
resampling=Resampling.gauss, **kwargs):
"""Build overviews at one or more decimation factors for all
bands of the dataset.
Parameters
--... | 0.001561 |
def add_layer2image(grid2d, x_pos, y_pos, kernel, order=1):
"""
adds a kernel on the grid2d image at position x_pos, y_pos with an interpolated subgrid pixel shift of order=order
:param grid2d: 2d pixel grid (i.e. image)
:param x_pos: x-position center (pixel coordinate) of the layer to be added
:pa... | 0.003492 |
def blueprint(self):
"""The name of the current blueprint"""
if self.url_rule and '.' in self.url_rule.endpoint:
return self.url_rule.endpoint.rsplit('.', 1)[0] | 0.010638 |
def to_dict(self):
"""Create a dict representation of this exception.
:return: The dictionary representation.
:rtype: dict
"""
rv = dict(self.payload or ())
rv["message"] = self.message
return rv | 0.007905 |
def _parse_east_asian(fname, properties=(u'W', u'F',)):
"""Parse unicode east-asian width tables."""
version, date, values = None, None, []
print("parsing {} ..".format(fname))
for line in open(fname, 'rb'):
uline = line.decode('utf-8')
if version is None:
... | 0.002035 |
def is_address_in_network(ip, net):
"""Is an address in a network"""
# http://stackoverflow.com/questions/819355/how-can-i-check-if-an-ip-is-in-a-network-in-python
import socket
import struct
ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
netaddr, bits = net.split('/')
if int(bits) ==... | 0.002053 |
def register_socket(self, socket):
"""Registers the given socket(s) for further use.
:param Socket|list[Socket] socket: Socket type object. See ``.sockets``.
"""
sockets = self._sockets
for socket in listify(socket):
uses_shared = isinstance(socket.address, Socket... | 0.003322 |
def _drain(writer, ion_event):
"""Drain the writer of its pending write events.
Args:
writer (Coroutine): A writer co-routine.
ion_event (amazon.ion.core.IonEvent): The first event to apply to the writer.
Yields:
DataEvent: Yields each pending data event.
"""
result_event =... | 0.003937 |
def mag_calibration(self):
"""Perform magnetometer calibration for current IMU."""
self.calibration_state = self.CAL_MAG
self.mag_dialog = SK8MagDialog(self.sk8.get_imu(self.spinIMU.value()), self)
if self.mag_dialog.exec_() == QDialog.Rejected:
return
self.calculate... | 0.00831 |
def parse_masked_phone_number(html, parser=None):
"""Get masked phone number from security check html
:param html: str: raw html text
:param parser: bs4.BeautifulSoup: html parser
:return: tuple of phone prefix and suffix, for example: ('+1234', '89')
:rtype : tuple
"""
if parser is None:
... | 0.00141 |
def split_string(x: str, n: int) -> List[str]:
"""
Split string into chunks of length n
"""
# https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa
return [x[i:i+n] for i in range(0, len(x), n)] | 0.004082 |
def get_nodes_with_recipe(recipe_name, environment=None):
"""Get all nodes which include a given recipe,
prefix-searches are also supported
"""
prefix_search = recipe_name.endswith("*")
if prefix_search:
recipe_name = recipe_name.rstrip("*")
for n in get_nodes(environment):
reci... | 0.001513 |
def append(self, child, *args, **kwargs):
"""See :meth:`AbstractElement.append`"""
#if no set is associated with the layer yet, we learn it from span annotation elements that are added
if self.set is False or self.set is None:
if inspect.isclass(child):
if issubclass(... | 0.010368 |
def lambda_handler(event, context):
'''A Python AWS Lambda function to process aggregated records sent to KinesisAnalytics.'''
raw_kpl_records = event['records']
output = [process_kpl_record(kpl_record) for kpl_record in raw_kpl_records]
# Print number of successful and failed records.
success_coun... | 0.006452 |
def parse_bookmark_data (data):
"""Parse data string.
Return iterator for bookmarks of the form (url, name).
Bookmarks are not sorted.
"""
for url, name in parse_bookmark_json(json.loads(data)):
yield url, name | 0.008403 |
def fixup_ins_del_tags(html):
""" Given an html string, move any <ins> or <del> tags inside of any
block-level elements, e.g. transform <ins><p>word</p></ins> to
<p><ins>word</ins></p> """
doc = parse_html(html, cleanup=False)
_fixup_ins_del_tags(doc)
html = serialize_html_fragment(doc, skip_out... | 0.002907 |
def create_button_label(icon, font_size=constants.FONT_SIZE_NORMAL):
"""Create a button label with a chosen icon.
:param icon: The icon
:param font_size: The size of the icon
:return: The created label
"""
label = Gtk.Label()
set_label_markup(label, '&#x' + icon + ';', constants.ICON_FONT, ... | 0.002747 |
def is_bbox_not_intersecting(self, other):
"""Returns False iif bounding boxed of self and other intersect"""
self_x_min, self_x_max, self_y_min, self_y_max = self.get_bbox()
other_x_min, other_x_max, other_y_min, other_y_max = other.get_bbox()
return \
self_x_min > other_x... | 0.004444 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.