code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def to_discontinuous(self):
"""Return a discontinuous version of the current collection."""
collection = HourlyDiscontinuousCollection(self.header.duplicate(),
self.values, self.datetimes)
collection._validated_a_period = True
return col... | Return a discontinuous version of the current collection. |
def wc_wrap(text, length):
"""
Wrap text to given length, breaking on whitespace and taking into account
character width.
Meant for use on a single line or paragraph. Will destroy spacing between
words and paragraphs and any indentation.
"""
line_words = []
line_len = 0
words = re.... | Wrap text to given length, breaking on whitespace and taking into account
character width.
Meant for use on a single line or paragraph. Will destroy spacing between
words and paragraphs and any indentation. |
def from_version(cls, version, op=None):
"""Create a range from a version.
Args:
version: Version object. This is used as the upper/lower bound of
the range.
op: Operation as a string. One of 'gt'/'>', 'gte'/'>=', lt'/'<',
'lte'/'<=', 'eq'/'=='. I... | Create a range from a version.
Args:
version: Version object. This is used as the upper/lower bound of
the range.
op: Operation as a string. One of 'gt'/'>', 'gte'/'>=', lt'/'<',
'lte'/'<=', 'eq'/'=='. If None, a bounded range will be created
... |
def patch(self, resource_id):
"""Return an HTTP response object resulting from an HTTP PATCH call.
:returns: ``HTTP 200`` if the resource already exists
:returns: ``HTTP 400`` if the request is malformed
:returns: ``HTTP 404`` if the resource is not found
:param resource_id: The... | Return an HTTP response object resulting from an HTTP PATCH call.
:returns: ``HTTP 200`` if the resource already exists
:returns: ``HTTP 400`` if the request is malformed
:returns: ``HTTP 404`` if the resource is not found
:param resource_id: The value of the resource's primary key |
def guess_process(query_str, process_map):
"""
Function to guess processes based on strings that are not available in
process_map. If the string has typos and is somewhat similar (50%) to any
process available in flowcraft it will print info to the terminal,
suggesting the most similar processes ava... | Function to guess processes based on strings that are not available in
process_map. If the string has typos and is somewhat similar (50%) to any
process available in flowcraft it will print info to the terminal,
suggesting the most similar processes available in flowcraft.
Parameters
----------
... |
def clear(self):
"""
calls clear on any report format instances created during setup
and drops the cache
"""
if self._formats:
for fmt in self._formats:
fmt.clear()
self._formats = None | calls clear on any report format instances created during setup
and drops the cache |
def set_environment_variable(self, key, val):
""" Sets a variable if that variable is not already set """
if self.get_environment_variable(key) in [None, val]:
self.__dict__['environment_variables'][key] = val
else:
raise Contradiction("Could not set environment variable ... | Sets a variable if that variable is not already set |
def mogrify(self, query, *parameters, **kwargs):
"""From http://initd.org/psycopg/docs/cursor.html?highlight=mogrify#cursor.mogrify
Return a query string after arguments binding.
The string returned is exactly the one that would be sent to the database running
the execute() method or sim... | From http://initd.org/psycopg/docs/cursor.html?highlight=mogrify#cursor.mogrify
Return a query string after arguments binding.
The string returned is exactly the one that would be sent to the database running
the execute() method or similar. |
def recurse(cls_or_slf, node, attrpath=None, attrpaths=[], siblings=[], level=0, value_dims=True):
"""
Recursive function that builds up an ASCII tree given an
AttrTree node.
"""
level, lines = cls_or_slf.node_info(node, attrpath, attrpaths, siblings, level, value_dims)
a... | Recursive function that builds up an ASCII tree given an
AttrTree node. |
def copy(self, x1=None, y1=None, x2=None, y2=None, label=None):
"""
Create a shallow copy of the BoundingBox object.
Parameters
----------
x1 : None or number
If not None, then the x1 coordinate of the copied object will be set to this value.
y1 : None or nu... | Create a shallow copy of the BoundingBox object.
Parameters
----------
x1 : None or number
If not None, then the x1 coordinate of the copied object will be set to this value.
y1 : None or number
If not None, then the y1 coordinate of the copied object will be se... |
def with_env_recursive(cmd, **envvars):
"""
Recursively updates the environment of cmd and all its subcommands.
Args:
cmd - A plumbum command-like object
**envvars - The environment variables to update
Returns:
The updated command.
"""
from plumbum.commands.base import ... | Recursively updates the environment of cmd and all its subcommands.
Args:
cmd - A plumbum command-like object
**envvars - The environment variables to update
Returns:
The updated command. |
def _send_direct_message_new(self, messageobject: Dict[str, Dict]) -> Any:
"""
:reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event.html
"""
headers, post_data = _buildmessageobject(messageobject)
newdm_path = "/direct_me... | :reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event.html |
def _sqrt(x):
"""
Return square root of an ndarray.
This sqrt function for ndarrays tries to use the exponentiation operator
if the objects stored do not supply a sqrt method.
"""
x = np.clip(x, a_min=0, a_max=None)
try:
return np.sqrt(x)
except AttributeError:
exponen... | Return square root of an ndarray.
This sqrt function for ndarrays tries to use the exponentiation operator
if the objects stored do not supply a sqrt method. |
def _pretrained_initializer(varname, weight_file, embedding_weight_file=None):
"""
We'll stub out all the initializers in the pretrained LM with
a function that loads the weights from the file
"""
weight_name_map = {}
for i in range(2):
for j in range(8): # if we decide to add more laye... | We'll stub out all the initializers in the pretrained LM with
a function that loads the weights from the file |
def export(self):
"""
This method deactivates the security context for the calling process and returns an
interprocess token which, when passed to :meth:`imprt` in another process, will re-activate
the context in the second process. Only a single instantiation of a given context may be
... | This method deactivates the security context for the calling process and returns an
interprocess token which, when passed to :meth:`imprt` in another process, will re-activate
the context in the second process. Only a single instantiation of a given context may be
active at any one time; attempt... |
def scan_directory(self, dirname, exclude_exts=(), exclude_fnames=()):
"""
Analyze the files contained in directory dirname.
Args:
dirname: directory path
exclude_exts: list of file extensions that should be skipped.
exclude_fnames: list of file names that sh... | Analyze the files contained in directory dirname.
Args:
dirname: directory path
exclude_exts: list of file extensions that should be skipped.
exclude_fnames: list of file names that should be skipped.
Returns:
List of pseudopotential objects. |
def extract(self, item, list_article_candidate):
"""Compares the extracted titles.
:param item: The corresponding NewscrawlerItem
:param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string, the most likely title
"""
... | Compares the extracted titles.
:param item: The corresponding NewscrawlerItem
:param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string, the most likely title |
def get_object(self):
"""Return the object of this TimeMachine"""
return self.content_type.model_class().objects.get(uid = self.uid) | Return the object of this TimeMachine |
def is_empty(self):
"""Return whether the block of user data is empty."""
return (not self.breakpoint and not self.code_analysis
and not self.todo and not self.bookmarks) | Return whether the block of user data is empty. |
def add_metadata_props(onnx_model, metadata_props, target_opset):
'''
Add metadata properties to the model. See recommended key names at:
`Extensibility - Metadata <https://github.com/onnx/onnx/blob/296953db87b79c0137c5d9c1a8f26dfaa2495afc/docs/IR.md#metadata>`_ and
`Optional Metadata <https://github.co... | Add metadata properties to the model. See recommended key names at:
`Extensibility - Metadata <https://github.com/onnx/onnx/blob/296953db87b79c0137c5d9c1a8f26dfaa2495afc/docs/IR.md#metadata>`_ and
`Optional Metadata <https://github.com/onnx/onnx/blob/master/docs/IR.md#optional-metadata>`_
:param onnx_mode... |
def convert_words_to_float(high_word, low_word):
"""Convert two words to a floating point"""
number, retval = convert_words_to_uint(high_word, low_word)
if not retval:
return 0.0, False
try:
packed_float = struct.pack('>l', number)
return struct.unpack('>f', packed_float)[0], Tr... | Convert two words to a floating point |
def _hz_to_semitones(self, hz):
"""
Convert hertz into a number of semitones above or below some reference
value, in this case, A440
"""
return np.log(hz / self._a440) / np.log(self._a) | Convert hertz into a number of semitones above or below some reference
value, in this case, A440 |
def simulate(self, l, noisefunc=None, random_state=None):
"""Simulate vector autoregressive (VAR) model.
This function generates data from the VAR model.
Parameters
----------
l : int or [int, int]
Number of samples to generate. Can be a tuple or list, where l[0]
... | Simulate vector autoregressive (VAR) model.
This function generates data from the VAR model.
Parameters
----------
l : int or [int, int]
Number of samples to generate. Can be a tuple or list, where l[0]
is the number of samples and l[1] is the number of trials.
... |
def update_migration_issue_accounts(self, id, account_id, workflow_state, content_migration_id):
"""
Update a migration issue.
Update the workflow_state of a migration issue
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
... | Update a migration issue.
Update the workflow_state of a migration issue |
def _run_default_moderator(comment, content_object, request):
"""
Run the default moderator
"""
# The default moderator will likely not check things like "auto close".
# It can still provide akismet and bad word checking.
if not default_moderator.allow(comment, content_object, request):
... | Run the default moderator |
def configure(self, repositories):
"""Prepare the system to be ready for an undercloud installation.
"""
self.enable_repositories(repositories)
self.create_stack_user()
self.install_base_packages()
self.clean_system()
self.yum_update(allow_reboot=True)
sel... | Prepare the system to be ready for an undercloud installation. |
def slow_augment(n, ii, jj, idx, count, x, y, u, v, c):
'''Perform the augmentation step to assign unassigned i and j
n - the # of i and j, also the marker of unassigned x and y
ii - the unassigned i
jj - the ragged arrays of j for each i
idx - the index of the first j for each i
count - th... | Perform the augmentation step to assign unassigned i and j
n - the # of i and j, also the marker of unassigned x and y
ii - the unassigned i
jj - the ragged arrays of j for each i
idx - the index of the first j for each i
count - the number of j for each i
x - the assignments of j for each ... |
def db_connect(connection_string=None, **kwargs):
"""Function to supply a database connection object."""
if connection_string is None:
connection_string = get_current_registry().settings[CONNECTION_STRING]
db_conn = psycopg2.connect(connection_string, **kwargs)
try:
with db_conn:
... | Function to supply a database connection object. |
def set_cipher_list(self, cipher_list):
"""
Set the list of ciphers to be used in this context.
See the OpenSSL manual for more information (e.g.
:manpage:`ciphers(1)`).
:param bytes cipher_list: An OpenSSL cipher string.
:return: None
"""
cipher_list = ... | Set the list of ciphers to be used in this context.
See the OpenSSL manual for more information (e.g.
:manpage:`ciphers(1)`).
:param bytes cipher_list: An OpenSSL cipher string.
:return: None |
def from_httplib(ResponseCls, r, **response_kw):
"""
Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``.
... | Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``. |
def process_event(self, event):
"""Apply an event to the snapshot instance
"""
if not isinstance(event, KindleEvent):
pass
elif isinstance(event, AddEvent):
self._data[event.asin] = BookSnapshot(event.asin)
elif isinstance(event, SetReadingEvent):
... | Apply an event to the snapshot instance |
def vectors(self, pos, vel, roll=0.0, pitch=0.0, yaw=0.0):
"""Get unit vectors pointing to the different pixels.
*pos* and *vel* are column vectors, or matrices of column
vectors. Returns vectors as stacked rows.
"""
# TODO: yaw steering mode !
# Fake nadir: This is the... | Get unit vectors pointing to the different pixels.
*pos* and *vel* are column vectors, or matrices of column
vectors. Returns vectors as stacked rows. |
def uncamel(name):
"""converts camelcase to underscore
>>> uncamel('fooBar')
'foo_bar'
>>> uncamel('FooBar')
'foo_bar'
>>> uncamel('_fooBar')
'_foo_bar'
>>> uncamel('_FooBar')
'__foo_bar'
"""
response, name = name[0].lower(), name[1:]
for n in name:
if n.isupper()... | converts camelcase to underscore
>>> uncamel('fooBar')
'foo_bar'
>>> uncamel('FooBar')
'foo_bar'
>>> uncamel('_fooBar')
'_foo_bar'
>>> uncamel('_FooBar')
'__foo_bar' |
def create_lzma(archive, compression, cmd, verbosity, interactive, filenames):
"""Create an LZMA archive with the lzma Python module."""
return _create(archive, compression, cmd, 'alone', verbosity, filenames) | Create an LZMA archive with the lzma Python module. |
def bin(values, bins, labels=None):
"""Bins data into declared bins
Bins data into declared bins. By default each bin is labelled
with bin center values but an explicit list of bin labels may be
defined.
Args:
values: Array of values to be binned
bins: List or array containing the ... | Bins data into declared bins
Bins data into declared bins. By default each bin is labelled
with bin center values but an explicit list of bin labels may be
defined.
Args:
values: Array of values to be binned
bins: List or array containing the bin boundaries
labels: List of labe... |
def _get_mapping():
"""
Finds and loads gulp's rev-manifest.json file.
In default, this is looking for rev-manifest.json file places in your
STATIC_ROOT. Can be overriden to a specific location by setting
DJANGO_GULP_REV_PATH.
"""
global _STATIC_MAPPING
if _STATIC_MAPPING is None:
... | Finds and loads gulp's rev-manifest.json file.
In default, this is looking for rev-manifest.json file places in your
STATIC_ROOT. Can be overriden to a specific location by setting
DJANGO_GULP_REV_PATH. |
def rollback_one_iter(self):
"""Rollback one iteration.
Returns
-------
self : Booster
Booster with rolled back one iteration.
"""
_safe_call(_LIB.LGBM_BoosterRollbackOneIter(
self.handle))
self.__is_predicted_cur_iter = [False for _ in ra... | Rollback one iteration.
Returns
-------
self : Booster
Booster with rolled back one iteration. |
def walk(self, topurl=''):
"""
Similar to os.walk method. Insted of filesystem it walks through
changeset starting at given ``topurl``. Returns generator of tuples
(topnode, dirnodes, filenodes).
"""
topnode = self.get_node(topurl)
yield (topnode, topnode.dirs, t... | Similar to os.walk method. Insted of filesystem it walks through
changeset starting at given ``topurl``. Returns generator of tuples
(topnode, dirnodes, filenodes). |
def removeRecordState( self, state ):
"""
Removes the state from this item.
:param state | <XOrbRecordItem.State>
"""
curr_state = self.recordState()
if curr_state & state:
self.setRecordState(curr_state ^ state) | Removes the state from this item.
:param state | <XOrbRecordItem.State> |
def GetMessages(self, formatter_mediator, event):
"""Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
eve... | Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
event (EventObject): event.
Returns:
tuple(str, s... |
def lower_has_substring_binary_compositions(ir_blocks):
"""Lower Filter blocks that use the "has_substring" operation into MATCH-representable form."""
def visitor_fn(expression):
"""Rewrite BinaryComposition expressions with "has_substring" into representable form."""
# The implementation of "h... | Lower Filter blocks that use the "has_substring" operation into MATCH-representable form. |
def from_api_repr(cls, resource):
"""Factory: create a policy from a JSON resource.
Overrides the base class version to store :attr:`etag` as bytes.
Args:
resource (dict): JSON policy resource returned by the
``getIamPolicy`` REST API.
Returns:
:cla... | Factory: create a policy from a JSON resource.
Overrides the base class version to store :attr:`etag` as bytes.
Args:
resource (dict): JSON policy resource returned by the
``getIamPolicy`` REST API.
Returns:
:class:`Policy`: the parsed policy |
def internal_auth_client(requires_instance=False, force_new_client=False):
"""
Looks up the values for this CLI's Instance Client in config
If none exists and requires_instance is True or force_new_client is True,
registers a new Instance Client with GLobus Auth
If none exists and requires_instanc... | Looks up the values for this CLI's Instance Client in config
If none exists and requires_instance is True or force_new_client is True,
registers a new Instance Client with GLobus Auth
If none exists and requires_instance is false, defaults to a Native Client
for backwards compatibility
Returns ei... |
def add(self, name, attributes):
"""
Add the relation to the Schema.
:param name: The name of a relation.
:param attributes: A list of attributes for the relation.
:raise RelationReferenceError: Raised if the name already exists.
"""
if name in self._data:
... | Add the relation to the Schema.
:param name: The name of a relation.
:param attributes: A list of attributes for the relation.
:raise RelationReferenceError: Raised if the name already exists. |
def spearman_correlation(X, rowvar=False):
"""
Computes the spearman correlation estimate.
This is effectively a bias corrected pearson correlation
between rank transformed columns of X.
Parameters
----------
X: array-like, shape = [n_samples, n_features]
Data matrix using which we ... | Computes the spearman correlation estimate.
This is effectively a bias corrected pearson correlation
between rank transformed columns of X.
Parameters
----------
X: array-like, shape = [n_samples, n_features]
Data matrix using which we compute the empirical
correlation
Returns
... |
def user_most(self):
'''
User most used.
'''
kwd = {
'pager': '',
'title': '',
}
self.render('user/info_list/user_most.html',
kwd=kwd,
user_name=self.get_current_user(),
userinfo=self.user... | User most used. |
def _on_connect(self, sequence, topic, message):
"""Process a request to connect to an IOTile device
A connection message triggers an attempt to connect to a device,
any error checking is done by the DeviceManager that is actually
managing the devices.
A disconnection message i... | Process a request to connect to an IOTile device
A connection message triggers an attempt to connect to a device,
any error checking is done by the DeviceManager that is actually
managing the devices.
A disconnection message is checked to make sure its key matches
what we excep... |
def remove_listener(self, evt_name, fn, remove_all=False):
"""删除观察者函数。
:params evt_name: 事件名称
:params fn: 要注册的触发函数函数
:params remove_all: 是否删除fn在evt_name中的所有注册\n
如果为 `True`,则删除所有\n
如果为 `False`,则按注册先后顺序删除第一个\n
.. note::
... | 删除观察者函数。
:params evt_name: 事件名称
:params fn: 要注册的触发函数函数
:params remove_all: 是否删除fn在evt_name中的所有注册\n
如果为 `True`,则删除所有\n
如果为 `False`,则按注册先后顺序删除第一个\n
.. note::
允许一个函数多次注册,多次注册意味着一次时间多次调用。 |
def ElementCreator(cls, json, **kwargs):
"""
Helper method for creating elements. If the created element type is
a SubElement class type, provide href value as kwargs since that class
type does not have a direct entry point. This is a lazy load that will
provide only the meta for the element. Additi... | Helper method for creating elements. If the created element type is
a SubElement class type, provide href value as kwargs since that class
type does not have a direct entry point. This is a lazy load that will
provide only the meta for the element. Additional attribute access
will load the full data.
... |
def acor(self, k = 5):
"""
Autocorrelation time of the chain
return the autocorrelation time for each parameters
Inputs :
k :
parameter in self-consistent window
Outputs :
t :
autocorrelation time of the chain
"""
try:
impo... | Autocorrelation time of the chain
return the autocorrelation time for each parameters
Inputs :
k :
parameter in self-consistent window
Outputs :
t :
autocorrelation time of the chain |
def process_xml(self, xml):
'''
Parse tool configuration data out of the Common Cartridge LTI link XML.
'''
root = objectify.fromstring(xml, parser = etree.XMLParser())
# Parse all children of the root node
for child in root.getchildren():
if 'title' in child.... | Parse tool configuration data out of the Common Cartridge LTI link XML. |
def plot_annual_returns(returns, ax=None, **kwargs):
"""
Plots a bar graph of returns by year.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
ax : matplotlib.Axes, optional
... | Plots a bar graph of returns by year.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
ax : matplotlib.Axes, optional
Axes upon which to plot.
**kwargs, optional
Passed to... |
def get_urls(self):
"""Manages not only TreeAdmin URLs but also TreeItemAdmin URLs."""
urls = super(TreeAdmin, self).get_urls()
prefix_change = 'change/' if DJANGO_POST_19 else ''
sitetree_urls = [
url(r'^change/$', redirects_handler, name=get_tree_item_url_name('changelist... | Manages not only TreeAdmin URLs but also TreeItemAdmin URLs. |
def lhlo(self):
"""
Send LMTP LHLO greeting, and process the server response.
A regular LMTP greeting is sent, and if accepted by the server, the
capabilities it returns are parsed.
DLMTP authentication starts here by announcing the dlmtp_ident in
the LHLO as our hostna... | Send LMTP LHLO greeting, and process the server response.
A regular LMTP greeting is sent, and if accepted by the server, the
capabilities it returns are parsed.
DLMTP authentication starts here by announcing the dlmtp_ident in
the LHLO as our hostname. When the ident is accepted and D... |
def func_attr(f, attr):
"""
Helper function to get the attribute of a function
like, name, code, defaults across Python 2.x and 3.x
"""
if hasattr(f, 'func_%s' % attr):
return getattr(f, 'func_%s' % attr)
elif hasattr(f, '__%s__' % attr):
return getattr(f, '__%s__' % attr)
el... | Helper function to get the attribute of a function
like, name, code, defaults across Python 2.x and 3.x |
def beacon(config):
'''
Read the last btmp file and return information on the failed logins
'''
ret = []
users = {}
groups = {}
defaults = None
for config_item in config:
if 'users' in config_item:
users = config_item['users']
if 'groups' in config_item:
... | Read the last btmp file and return information on the failed logins |
def hasField(cls, fieldName) :
"""returns True/False wether the collection has field K in it's schema. Use the dot notation for the nested fields: address.street"""
path = fieldName.split(".")
v = cls._fields
for k in path :
try :
v = v[k]
except K... | returns True/False wether the collection has field K in it's schema. Use the dot notation for the nested fields: address.street |
def name_match(self, elt):
'''Simple boolean test to see if we match the element name.
Parameters:
elt -- the DOM element being parsed
'''
return self.pname == elt.localName and \
self.nspname in [None, '', elt.namespaceURI] | Simple boolean test to see if we match the element name.
Parameters:
elt -- the DOM element being parsed |
def _convert(self, payload):
"""
Converts payload to a string. Complex objects are dumped to json
"""
if not isinstance(payload, six.string_types):
payload = json.dumps(payload, cls=DefaultJSONEncoder, sort_keys=True)
return str(payload) | Converts payload to a string. Complex objects are dumped to json |
def validate(self, formats_dir="../formats/"):
"""checks if the document is valid"""
#TODO: download XSD from web
if self.inline:
xmlschema = ElementTree.XMLSchema(ElementTree.parse(StringIO("\n".join(open(formats_dir+"dcoi-dsc.xsd").readlines()))))
xmlschema.assertValid(... | checks if the document is valid |
def aes_decrypt(value, secret, block_size=AES.block_size):
""" AES decrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES decrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
ae... | AES decrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES decrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
aes_encrypt("Hello, world",
"aLWEFlwgwlreWELF... |
def fw_rule_create(self, data, fw_name=None, cache=False):
"""Top level rule creation routine. """
LOG.debug("FW Rule create %s", data)
self._fw_rule_create(fw_name, data, cache) | Top level rule creation routine. |
def event_at(self, when, data_tuple):
"""
Schedule an event to be emitted at a certain time.
:param when: an absolute timestamp
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling.
"""
return self._base.event_at(when, self.... | Schedule an event to be emitted at a certain time.
:param when: an absolute timestamp
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling. |
def _post_resource(self, url, body):
"""
Canvas POST method.
"""
params = {}
self._set_as_user(params)
headers = {'Content-Type': 'application/json',
'Accept': 'application/json',
'Connection': 'keep-alive'}
url = url + self._... | Canvas POST method. |
def get_client_properties_per_page(self, per_page=1000, page=1, params=None):
"""
Get client properties per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
... | Get client properties per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list |
def build_bbp(self, x, y, wave_const=550):
"""
Builds the particle backscattering function :math:`X(\\frac{550}{\\lambda})^Y`
:param x: function coefficient
:param y: order of the power function
:param wave_const: wave constant default 550 (nm)
:returns null:
""... | Builds the particle backscattering function :math:`X(\\frac{550}{\\lambda})^Y`
:param x: function coefficient
:param y: order of the power function
:param wave_const: wave constant default 550 (nm)
:returns null: |
def add_property(self,label,term_span,pid=None):
"""
Adds a property to the property layer
@type label: string
@param label: the type of property
@type term_span: list
@param term_span: list of term ids
@type pid: string
@param pid: the identifier for the ... | Adds a property to the property layer
@type label: string
@param label: the type of property
@type term_span: list
@param term_span: list of term ids
@type pid: string
@param pid: the identifier for the property (use None to automatically generate one) |
def delete(self, fnames=None):
"""Delete files"""
if fnames is None:
fnames = self.get_selected_filenames()
multiple = len(fnames) > 1
yes_to_all = None
for fname in fnames:
spyproject_path = osp.join(fname,'.spyproject')
if osp.isdir(f... | Delete files |
def get_request_uri_parameters(self, as_dict=False):
""" Return the URI parameters from a request passed to the 'validate' method
The query parameters returned by this method **MUST** be included in the
``action=""`` URI of the authorization form presented to the user. This
carries the original authori... | Return the URI parameters from a request passed to the 'validate' method
The query parameters returned by this method **MUST** be included in the
``action=""`` URI of the authorization form presented to the user. This
carries the original authorization request parameters across the request to
show the ... |
def top_k_with_unique(inputs, k):
"""Finds the values and indices of the k largests entries.
Instead of doing sort like tf.nn.top_k, this function finds the max value
k times. The running time is proportional to k, which is be faster when k
is small. The current implementation supports only inputs of rank 2.
... | Finds the values and indices of the k largests entries.
Instead of doing sort like tf.nn.top_k, this function finds the max value
k times. The running time is proportional to k, which is be faster when k
is small. The current implementation supports only inputs of rank 2.
In addition, iota is used to replace t... |
def get(self):
"""
Constructs a StepContextContext
:returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext
:rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext
"""
return StepContextContext(
self._ver... | Constructs a StepContextContext
:returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext
:rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext |
def read_string(source, offset, length):
"""Reads a string from a byte string.
:param bytes source: Source byte string
:param int offset: Point in byte string to start reading
:param int length: Length of string to read
:returns: Read string and offset at point after read data
:rtype: tuple of ... | Reads a string from a byte string.
:param bytes source: Source byte string
:param int offset: Point in byte string to start reading
:param int length: Length of string to read
:returns: Read string and offset at point after read data
:rtype: tuple of str and int
:raises SerializationError: if u... |
def _write_private_key_file(self, tag, filename, data, password=None):
"""
Write an SSH2-format private key file in a form that can be read by
ssh or openssh. If no password is given, the key is written in
a trivially-encoded format (base64) which is completely insecure. If
a p... | Write an SSH2-format private key file in a form that can be read by
ssh or openssh. If no password is given, the key is written in
a trivially-encoded format (base64) which is completely insecure. If
a password is given, DES-EDE3-CBC is used.
@param tag: C{"RSA"} or C{"DSA"}, the tag ... |
def get_genus_type(self):
"""Gets the genus type of this object.
return: (osid.type.Type) - the genus type of this object
*compliance: mandatory -- This method must be implemented.*
"""
try:
# Try to stand up full Type objects if they can be found
# (Als... | Gets the genus type of this object.
return: (osid.type.Type) - the genus type of this object
*compliance: mandatory -- This method must be implemented.* |
def open_connection(self):
"""
Open connection over TCP socket.
:return: Nothing
"""
self.logger.debug("Open COM %s", self.comport)
self.port = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
(ip_addr, port) = self.comport.split(':')
self.port.connect(ip... | Open connection over TCP socket.
:return: Nothing |
def CreateColumns( self ):
"""Create/recreate our column definitions from current self.columns"""
self.SetItemCount(0)
# clear any current columns...
for i in range( self.GetColumnCount())[::-1]:
self.DeleteColumn( i )
# now create
for i, column in enumerate(s... | Create/recreate our column definitions from current self.columns |
def reset(self):
"""
Reset the state of the instance to when it was constructed
"""
self.operations = []
self._last_overflow = 'WRAP'
self.overflow(self._default_overflow or self._last_overflow) | Reset the state of the instance to when it was constructed |
def get_doc(additional_doc=False,
field_prefix='$',
field_suffix=':',
indent=4):
"""Return a formated string containing documentation about the audio
fields.
"""
if additional_doc:
f = fields.copy()
f.update(additional_doc)
else:
f = fields... | Return a formated string containing documentation about the audio
fields. |
def get_plugin_list():
"""Finds all yaz plugins and returns them in a __qualname__: plugin_class dictionary"""
global _yaz_plugin_classes
def get_recursively(cls, plugin_list):
for plugin in cls.__subclasses__():
if not (plugin.yaz_is_final() or plugin.__qualname__ in _yaz_plugin_classe... | Finds all yaz plugins and returns them in a __qualname__: plugin_class dictionary |
def store_object(file_name, save_key, file_location, object_to_store=None):
"""
Function to store objects in a shelve
Args:
file_name: Shelve storage file name
save_key: The name of the key to store the item to
file_location: The location of the file, derive from the os module
... | Function to store objects in a shelve
Args:
file_name: Shelve storage file name
save_key: The name of the key to store the item to
file_location: The location of the file, derive from the os module
object_to_store: The object you want to store
Returns: |
def getState(self):
"""See comments in base class."""
return dict(_position = self.getPosition(),
position = self.getPosition(),
velocity = None,
bestPosition = self.choices[self._bestPositionIdx],
bestResult = self._bestResult) | See comments in base class. |
def _allocate_address(self, instance, network_ids):
"""
Allocates a floating/public ip address to the given instance,
dispatching to either the Compute or Network API depending
on installed packages.
:param instance: instance to assign address to
:param list network_id:... | Allocates a floating/public ip address to the given instance,
dispatching to either the Compute or Network API depending
on installed packages.
:param instance: instance to assign address to
:param list network_id: List of IDs (as strings) of networks
where to request allocat... |
def debug_btn_clicked(self, widget, data=None):
"""
Event in case that debug button is pressed.
"""
self.store.clear()
self.thread = threading.Thread(target=self.logs_update)
self.thread.start() | Event in case that debug button is pressed. |
def getReverseRankMap(self):
"""
Returns a dictionary that associates each position in the ranking with a list of integer
representations of the candidates ranked at that position.
"""
# We sort the candidates based on the number of incoming edges they have in the graph... | Returns a dictionary that associates each position in the ranking with a list of integer
representations of the candidates ranked at that position. |
def solve(self):
'''
Solves a one period consumption saving problem with risky income.
Parameters
----------
None
Returns
-------
solution : ConsumerSolution
The solution to the one period problem.
'''
aNrm = self.prepar... | Solves a one period consumption saving problem with risky income.
Parameters
----------
None
Returns
-------
solution : ConsumerSolution
The solution to the one period problem. |
def sub_compile(self, schema, path=None, matcher=False):
""" Compile a sub-schema
:param schema: Validation schema
:type schema: *
:param path: Path to this schema, if any
:type path: list|None
:param matcher: Compile a matcher?
:type matcher: bool
:rtype... | Compile a sub-schema
:param schema: Validation schema
:type schema: *
:param path: Path to this schema, if any
:type path: list|None
:param matcher: Compile a matcher?
:type matcher: bool
:rtype: CompiledSchema |
def fir(self, coefficients):
'''Use SoX’s FFT convolution engine with given FIR filter coefficients.
Parameters
----------
coefficients : list
fir filter coefficients
'''
if not isinstance(coefficients, list):
raise ValueError("coefficients must ... | Use SoX’s FFT convolution engine with given FIR filter coefficients.
Parameters
----------
coefficients : list
fir filter coefficients |
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None):
'''
Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1
'''
return [g['CacheSubnetGroupName'] for g in
... | Return a list of all cache subnet group names
Example:
.. code-block:: bash
salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1 |
def create_node(self, channel_names, config_file, injection_file=None,
seed=None, fake_strain_seed=None, tags=None):
""" Set up a CondorDagmanNode class to run ``pycbc_inference``.
Parameters
----------
channel_names : dict
A ``dict`` of ``str`` to use fo... | Set up a CondorDagmanNode class to run ``pycbc_inference``.
Parameters
----------
channel_names : dict
A ``dict`` of ``str`` to use for ``--channel-name`` option.
config_file : pycbc.workflow.core.File
A ``pycbc.workflow.core.File`` for inference configuration fi... |
def not26(func):
"""Function decorator for methods not implemented in Python 2.6."""
@wraps(func)
def errfunc(*args, **kwargs):
raise NotImplementedError
if hexversion < 0x02070000:
return errfunc
else:
return func | Function decorator for methods not implemented in Python 2.6. |
def get_xdg_home(self):
# type: () -> str
"""
Returns the value specified in the XDG_CONFIG_HOME environment variable
or the appropriate default.
"""
config_home = getenv('XDG_CONFIG_HOME', '')
if config_home:
self._log.debug('XDG_CONFIG_HOME is set to... | Returns the value specified in the XDG_CONFIG_HOME environment variable
or the appropriate default. |
def api(name, url, token, **kwargs):
"""Shortcut for caling methods on `Client(token, version)`."""
return Client(token).api(name, url, **kwargs) | Shortcut for caling methods on `Client(token, version)`. |
def plotit(self, x, y, fields, colors=[]):
'''plot a set of graphs using date for x axis'''
pylab.ion()
fig = pylab.figure(num=1, figsize=(12,6))
ax1 = fig.gca()
ax2 = None
xrange = 0.0
for i in range(0, len(fields)):
if len(x[i]) == 0: continue
... | plot a set of graphs using date for x axis |
def keybd_event(bVk: int, bScan: int, dwFlags: int, dwExtraInfo: int) -> None:
"""keybd_event from Win32."""
ctypes.windll.user32.keybd_event(bVk, bScan, dwFlags, dwExtraInfo) | keybd_event from Win32. |
def fill_pool(self):
"""
Add connections as necessary to meet the target pool size. If there
are no nodes to connect to (because we maxed out connections-per-node
on all active connections and any unconnected nodes have pending
reconnect timers), call the on_insufficient_nodes ca... | Add connections as necessary to meet the target pool size. If there
are no nodes to connect to (because we maxed out connections-per-node
on all active connections and any unconnected nodes have pending
reconnect timers), call the on_insufficient_nodes callback. |
def tryReduceXor(sig, val):
"""
Return sig and val reduced by ^ operator or None
if it is not possible to statically reduce expression
"""
m = sig._dtype.all_mask()
if not val.vldMask:
return val
if val._isFullVld():
v = val.val
if v == m:
return ~sig
... | Return sig and val reduced by ^ operator or None
if it is not possible to statically reduce expression |
def save_freesurfer_morph(filename, obj, face_count=0):
'''
save_freesurfer_morph(filename, obj) saves the given object using nibabel.freesurfer.io's
write_morph_data function, and returns the given filename.
'''
fsio.write_morph_data(filename, obj, fnum=face_count)
return filename | save_freesurfer_morph(filename, obj) saves the given object using nibabel.freesurfer.io's
write_morph_data function, and returns the given filename. |
def dump_wcxf(self, C_out, scale_out, fmt='yaml', stream=None, **kwargs):
"""Return a string representation of the Wilson coefficients `C_out`
in WCxf format. If `stream` is specified, export it to a file.
`fmt` defaults to `yaml`, but can also be `json`.
Note that the Wilson coefficien... | Return a string representation of the Wilson coefficients `C_out`
in WCxf format. If `stream` is specified, export it to a file.
`fmt` defaults to `yaml`, but can also be `json`.
Note that the Wilson coefficients are rotated into the Warsaw basis
as defined in WCxf, i.e. to the basis wh... |
def walk_comic_archive(filename_full, image_format, optimize_after):
"""
Optimize a comic archive.
This is done mostly inline to use the master processes process pool
for workers. And to avoid calling back up into walk from a dedicated
module or format processor. It does mean that we block on uncom... | Optimize a comic archive.
This is done mostly inline to use the master processes process pool
for workers. And to avoid calling back up into walk from a dedicated
module or format processor. It does mean that we block on uncompress
and on waiting for the contents subprocesses to compress. |
def most_recent_among(versions):
"""
Compare a list of NSS versions and return the latest one.
Uses first_older_than_second() for comparison.
:param versions: an array of NSS version strings
:return: verbatim copy of the most recent version string
"""
latest = ver... | Compare a list of NSS versions and return the latest one.
Uses first_older_than_second() for comparison.
:param versions: an array of NSS version strings
:return: verbatim copy of the most recent version string |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.