text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def construct_entry_with_release(focus, issues, manager, log, releases, rest):
"""
Releases 'eat' the entries in their line's list and get added to the
final data structure. They also inform new release-line 'buffers'.
Release lines, once the release obj is removed, should be empty or a
comma-separa... | 0.00016 |
def extract_cosponsors(bill):
"""
Return a list of list relating cosponsors to legislation.
"""
logger.debug("Extracting Cosponsors")
cosponsor_map = []
cosponsors = bill.get('cosponsors', [])
bill_id = bill.get('bill_id', None)
for co in cosponsors:
co_list = []
co_list... | 0.001733 |
def bvlpdu_contents(self, use_dict=None, as_class=dict):
"""Return the contents of an object as a dict."""
return key_value_contents(use_dict=use_dict, as_class=as_class,
key_values=(
('function', 'RegisterForeignDevice'),
('ttl', self.bvlciTimeToLive),
... | 0.009146 |
def uid_gid(user, group, fd=None, path=None):
'''Get uid and gid from either uid/gid, user name/group name, or from the
environment of the calling process, or optionally from an fd, or
optionally from a path'''
type_msg = u'{0} must be a string or integer, not: {1}'
nosuch_msg = u'no such {0}:... | 0.001279 |
def handle_async_gen(gen: Any, gen_obj: Any) -> Any:
"""
处理异步生成器
"""
if gen is None:
return None
if asyncio.iscoroutine(gen):
try:
temp = yield from gen
gen_obj.send(temp)
return
except Exception as error:
try:
g... | 0.001988 |
def _build_arguments(self):
"""
build arguments for command.
"""
self._parser.add_argument(
'image_name',
metavar='IMAGE_NAME',
type=six.text_type,
help='Name of the image example: \"namespace/repository\"'
) | 0.006757 |
def parse_zone(zonefile=None, zone=None):
'''
Parses a zone file. Can be passed raw zone data on the API level.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.parse_zone /var/lib/named/example.com.zone
'''
if zonefile:
try:
with salt.utils.files.fopen(zonefile,... | 0.000375 |
def harmonize_ocean(ocean, elevation, ocean_level):
"""
The goal of this function is to make the ocean floor less noisy.
The underwater erosion should cause the ocean floor to be more uniform
"""
shallow_sea = ocean_level * 0.85
midpoint = shallow_sea / 2.0
ocean_points = numpy.logical_and... | 0.004484 |
def lyap_e_len(**kwargs):
"""
Helper function that calculates the minimum number of data points required
to use lyap_e.
Note that none of the required parameters may be set to None.
Kwargs:
kwargs(dict):
arguments used for lyap_e (required: emb_dim, matrix_dim, min_nb
and min_tsep)
Return... | 0.013825 |
def protege_data(datas_str, sens):
"""
Used to crypt/decrypt data before saving locally.
Override if securit is needed.
bytes -> str when decrypting
str -> bytes when crypting
:param datas_str: When crypting, str. when decrypting bytes
:param sens: True to crypt, False to decrypt
"""
... | 0.004914 |
def flick(self, element, x, y, speed):
"""Deprecated use touch('drag', { fromX, fromY, toX, toY, duration(s) }) instead.
Flick on the touch screen using finger motion events.
This flickcommand starts at a particulat screen location.
Support:
iOS
Args:
... | 0.003831 |
def devid(self):
"""
Two-tuple containing device's vendor ID and model ID (hex).
"""
d = self.device
vend_id = d.get('ID_VENDOR_ID')
model_id = d.get('ID_MODEL_ID')
return (vend_id, model_id) | 0.008097 |
def plot_input(ace_model, fname='ace_input.png'):
"""Plot the transforms."""
if not plt:
raise ImportError('Cannot plot without the matplotlib package')
plt.rcParams.update({'font.size': 8})
plt.figure()
num_cols = len(ace_model.x) / 2 + 1
for i in range(len(ace_model.x)):
plt.su... | 0.001812 |
def pop_loop_instrs(setup_loop_instr, queue):
"""
Determine whether setup_loop_instr is setting up a for-loop or a
while-loop. Then pop the loop instructions from queue.
The easiest way to tell the difference is to look at the target of the
JUMP_ABSOLUTE instruction at the end of the loop. If it ... | 0.000501 |
def items(self):
"""Yield the async reuslts for the context."""
for key, task in self._tasks:
if not (task and task.result):
yield key, None
else:
yield key, json.loads(task.result)["payload"] | 0.007576 |
def on_hazard_exposure_bookmark_toggled(self, enabled):
"""Update the UI when the user toggles the bookmarks radiobutton.
:param enabled: The status of the radiobutton.
:type enabled: bool
"""
if enabled:
self.bookmarks_index_changed()
else:
self.... | 0.005222 |
def is_node_highlighted(graph: BELGraph, node: BaseEntity) -> bool:
"""Returns if the given node is highlighted.
:param graph: A BEL graph
:param node: A BEL node
:type node: tuple
:return: Does the node contain highlight information?
:rtype: bool
"""
return NODE_HIGHLIGHT in graph.node... | 0.003067 |
def has_logs(self):
"""
Check if log files are available and return file names if they exist.
:return: list
"""
found_files = []
if self.logpath is None:
return found_files
if os.path.exists(self.logpath):
for root, _, files in os.walk(os.... | 0.004219 |
def _validate_hands(hands, missing):
'''
Validates hands, based on values that
are supposed to be missing from them.
:param list hands: list of Hand objects to validate
:param list missing: list of sets that indicate the values
that are supposed to be missing from
... | 0.001534 |
def set_row_heights(self, pcts=None, amts=None, maxs=None, mins=None):
"""
:param pcts: the percent of available height to use or ratio is also ok
:param amts: (Array or scalar) the fixed height of the rows
:param maxs: (Array or scalar) the maximum height of the rows (only use when pcts... | 0.006543 |
async def get_resources(self, **kwargs) -> dict:
"""Get a list of resources.
:raises PvApiError when an error occurs.
"""
resources = await self.request.get(self._base_path, **kwargs)
self._sanitize_resources(resources)
return resources | 0.007018 |
def preview(self, **query_params):
"""Returns a streaming handle to this job's preview search results.
Unlike :class:`splunklib.results.ResultsReader`, which requires a job to
be finished to
return any results, the ``preview`` method returns any results that have
been generated ... | 0.002826 |
def message(self):
'the standard message which can be transfer'
return {
'source':
'account',
'frequence':
self.frequence,
'account_cookie':
self.account_cookie,
'portfolio_cookie':
self.portfolio_cookie,
... | 0.001122 |
def rsem_stats_table(self):
""" Take the parsed stats from the rsem report and add them to the
basic stats table at the top of the report """
headers = OrderedDict()
headers['alignable_percent'] = {
'title': '% Alignable'.format(config.read_count_prefix),
'descrip... | 0.003597 |
def enable_autozoom(self, option):
"""Set ``autozoom`` behavior.
Parameters
----------
option : {'on', 'override', 'once', 'off'}
Option for zoom behavior. A list of acceptable options can
also be obtained by :meth:`get_autozoom_options`.
Raises
... | 0.003086 |
def classical(group, src_filter, gsims, param, monitor=Monitor()):
"""
Compute the hazard curves for a set of sources belonging to the same
tectonic region type for all the GSIMs associated to that TRT.
The arguments are the same as in :func:`calc_hazard_curves`, except
for ``gsims``, which is a lis... | 0.000264 |
def make_parser():
"""
Create a parser which is suitably configured for parsing an XMPP XML
stream. It comes equipped with :class:`XMPPLexicalHandler`.
"""
p = xml.sax.make_parser()
p.setFeature(xml.sax.handler.feature_namespaces, True)
p.setFeature(xml.sax.handler.feature_external_ges, Fals... | 0.002309 |
def tail(self, path, tail_length=1024, append=False):
# Note: append is currently not implemented.
''' Show the end of the file - default 1KB, supports up to the Hadoop block size.
:param path: Path to read
:type path: string
:param tail_length: The length to read from the end o... | 0.008227 |
def create_eager_metrics(metric_names, weights_fn=common_layers.weights_all):
"""Create metrics accumulators and averager for Eager mode.
Args:
metric_names: list<str> from Metrics enum
weights_fn: function that takes labels and returns a weights mask. Defaults
to weights of all 1, i.e. common_layers... | 0.006033 |
def to_array(self):
"""
Convert the RiakLinkPhase to a format that can be output into
JSON. Used internally.
"""
stepdef = {'bucket': self._bucket,
'tag': self._tag,
'keep': self._keep}
return {'link': stepdef} | 0.006757 |
def androlyze_main(session, filename):
"""
Start an interactive shell
:param session: Session file to load
:param filename: File to analyze, can be APK or DEX (or ODEX)
"""
from androguard.core.androconf import ANDROGUARD_VERSION, CONF
from IPython.terminal.embed import InteractiveShellEmbe... | 0.000881 |
def _select_theory(theories):
"""Return the most likely spacing convention given different options.
Given a dictionary of convention options as keys and their occurrence
as values, return the convention that occurs the most, or ``None`` if
there is no clear preferred style.
"""
... | 0.003527 |
def _cluster_by(end_iter, attr1, attr2, cluster_distance):
"""Cluster breakends by specified attributes.
"""
ClusterInfo = namedtuple("ClusterInfo", ["chroms", "clusters", "lookup"])
chr_clusters = {}
chroms = []
brends_by_id = {}
for brend in end_iter:
if not chr_clusters.has_key(br... | 0.002703 |
def add_to_item_list_by_name(self, item_urls, item_list_name):
""" Instruct the server to add the given items to the specified
Item List (which will be created if it does not already exist)
:type item_urls: List or ItemGroup
:param item_urls: List of URLs for the items to add,
... | 0.00227 |
def fit_select_best(X, y):
"""
Selects the best fit of the estimators already implemented by choosing the
model with the smallest mean square error metric for the trained values.
"""
models = [fit(X,y) for fit in [fit_linear, fit_quadratic]]
errors = map(lambda model: mse(y, model.predict(X)), m... | 0.005195 |
def user_absent(name):
'''
Ensure a user is not present
name
username to remove if it exists
Examples:
.. code-block:: yaml
delete:
onyx.user_absent:
- name: daniel
'''
ret = {'name': name,
'result': False,
'changes': {},
... | 0.000933 |
def add_step(self, step):
"""
Adds a new step to the waterfall.
:param step: Step to add
:return: Waterfall dialog for fluent calls to `add_step()`.
"""
if not step:
raise TypeError('WaterfallDialog.add_step(): step cannot be None.')
self.... | 0.008357 |
def maybe_call_fn_and_grads(fn,
fn_arg_list,
result=None,
grads=None,
check_non_none_grads=True,
name=None):
"""Calls `fn` and computes the gradient of the result wrt `args_list`... | 0.005431 |
def _estimate_bkg_rms(self, xmin, xmax, ymin, ymax):
"""
Estimate the background noise mean and RMS.
The mean is estimated as the median of data.
The RMS is estimated as the IQR of data / 1.34896.
Parameters
----------
xmin, xmax, ymin, ymax : int
The... | 0.001663 |
def logout_allowed(service):
"""Check if a given service identifier should be sent a logout request."""
if hasattr(settings, 'MAMA_CAS_SERVICES'):
return _is_allowed('logout_allowed', service)
if hasattr(settings, 'MAMA_CAS_ENABLE_SINGLE_SIGN_OUT'):
warnings.warn(
'The MAMA_CAS_... | 0.003824 |
def _get_trusted_comma(self, trusted, value):
"""Get the real value from a comma-separated header based on the
configured number of trusted proxies.
:param trusted: Number of values to trust in the header.
:param value: Header value to parse.
:return: The real value, or ``None``... | 0.003231 |
def clean():
"""Cleans up temporary resources
Tries to clean up:
1. The temporary update branch used during ``temple update``
2. The primary update branch used during ``temple update``
"""
temple.check.in_git_repo()
current_branch = _get_current_branch()
update_branch = temple.constan... | 0.00216 |
def get_condition(self, condition_id):
"""Retrieve the condition for a condition_id.
:param condition_id: id of the condition, str
:return:
"""
condition = self.contract_concise.getCondition(condition_id)
if condition and len(condition) == 7:
return Condition... | 0.005571 |
def end_grouping(self):
"""
Raises IndexError when no group is open.
"""
close = self._open.pop()
if not close:
return
if self._open:
self._open[-1].extend(close)
elif self._undoing:
self._redo.append(close)
else:
... | 0.005376 |
def legislator_vote_value(self):
'''If this vote was accessed through the legislator.votes_manager,
return the value of this legislator's vote.
'''
if not hasattr(self, 'legislator'):
msg = ('legislator_vote_value can only be called '
'from a vote accessed ... | 0.003466 |
def restore(self):
"""Restore the saved value for the attribute of the object."""
if self.proxy_object is None:
if self.getter:
setattr(self.getter_class, self.attr_name, self.getter)
elif self.is_local:
setattr(self.orig_object, self.attr_name, se... | 0.003215 |
def globals(self):
"""Iterates over the defined Globals."""
defglobal = lib.EnvGetNextDefglobal(self._env, ffi.NULL)
while defglobal != ffi.NULL:
yield Global(self._env, defglobal)
defglobal = lib.EnvGetNextDefglobal(self._env, defglobal) | 0.006944 |
def get_file_by_id(self, file_id):
"""
Get folder details for a file id.
:param file_id: str: uuid of the file
:return: File
"""
return self._create_item_response(
self.data_service.get_file(file_id),
File
) | 0.006969 |
def ReqConnect(self, pAddress: str):
"""连接行情前置
:param pAddress:
"""
self.q.CreateApi()
spi = self.q.CreateSpi()
self.q.RegisterSpi(spi)
self.q.OnFrontConnected = self._OnFrontConnected
self.q.OnFrontDisconnected = self._OnFrontDisConnected
self.q... | 0.003509 |
def dns_encode(x, check_built=False):
"""Encodes a bytes string into the DNS format
:param x: the string
:param check_built: detect already-built strings and ignore them
:returns: the encoded bytes string
"""
if not x or x == b".":
return b"\x00"
if check_built and b"." not in x an... | 0.001475 |
def sign(self, data: bytes, v: int = 27) -> Signature:
""" Sign data hash with local private key """
assert v in (0, 27), 'Raiden is only signing messages with v in (0, 27)'
_hash = eth_sign_sha3(data)
signature = self.private_key.sign_msg_hash(message_hash=_hash)
sig_bytes = sig... | 0.007009 |
def add_client(self, client_identifier):
"""Add a client."""
if client_identifier in self.clients:
_LOGGER.error('%s already in group %s', client_identifier, self.identifier)
return
new_clients = self.clients
new_clients.append(client_identifier)
yield fro... | 0.005607 |
def determine_apache_port(public_port, singlenode_mode=False):
'''
Description: Determine correct apache listening port based on public IP +
state of the cluster.
public_port: int: standard public port for given service
singlenode_mode: boolean: Shuffle ports when only a single unit is present
... | 0.001845 |
def is_scipy_sparse(arr):
"""
Check whether an array-like is a scipy.sparse.spmatrix instance.
Parameters
----------
arr : array-like
The array-like to check.
Returns
-------
boolean
Whether or not the array-like is a scipy.sparse.spmatrix instance.
Notes
-----... | 0.002222 |
def set_log_level(log_level):
"""
Set logging level of this module. Using
`logbook <https://logbook.readthedocs.io/en/stable/>`__ module for logging.
:param int log_level:
One of the log level of
`logbook <https://logbook.readthedocs.io/en/stable/api/base.html>`__.
Disabled logg... | 0.001057 |
def crs(self, crs):
"""Setter for extent_crs property.
:param crs: The coordinate reference system for the analysis boundary.
:type crs: QgsCoordinateReferenceSystem
"""
if isinstance(crs, QgsCoordinateReferenceSystem):
self._crs = crs
self._is_ready = Fa... | 0.004843 |
def retrieve_info(self):
"""Query Bugzilla API to retrieve the needed infos."""
scheme = urlparse(self.url).scheme
netloc = urlparse(self.url).netloc
query = urlparse(self.url).query
if scheme not in ('http', 'https'):
return
for item in query.split('&'):
... | 0.001134 |
def annotation_spec_path(cls, project, location, dataset, annotation_spec):
"""Return a fully-qualified annotation_spec string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}",
project=... | 0.006772 |
def du(path):
'''
Put it all together!
'''
size, err = calc(path)
if err:
return err
else:
hr, unit = convert(size)
hr = str(hr)
result = hr + " " + unit
return result | 0.004329 |
def load_token(data):
"""Load the oauth2server token from data dump."""
from invenio_oauth2server.models import Token
data['expires'] = iso2dt_or_none(data['expires'])
load_common(Token, data) | 0.004808 |
def _do_magic_import(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr, code, name):
"""
Implements @import for sprite-maps
Imports magic sprite map directories
"""
if callable(STATIC_ROOT):
files = sorted(STATIC_ROOT(name))... | 0.003119 |
def __authorize(self, client_id, client_secret, credit_card_id, **kwargs):
"""Call documentation: `/credit_card/authorize
<https://www.wepay.com/developer/reference/credit_card#authorize>`_,
plus extra keyword parameter:
:keyword bool batch_mode: turn on/off the batch_mode, see ... | 0.005 |
def parametrized_bottleneck(x, hparams):
"""Meta-function calling all the above bottlenecks with hparams."""
if hparams.bottleneck_kind == "tanh_discrete":
d, _ = tanh_discrete_bottleneck(
x, hparams.bottleneck_bits, hparams.bottleneck_noise * 0.5,
hparams.discretize_warmup_steps, hparams.mode)
... | 0.005521 |
def start_rest_api(host, port, connection, timeout, registry,
client_max_size=None):
"""Builds the web app, adds route handlers, and finally starts the app.
"""
loop = asyncio.get_event_loop()
connection.open()
app = web.Application(loop=loop, client_max_size=client_max_size)
... | 0.000513 |
def find_hosted_zone(Id=None, Name=None, PrivateZone=None,
region=None, key=None, keyid=None, profile=None):
'''
Find a hosted zone with the given characteristics.
Id
The unique Zone Identifier for the Hosted Zone. Exclusive with Name.
Name
The domain name associa... | 0.005086 |
def delete(self):
"""Delete this job."""
self.conn.delete(self.jid)
self.reserved = False | 0.017699 |
def setup_server_users(server):
"""
Seeds all users returned by get_seed_users() IF there are no users seed yet
i.e. system.users collection is empty
"""
"""if not should_seed_users(server):
log_verbose("Not seeding users for server '%s'" % server.id)
return"""
log_info("Checkin... | 0.001762 |
def setup_global_logging():
"""
Initializes capture of stdout/stderr, Python warnings, and exceptions;
redirecting them to the loggers for the modules from which they originated.
"""
global global_logging_started
if not PY3K:
sys.exc_clear()
if global_logging_started:
retu... | 0.00083 |
def get_algorithm(self, name):
"""
Gets a single algorithm by its unique name.
:param str name: Either a fully-qualified XTCE name or an alias in the
format ``NAMESPACE/NAME``.
:rtype: .Algorithm
"""
name = adapt_name_for_rest(name)
url =... | 0.00367 |
def _dump_multipoint(obj, decimals):
"""
Dump a GeoJSON-like MultiPoint object to WKT.
Input parameters and return value are the MULTIPOINT equivalent to
:func:`_dump_point`.
"""
coords = obj['coordinates']
mp = 'MULTIPOINT (%s)'
points = (' '.join(_round_and_pad(c, decimals)
... | 0.002062 |
async def close(self):
"""
Terminate the ICE agent, ending ICE processing and streams.
"""
if self.__isClosed:
return
self.__isClosed = True
self.__setSignalingState('closed')
# stop senders / receivers
for transceiver in self.__transceivers:
... | 0.002172 |
def get_from_config_setting_cascade(self, sec_param_list, default=None, warn_on_none_level=logging.WARN):
"""return the first non-None setting from a series where each
element in `sec_param_list` is a section, param pair suitable for
a get_config_setting call.
Note that non-None values ... | 0.007101 |
def body(self):
""" String from `wsgi.input`.
"""
if self._body is None:
if self._fieldstorage is not None:
raise ReadBodyTwiceError()
clength = int(self.environ('CONTENT_LENGTH') or 0)
self._body = self._environ['wsgi.input'].read(clength)
... | 0.004494 |
def clean(cls, cpf):
u"""
Retorna apenas os dígitos do CPF.
>>> CPF.clean('581.194.436-59')
'58119443659'
"""
if isinstance(cpf, six.string_types):
cpf = int(re.sub('[^0-9]', '', cpf))
return '{0:011d}'.format(cpf) | 0.007042 |
def try_render(filepath=None, content=None, **options):
"""
Compile and render template and return the result as a string.
:param filepath: Absolute or relative path to the template file
:param content: Template content (str)
:param options: Keyword options passed to :func:`render` defined above.
... | 0.000944 |
def cli(context, mongodb, username, password, authdb, host, port, loglevel, config, demo):
"""scout: manage interactions with a scout instance."""
# log_format = "%(message)s" if sys.stdout.isatty() else None
log_format = None
coloredlogs.install(level=loglevel, fmt=log_format)
LOG.info("Running sco... | 0.002834 |
def error(self, error):
"""
set the error
"""
# TODO: check length with value?
# TODO: type checks (similar to value)
if self.direction not in ['x', 'y', 'z'] and error is not None:
raise ValueError("error only accepted for x, y, z dimensions")
if isi... | 0.004739 |
def pil_save(self, filename, fformat=None, fill_value=None,
compute=True, **format_kwargs):
"""Save the image to the given *filename* using PIL.
For now, the compression level [0-9] is ignored, due to PIL's lack of
support. See also :meth:`save`.
"""
fformat = f... | 0.004054 |
def console_progress():
""" Return a progress indicator for consoles if
stdout is a tty.
"""
def progress(totalhashed, totalsize):
"Helper"
msg = " " * 30
if totalhashed < totalsize:
msg = "%5.1f%% complete" % (totalhashed * 100.0 / totalsize)
sys.stdout.w... | 0.002092 |
def hash_str(data, hasher=None):
"""Checksum hash a string."""
hasher = hasher or hashlib.sha1()
hasher.update(data)
return hasher | 0.006849 |
def dict_factory(cursor, row):
"""
Converts the cursor information from a SQLite query to a dictionary.
:param cursor | <sqlite3.Cursor>
row | <sqlite3.Row>
:return {<str> column: <variant> value, ..}
"""
out = {}
for i, col in enumerate(cursor.description):
... | 0.002778 |
def cli(env, account_id):
"""List origin pull mappings."""
manager = SoftLayer.CDNManager(env.client)
origins = manager.get_origins(account_id)
table = formatting.Table(['id', 'media_type', 'cname', 'origin_url'])
for origin in origins:
table.add_row([origin['id'],
... | 0.002128 |
def relative_filename(self, filename):
"""Return the relative form of `filename`.
The filename will be relative to the current directory when the
`FileLocator` was constructed.
"""
fnorm = os.path.normcase(filename)
if fnorm.startswith(self.relative_dir):
fi... | 0.005181 |
def startup_config_content(self):
"""
Returns the content of the current startup-config file.
"""
config_file = self.startup_config_file
if config_file is None:
return None
try:
with open(config_file, "rb") as f:
return f.read().d... | 0.006329 |
def update_unique(self, table_name, fields, data, cond=None, unique_fields=None,
*, raise_if_not_found=False):
"""Update the unique matching element to have a given set of fields.
Parameters
----------
table_name: str
fields: dict or function[dict -> None]... | 0.004658 |
def undeflate(data):
"""Decompresses data for Content-Encoding: deflate.
(the zlib compression is used.)
"""
import zlib
decompressobj = zlib.decompressobj(-zlib.MAX_WBITS)
return decompressobj.decompress(data)+decompressobj.flush() | 0.003906 |
def get_endpoint(cls):
"""
Accessor method to enable omition of endpoint name.
In general we want the class name to be translated to endpoint name,
this way unless otherwise specified will translate class name to
endpoint name.
"""
if cls.endpoint is not None:
... | 0.00369 |
def get_right_geo_fhs(self, dsid, fhs):
"""Find the right geographical file handlers for given dataset ID *dsid*."""
ds_info = self.ids[dsid]
req_geo, rem_geo = self._get_req_rem_geo(ds_info)
desired, other = split_desired_other(fhs, req_geo, rem_geo)
if desired:
try:... | 0.006048 |
def _create_save_scenario_action(self):
"""Create action for save scenario dialog."""
icon = resources_path('img', 'icons', 'save-as-scenario.svg')
self.action_save_scenario = QAction(
QIcon(icon),
self.tr('Save Current Scenario'), self.iface.mainWindow())
message... | 0.002874 |
def putmask(self, mask, value):
"""
Return a new Index of the values set with the mask.
See Also
--------
numpy.ndarray.putmask
"""
values = self.values.copy()
try:
np.putmask(values, mask, self._convert_for_op(value))
return self.... | 0.00367 |
def copy(self,*args,**kwargs):
'''
Returns a copy of the current data object
:param flag: if an argument is provided, this returns an updated copy of current object (ie. equivalent to obj.copy();obj.update(flag)), optimising the memory (
:keyword True deep: deep copies the ... | 0.0189 |
def charge_credit_card(self, credit_card_psp_object: Model, amount: Money, client_ref: str) -> Tuple[bool, Model]:
"""
:param credit_card_psp_object: an instance representing the credit card in the psp
:param amount: the amount to charge
:param client_ref: a reference that will appear on... | 0.011521 |
def put_member(self, name: InstanceName, value: Value,
raw: bool = False) -> "InstanceNode":
"""Return receiver's member with a new value.
If the member is permitted by the schema but doesn't exist, it
is created.
Args:
name: Instance name of the member.
... | 0.005203 |
def onThemeColor(self, color, item):
"""pass theme colors to bottom panel"""
bconf = self.panel_bot.conf
if item == 'grid':
bconf.set_gridcolor(color)
elif item == 'bg':
bconf.set_bgcolor(color)
elif item == 'frame':
bconf.set_framecolor(color)... | 0.004808 |
def difference(cls, first, second):
"""Tells the numerical difference between two ranks."""
# so we always get a Rank instance even if string were passed in
first, second = cls(first), cls(second)
rank_list = list(cls)
return abs(rank_list.index(first) - rank_list.index(second)) | 0.00625 |
def histogram(data, bins=None, *args, **kwargs):
"""Facade function to create 1D histograms.
This proceeds in three steps:
1) Based on magical parameter bins, construct bins for the histogram
2) Calculate frequencies for the bins
3) Construct the histogram object itself
*Guiding principle:* pa... | 0.002142 |
def get_stp_mst_detail_output_msti_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
... | 0.00274 |
def validate_public_key(value):
"""
Check that the given value is a valid RSA Public key in either PEM or OpenSSH format. If it is invalid,
raises ``django.core.exceptions.ValidationError``.
"""
is_valid = False
exc = None
for load in (load_pem_public_key, load_ssh_public_key):
if n... | 0.00339 |
def curve_to(self, x, y, x2, y2, x3, y3):
"""draw a curve. (x2, y2) is the middle point of the curve"""
self._add_instruction("curve_to", x, y, x2, y2, x3, y3) | 0.011429 |
def _get_link(self, peer):
"""
Returns a link to the given peer
:return: A Link object
:raise ValueError: Unknown peer
"""
assert isinstance(peer, beans.Peer)
# Look for a link to the peer, using routers
for router in self._routers:
link = ro... | 0.004255 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.