code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def authenticate(self, username, password):
"""Authenticate against the ObjectRocket API.
:param str username: The username to perform basic authentication against the API with.
:param str password: The password to perform basic authentication against the API with.
:returns: A token use... | Authenticate against the ObjectRocket API.
:param str username: The username to perform basic authentication against the API with.
:param str password: The password to perform basic authentication against the API with.
:returns: A token used for authentication against token protected resources.... |
def _request_toc_element(self, index):
"""Request information about a specific item in the TOC"""
logger.debug('Requesting index %d on port %d', index, self.port)
pk = CRTPPacket()
if self._useV2:
pk.set_header(self.port, TOC_CHANNEL)
pk.data = (CMD_TOC_ITEM_V2, i... | Request information about a specific item in the TOC |
def validate_template(template_body=None, template_url=None, region=None, key=None, keyid=None, profile=None):
'''
Validate cloudformation template
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.validate_template mystack-template
'''
conn = _g... | Validate cloudformation template
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.validate_template mystack-template |
def setup(self, path=None):
"""
Look for SExtractor program ('sextractor', or 'sex').
If a full path is provided, only this path is checked.
Raise a SExtractorException if it failed.
Return program and version if it succeed.
"""
# -- Finding sextractor program an... | Look for SExtractor program ('sextractor', or 'sex').
If a full path is provided, only this path is checked.
Raise a SExtractorException if it failed.
Return program and version if it succeed. |
def parse_add_loopback():
"""
Validate params when adding a loopback adapter
"""
class Add(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
try:
ipaddress.IPv4Interface("{}/{}".format(values[1], values[2]))
except ipaddress... | Validate params when adding a loopback adapter |
def Stop(self):
"""Stops the emulator instance."""
if not self.__running:
return
logging.info('shutting down the emulator running at %s', self._host)
headers = {'Content-length': '0'}
response, _ = self._http.request('%s/shutdown' % self._host,
method='POST... | Stops the emulator instance. |
def IsWalletTransaction(self, tx):
"""
Verifies if a transaction belongs to the wallet.
Args:
tx (TransactionOutput):an instance of type neo.Core.TX.Transaction.TransactionOutput to verify.
Returns:
bool: True, if transaction belongs to wallet. False, if not.
... | Verifies if a transaction belongs to the wallet.
Args:
tx (TransactionOutput):an instance of type neo.Core.TX.Transaction.TransactionOutput to verify.
Returns:
bool: True, if transaction belongs to wallet. False, if not. |
def minimum(left, right):
"""Returns element-wise minimum of the input elements.
Both inputs can be Symbol or scalar number. Broadcasting is not supported.
Parameters
---------
left : Symbol or scalar
First symbol to be compared.
right : Symbol or scalar
Second symbol to be com... | Returns element-wise minimum of the input elements.
Both inputs can be Symbol or scalar number. Broadcasting is not supported.
Parameters
---------
left : Symbol or scalar
First symbol to be compared.
right : Symbol or scalar
Second symbol to be compared.
Returns
-------
... |
def xpnsl(h1, h2, use_threads=True):
"""Cross-population version of the NSL statistic.
Parameters
----------
h1 : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array for the first population.
h2 : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array for th... | Cross-population version of the NSL statistic.
Parameters
----------
h1 : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array for the first population.
h2 : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array for the second population.
use_threads : bool,... |
def parse_content(self, content):
"""
Sample Input::
TimeoutStartUSec=1min 30s
LimitNOFILE=65536
LimitMEMLOCK=
LimitLOCKS=18446744073709551615
Sample Output::
{"LimitNOFILE" : "65536",
"TimeoutStartUSec" : "1min 30s",... | Sample Input::
TimeoutStartUSec=1min 30s
LimitNOFILE=65536
LimitMEMLOCK=
LimitLOCKS=18446744073709551615
Sample Output::
{"LimitNOFILE" : "65536",
"TimeoutStartUSec" : "1min 30s",
"LimitLOCKS" : "1844674407370955161... |
def unsubscribe(self, code_list, subtype_list):
"""
取消订阅
:param code_list: 取消订阅的股票代码列表
:param subtype_list: 取消订阅的类型,参见SubType
:return: (ret, err_message)
ret == RET_OK err_message为None
ret != RET_OK err_message为错误描述字符串
"""
ret, m... | 取消订阅
:param code_list: 取消订阅的股票代码列表
:param subtype_list: 取消订阅的类型,参见SubType
:return: (ret, err_message)
ret == RET_OK err_message为None
ret != RET_OK err_message为错误描述字符串 |
def _connect(self):
"""Connect to our domain"""
if not self._db:
import boto
sdb = boto.connect_sdb()
if not self.domain_name:
self.domain_name = boto.config.get("DB", "sequence_db", boto.config.get("DB", "db_name", "default"))
try:
... | Connect to our domain |
def object(self, infotype, key):
"Return the encoding, idletime, or refcount about the key"
return self.execute_command('OBJECT', infotype, key, infotype=infotype) | Return the encoding, idletime, or refcount about the key |
async def _read_packet(self, packet_type=MysqlPacket):
"""Read an entire "mysql packet" in its entirety from the network
and return a MysqlPacket type that represents the results.
"""
buff = b''
while True:
try:
packet_header = await self._read_bytes(4... | Read an entire "mysql packet" in its entirety from the network
and return a MysqlPacket type that represents the results. |
def check_model(self):
"""
Check the model for various errors. This method checks for the following
errors.
* Checks if factors are defined for all the cliques or not.
* Check for running intersection property is not done explicitly over
here as it done in the add_edge... | Check the model for various errors. This method checks for the following
errors.
* Checks if factors are defined for all the cliques or not.
* Check for running intersection property is not done explicitly over
here as it done in the add_edges method.
* Checks if cardinality i... |
def vatu0(self,E,Lz,u0,R,retv2=False):
"""
NAME:
vatu0
PURPOSE:
calculate the velocity at u0
INPUT:
E - energy
Lz - angular momentum
u0 - u0
R - radius corresponding to u0,pi/2.
retv2= (False), if True return v^... | NAME:
vatu0
PURPOSE:
calculate the velocity at u0
INPUT:
E - energy
Lz - angular momentum
u0 - u0
R - radius corresponding to u0,pi/2.
retv2= (False), if True return v^2
OUTPUT:
velocity
HISTORY:
... |
def _get_connection_from_url(self, url, timeout, **kwargs):
"""Returns a connection object given a string url"""
url = self._decode_url(url, "")
if url.scheme == 'http' or url.scheme == 'https':
return HttpConnection(url.geturl(), timeout=timeout, **kwargs)
else:
... | Returns a connection object given a string url |
def pause(self, *partitions):
"""Suspend fetching from the requested partitions.
Future calls to :meth:`~kafka.KafkaConsumer.poll` will not return any
records from these partitions until they have been resumed using
:meth:`~kafka.KafkaConsumer.resume`.
Note: This method does no... | Suspend fetching from the requested partitions.
Future calls to :meth:`~kafka.KafkaConsumer.poll` will not return any
records from these partitions until they have been resumed using
:meth:`~kafka.KafkaConsumer.resume`.
Note: This method does not affect partition subscription. In parti... |
def get_heading_encoding(response):
'''Return the document encoding from a HTTP header.
Args:
response (Response): An instance of :class:`.http.Response`.
Returns:
``str``, ``None``: The codec name.
'''
encoding = wpull.protocol.http.util.parse_charset(
response.fields.get(... | Return the document encoding from a HTTP header.
Args:
response (Response): An instance of :class:`.http.Response`.
Returns:
``str``, ``None``: The codec name. |
def save(self):
"""
Save any outstanding items. This returns a Deferred which will
errback if Tor was unhappy with anything, or callback with
this TorConfig object on success.
"""
if not self.needs_save():
return defer.succeed(self)
args = []
... | Save any outstanding items. This returns a Deferred which will
errback if Tor was unhappy with anything, or callback with
this TorConfig object on success. |
def get_bulk_asn_whois(addresses=None, retry_count=3, timeout=120):
"""
The function for retrieving ASN information for multiple IP addresses from
Cymru via port 43/tcp (WHOIS).
Args:
addresses (:obj:`list` of :obj:`str`): IP addresses to lookup.
retry_count (:obj:`int`): The number of ... | The function for retrieving ASN information for multiple IP addresses from
Cymru via port 43/tcp (WHOIS).
Args:
addresses (:obj:`list` of :obj:`str`): IP addresses to lookup.
retry_count (:obj:`int`): The number of times to retry in case socket
errors, timeouts, connection resets, e... |
def forward(self, is_train=False):
"""Perform a forward pass on each executor."""
for texec in self.train_execs:
texec.forward(is_train=is_train) | Perform a forward pass on each executor. |
def _process_custom_unitary(self, node):
"""Process a custom unitary node."""
name = node.name
if node.arguments is not None:
args = self._process_node(node.arguments)
else:
args = []
bits = [self._process_bit_id(node_element)
for node_elem... | Process a custom unitary node. |
def on(self, analyte=None, filt=None):
"""
Turn on specified filter(s) for specified analyte(s).
Parameters
----------
analyte : optional, str or array_like
Name or list of names of analytes.
Defaults to all analytes.
filt : optional. int, str or ... | Turn on specified filter(s) for specified analyte(s).
Parameters
----------
analyte : optional, str or array_like
Name or list of names of analytes.
Defaults to all analytes.
filt : optional. int, str or array_like
Name/number or iterable names/number... |
def alpha_beta_aligned(returns,
factor_returns,
risk_free=0.0,
period=DAILY,
annualization=None,
out=None):
"""Calculates annualized alpha and beta.
If they are pd.Series, expects returns and fact... | Calculates annualized alpha and beta.
If they are pd.Series, expects returns and factor_returns have already
been aligned on their labels. If np.ndarray, these arguments should have
the same shape.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, ... |
def _insert_compressed(
collection_name, docs, check_keys, continue_on_error, opts, ctx):
"""Internal compressed unacknowledged insert message helper."""
op_insert, max_bson_size = _insert(
collection_name, docs, check_keys, continue_on_error, opts)
rid, msg = _compress(2002, op_insert, ctx)... | Internal compressed unacknowledged insert message helper. |
def run_preassembly(stmts_in, **kwargs):
"""Run preassembly on a list of statements.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to preassemble.
return_toplevel : Optional[bool]
If True, only the top-level statements are returned. If False,... | Run preassembly on a list of statements.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to preassemble.
return_toplevel : Optional[bool]
If True, only the top-level statements are returned. If False,
all statements are returned irrespectiv... |
def add_resource(self, value, name: str = 'default', context_attr: str = None,
types: Union[type, Sequence[type]] = ()) -> None:
"""
Add a resource to this context.
This will cause a ``resource_added`` event to be dispatched.
:param value: the actual resource value... | Add a resource to this context.
This will cause a ``resource_added`` event to be dispatched.
:param value: the actual resource value
:param name: name of this resource (unique among all its registered types within a single
context)
:param context_attr: name of the context a... |
def getopt(self, name, argv, opts):
"""getopt(name, argv, opts)
Parse X command line options, inserting the recognised options
into the resource database.
NAME is the application name, and will be prepended to all
specifiers. ARGV is the list of command line arguments,
... | getopt(name, argv, opts)
Parse X command line options, inserting the recognised options
into the resource database.
NAME is the application name, and will be prepended to all
specifiers. ARGV is the list of command line arguments,
typically sys.argv[1:].
OPTS is a map... |
def can_use_autofor(self, node):
"""
Check if given for Node can use autoFor syntax.
To use auto_for:
- iterator should have local scope
- yield should not be use
- OpenMP pragma should not be use
TODO : Yield should block only if it is use in the fo... | Check if given for Node can use autoFor syntax.
To use auto_for:
- iterator should have local scope
- yield should not be use
- OpenMP pragma should not be use
TODO : Yield should block only if it is use in the for loop, not in the
whole function. |
def simxGetFloatingParameter(clientID, paramIdentifier, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
paramValue = ct.c_float()
return c_GetFloatingParameter(clientID, paramIdentifier, ct.byref(paramValue), operationMode), paramValue.v... | Please have a look at the function description/documentation in the V-REP user manual |
def add_connection(self, host):
"""
Create a new :class:`~elasticsearch.Connection` instance and add it to the pool.
:arg host: kwargs that will be used to create the instance
"""
self.hosts.append(host)
self.set_connections(self.hosts) | Create a new :class:`~elasticsearch.Connection` instance and add it to the pool.
:arg host: kwargs that will be used to create the instance |
def nr_of_antenna(nbl, auto_correlations=False):
"""
Compute the number of antenna for the
given number of baselines. Can specify whether
auto-correlations should be taken into
account
"""
t = 1 if auto_correlations is False else -1
return int(t + math.sqrt(1 + 8*nbl)) // 2 | Compute the number of antenna for the
given number of baselines. Can specify whether
auto-correlations should be taken into
account |
def f(self, m):
"""
The recursively composed version of filter function f.
By default, returns logical **conjunction** of operator and single
child operator
"""
if len(self.children) == 0:
return self._f(m)
elif len(self.children) == 1:
ret... | The recursively composed version of filter function f.
By default, returns logical **conjunction** of operator and single
child operator |
def forward_events_to(self, sink, include_source=False):
"""This forwards signal to sink"""
assert isinstance(sink, Eventful), f'{sink.__class__.__name__} is not Eventful'
self._forwards[sink] = include_source | This forwards signal to sink |
def download_csv(data, filename):
"""
Download an H2O data set to a CSV file on the local disk.
Warning: Files located on the H2O server may be very large! Make sure you have enough
hard drive space to accommodate the entire file.
:param data: an H2OFrame object to be downloaded.
:param filena... | Download an H2O data set to a CSV file on the local disk.
Warning: Files located on the H2O server may be very large! Make sure you have enough
hard drive space to accommodate the entire file.
:param data: an H2OFrame object to be downloaded.
:param filename: name for the CSV file where the data shoul... |
def md5(text):
"""Returns the md5 hash of a string."""
h = hashlib.md5()
h.update(_unicode(text).encode("utf-8"))
return h.hexdigest() | Returns the md5 hash of a string. |
def delete_chat_photo(chat_id, **kwargs):
"""
Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat
for this to work and must have the appropriate admin rights.
:param chat_id: Unique identifier for the target chat or username of... | Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat
for this to work and must have the appropriate admin rights.
:param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
... |
def crsConvert(crsIn, crsOut):
"""
convert between different types of spatial references
Parameters
----------
crsIn: int, str or :osgeo:class:`osr.SpatialReference`
the input CRS
crsOut: {'wkt', 'proj4', 'epsg', 'osr', 'opengis' or 'prettyWkt'}
the output CRS type
Returns
... | convert between different types of spatial references
Parameters
----------
crsIn: int, str or :osgeo:class:`osr.SpatialReference`
the input CRS
crsOut: {'wkt', 'proj4', 'epsg', 'osr', 'opengis' or 'prettyWkt'}
the output CRS type
Returns
-------
int, str or :osgeo:class:`o... |
def acquire(self, tag, blocking=True):
"""Acquire the semaphore
:param tag: A tag identifying what is acquiring the semaphore. Note
that this is not really needed to directly use this class but is
needed for API compatibility with the SlidingWindowSemaphore
implement... | Acquire the semaphore
:param tag: A tag identifying what is acquiring the semaphore. Note
that this is not really needed to directly use this class but is
needed for API compatibility with the SlidingWindowSemaphore
implementation.
:param block: If True, block until ... |
def with_user_roles(roles):
"""
with_user_roles(roles)
It allows to check if a user has access to a view by adding the decorator
with_user_roles([])
Requires flask-login
In your model, you must have a property 'role', which will be invoked to
be compared to the roles provided.
If cur... | with_user_roles(roles)
It allows to check if a user has access to a view by adding the decorator
with_user_roles([])
Requires flask-login
In your model, you must have a property 'role', which will be invoked to
be compared to the roles provided.
If current_user doesn't have a role, it will t... |
def read(fname,**kw):
'''
Reads an lsp output file and returns a raw dump of data,
sectioned into quantities either as an dictionary or a typed numpy array.
Parameters:
-----------
fname -- filename of thing to read
Keyword Arguments:
------------------
vprint -- Verbose p... | Reads an lsp output file and returns a raw dump of data,
sectioned into quantities either as an dictionary or a typed numpy array.
Parameters:
-----------
fname -- filename of thing to read
Keyword Arguments:
------------------
vprint -- Verbose printer. Used in scripts
overri... |
def options(self, **options):
"""A context-manager for setting connection options; the original
values of the options will be restored when the context-manager exits.
For example::
with c.options(gui_mode = False):
c.cmd.vol_list()
"""
self._contexts... | A context-manager for setting connection options; the original
values of the options will be restored when the context-manager exits.
For example::
with c.options(gui_mode = False):
c.cmd.vol_list() |
def state(name):
'''
Return state of container (running or stopped)
CLI Example:
.. code-block:: bash
salt myminion nspawn.state <name>
'''
try:
cmd = 'show {0} --property=State'.format(name)
return _machinectl(cmd, ignore_retcode=True)['stdout'].split('=')[-1]
exc... | Return state of container (running or stopped)
CLI Example:
.. code-block:: bash
salt myminion nspawn.state <name> |
def _remove_extraneous_xml_declarations(xml_str):
"""
Sometimes devices return XML with more than one XML declaration in, such as when returning
their own XML config files. This removes the extra ones and preserves the first one.
"""
xml_declaration = ''
if xml_str.starts... | Sometimes devices return XML with more than one XML declaration in, such as when returning
their own XML config files. This removes the extra ones and preserves the first one. |
def SetSize(self, rect):
"Called to position/size the edit control within the cell rectangle."
self._tc.SetDimensions(rect.x, rect.y, rect.width+2, rect.height+2,
wx.SIZE_ALLOW_MINUS_ONE) | Called to position/size the edit control within the cell rectangle. |
def handle_exception(self, exc):
"""Use custom exception handler for errors."""
if isinstance(
exc, (rest_exceptions.NotAuthenticated,
rest_exceptions.AuthenticationFailed)) and self.HANDLE_UNAUTHENTICATED:
return HttpResponseRedirect('{}?next={}'.format(
... | Use custom exception handler for errors. |
def token(config, token):
"""Store and fetch a GitHub access token"""
if not token:
info_out(
"To generate a personal API token, go to:\n\n\t"
"https://github.com/settings/tokens\n\n"
"To read more about it, go to:\n\n\t"
"https://help.github.com/articles/... | Store and fetch a GitHub access token |
def install_docs(instance, clear_target):
"""Builds and installs the complete HFOS documentation."""
_check_root()
def make_docs():
"""Trigger a Sphinx make command to build the documentation."""
log("Generating HTML documentation")
try:
build = Popen(
... | Builds and installs the complete HFOS documentation. |
def payload_unregister(klass, pid):
""" is used while a hook is running to let Juju know
that a payload has been manually stopped. The <class> and <id> provided
must match a payload that has been previously registered with juju using
payload-register."""
cmd = ['payload-unregister']
for x in [kl... | is used while a hook is running to let Juju know
that a payload has been manually stopped. The <class> and <id> provided
must match a payload that has been previously registered with juju using
payload-register. |
def _norm_default(x):
"""Default Euclidean norm implementation."""
# Lazy import to improve `import odl` time
import scipy.linalg
if _blas_is_applicable(x.data):
nrm2 = scipy.linalg.blas.get_blas_funcs('nrm2', dtype=x.dtype)
norm = partial(nrm2, n=native(x.size))
else:
norm ... | Default Euclidean norm implementation. |
def get_subfolders(self):
"""Retrieve all child Folders inside of this Folder.
Raises:
AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token.
Returns:
List[:class:`Folder <pyOutlook.core.folder.Folder>`]
"""
h... | Retrieve all child Folders inside of this Folder.
Raises:
AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token.
Returns:
List[:class:`Folder <pyOutlook.core.folder.Folder>`] |
def _on_stackexchange_user(self, future, access_token, response):
"""Invoked as a callback when self.stackexchange_request returns the
response to the request for user data.
:param method future: The callback method to pass along
:param str access_token: The access token for the user's ... | Invoked as a callback when self.stackexchange_request returns the
response to the request for user data.
:param method future: The callback method to pass along
:param str access_token: The access token for the user's use
:param dict response: The HTTP response already decoded |
def cols_strip(df,col_list, dest = False):
""" Performs str.strip() a column of a DataFrame
Parameters:
df - DataFrame
DataFrame to operate on
col_list - list of strings
names of columns to strip
dest - bool, default False
Whether to apply the result to the DataFrame or retur... | Performs str.strip() a column of a DataFrame
Parameters:
df - DataFrame
DataFrame to operate on
col_list - list of strings
names of columns to strip
dest - bool, default False
Whether to apply the result to the DataFrame or return it.
True is apply, False is return. |
def _yum_pkginfo(output):
'''
Parse yum/dnf output (which could contain irregular line breaks if package
names are long) retrieving the name, version, etc., and return a list of
pkginfo namedtuples.
'''
cur = {}
keys = itertools.cycle(('name', 'version', 'repoid'))
values = salt.utils.it... | Parse yum/dnf output (which could contain irregular line breaks if package
names are long) retrieving the name, version, etc., and return a list of
pkginfo namedtuples. |
def print_log(value_color="", value_noncolor=""):
"""set the colors for text."""
HEADER = '\033[92m'
ENDC = '\033[0m'
print(HEADER + value_color + ENDC + str(value_noncolor)) | set the colors for text. |
def get_group_filters(self):
"""Return es OR filters to include all special coverage group conditions."""
group_filters = []
field_map = {
"feature-type": "feature_type.slug",
"tag": "tags.slug",
"content-type": "_type"
}
for group_set in self.... | Return es OR filters to include all special coverage group conditions. |
def axes(self):
"""
Returns all the axes that have been defined for this chart.
:return [<projexui.widgets.xchart.XChartAxis>, ..]
"""
out = self._axes[:]
if self._horizontalAxis:
out.append(self._horizontalAxis)
if self._vertical... | Returns all the axes that have been defined for this chart.
:return [<projexui.widgets.xchart.XChartAxis>, ..] |
def _get_placeholders(sql_statement, parameters):
"""
Retrieve the list of placeholders and their type defined in an SQL
statement.
@param sql_statement: a parameterized statement.
@param parameters: the list of parameters used in the SQL statement.
@return: a dictio... | Retrieve the list of placeholders and their type defined in an SQL
statement.
@param sql_statement: a parameterized statement.
@param parameters: the list of parameters used in the SQL statement.
@return: a dictionary of placeholders where the key represents the
name of ... |
def isIsosceles(self):
'''
True iff two side lengths are equal, boolean.
'''
return (self.a == self.b) or (self.a == self.c) or (self.b == self.c) | True iff two side lengths are equal, boolean. |
def match1(pattern, data, **parse_kwargs):
"""Returns first matched value of pattern in data or None if no matches"""
matches = match(pattern, data, **parse_kwargs)
return matches[0] if matches else None | Returns first matched value of pattern in data or None if no matches |
def _sanity_check_construct_result_block(ir_blocks):
"""Assert that ConstructResult is always the last block, and only the last block."""
if not isinstance(ir_blocks[-1], ConstructResult):
raise AssertionError(u'The last block was not ConstructResult: {}'.format(ir_blocks))
for block in ir_blocks[:-... | Assert that ConstructResult is always the last block, and only the last block. |
def enumerate_chunks (phrase, spacy_nlp):
"""
iterate through the noun phrases
"""
if (len(phrase) > 1):
found = False
text = " ".join([rl.text for rl in phrase])
doc = spacy_nlp(text.strip(), parse=True)
for np in doc.noun_chunks:
if np.text != text:
... | iterate through the noun phrases |
def update(self):
"""This method should be called to update associated Posts
It will call content-specific methods:
_get_data() to obtain list of entries
_store_post() to store obtained entry object
_get_data_source_url() to get an URL to identify Posts from this D... | This method should be called to update associated Posts
It will call content-specific methods:
_get_data() to obtain list of entries
_store_post() to store obtained entry object
_get_data_source_url() to get an URL to identify Posts from this Data Source |
def canonicalize_path(cwd, path):
"""
Canonicalizes a path relative to a given working directory. That
is, the path, if not absolute, is interpreted relative to the
working directory, then converted to absolute form.
:param cwd: The working directory.
:param path: The path to canonicalize.
... | Canonicalizes a path relative to a given working directory. That
is, the path, if not absolute, is interpreted relative to the
working directory, then converted to absolute form.
:param cwd: The working directory.
:param path: The path to canonicalize.
:returns: The absolute path. |
def to_repr(value, ctx):
"""
Converts a value back to its representation form, e.g. x -> "x"
"""
as_string = to_string(value, ctx)
if isinstance(value, str) or isinstance(value, datetime.date) or isinstance(value, datetime.time):
as_string = as_string.replace('"', '""') # escape quotes by ... | Converts a value back to its representation form, e.g. x -> "x" |
def simplex_summation_matrix(simplices, weight=None, inverse=False):
'''
simplex_summation_matrix(mtx) yields a scipy sparse array matrix that, when dotted with a
column vector of length m (where m is the number of simplices described in the simplex matrix,
mtx), yields a vector of length n (where n... | simplex_summation_matrix(mtx) yields a scipy sparse array matrix that, when dotted with a
column vector of length m (where m is the number of simplices described in the simplex matrix,
mtx), yields a vector of length n (where n is the number of vertices in the simplex mesh); the
returned vetor is the ... |
def zplane(self,auto_scale=True,size=2,detect_mult=True,tol=0.001):
"""
Plot the poles and zeros of the FIR filter in the z-plane
"""
iir_d.sos_zplane(self.sos,auto_scale,size,tol) | Plot the poles and zeros of the FIR filter in the z-plane |
def set_server_key(self, zmq_socket, server_secret_key_path):
'''must call before bind'''
load_and_set_key(zmq_socket, server_secret_key_path)
zmq_socket.curve_server = True | must call before bind |
def reset_options(self, empty=True):
"""Empty ALL options.
:param bool empty: When :data:`True`, completelly removes all options;
when :data:`False`, sets them back to its original value.
This function skips ``locked`` control.
"""
if empty:
self.gc = pd... | Empty ALL options.
:param bool empty: When :data:`True`, completelly removes all options;
when :data:`False`, sets them back to its original value.
This function skips ``locked`` control. |
def get_potential_markables(docgraph):
"""
returns a list of all NPs and PPs in the given docgraph.
Parameters
----------
docgraph : DiscourseDocumentGraph
a document graph that (at least) contains syntax trees
(imported from Tiger XML files)
Returns
-------
potential_m... | returns a list of all NPs and PPs in the given docgraph.
Parameters
----------
docgraph : DiscourseDocumentGraph
a document graph that (at least) contains syntax trees
(imported from Tiger XML files)
Returns
-------
potential_markables : list of str or int
Node IDs of a... |
def checkIfRemoteIsNewer(self, localfile, remote_size, remote_modify):
"""
Overrides checkIfRemoteIsNewer in Source class
:param localfile: str file path
:param remote_size: str bytes
:param remote_modify: str last modify date in the form 20160705042714
:return: boolean ... | Overrides checkIfRemoteIsNewer in Source class
:param localfile: str file path
:param remote_size: str bytes
:param remote_modify: str last modify date in the form 20160705042714
:return: boolean True if remote file is newer else False |
def gpg_list_app_keys( blockchain_id, appname, proxy=None, wallet_keys=None, config_dir=None ):
"""
List the set of available GPG keys tagged for a given application.
Return list of {'keyName': key name, 'contentUrl': URL to key data}
Raise on error
"""
raise Exception("BROKEN; depends on list_... | List the set of available GPG keys tagged for a given application.
Return list of {'keyName': key name, 'contentUrl': URL to key data}
Raise on error |
def encode_offset_commit_request(cls, client_id, correlation_id,
group, group_generation_id, consumer_id,
payloads):
"""
Encode some OffsetCommitRequest structs (v1)
:param bytes client_id: string
:param int corre... | Encode some OffsetCommitRequest structs (v1)
:param bytes client_id: string
:param int correlation_id: int
:param str group: the consumer group to which you are committing offsets
:param int group_generation_id: int32, generation ID of the group
:param str consumer_id: string, I... |
def from_xml_node(xml_node):
"""constructs a CLI.Parameter from an xml node.
:param xml_node:
:type xml_node: xml.etree.ElementTree.Element
:rtype: Executable.Parameter
:return:
"""
def gather_enum_values():
l = []
for element in xml_node.... | constructs a CLI.Parameter from an xml node.
:param xml_node:
:type xml_node: xml.etree.ElementTree.Element
:rtype: Executable.Parameter
:return: |
def add_filter(self, filter_, frequencies=None, dB=True,
analog=False, sample_rate=None, **kwargs):
"""Add a linear time-invariant filter to this BodePlot
Parameters
----------
filter_ : `~scipy.signal.lti`, `tuple`
the filter to plot, either as a `~scipy.... | Add a linear time-invariant filter to this BodePlot
Parameters
----------
filter_ : `~scipy.signal.lti`, `tuple`
the filter to plot, either as a `~scipy.signal.lti`, or a
`tuple` with the following number and meaning of elements
- 2: (numerator, denomin... |
def info(name, location='\\'):
r'''
Get the details about a task in the task scheduler.
:param str name: The name of the task for which to return the status
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
... | r'''
Get the details about a task in the task scheduler.
:param str name: The name of the task for which to return the status
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
... |
def fetch_withdrawals(self, limit: int) -> List[Withdrawal]:
"""Fetch latest withdrawals, must provide a limit."""
return self._transactions(self._withdrawals, 'withdrawals', limit) | Fetch latest withdrawals, must provide a limit. |
def set_value(self, value, layer=None, source=None):
"""Set a value for a particular layer with optional metadata about source.
Parameters
----------
value : str
Data to store in the node.
layer : str
Name of the layer to use. If None then the outermost w... | Set a value for a particular layer with optional metadata about source.
Parameters
----------
value : str
Data to store in the node.
layer : str
Name of the layer to use. If None then the outermost where the value
exists will be used.
source :... |
def brief_exception_text(exception, secret_values):
"""
Returns the Exception class and the message of the exception as string.
:param exception: The exception to format
:param secret_values: Values to hide in output
"""
exception_text = _hide_secret_values(str(exception), secret_values)
re... | Returns the Exception class and the message of the exception as string.
:param exception: The exception to format
:param secret_values: Values to hide in output |
def json_path_components(path):
"""Convert JSON path to individual path components.
:param path: JSON path, which can be either an iterable of path
components or a dot-separated string
:return: A list of path components
"""
if isinstance(path, str):
path = path.split('.')
retur... | Convert JSON path to individual path components.
:param path: JSON path, which can be either an iterable of path
components or a dot-separated string
:return: A list of path components |
def add(self, variant, arch, image):
"""
Assign an :class:`.Image` object to variant and arch.
:param variant: compose variant UID
:type variant: str
:param arch: compose architecture
:type arch: str
:param image: image
:type image: :class:`.... | Assign an :class:`.Image` object to variant and arch.
:param variant: compose variant UID
:type variant: str
:param arch: compose architecture
:type arch: str
:param image: image
:type image: :class:`.Image` |
def remove_adapter(widget_class, flavour=None):
"""Removes the given widget class information from the default set
of adapters.
If widget_class had been previously added by using add_adapter,
the added adapter will be removed, restoring possibly previusly
existing adapter(s). Notice that this funct... | Removes the given widget class information from the default set
of adapters.
If widget_class had been previously added by using add_adapter,
the added adapter will be removed, restoring possibly previusly
existing adapter(s). Notice that this function will remove only
*one* adapter about given wige... |
def createmergerequest(self, project_id, sourcebranch, targetbranch,
title, target_project_id=None, assignee_id=None):
"""
Create a new merge request.
:param project_id: ID of the project originating the merge request
:param sourcebranch: name of the branch to... | Create a new merge request.
:param project_id: ID of the project originating the merge request
:param sourcebranch: name of the branch to merge from
:param targetbranch: name of the branch to merge to
:param title: Title of the merge request
:param assignee_id: Assignee user ID
... |
def clear_priority(self):
"""Removes the priority.
raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.logging.LogE... | Removes the priority.
raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* |
def _render(self, contexts, partials):
"""render variable"""
value = self._lookup(self.value, contexts)
# lambda
if callable(value):
value = inner_render(str(value()), contexts, partials)
return self._escape(value) | render variable |
def items(self):
"""Return list of tuples of keys and values in db
>>> dc = Dictator()
>>> dc['l0'] = [1, 2, 3, 4]
>>> dc.items()
[('l0', ['1', '2', '3', '4'])]
>>> dc.clear()
:return: list of (key, value) pairs
:rtype: list of tuple
"""
... | Return list of tuples of keys and values in db
>>> dc = Dictator()
>>> dc['l0'] = [1, 2, 3, 4]
>>> dc.items()
[('l0', ['1', '2', '3', '4'])]
>>> dc.clear()
:return: list of (key, value) pairs
:rtype: list of tuple |
def parse_file(file):
"""
Take an open file containing the IANA subtag registry, and yield a
dictionary of information for each subtag it describes.
"""
lines = []
for line in file:
line = line.rstrip('\n')
if line == '%%':
# This is a separator between items. Parse t... | Take an open file containing the IANA subtag registry, and yield a
dictionary of information for each subtag it describes. |
def is_tuple_end(self, extra_end_rules=None):
"""Are we at the end of a tuple?"""
if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):
return True
elif extra_end_rules is not None:
return self.stream.current.test_any(extra_end_rules)
return Fals... | Are we at the end of a tuple? |
def textFileStream(self, directory, process_all=False):
"""Monitor a directory and process all text files.
File names starting with ``.`` are ignored.
:param string directory: a path
:param bool process_all: whether to process pre-existing files
:rtype: DStream
.. warn... | Monitor a directory and process all text files.
File names starting with ``.`` are ignored.
:param string directory: a path
:param bool process_all: whether to process pre-existing files
:rtype: DStream
.. warning::
The ``process_all`` parameter does not exist in t... |
def set_glitch_filter(self, user_gpio, steady):
"""
Sets a glitch filter on a GPIO.
Level changes on the GPIO are not reported unless the level
has been stable for at least [*steady*] microseconds. The
level is then reported. Level changes of less than [*steady*]
micros... | Sets a glitch filter on a GPIO.
Level changes on the GPIO are not reported unless the level
has been stable for at least [*steady*] microseconds. The
level is then reported. Level changes of less than [*steady*]
microseconds are ignored.
user_gpio:= 0-31
steady:= 0-3... |
def cmd_list(self, argv, help):
"""Return a list of various things"""
parser = argparse.ArgumentParser(
prog="%s list" % self.progname,
description=help,
)
parser.add_argument("list", nargs=1,
metavar="listname",
... | Return a list of various things |
def set_default_headers(context):
"""
:type context: behave.runner.Context
"""
headers = row_table(context)
def default_headers_function():
return headers
requestsdefaulter.default_headers(default_headers_function) | :type context: behave.runner.Context |
def collate_revs(old, new, key=lambda x: x, merge=lambda old, new: new):
"""
Given revision sets old and new, each containing a series
of revisions of some set of objects, collate them based on
these rules:
- all items from each set are yielded in stable order
- items in old are yielded first
- items in new are... | Given revision sets old and new, each containing a series
of revisions of some set of objects, collate them based on
these rules:
- all items from each set are yielded in stable order
- items in old are yielded first
- items in new are yielded last
- items that match are yielded in the order in which they
appea... |
def _update_history(self):
"""Update the history file"""
version = self.data['new_version']
history = self.vcs.history_file()
if not history:
logger.warn("No history file found")
return
history_lines = open(history).read().split('\n')
headings = ut... | Update the history file |
def add(name, **kwargs):
'''
Add the specified group
Args:
name (str):
The name of the group to add
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' group.add foo
'''
if not info(name):
... | Add the specified group
Args:
name (str):
The name of the group to add
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' group.add foo |
def get_metadata(self):
"""
Provide metadata about this image.
:return: ImageMetadata, Image metadata instance
"""
if self._metadata is None:
self._metadata = ImageMetadata()
inspect_to_metadata(self._metadata, self.inspect(refresh=True))
return self.... | Provide metadata about this image.
:return: ImageMetadata, Image metadata instance |
def LeaseCronJobs(self, cronjob_ids=None, lease_time=None):
"""Leases all available cron jobs."""
leased_jobs = []
now = rdfvalue.RDFDatetime.Now()
expiration_time = now + lease_time
for job in itervalues(self.cronjobs):
if cronjob_ids and job.cron_job_id not in cronjob_ids:
continue... | Leases all available cron jobs. |
def tool_click(self, evt):
"Event handler tool selection (just add to default handler)"
# get the control
ctrl = self.menu_ctrl_map[evt.GetId()]
# create the control on the parent:
if self.inspector.selected_obj:
# find the first parent drop target
pa... | Event handler tool selection (just add to default handler) |
def get_revision():
"""
GET THE CURRENT GIT REVISION
"""
proc = Process("git log", ["git", "log", "-1"])
try:
while True:
line = proc.stdout.pop().strip().decode('utf8')
if not line:
continue
if line.startswith("commit "):
... | GET THE CURRENT GIT REVISION |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.