text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def inverse(self):
"""Calculate the inverse of the range.
Returns:
New VersionRange object representing the inverse of this range, or
None if there is no inverse (ie, this range is the any range).
"""
if self.is_any():
return None
else:
... | 0.004357 |
def parse_args(cls):
"""Main argument parser of Laniakea.
"""
# Initialize configuration and userdata directories.
dirs = appdirs.AppDirs(__title__, 'Mozilla Security')
if not os.path.isdir(dirs.user_config_dir):
shutil.copytree(os.path.join(cls.HOME, 'examples'), dir... | 0.002325 |
def render(self, filename_root=None, file=None):
"""Render the document repeatedly until the output no longer changes due
to cross-references that need some iterations to converge."""
self.error = False
filename_root = Path(filename_root) if filename_root else None
if filename_ro... | 0.001142 |
def as_xml(self,parent):
"""Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: `libxml2.xmlNode`"""
n=pa... | 0.024316 |
def visitValueType(self, ctx: jsgParser.ValueTypeContext):
""" valueType: idref | nonRefValueType """
if ctx.idref():
self._typeid = as_token(ctx)
else:
self.visitChildren(ctx) | 0.008929 |
def _validate_children(self):
"""Check that the children we have are allowed here."""
for child in self._children:
if child.__class__ not in self._allowed_children:
raise ValueError(
"Child %s is not allowed as a children for this %s type entity." % (
... | 0.007481 |
def call():
"""Execute command line helper."""
args = get_arguments()
if args.debug:
log_level = logging.DEBUG
elif args.quiet:
log_level = logging.WARN
else:
log_level = logging.INFO
setup_logging(log_level)
lupusec = None
if not args.username or not args.pas... | 0.0041 |
def add_from_string(self, buffer, length=-1):
"""add_from_string(buffer, length=-1)
{{ all }}
"""
return Gtk.Builder.add_from_string(self, buffer, length) | 0.010638 |
def clip(self, channels=True):
"""Limit the values of the array to the default [0,1] range. *channels*
says which channels should be clipped."""
if not isinstance(channels, (tuple, list)):
channels = [channels] * len(self.channels)
for i in range(len(self.channels)):
... | 0.004831 |
def de_projection_3d(amplitudes, sigmas):
"""
de-projects a gaussian (or list of multiple Gaussians from a 2d projected to a 3d profile)
:param amplitudes:
:param sigmas:
:return:
"""
amplitudes_3d = amplitudes / sigmas / np.sqrt(2*np.pi)
return amplitudes_3d, sigmas | 0.006689 |
def disambiguate_pdf(self, file, language=None, entities=None):
""" Call the disambiguation service in order to process a pdf file .
Args:
pdf (file): PDF file to be disambiguated.
language (str): language of text (if known)
Returns:
dict, int: API response ... | 0.001864 |
def bottom(self):
"""
The row index that marks the bottom extent of the vertical span of
this cell. This is one greater than the index of the bottom-most row
of the span, similar to how a slice of the cell's rows would be
specified.
"""
if self.vMerge is not None:... | 0.003945 |
def to_fixed(stype):
""" Returns the instruction sequence for converting the given
type stored in DE,HL to fixed DE,HL.
"""
output = [] # List of instructions
if is_int_type(stype):
output = to_word(stype)
output.append('ex de, hl')
output.append('ld hl, 0') # 'Truncate' t... | 0.002193 |
def query(self, *args, **kwargs):
"""
Returns a new QuerySet instance with the args ANDed to the existing
set.
"""
clone = self._clone()
queries = []
from pyes.query import Query
if args:
for f in args:
if isinstance(f, Query):... | 0.00428 |
def upgrade(dbname, connect_str, alembic_conf):
"""
Get the database's upgrade lock and run alembic.
:param dbname: Name of the database to upgrade/create
:param connect_str: Connection string to the database (usually Flask's SQLALCHEMY_DATABASE_URI)
:param alembic_conf: location of alembic.ini
... | 0.002481 |
def concat_list(listA, listB, delim=' '):
"""
Concatenate list elements pair-wise with the delim character
Returns the concatenated list
Raises index error if lists are not parallel
"""
# Lists must be of equal length.
if len(listA) != len(listB):
raise IndexError('Input lists are n... | 0.002024 |
def get_publications(context, template='publications/publications.html'):
"""
Get all publications.
"""
types = Type.objects.filter(hidden=False)
publications = Publication.objects.select_related()
publications = publications.filter(external=False, type__in=types)
publications = publications.order_by('-year', '... | 0.02729 |
def add_manager_view(request):
''' View to add a new manager position. Restricted to superadmins and presidents. '''
form = ManagerForm(request.POST or None)
if form.is_valid():
manager = form.save()
messages.add_message(request, messages.SUCCESS,
MESSAGES['MANAG... | 0.004601 |
def delete(self, membershipId):
"""Delete a membership, by ID.
Args:
membershipId(basestring): The membership ID.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
check_type(me... | 0.004651 |
def echo_via_pager(text_or_generator, color=None):
"""This function takes a text and shows it via an environment specific
pager on stdout.
.. versionchanged:: 3.0
Added the `color` flag.
:param text_or_generator: the text to page, or alternatively, a
generator emit... | 0.000998 |
def get_context_file_name(pid_file):
"""When the daemon is started write out the information which port it was using."""
root = os.path.dirname(pid_file)
port_file = os.path.join(root, "context.json")
return port_file | 0.008584 |
def index(request):
session = Session(request.body)
print 'request.body begin'
print request.body
print 'request.body end'
t = Tropo()
smsContent = session.initialText
#t.call(to=session.parameters['callToNumber'], network='SIP')
#t.say(session.parameters['message'])
"""
t = Trop... | 0.011714 |
def attribute_difference(att_diff):
''' The attribute distance.
'''
ret = 0
for a_value, b_value in att_diff:
if max(a_value, b_value) == 0:
ret += 0
else:
ret += abs(a_value - b_value) * 1.0 / max(a_value, b_value)
return ret * 1.0 / len(att_diff) | 0.003236 |
def zorsupas(client, event, channel, nick, rest):
'Zor supas! — !زۆر سوپاس'
if rest:
rest = rest.strip()
Karma.store.change(rest, 1)
rcpt = rest
else:
rcpt = channel
return (
f'Zor supas {rcpt}, to zor zor barezi! —'
' زۆر سوپاس، تۆ زۆر زۆر بهرهزی'
) | 0.003125 |
def rebuild_indexes(self, chunk_size=1000, aggressive_clear=False, index_class=None):
"""Rebuild all indexes tied to this field
Parameters
----------
chunk_size: int
Default to 1000, it's the number of instances to load at once.
aggressive_clear: bool
Wil... | 0.006863 |
def setOpenIDNamespace(self, openid_ns_uri, implicit):
"""Set the OpenID namespace URI used in this message.
@raises InvalidOpenIDNamespace: if the namespace is not in
L{Message.allowed_openid_namespaces}
"""
if openid_ns_uri not in self.allowed_openid_namespaces:
... | 0.004132 |
def source_encoding(source):
"""Determine the encoding for `source` (a string), according to PEP 263.
Returns a string, the name of the encoding.
"""
# Note: this function should never be called on Python 3, since py3 has
# built-in tools to do this.
assert sys.version_info < (3, 0)
# Thi... | 0.000323 |
def rename_axis(self, mapper=sentinel, **kwargs):
"""
Set the name of the axis for the index or columns.
Parameters
----------
mapper : scalar, list-like, optional
Value to set the axis name attribute.
index, columns : scalar, list-like, dict-like or function... | 0.000302 |
def ekops():
"""
Open a scratch (temporary) E-kernel file and prepare the file
for writing.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekops_c.html
:return: Handle attached to new EK file.
:rtype: int
"""
handle = ctypes.c_int()
libspice.ekops_c(ctypes.byref(handle))
... | 0.002924 |
def write_frame(self):
""" Writes a single frame to the movie file """
if not hasattr(self, 'mwriter'):
raise AssertionError('This plotter has not opened a movie or GIF file.')
self.mwriter.append_data(self.image) | 0.012048 |
def pauli_basis(nq=1):
"""
Returns a TomographyBasis for the Pauli basis on ``nq``
qubits.
:param int nq: Number of qubits on which the returned
basis is defined.
"""
basis = tensor_product_basis(*[
TomographyBasis(
gell_mann_basis(2).data[[0, 2, 3, 1]],
... | 0.002203 |
def update(self, d):
"""Update the dict with the dict tree in parameter d.
Parameters
----------
d : dict
New dict content
"""
# Call __setitem__ for all keys in d
for key in list(d.keys()):
self.__setitem__(key, d[key]) | 0.006667 |
def findParent(self, name=None, attrs={}, **kwargs):
"""Returns the closest parent of this Tag that matches the given
criteria."""
# NOTE: We can't use _findOne because findParents takes a different
# set of arguments.
r = None
l = self.findParents(name, attrs, 1)
... | 0.008242 |
def init(opts):
'''
Opens the connection with the network device.
'''
NETWORK_DEVICE.update(salt.utils.napalm.get_device(opts))
DETAILS['initialized'] = True
return True | 0.005181 |
def DbGetDeviceWideList(self, argin):
""" Get a list of devices whose names satisfy the filter.
:param argin: filter
:type: tango.DevString
:return: list of exported devices
:rtype: tango.DevVarStringArray """
self._log.debug("In DbGetDeviceWideList()")
argin = r... | 0.005089 |
def set_setting(self, setting, value, area='1', validate_value=True):
"""Set an abode system setting to a given value."""
setting = setting.lower()
if setting not in CONST.ALL_SETTINGS:
raise AbodeException(ERROR.INVALID_SETTING, CONST.ALL_SETTINGS)
if setting in CONST.PANE... | 0.002051 |
def top(self, container, ps_args=None):
"""
Display the running processes of a container.
Args:
container (str): The container to inspect
ps_args (str): An optional arguments passed to ps (e.g. ``aux``)
Returns:
(str): The output of the top
... | 0.003101 |
def validate_service(self, request, uid):
"""Validates the specs values from request for the service uid. Returns
a non-translated message if the validation failed."""
result = get_record_value(request, uid, 'result')
if not result:
# No result set for this service, dismiss
... | 0.001639 |
def register_drop(self, task, event_details=None):
""" :meth:`.WSimpleTrackerStorage.register_drop` method implementation
"""
if self.record_drop() is True:
record_type = WTrackerEvents.drop
record = WSimpleTrackerStorage.Record(record_type, task, event_details=event_details)
self.__store_record(record) | 0.028213 |
def _extract_services_list_helper(services):
"""Extract a OrderedDict of {service: [ports]} of the supplied services
for use by the other functions.
The services object can either be:
- None : no services were passed (an empty dict is returned)
- a list of strings
- A dictionary (optional... | 0.00102 |
def get_patient_pharmacies(self, patient_id,
patients_favorite_only='N'):
"""
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:return: JSON response
"""
magic = self._magic_json(
action=TouchWorksMagicConsta... | 0.007032 |
def places_nearby(client, location=None, radius=None, keyword=None,
language=None, min_price=None, max_price=None, name=None,
open_now=False, rank_by=None, type=None, page_token=None):
"""
Performs nearby search for places.
:param location: The latitude/longitude value f... | 0.0009 |
def get_script(self):
"""
Gets the configuration script of the logical enclosure by ID or URI.
Return:
str: Configuration script.
"""
uri = "{}/script".format(self.data["uri"])
return self._helper.do_get(uri) | 0.007435 |
def _avro_rows(block, avro_schema):
"""Parse all rows in a stream block.
Args:
block ( \
~google.cloud.bigquery_storage_v1beta1.types.ReadRowsResponse \
):
A block containing Avro bytes to parse into rows.
avro_schema (fastavro.schema):
A parsed Avro ... | 0.001088 |
def move_notes(self, noteids, folderid):
"""Move notes to a folder
:param noteids: The noteids to move
:param folderid: The folderid to move notes to
"""
if self.standard_grant_type is not "authorization_code":
raise DeviantartError("Authentication through Authoriz... | 0.008977 |
def _histogram_fixed_binsize(a, start, width, n):
"""histogram_even(a, start, width, n) -> histogram
Return an histogram where the first bin counts the number of lower
outliers and the last bin the number of upper outliers. Works only with
fixed width bins.
:Stochastics:
a : array
Ar... | 0.001261 |
def union(self, other, sort=None):
"""
Form the union of two Index objects and sorts if possible
Parameters
----------
other : Index or array-like
sort : False or None, default None
Whether to sort resulting index. ``sort=None`` returns a
mononot... | 0.00074 |
def ubridge_path(self):
"""
Returns the uBridge executable path.
:returns: path to uBridge
"""
path = self._manager.config.get_section_config("Server").get("ubridge_path", "ubridge")
path = shutil.which(path)
return path | 0.010791 |
def validate_request_partition_key(self, request):
'''
Validates that all requests have the same PartitiionKey. Set the
PartitionKey if it is the first request for the batch operation.
request:
the request to insert, update or delete entity
'''
if self.batch_... | 0.006472 |
def markdown_table(data, headers):
"""
Creates MarkDown table. Returns list of strings
Arguments:
data -- [(cell00, cell01, ...), (cell10, cell11, ...), ...]
headers -- sequence of strings: (header0, header1, ...)
"""
maxx = [max([len(x) for x in column]) for column in zip(*da... | 0.001642 |
def parse_time(time):
'''Change the time to seconds'''
unit = time[-1]
if unit not in ['s', 'm', 'h', 'd']:
print_error('the unit of time could only from {s, m, h, d}')
exit(1)
time = time[:-1]
if not time.isdigit():
print_error('time format error!')
exit(1)
parse... | 0.012376 |
def to_datetime(data):
"""
convert Datetime 9-tuple to the date and time format
feedparser provides this 9-tuple
:param data: data to be checked
:type data: dict
"""
my_date_time = None
if 'published_parsed' in data:
my_date_time = datetime.datetime.utcfromtimest... | 0.005427 |
def search(self, key, default=None):
"""Find the first key-value pair with key *key* and return its value.
If the key was not found, return *default*. If no default was provided,
return ``None``. This method never raises a ``KeyError``.
"""
self._find_lt(key)
node = self... | 0.004651 |
def compare(eq_dfs, columns=None, selection='Adj Close'):
"""
Get the relative performance of multiple equities.
.. versionadded:: 0.5.0
Parameters
----------
eq_dfs : list or tuple of DataFrame
Performance data for multiple equities over
a consistent time frame.
columns : ... | 0.001876 |
def resolve_dependencies(self, to_build, depender):
"""Add any required dependencies.
"""
shutit_global.shutit_global_object.yield_to_draw()
self.log('In resolve_dependencies',level=logging.DEBUG)
cfg = self.cfg
for dependee_id in depender.depends_on:
dependee = self.shutit_map.get(dependee_id)
# Don'... | 0.030875 |
def _check_valid_udunits(self, ds, variable_name):
'''
Checks that the variable's units are contained in UDUnits
:param netCDF4.Dataset ds: An open netCDF dataset
:param str variable_name: Name of the variable to be checked
'''
variable = ds.variables[variable_name]
... | 0.005435 |
def eval_cached(self, statement, *args):
"""
Evaluate a statement and cache the result before returning.
Statements are evaluated inside the Trimesh object, and
Parameters
-----------
statement : str
Statement of valid python code
*args : list
... | 0.002307 |
def clean_markdown(text):
"""
Parse markdown sintaxt to html.
"""
result = text
if isinstance(text, str):
result = ''.join(
BeautifulSoup(markdown(text), 'lxml').findAll(text=True))
return result | 0.004149 |
def spec_compliant_decrypt(jwe, jwk, validate_claims=True,
expiry_seconds=None):
""" Decrypts a deserialized :class:`~jose.JWE`
:param jwe: An instance of :class:`~jose.JWE`
:param jwk: A `dict` representing the JWK required to decrypt the content
of the :class:`~... | 0.00044 |
def parse(cls, op):
"""Gets the enum for the op code
Args:
op: value of the op code (will be casted to int)
Returns:
The enum that matches the op code
"""
for event in cls:
if event.value == int(op):
return event
retur... | 0.006135 |
def sym(self, nested_scope=None):
"""Return the correspond symbolic number."""
if not nested_scope or self.name not in nested_scope[-1]:
raise NodeException("Expected local parameter name: ",
"name=%s, line=%s, file=%s" % (
... | 0.004566 |
def add_scope(self, scope_type, scope_name, scope_start, is_method=False):
"""we identified a scope and add it to positions."""
if self._curr is not None:
self._curr['end'] = scope_start - 1 # close last scope
self._curr = {
'type': scope_type, 'name': scope_name,
... | 0.00468 |
async def read(cls, node, block_device):
"""Get list of `Partitions`'s for `node` and `block_device`."""
if isinstance(node, str):
system_id = node
elif isinstance(node, Node):
system_id = node.system_id
else:
raise TypeError(
"node mus... | 0.002265 |
def write_source(self, filename):
'''
Save source to file by calling `write` on the root element.
'''
with open(filename, 'w') as fp:
return json.dump(self.message._elem, fp, indent=4, sort_keys=True) | 0.008032 |
def select_mask(cls, dataset, selection):
"""
Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e tuple ranges, slices, sets, lists or literals)
return a boolean mask over the rows in the Dataset object that
have been selected.
"""
... | 0.001233 |
def write_transform(transform, filename):
"""
Write ANTsTransform to file
ANTsR function: `writeAntsrTransform`
Arguments
---------
transform : ANTsTransform
transform to save
filename : string
filename of transform (file extension is ".mat" for affine transforms)
... | 0.002625 |
def _learning_rate_decay(hparams, warmup_steps=0):
"""Learning rate decay multiplier."""
scheme = hparams.learning_rate_decay_scheme
warmup_steps = tf.to_float(warmup_steps)
global_step = _global_step(hparams)
if not scheme or scheme == "none":
return tf.constant(1.)
tf.logging.info("Applying learning... | 0.007923 |
def get_conn(conn_type):
'''
Return a conn object for the passed VM data
'''
vm_ = get_configured_provider()
kwargs = vm_.copy() # pylint: disable=E1103
kwargs['username'] = vm_['username']
kwargs['auth_endpoint'] = vm_.get('identity_url', None)
kwargs['region'] = vm_['compute_region'... | 0.002597 |
def import_module(self, module):
"""
Allows remote execution of a local module. Depending on the
``remote_import_system`` attribute it may use execnet's implementation
or remoto's own based on JSON.
.. note:: It is not possible to use execnet's remote execution model on
... | 0.00618 |
def callable_name(callable_obj):
"""
Attempt to return a meaningful name identifying a callable or generator
"""
try:
if (isinstance(callable_obj, type)
and issubclass(callable_obj, param.ParameterizedFunction)):
return callable_obj.__name__
elif (isinstance(calla... | 0.005364 |
def _get_no_rowscols(self, bbox):
"""Returns tuple of number of rows and cols from bbox"""
if bbox is None:
return 1, 1
else:
(bb_top, bb_left), (bb_bottom, bb_right) = bbox
if bb_top is None:
bb_top = 0
if bb_left is None:
... | 0.00335 |
def get_product_metadata_name(self):
"""
:return: name of product metadata file
:rtype: str
"""
if self.safe_type == EsaSafeType.OLD_TYPE:
name = _edit_name(self.product_id, 'MTD', 'SAFL1C')
else:
name = 'MTD_{}'.format(self.product_id.split('_')[1... | 0.005291 |
def timer_cb(self, timer):
"""Timer callback. Update all our clocks."""
dt_now = datetime.utcnow().replace(tzinfo=pytz.utc)
self.logger.debug("timer fired. utc time is '%s'" % (str(dt_now)))
for clock in self.clocks.values():
clock.update_clock(dt_now)
# update clo... | 0.005435 |
def bna_config_cmd_status_output_status(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
bna_config_cmd_status = ET.Element("bna_config_cmd_status")
config = bna_config_cmd_status
output = ET.SubElement(bna_config_cmd_status, "output")
sta... | 0.004073 |
def _load(self, keyframe=True):
"""Read all remaining pages from file."""
if self._cached:
return
pages = self.pages
if not pages:
return
if not self._indexed:
self._seek(-1)
if not self._cache:
return
fh = self.pare... | 0.003044 |
def indexMatch(L, func):
'returns the smallest i for which func(L[i]) is true'
for i, x in enumerate(L):
if func(x):
return i | 0.006536 |
def by_title(cls, title, conn=None, google_user=None,
google_password=None):
""" Open the first document with the given ``title`` that is
returned by document search. """
conn = Connection.connect(conn=conn, google_user=google_user,
google_passw... | 0.004747 |
def _depending_columns(self, columns=None, columns_exclude=None, check_filter=True):
'''Find all depending column for a set of column (default all), minus the excluded ones'''
columns = set(columns or self.get_column_names(hidden=True))
if columns_exclude:
columns -= set(columns_excl... | 0.005256 |
def visitCodeDecl(self, ctx: ShExDocParser.CodeDeclContext):
""" codeDecl: '%' iri (CODE | '%')
CODE: : '{' (~[%\\] | '\\' [%\\] | UCHAR)* '%' '}' """
semact = SemAct()
semact.name = self.context.iri_to_iriref(ctx.iri())
if ctx.CODE():
semact.code = ctx.CODE().ge... | 0.009302 |
def account_pin(self, id):
"""
Pin / endorse a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}/pin'.format(str(id))
return self.__api_request('POST', url) | 0.012698 |
def get_assessment_bank_session(self, proxy):
"""Gets the ``OsidSession`` associated with the assessment banking service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.AssessmentBankSession) - an
``AssessmentBankSession``
raise: NullArgument - ``pro... | 0.004819 |
def _standalone_init(self, spark_master_address, pre_20_mode, requests_config, tags):
"""
Return a dictionary of {app_id: (app_name, tracking_url)} for the running Spark applications
"""
metrics_json = self._rest_request_to_json(
spark_master_address, SPARK_MASTER_STATE_PATH,... | 0.00418 |
def image_shape(img):
'''handle different image formats, returning (width,height) tuple'''
if hasattr(img, 'shape'):
return (img.shape[1], img.shape[0])
return (img.width, img.height) | 0.004926 |
def list_lights(self, selector='all'):
"""Given a selector (defaults to all), return a list of lights.
Without a selector provided, return list of all lights.
"""
return self.client.perform_request(
method='get', endpoint='lights/{}',
endpoint_args=[selector], pa... | 0.00597 |
def list_product(self, offset=0, limit=10, status=None, key=None):
"""
批量查询商品信息
详情请参考
http://mp.weixin.qq.com/wiki/15/7fa787701295b884410b5163e13313af.html
:param offset: 可选,批量查询的起始位置,从 0 开始,包含该起始位置
:param limit: 可选,批量查询的数量,默认为 10
:param status: 可选,支持按状态拉取。on为发布... | 0.00289 |
def get_candles(self, market, tick_interval):
"""
Used to get all tick candles for a market.
Endpoint:
1.1 NO EQUIVALENT
2.0 /pub/market/GetTicks
Example ::
{ success: true,
message: '',
result:
[ { O: 421.20630125... | 0.001807 |
def translate_indirect(properties, context_module):
"""Assumes that all feature values that start with '@' are
names of rules, used in 'context-module'. Such rules can be
either local to the module or global. Qualified local rules
with the name of the module."""
assert is_iterable_typed(properties, ... | 0.00142 |
def append_from_dict(self, the_dict):
"""
Creates a ``measurement.Measurement`` object from the supplied dict
and then appends it to the buffer
:param the_dict: dict
"""
m = Measurement.from_dict(the_dict)
self.append(m) | 0.00722 |
def bulk_save(self, action_list, **kwargs):
''' sends a passed in action_list to elasticsearch '''
lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3]))
lg.setLevel(self.log_level)
err_log = logging.getLogger("index.errors")
es = self.es
es_index = ge... | 0.003337 |
def log_request(self, handler: web.RequestHandler) -> None:
"""Handle access log."""
if 'log_function' in self.settings:
self.settings['log_function'](handler)
return
status = handler.get_status()
if status < 400:
log_method = logger.info
elif ... | 0.002778 |
def update_pos(pos_dict, start_key, nbr=2):
"Update the `pos_dict` by moving all positions after `start_key` by `nbr`."
for key,idx in pos_dict.items():
if str.lower(key) >= str.lower(start_key): pos_dict[key] += nbr
return pos_dict | 0.011905 |
def perform(self, store, count):
"""
Upgrade C{store} performing C{count} upgrades per transaction.
Also, catch any exceptions and print out something useful.
"""
self.count = count
try:
self.upgradeStore(store)
print 'Upgrade complete'
e... | 0.003268 |
def retcode_pillar(pillar_name):
'''
Run one or more nagios plugins from pillar data and get the result of cmd.retcode
The pillar have to be in this format::
------
webserver:
Ping_google:
- check_icmp: 8.8.8.8
- check_icmp: google.com
... | 0.001173 |
def tracked_array(array, dtype=None):
"""
Properly subclass a numpy ndarray to track changes.
Avoids some pitfalls of subclassing by forcing contiguous
arrays, and does a view into a TrackedArray.
Parameters
------------
array : array- like object
To be turned into a TrackedArray
... | 0.001221 |
def list_containers(self):
"""
list all available nspawn containers
:return: collection of instances of :class:`conu.backend.nspawn.container.NspawnContainer`
"""
data = run_cmd(["machinectl", "list", "--no-legend", "--no-pager"],
return_output=True)
... | 0.004702 |
def verify_client(self, client_jid = None, domains = None):
"""Verify certificate for a client.
Please note that `client_jid` is only a hint to choose from the names,
other JID may be returned if `client_jid` is not included in the
certificate.
:Parameters:
- `clien... | 0.00543 |
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
... | 0.003014 |
def to_dict(self):
"""Convert WordSet into raw dictionary data."""
return {
'id': self.set_id,
'title': self.title,
'terms': [term.to_dict() for term in self.terms]
} | 0.00885 |
def repositories(self):
"""Get dependencies by repositories
"""
if self.repo == "sbo":
self.sbo_case_insensitive()
self.find_pkg = sbo_search_pkg(self.name)
if self.find_pkg:
self.dependencies_list = Requires(self.flag).sbo(self.name)
e... | 0.002378 |
def getDefaultStack(layer = None, axolotl = False, groups = True, media = True, privacy = True, profiles = True):
"""
:param layer: An optional layer to put on top of default stack
:param axolotl: E2E encryption enabled/ disabled
:return: YowStack
"""
allLayers = YowStac... | 0.040968 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.