text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def has_scope(context=None):
'''
Scopes were introduced in systemd 205, this function returns a boolean
which is true when the minion is systemd-booted and running systemd>=205.
'''
if not booted(context):
return False
_sd_version = version(context)
if _sd_version is None:
re... | 0.002778 |
def get_http_status_string(v):
"""Return HTTP response string, e.g. 204 -> ('204 No Content').
The return string always includes descriptive text, to satisfy Apache mod_dav.
`v`: status code or DAVError
"""
code = get_http_status_code(v)
try:
return ERROR_DESCRIPTIONS[code]
except K... | 0.005435 |
def extract_all_snow_tweets_from_disk_generator(json_folder_path):
"""
A generator that returns all SNOW tweets stored in disk.
Input: - json_file_path: The path of the folder containing the raw data.
Yields: - tweet: A tweet in python dictionary (json) format.
"""
# Get a generator with all ... | 0.003431 |
def save_image(data, epoch, image_size, batch_size, output_dir, padding=2):
""" save image """
data = data.asnumpy().transpose((0, 2, 3, 1))
datanp = np.clip(
(data - np.min(data))*(255.0/(np.max(data) - np.min(data))), 0, 255).astype(np.uint8)
x_dim = min(8, batch_size)
y_dim = int(math.cei... | 0.001896 |
def log_finished(self):
"""Log that this task is done."""
delta = time.perf_counter() - self.start_time
logger.log("Finished '", logger.cyan(self.name),
"' after ", logger.magenta(time_to_text(delta))) | 0.033333 |
def asset_path(cls, organization, asset):
"""Return a fully-qualified asset string."""
return google.api_core.path_template.expand(
"organizations/{organization}/assets/{asset}",
organization=organization,
asset=asset,
) | 0.007143 |
def get_disk_cache(self, key=None):
"""Return result in disk cache for key 'key' or None if not found."""
key = self.model.hash if key is None else key
if not getattr(self, 'disk_cache_location', False):
self.init_disk_cache()
disk_cache = shelve.open(self.disk_cache_location... | 0.004751 |
def add_files(self, *filenames: str, owner: str=SANDBOX_USERNAME, read_only: bool=False):
"""
Copies the specified files into the working directory of this
sandbox.
The filenames specified can be absolute paths or relative paths
to the current working directory.
:param o... | 0.005894 |
def count(self):
'''Estimate the cardinality count based on the technique described in
`this paper <http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=365694>`_.
Returns:
int: The estimated cardinality of the set represented by this MinHash.
'''
k = len(self)
... | 0.01269 |
def getTemplates(bikalims_path, restype, filter_by_type=False):
""" Returns an array with the Templates available in the Bika LIMS path
specified plus the templates from the resources directory specified and
available on each additional product (restype).
Each array item is a dictionary wit... | 0.000796 |
def attach_to_container(self, container_id):
""" A socket attached to the stdin/stdout of a container. The object returned contains a get_socket() function to get a socket.socket
object and close_socket() to close the connection """
sock = self._docker.containers.get(container_id).attach_socket... | 0.007105 |
def bind(self, func, etype):
'''
Register @func for execution when events with `.type` of @etype
or meta-events with `.utype` of @etype are handled. @func will be
called with self, self.gstate, and the event as arguments.
'''
self.event_funcs.setdefault(etype, [])
... | 0.008949 |
def visit_Tuple(self, node: AST, dfltChaining: bool = True) -> str:
"""Return tuple representation of `node`s elements."""
elems = (self.visit(elt) for elt in node.elts)
return f"({', '.join(elems)}{')' if len(node.elts) != 1 else ',)'}" | 0.007663 |
def parse_devices(self, json):
"""Parse result from API."""
result = []
for json_device in json:
license_plate = json_device['EquipmentHeader']['SerialNumber']
device = Device(self, license_plate)
device.update_from_json(json_device)
result.appen... | 0.005682 |
def child_link_update_from_dirrecord(self):
# type: () -> None
'''
Update the logical extent number stored in the child link record (if
there is one), from the directory record entry that was stored in
the child_link member. This is used at the end of reshuffling extents
... | 0.006369 |
def copy(self):
"""Returns a copy of this ClasspathProducts.
Edits to the copy's classpaths or exclude associations will not affect the classpaths or
excludes in the original. The copy is shallow though, so edits to the copy's product values
will mutate the original's product values. See `UnionProduct... | 0.005137 |
def parse_input(args, kwargs=None, condition=True, no_parse=None):
'''
Parse out the args and kwargs from a list of input values. Optionally,
return the args and kwargs without passing them to condition_input().
Don't pull args with key=val apart if it has a newline in it.
'''
if no_parse is No... | 0.000763 |
def show_pages(parser, token):
"""Show page links.
Usage:
.. code-block:: html+django
{% show_pages %}
It is just a shortcut for:
.. code-block:: html+django
{% get_pages %}
{{ pages.get_rendered }}
You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *set... | 0.001143 |
def add_namespaces(spec_dict):
"""Add namespace convenience keys, list, list_{short|long}, to_{short|long}"""
for ns in spec_dict["namespaces"]:
spec_dict["namespaces"][ns]["list"] = []
spec_dict["namespaces"][ns]["list_long"] = []
spec_dict["namespaces"][ns]["list_short"] = []
... | 0.006823 |
def _parse_section_to_dict(cls, section_options, values_parser=None):
"""Parses section options into a dictionary.
Optionally applies a given parser to values.
:param dict section_options:
:param callable values_parser:
:rtype: dict
"""
value = {}
values... | 0.004141 |
def to_dotfile(self):
""" Writes a DOT graphviz file of the domain structure, and returns the filename"""
domain = self.get_domain()
filename = "%s.dot" % (self.__class__.__name__)
nx.write_dot(domain, filename)
return filename | 0.011236 |
def delete_partitions(self, ds):
"""Fast delete of all of a datasets codes, columns, partitions and tables"""
from ambry.orm import Partition
ssq = self.session.query
ssq(Process).filter(Process.d_vid == ds.vid).delete()
ssq(Code).filter(Code.d_vid == ds.vid).delete()
s... | 0.006757 |
def execute(self, command, is_displayed=True, profile=None):
"""
Execute a command on the remote server
:param command: Command to execute remotely
:param is_displayed: True if information should be display; false to return output
(default: true)
:pa... | 0.003968 |
def is_docker_reachable(self):
"""
Checks if Docker daemon is running. This is required for us to invoke the function locally
Returns
-------
bool
True, if Docker is available, False otherwise
"""
try:
self.docker_client.ping()
... | 0.006791 |
def report(self):
"""Return a dictionary of different status codes and the percentage of time
spent in each throughout the last summation_period seconds.
Truncate the aggregated history appropriately."""
timestamp = time.time()
cutoff = timestamp - self.period
truncate = ... | 0.002681 |
def gibson_primers(dna1, dna2, overlap='mixed', maxlen=80, overlap_tm=65.0,
insert=None, primer_kwargs=None):
'''Design Gibson primers given two DNA sequences (connect left to right)
:param dna1: First piece of DNA for which to design primers. Once Gibsoned,
would be connect... | 0.000177 |
def approx(x, y, xout, method='linear', rule=1, f=0, yleft=None,
yright=None, ties='mean'):
"""Linearly interpolate points.
Return a list of points which (linearly) interpolate given data points,
or a function performing the linear (or constant) interpolation.
Parameters
----------
... | 0.000314 |
def container_remove_folder(object_id, input_params={}, always_retry=False, **kwargs):
"""
Invokes the /container-xxxx/removeFolder API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FremoveFolder
"""
return DXHTTPReq... | 0.009828 |
def get_sea_names():
'''
Returns a list of NODC sea names
source of list: https://www.nodc.noaa.gov/General/NODC-Archive/seanamelist.txt
'''
global _SEA_NAMES
if _SEA_NAMES is None:
buf = {}
with open(resource_filename('compliance_checker', 'data/seanames.csv'), 'r') as f:
... | 0.006316 |
def closed(self, error=None):
"""
Notify the application that the connection has been closed.
:param error: The exception which has caused the connection to
be closed. If the connection has been closed
due to an EOF, pass ``None``.
"""
... | 0.003861 |
def _get_overlapped_result_ex_impl(pipe, olap, nbytes, millis, alertable):
""" Windows 7 and earlier does not support GetOverlappedResultEx. The
alternative is to use GetOverlappedResult and wait for read or write
operation to complete. This is done be using CreateEvent and
WaitForSingleObjectEx. Create... | 0.002069 |
def extract_zip(filename, extract_dir):
""" Extract the sources in a temporary folder.
:arg filename, name of the zip file containing the data from MapQTL
which will be extracted
:arg extract_dir, folder in which to extract the archive.
"""
LOG.info("Extracting %s in %s " % (filename, extract_di... | 0.000583 |
def validate(self, value):
"""
Validates value and throws ValidationError. Subclasses should override
this to provide validation logic.
"""
# check object type
if not isinstance(value, list):
raise tldap.exceptions.ValidationError(
"is not a li... | 0.002099 |
def log_in(self, utterance: Any, dialog_id: Optional[Hashable] = None) -> None:
"""Wraps _log method for all input utterances.
Args:
utterance: Dialog utterance.
dialog_id: Dialog ID.
"""
if self.enabled:
self._log(utterance, 'in', dialog_id) | 0.006452 |
def copy(self):
"""
Returns
-------
A copy of the dimension
"""
return Dimension(self._name, self._global_size,
lower_extent=self._lower_extent,
upper_extent=self._upper_extent,
description=self._description) | 0.016892 |
def _has_name(soup_obj):
"""checks if soup_obj is really a soup object or just a string
If it has a name it is a soup object"""
try:
name = soup_obj.name
if name == None:
return False
return True
except AttributeError:
return False | 0.006873 |
def receive(
self,
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False) -> Tuple[str, str]:
"""Receive a payload.
For testing purposes, `skip_author_verification`... | 0.003525 |
def _name(iris_obj, default='unknown'):
""" Mimicks `iris_obj.name()` but with different name resolution order.
Similar to iris_obj.name() method, but using iris_obj.var_name first to
enable roundtripping.
"""
return (iris_obj.var_name or iris_obj.standard_name or
iris_obj.long_name or ... | 0.003049 |
def authenticate(self, username, password):
"""
Obtain an oauth token. Pass username and password. Get a token back. If KitsuAuth is set to remember your tokens
for this session, it will store the token under the username given.
:param username: username
:param password: passwor... | 0.008237 |
def dismiss(self, member_ids):
"""踢人. 注意别把自己给踢了.
:param member_ids: 组员 ids
:return: bool
"""
url = 'http://www.shanbay.com/api/v1/team/member/'
data = {
'action': 'dispel',
}
if isinstance(member_ids, (list, tuple)):
data['ids'] = ... | 0.003344 |
def on_mismatch(self, pair):
"""Called for pairs that don't match `match` and `exclude` filters.
If --delete-unmatched is on, remove the remote resource.
"""
remote_entry = pair.remote
if self.options.get("delete_unmatched") and remote_entry:
self._log_action("delete... | 0.004975 |
def get_configuration(filename):
""" Read configuration file
:type filename: str
:param filename: Path to the configuration file
"""
logger.debug('Reading configuration from {}'.format(filename))
conf = SafeConfigParser()
conf.read(filename)
if not conf:
logger.error('Configura... | 0.00113 |
def find_keywords(string, parser, top=10, frequency={}, **kwargs):
""" Returns a sorted list of keywords in the given string.
The given parser (e.g., pattern.en.parser) is used to identify noun phrases.
The given frequency dictionary can be a reference corpus,
with relative document frequenc... | 0.002647 |
def get_word_saliency(topic_word_distrib, doc_topic_distrib, doc_lengths):
"""
Calculate word saliency according to Chuang et al. 2012.
saliency(w) = p(w) * distinctiveness(w)
J. Chuang, C. Manning, J. Heer 2012: "Termite: Visualization Techniques for Assessing Textual Topic Models"
"""
p_t = g... | 0.003953 |
def omgparse(args):
"""
%prog omgparse work
Parse the OMG outputs to get gene lists.
"""
p = OptionParser(omgparse.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
work, = args
omgfiles = glob(op.join(work, "gf*.out"))
for omgfil... | 0.001946 |
def _pollMouse(self):
"""
Polls @10Hz, with a slight delay at the
start.
"""
if self._mouseJustPressed:
delay = 300
self._mouseJustPressed = False
else:
delay = 100
if self._leftMousePressed:
self.add(1)
... | 0.002653 |
def make_rule(filter, *symbolizers):
""" Given a Filter and some symbolizers, return a Rule prepopulated
with applicable min/max scale denominator and filter.
"""
scale_tests = [test for test in filter.tests if test.isMapScaled()]
other_tests = [test for test in filter.tests if not test.isMapSca... | 0.0056 |
def check_compression_gathering(self, ds):
"""
At the current time the netCDF interface does not provide for packing
data. However a simple packing may be achieved through the use of the
optional NUG defined attributes scale_factor and add_offset . After the
data values of a vari... | 0.001569 |
def create_app(config=None, config_obj=None):
"""Flask app factory function.
Args:
config (Optional[path]): path to a Python module config file
config_obj (Optional[class]): Python config object
"""
app = Flask(__name__)
# configure application from external configs
configure_ap... | 0.001976 |
def _makeLocationElement(self, locationObject, name=None):
""" Convert Location object to an locationElement."""
locElement = ET.Element("location")
if name is not None:
locElement.attrib['name'] = name
for dimensionName, dimensionValue in locationObject.items():
d... | 0.02038 |
def characterize_psf(self):
""" Get support size and drift polynomial for current set of params """
# there may be an issue with the support and characterization--
# it might be best to do the characterization with the same support
# as the calculated psf.
l,u = max(self.zrange[0... | 0.00478 |
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wir... | 0.003699 |
def get_select_items(items):
"""Return list of possible select items."""
option_items = list()
for item in items:
if isinstance(item, dict) and defs.VALUE in item and defs.LABEL in item:
option_items.append(item[defs.VALUE])
else:
raise exceptions.ParametersFieldError... | 0.008639 |
def get_value(self):
"""Get a fresh sensor value from the KATCP resource
Returns
-------
reply : tornado Future resolving with :class:`KATCPSensorReading` object
Note
----
As a side-effect this will update the reading stored in this object, and result in
... | 0.00759 |
def __mark(self, element, mark_set):
"""
Marks an element
:param element: The element to mark
:param mark_set: The set corresponding to the mark
:return: True if the element was known
"""
try:
# The given element can be of a different type than the or... | 0.002894 |
def bury(self, job: Job, priority: int = DEFAULT_PRIORITY) -> None:
"""Buries a reserved job.
:param job: The job to bury.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
most urgent.
"""
self._send_cmd(b'bury %d %d' % (job.id, pri... | 0.005917 |
def offset(self, num_to_skip):
"""Skip to an offset in a query with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.offset` for
more information on this method.
Args:
num_to_skip (int): The number of results to skip at the beginning
... | 0.003724 |
def _supported_baremetal_transaction(self, context):
"""Verify transaction is complete and for us."""
port = context.current
if self.trunk.is_trunk_subport_baremetal(port):
return self._baremetal_set_binding(context)
if not nexus_help.is_baremetal(port):
return... | 0.001275 |
def swipe_by_coordinates(self, sx, sy, ex, ey, steps=10):
"""
Swipe from (sx, sy) to (ex, ey) with *steps* .
Example:
| Swipe By Coordinates | 540 | 1340 | 940 | 1340 | | # Swipe from (540, 1340) to (940, 100) with default steps 10 |
| Swipe By Coordinates | 540 | 1340 | 940... | 0.008715 |
def _put(self, item: SQLBaseObject):
"""Puts a item into the database. Updates lastUpdate column"""
if item._dto_type in self._expirations and self._expirations[item._dto_type] == 0:
# The expiration time has been set to 0 -> shoud not be cached
return
item.updated()
... | 0.008547 |
def _dnsname_to_stdlib(name):
"""
Converts a dNSName SubjectAlternativeName field to the form used by the
standard library on the given Python version.
Cryptography produces a dNSName as a unicode string that was idna-decoded
from ASCII bytes. We need to idna-encode that string to get it back, and
... | 0.000731 |
def remove_component(self, entity: int, component_type: Any) -> int:
"""Remove a Component instance from an Entity, by type.
A Component instance can be removed by providing it's type.
For example: world.delete_component(enemy_a, Velocity) will remove
the Velocity instance from the Enti... | 0.002165 |
def _generate(self):
"""Generates a particle using the creator function.
Notes
-----
Position and speed are uniformly randomly seeded within
allowed bounds. The particle also has speed limit settings
taken from global values.
Returns
-------
part... | 0.002494 |
def min_images(images):
"""Create a min Image from a list of Images.
Parameters
----------
:obj:`list` of :obj:`Image`
A list of Image objects.
Returns
-------
:obj:`Image`
A new Image of the same type whose data is the min of all of
... | 0.002706 |
def extract(self, name, example):
''' Extract keywords from an example path '''
# if pathlib not available do nothing
if not pathlib:
return None
# ensure example is a string
if isinstance(example, pathlib.Path):
example = str(example)
assert isi... | 0.002949 |
def scatter_props(event):
"""
Get information for a pick event on a PathCollection artist (usually
created with ``scatter``).
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`c`: The value of the color array at t... | 0.000808 |
def format_sql(self):
"""
Builds the sql in a format that is easy for humans to read and debug
:return: The formatted sql for this query
:rtype: str
"""
# TODO: finish adding the other parts of the sql generation
sql = ''
# build SELECT
select_se... | 0.002978 |
def write_config_files(out_dir='.',
java_home_dir=None,
jvm_dll_file=None,
install_dir=None,
req_java_api_conf=True,
req_py_api_conf=True):
"""
Writes the jpy configuration files for Java and/or Py... | 0.003679 |
def parse_response(fields, records):
"""Parse an API response into usable objects.
Args:
fields (list[str]): List of strings indicating the fields that
are represented in the records, in the order presented in
the records.::
[
... | 0.001181 |
def filter(self, request, queryset, view):
""" Filter each resource separately using its own filter """
summary_queryset = queryset
filtered_querysets = []
for queryset in summary_queryset.querysets:
filter_class = self._get_filter(queryset)
queryset = filter_clas... | 0.003984 |
def validate_callback(self, service, pgturl, pgtid, pgtiou):
"""Verify the provided proxy callback URL."""
if not proxy_allowed(service):
raise UnauthorizedServiceProxy("%s is not authorized to use proxy authentication" % service)
if not is_scheme_https(pgturl):
raise In... | 0.004685 |
def input_from_blif(blif, block=None, merge_io_vectors=True):
""" Read an open blif file or string as input, updating the block appropriately
Assumes the blif has been flattened and their is only a single module.
Assumes that there is only one single shared clock and reset
Assumes that output is genera... | 0.002341 |
def symmetries(self):
"""Graph symmetries (permutations) that map the graph onto itself."""
symmetry_cycles = set([])
symmetries = set([])
for match in GraphSearch(EqualPattern(self))(self):
match.cycles = match.get_closed_cycles()
if match.cycles in symmetry_cyc... | 0.004057 |
def summarize_taxa(biom):
"""
Given an abundance table, group the counts by every
taxonomic level.
"""
tamtcounts = defaultdict(int)
tot_seqs = 0.0
for row, col, amt in biom['data']:
tot_seqs += amt
rtax = biom['rows'][row]['metadata']['taxonomy']
for i, t in enumera... | 0.002967 |
def setup_oauth_client(self, url=None):
""" Sets up client for requests to pump """
if url and "://" in url:
server, endpoint = self._deconstruct_url(url)
else:
server = self.client.server
if server not in self._server_cache:
self._add_client(server)
... | 0.002296 |
def run( self ):
"""
Interact with the blockchain peer,
until we get a socket error or we
exit the loop explicitly.
Return True on success
Raise on error
"""
self.handshake()
try:
self.loop()
except socket.error, se:
... | 0.009804 |
def consume_input(self, input):
"""
Make a copy of the input for the run function and consume the input to free up the queue for more input. If all
input is consumed, there is no need to overload this function. Input is provided as lists. To copy and consume
input the following commands ... | 0.005423 |
def insert_trie(trie, value): # aka get_subtrie_or_insert
""" Insert a value into the trie if it is not already contained in the trie.
Return the subtree for the value regardless of whether it is a new value
or not. """
if value in trie:
return trie[value]
multi_check = False
fo... | 0.005631 |
def to_period(self, freq=None, copy=True):
"""
Convert Series from DatetimeIndex to PeriodIndex with desired
frequency (inferred from index if not passed).
Parameters
----------
freq : str, default None
Frequency associated with the PeriodIndex.
copy ... | 0.002625 |
def create_ipsec_endpoint(cls, gateway, tunnel_interface=None):
"""
Create the VPN tunnel endpoint. If the VPN tunnel endpoint
is an SMC managed device, both a gateway and a tunnel interface
is required. If the VPN endpoint is an externally managed
device, only a gateway is r... | 0.004695 |
def compute_allele_frequencies(self, using=None):
"Computes the allele frequencies across all samples in this cohort."
if using is None:
using = router.db_for_write(self.__class__)
cursor = connections[using].cursor()
with transition(self, 'Recomputed Allele Frequencies'):
... | 0.001048 |
def move_images_to_cache(source, destination):
"""
Handles the movement of images to the cache. Must be helpful if it finds
that the folder for this article already exists.
"""
if os.path.isdir(destination):
log.debug('Cached images for this article already exist')
return
else:
... | 0.003328 |
def update(self, item, id_expression=None, upsert=False, update_ops={}, safe=None, **kwargs):
''' Update an item in the database. Uses the on_update keyword to each
field to decide which operations to do, or.
:param item: An instance of a :class:`~ommongo.document.Document` \
subclass
:param id_express... | 0.022576 |
def validate_cookies(session, class_name):
"""
Checks whether we have all the required cookies
to authenticate on class.coursera.org. Also check for and remove
stale session.
"""
if not do_we_have_enough_cookies(session.cookies, class_name):
return False
url = CLASS_URL.format(class... | 0.001603 |
def insert(self, key):
"""
Insert new key into node
"""
# Create new node
n = TreeNode(key)
if not self.node:
self.node = n
self.node.left = AvlTree()
self.node.right = AvlTree()
elif key < self.node.val:
self.node.l... | 0.004598 |
def bold(self, action):
'''Enable/cancel bold printing
Args:
action: Enable or disable bold printing. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action.
'''
if action =='on':
action = 'E'... | 0.009728 |
def load_balancers_list_all(**kwargs):
'''
.. versionadded:: 2019.2.0
List all load balancers within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.load_balancers_list_all
'''
result = {}
netconn = __utils__['azurearm.get_client']('network', **k... | 0.002837 |
def exportNewKey(fingerprint):
"""Export the new keys into .asc files.
:param str fingerprint: A full key fingerprint.
"""
log.info("Exporting key: %s" % fingerprint)
keyfn = os.path.join(gpg.homedir,
fingerprint + '-8192-bit-key') + os.path.extsep
pubkey = gpg.export... | 0.001359 |
def polyline(self, vertexes, attr=0, row=None):
'adds lines for (x,y) vertexes of a polygon'
self.polylines.append((vertexes, attr, row)) | 0.013072 |
def create_bootstrap_id_array(obs_id_per_sample):
"""
Creates a 2D ndarray that contains the 'bootstrap ids' for each replication
of each unit of observation that is an the set of bootstrap samples.
Parameters
----------
obs_id_per_sample : 2D ndarray of ints.
Should have one row for ea... | 0.001012 |
def process_opres_input(key, value, key_options):
"""
Check if `value` or `key` is a Result object and populate the
options accordingly.
:param key:
:param value:
:param key_options:
:return:
"""
opres = None
if isinstance(value, OperationResult):
opres = value
elif ... | 0.001742 |
def _dump_registry(cls, file=None):
"""Debug helper to print the ABC registry."""
print >> file, "Class: %s.%s" % (cls.__module__, cls.__name__)
print >> file, "Inv.counter: %s" % ABCMeta._abc_invalidation_counter
for name in sorted(cls.__dict__.keys()):
if name.startswith("_... | 0.004695 |
def _load_outcome_models(self):
""" Create outcome models from core outcomes """
self.outcomes = []
for outcome in self.state.outcomes.values():
self._add_model(self.outcomes, outcome, OutcomeModel) | 0.008547 |
def info(name, root=None):
'''
Return information about a group
name
Name of the group
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' group.info foo
'''
if root is not None:
getgrnam = functools.partial(_getgrnam, root=root)
... | 0.001972 |
def list(self, max=None, **request_parameters):
"""List teams to which the authenticated user belongs.
This method supports Webex Teams's implementation of RFC5988 Web
Linking to provide pagination support. It returns a generator
container that incrementally yields all teams returned b... | 0.001154 |
def clear(self):
"""
Clears all the container for this query widget.
"""
for i in range(self.count()):
widget = self.widget(i)
if widget is not None:
widget.close()
widget.setParent(None)
widget.deleteLater(... | 0.006231 |
def _make_signature(self, header_b64, payload_b64, signing_key):
"""
Sign a serialized header and payload.
Return the urlsafe-base64-encoded signature.
"""
token_segments = [header_b64, payload_b64]
signing_input = b'.'.join(token_segments)
signer = self._get_sig... | 0.003745 |
def _load_db():
"""Deserializes the script database from JSON."""
from os import path
from pyci.utility import get_json
global datapath, db
datapath = path.abspath(path.expanduser(settings.datafile))
vms("Deserializing DB from {}".format(datapath))
db = get_json(datapath, {"installed": [], "... | 0.002849 |
def flatten_dictionary(nested_dict, separator):
"""Flattens a nested dictionary.
New keys are concatenations of nested keys with the `separator` in between.
"""
flat_dict = {}
for key, val in nested_dict.items():
if isinstance(val, dict):
new_flat_dict = flatten_dictionary(val,... | 0.001805 |
def _add_combined_condition_to_template(self, template_dict, condition_name, conditions_to_combine):
"""
Add top-level template condition that combines the given list of conditions.
:param dict template_dict: SAM template dictionary
:param string condition_name: Name of top-level templa... | 0.006876 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.