positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def get_values(self):
"""
returns final values (same result as tf.Session.run())
"""
return [self._cache.get(i.name,None) for i in self._original_evals] | returns final values (same result as tf.Session.run()) |
def _max_width_formatter(string, cols, separator='\n'):
"""Returns a freshly formatted
:param string: string to be formatted
:type string: basestring or clint.textui.colored.ColoredString
:param cols: max width the text to be formatted
:type cols: int
:param separator: separator to break rows
... | Returns a freshly formatted
:param string: string to be formatted
:type string: basestring or clint.textui.colored.ColoredString
:param cols: max width the text to be formatted
:type cols: int
:param separator: separator to break rows
:type separator: basestring |
def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False):
""" In-place simplification of segments
Args:
max_dist_error (float): Min distance error, in meters
max_speed_error (float): Min speed error, in km/h
topology_only: Boolean, optional. True... | In-place simplification of segments
Args:
max_dist_error (float): Min distance error, in meters
max_speed_error (float): Min speed error, in km/h
topology_only: Boolean, optional. True to keep
the topology, neglecting velocity and time
accurac... |
def _route(self, attr, args, kwargs, **fkwargs):
"""
The first argument is assumed to be the ``key`` for routing.
"""
key = get_key(args, kwargs)
found = self._hash.get_node(key)
if not found and len(self._down_connections) > 0:
raise self.HostListExhausted... | The first argument is assumed to be the ``key`` for routing. |
def WriteClientSnapshotHistory(self, clients, cursor=None):
"""Writes the full history for a particular client."""
client_id = clients[0].client_id
latest_timestamp = max(client.timestamp for client in clients)
query = ""
params = {
"client_id": db_utils.ClientIDToInt(client_id),
"l... | Writes the full history for a particular client. |
def sample_from_data(self, model, data):
"""Convert incoming sample *data* into a numpy array.
:param model:
The :class:`~Model` instance to use for making predictions.
:param data:
A dict-like with the sample's data, typically retrieved from
``request.args`` or si... | Convert incoming sample *data* into a numpy array.
:param model:
The :class:`~Model` instance to use for making predictions.
:param data:
A dict-like with the sample's data, typically retrieved from
``request.args`` or similar. |
def findBest(self, pattern):
""" Returns the *best* match in the region (instead of the first match) """
findFailedRetry = True
while findFailedRetry:
best_match = None
all_matches = self.findAll(pattern)
for match in all_matches:
if best_match... | Returns the *best* match in the region (instead of the first match) |
def is_iterable(obj):
"""
Are we being asked to look up a list of things, instead of a single thing?
We check for the `__iter__` attribute so that this can cover types that
don't have to be known by this module, such as NumPy arrays.
Strings, however, should be considered as atomic values to look u... | Are we being asked to look up a list of things, instead of a single thing?
We check for the `__iter__` attribute so that this can cover types that
don't have to be known by this module, such as NumPy arrays.
Strings, however, should be considered as atomic values to look up, not
iterables. The same goe... |
def add_all_database_reactions(model, compartments):
"""Add all reactions from database that occur in given compartments.
Args:
model: :class:`psamm.metabolicmodel.MetabolicModel`.
"""
added = set()
for rxnid in model.database.reactions:
reaction = model.database.get_reaction(rxnid... | Add all reactions from database that occur in given compartments.
Args:
model: :class:`psamm.metabolicmodel.MetabolicModel`. |
def authenticate(self, username, password):
"""
Authenticate user on server.
:param username: Username used to be authenticated.
:type username: six.string_types
:param password: Password used to be authenticated.
:type password: six.string_types
:return: True if... | Authenticate user on server.
:param username: Username used to be authenticated.
:type username: six.string_types
:param password: Password used to be authenticated.
:type password: six.string_types
:return: True if successful.
:raises: InvalidCredentials, Authentication... |
def insert_text_to(cursor, text, fmt):
"""Helper to print text, taking into account backspaces"""
while True:
index = text.find(chr(8)) # backspace
if index == -1:
break
cursor.insertText(text[:index], fmt)
if cursor.positionInBlock() > 0:
cursor.deletePr... | Helper to print text, taking into account backspaces |
def pw_converter(handler, flt):
"""Convert column name to filter."""
import peewee as pw
if isinstance(flt, Filter):
return flt
model = handler.model
field = getattr(model, flt)
if isinstance(field, pw.BooleanField):
return PWBoolFilter(flt)
if field.choices:
choi... | Convert column name to filter. |
def first_interesting_frame(self):
"""
Traverse down the frame hierarchy until a frame is found with more than one child
"""
root_frame = self.root_frame()
frame = root_frame
while len(frame.children) <= 1:
if frame.children:
frame = frame.chi... | Traverse down the frame hierarchy until a frame is found with more than one child |
def infix(self, node, children):
'infix = "(" expr operator expr ")"'
_, expr1, operator, expr2, _ = children
return operator(expr1, expr2) | infix = "(" expr operator expr ")" |
def copy_patches(ptches0):
""" return a list of copied input matplotlib patches
:param ptches0: list of matploblib.patches objects
:return: copyed patches object
"""
if not isinstance(ptches0, list):
ptches0 = list(ptches0)
copyed_ptches = []
... | return a list of copied input matplotlib patches
:param ptches0: list of matploblib.patches objects
:return: copyed patches object |
def put_file(self, file_path, content, content_type=None, compress=None, cache_control=None):
"""
Args:
filename (string): it can contains folders
content (string): binary data to save
"""
return self.put_files([ (file_path, content) ],
content_type=content_type,
compress=comp... | Args:
filename (string): it can contains folders
content (string): binary data to save |
def get_patch_op(self, keypath, value, op='replace'):
"""
Return an object that describes a change of configuration on the given staging.
Setting will be applied on all available HTTP methods.
"""
if isinstance(value, bool):
value = str(value).lower()
return {... | Return an object that describes a change of configuration on the given staging.
Setting will be applied on all available HTTP methods. |
def _to_unicode(s):
"""
decode a string as ascii or utf8 if possible (as required by the sftp
protocol). if neither works, just return a byte string because the server
probably doesn't know the filename's encoding.
"""
try:
return s.encode('ascii')
except (UnicodeError, AttributeErr... | decode a string as ascii or utf8 if possible (as required by the sftp
protocol). if neither works, just return a byte string because the server
probably doesn't know the filename's encoding. |
def unit_net_value(self):
"""
[float] 实时净值
"""
if self._units == 0:
return np.nan
return self.total_value / self._units | [float] 实时净值 |
def _rsplit(expr, pat=None, n=-1):
"""
Split each string in the Series/Index by the given delimiter string,
starting at the end of the string and working to the front.
Equivalent to str.rsplit().
:param expr:
:param pat: Separator to split on. If None, splits on whitespace
:param n: None, 0... | Split each string in the Series/Index by the given delimiter string,
starting at the end of the string and working to the front.
Equivalent to str.rsplit().
:param expr:
:param pat: Separator to split on. If None, splits on whitespace
:param n: None, 0 and -1 will be interpreted as return all split... |
def electric_field_amplitude_intensity(s0,Omega=1.0e6):
'''This function returns the value of E0 (the amplitude of the electric field)
at a given saturation parameter s0=I/I0, where I0=2.50399 mW/cm^2 is the
saturation intensity of the D2 line of Rubidium for linearly polarized light.'''
e0=hbar*Omega/(e*a0) #T... | This function returns the value of E0 (the amplitude of the electric field)
at a given saturation parameter s0=I/I0, where I0=2.50399 mW/cm^2 is the
saturation intensity of the D2 line of Rubidium for linearly polarized light. |
def generate_gradient(self, color_list, size=101):
"""
Create a gradient of size colors that passes through the colors
give in the list (the resultant list may not be exactly size long).
The gradient will be evenly distributed.
colors should be in hex format eg '#FF00FF'
... | Create a gradient of size colors that passes through the colors
give in the list (the resultant list may not be exactly size long).
The gradient will be evenly distributed.
colors should be in hex format eg '#FF00FF' |
def check(self, request, secret):
"""Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature.
This verifies every element of the signature, including the timestamp's value.
Does not alter the request.
Keyword arguments:
... | Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature.
This verifies every element of the signature, including the timestamp's value.
Does not alter the request.
Keyword arguments:
request -- A request object which can be cons... |
def write_header(self, chunk):
"""Write to header.
Note: the header stream is only available to write before write body.
:param chunk: content to write to header
:except TChannelError:
Raise TChannelError if the response's flush() has been called
"""
if se... | Write to header.
Note: the header stream is only available to write before write body.
:param chunk: content to write to header
:except TChannelError:
Raise TChannelError if the response's flush() has been called |
def _calc_bkg_bkgrms(self):
"""
Calculate the background and background RMS estimate in each of
the meshes.
Both meshes are computed at the same time here method because
the filtering of both depends on the background mesh.
The ``background_mesh`` and ``background_rms_m... | Calculate the background and background RMS estimate in each of
the meshes.
Both meshes are computed at the same time here method because
the filtering of both depends on the background mesh.
The ``background_mesh`` and ``background_rms_mesh`` images are
equivalent to the low-r... |
def keys_in_dict(d, parent_key, keys):
"""
Create a list of keys from a dict recursively.
"""
for key, value in d.iteritems():
if isinstance(value, dict):
keys_in_dict(value, key, keys)
else:
if parent_key:
prefix = parent_key + "."
els... | Create a list of keys from a dict recursively. |
def add_to(self, parent, name=None, index=None):
"""Add element to a parent."""
parent.add_child(self, name=name, index=index)
return self | Add element to a parent. |
def field_cols(model):
""" Get the models columns in a friendly SQL format
This will be a string of comma separated field
names prefixed by the models resource type.
TIP: to_manys are not located on the table in Postgres
& are instead application references, so any referen... | Get the models columns in a friendly SQL format
This will be a string of comma separated field
names prefixed by the models resource type.
TIP: to_manys are not located on the table in Postgres
& are instead application references, so any reference
to there column nam... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'from_') and self.from_ is not None:
_dict['from'] = self.from_
if hasattr(self, 'to') and self.to is not None:
_dict['to'] = self.to
if hasattr(self, '... | Return a json dictionary representing this model. |
def from_url(cls, url):
"""
Creates a `~mocpy.moc.MOC` object from a given url.
Parameters
----------
url : str
The url of a FITS file storing a MOC.
Returns
-------
result : `~mocpy.moc.MOC`
The resulting MOC.
"""
... | Creates a `~mocpy.moc.MOC` object from a given url.
Parameters
----------
url : str
The url of a FITS file storing a MOC.
Returns
-------
result : `~mocpy.moc.MOC`
The resulting MOC. |
def ascii2h5(bh_dir=None):
"""
Convert the Burstein & Heiles (1982) dust map from ASCII to HDF5.
"""
if bh_dir is None:
bh_dir = os.path.join(data_dir_default, 'bh')
fname = os.path.join(bh_dir, '{}.ascii')
f = h5py.File('bh.h5', 'w')
for region in ('hinorth', 'hisouth'):
... | Convert the Burstein & Heiles (1982) dust map from ASCII to HDF5. |
def processor_for(content_model_or_slug, exact_page=False):
"""
Decorator that registers the decorated function as a page
processor for the given content model or slug.
When a page exists that forms the prefix of custom urlpatterns
in a project (eg: the blog page and app), the page will be
adde... | Decorator that registers the decorated function as a page
processor for the given content model or slug.
When a page exists that forms the prefix of custom urlpatterns
in a project (eg: the blog page and app), the page will be
added to the template context. Passing in ``True`` for the
``exact_page`... |
def residue_network():
"""The network for the residue example.
Current and previous state are all nodes OFF.
Diagram::
+~~~~~~~+ +~~~~~~~+
| A | | B |
+~~>| (AND) | | (AND) |<~~+
| +~~~~~~~+ +~~~~~~~+ |
... | The network for the residue example.
Current and previous state are all nodes OFF.
Diagram::
+~~~~~~~+ +~~~~~~~+
| A | | B |
+~~>| (AND) | | (AND) |<~~+
| +~~~~~~~+ +~~~~~~~+ |
| ^ ... |
def perform_es_corr(self, lattice, q, step=1e-4):
"""
Peform Electrostatic Freysoldt Correction
"""
logger.info("Running Freysoldt 2011 PC calculation (should be " "equivalent to sxdefectalign)")
logger.debug("defect lattice constants are (in angstroms)" + str(lattice.abc))
... | Peform Electrostatic Freysoldt Correction |
def set_foreign_key(self, parent_table, parent_column, child_table, child_column):
"""Create a Foreign Key constraint on a column from a table."""
self.execute('ALTER TABLE {0} ADD FOREIGN KEY ({1}) REFERENCES {2}({3})'.format(parent_table, parent_column,
... | Create a Foreign Key constraint on a column from a table. |
def check(self, hash_algorithm, offset=0, length=0, block_size=0):
"""
Ask the server for a hash of a section of this file. This can be used
to verify a successful upload or download, or for various rsync-like
operations.
The file is hashed from ``offset``, for ``length`` bytes... | Ask the server for a hash of a section of this file. This can be used
to verify a successful upload or download, or for various rsync-like
operations.
The file is hashed from ``offset``, for ``length`` bytes.
If ``length`` is 0, the remainder of the file is hashed. Thus, if both
... |
def run_job(self, job_details, workflow, vm_instance_name):
"""
Execute a workflow on a worker.
:param job_details: object: details about job(id, name, created date, workflow version)
:param workflow: jobapi.Workflow: url to workflow and parameters to use
:param vm_instance_name:... | Execute a workflow on a worker.
:param job_details: object: details about job(id, name, created date, workflow version)
:param workflow: jobapi.Workflow: url to workflow and parameters to use
:param vm_instance_name: name of the instance lando_worker is running on (this passed back in the respon... |
def remove_stream_handlers(logger=None):
"""
Remove only stream handlers from the specified logger
:param logger: logging name or object to modify, defaults to root logger
"""
if not isinstance(logger, logging.Logger):
logger = logging.getLogger(logger)
new_handlers = []
for handle... | Remove only stream handlers from the specified logger
:param logger: logging name or object to modify, defaults to root logger |
def make_int(value, missing=-1):
"""Convert string value to long, '' to missing"""
if isinstance(value, six.string_types):
if not value.strip():
return missing
elif value is None:
return missing
return int(value) | Convert string value to long, '' to missing |
def estimate_vt(injections, mchirp_sampler, model_pdf, **kwargs):
#Try including ifar threshold
'''Based on injection strategy and the desired astro model estimate the injected volume.
Scale injections and estimate sensitive volume.
Parameters
----------
injections: dictionary
... | Based on injection strategy and the desired astro model estimate the injected volume.
Scale injections and estimate sensitive volume.
Parameters
----------
injections: dictionary
Dictionary obtained after reading injections from read_injections
mchirp_sampler: function
... |
def set_sqlite_pragmas(self):
"""
Sets the connection PRAGMAs for the sqlalchemy engine stored in self.engine.
It currently sets:
- journal_mode to WAL
:return: None
"""
def _pragmas_on_connect(dbapi_con, con_record):
dbapi_con.execute("PRAGMA journ... | Sets the connection PRAGMAs for the sqlalchemy engine stored in self.engine.
It currently sets:
- journal_mode to WAL
:return: None |
def _set_directories(self):
'''Initialize variables based on evidence about the directories.'''
if self._dirs['initial'] == None:
self._dirs['base'] = discover_base_dir(self._dirs['run'])
else:
self._dirs['base'] = discover_base_dir(self._dirs['initial'])
# no... | Initialize variables based on evidence about the directories. |
def LSL(self, a):
"""
Shifts all bits of accumulator A or B or memory location M one place to
the left. Bit zero is loaded with a zero. Bit seven of accumulator A or
B or memory location M is shifted into the C (carry) bit.
This is a duplicate assembly-language mnemonic for the ... | Shifts all bits of accumulator A or B or memory location M one place to
the left. Bit zero is loaded with a zero. Bit seven of accumulator A or
B or memory location M is shifted into the C (carry) bit.
This is a duplicate assembly-language mnemonic for the single machine
instruction ASL... |
async def zrange(self, name, start, end, desc=False, withscores=False,
score_cast_func=float):
"""
Return a range of values from sorted set ``name`` between
``start`` and ``end`` sorted in ascending order.
``start`` and ``end`` can be negative, indicating the end of... | Return a range of values from sorted set ``name`` between
``start`` and ``end`` sorted in ascending order.
``start`` and ``end`` can be negative, indicating the end of the range.
``desc`` a boolean indicating whether to sort the results descendingly
``withscores`` indicates to return ... |
def plus_replacement(random, population, parents, offspring, args):
"""Performs "plus" replacement.
This function performs "plus" replacement, which means that
the entire existing population is replaced by the best
population-many elements from the combined set of parents and
offspring.
... | Performs "plus" replacement.
This function performs "plus" replacement, which means that
the entire existing population is replaced by the best
population-many elements from the combined set of parents and
offspring.
.. Arguments:
random -- the random number generator object
... |
def remove_asset(self, asset_id, composition_id):
"""Removes an ``Asset`` from a ``Composition``.
arg: asset_id (osid.id.Id): ``Id`` of the ``Asset``
arg: composition_id (osid.id.Id): ``Id`` of the
``Composition``
raise: NotFound - ``asset_id`` ``not found in com... | Removes an ``Asset`` from a ``Composition``.
arg: asset_id (osid.id.Id): ``Id`` of the ``Asset``
arg: composition_id (osid.id.Id): ``Id`` of the
``Composition``
raise: NotFound - ``asset_id`` ``not found in composition_id``
raise: NullArgument - ``asset_id`` or ... |
def _read_protos(self, size):
"""Read next layer protocol type.
Positional arguments:
* size -- int, buffer size
Returns:
* str -- next layer's protocol name
"""
_byte = self._read_unpack(size)
_prot = TP_PROTO.get(_byte)
return _prot | Read next layer protocol type.
Positional arguments:
* size -- int, buffer size
Returns:
* str -- next layer's protocol name |
def consolidate(self, args):
""" Consolidate the provided arguments.
If the provided arguments have matching options, this performs a type conversion.
For any option that has a default value and is not present in the provided
arguments, the default value is added.
Args:
... | Consolidate the provided arguments.
If the provided arguments have matching options, this performs a type conversion.
For any option that has a default value and is not present in the provided
arguments, the default value is added.
Args:
args (dict): A dictionary of the pro... |
def _copy_globalization_resources(self):
'''Copy the language resource files for python api functions
This function copies the TopologySplpy Resource files from Topology toolkit directory
into the impl/nl folder of the project.
Returns: the list with the copied locale strings'''
... | Copy the language resource files for python api functions
This function copies the TopologySplpy Resource files from Topology toolkit directory
into the impl/nl folder of the project.
Returns: the list with the copied locale strings |
def encrypt(self, plain, algorithm='md5'):
""" 简单封装系统加密
:param plain: 待加密内容
:type plain: ``str/bytes``
:param algorithm: 加密算法
:type algorithm: str
:return:
:rtype:
"""
plain = helper.to_bytes(plain)
return getattr(hashlib, algorithm)(plai... | 简单封装系统加密
:param plain: 待加密内容
:type plain: ``str/bytes``
:param algorithm: 加密算法
:type algorithm: str
:return:
:rtype: |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: FieldContext for this FieldInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldCo... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: FieldContext for this FieldInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldContext |
def _chunks(l, ncols):
"""Yield successive n-sized chunks from list, l."""
assert isinstance(ncols, int), "ncols must be an integer"
for i in range(0, len(l), ncols):
yield l[i: i+ncols] | Yield successive n-sized chunks from list, l. |
def mols_from_text(text, no_halt=True, assign_descriptors=True):
"""Returns molecules generated from sdfile text
Throws:
StopIteration: if the text does not have molecule
ValueError: if Unsupported symbol is found
"""
if isinstance(text, bytes):
t = tx.decode(text)
else:
... | Returns molecules generated from sdfile text
Throws:
StopIteration: if the text does not have molecule
ValueError: if Unsupported symbol is found |
def _date_from_match(match_object):
"""
Create a date object from a regular expression match.
The regular expression match is expected to be from _RE_DATE or
_RE_DATETIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: A date object.
... | Create a date object from a regular expression match.
The regular expression match is expected to be from _RE_DATE or
_RE_DATETIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: A date object.
@rtype: B{datetime}.I{date} |
def new_calendar(self, calendar_name):
""" Creates a new calendar
:param str calendar_name: name of the new calendar
:return: a new Calendar instance
:rtype: Calendar
"""
if not calendar_name:
return None
url = self.build_url(self._endpoints.get('roo... | Creates a new calendar
:param str calendar_name: name of the new calendar
:return: a new Calendar instance
:rtype: Calendar |
def __setUpTrakers(self):
''' set symbols '''
for symbol in self.symbols:
self.__trakers[symbol]=OneTraker(symbol, self, self.buyingRatio) | set symbols |
def _format_list(self, data):
"""
Format a list to use in javascript
"""
dataset = "["
i = 0
for el in data:
if pd.isnull(el):
dataset += "null"
else:
dtype = type(data[i])
if dtype == int or dtype ==... | Format a list to use in javascript |
def removeStepListener(listener):
"""removeStepListener(traci.StepListener) -> bool
Remove the step listener from traci's step listener container.
Returns True if the listener was removed successfully, False if it wasn't registered.
"""
if listener in _stepListeners:
_stepListeners.remove(l... | removeStepListener(traci.StepListener) -> bool
Remove the step listener from traci's step listener container.
Returns True if the listener was removed successfully, False if it wasn't registered. |
def app_update_state(app_id,state):
"""
update app state
"""
try:
create_at = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
conn = get_conn()
c = conn.cursor()
c.execute("UPDATE app SET state='{0}',change_at='{1}' WHERE id='{2}'".format(state, create_at, app_id))
... | update app state |
def update_data_frames(network, cluster_weights, dates, hours):
""" Updates the snapshots, snapshots weights and the dataframes based on
the original data in the network and the medoids created by clustering
these original data.
Parameters
-----------
network : pyPSA network object
cluster_... | Updates the snapshots, snapshots weights and the dataframes based on
the original data in the network and the medoids created by clustering
these original data.
Parameters
-----------
network : pyPSA network object
cluster_weights: dictionary
dates: Datetimeindex
Returns
-------
... |
def predict(rf_model, features):
"""
Return label and probability estimated.
Parameters
----------
rf_model : sklearn.ensemble.RandomForestClassifier
The UPSILoN random forests model.
features : array_like
A list of features estimated by UPSILoN.
Returns
-------
lab... | Return label and probability estimated.
Parameters
----------
rf_model : sklearn.ensemble.RandomForestClassifier
The UPSILoN random forests model.
features : array_like
A list of features estimated by UPSILoN.
Returns
-------
label : str
A predicted label (i.e. clas... |
def _add_data(self, plotter_cls, *args, **kwargs):
"""
Visualize this data array
Parameters
----------
%(Plotter.parameters.no_data)s
Returns
-------
psyplot.plotter.Plotter
The plotter that visualizes the data
"""
# this meth... | Visualize this data array
Parameters
----------
%(Plotter.parameters.no_data)s
Returns
-------
psyplot.plotter.Plotter
The plotter that visualizes the data |
def _array2image_list(self, array):
"""
maps 1d vector of joint exposures in list of 2d images of single exposures
:param array: 1d numpy array
:return: list of 2d numpy arrays of size of exposures
"""
image_list = []
k = 0
for i in range(self._num_bands... | maps 1d vector of joint exposures in list of 2d images of single exposures
:param array: 1d numpy array
:return: list of 2d numpy arrays of size of exposures |
def ping(token_or_hostname=None):
""" Send an echo request to a nago host.
Arguments:
token_or_host_name -- The remote node to ping
If node is not provided, simply return pong
You can use the special nodenames "server" or "master"
"""
if... | Send an echo request to a nago host.
Arguments:
token_or_host_name -- The remote node to ping
If node is not provided, simply return pong
You can use the special nodenames "server" or "master" |
def ssl_options(self):
"""Check the config to see if SSL configuration options have been passed
and replace none, option, and required with the correct values in
the certreqs attribute if it is specified.
:rtype: dict
"""
opts = self.namespace.server.get(config.SSL_OPTI... | Check the config to see if SSL configuration options have been passed
and replace none, option, and required with the correct values in
the certreqs attribute if it is specified.
:rtype: dict |
def hash_and_stat_file(self, path, saltenv='base'):
'''
The same as hash_file, but also return the file's mode, or None if no
mode data is present.
'''
hash_result = self.hash_file(path, saltenv)
try:
path = self._check_proto(path)
except MinionError a... | The same as hash_file, but also return the file's mode, or None if no
mode data is present. |
def find_prekeyed(self, value, key):
"""
Find a value in a node, using a key function. The value is already a
key.
"""
while self is not NULL:
direction = cmp(value, key(self.value))
if direction < 0:
self = self.left
elif dire... | Find a value in a node, using a key function. The value is already a
key. |
def get_lockfile_filename(impl, working_dir):
"""
Get the absolute path to the chain's indexing lockfile
"""
lockfile_name = impl.get_virtual_chain_name() + ".lock"
return os.path.join(working_dir, lockfile_name) | Get the absolute path to the chain's indexing lockfile |
def parameter(self, parameter_id):
"""Return the specified global parameter (the entire object, not just the value)"""
for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable
for parameter in parameters:
if parameter.id == parameter_id:
... | Return the specified global parameter (the entire object, not just the value) |
def get_message_headers(self, section: Sequence[int] = None,
subset: Collection[bytes] = None,
inverse: bool = False) -> Writeable:
"""Get the headers from the message or a ``message/rfc822`` sub-part of
the message..
The ``section`` argum... | Get the headers from the message or a ``message/rfc822`` sub-part of
the message..
The ``section`` argument can index a nested sub-part of the message.
For example, ``[2, 3]`` would get the 2nd sub-part of the message and
then index it for its 3rd sub-part.
Args:
se... |
def listRuns(self, **kwargs):
"""
API to list all run dictionary, for example: [{'run_num': [160578, 160498, 160447, 160379]}].
At least one parameter is mandatory.
:param logical_file_name: List all runs in the file
:type logical_file_name: str
:param block_name: List ... | API to list all run dictionary, for example: [{'run_num': [160578, 160498, 160447, 160379]}].
At least one parameter is mandatory.
:param logical_file_name: List all runs in the file
:type logical_file_name: str
:param block_name: List all runs in the block
:type block_name: st... |
def dre_dc(self, pars):
r"""
:math:Add formula
"""
self._set_parameters(pars)
# term 1
num1a = np.log(self.w * self.tau) * self.otc * np.sin(self.ang)
num1b = self.otc * np.cos(self.ang) * np.pi / 2.0
term1 = (num1a + num1b) / self.denom
# term 2
... | r"""
:math:Add formula |
def poll(self, poll_rate=None, timeout=None):
"""Return the status of a task or timeout.
There are several API calls that trigger asynchronous tasks, such as
synchronizing a repository, or publishing or promoting a content view.
It is possible to check on the status of a task if you kno... | Return the status of a task or timeout.
There are several API calls that trigger asynchronous tasks, such as
synchronizing a repository, or publishing or promoting a content view.
It is possible to check on the status of a task if you know its UUID.
This method polls a task once every `... |
def get_dev_mac_learn(devid, auth, url):
'''
function takes devid of specific device and issues a RESTFUL call to gather the current IP-MAC learning entries on
the target device.
:param devid: int value of the target device
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.a... | function takes devid of specific device and issues a RESTFUL call to gather the current IP-MAC learning entries on
the target device.
:param devid: int value of the target device
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interfa... |
def convert(image, shape, gray=False, dtype='float64', normalize='max'):
"""Convert image to standardized format.
Several properties of the input image may be changed including the shape,
data type and maximal value of the image. In addition, this function may
convert the image into an ODL object and/o... | Convert image to standardized format.
Several properties of the input image may be changed including the shape,
data type and maximal value of the image. In addition, this function may
convert the image into an ODL object and/or a gray scale image. |
async def syscall(self, func, ignoreException = False):
"""
Call a syscall method and retrieve its return value
"""
ev = await self.syscall_noreturn(func)
if hasattr(ev, 'exception'):
if ignoreException:
return
else:
raise e... | Call a syscall method and retrieve its return value |
def hostname(self, value):
"""
The hostname where the log message was created.
Should be the first part of the hostname, or
an IP address. Should NOT be set to a fully
qualified domain name.
"""
if value is None:
value = socket.gethostname()
... | The hostname where the log message was created.
Should be the first part of the hostname, or
an IP address. Should NOT be set to a fully
qualified domain name. |
def resource_of_node(resources, node):
""" Returns resource of node.
"""
for resource in resources:
model = getattr(resource, 'model', None)
if type(node) == model:
return resource
return BasePageResource | Returns resource of node. |
def _set_axis(self,traces,on=None,side='right',title=''):
"""
Sets the axis in which each trace should appear
If the axis doesn't exist then a new axis is created
Parameters:
-----------
traces : list(str)
List of trace names
on : string
The axis in which the traces should be placed.
If this is not i... | Sets the axis in which each trace should appear
If the axis doesn't exist then a new axis is created
Parameters:
-----------
traces : list(str)
List of trace names
on : string
The axis in which the traces should be placed.
If this is not indicated then a new axis will be
created
side : string
S... |
def cancel_root_generation(self):
"""Cancel any in-progress root generation attempt.
This clears any progress made. This must be called to change the OTP or PGP key being used.
Supported methods:
DELETE: /sys/generate-root/attempt. Produces: 204 (empty body)
:return: The r... | Cancel any in-progress root generation attempt.
This clears any progress made. This must be called to change the OTP or PGP key being used.
Supported methods:
DELETE: /sys/generate-root/attempt. Produces: 204 (empty body)
:return: The response of the request.
:rtype: reque... |
def __callback(self, event, *args, **kwargs):
# type: (str, *Any, **Any) -> Any
"""
Calls the registered method in the component for the given event
:param event: An event (IPOPO_CALLBACK_VALIDATE, ...)
:return: The callback result, or None
:raise Exception: Something we... | Calls the registered method in the component for the given event
:param event: An event (IPOPO_CALLBACK_VALIDATE, ...)
:return: The callback result, or None
:raise Exception: Something went wrong |
def essays(self):
"""Copy essays from the source profile to the destination profile."""
for essay_name in self.dest_user.profile.essays.essay_names:
setattr(self.dest_user.profile.essays, essay_name,
getattr(self.source_profile.essays, essay_name)) | Copy essays from the source profile to the destination profile. |
def from_shapely(sgeom, srid=None):
"""
Create a Geometry from a Shapely geometry and the specified SRID.
The Shapely geometry will not be modified.
"""
if SHAPELY:
WKBWriter.defaults["include_srid"] = True
if srid:
lgeos.GEOSSetSRID(sgeom... | Create a Geometry from a Shapely geometry and the specified SRID.
The Shapely geometry will not be modified. |
def load_from_json(data):
"""
Load a :class:`Item` from a dictionary ot string (that will be parsed
as json)
"""
if isinstance(data, str):
data = json.loads(data)
return Item(data['title'], data['uri']) | Load a :class:`Item` from a dictionary ot string (that will be parsed
as json) |
def _visibleToRealColumn(self, text, visiblePos):
"""If \t is used, real position of symbol in block and visible position differs
This function converts visible to real.
Bigger value is returned, if visiblePos is in the middle of \t, None if text is too short
"""
if visiblePos ==... | If \t is used, real position of symbol in block and visible position differs
This function converts visible to real.
Bigger value is returned, if visiblePos is in the middle of \t, None if text is too short |
def get_id(self):
"""Converts a User ID and parts of a User password hash to a token."""
# This function is used by Flask-Login to store a User ID securely as a browser cookie.
# The last part of the password is included to invalidate tokens when password change.
# user_id and password_... | Converts a User ID and parts of a User password hash to a token. |
def get_from_headers(request, key):
"""Try to read a value named ``key`` from the headers.
"""
value = request.headers.get(key)
return to_native(value) | Try to read a value named ``key`` from the headers. |
def diffuse_advanced(self, heatColumnName=None, time=None, verbose=False):
"""
Diffusion will send the selected network view and its selected nodes to
a web-based REST service to calculate network propagation. Results are
returned and represented by columns in the node table.
Col... | Diffusion will send the selected network view and its selected nodes to
a web-based REST service to calculate network propagation. Results are
returned and represented by columns in the node table.
Columns are created for each execution of Diffusion and their names are
returned in the re... |
def license_present(name):
'''
Ensures that the specified PowerPath license key is present
on the host.
name
The license key to ensure is present
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['powerpath.has_... | Ensures that the specified PowerPath license key is present
on the host.
name
The license key to ensure is present |
def writefile(filename, content):
"""
writes the content into the file
:param filename: the filename
:param content: teh content
:return:
"""
with open(path_expand(filename), 'w') as outfile:
outfile.write(content) | writes the content into the file
:param filename: the filename
:param content: teh content
:return: |
def add(self, level, message, extra_tags='', *args, **kwargs):
"""
Queues a message to be stored.
The message is only queued if it contained something and its level is
not less than the recording level (``self.level``).
"""
if not message:
return
... | Queues a message to be stored.
The message is only queued if it contained something and its level is
not less than the recording level (``self.level``). |
def _exec_callers(xinst, result):
"""Adds the dependency calls from the specified executable instance
to the results dictionary.
"""
for depkey, depval in xinst.dependencies.items():
if depval.target is not None:
if depval.target.name in result:
if xinst not in result... | Adds the dependency calls from the specified executable instance
to the results dictionary. |
def do_execute_direct(self, code: str, silent: bool = False) -> [str, dict]:
"""
This is the main method that takes code from the Jupyter cell and submits it to the SAS server
:param code: code from the cell
:param silent:
:return: str with either the log or list
"""
... | This is the main method that takes code from the Jupyter cell and submits it to the SAS server
:param code: code from the cell
:param silent:
:return: str with either the log or list |
def compute_message_authenticator(radius_packet, packed_req_authenticator,
shared_secret):
"""
Computes the "Message-Authenticator" of a given RADIUS packet.
"""
data = prepare_packed_data(radius_packet, packed_req_authenticator)
radius_hmac... | Computes the "Message-Authenticator" of a given RADIUS packet. |
def fbresnet152(num_classes=1000, pretrained='imagenet'):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = FBResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes)
if pretrained is not None:
settings = pretra... | Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet |
def install(self, goal=None, first=False, replace=False, before=None, after=None):
"""Install the task in the specified goal (or a new goal with the same name as the task).
The placement of the task in the execution list of the goal defaults to the end but can be
:rtype : object
influence by specifying... | Install the task in the specified goal (or a new goal with the same name as the task).
The placement of the task in the execution list of the goal defaults to the end but can be
:rtype : object
influence by specifying exactly one of the following arguments:
:API: public
:param first: Places this ... |
def find_data_files(source, target, patterns):
"""
Locates the specified data-files and returns the matches
in a data_files compatible format.
source is the root of the source data tree.
Use '' or '.' for current directory.
target is the root of the target data tree.
Use '' or '.' f... | Locates the specified data-files and returns the matches
in a data_files compatible format.
source is the root of the source data tree.
Use '' or '.' for current directory.
target is the root of the target data tree.
Use '' or '.' for the distribution directory.
patterns is a sequence o... |
def expire(self, key, timeout):
"""Set a timeout on key. After the timeout has expired, the key will
automatically be deleted. A key with an associated timeout is often
said to be volatile in Redis terminology.
The timeout is cleared only when the key is removed using the
:meth:... | Set a timeout on key. After the timeout has expired, the key will
automatically be deleted. A key with an associated timeout is often
said to be volatile in Redis terminology.
The timeout is cleared only when the key is removed using the
:meth:`~tredis.RedisClient.delete` method or over... |
def join(self, other, **kwargs):
"""Joins a list or two objects together.
Args:
other: The other object(s) to join on.
Returns:
Joined objects.
"""
if not isinstance(other, list):
other = [other]
return self._join_list_of_managers(oth... | Joins a list or two objects together.
Args:
other: The other object(s) to join on.
Returns:
Joined objects. |
def build_sourcemap(sources):
"""
Similar to build_headermap(), but builds a dictionary of includes from
the "source" files (i.e. ".c/.cc" files).
"""
sourcemap = {}
for sfile in sources:
inc = find_includes(sfile)
sourcemap[sfile] = set(inc)
return sourcemap | Similar to build_headermap(), but builds a dictionary of includes from
the "source" files (i.e. ".c/.cc" files). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.