text stringlengths 81 112k |
|---|
Get the plain text of an email, searching by subject.
@Params
email_name - the subject to search for
@Returns
Plaintext content of the matched email
def fetch_plaintext_by_subject(self, email_name):
"""
Get the plain text of an email, searching by subject.
@Param... |
Get content of emails, sent to a specific email address.
@Params
email - the recipient email address to search for
timeout - seconds to try beore timing out
content_type - type of email string to return
@Returns
Content of the matched email in the given content type
def ... |
Get content of emails, sent to a specific email address.
@Params
email - the recipient email address to search for
timeout - seconds to try beore timing out
content_type - type of email string to return
@Returns
Content of the matched email in the given content type
def ... |
A search that keeps searching up until timeout for a
specific number of matches to a search. If timeout is not
specified we use the default. If count= is not specified we
will fail. Return values are the same as search(), except for count=0,
where we will return an empty list. Use this ... |
Checks an Email.Message object for the headers in email_headers.
Following are acceptable header names: ['Delivered-To',
'Received', 'Return-Path', 'Received-SPF',
'Authentication-Results', 'DKIM-Signature',
'DomainKey-Signature', 'From', 'To', 'Message-ID',
'Sub... |
Given a message number, return the Email.Message object.
@Params
msgnum - message number to find
@Returns
Email.Message object for the given message number
def fetch_message(self, msgnum):
"""
Given a message number, return the Email.Message object.
@Params
... |
Given an Email.Message object, gets the content-type payload
as specified by @content_type. This is the actual body of the
email.
@Params
msg - Email.Message object to get message content for
content_type - Type of content to get from the email
@Return
String cont... |
Checks email inbox every 15 seconds that match the criteria
up until timeout.
Search criteria should be keyword args eg
TO="selenium@gmail.com". See __imap_search docstring for list
of valid criteria. If content_type is not defined, will return
a list of msg numbers.
O... |
Clean whitespace from html
@Params
html - html source to remove whitespace from
@Returns
String html without whitespace
def remove_whitespace(self, html):
"""
Clean whitespace from html
@Params
html - html source to remove whitespace from
@Returns... |
Replace htmlentities with unicode characters
@Params
html - html source to replace entities in
@Returns
String html with entities replaced
def replace_entities(self, html):
"""
Replace htmlentities with unicode characters
@Params
html - html source to rep... |
The DOM (Document Object Model) has a property called "readyState".
When the value of this becomes "complete", page resources are considered
fully loaded (although AJAX and other loads might still be happening).
This method will wait until document.readyState == "complete".
def wait_for_ready_state_complet... |
If "jQuery is not defined", use this method to activate it for use.
This happens because jQuery is not always defined on web sites.
def activate_jquery(driver):
""" If "jQuery is not defined", use this method to activate it for use.
This happens because jQuery is not always defined on web sites. ""... |
re.escape() works differently in Python 3.7.0 than earlier versions:
Python 3.6.5:
>>> import re
>>> re.escape('"')
'\\"'
Python 3.7.0:
>>> import re
>>> re.escape('"')
'"'
SeleniumBase needs quotes to be properly escaped for Javascript calls.
def escape_quotes_if_needed(string):... |
When executing a script that contains a jQuery command,
it's important that the jQuery library has been loaded first.
This method will load jQuery if it wasn't already loaded.
def safe_execute_script(driver, script):
""" When executing a script that contains a jQuery command,
it's important... |
A helper method to post a message on the screen with Messenger.
(Should only be called from post_message() in base_case.py)
def post_message(driver, message, msg_dur, style="info"):
""" A helper method to post a message on the screen with Messenger.
(Should only be called from post_message() in bas... |
DEPRECATED - Use re.escape() instead, which performs the intended action.
Use before throwing raw code such as 'div[tab="advanced"]' into jQuery.
Selectors with quotes inside of quotes would otherwise break jQuery.
If you just want to escape quotes, there's escape_quotes_if_needed().
This is similar to ... |
When testing_base is specified, but none of the log options to save are
specified (basic_test_info, screen_shots, page_source), then save them
all by default. Otherwise, save only selected ones from their plugins.
def __log_all_options_if_none_specified(self, test):
"""
When testing_bas... |
Since Skip, Blocked, and Deprecated are all technically errors, but not
error states, we want to make sure that they don't show up in
the nose output as errors.
def addError(self, test, err, capt=None):
"""
Since Skip, Blocked, and Deprecated are all technically errors, but not
... |
If the database plugin is not present, we have to handle capturing
"errors" that shouldn't be reported as such in base.
def handleError(self, test, err, capt=None):
"""
If the database plugin is not present, we have to handle capturing
"errors" that shouldn't be reported as such in base... |
Executes a db query, gets all the values, and closes the connection.
def query_fetch_all(self, query, values):
"""
Executes a db query, gets all the values, and closes the connection.
"""
self.cursor.execute(query, values)
retval = self.cursor.fetchall()
self.__close_db(... |
Executes a db query, gets the first value, and closes the connection.
def query_fetch_one(self, query, values):
"""
Executes a db query, gets the first value, and closes the connection.
"""
self.cursor.execute(query, values)
retval = self.cursor.fetchone()
self.__close_d... |
Executes a query to the test_db and closes the connection afterwards.
def execute_query(self, query, values):
"""
Executes a query to the test_db and closes the connection afterwards.
"""
retval = self.cursor.execute(query, values)
self.__close_db()
return retval |
Combines the domain base href with the html source.
This is needed for the page html to render correctly.
def get_html_source_with_base_href(driver, page_source):
''' Combines the domain base href with the html source.
This is needed for the page html to render correctly. '''
last_page = get_la... |
Handle Logging
def log_folder_setup(log_path, archive_logs=False):
""" Handle Logging """
if log_path.endswith("/"):
log_path = log_path[:-1]
if not os.path.exists(log_path):
try:
os.makedirs(log_path)
except Exception:
pass # Should only be reachable during... |
Downloads the Selenium Server JAR file from its
online location and stores it locally.
def download_selenium_server():
"""
Downloads the Selenium Server JAR file from its
online location and stores it locally.
"""
try:
local_file = open(JAR_FILE, 'wb')
remote_file = urlopen(SELE... |
At the start of the run, we want to record the test
execution information in the database.
def begin(self):
""" At the start of the run, we want to record the test
execution information in the database. """
exec_payload = ExecutionQueryPayload()
exec_payload.execution_st... |
At the end of the run, we want to
update the DB row with the execution time.
def finalize(self, result):
""" At the end of the run, we want to
update the DB row with the execution time. """
runtime = int(time.time() * 1000) - self.execution_start_time
self.testcase_manager.updat... |
After test completion, we want to record testcase run information.
def addSuccess(self, test, capt):
"""
After test completion, we want to record testcase run information.
"""
self.__insert_test_result(constants.State.PASS, test) |
After a test error, we want to record testcase run information.
def addError(self, test, err, capt=None):
"""
After a test error, we want to record testcase run information.
"""
self.__insert_test_result(constants.State.ERROR, test, err) |
After a test error, we want to record testcase run information.
"Error" also encompasses any states other than Pass or Fail, so we
check for those first.
def handleError(self, test, err, capt=None):
"""
After a test error, we want to record testcase run information.
"Error" also... |
After a test failure, we want to record testcase run information.
def addFailure(self, test, err, capt=None, tbinfo=None):
"""
After a test failure, we want to record testcase run information.
"""
self.__insert_test_result(constants.State.FAILURE, test, err) |
Implementation of https://stackoverflow.com/a/35293284 for
https://stackoverflow.com/questions/12848327/
(Run Selenium on a proxy server that requires authentication.)
def _add_chrome_proxy_extension(
chrome_options, proxy_string, proxy_user, proxy_pass):
""" Implementation of https://stack... |
Spins up a new web browser and returns the driver.
Can also be used to spin up additional browsers for the same test.
def get_local_driver(
browser_name, headless, proxy_string, proxy_auth,
proxy_user, proxy_pass, user_agent, disable_csp):
'''
Spins up a new web browser and returns the driv... |
Get the options.
def configure(self, options, conf):
""" Get the options. """
super(S3Logging, self).configure(options, conf)
self.options = options |
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.
def get_serializer(self, *args, **kwargs):
"""
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.
... |
Returns an active user that matches the payload's user id and email.
def authenticate_credentials(self, payload):
"""
Returns an active user that matches the payload's user id and email.
"""
User = get_user_model()
username = jwt_get_username_from_payload(payload)
if no... |
Scan a single row from an Excel file, and return the list of ranges
corresponding to each consecutive span of non-empty cells in this row.
If all cells are empty, return an empty list. Each "range" in the list
is a tuple of the form `(startcol, endcol)`.
For example, if the row is the following:
... |
This function takes a list of row-ranges (as returned by `_parse_row`)
ordered by rows, and produces a list of distinct rectangular ranges
within this grid.
Within this function we define a 2d-range as a rectangular set of cells
such that:
- there are no empty rows / columns within this rectangle... |
Within the `ranges` list find those 2d-ranges that overlap with `ranges[ja]`
and merge them into `ranges[ja]`. Finally, return the new index of the
ja-th range within the `ranges` list.
def _collapse_ranges(ranges, ja):
"""
Within the `ranges` list find those 2d-ranges that overlap with `ranges[ja]`
... |
This function attempts to locate the required link libraries, and returns
them as a list of absolute paths.
def find_linked_dynamic_libraries():
"""
This function attempts to locate the required link libraries, and returns
them as a list of absolute paths.
"""
with TaskContext("Find the require... |
Listen to user's keystrokes and return them to caller one at a time.
The produced values are instances of blessed.keyboard.Keystroke class.
If the user did not press anything with the last `refresh_rate` seconds
the generator will yield `None`, allowing the caller to perform any
updates... |
Return the slice tuple normalized for an ``n``-element object.
:param e: a slice object representing a selector
:param n: number of elements in a sequence to which ``e`` is applied
:returns: tuple ``(start, count, step)`` derived from ``e``.
def normalize_slice(e, n):
"""
Return the slice tuple no... |
Return the range tuple normalized for an ``n``-element object.
The semantics of a range is slightly different than that of a slice.
In particular, a range is similar to a list in meaning (and on Py2 it was
eagerly expanded into a list). Thus we do not allow the range to generate
indices that would be ... |
Import and return the requested module.
def load_module(module):
"""
Import and return the requested module.
"""
try:
m = importlib.import_module(module)
return m
except ModuleNotFoundError: # pragma: no cover
raise TImportError("Module `%s` is not installed. It is required... |
Convert given number of bytes into a human readable representation, i.e. add
prefix such as KB, MB, GB, etc. The `size` argument must be a non-negative
integer.
:param size: integer representing byte size of something
:return: string representation of the size, in human-readable form
def humanize_byte... |
Retrieve frame data within the current view window.
This method will adjust the view window if it goes out-of-bounds.
def _fetch_data(self):
"""
Retrieve frame data within the current view window.
This method will adjust the view window if it goes out-of-bounds.
"""
se... |
Return the list of all source/header files in `c/` directory.
The files will have pathnames relative to the current folder, for example
"c/csv/reader_utils.cc".
def get_files():
"""
Return the list of all source/header files in `c/` directory.
The files will have pathnames relative to the current... |
Find user includes (no system includes) requested from given source file.
All .h files will be given relative to the current folder, e.g.
["c/rowindex.h", "c/column.h"].
def find_includes(filename):
"""
Find user includes (no system includes) requested from given source file.
All .h files will be... |
Construct dictionary {header_file : set_of_included_files}.
This function operates on "real" set of includes, in the sense that it
parses each header file to check which files are included from there.
def build_headermap(headers):
"""
Construct dictionary {header_file : set_of_included_files}.
Th... |
Similar to build_headermap(), but builds a dictionary of includes from
the "source" files (i.e. ".c/.cc" files).
def build_sourcemap(sources):
"""
Similar to build_headermap(), but builds a dictionary of includes from
the "source" files (i.e. ".c/.cc" files).
"""
sourcemap = {}
for sfile in... |
Find all C/C++ source files in the `folder` directory.
def get_c_sources(folder, include_headers=False):
"""Find all C/C++ source files in the `folder` directory."""
allowed_extensions = [".c", ".C", ".cc", ".cpp", ".cxx", ".c++"]
if include_headers:
allowed_extensions += [".h", ".hpp"]
sources... |
Invoked from the C level, this function will return either the name of
the folder where the datatable is to be saved; or None, indicating that
the datatable should be read into RAM. This function may also raise an
exception if it determines that it cannot find a good strategy to
handle a... |
Save Frame in binary NFF/Jay format.
:param dest: destination where the Frame should be saved.
:param _strategy: one of "mmap", "write" or "auto"
def save_nff(self, dest, _strategy="auto"):
"""
Save Frame in binary NFF/Jay format.
:param dest: destination where the Frame should be saved.
:par... |
Send an event.
def event(
title,
text,
alert_type=None,
aggregation_key=None,
source_type_name=None,
date_happened=None,
priority=None,
tags=None,
hostname=None,
):
"""
Send an event.
""" |
Return all the projects for which the user is a sole owner
def user_projects(request):
""" Return all the projects for which the user is a sole owner """
projects_owned = (
request.db.query(Project.id)
.join(Role.project)
.filter(Role.role_name == "Owner", Role.user == request.user)
... |
Merge one or more revisions.
Takes one or more revisions or "heads" for all heads and merges them into
a single revision.
def merge(config, revisions, **kwargs):
"""
Merge one or more revisions.
Takes one or more revisions or "heads" for all heads and merges them into
a single revision.
"... |
Return a series of WHERE clauses against a given column that break it into
windows.
Result is an iterable of tuples, consisting of ((start, end), whereclause),
where (start, end) are the ids.
Requires a database that supports window functions, i.e. Postgresql,
SQL Server, Oracle.
Enhance this... |
Break a Query into windows on a given column.
def windowed_query(q, column, windowsize):
""""
Break a Query into windows on a given column.
"""
for whereclause in column_windows(q.session, column, windowsize):
for row in q.filter(whereclause).order_by(column):
yield row |
Filters given query with the below regex
and returns lists of quoted and unquoted strings
def filter_query(s):
"""
Filters given query with the below regex
and returns lists of quoted and unquoted strings
"""
matches = re.findall(r'(?:"([^"]*)")|([^"]*)', s)
result_quoted = [t[0].strip() fo... |
Returns a multi match query
def form_query(query_type, query):
"""
Returns a multi match query
"""
fields = [
field + "^" + str(SEARCH_BOOSTS[field]) if field in SEARCH_BOOSTS else field
for field in SEARCH_FIELDS
]
return Q("multi_match", fields=fields, query=query, type=query_... |
Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.... |
Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
def run_migrations_online():
"""
Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
co... |
Show current branch points.
def branches(config, **kwargs):
"""
Show current branch points.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
alembic.command.branches(alembic_config, **kwargs) |
Upgrade database.
def upgrade(config, revision, **kwargs):
"""
Upgrade database.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
alembic.command.upgrade(alembic_config, revision, **kwargs) |
Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
a different host and uses a safe scheme).
Always returns ``False`` on an empty url.
def is_safe_url(url, host=None):
"""
Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
a different host and uses a ... |
Sanitize any user-submitted data to ensure that it can be used in XML
def _clean_for_xml(data):
""" Sanitize any user-submitted data to ensure that it can be used in XML """
# If data is None or an empty string, don't bother
if data:
# This turns a string like "Hello…" into "Hello…"
... |
Submit metrics.
def submit_xmlrpc_metrics(method=None):
"""
Submit metrics.
"""
def decorator(f):
def wrapped(context, request):
metrics = request.find_service(IMetricsService, context=None)
metrics.increment("warehouse.xmlrpc.call", tags=[f"rpc_method:{method}"])
... |
Support multiple endpoints serving the same views by chaining calls to
xmlrpc_method
def xmlrpc_method(**kwargs):
"""
Support multiple endpoints serving the same views by chaining calls to
xmlrpc_method
"""
# Add some default arguments
kwargs.update(
require_csrf=False,
requ... |
Display the current revision for a database.
def current(config, **kwargs):
"""
Display the current revision for a database.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
alembic.command.current(alembic_config, **kwargs) |
Perform some basic checks to see whether the indicated file could be
a valid distribution file.
def _is_valid_dist_file(filename, filetype):
"""
Perform some basic checks to see whether the indicated file could be
a valid distribution file.
"""
# If our file is a zipfile, then ensure that it's... |
Check to see if file already exists, and if it's content matches.
A file is considered to exist if its filename *or* blake2 digest are
present in a file row in the database.
Returns:
- True: This file is a duplicate and all further processing should halt.
- False: This file exists, but it is not a ... |
Open up a Python shell with Warehouse preconfigured in it.
def shell(config, type_):
"""
Open up a Python shell with Warehouse preconfigured in it.
"""
# Imported here because we don't want to trigger an import from anything
# but warehouse.cli at the module scope.
from warehouse.db import Ses... |
This decorator is used to turn an e function into an email sending function!
The name parameter is the name of the email we're going to be sending (used to
locate the templates on the file system).
The allow_unverified kwarg flags whether we will send this email to an unverified
email or not. We gener... |
List changeset scripts in chronological order.
def history(config, revision_range, **kwargs):
"""
List changeset scripts in chronological order.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
alembic.command.history(alembic_... |
Recreate the Search Index.
def reindex(config):
"""
Recreate the Search Index.
"""
request = config.task(_reindex).get_request()
config.task(_reindex).run(request) |
Show current available heads.
def heads(config, **kwargs):
"""
Show current available heads.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
alembic.command.heads(alembic_config, **kwargs) |
Recreate the Search Index.
def reindex(self, request):
"""
Recreate the Search Index.
"""
r = redis.StrictRedis.from_url(request.registry.settings["celery.scheduler_url"])
try:
with SearchLock(r, timeout=30 * 60, blocking_timeout=30):
p = urllib.parse.urlparse(request.registry.s... |
API endpoint to retrieve a list of links to transaction
outputs.
Returns:
A :obj:`list` of :cls:`str` of links to outputs.
def get(self):
"""API endpoint to retrieve a list of links to transaction
outputs.
Returns:
A :obj:`list` of :cls:... |
Show the current configuration
def run_show_config(args):
"""Show the current configuration"""
# TODO Proposal: remove the "hidden" configuration. Only show config. If
# the system needs to be configured, then display information on how to
# configure the system.
config = copy.deepcopy(bigchaindb.c... |
Run a script to configure the current node.
def run_configure(args):
"""Run a script to configure the current node."""
config_path = args.config or bigchaindb.config_utils.CONFIG_DEFAULT_PATH
config_file_exists = False
# if the config path is `-` then it's stdout
if config_path != '-':
con... |
Initiates an election to add/update/remove a validator to an existing BigchainDB network
:param args: dict
args = {
'public_key': the public key of the proposed peer, (str)
'power': the proposed validator power for the new peer, (str)
'node_id': the node_id of the new peer (str)
... |
Approve an election
:param args: dict
args = {
'election_id': the election_id of the election (str)
'sk': the path to the private key of the signer (str)
}
:param bigchain: an instance of BigchainDB
:return: success log message or `False` in case of error
def run_election_a... |
Retrieves information about an election
:param args: dict
args = {
'election_id': the transaction_id for an election (str)
}
:param bigchain: an instance of BigchainDB
def run_election_show(args, bigchain):
"""Retrieves information about an election
:param args: dict
a... |
Drop the database
def run_drop(args):
"""Drop the database"""
dbname = bigchaindb.config['database']['name']
if not args.yes:
response = input_on_stderr('Do you want to drop `{}` database? [y/n]: '.format(dbname))
if response != 'y':
return
conn = backend.connect()
dbn... |
Start the processes to run the node
def run_start(args):
"""Start the processes to run the node"""
# Configure Logging
setup_logging()
logger.info('BigchainDB Version %s', bigchaindb.__version__)
run_recover(bigchaindb.lib.BigchainDB())
if not args.skip_initialize_database:
logger.in... |
Show the supported Tendermint version(s)
def run_tendermint_version(args):
"""Show the supported Tendermint version(s)"""
supported_tm_ver = {
'description': 'BigchainDB supports the following Tendermint version(s)',
'tendermint': __tm_supported_versions__,
}
print(json.dumps(supported_... |
Return all the assets that match the text search.
The results are sorted by text score.
For more information about the behavior of text search on MongoDB see
https://docs.mongodb.com/manual/reference/operator/query/text/#behavior
Args:
search (str): Text search string to query the text index
... |
Main function
def main():
""" Main function """
ctx = {}
def pretty_json(data):
return json.dumps(data, indent=2, sort_keys=True)
client = server.create_app().test_client()
host = 'example.com:9984'
# HTTP Index
res = client.get('/', environ_overrides={'HTTP_HOST': host})
r... |
Serialize a dict into a JSON formatted string.
This function enforces rules like the separator and order of keys.
This ensures that all dicts are serialized in the same way.
This is specially important for hashing data. We need to make sure that
everyone serializes their data in the sa... |
Validate value of `key` in `obj` using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
key (str): key to be validated in `obj`.
validation_fun (function): function used to validate the value
of `k... |
Validate all (nested) keys in `obj` by using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
validation_fun (function): function used to validate the value
of `key`.
Returns:
None: indica... |
Validate value for all (nested) occurrence of `key` in `obj`
using `validation_fun`.
Args:
obj (dict): dictionary object.
key (str): key whose value is to be validated.
validation_fun (function): function used to validate the value
of `key`.
Rais... |
Check if `key` contains ".", "$" or null characters.
https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names
Args:
obj_name (str): object name to use when raising exception
key (str): key to validated
Returns:
None: validation successfu... |
Return an instance of the Flask application.
Args:
debug (bool): a flag to activate the debug mode for the app
(default: False).
threads (int): number of threads to use
Return:
an instance of the Flask application.
def create_app(*, debug=False, threads=1, bigchaindb_factor... |
Wrap and return an application ready to be run.
Args:
settings (dict): a dictionary containing the settings, more info
here http://docs.gunicorn.org/en/latest/settings.html
Return:
an initialized instance of the application.
def create_server(settings, log_config=None, bigchaindb_... |
Function to configure log hadlers.
.. important::
Configuration, if needed, should be applied before invoking this
decorator, as starting the subscriber process for logging will
configure the root logger for the child process based on the
state of :obj:`bigchaindb.config` at the mo... |
Return a dict with all the information specific for the v1 of the
api.
def get_api_v1_info(api_prefix):
"""Return a dict with all the information specific for the v1 of the
api.
"""
websocket_root = base_ws_uri() + EVENTS_ENDPOINT
docs_url = [
'https://docs.bigchaindb.com/projects/serve... |
Decorator to be used by command line functions, such that the
configuration of bigchaindb is performed before the execution of
the command.
Args:
command: The command to decorate.
Returns:
The command wrapper function.
def configure_bigchaindb(command):
"""Decorator to be used by ... |
Output a string to stderr and wait for input.
Args:
prompt (str): the message to display.
default: the default value to return if the user
leaves the field empty
convert (callable): a callable to be used to convert
the value the user inserted. If None, the type of
... |
Utility function to execute a subcommand.
The function will look up in the ``scope``
if there is a function called ``run_<parser.args.command>``
and will run it using ``parser.args`` as first positional argument.
Args:
parser: an ArgumentParser instance.
argv: the list of command line ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.