code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _to_DOM(self):
"""
Dumps object data to a fully traversable DOM representation of the
object.
:returns: a ``xml.etree.Element`` object
"""
root_node = ET.Element("ozone")
reference_time_node = ET.SubElement(root_node, "reference_time")
reference_time... | Dumps object data to a fully traversable DOM representation of the
object.
:returns: a ``xml.etree.Element`` object |
def add_ovsbridge_linuxbridge(name, bridge):
''' Add linux bridge to the named openvswitch bridge
:param name: Name of ovs bridge to be added to Linux bridge
:param bridge: Name of Linux bridge to be added to ovs bridge
:returns: True if veth is added between ovs bridge and linux bridge,
False other... | Add linux bridge to the named openvswitch bridge
:param name: Name of ovs bridge to be added to Linux bridge
:param bridge: Name of Linux bridge to be added to ovs bridge
:returns: True if veth is added between ovs bridge and linux bridge,
False otherwise |
def get_affinity_group_properties(self, affinity_group_name):
'''
Returns the system properties associated with the specified affinity
group.
affinity_group_name:
The name of the affinity group.
'''
_validate_not_none('affinity_group_name', affinity_group_nam... | Returns the system properties associated with the specified affinity
group.
affinity_group_name:
The name of the affinity group. |
def resample(self, rule, how=None, axis=0, fill_method=None, closed=None,
label=None, convention='start', kind=None, loffset=None,
limit=None, base=0, on=None, level=None):
"""
Resample time-series data.
Convenience method for frequency conversion and resamplin... | Resample time-series data.
Convenience method for frequency conversion and resampling of time
series. Object must have a datetime-like index (`DatetimeIndex`,
`PeriodIndex`, or `TimedeltaIndex`), or pass datetime-like values
to the `on` or `level` keyword.
Parameters
--... |
def read_api_service(self, name, **kwargs): # noqa: E501
"""read_api_service # noqa: E501
read the specified APIService # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read... | read_api_service # noqa: E501
read the specified APIService # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_api_service(name, async_req=True)
>>> result = thread.get()
... |
def as_unit(self, unit, location='suffix', *args, **kwargs):
"""Format subset as with units
:param unit: string to use as unit
:param location: prefix or suffix
:param subset: Pandas subset
"""
f = Formatter(
as_unit(unit, location=location),
args... | Format subset as with units
:param unit: string to use as unit
:param location: prefix or suffix
:param subset: Pandas subset |
def project_leave(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /project-xxxx/leave API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Project-Permissions-and-Sharing#API-method%3A-%2Fproject-xxxx%2Fleave
"""
return DXHTTPRequest('/%s/leav... | Invokes the /project-xxxx/leave API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Project-Permissions-and-Sharing#API-method%3A-%2Fproject-xxxx%2Fleave |
def list_files(tag='', sat_id=None, data_path=None, format_str=None):
"""Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '' and 'ascii'.
If '' is specified, the primary dat... | Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '' and 'ascii'.
If '' is specified, the primary data type (ascii) is loaded.
(default='')
sat_id : (string or NoneTy... |
def windows_k_distinct(x, k):
"""Find all largest windows containing exactly k distinct elements
:param x: list or string
:param k: positive integer
:yields: largest intervals [i, j) with len(set(x[i:j])) == k
:complexity: `O(|x|)`
"""
dist, i, j = 0, 0, 0 # dist = |{x[i], ..... | Find all largest windows containing exactly k distinct elements
:param x: list or string
:param k: positive integer
:yields: largest intervals [i, j) with len(set(x[i:j])) == k
:complexity: `O(|x|)` |
def from_string(data_str):
"""Creates a MonsoonData object from a string representation generated
by __str__.
Args:
str: The string representation of a MonsoonData.
Returns:
A MonsoonData object.
"""
lines = data_str.strip().split('\n')
e... | Creates a MonsoonData object from a string representation generated
by __str__.
Args:
str: The string representation of a MonsoonData.
Returns:
A MonsoonData object. |
def new_main_mod(self,ns=None):
"""Return a new 'main' module object for user code execution.
"""
main_mod = self._user_main_module
init_fakemod_dict(main_mod,ns)
return main_mod | Return a new 'main' module object for user code execution. |
def nested_insert(self, item_list):
""" Create a series of nested LIVVDicts given a list """
if len(item_list) == 1:
self[item_list[0]] = LIVVDict()
elif len(item_list) > 1:
if item_list[0] not in self:
self[item_list[0]] = LIVVDict()
self[item... | Create a series of nested LIVVDicts given a list |
def strip_filter(value):
'''
Strips HTML tags from strings according to SANITIZER_ALLOWED_TAGS,
SANITIZER_ALLOWED_ATTRIBUTES and SANITIZER_ALLOWED_STYLES variables in
settings.
Example usage:
{% load sanitizer %}
{{ post.content|strip_html }}
'''
if isinstance(value, basestring):
... | Strips HTML tags from strings according to SANITIZER_ALLOWED_TAGS,
SANITIZER_ALLOWED_ATTRIBUTES and SANITIZER_ALLOWED_STYLES variables in
settings.
Example usage:
{% load sanitizer %}
{{ post.content|strip_html }} |
def getall(self, key, failobj=None):
"""Returns a list of all the matching values for key,
containing a single entry for unambiguous matches and
multiple entries for ambiguous matches."""
if self.mmkeys is None: self._mmInit()
k = self.mmkeys.get(key)
if not k: return fai... | Returns a list of all the matching values for key,
containing a single entry for unambiguous matches and
multiple entries for ambiguous matches. |
def role_search(auth=None, **kwargs):
'''
Search roles
CLI Example:
.. code-block:: bash
salt '*' keystoneng.role_search
salt '*' keystoneng.role_search name=role1
salt '*' keystoneng.role_search domain_id=b62e76fbeeff4e8fb77073f591cf211e
'''
cloud = get_operator_cloud... | Search roles
CLI Example:
.. code-block:: bash
salt '*' keystoneng.role_search
salt '*' keystoneng.role_search name=role1
salt '*' keystoneng.role_search domain_id=b62e76fbeeff4e8fb77073f591cf211e |
def set_exception(self, exception):
"""Signal unsuccessful completion."""
was_handled = self._finish(self.errbacks, exception)
if not was_handled:
traceback.print_exception(
type(exception), exception, exception.__traceback__) | Signal unsuccessful completion. |
def desc(self, table):
'''Returns table description
>>> yql.desc('geo.countries')
>>>
'''
query = "desc {0}".format(table)
response = self.raw_query(query)
return response | Returns table description
>>> yql.desc('geo.countries')
>>> |
def commit(self):
"""! @brief Write all collected data to flash.
This routine ensures that chip erase is only used once if either the auto mode or chip
erase mode are used. As an example, if two regions are to be written to and True was
passed to the constructor for chip_erase (... | ! @brief Write all collected data to flash.
This routine ensures that chip erase is only used once if either the auto mode or chip
erase mode are used. As an example, if two regions are to be written to and True was
passed to the constructor for chip_erase (or if the session option was ... |
def plot_gos(self, fout_img, goids=None, **kws_usr):
"""Plot GO IDs."""
gosubdagplot = self.get_gosubdagplot(goids, **kws_usr) # GoSubDagPlot
gosubdagplot.plt_dag(fout_img) | Plot GO IDs. |
def deserialize_durable_record_to_durable_model(record, durable_model):
"""
Utility function that will take a Dynamo event record and turn it into the proper Durable Dynamo object.
This will properly deserialize the ugly Dynamo datatypes away.
:param record:
:param durable_model:
:return:
"... | Utility function that will take a Dynamo event record and turn it into the proper Durable Dynamo object.
This will properly deserialize the ugly Dynamo datatypes away.
:param record:
:param durable_model:
:return: |
def get_process_flow(self, pid=None):
'''
get_process_flow(self, pid=None)
Get process in flow context. The response returns a sub-tree of the whole flow containing the requested process, its direct children processes, and all ancestors.
You can navigate within the flow backword and for... | get_process_flow(self, pid=None)
Get process in flow context. The response returns a sub-tree of the whole flow containing the requested process, its direct children processes, and all ancestors.
You can navigate within the flow backword and forward by running this call on the children or ancestors of ... |
def _create_technical_words_dictionary(spellchecker_cache_path,
relative_path,
user_words,
shadow):
"""Create Dictionary at spellchecker_cache_path with technical words."""
technical_terms_set = ... | Create Dictionary at spellchecker_cache_path with technical words. |
def auto_inline_code(self, node):
"""Try to automatically generate nodes for inline literals.
Parameters
----------
node : nodes.literal
Original codeblock node
Returns
-------
tocnode: docutils node
The converted toc tree node, None if co... | Try to automatically generate nodes for inline literals.
Parameters
----------
node : nodes.literal
Original codeblock node
Returns
-------
tocnode: docutils node
The converted toc tree node, None if conversion is not possible. |
def keypoint_vflip(kp, rows, cols):
"""Flip a keypoint vertically around the x-axis."""
x, y, angle, scale = kp
c = math.cos(angle)
s = math.sin(angle)
angle = math.atan2(-s, c)
return [x, (rows - 1) - y, angle, scale] | Flip a keypoint vertically around the x-axis. |
def threads_init(gtk=True):
"""Enables multithreading support in Xlib and PyGTK.
See the module docstring for more info.
:Parameters:
gtk : bool
May be set to False to skip the PyGTK module.
"""
# enable X11 multithreading
x11.XInitThreads()
if gtk:
from gtk.gdk im... | Enables multithreading support in Xlib and PyGTK.
See the module docstring for more info.
:Parameters:
gtk : bool
May be set to False to skip the PyGTK module. |
def write_roi(self, outfile=None,
save_model_map=False, **kwargs):
"""Write current state of the analysis to a file. This method
writes an XML model definition, a ROI dictionary, and a FITS
source catalog file. A previously saved analysis state can be
reloaded from th... | Write current state of the analysis to a file. This method
writes an XML model definition, a ROI dictionary, and a FITS
source catalog file. A previously saved analysis state can be
reloaded from the ROI dictionary file with the
`~fermipy.gtanalysis.GTAnalysis.load_roi` method.
... |
def MapByteStream(self, byte_stream, **unused_kwargs): # pylint: disable=redundant-returns-doc
"""Maps the data type on a byte stream.
Args:
byte_stream (bytes): byte stream.
Returns:
object: mapped value.
Raises:
MappingError: if the data type definition cannot be mapped on
... | Maps the data type on a byte stream.
Args:
byte_stream (bytes): byte stream.
Returns:
object: mapped value.
Raises:
MappingError: if the data type definition cannot be mapped on
the byte stream. |
def get_mime_data(self, mime_type):
"""Return mime data previously attached to surface
using the specified mime type.
:param mime_type: The MIME type of the image data.
:type mime_type: ASCII string
:returns:
A CFFI buffer object, or :obj:`None`
if no dat... | Return mime data previously attached to surface
using the specified mime type.
:param mime_type: The MIME type of the image data.
:type mime_type: ASCII string
:returns:
A CFFI buffer object, or :obj:`None`
if no data has been attached with the given mime type.
... |
def create_volume(client, resource_group_name,
name, location,
template_file=None, template_uri=None):
"""Create a volume. """
volume_properties = None
if template_uri:
volume_properties = shell_safe_json_parse(_urlretrieve(template_uri).decode('utf-8'), preserve... | Create a volume. |
def cut_video_stream(stream, start, end, fmt):
""" cut video stream from `start` to `end` time
Parameters
----------
stream : bytes
video file content
start : float
start time
end : float
end time
Returns
-------
result : bytes
content of cut video
... | cut video stream from `start` to `end` time
Parameters
----------
stream : bytes
video file content
start : float
start time
end : float
end time
Returns
-------
result : bytes
content of cut video |
def getRandomBinaryTreeLeafNode(binaryTree):
"""Get random binary tree node.
"""
if binaryTree.internal == True:
if random.random() > 0.5:
return getRandomBinaryTreeLeafNode(binaryTree.left)
else:
return getRandomBinaryTreeLeafNode(binaryTree.right)
else:
... | Get random binary tree node. |
def copy_file(self, path, prefixed_path, source_storage):
"""
Attempt to copy ``path`` with storage
"""
# Skip this file if it was already copied earlier
if prefixed_path in self.copied_files:
return self.log("Skipping '%s' (already copied earlier)" % path)
# ... | Attempt to copy ``path`` with storage |
def update_comment(self, comment_id, body):
"""
Update a specific comment. This can be used to edit the content of an
existing comment.
"""
path = '/msg/update_comment'
req = ET.Element('request')
ET.SubElement(req, 'comment_id').text = str(int(comment_id))
... | Update a specific comment. This can be used to edit the content of an
existing comment. |
def default_panels(institute_id, case_name):
"""Update default panels for a case."""
panel_ids = request.form.getlist('panel_ids')
controllers.update_default_panels(store, current_user, institute_id, case_name, panel_ids)
return redirect(request.referrer) | Update default panels for a case. |
def asList(self):
""" returns a Point value as a list of [x,y,<z>,<m>] """
base = [self._x, self._y]
if not self._z is None:
base.append(self._z)
elif not self._m is None:
base.append(self._m)
return base | returns a Point value as a list of [x,y,<z>,<m>] |
def intersection(self, *others):
r"""Return a new multiset with elements common to the multiset and all others.
>>> ms = Multiset('aab')
>>> sorted(ms.intersection('abc'))
['a', 'b']
You can also use the ``&`` operator for the same effect. However, the operator version
... | r"""Return a new multiset with elements common to the multiset and all others.
>>> ms = Multiset('aab')
>>> sorted(ms.intersection('abc'))
['a', 'b']
You can also use the ``&`` operator for the same effect. However, the operator version
will only accept a set as other operator,... |
def set_basic_params(
self, workers=None, zerg_server=None, fallback_node=None, concurrent_events=None,
cheap_mode=None, stats_server=None, quiet=None, buffer_size=None,
fallback_nokey=None, subscription_key=None, emperor_command_socket=None):
"""
:param int workers: ... | :param int workers: Number of worker processes to spawn.
:param str|unicode zerg_server: Attach the router to a zerg server.
:param str|unicode fallback_node: Fallback to the specified node in case of error.
:param int concurrent_events: Set the maximum number of concurrent events router can ... |
def accept(self, deviceId, device):
"""
Adds the named device to the store.
:param deviceId:
:param device:
:return:
"""
storedDevice = self.devices.get(deviceId)
if storedDevice is None:
logger.info('Initialising device ' + deviceId)
... | Adds the named device to the store.
:param deviceId:
:param device:
:return: |
def find_span_binsearch(degree, knot_vector, num_ctrlpts, knot, **kwargs):
""" Finds the span of the knot over the input knot vector using binary search.
Implementation of Algorithm A2.1 from The NURBS Book by Piegl & Tiller.
The NURBS Book states that the knot span index always starts from zero, i.e. for... | Finds the span of the knot over the input knot vector using binary search.
Implementation of Algorithm A2.1 from The NURBS Book by Piegl & Tiller.
The NURBS Book states that the knot span index always starts from zero, i.e. for a knot vector [0, 0, 1, 1];
if FindSpan returns 1, then the knot is between th... |
def __raise_user_error(self, view):
"""
Raises an error if the given View has been set read only and the user attempted to edit its content.
:param view: View.
:type view: QWidget
"""
raise foundations.exceptions.UserError("{0} | Cannot perform action, '{1}' View has be... | Raises an error if the given View has been set read only and the user attempted to edit its content.
:param view: View.
:type view: QWidget |
def kitchen_get(backend, kitchen_name, recipe):
"""
Get an existing Kitchen
"""
found_kitchen = DKKitchenDisk.find_kitchen_name()
if found_kitchen is not None and len(found_kitchen) > 0:
raise click.ClickException("You cannot get a kitchen into an existing kitchen directory structure.")
... | Get an existing Kitchen |
def guess_wxr_version(self, tree):
"""
We will try to guess the wxr version used
to complete the wordpress xml namespace name.
"""
for v in ('1.2', '1.1', '1.0'):
try:
tree.find('channel/{%s}wxr_version' % (WP_NS % v)).text
return v
... | We will try to guess the wxr version used
to complete the wordpress xml namespace name. |
def catalog_register(consul_url=None, token=None, **kwargs):
'''
Registers a new node, service, or check
:param consul_url: The Consul server URL.
:param dc: By default, the datacenter of the agent is queried;
however, the dc can be provided using the "dc" parameter.
:param node: The... | Registers a new node, service, or check
:param consul_url: The Consul server URL.
:param dc: By default, the datacenter of the agent is queried;
however, the dc can be provided using the "dc" parameter.
:param node: The node to register.
:param address: The address of the node.
:para... |
def get_shape(self, prune=False, hs_dims=None):
"""Tuple of array dimensions' lengths.
It returns a tuple of ints, each representing the length of a cube
dimension, in the order those dimensions appear in the cube.
Pruning is supported. Dimensions that get reduced to a single element
... | Tuple of array dimensions' lengths.
It returns a tuple of ints, each representing the length of a cube
dimension, in the order those dimensions appear in the cube.
Pruning is supported. Dimensions that get reduced to a single element
(e.g. due to pruning) are removed from the returning ... |
def check_key(user,
key,
enc,
comment,
options,
config='.ssh/authorized_keys',
cache_keys=None,
fingerprint_hash_type=None):
'''
Check to see if a key needs updating, returns "update", "add" or "exists"
CLI Ex... | Check to see if a key needs updating, returns "update", "add" or "exists"
CLI Example:
.. code-block:: bash
salt '*' ssh.check_key <user> <key> <enc> <comment> <options> |
def ppo_original_params():
"""Parameters based on the original PPO paper."""
hparams = ppo_atari_base()
hparams.learning_rate_constant = 2.5e-4
hparams.gae_gamma = 0.99
hparams.gae_lambda = 0.95
hparams.clipping_coef = 0.1
hparams.value_loss_coef = 1
hparams.entropy_loss_coef = 0.01
hparams.eval_every... | Parameters based on the original PPO paper. |
def delete(self, *keys):
"""Emulate delete."""
key_counter = 0
for key in map(self._encode, keys):
if key in self.redis:
del self.redis[key]
key_counter += 1
if key in self.timeouts:
del self.timeouts[key]
return key... | Emulate delete. |
def QA_util_random_with_zh_stock_code(stockNumber=10):
'''
随机生成股票代码
:param stockNumber: 生成个数
:return: ['60XXXX', '00XXXX', '300XXX']
'''
codeList = []
pt = 0
for i in range(stockNumber):
if pt == 0:
#print("random 60XXXX")
iCode = random.randint(600000, 6... | 随机生成股票代码
:param stockNumber: 生成个数
:return: ['60XXXX', '00XXXX', '300XXX'] |
def conn_handler(self, session: ClientSession, proxy: str = None) -> ConnectionHandler:
"""
Return connection handler instance for the endpoint
:param session: AIOHTTP client session instance
:param proxy: Proxy url
:return:
"""
return ConnectionHandler("https", ... | Return connection handler instance for the endpoint
:param session: AIOHTTP client session instance
:param proxy: Proxy url
:return: |
def colors_to_dict(colors, img):
"""Convert list of colors to pywal format."""
return {
"wallpaper": img,
"alpha": util.Color.alpha_num,
"special": {
"background": colors[0],
"foreground": colors[15],
"cursor": colors[15]
},
"colors":... | Convert list of colors to pywal format. |
def _set_compact_flash(self, v, load=False):
"""
Setter method for compact_flash, mapped from YANG variable /system_monitor/compact_flash (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_compact_flash is considered as a private
method. Backends looking to ... | Setter method for compact_flash, mapped from YANG variable /system_monitor/compact_flash (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_compact_flash is considered as a private
method. Backends looking to populate this variable should
do so via calling thisO... |
def confirm_commit(jid):
'''
.. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
... | .. versionadded:: 2019.2.0
Confirm a commit scheduled to be reverted via the ``revert_in`` and
``revert_at`` arguments from the
:mod:`net.load_template <salt.modules.napalm_network.load_template>` or
:mod:`net.load_config <salt.modules.napalm_network.load_config>`
execution functions. The commit I... |
async def Track(self, payloads):
'''
payloads : typing.Sequence[~Payload]
Returns -> typing.Sequence[~PayloadResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='PayloadsHookContext',
request='Track',
ver... | payloads : typing.Sequence[~Payload]
Returns -> typing.Sequence[~PayloadResult] |
def _perturbation(self):
"""
Returns Gaussian perturbation
"""
if self.P>1:
scales = []
for term_i in range(self.n_terms):
_scales = SP.randn(self.diag[term_i].shape[0])
if self.offset[term_i]>0:
_scales = SP.co... | Returns Gaussian perturbation |
def cmd_rcbind(self, args):
'''start RC bind'''
if len(args) < 1:
print("Usage: rcbind <dsmmode>")
return
self.master.mav.command_long_send(self.settings.target_system,
self.settings.target_component,
... | start RC bind |
def from_arrays(cls, arrays, sortorder=None, names=None):
"""
Convert arrays to MultiIndex.
Parameters
----------
arrays : list / sequence of array-likes
Each array-like gives one level's value for each data point.
len(arrays) is the number of levels.
... | Convert arrays to MultiIndex.
Parameters
----------
arrays : list / sequence of array-likes
Each array-like gives one level's value for each data point.
len(arrays) is the number of levels.
sortorder : int or None
Level of sortedness (must be lexicogr... |
def p_const_map(self, p):
'''const_map : '{' const_map_seq '}' '''
p[0] = ast.ConstMap(dict(p[2]), p.lineno(1)) | const_map : '{' const_map_seq '}' |
def vor_plot(self, which='vor'):
"""
Voronoi diagram visualizations. There are three types:
1. **vor**: Voronoi diagram of the Solar Horizont.
2. **freq**: Frequency of Sun positions in t in the Voronoi
diagram of the Solar Horizont.
3.... | Voronoi diagram visualizations. There are three types:
1. **vor**: Voronoi diagram of the Solar Horizont.
2. **freq**: Frequency of Sun positions in t in the Voronoi
diagram of the Solar Horizont.
3. **data**: Accumulated time integral of the data projec... |
def _int2coord(x, y, dim):
"""Convert x, y values in dim x dim-grid coordinate system into lng, lat values.
Parameters:
x: int x value of point [0, dim); corresponds to longitude
y: int y value of point [0, dim); corresponds to latitude
dim: int Number of coding point... | Convert x, y values in dim x dim-grid coordinate system into lng, lat values.
Parameters:
x: int x value of point [0, dim); corresponds to longitude
y: int y value of point [0, dim); corresponds to latitude
dim: int Number of coding points each x, y value can take.
... |
def decode_xml(elem, _in_bind = False):
""" Decodes an XML element into an OpenMath object.
:param elem: Element to decode.
:type elem: etree._Element
:param _in_bind: Internal flag used to indicate if we should decode within
an OMBind.
:type _in_bind: bool
:rtype: OMAny
"""
obj ... | Decodes an XML element into an OpenMath object.
:param elem: Element to decode.
:type elem: etree._Element
:param _in_bind: Internal flag used to indicate if we should decode within
an OMBind.
:type _in_bind: bool
:rtype: OMAny |
def normalize(self, stats:Collection[Tensor]=None, do_x:bool=True, do_y:bool=False)->None:
"Add normalize transform using `stats` (defaults to `DataBunch.batch_stats`)"
if getattr(self,'norm',False): raise Exception('Can not call normalize twice')
if stats is None: self.stats = self.batch_stats(... | Add normalize transform using `stats` (defaults to `DataBunch.batch_stats`) |
def read_data(self, **kwargs):
"""
get the data from the service
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list
"""
now = arrow.utcnow().to(settings.TIME_ZONE)
my_toots = []
search = {}
... | get the data from the service
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list |
def import_batch(self, filename):
"""Imports the batch of outgoing transactions into
model IncomingTransaction.
"""
batch = self.batch_cls()
json_file = self.json_file_cls(name=filename, path=self.path)
try:
deserialized_txs = json_file.deserialized_objects
... | Imports the batch of outgoing transactions into
model IncomingTransaction. |
def run_evaluate(self, *args, **kwargs) -> None:
"""
Evaluates the current item
:returns An evaluation result object containing the result, or reasons why
evaluation failed
"""
if self._needs_evaluation:
for _, item in self._nested_items.items():
... | Evaluates the current item
:returns An evaluation result object containing the result, or reasons why
evaluation failed |
def _get_cached_style_urls(self, asset_url_path):
"""
Gets the URLs of the cached styles.
"""
try:
cached_styles = os.listdir(self.cache_path)
except IOError as ex:
if ex.errno != errno.ENOENT and ex.errno != errno.ESRCH:
raise
... | Gets the URLs of the cached styles. |
def _dt_to_epoch(dt):
"""Convert datetime to epoch seconds."""
try:
epoch = dt.timestamp()
except AttributeError: # py2
epoch = (dt - datetime(1970, 1, 1)).total_seconds()
return epoch | Convert datetime to epoch seconds. |
def validate_registry_uri_authority(auth: str) -> None:
"""
Raise an exception if the authority is not a valid ENS domain
or a valid checksummed contract address.
"""
if is_ens_domain(auth) is False and not is_checksum_address(auth):
raise ValidationError(f"{auth} is not a valid registry URI... | Raise an exception if the authority is not a valid ENS domain
or a valid checksummed contract address. |
def _get_data_bytes_or_stream_only(param_name, param_value):
'''Validates the request body passed in is a stream/file-like or bytes
object.'''
if param_value is None:
return b''
if isinstance(param_value, bytes) or hasattr(param_value, 'read'):
return param_value
raise TypeError(_E... | Validates the request body passed in is a stream/file-like or bytes
object. |
def _init_fld2col_widths(self):
"""Return default column widths for writing an Excel Spreadsheet."""
# GO info namedtuple fields: NS dcnt level depth GO D1 name
# GO header namedtuple fields: format_txt hdr_idx
fld2col_widths = GoSubDagWr.fld2col_widths.copy()
for fld, wid in sel... | Return default column widths for writing an Excel Spreadsheet. |
def authenticate(self, request):
"""
Authenticate a user from a token form field
Errors thrown here will be swallowed by django-rest-framework, and it
expects us to return None if authentication fails.
"""
try:
key = request.data['token']
except KeyEr... | Authenticate a user from a token form field
Errors thrown here will be swallowed by django-rest-framework, and it
expects us to return None if authentication fails. |
def _shrink(self):
"""
Shrinks the dynamic table to be at or below maxsize
"""
cursize = self._current_size
while cursize > self._maxsize:
name, value = self.dynamic_entries.pop()
cursize -= table_entry_size(name, value)
self._current_size = cursiz... | Shrinks the dynamic table to be at or below maxsize |
def pretty_print(self, indent=0):
"""Print the document without tags using indentation
"""
s = tab = ' '*indent
s += '%s: ' %self.tag
if isinstance(self.value, basestring):
s += self.value
else:
s += '\n'
for e in self.value:
... | Print the document without tags using indentation |
def _get_char(self, win, char):
def get_check_next_byte():
char = win.getch()
if 128 <= char <= 191:
return char
else:
raise UnicodeError
bytes = []
if char <= 127:
# 1 bytes
bytes.append(char)
#... | no zero byte allowed |
def mean(name, num, minimum=0, maximum=0, ref=None):
'''
Calculates the mean of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.mean:
- name: myregentry
- num: 5
'''
return calc(
name=name,
num=nu... | Calculates the mean of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.mean:
- name: myregentry
- num: 5 |
def _parse_selector(self, scoped=True, allow_periods_in_scope=False):
"""Parse a (possibly scoped) selector.
A selector is a sequence of one or more valid Python-style identifiers
separated by periods (see also `SelectorMap`). A scoped selector is a
selector that may be preceded by scope names (separat... | Parse a (possibly scoped) selector.
A selector is a sequence of one or more valid Python-style identifiers
separated by periods (see also `SelectorMap`). A scoped selector is a
selector that may be preceded by scope names (separated by slashes).
Args:
scoped: Whether scopes are allowed.
al... |
def begin_auth():
""" Request authentication token to sign """
repository = request.headers['repository']
if repository not in config['repositories']: return fail(no_such_repo_msg)
# ==
repository_path = config['repositories'][repository]['path']
conn = auth_db_connect(cpjoin(repository_pat... | Request authentication token to sign |
def create_cluster(dc_ref, cluster_name, cluster_spec):
'''
Creates a cluster in a datacenter.
dc_ref
The parent datacenter reference.
cluster_name
The cluster name.
cluster_spec
The cluster spec (vim.ClusterConfigSpecEx).
Defaults to None.
'''
dc_name = ge... | Creates a cluster in a datacenter.
dc_ref
The parent datacenter reference.
cluster_name
The cluster name.
cluster_spec
The cluster spec (vim.ClusterConfigSpecEx).
Defaults to None. |
def com_google_fonts_check_whitespace_widths(ttFont):
"""Whitespace and non-breaking space have the same width?"""
from fontbakery.utils import get_glyph_name
space_name = get_glyph_name(ttFont, 0x0020)
nbsp_name = get_glyph_name(ttFont, 0x00A0)
space_width = ttFont['hmtx'][space_name][0]
nbsp_width = ttF... | Whitespace and non-breaking space have the same width? |
def arp():
'''
Return the arp table from the minion
.. versionchanged:: 2015.8.0
Added support for SunOS
CLI Example:
.. code-block:: bash
salt '*' network.arp
'''
ret = {}
out = __salt__['cmd.run']('arp -an')
for line in out.splitlines():
comps = line.spl... | Return the arp table from the minion
.. versionchanged:: 2015.8.0
Added support for SunOS
CLI Example:
.. code-block:: bash
salt '*' network.arp |
def get_receive(self, script_list):
"""Return a list of received events contained in script_list."""
events = defaultdict(set)
for script in script_list:
if self.script_start_type(script) == self.HAT_WHEN_I_RECEIVE:
event = script.blocks[0].args[0].lower()
... | Return a list of received events contained in script_list. |
def evaluate_objective(self):
"""
Evaluates the objective
"""
self.Y_new, cost_new = self.objective.evaluate(self.suggested_sample)
self.cost.update_cost_model(self.suggested_sample, cost_new)
self.Y = np.vstack((self.Y,self.Y_new)) | Evaluates the objective |
def stamp(name, backdate=None,
unique=None, keep_subdivisions=None, quick_print=None,
un=None, ks=None, qp=None):
"""
Mark the end of a timing interval.
Notes:
If keeping subdivisions, each subdivision currently awaiting
assignment to a stamp (i.e. ended since the last s... | Mark the end of a timing interval.
Notes:
If keeping subdivisions, each subdivision currently awaiting
assignment to a stamp (i.e. ended since the last stamp in this level)
will be assigned to this one. Otherwise, all awaiting ones will be
discarded after aggregating their self tim... |
def WriteLine(log: Any, consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None:
"""
log: any type.
consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`.
writeToFile: bool.
printToStdout: bool.
... | log: any type.
consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`.
writeToFile: bool.
printToStdout: bool.
logFile: str, log file path. |
def fulltext_scan_ids(self, query_id=None, query_fc=None,
preserve_order=True, indexes=None):
'''Fulltext search for identifiers.
Yields an iterable of triples (score, identifier)
corresponding to the search results of the fulltext search
in ``query``. This wil... | Fulltext search for identifiers.
Yields an iterable of triples (score, identifier)
corresponding to the search results of the fulltext search
in ``query``. This will only search text indexed under the
given feature named ``fname``.
Note that, unless ``preserve_order`` is set to... |
def _escape_jid(jid):
'''
Do proper formatting of the jid
'''
jid = six.text_type(jid)
jid = re.sub(r"'*", "", jid)
return jid | Do proper formatting of the jid |
def fstab(config='/etc/fstab'):
'''
.. versionchanged:: 2016.3.2
List the contents of the fstab
CLI Example:
.. code-block:: bash
salt '*' mount.fstab
'''
ret = {}
if not os.path.isfile(config):
return ret
with salt.utils.files.fopen(config) as ifile:
for ... | .. versionchanged:: 2016.3.2
List the contents of the fstab
CLI Example:
.. code-block:: bash
salt '*' mount.fstab |
def _tr_system(line_info):
"Translate lines escaped with: !"
cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
return '%sget_ipython().system(%r)' % (line_info.pre, cmd) | Translate lines escaped with: ! |
def remove_existing_pidfile(pidfile_path):
""" Remove the named PID file if it exists.
Removing a PID file that doesn't already exist puts us in the
desired state, so we ignore the condition if the file does not
exist.
"""
try:
os.remove(pidfile_path)
except OSError... | Remove the named PID file if it exists.
Removing a PID file that doesn't already exist puts us in the
desired state, so we ignore the condition if the file does not
exist. |
def resizeToMinimum(self):
"""
Resizes the dock toolbar to the minimum sizes.
"""
offset = self.padding()
min_size = self.minimumPixmapSize()
if self.position() in (XDockToolbar.Position.East,
XDockToolbar.Position.West):
... | Resizes the dock toolbar to the minimum sizes. |
def rpc(name, dest=None, **kwargs):
'''
Executes the given rpc. The returned data can be stored in a file
by specifying the destination path with dest as an argument
.. code-block:: yaml
get-interface-information:
junos:
- rpc
- dest: /home/user/rpc.log
... | Executes the given rpc. The returned data can be stored in a file
by specifying the destination path with dest as an argument
.. code-block:: yaml
get-interface-information:
junos:
- rpc
- dest: /home/user/rpc.log
- interface_name: lo0
Parame... |
def _AddUser(self, user):
"""Configure a Linux user account.
Args:
user: string, the name of the Linux user account to create.
Returns:
bool, True if user creation succeeded.
"""
self.logger.info('Creating a new user account for %s.', user)
command = self.useradd_cmd.format(user=u... | Configure a Linux user account.
Args:
user: string, the name of the Linux user account to create.
Returns:
bool, True if user creation succeeded. |
def to_new(self, data, perplexities=None, return_distances=False):
"""Compute the affinities of new samples to the initial samples.
This is necessary for embedding new data points into an existing
embedding.
Please see the :ref:`parameter-guide` for more information.
Parameter... | Compute the affinities of new samples to the initial samples.
This is necessary for embedding new data points into an existing
embedding.
Please see the :ref:`parameter-guide` for more information.
Parameters
----------
data: np.ndarray
The data points to b... |
def remove_labels(self, test):
"""
Remove labels from this cell.
The function or callable ``test`` is called for each label in
the cell. If its return value evaluates to ``True``, the
corresponding label is removed from the cell.
Parameters
----------
t... | Remove labels from this cell.
The function or callable ``test`` is called for each label in
the cell. If its return value evaluates to ``True``, the
corresponding label is removed from the cell.
Parameters
----------
test : callable
Test function to query w... |
def _match_offset_front_id_to_onset_front_id(onset_front_id, onset_fronts, offset_fronts, onsets, offsets):
"""
Find all offset fronts which are composed of at least one offset which corresponds to one of the onsets in the
given onset front.
The offset front which contains the most of such offsets is th... | Find all offset fronts which are composed of at least one offset which corresponds to one of the onsets in the
given onset front.
The offset front which contains the most of such offsets is the match.
If there are no such offset fronts, return -1. |
def configure(cls, impl, **kwargs):
# type: (Any, **Any) -> None
"""Sets the class to use when the base class is instantiated.
Keyword arguments will be saved and added to the arguments passed
to the constructor. This can be used to set global defaults for
some parameters.
... | Sets the class to use when the base class is instantiated.
Keyword arguments will be saved and added to the arguments passed
to the constructor. This can be used to set global defaults for
some parameters. |
def coerce(self, value):
"""Convert text values into boolean values.
True values are (case insensitive): 'yes', 'true', '1'. False values
are (case insensitive): 'no', 'false', '0'.
Args:
value (str or bool): The value to coerce.
Raises:
TypeE... | Convert text values into boolean values.
True values are (case insensitive): 'yes', 'true', '1'. False values
are (case insensitive): 'no', 'false', '0'.
Args:
value (str or bool): The value to coerce.
Raises:
TypeError: If the value is not a bool or s... |
def featureName(self):
"""
ID attribute from GFF3 or None if record doesn't have it.
Called "Name" rather than "Id" within GA4GH, as there is
no guarantee of either uniqueness or existence.
"""
featId = self.attributes.get("ID")
if featId is not None:
... | ID attribute from GFF3 or None if record doesn't have it.
Called "Name" rather than "Id" within GA4GH, as there is
no guarantee of either uniqueness or existence. |
def _set_symlink_ownership(path, user, group, win_owner):
'''
Set the ownership of a symlink and return a boolean indicating
success/failure
'''
if salt.utils.platform.is_windows():
try:
salt.utils.win_dacl.set_owner(path, win_owner)
except CommandExecutionError:
... | Set the ownership of a symlink and return a boolean indicating
success/failure |
def DomainTokensGet(self, domain_id):
"""
T his method returns the list of tokens which are available for this domain.
Only domain managers can list domain tokens.
@param domain_id - ID of the domain for which to retrieve tokens
@... | T his method returns the list of tokens which are available for this domain.
Only domain managers can list domain tokens.
@param domain_id - ID of the domain for which to retrieve tokens
@return (bool) - Boolean indicating whether DomainTokensGet was s... |
def get_log_entries_by_log(self, log_id):
"""Gets the list of log entries associated with a ``Log``.
arg: log_id (osid.id.Id): ``Id`` of a ``Log``
return: (osid.logging.LogEntryList) - list of related logEntry
raise: NotFound - ``log_id`` is not found
raise: NullArgument - ... | Gets the list of log entries associated with a ``Log``.
arg: log_id (osid.id.Id): ``Id`` of a ``Log``
return: (osid.logging.LogEntryList) - list of related logEntry
raise: NotFound - ``log_id`` is not found
raise: NullArgument - ``log_id`` is ``null``
raise: OperationFaile... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.