code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def make_data(self, message):
"""
make data string from message according to transport_content_type
Returns:
str: message data
"""
if not isinstance(message, Message):
return message
return message.export(self.transport_content_type) | make data string from message according to transport_content_type
Returns:
str: message data |
def iyang(imgIn, krnl, imgSeg, Cnt, itr=5):
'''partial volume correction using iterative Yang method
imgIn: input image which is blurred due to the PSF of the scanner
krnl: shift invariant kernel of the PSF
imgSeg: segmentation into regions starting with 0 (e.g., background) and then next integer number... | partial volume correction using iterative Yang method
imgIn: input image which is blurred due to the PSF of the scanner
krnl: shift invariant kernel of the PSF
imgSeg: segmentation into regions starting with 0 (e.g., background) and then next integer numbers
itr: number of iteration (default 5) |
def convert_references_json(ref_content, soup=None):
"Check for references that will not pass schema validation, fix or convert them to unknown"
# Convert reference to unkonwn if still missing important values
if (
(ref_content.get("type") == "other")
or
(ref_content.get("type") == ... | Check for references that will not pass schema validation, fix or convert them to unknown |
def post(self, request, bot_id, format=None):
"""
Add a new state
---
serializer: StateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
"""
return super(S... | Add a new state
---
serializer: StateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request |
def _cleanup_pods(namespace, labels):
""" Remove all pods with these labels in this namespace """
api = kubernetes.client.CoreV1Api()
pods = api.list_namespaced_pod(namespace, label_selector=format_labels(labels))
for pod in pods.items:
try:
api.delete_namespaced_pod(pod.metadata.nam... | Remove all pods with these labels in this namespace |
def update_node_attributes(self, attributes_flags=int(Qt.ItemIsSelectable | Qt.ItemIsEnabled)):
"""
Updates the Node attributes.
:param attributes_flags: Attributes flags.
:type attributes_flags: int
:return: Method success.
:rtype: bool
"""
self.traced.... | Updates the Node attributes.
:param attributes_flags: Attributes flags.
:type attributes_flags: int
:return: Method success.
:rtype: bool |
def run(self):
""" Solves a state estimation problem.
"""
case = self.case
baseMVA = case.base_mva
buses = self.case.connected_buses
branches = case.online_branches
generators = case.online_generators
meas = self.measurements
# Update indices.
... | Solves a state estimation problem. |
def check_error(self, response, status, err_cd):
" Check an error in the response."
if 'status' not in response:
return False
if response['status'] != status:
return False
if 'msgs' not in response:
return False
if not isinstance(response['... | Check an error in the response. |
def link(url, text='', classes='', target='', get="", **kwargs):
'''
Output a link tag.
'''
if not (url.startswith('http') or url.startswith('/')):
# Handle additional reverse args.
urlargs = {}
for arg, val in kwargs.items():
if arg[:4] == "url_":
u... | Output a link tag. |
def newline(self):
"""
Advances the cursor position ot the left hand side, and to the next
line. If the cursor is on the lowest line, the displayed contents are
scrolled, causing the top line to be lost.
"""
self.carriage_return()
if self._cy + (2 * self._ch) >= ... | Advances the cursor position ot the left hand side, and to the next
line. If the cursor is on the lowest line, the displayed contents are
scrolled, causing the top line to be lost. |
def add_secondary_ip(self, ip_address, interface=1):
"""Adds an IP address as a secondary IP address
:param ip_address: String IP address to add as a secondary IP
:param interface: Integer associated to the interface/device number
:return: None
:raises: AWSAPIError, EC2UtilError... | Adds an IP address as a secondary IP address
:param ip_address: String IP address to add as a secondary IP
:param interface: Integer associated to the interface/device number
:return: None
:raises: AWSAPIError, EC2UtilError |
def _systemd_notify_once():
"""Send notification once to Systemd that service is ready.
Systemd sets NOTIFY_SOCKET environment variable with the name of the
socket listening for notifications from services.
This method removes the NOTIFY_SOCKET environment variable to ensure
not... | Send notification once to Systemd that service is ready.
Systemd sets NOTIFY_SOCKET environment variable with the name of the
socket listening for notifications from services.
This method removes the NOTIFY_SOCKET environment variable to ensure
notification is sent only once. |
def gateways_info():
"""Returns gateways data.
"""
data = netifaces.gateways()
results = {'default': {}}
with suppress(KeyError):
results['ipv4'] = data[netifaces.AF_INET]
results['default']['ipv4'] = data['default'][netifaces.AF_INET]
with suppress(KeyError):
results['i... | Returns gateways data. |
def _set_visible(self, visibility, grid_index=None):
"""Sets the visibility property of all axes."""
if grid_index is None:
for ax in self.flat_grid:
ax.set_visible(visibility)
else:
if grid_index < 0 or grid_index >= len(self.grids):
rais... | Sets the visibility property of all axes. |
def _has_y(self, kwargs):
'''Returns True if y is explicitly defined in kwargs'''
return (('y' in kwargs) or (self._element_y in kwargs) or
(self._type == 3 and self._element_1my in kwargs)) | Returns True if y is explicitly defined in kwargs |
def save_image(image, filename=None):
"""
Saves a Docker image from the remote to a local files. For performance reasons, uses the Docker command line client
on the host, generates a gzip-tarball and downloads that.
:param image: Image name or id.
:type image: unicode
:param filename: File name... | Saves a Docker image from the remote to a local files. For performance reasons, uses the Docker command line client
on the host, generates a gzip-tarball and downloads that.
:param image: Image name or id.
:type image: unicode
:param filename: File name to store the local file. If not provided, will us... |
def body(quantity=2, separator='\n\n', wrap_start='', wrap_end='',
html=False, sentences_quantity=3, as_list=False):
"""Return a random email text."""
return lorem_ipsum.paragraphs(quantity=quantity, separator=separator,
wrap_start=wrap_start, wrap_end=wrap_end,
... | Return a random email text. |
def select_many_with_index(
self,
collection_selector=IndexedElement,
result_selector=lambda source_element,
collection_element: collection_element):
'''Projects each element of a sequence to an intermediate new sequence,
incorporati... | Projects each element of a sequence to an intermediate new sequence,
incorporating the index of the element, flattens the resulting sequence
into one sequence and optionally transforms the flattened sequence
using a selector function.
Note: This method uses deferred execution.
... |
def tag_labels(self):
"""Tag named entity labels in the ``words`` layer."""
if not self.is_tagged(ANALYSIS):
self.tag_analysis()
if self.__ner_tagger is None:
self.__ner_tagger = load_default_ner_tagger()
self.__ner_tagger.tag_document(self)
return self | Tag named entity labels in the ``words`` layer. |
def stats_set_value(self, key, value=1):
"""Set the specified key/value in the per-message measurements
.. versionadded:: 3.13.0
.. note:: If this method is called when there is not a message being
processed, a message will be logged at the ``warning`` level to
indicate... | Set the specified key/value in the per-message measurements
.. versionadded:: 3.13.0
.. note:: If this method is called when there is not a message being
processed, a message will be logged at the ``warning`` level to
indicate the value is being dropped. To suppress these warni... |
def save_to_file(self,
file_path,
labels=None,
predict_proba=True,
show_predicted_value=True,
**kwargs):
"""Saves html explanation to file. .
Params:
file_path: file to save explanations... | Saves html explanation to file. .
Params:
file_path: file to save explanations to
See as_html() for additional parameters. |
def prepare_transaction(*, operation='CREATE', signers=None,
recipients=None, asset=None, metadata=None,
inputs=None):
"""Prepares a transaction payload, ready to be fulfilled. Depending on
the value of ``operation``, simply dispatches to either
:func:`~.prepa... | Prepares a transaction payload, ready to be fulfilled. Depending on
the value of ``operation``, simply dispatches to either
:func:`~.prepare_create_transaction` or
:func:`~.prepare_transfer_transaction`.
Args:
operation (str): The operation to perform. Must be ``'CREATE'``
or ``'TRA... |
def read_line(self, line):
"""Read a new line"""
if self.ignore:
return
for i, char in enumerate(line):
if char not in ['"', "'"]:
continue
# Is the char escaped?
if line[i - 1:i] == '\\':
continue
if s... | Read a new line |
def translate_wp_comment(self, e):
"""
<wp:comment>
<wp:comment_id>1234</wp:comment_id>
<wp:comment_author><![CDATA[John Doe]]></wp:comment_author>
<wp:comment_author_email><![CDATA[info@adsasd.com]]></wp:comment_author_email>
<wp:comment_author_url>http://myhomepage.com/</wp:c... | <wp:comment>
<wp:comment_id>1234</wp:comment_id>
<wp:comment_author><![CDATA[John Doe]]></wp:comment_author>
<wp:comment_author_email><![CDATA[info@adsasd.com]]></wp:comment_author_email>
<wp:comment_author_url>http://myhomepage.com/</wp:comment_author_url>
<wp:comment_author_IP><![CD... |
def charts_slug_get(self, slug, **kwargs):
"""
Chart
A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysis on Questions instead. Charts are derived data; Pollster ... | Chart
A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysis on Questions instead. Charts are derived data; Pollster editors publish them and change them as editorial priorities ch... |
def match(cls, event):
"""Match a given cwe event as cloudtrail with an api call
That has its information filled out.
"""
if 'detail' not in event:
return False
if 'eventName' not in event['detail']:
return False
k = event['detail']['eventName']
... | Match a given cwe event as cloudtrail with an api call
That has its information filled out. |
def is_rfc822(self) -> bool:
"""True if the content-type of the message is ``message/rfc822``."""
ct_hdr = self.header.parsed.content_type
if ct_hdr is None:
return False
else:
return ct_hdr.content_type == 'message/rfc822' | True if the content-type of the message is ``message/rfc822``. |
def register_layouts(layouts, app, url="/api/props/", brand="Pyxley"):
""" register UILayout with the flask app
create a function that will send props for each UILayout
Args:
layouts (dict): dict of UILayout objects by name
app (object): flask app
url (string): ... | register UILayout with the flask app
create a function that will send props for each UILayout
Args:
layouts (dict): dict of UILayout objects by name
app (object): flask app
url (string): address of props; default is /api/props/ |
def register_preset(cls, name, preset):
"""
Register a preset instance with the class of the hub it corresponds to. This allows individual plugin objects to
automatically register themselves with a preset by using a classmethod of their own with only the name of the
preset to register wi... | Register a preset instance with the class of the hub it corresponds to. This allows individual plugin objects to
automatically register themselves with a preset by using a classmethod of their own with only the name of the
preset to register with. |
def get_thread_info(self, enforce_re=True, latest_date=None):
"""Return a json list with information about threads in the group.
:param enforce_re=True: Whether to require titles to match
regexp in self.topic_re.
:param latest_date=None: Opti... | Return a json list with information about threads in the group.
:param enforce_re=True: Whether to require titles to match
regexp in self.topic_re.
:param latest_date=None: Optional datetime.datetime for latest
... |
def _logpdf(self, **kwargs):
"""Returns the log of the pdf at the given values. The keyword
arguments must contain all of parameters in self's params. Unrecognized
arguments are ignored.
"""
for p in self._params:
if p not in kwargs.keys():
raise Value... | Returns the log of the pdf at the given values. The keyword
arguments must contain all of parameters in self's params. Unrecognized
arguments are ignored. |
def dict_factory(self, cursor, row):
""" Sqlite callback accepting the cursor and the original row as a tuple.
Simple return of JSON safe types.
Args:
cursor (sqlite cursor): Original cursory
row (sqlite row tuple): Original row.
Returns:
dict: mod... | Sqlite callback accepting the cursor and the original row as a tuple.
Simple return of JSON safe types.
Args:
cursor (sqlite cursor): Original cursory
row (sqlite row tuple): Original row.
Returns:
dict: modified row. |
def linestrings_intersect(line1, line2):
"""
To valid whether linestrings from geojson are intersected with each other.
reference: http://www.kevlindev.com/gui/math/intersection/Intersection.js
Keyword arguments:
line1 -- first line geojson object
line2 -- second line geojson object
if(lin... | To valid whether linestrings from geojson are intersected with each other.
reference: http://www.kevlindev.com/gui/math/intersection/Intersection.js
Keyword arguments:
line1 -- first line geojson object
line2 -- second line geojson object
if(line1 intersects with other) return intersect point arra... |
def spawn_missing_classes(self, context=None):
"""
Creates the appropriate python user relation classes from tables in the schema and places them
in the context.
:param context: alternative context to place the missing classes into, e.g. locals()
"""
if context is None:
... | Creates the appropriate python user relation classes from tables in the schema and places them
in the context.
:param context: alternative context to place the missing classes into, e.g. locals() |
def dict_2_mat(data, fill = True):
"""
Creates a NumPy array from a dictionary with only integers as keys and
NumPy arrays as values. Dimension 0 of the resulting array is formed from
data.keys(). Missing values in keys can be filled up with np.nan (default)
or ignored.
Parameters
---------... | Creates a NumPy array from a dictionary with only integers as keys and
NumPy arrays as values. Dimension 0 of the resulting array is formed from
data.keys(). Missing values in keys can be filled up with np.nan (default)
or ignored.
Parameters
----------
data : dict
a dictionary with int... |
def parse_version(package):
"""
Parse versions
"""
init_file = f'{PACKAGE_ROOT}/{package}/__init__.py'
with open(init_file, 'r', encoding='utf-8') as f:
for line in f.readlines():
if '__version__' in line:
return line.split('=')[1].strip()[1:-1]
return '' | Parse versions |
def multigrad_dict(fun):
"Takes gradients wrt all arguments simultaneously,"
"returns a dict mapping 'argname' to 'gradval'"
import funcsigs
sig = funcsigs.signature(fun)
def select(preds, lst):
idx = lambda item: next(
(i for i, pred in enumerate(preds) if pred(item)), len(pre... | Takes gradients wrt all arguments simultaneously, |
def isprintable(string):
"""Return if all characters in string are printable.
>>> isprintable('abc')
True
>>> isprintable(b'\01')
False
"""
string = string.strip()
if not string:
return True
if sys.version_info[0] == 3:
try:
return string.isprintable()
... | Return if all characters in string are printable.
>>> isprintable('abc')
True
>>> isprintable(b'\01')
False |
def nlp(self, inputString, sourceTime=None, version=None):
"""Utilizes parse() after making judgements about what datetime
information belongs together.
It makes logical groupings based on proximity and returns a parsed
datetime for each matched grouping of datetime text, along with
... | Utilizes parse() after making judgements about what datetime
information belongs together.
It makes logical groupings based on proximity and returns a parsed
datetime for each matched grouping of datetime text, along with
location info within the given inputString.
@type input... |
def wifi_status(self):
"""Get the wifi status."""
return self._info_json.get(CONST.STATUS, {}).get(CONST.WIFI_LINK) | Get the wifi status. |
def get_usedby_and_readonly(self, id):
"""
Gets the build plans details os teh selected plan script as per the selected attributes.
Args:
id: ID of the Plan Script.
Returns:
array of build plans
"""
uri = self.URI + "/" + id + "/usedby/readonly"
... | Gets the build plans details os teh selected plan script as per the selected attributes.
Args:
id: ID of the Plan Script.
Returns:
array of build plans |
def update_body(app, pagename, templatename, context, doctree):
"""
Add Read the Docs content to Sphinx body content.
This is the most reliable way to inject our content into the page.
"""
STATIC_URL = context.get('STATIC_URL', DEFAULT_STATIC_URL)
online_builders = [
'readthedocs', 're... | Add Read the Docs content to Sphinx body content.
This is the most reliable way to inject our content into the page. |
async def get_state(self):
"""Get the latest state change of QTM. If the :func:`~qtm.connect` on_event
callback was set the callback will be called as well.
:rtype: A :class:`qtm.QRTEvent`
"""
await self._protocol.send_command("getstate", callback=False)
return await sel... | Get the latest state change of QTM. If the :func:`~qtm.connect` on_event
callback was set the callback will be called as well.
:rtype: A :class:`qtm.QRTEvent` |
def get_userinfo(self, access_token, id_token, payload):
"""Return user details dictionary. The id_token and payload are not used in
the default implementation, but may be used when overriding this method"""
user_response = requests.get(
self.OIDC_OP_USER_ENDPOINT,
heade... | Return user details dictionary. The id_token and payload are not used in
the default implementation, but may be used when overriding this method |
def status_message(self):
"""Detailed message about whether the dependency is installed.
:rtype: str
"""
if self.is_available:
return "INSTALLED {0!s}"
elif self.why and self.package:
return "MISSING {0!s:<20}needed for {0.why}, part of the {0.package} ... | Detailed message about whether the dependency is installed.
:rtype: str |
def P(self):
"""Diffusion operator (cached)
Return or calculate the diffusion operator
Returns
-------
P : array-like, shape=[n_samples, n_samples]
diffusion operator defined as a row-stochastic form
of the kernel matrix
"""
try:
... | Diffusion operator (cached)
Return or calculate the diffusion operator
Returns
-------
P : array-like, shape=[n_samples, n_samples]
diffusion operator defined as a row-stochastic form
of the kernel matrix |
def _setup_aggregation(self, aggregator=None):
""" Wrap `self.index` method with ESAggregator.
This makes `self.index` to first try to run aggregation and only
on fail original method is run. Method is wrapped only if it is
defined and `elasticsearch.enable_aggregations` setting is true... | Wrap `self.index` method with ESAggregator.
This makes `self.index` to first try to run aggregation and only
on fail original method is run. Method is wrapped only if it is
defined and `elasticsearch.enable_aggregations` setting is true. |
def load(robot, container_name, slot, label=None, share=False):
"""
Examples
--------
>>> from opentrons import containers
>>> containers.load('96-flat', '1')
<Deck>/<Slot 1>/<Container 96-flat>
>>> containers.load('96-flat', '4', 'plate')
<Deck>/<Slot 4>/<Container plate>
>>> contai... | Examples
--------
>>> from opentrons import containers
>>> containers.load('96-flat', '1')
<Deck>/<Slot 1>/<Container 96-flat>
>>> containers.load('96-flat', '4', 'plate')
<Deck>/<Slot 4>/<Container plate>
>>> containers.load('non-existent-type', '4') # doctest: +ELLIPSIS
Exception: Cont... |
def put_method(restApiId=None, resourceId=None, httpMethod=None, authorizationType=None, authorizerId=None, apiKeyRequired=None, operationName=None, requestParameters=None, requestModels=None, requestValidatorId=None):
"""
Add a method to an existing Resource resource.
See also: AWS API Documentation
... | Add a method to an existing Resource resource.
See also: AWS API Documentation
:example: response = client.put_method(
restApiId='string',
resourceId='string',
httpMethod='string',
authorizationType='string',
authorizerId='string',
apiKeyRequired=True|F... |
def url(self):
"""The url on jupyter nbviewer for this notebook or None if unknown"""
if self._url is not None:
url = self._url
else:
url = getattr(self.nb.metadata, 'url', None)
if url is not None:
return nbviewer_link(url) | The url on jupyter nbviewer for this notebook or None if unknown |
def convert_ages_to_calendar_year(self, er_ages_rec):
"""
convert all age units to calendar year
Parameters
----------
er_ages_rec : Dict type object containing preferbly at least keys
'age', 'age_unit', and either 'age_range_high', 'age_range_low'
or 'ag... | convert all age units to calendar year
Parameters
----------
er_ages_rec : Dict type object containing preferbly at least keys
'age', 'age_unit', and either 'age_range_high', 'age_range_low'
or 'age_sigma'
Returns
-------
er_ages_rec : Same dict ... |
def query(self):
""" The mongo query object which would be executed if this Query
object were used """
if self._rawquery==True:
return self.__query
return flatten(self.__query) | The mongo query object which would be executed if this Query
object were used |
def _create_raw_data(self):
"""
Gathers the different sections ids and creates a string as first
cookie data.
:return: A dictionary like:
{'analyses':'all','analysisrequest':'all','worksheets':'all'}
"""
result = {}
for section in self.get_sections():... | Gathers the different sections ids and creates a string as first
cookie data.
:return: A dictionary like:
{'analyses':'all','analysisrequest':'all','worksheets':'all'} |
def start(self):
"""Start the message sending loop."""
if self._send_greenlet is None:
self._send_greenlet = gevent.spawn(self._send_loop) | Start the message sending loop. |
def strip_unreferenced_labels(asm_lines):
"""Strip all labels, which are never referenced."""
asm_stripped = []
for line in asm_lines:
if re.match(r'^\S+:', line):
# Found label
label = line[0:line.find(':')]
# Search for references to current label
if... | Strip all labels, which are never referenced. |
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
return getattr(value, arg)
elif hasattr(value, 'has_key') and value.has_key(arg):
return value[arg]
elif numeric_test.match(str(arg)) and len(value) > int(arg):... | Gets an attribute of an object dynamically from a string name |
def main():
"""
simple user-interface
"""
print("\t\tCalculator\n\n")
while True:
user_input = input("expression or exit: ")
if user_input == "exit":
break
try:
print("The result is {0}".format(evaluate(user_input)))
except Excep... | simple user-interface |
def pad_equal_whitespace(string, pad=None):
"""Given a multiline string, add whitespaces to every line
so that every line has the same length."""
if pad is None: pad = max(map(len, string.split('\n'))) + 1
return '\n'.join(('{0: <%i}' % pad).format(line) for line in string.split('\n')) | Given a multiline string, add whitespaces to every line
so that every line has the same length. |
def _rts_smoother_update_step(k, p_m , p_P, p_m_pred, p_P_pred, p_m_prev_step,
p_P_prev_step, p_dynamic_callables):
"""
Rauch–Tung–Striebel(RTS) update step
Input:
-----------------------------
k: int
Iteration No. Starts at 0. Tot... | Rauch–Tung–Striebel(RTS) update step
Input:
-----------------------------
k: int
Iteration No. Starts at 0. Total number of iterations equal to the
number of measurements.
p_m: matrix of size (state_dim, time_series_no)
Filter mean on step k
... |
def rename_tokens(docgraph_with_old_names, docgraph_with_new_names, verbose=False):
"""
Renames the tokens of a graph (``docgraph_with_old_names``) in-place,
using the token names of another document graph
(``docgraph_with_new_names``). Also updates the ``.tokens`` list of the old
graph.
This w... | Renames the tokens of a graph (``docgraph_with_old_names``) in-place,
using the token names of another document graph
(``docgraph_with_new_names``). Also updates the ``.tokens`` list of the old
graph.
This will only work, iff both graphs have the same tokenization. |
def left_complement(clr):
"""
Returns the left half of the split complement.
A list is returned with the same darker and softer colors
as in the complementary list, but using the hue of the
left split complement instead of the complement itself.
"""
left = split_complementary(clr)[1]
co... | Returns the left half of the split complement.
A list is returned with the same darker and softer colors
as in the complementary list, but using the hue of the
left split complement instead of the complement itself. |
def create_git_release(self, tag, name, message, draft=False, prerelease=False, target_commitish=github.GithubObject.NotSet):
"""
:calls: `POST /repos/:owner/:repo/releases <http://developer.github.com/v3/repos/releases>`_
:param tag: string
:param name: string
:param message: st... | :calls: `POST /repos/:owner/:repo/releases <http://developer.github.com/v3/repos/releases>`_
:param tag: string
:param name: string
:param message: string
:param draft: bool
:param prerelease: bool
:param target_commitish: string or :class:`github.Branch.Branch` or :class... |
def get_rendered_toctree(builder, docname, prune=False, collapse=True):
"""Build the toctree relative to the named document,
with the given parameters, and then return the rendered
HTML fragment.
"""
fulltoc = build_full_toctree(builder,
docname,
... | Build the toctree relative to the named document,
with the given parameters, and then return the rendered
HTML fragment. |
def tail(collection, filter=None, projection=None, limit=0, timeout=None, aggregate=False):
"""A generator which will block and yield entries as they are added to a capped collection.
Only use this on capped collections; behaviour is undefined against non-tailable cursors. Accepts a timeout as an
integer or floati... | A generator which will block and yield entries as they are added to a capped collection.
Only use this on capped collections; behaviour is undefined against non-tailable cursors. Accepts a timeout as an
integer or floating point number of seconds, indicating how long to wait for a result. Correct operation requires... |
def latex_defs_to_katex_macros(defs):
r'''Converts LaTeX \def statements to KaTeX macros.
This is a helper function that can be used in conf.py to translate your
already specified LaTeX definitions.
https://github.com/Khan/KaTeX#rendering-options, e.g.
`\def \e #1{\mathrm{e}^{#1}}` => `"\\e:" "\\m... | r'''Converts LaTeX \def statements to KaTeX macros.
This is a helper function that can be used in conf.py to translate your
already specified LaTeX definitions.
https://github.com/Khan/KaTeX#rendering-options, e.g.
`\def \e #1{\mathrm{e}^{#1}}` => `"\\e:" "\\mathrm{e}^{#1}"`'
Example
-------
... |
def validate_swagger_schema(schema_dir, resource_listing):
"""Validate the structure of Swagger schemas against the spec.
**Valid only for Swagger v1.2 spec**
Note: It is possible that resource_listing is not present in
the schema_dir. The path is passed in the call so that ssv
can fetch the api-d... | Validate the structure of Swagger schemas against the spec.
**Valid only for Swagger v1.2 spec**
Note: It is possible that resource_listing is not present in
the schema_dir. The path is passed in the call so that ssv
can fetch the api-declaration files from the path.
:param resource_listing: Swag... |
def results(self, trial_ids):
"""
Accepts a sequence of trial ids and returns a pandas dataframe
with the schema
trial_id, iteration?, *metric_schema_union
where iteration is an optional column that specifies the iteration
when a user logged a metric, if the user suppli... | Accepts a sequence of trial ids and returns a pandas dataframe
with the schema
trial_id, iteration?, *metric_schema_union
where iteration is an optional column that specifies the iteration
when a user logged a metric, if the user supplied one. The iteration
column is added if a... |
def calledTwice(cls, spy): #pylint: disable=invalid-name
"""
Checking the inspector is called twice
Args: SinonSpy
"""
cls.__is_spy(spy)
if not (spy.calledTwice):
raise cls.failException(cls.message) | Checking the inspector is called twice
Args: SinonSpy |
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io) | Format input to textual table. |
def append(self, parent, content):
"""
Append the specified L{content} to the I{parent}.
@param parent: The parent node to append to.
@type parent: L{Element}
@param content: The content to append.
@type content: L{Object}
"""
log.debug('appending parent:\... | Append the specified L{content} to the I{parent}.
@param parent: The parent node to append to.
@type parent: L{Element}
@param content: The content to append.
@type content: L{Object} |
def validate_response(self):
"""Raises an exception if there was an error. Otherwise, do nothing.
Clients should handle these errors, since these require custom handling
to properly resolve.
"""
if self.is_success():
return
# Handle the error if we have any ... | Raises an exception if there was an error. Otherwise, do nothing.
Clients should handle these errors, since these require custom handling
to properly resolve. |
def promote_transaction(
self,
transaction,
depth=3,
min_weight_magnitude=None,
):
# type: (TransactionHash, int, Optional[int]) -> dict
"""
Promotes a transaction by adding spam on top of it.
:return:
Dict with the followi... | Promotes a transaction by adding spam on top of it.
:return:
Dict with the following structure::
{
'bundle': Bundle,
The newly-published bundle.
} |
def parse_default_property_value(property_name, property_type_id, default_value_string):
"""Parse the default value string into its proper form given the property type ID.
Args:
property_name: string, the name of the property whose default value is being parsed.
Used primarily to... | Parse the default value string into its proper form given the property type ID.
Args:
property_name: string, the name of the property whose default value is being parsed.
Used primarily to construct meaningful error messages, should the default
value prove inva... |
def keys_values(data, *keys):
"""Get an entry as a list from a dict. Provide a fallback key."""
values = []
if is_mapping(data):
for key in keys:
if key in data:
values.extend(ensure_list(data[key]))
return values | Get an entry as a list from a dict. Provide a fallback key. |
def eval_callx(self, exp):
"dispatch for CallX"
# below: this isn't contains(exp,consumes_row) -- it's just checking the current expression
return (self.eval_agg_call if consumes_rows(exp) else self.eval_nonagg_call)(exp) | dispatch for CallX |
def Satisfy_Constraints(U, B, BtBinv):
"""U is the prolongator update. Project out components of U such that U*B = 0.
Parameters
----------
U : bsr_matrix
m x n sparse bsr matrix
Update to the prolongator
B : array
n x k array of the coarse grid near nullspace vectors
B... | U is the prolongator update. Project out components of U such that U*B = 0.
Parameters
----------
U : bsr_matrix
m x n sparse bsr matrix
Update to the prolongator
B : array
n x k array of the coarse grid near nullspace vectors
BtBinv : array
Local inv(B_i.H*B_i) mat... |
def publish_active_scene(self, scene_id):
"""publish changed active scene"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_active(self.sequence_number, scene_id))
return self.sequence_number | publish changed active scene |
def stream_time(self, significant_digits=3):
"""
:param significant_digits: int of the number of significant digits
in the return
:return: float of the time in seconds of how long the
data took to stream
"""
try:
return round(
... | :param significant_digits: int of the number of significant digits
in the return
:return: float of the time in seconds of how long the
data took to stream |
def date_time_this_century(
self,
before_now=True,
after_now=False,
tzinfo=None):
"""
Gets a DateTime object for the current century.
:param before_now: include days in current century before today
:param after_now: include days in current... | Gets a DateTime object for the current century.
:param before_now: include days in current century before today
:param after_now: include days in current century after today
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('2012-04-04 11:02:02')
:r... |
def _to_DOM(self):
"""
Dumps object data to a fully traversable DOM representation of the
object.
:returns: a ``xml.etree.Element`` object
"""
root_node = ET.Element('station')
created_at_node = ET.SubElement(root_node, "created_at")
created_at_node.text... | Dumps object data to a fully traversable DOM representation of the
object.
:returns: a ``xml.etree.Element`` object |
def Search(pattern, s):
"""Searches the string for the pattern, caching the compiled regexp."""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].search(s) | Searches the string for the pattern, caching the compiled regexp. |
def GetValues(self):
"""Retrieves all values within the key.
Returns:
generator[WinRegistryValue]: Windows Registry value generator.
"""
if not self._registry_key and self._registry:
self._GetKeyFromRegistry()
if self._registry_key:
return self._registry_key.GetValues()
retu... | Retrieves all values within the key.
Returns:
generator[WinRegistryValue]: Windows Registry value generator. |
def numa_nodemask_to_set(mask):
"""
Convert NUMA nodemask to Python set.
"""
result = set()
for i in range(0, get_max_node() + 1):
if __nodemask_isset(mask, i):
result.add(i)
return result | Convert NUMA nodemask to Python set. |
def surfaceIntersection(actor1, actor2, tol=1e-06, lw=3):
"""Intersect 2 surfaces and return a line actor.
.. hint:: |surfIntersect.py|_
"""
bf = vtk.vtkIntersectionPolyDataFilter()
poly1 = actor1.GetMapper().GetInput()
poly2 = actor2.GetMapper().GetInput()
bf.SetInputData(0, poly1)
bf.... | Intersect 2 surfaces and return a line actor.
.. hint:: |surfIntersect.py|_ |
def resolve_push_to(push_to, default_url, default_namespace):
'''
Given a push-to value, return the registry and namespace.
:param push_to: string: User supplied --push-to value.
:param default_url: string: Container engine's default_index value (e.g. docker.io).
:return: tuple: registry_url, names... | Given a push-to value, return the registry and namespace.
:param push_to: string: User supplied --push-to value.
:param default_url: string: Container engine's default_index value (e.g. docker.io).
:return: tuple: registry_url, namespace |
def backward(self, diff_x, influences, activations, **kwargs):
"""
Backward pass through the network, including update.
Parameters
----------
diff_x : numpy array
A matrix containing the differences between the input and neurons.
influences : numpy array
... | Backward pass through the network, including update.
Parameters
----------
diff_x : numpy array
A matrix containing the differences between the input and neurons.
influences : numpy array
A matrix containing the influence each neuron has on each
other... |
def remove_editor(self, username, *args, **kwargs):
"""Remove an editor from this wiki page.
:param username: The name or Redditor object of the user to remove.
This method points to :meth:`add_editor` with _delete=True.
Additional parameters are are passed to :meth:`add_editor` and
... | Remove an editor from this wiki page.
:param username: The name or Redditor object of the user to remove.
This method points to :meth:`add_editor` with _delete=True.
Additional parameters are are passed to :meth:`add_editor` and
subsequently into :meth:`~praw.__init__.BaseReddit.reque... |
def from_hex(cls, value):
"""Initialize a new network from hexadecimal notation."""
if len(value) == 8:
return cls(int(value, 16))
elif len(value) == 32:
return cls(int(value, 16))
else:
raise ValueError('%r: invalid hexadecimal notation' % (value,)) | Initialize a new network from hexadecimal notation. |
def spawn_worker(params):
"""
This method has to be module level function
:type params: Params
"""
setup_logging(params)
log.info("Adding worker: idx=%s\tconcurrency=%s\tresults=%s", params.worker_index, params.concurrency,
params.report)
worker = Worker(params)
worker.star... | This method has to be module level function
:type params: Params |
def load_excel(self, filepath, **kwargs):
"""Set the main dataframe with the content of an Excel file
:param filepath: url of the csv file to load,
can be absolute if it starts with ``/``
or relative if it starts with ``./``
:type filepath: str
... | Set the main dataframe with the content of an Excel file
:param filepath: url of the csv file to load,
can be absolute if it starts with ``/``
or relative if it starts with ``./``
:type filepath: str
:param kwargs: keyword arguments to pass to
... |
def _formatter(self, x=None, y=None, z=None, s=None, label=None, **kwargs):
"""
Default formatter function, if no `formatter` kwarg is specified. Takes
information about the pick event as a series of kwargs and returns the
string to be displayed.
"""
def is_date(axis):
... | Default formatter function, if no `formatter` kwarg is specified. Takes
information about the pick event as a series of kwargs and returns the
string to be displayed. |
def expandRecs(G, RecCollect, nodeType, weighted):
"""Expand all the citations from _RecCollect_"""
for Rec in RecCollect:
fullCiteList = [makeID(c, nodeType) for c in Rec.createCitation(multiCite = True)]
if len(fullCiteList) > 1:
for i, citeID1 in enumerate(fullCiteList):
... | Expand all the citations from _RecCollect_ |
def get_asset_content(self, asset_content_id):
"""Gets the ``AssetContent`` specified by its ``Id``.
In plenary mode, the exact ``Id`` is found or a ``NotFound``
results. Otherwise, the returned ``AssetContent`` may have a different
``Id`` than requested, such as the case where a duplic... | Gets the ``AssetContent`` specified by its ``Id``.
In plenary mode, the exact ``Id`` is found or a ``NotFound``
results. Otherwise, the returned ``AssetContent`` may have a different
``Id`` than requested, such as the case where a duplicate ``Id``
was assigned to an ``AssetContent`` and... |
def handle(self, *args, **options):
"""
Iterates over all the CRON_CLASSES (or if passed in as a commandline argument)
and runs them.
"""
cron_classes = options['cron_classes']
if cron_classes:
cron_class_names = cron_classes
else:
cron_cla... | Iterates over all the CRON_CLASSES (or if passed in as a commandline argument)
and runs them. |
def list_path(root_dir):
"""List directory if exists.
:param dir: str
:return: list
"""
res = []
if os.path.isdir(root_dir):
for name in os.listdir(root_dir):
res.append(name)
return res | List directory if exists.
:param dir: str
:return: list |
def get_valences(self, structure):
"""
Returns a list of valences for the structure. This currently works only
for ordered structures only.
Args:
structure: Structure to analyze
Returns:
A list of valences for each site in the structure (for an ordered
... | Returns a list of valences for the structure. This currently works only
for ordered structures only.
Args:
structure: Structure to analyze
Returns:
A list of valences for each site in the structure (for an ordered
structure), e.g., [1, 1, -2] or a list of li... |
def _get_menu_meta_width(self, max_width, complete_state):
"""
Return the width of the meta column.
"""
if self._show_meta(complete_state):
return min(max_width, max(get_cwidth(c.display_meta)
for c in complete_state.current_completions) + 2)
el... | Return the width of the meta column. |
def _GetEarliestYearFromFileEntry(self):
"""Retrieves the year from the file entry date and time values.
This function uses the creation time if available otherwise the change
time (metadata last modification time) is used.
Returns:
int: year of the file entry or None.
"""
file_entry = s... | Retrieves the year from the file entry date and time values.
This function uses the creation time if available otherwise the change
time (metadata last modification time) is used.
Returns:
int: year of the file entry or None. |
def get_app_dir(app_name, roaming=True, force_posix=False):
r"""Returns the config folder for the application. The default behavior
is to return whatever is most appropriate for the operating system.
To give you an idea, for an app called ``"Foo Bar"``, something like
the following folders could be re... | r"""Returns the config folder for the application. The default behavior
is to return whatever is most appropriate for the operating system.
To give you an idea, for an app called ``"Foo Bar"``, something like
the following folders could be returned:
Mac OS X:
``~/Library/Application Support/Foo... |
def get_results(self, job_id):
"""Get results of a job
Args:
job_id (str): The ID of the job.
See: https://auth0.com/docs/api/management/v2#!/Jobs/get_results
"""
url = self._url('%s/results' % job_id)
return self.client.get(url) | Get results of a job
Args:
job_id (str): The ID of the job.
See: https://auth0.com/docs/api/management/v2#!/Jobs/get_results |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.