code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def start(self):
'''
Start listening for messages.
'''
log.debug('Creating the TCP server')
if ':' in self.address:
self.skt = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
... | Start listening for messages. |
def cursor_batch(self,
table_name,
start_timeperiod,
end_timeperiod):
""" method returns batched DB cursor """
raise NotImplementedError('method cursor_batch must be implemented by {0}'.format(self.__class__.__name__)) | method returns batched DB cursor |
def login(self, email=None, password=None):
"""
Interactive login using the `cloudgenix.API` object. This function is more robust and handles SAML and MSP accounts.
Expects interactive capability. if this is not available, use `cloudenix.API.post.login` directly.
**Parameters:**:
... | Interactive login using the `cloudgenix.API` object. This function is more robust and handles SAML and MSP accounts.
Expects interactive capability. if this is not available, use `cloudenix.API.post.login` directly.
**Parameters:**:
- **email**: Email to log in for, will prompt if not entere... |
def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE):
"""Yield pieces of data from a file-like object until EOF."""
while True:
chunk = file.read(size)
if not chunk:
break
yield chunk | Yield pieces of data from a file-like object until EOF. |
def get_discrete_grid(self):
"""
Computes a Numpy array with the grid of points that results after crossing the possible outputs of the discrete
variables
"""
sets_grid = []
for d in self.space:
if d.type == 'discrete':
sets_grid.extend([d.doma... | Computes a Numpy array with the grid of points that results after crossing the possible outputs of the discrete
variables |
def setbit(self, name, offset, val):
"""
Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
indicating the previous value of ``offset``.
Like **Redis.SETBIT**
:param string name: the key name
:param int offset: the bit position
:para... | Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
indicating the previous value of ``offset``.
Like **Redis.SETBIT**
:param string name: the key name
:param int offset: the bit position
:param bool val: the bit value
:return: the previous b... |
def add_class(self, node):
"""visit one class and add it to diagram"""
self.linker.visit(node)
self.classdiagram.add_object(self.get_title(node), node) | visit one class and add it to diagram |
def parse(
idp_metadata,
required_sso_binding=OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT,
required_slo_binding=OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT,
entity_id=None):
"""
Parse the Identity Provider metadata and return a dict with extracted da... | Parse the Identity Provider metadata and return a dict with extracted data.
If there are multiple <IDPSSODescriptor> tags, parse only the first.
Parse only those SSO endpoints with the same binding as given by
the `required_sso_binding` parameter.
Parse only those SLO endpoints with t... |
def create(self, request):
"""Creates a new wiki page for the specified PullRequest instance. The page
gets initialized with basic information about the pull request, the tests
that will be run, etc. Returns the URL on the wiki.
:arg request: the PullRequest instance with testing inform... | Creates a new wiki page for the specified PullRequest instance. The page
gets initialized with basic information about the pull request, the tests
that will be run, etc. Returns the URL on the wiki.
:arg request: the PullRequest instance with testing information. |
def split_comp_info(self, catalog_name, split_ver, split_key):
""" Return the info for a particular split key """
return self._split_comp_info_dicts["%s_%s" % (catalog_name, split_ver)][split_key] | Return the info for a particular split key |
def _identity_stmt(self, stmt: Statement, sctx: SchemaContext) -> None:
"""Handle identity statement."""
if not sctx.schema_data.if_features(stmt, sctx.text_mid):
return
id = (stmt.argument, sctx.schema_data.namespace(sctx.text_mid))
adj = sctx.schema_data.identity_adjs.setde... | Handle identity statement. |
def build_tqdm_outer(self, desc, total):
"""
Extension point. Override to provide custom options to outer progress bars (Epoch loop)
:param desc: Description
:param total: Number of epochs
:return: new progress bar
"""
return self.tqdm(desc=desc, total=total, leav... | Extension point. Override to provide custom options to outer progress bars (Epoch loop)
:param desc: Description
:param total: Number of epochs
:return: new progress bar |
def render_view(parser, token):
"""
Return an string version of a View with as_string method.
First argument is the name of the view. Any other arguments
should be keyword arguments and will be passed to the view.
Example:
{% render_view viewname var1=xx var2=yy %}
"""
bits = token.spl... | Return an string version of a View with as_string method.
First argument is the name of the view. Any other arguments
should be keyword arguments and will be passed to the view.
Example:
{% render_view viewname var1=xx var2=yy %} |
def _set_attribute(self, name, value):
"""Make sure namespace gets updated when setting attributes."""
setattr(self, name, value)
self.namespace.update({name: getattr(self, name)}) | Make sure namespace gets updated when setting attributes. |
def _cont_norm(fluxes, ivars, cont):
""" Continuum-normalize a continuous segment of spectra.
Parameters
----------
fluxes: numpy ndarray
pixel intensities
ivars: numpy ndarray
inverse variances, parallel to fluxes
contmask: boolean mask
True indicates that pixel is co... | Continuum-normalize a continuous segment of spectra.
Parameters
----------
fluxes: numpy ndarray
pixel intensities
ivars: numpy ndarray
inverse variances, parallel to fluxes
contmask: boolean mask
True indicates that pixel is continuum
Returns
-------
norm_flu... |
def upload_plugin(self, plugin_path):
"""
Provide plugin path for upload into Jira e.g. useful for auto deploy
:param plugin_path:
:return:
"""
files = {
'plugin': open(plugin_path, 'rb')
}
headers = {
'X-Atlassian-Token': 'nocheck'... | Provide plugin path for upload into Jira e.g. useful for auto deploy
:param plugin_path:
:return: |
def infer(self, sensationList, reset=True, objectName=None):
"""
Infer on given sensations.
The provided sensationList is a list of sensations, and each sensation is
a mapping from cortical column to a tuple of two SDR's respectively
corresponding to the location in object space and the feature.
... | Infer on given sensations.
The provided sensationList is a list of sensations, and each sensation is
a mapping from cortical column to a tuple of two SDR's respectively
corresponding to the location in object space and the feature.
For example, the input can look as follows, if we are inferring a simp... |
def is_authorization_expired(self):
"""Checks if the authorization token (access_token) has expired.
:return: If expired.
:rtype: ``bool``
"""
if not self.auth.token_expiration:
return True
return (datetime.datetime.utcnow() > self.auth.token_expiration) | Checks if the authorization token (access_token) has expired.
:return: If expired.
:rtype: ``bool`` |
def purgeCache(self, *args, **kwargs):
"""
Purge Worker Cache
Publish a purge-cache message to purge caches named `cacheName` with
`provisionerId` and `workerType` in the routing-key. Workers should
be listening for this message and purge caches when they see it.
This m... | Purge Worker Cache
Publish a purge-cache message to purge caches named `cacheName` with
`provisionerId` and `workerType` in the routing-key. Workers should
be listening for this message and purge caches when they see it.
This method takes input: ``v1/purge-cache-request.json#``
... |
def safe_main():
"""A safe version of the main function (that catches ProgramError)."""
try:
main()
except KeyboardInterrupt:
logger.info("Cancelled by user")
sys.exit(0)
except ProgramError as e:
logger.error(e.message)
parser.error(e.message) | A safe version of the main function (that catches ProgramError). |
async def stdout_writer():
"""
This is a bit complex, as stdout can be a pipe or a file.
If it is a file, we cannot use
:meth:`asycnio.BaseEventLoop.connect_write_pipe`.
"""
if sys.stdout.seekable():
# it’s a file
return sys.stdout.buffer.raw
if os.isatty(sys.stdin.fileno()... | This is a bit complex, as stdout can be a pipe or a file.
If it is a file, we cannot use
:meth:`asycnio.BaseEventLoop.connect_write_pipe`. |
def generate_shared_access_signature(self, services, resource_types,
permission, expiry, start=None,
ip=None, protocol=None):
'''
Generates a shared access signature for the account.
Use the returned signature with... | Generates a shared access signature for the account.
Use the returned signature with the sas_token parameter of the service
or to create a new account object.
:param Services services:
Specifies the services accessible with the account SAS. You can
combine values to pr... |
def _handle_backend_error(self, exception, idp):
"""
See super class satosa.frontends.base.FrontendModule
:type exception: satosa.exception.SATOSAAuthenticationError
:type idp: saml.server.Server
:rtype: satosa.response.Response
:param exception: The SATOSAAuthenticatio... | See super class satosa.frontends.base.FrontendModule
:type exception: satosa.exception.SATOSAAuthenticationError
:type idp: saml.server.Server
:rtype: satosa.response.Response
:param exception: The SATOSAAuthenticationError
:param idp: The saml frontend idp server
:retu... |
def prehook(self, **kwargs):
"""Launch local smpd."""
cmd = ['smpd', '-s']
logger.info("Starting smpd: "+" ".join(cmd))
rc = subprocess.call(cmd)
return rc | Launch local smpd. |
def _preprocess(self, valid_features=["pcp", "tonnetz", "mfcc",
"cqt", "tempogram"]):
"""This method obtains the actual features."""
# Use specific feature
if self.feature_str not in valid_features:
raise RuntimeError("Feature %s in not valid... | This method obtains the actual features. |
def load_file_contents(cls, file_contents, seed_values=None):
"""Loads config from the given string payloads.
A handful of seed values will be set to act as if specified in the loaded config file's DEFAULT
section, and be available for use in substitutions. The caller may override some of these
seed v... | Loads config from the given string payloads.
A handful of seed values will be set to act as if specified in the loaded config file's DEFAULT
section, and be available for use in substitutions. The caller may override some of these
seed values.
:param list[FileContents] file_contents: Load from these ... |
def init_map(self):
""" Add markers, polys, callouts, etc.."""
d = self.declaration
if d.show_location:
self.set_show_location(d.show_location)
if d.show_traffic:
self.set_show_traffic(d.show_traffic)
if d.show_indoors:
self.set_show_indoors(d.... | Add markers, polys, callouts, etc.. |
def _open_ds_from_store(fname, store_mod=None, store_cls=None, **kwargs):
"""Open a dataset and return it"""
if isinstance(fname, xr.Dataset):
return fname
if not isstring(fname):
try: # test iterable
fname[0]
except TypeError:
pass
else:
... | Open a dataset and return it |
def convert_user_type(cls, name, value):
"""
Converts a user type to RECORD that contains n fields, where n is the
number of attributes. Each element in the user type class will be converted to its
corresponding data type in BQ.
"""
names = value._fields
values = ... | Converts a user type to RECORD that contains n fields, where n is the
number of attributes. Each element in the user type class will be converted to its
corresponding data type in BQ. |
def merge_offsets_metadata(topics, *offsets_responses):
"""Merge the offset metadata dictionaries from multiple responses.
:param topics: list of topics
:param offsets_responses: list of dict topic: partition: offset
:returns: dict topic: partition: offset
"""
result = dict()
for topic in t... | Merge the offset metadata dictionaries from multiple responses.
:param topics: list of topics
:param offsets_responses: list of dict topic: partition: offset
:returns: dict topic: partition: offset |
def _buildTemplates(self):
"""
OVERRIDING THIS METHOD from Factory
"""
# INDEX - MAIN PAGE
contents = self._renderTemplate("html-multi/index.html", extraContext={"theme": self.theme, "index_page_flag" : True})
FILE_NAME = "index.html"
main_url = self._save2File(co... | OVERRIDING THIS METHOD from Factory |
def create_surface_grid(nr_electrodes=None, spacing=None,
electrodes_x=None,
depth=None,
left=None,
right=None,
char_lengths=None,
lines=None,
... | This is a simple wrapper for cr_trig_create to create simple surface
grids.
Automatically generated electrode positions are rounded to the third
digit.
Parameters
----------
nr_electrodes: int, optional
the number of surface electrodes
spacing: float... |
def _handle_http_error(self, url, response_obj, status_code, psp_ref,
raw_request, raw_response, headers, message):
"""This function handles the non 200 responses from Adyen, raising an
error that should provide more information.
Args:
url (str): url of th... | This function handles the non 200 responses from Adyen, raising an
error that should provide more information.
Args:
url (str): url of the request
response_obj (dict): Dict containing the parsed JSON response from
Adyen
status_code (int): HTTP status ... |
def intersect_leaderboards(self, destination, keys, aggregate='SUM'):
'''
Intersect leaderboards given by keys with this leaderboard into a named destination leaderboard.
@param destination [String] Destination leaderboard name.
@param keys [Array] Leaderboards to be merged with the cur... | Intersect leaderboards given by keys with this leaderboard into a named destination leaderboard.
@param destination [String] Destination leaderboard name.
@param keys [Array] Leaderboards to be merged with the current leaderboard.
@param options [Hash] Options for intersecting the leaderboards. |
def _arg(self, line):
'''singularity doesn't have support for ARG, so instead will issue
a warning to the console for the user to export the variable
with SINGULARITY prefixed at build.
Parameters
==========
line: the line from the recipe file to parse fo... | singularity doesn't have support for ARG, so instead will issue
a warning to the console for the user to export the variable
with SINGULARITY prefixed at build.
Parameters
==========
line: the line from the recipe file to parse for ARG |
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_list httpd
salt... | List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_list httpd
salt '*' lowpkg.file_list httpd postfix
salt... |
def insertRnaQuantificationSet(self, rnaQuantificationSet):
"""
Inserts a the specified rnaQuantificationSet into this repository.
"""
try:
models.Rnaquantificationset.create(
id=rnaQuantificationSet.getId(),
datasetid=rnaQuantificationSet.getP... | Inserts a the specified rnaQuantificationSet into this repository. |
async def main() -> None:
"""Create the aiohttp session and run the example."""
logging.basicConfig(level=logging.INFO)
async with ClientSession() as websession:
try:
client = Client(websession)
await client.profile.login('<EMAIL>', '<PASSWORD>')
_LOGGER.info('A... | Create the aiohttp session and run the example. |
def embedding_density(
adata: AnnData,
basis: str,
*,
groupby: Optional[str] = None,
key_added: Optional[str] = None,
components: Union[str, Sequence[str]] = None
):
"""Calculate the density of cells in an embedding (per condition)
Gaussian kernel density estimation is used to calculate... | Calculate the density of cells in an embedding (per condition)
Gaussian kernel density estimation is used to calculate the density of
cells in an embedded space. This can be performed per category over a
categorical cell annotation. The cell density can be plotted using the
`sc.pl.embedding_density()`... |
def build_docs(location="doc-source", target=None, library="icetea_lib"):
"""
Build documentation for Icetea. Start by autogenerating module documentation
and finish by building html.
:param location: Documentation source
:param target: Documentation target path
:param library: Library location... | Build documentation for Icetea. Start by autogenerating module documentation
and finish by building html.
:param location: Documentation source
:param target: Documentation target path
:param library: Library location for autodoc.
:return: -1 if something fails. 0 if successfull. |
def _gerritCmd(self, *args):
'''Construct a command as a list of strings suitable for
:func:`subprocess.call`.
'''
if self.gerrit_identity_file is not None:
options = ['-i', self.gerrit_identity_file]
else:
options = []
return ['ssh'] + options + [... | Construct a command as a list of strings suitable for
:func:`subprocess.call`. |
def analyze_bash_vars(job_input_file, job_homedir):
'''
This function examines the input file, and calculates variables to
instantiate in the shell environment. It is called right before starting the
execution of an app in a worker.
For each input key, we want to have
$var
$var_filename
... | This function examines the input file, and calculates variables to
instantiate in the shell environment. It is called right before starting the
execution of an app in a worker.
For each input key, we want to have
$var
$var_filename
$var_prefix
remove last dot (+gz), and/or remove pattern... |
def _http_put(self, url, data, **kwargs):
"""
Performs the HTTP PUT request.
"""
kwargs.update({'data': json.dumps(data)})
return self._http_request('put', url, kwargs) | Performs the HTTP PUT request. |
def set_imap(self, imap, callback=True):
"""
Set the intensity map used by this RGBMapper.
`imap` specifies an IntensityMap object. If `callback` is True, then
any callbacks associated with this change will be invoked.
"""
self.imap = imap
self.calc_imap()
... | Set the intensity map used by this RGBMapper.
`imap` specifies an IntensityMap object. If `callback` is True, then
any callbacks associated with this change will be invoked. |
def subset(self, service=None):
"""Subset the dataset.
Open the remote dataset and get a client for talking to ``service``.
Parameters
----------
service : str, optional
The name of the service for subsetting the dataset. Defaults to 'NetcdfSubset'
or 'N... | Subset the dataset.
Open the remote dataset and get a client for talking to ``service``.
Parameters
----------
service : str, optional
The name of the service for subsetting the dataset. Defaults to 'NetcdfSubset'
or 'NetcdfServer', in that order, depending on t... |
def get_config_parameter_boolean(config: ConfigParser,
section: str,
param: str,
default: bool) -> bool:
"""
Get Boolean parameter from ``configparser`` ``.INI`` file.
Args:
config: :class:`ConfigPars... | Get Boolean parameter from ``configparser`` ``.INI`` file.
Args:
config: :class:`ConfigParser` object
section: section name within config file
param: name of parameter within section
default: default value
Returns:
parameter value, or default |
def search(self, query, nid=None):
"""Search for posts with ``query``
:type nid: str
:param nid: This is the ID of the network to get the feed
from. This is optional and only to override the existing
`network_id` entered when created the class
:type query: str
... | Search for posts with ``query``
:type nid: str
:param nid: This is the ID of the network to get the feed
from. This is optional and only to override the existing
`network_id` entered when created the class
:type query: str
:param query: The search query; should ... |
def get_secret(
end_state: NettingChannelEndState,
secrethash: SecretHash,
) -> Optional[Secret]:
"""Returns `secret` if the `secrethash` is for a lock with a known secret."""
partial_unlock_proof = end_state.secrethashes_to_unlockedlocks.get(secrethash)
if partial_unlock_proof is None:
... | Returns `secret` if the `secrethash` is for a lock with a known secret. |
def setRequest(self, endPointReference, action):
'''Call For Request
'''
self._action = action
self.header_pyobjs = None
pyobjs = []
namespaceURI = self.wsAddressURI
addressTo = self._addressTo
messageID = self._messageID = "uuid:%s" %time.time()
... | Call For Request |
def get_logger(name):
"""Return logger with null handle
"""
log = logging.getLogger(name)
if not log.handlers:
log.addHandler(NullHandler())
return log | Return logger with null handle |
def date_struct_nn(year, month, day, tz="UTC"):
"""
Assemble a date object but if day or month is none set them to 1
to make it easier to deal with partial dates
"""
if not day:
day = 1
if not month:
month = 1
return date_struct(year, month, day, tz) | Assemble a date object but if day or month is none set them to 1
to make it easier to deal with partial dates |
def command(execute=None): # noqa: E501
"""Execute a Command
Execute a command # noqa: E501
:param execute: The data needed to execute this command
:type execute: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
execute = Execute.from_dict(connexion.request.get_jso... | Execute a Command
Execute a command # noqa: E501
:param execute: The data needed to execute this command
:type execute: dict | bytes
:rtype: Response |
def _init_valid_functions(action_dimensions):
"""Initialize ValidFunctions and set up the callbacks."""
sizes = {
"screen": tuple(int(i) for i in action_dimensions.screen),
"screen2": tuple(int(i) for i in action_dimensions.screen),
"minimap": tuple(int(i) for i in action_dimensions.minimap),
}
... | Initialize ValidFunctions and set up the callbacks. |
def _get_offset(text, visible_width, unicode_aware=True):
"""
Find the character offset within some text for a given visible offset (taking into account the
fact that some character glyphs are double width).
:param text: The text to analyze
:param visible_width: The required location within that te... | Find the character offset within some text for a given visible offset (taking into account the
fact that some character glyphs are double width).
:param text: The text to analyze
:param visible_width: The required location within that text (as seen on screen).
:return: The offset within text (as a char... |
def get_file_type(filename):
""" Returns I/O object to use for file.
Parameters
----------
filename : str
Name of file.
Returns
-------
file_type : {InferenceFile, InferenceTXTFile}
The type of inference file object to use.
"""
txt_extensions = [".txt", ".dat", ".cs... | Returns I/O object to use for file.
Parameters
----------
filename : str
Name of file.
Returns
-------
file_type : {InferenceFile, InferenceTXTFile}
The type of inference file object to use. |
def _format_explain(self):
""" Format the results of an EXPLAIN """
lines = []
for (command, kwargs) in self._call_list:
lines.append(command + " " + pformat(kwargs))
return "\n".join(lines) | Format the results of an EXPLAIN |
def convert_graph(self, graph_file, input_format, output_formats,
email=None, use_threads=False, callback=None):
"""
Convert a graph from one GraphFormat to another.
Arguments:
graph_file (str): Filename of the file to convert
input_format (str): A ... | Convert a graph from one GraphFormat to another.
Arguments:
graph_file (str): Filename of the file to convert
input_format (str): A grute.GraphFormats
output_formats (str[]): A grute.GraphFormats
email (str: self.email)*: The email to notify
use_threa... |
async def _request(self, *, http_verb, api_url, req_args):
"""Submit the HTTP request with the running session or a new session.
Returns:
A dictionary of the response data.
"""
if self.session and not self.session.closed:
async with self.session.request(http_verb,... | Submit the HTTP request with the running session or a new session.
Returns:
A dictionary of the response data. |
def new(expr, *args, **kwargs):
"""
Template an object.
::
>>> class MyObject:
... def __init__(self, arg1, arg2, *var_args, foo=None, bar=None, **kwargs):
... self.arg1 = arg1
... self.arg2 = arg2
... self.var_args = var_args
...... | Template an object.
::
>>> class MyObject:
... def __init__(self, arg1, arg2, *var_args, foo=None, bar=None, **kwargs):
... self.arg1 = arg1
... self.arg2 = arg2
... self.var_args = var_args
... self.foo = foo
... ... |
def import_log_funcs():
"""Import the common log functions from the global logger to the module."""
global g_logger
curr_mod = sys.modules[__name__]
for func_name in _logging_funcs:
func = getattr(g_logger, func_name)
setattr(curr_mod, func_name, func) | Import the common log functions from the global logger to the module. |
def add_dimension(self, dimension, dim_pos, dim_val, vdim=False, **kwargs):
"""Adds a dimension and its values to the object
Requires the dimension name or object, the desired position in
the key dimensions and a key value scalar or sequence of the
same length as the existing keys.
... | Adds a dimension and its values to the object
Requires the dimension name or object, the desired position in
the key dimensions and a key value scalar or sequence of the
same length as the existing keys.
Args:
dimension: Dimension or dimension spec to add
dim_po... |
def _aggregation_op(cls,
op: Callable[[tf.Tensor, Optional[Sequence[int]]], tf.Tensor],
x: 'TensorFluent',
vars_list: List[str]) -> 'TensorFluent':
'''Returns a TensorFluent for the aggregation `op` applied to fluent `x`.
Args:
op: The aggregation operati... | Returns a TensorFluent for the aggregation `op` applied to fluent `x`.
Args:
op: The aggregation operation.
x: The input fluent.
vars_list: The list of variables to be aggregated over.
Returns:
A TensorFluent wrapping the aggregation operator's output. |
def error_value_processor(value, error):
"""
If an error is a percentage, we convert to a float, then
calculate the percentage of the supplied value.
:param value: base value, e.g. 10
:param error: e.g. 20.0%
:return: the absolute error, e.g. 12 for the above case.
"""
if isinstance(err... | If an error is a percentage, we convert to a float, then
calculate the percentage of the supplied value.
:param value: base value, e.g. 10
:param error: e.g. 20.0%
:return: the absolute error, e.g. 12 for the above case. |
def build(self, lv2_uri):
"""
Returns a new :class:`.Lv2Effect` by the valid lv2_uri
:param string lv2_uri:
:return Lv2Effect: Effect created
"""
try:
plugin = self._plugins[lv2_uri]
except KeyError:
raise Lv2EffectBuilderError(
... | Returns a new :class:`.Lv2Effect` by the valid lv2_uri
:param string lv2_uri:
:return Lv2Effect: Effect created |
def __response_message_descriptor(self, message_type, method_id):
"""Describes the response.
Args:
message_type: messages.Message class, The message to describe.
method_id: string, Unique method identifier (e.g. 'myapi.items.method')
Returns:
Dictionary describing the response.
"""
... | Describes the response.
Args:
message_type: messages.Message class, The message to describe.
method_id: string, Unique method identifier (e.g. 'myapi.items.method')
Returns:
Dictionary describing the response. |
def _info_long(self) -> Optional[str]:
"""Extract journey information."""
try:
return str(
html.unescape(self.journey.InfoTextList.InfoText.get("textL")).replace(
"<br />", "\n"
)
)
except AttributeError:
ret... | Extract journey information. |
def Case(self, caseVal, *statements):
"c-like case of switch statement"
assert self.parentStm is None
caseVal = toHVal(caseVal, self.switchOn._dtype)
assert isinstance(caseVal, Value), caseVal
assert caseVal._isFullVld(), "Cmp with invalid value"
assert caseVal not in se... | c-like case of switch statement |
def remove_node(self, node, stop=False):
"""Removes a node from the cluster.
By default, it doesn't also stop the node, just remove from
the known hosts of this cluster.
:param node: node to remove
:type node: :py:class:`Node`
:param stop: Stop the node
:type s... | Removes a node from the cluster.
By default, it doesn't also stop the node, just remove from
the known hosts of this cluster.
:param node: node to remove
:type node: :py:class:`Node`
:param stop: Stop the node
:type stop: bool |
def roll(self, speed, heading, state=1):
"""
speed can have value between 0x00 and 0xFF
heading can have value between 0 and 359
"""
return self.write(request.Roll(self.seq, speed, heading, state )) | speed can have value between 0x00 and 0xFF
heading can have value between 0 and 359 |
def blockSelectionSignals( self, state ):
"""
Sets the state for the seleciton finished signal. When it \
is set to True, it will emit the signal. This is used \
internally to control selection signal propogation, so \
should not really be called unless you know why you are \
... | Sets the state for the seleciton finished signal. When it \
is set to True, it will emit the signal. This is used \
internally to control selection signal propogation, so \
should not really be called unless you know why you are \
calling it.
:param s... |
def _parseSCDOCDC(self, src):
"""[S|CDO|CDC]*"""
while 1:
src = src.lstrip()
if src.startswith('<!--'):
src = src[4:]
elif src.startswith('-->'):
src = src[3:]
else:
break
return src | [S|CDO|CDC]* |
def storage(self, *, resource=None):
""" Get an instance to handle file storage (OneDrive / Sharepoint)
for the specified account resource
:param str resource: Custom resource to be used in this drive object
(Defaults to parent main_resource)
:return: a representation of OneDri... | Get an instance to handle file storage (OneDrive / Sharepoint)
for the specified account resource
:param str resource: Custom resource to be used in this drive object
(Defaults to parent main_resource)
:return: a representation of OneDrive File Storage
:rtype: Storage
:... |
def by_value(self, value, default=None):
"""
Returns the key for the given value
"""
try:
return [k for k, v in self.items() if v == value][0]
except IndexError:
if default is not None:
return default
raise ValueError('%s' % val... | Returns the key for the given value |
def do_cd(self, line):
"""cd DIRECTORY
Changes the current directory. ~ expansion is supported, and cd -
goes to the previous directory.
"""
args = self.line_to_args(line)
if len(args) == 0:
dirname = '~'
else:
if args[0] == '-':
... | cd DIRECTORY
Changes the current directory. ~ expansion is supported, and cd -
goes to the previous directory. |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Suite(key)
if key not in Suite._member_map_:
extend_enum(Suite, key, default)
return Suite[key] | Backport support for original codes. |
def exec_command(cmd, in_data='', chdir=None, shell=None, emulate_tty=False):
"""
Run a command in a subprocess, emulating the argument handling behaviour of
SSH.
:param bytes cmd:
String command line, passed to user's shell.
:param bytes in_data:
Optional standard input for the com... | Run a command in a subprocess, emulating the argument handling behaviour of
SSH.
:param bytes cmd:
String command line, passed to user's shell.
:param bytes in_data:
Optional standard input for the command.
:return:
(return code, stdout bytes, stderr bytes) |
def do_set_log_level(self, arg):
"""Set the log level.
Usage:
set_log_level i|v
Parameters:
log_level: i - info | v - verbose
"""
if arg in ['i', 'v']:
_LOGGING.info('Setting log level to %s', arg)
if arg == 'i':
_... | Set the log level.
Usage:
set_log_level i|v
Parameters:
log_level: i - info | v - verbose |
def load(self, verbose=False):
"""
Load the list of songs.
Note that this only loads a list of songs that this artist was the main
artist of. If they were only featured in the song, that song won't be
listed here. There is a list on the artist page for that, I just
hav... | Load the list of songs.
Note that this only loads a list of songs that this artist was the main
artist of. If they were only featured in the song, that song won't be
listed here. There is a list on the artist page for that, I just
haven't added any parsing code for that, since I don't... |
def register_comet_callback(self, *args, **kwargs):
"""Registers a single Comet callback function
(see :ref:`comet-plugin`).
Refer to :func:`sijax.plugin.comet.register_comet_callback`
for more details - its signature differs slightly.
This method's signature is the same, excep... | Registers a single Comet callback function
(see :ref:`comet-plugin`).
Refer to :func:`sijax.plugin.comet.register_comet_callback`
for more details - its signature differs slightly.
This method's signature is the same, except that the first
argument that :func:`sijax.plugin.come... |
def in_project_directory() -> bool:
"""
Returns whether or not the current working directory is a Cauldron project
directory, which contains a cauldron.json file.
"""
current_directory = os.path.realpath(os.curdir)
project_path = os.path.join(current_directory, 'cauldron.json')
return os.pat... | Returns whether or not the current working directory is a Cauldron project
directory, which contains a cauldron.json file. |
def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs):
"""
{_gate_plot_doc}
"""
for gate in self.gates:
gate.plot(flip=flip, ax_channels=ax_channels, ax=ax, *args, **kwargs) | {_gate_plot_doc} |
def _lazy_load_get_model():
"""Lazy loading of get_model.
get_model loads django.conf.settings, which may fail if
the settings haven't been configured yet.
"""
if django is None:
def _get_model(app, model):
raise import_failure
else:
from django import apps as django... | Lazy loading of get_model.
get_model loads django.conf.settings, which may fail if
the settings haven't been configured yet. |
def get_new_selection_attr_state(self, selection, attr_key):
"""Toggles new attr selection state and returns it
Parameters
----------
selection: Selection object
\tSelection for which attr toggle shall be returned
attr_key: Hashable
\tAttribute key
"""
... | Toggles new attr selection state and returns it
Parameters
----------
selection: Selection object
\tSelection for which attr toggle shall be returned
attr_key: Hashable
\tAttribute key |
def update(self, cur_value, mesg=None):
"""Update progressbar with current value of process
Parameters
----------
cur_value : number
Current value of process. Should be <= max_value (but this is not
enforced). The percent of the progressbar will be computed as
... | Update progressbar with current value of process
Parameters
----------
cur_value : number
Current value of process. Should be <= max_value (but this is not
enforced). The percent of the progressbar will be computed as
(cur_value / max_value) * 100
m... |
def predict(self, X):
"""Predict count for samples in X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array, shape = [n_samples,]
Predicted count for each sample
"""
X_ = self._check_array(... | Predict count for samples in X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array, shape = [n_samples,]
Predicted count for each sample |
def late():
"""Used by functions in package.py that are evaluated lazily.
The term 'late' refers to the fact these package attributes are evaluated
late, ie when the attribute is queried for the first time.
If you want to implement a package.py attribute as a function, you MUST use
this decorator ... | Used by functions in package.py that are evaluated lazily.
The term 'late' refers to the fact these package attributes are evaluated
late, ie when the attribute is queried for the first time.
If you want to implement a package.py attribute as a function, you MUST use
this decorator - otherwise it is u... |
def filter_human_only(stmts_in, **kwargs):
"""Filter out statements that are grounded, but not to a human gene.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to filter.
save : Optional[str]
The name of a pickle file to save the results (stmts... | Filter out statements that are grounded, but not to a human gene.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to filter.
save : Optional[str]
The name of a pickle file to save the results (stmts_out) into.
remove_bound: Optional[bool]
... |
def prior_from_config(cp, prior_section='prior'):
"""Loads a prior distribution from the given config file.
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
The config file to read.
sections : list of str, optional
The sections to retrieve the prior from. If ``None`` (... | Loads a prior distribution from the given config file.
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
The config file to read.
sections : list of str, optional
The sections to retrieve the prior from. If ``None`` (the default),
will look in sections starting with... |
def kill(self, sig):
'''Invoke the stop on the event loop method.'''
if self.is_alive() and self._loop:
self._loop.call_soon_threadsafe(self._loop.stop) | Invoke the stop on the event loop method. |
def chrome_getdata_view(request):
"""Get the data of the last notification sent to the current user.
This is needed because Chrome, as of version 44, doesn't support
sending a data payload to a notification. Thus, information on what
the notification is actually for must be manually fetched.
"""
... | Get the data of the last notification sent to the current user.
This is needed because Chrome, as of version 44, doesn't support
sending a data payload to a notification. Thus, information on what
the notification is actually for must be manually fetched. |
def remove_reactions(self, reactions, remove_orphans=False):
"""Remove reactions from the model.
The change is reverted upon exit when using the model as a context.
Parameters
----------
reactions : list
A list with reactions (`cobra.Reaction`), or their id's, to re... | Remove reactions from the model.
The change is reverted upon exit when using the model as a context.
Parameters
----------
reactions : list
A list with reactions (`cobra.Reaction`), or their id's, to remove
remove_orphans : bool
Remove orphaned genes an... |
def _configure_send(self, request, **kwargs):
# type: (ClientRequest, Any) -> Dict[str, str]
"""Configure the kwargs to use with requests.
See "send" for kwargs details.
:param ClientRequest request: The request object to be sent.
:returns: The requests.Session.request kwargs
... | Configure the kwargs to use with requests.
See "send" for kwargs details.
:param ClientRequest request: The request object to be sent.
:returns: The requests.Session.request kwargs
:rtype: dict[str,str] |
def pivot(self, index, **kwargs):
"""
Pivots a dataframe
"""
try:
df = self._pivot(index, **kwargs)
return pd.pivot_table(self.df, index=kwargs["index"], **kwargs)
"""if df is None:
self.err("Can not pivot table")
retur... | Pivots a dataframe |
def run_updater_in_background(self):
""" Starts a thread that runs the updater in the background. """
thread = threading.Thread(target=self.updater_loop())
thread.daemon = True
thread.start() | Starts a thread that runs the updater in the background. |
def parameter_to_field(self, name):
"""
Promotes a parameter to a field by creating a new array of same
size as the other existing fields, filling it with the current
value of the parameter, and then removing that parameter.
"""
if name not in self._parameters:
... | Promotes a parameter to a field by creating a new array of same
size as the other existing fields, filling it with the current
value of the parameter, and then removing that parameter. |
def _related(self, concept):
"""
Returns related concepts for a concept.
"""
return concept.hypernyms() + \
concept.hyponyms() + \
concept.member_meronyms() + \
concept.substance_meronyms() + \
concept.part_meronyms() + \
... | Returns related concepts for a concept. |
def write_entity(self, entity):
"""
Write a single entity to a line in the output file
"""
db, db_object_id = self._split_prefix(entity)
taxon = normalize_taxon(entity["taxon"]["id"])
vals = [
db,
db_object_id,
entity.get('label'),
... | Write a single entity to a line in the output file |
def user_present(name,
password,
email,
tenant=None,
enabled=True,
roles=None,
profile=None,
password_reset=True,
project=None,
**connection_args):
'''
Ensure ... | Ensure that the keystone user is present with the specified properties.
name
The name of the user to manage
password
The password to use for this user.
.. note::
If the user already exists and a different password was set for
the user than the one specified he... |
def add_header_part(self):
"""Return (header_part, rId) pair for newly-created header part."""
header_part = HeaderPart.new(self.package)
rId = self.relate_to(header_part, RT.HEADER)
return header_part, rId | Return (header_part, rId) pair for newly-created header part. |
def volshow(
data,
lighting=False,
data_min=None,
data_max=None,
max_shape=256,
tf=None,
stereo=False,
ambient_coefficient=0.5,
diffuse_coefficient=0.8,
specular_coefficient=0.5,
specular_exponent=5,
downscale=1,
level=[0.1, 0.5, 0.9],
opacity=[0.01, 0.05, 0.1],
... | Visualize a 3d array using volume rendering.
Currently only 1 volume can be rendered.
:param data: 3d numpy array
:param origin: origin of the volume data, this is to match meshes which have a different origin
:param domain_size: domain size is the size of the volume
:param bool lighting: use lig... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.