Search is not available for this dataset
text stringlengths 75 104k |
|---|
def post_request(self, container, resource=None, params=None, accept=None):
"""Send a POST request."""
url = self.make_url(container, resource)
headers = self._make_headers(accept)
try:
rsp = requests.post(url, data=params, headers=headers,
ve... |
def delete_request(self, container, resource=None, query_items=None,
accept=None):
"""Send a DELETE request."""
url = self.make_url(container, resource)
headers = self._make_headers(accept)
if query_items and isinstance(query_items, (list, tuple, set)):
... |
def download_file(self, container, resource, save_path=None, accept=None,
query_items=None):
"""Download a file.
If a timeout defined, it is not a time limit on the entire download;
rather, an exception is raised if the server has not issued a response
for timeout ... |
def upload_file(self, container, src_file_path, dst_name=None, put=True,
content_type=None):
"""Upload a single file."""
if not os.path.exists(src_file_path):
raise RuntimeError('file not found: ' + src_file_path)
if not dst_name:
dst_name = os.path.ba... |
def upload_file_mp(self, container, src_file_path, dst_name=None,
content_type=None):
"""Upload a file using multi-part encoding."""
if not os.path.exists(src_file_path):
raise RuntimeError('file not found: ' + src_file_path)
if not dst_name:
dst_na... |
def upload_files(self, container, src_dst_map, content_type=None):
"""Upload multiple files."""
if not content_type:
content_type = "application/octet.stream"
url = self.make_url(container, None, None)
headers = self._base_headers
multi_files = []
try:
... |
def new_session(self, server=None, session_name=None, user_name=None,
existing_session=None):
"""Create a new session or attach to existing.
Normally, this function is called automatically, and gets its parameter
values from the environment. It is provided as a public funct... |
def _end_session(self, kill=None):
"""End the client session."""
if self._stc:
if kill is None:
kill = os.environ.get('STC_SESSION_TERMINATE_ON_DISCONNECT')
kill = _is_true(kill)
self._stc.end_session(kill)
self._stc = None |
def setup(app):
"""
This isn't used in Production,
but allows this module to be used as a standalone extension.
"""
app.add_directive('readthedocs-embed', EmbedDirective)
app.add_config_value('readthedocs_embed_project', '', 'html')
app.add_config_value('readthedocs_embed_version', '', 'htm... |
def finalize_media(app):
"""Point media files at our media server."""
if (app.builder.name == 'readthedocssinglehtmllocalmedia' or
app.builder.format != 'html' or
not hasattr(app.builder, 'script_files')):
return # Use local media for downloadable files
# Pull project data ... |
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... |
def generate_json_artifacts(app, pagename, templatename, context, doctree):
"""
Generate JSON artifacts for each page.
This way we can skip generating this in other build step.
"""
try:
# We need to get the output directory where the docs are built
# _build/json.
build_json ... |
def _copy_searchtools(self, renderer=None):
"""Copy and patch searchtools
This uses the included Sphinx version's searchtools, but patches it to
remove automatic initialization. This is a fork of
``sphinx.util.fileutil.copy_asset``
"""
log.info(bold('copying searchtools.... |
def stc_system_info(stc_addr):
"""Return dictionary of STC and API information.
If a session already exists, then use it to get STC information and avoid
taking the time to start a new session. A session is necessary to get
STC information.
"""
stc = stchttp.StcHttp(stc_addr)
sessions = s... |
def new_session(self, user_name=None, session_name=None,
kill_existing=False, analytics=None):
"""Create a new test session.
The test session is identified by the specified user_name and optional
session_name parameters. If a session name is not specified, then the
... |
def join_session(self, sid):
"""Attach to an existing session."""
self._rest.add_header('X-STC-API-Session', sid)
self._sid = sid
try:
status, data = self._rest.get_request('objects', 'system1',
['version', 'name'])
ex... |
def end_session(self, end_tcsession=True, sid=None):
"""End this test session.
A session can be ended in three ways, depending on the value of the
end_tcsession parameter:
- end_tcsession=None:
Stop using session locally, do not contact server.
- end_tcse... |
def session_info(self, session_id=None):
"""Get information on session.
If session_id is None, the default, then return information about this
session. If a session ID is given, then get information about that
session.
Arguments:
session_id -- Id of session to get info... |
def files(self):
"""Get list of files, for this session, on server."""
self._check_session()
status, data = self._rest.get_request('files')
return data |
def bll_version(self):
"""Get the BLL version this session is connected to.
Return:
Version string if session started. None if session not started.
"""
if not self.started():
return None
status, data = self._rest.get_request('objects', 'system1',
... |
def get(self, handle, *args):
"""Returns the value(s) of one or more object attributes.
If multiple arguments, this method returns a dictionary of argument
names mapped to the value returned by each argument.
If a single argument is given, then the response is a list of values
... |
def create(self, object_type, under=None, attributes=None, **kwattrs):
"""Create a new automation object.
Arguments:
object_type -- Type of object to create.
under -- Handle of the parent of the new object.
attributes -- Dictionary of attributes (name-value pairs).
... |
def createx(self, object_type, under=None, attributes=None, **kwattrs):
"""Create a new automation object.
Arguments:
object_type -- Type of object to create.
under -- Handle of the parent of the new object.
attributes -- Dictionary of attributes (name-value pairs).
... |
def delete(self, handle):
"""Delete the specified object.
Arguments:
handle -- Handle of object to delete.
"""
self._check_session()
self._rest.delete_request('objects', str(handle)) |
def perform(self, command, params=None, **kwargs):
"""Execute a command.
Arguments can be supplied either as a dictionary or as keyword
arguments. Examples:
stc.perform('LoadFromXml', {'filename':'config.xml'})
stc.perform('LoadFromXml', filename='config.xml')
... |
def config(self, handle, attributes=None, **kwattrs):
"""Sets or modifies one or more object attributes or relations.
Arguments can be supplied either as a dictionary or as keyword
arguments. Examples:
stc.config('port1', location='//10.1.2.3/1/1')
stc.config('port2', {... |
def chassis(self):
"""Get list of chassis known to test session."""
self._check_session()
status, data = self._rest.get_request('chassis')
return data |
def chassis_info(self, chassis):
"""Get information about the specified chassis."""
if not chassis or not isinstance(chassis, str):
raise RuntimeError('missing chassis address')
self._check_session()
status, data = self._rest.get_request('chassis', chassis)
return dat... |
def connections(self):
"""Get list of connections."""
self._check_session()
status, data = self._rest.get_request('connections')
return data |
def is_connected(self, chassis):
"""Get Boolean connected status of the specified chassis."""
self._check_session()
try:
status, data = self._rest.get_request('connections', chassis)
except resthttp.RestHttpError as e:
if int(e) == 404:
# 404 NOT F... |
def connect(self, chassis_list):
"""Establish connection to one or more chassis.
Arguments:
chassis_list -- List of chassis (IP addresses or DNS names)
Return:
List of chassis addresses.
"""
self._check_session()
if not isinstance(chassis_list, (list, t... |
def disconnect(self, chassis_list):
"""Remove connection with one or more chassis.
Arguments:
chassis_list -- List of chassis (IP addresses or DNS names)
"""
self._check_session()
if not isinstance(chassis_list, (list, tuple, set, dict, frozenset)):
chassis_... |
def help(self, subject=None, args=None):
"""Get help information about Automation API.
The following values can be specified for the subject:
None -- gets an overview of help.
'commands' -- gets a list of API functions
command name -- get info about the specified com... |
def log(self, level, msg):
"""Write a diagnostic message to a log file or to standard output.
Arguments:
level -- Severity level of entry. One of: INFO, WARN, ERROR, FATAL.
msg -- Message to write to log.
"""
self._check_session()
level = level.upper()
... |
def download(self, file_name, save_as=None):
"""Download the specified file from the server.
Arguments:
file_name -- Name of file resource to save.
save_as -- Optional path name to write file to. If not specified,
then file named by the last part of the resource ... |
def download_all(self, dst_dir=None):
"""Download all available files.
Arguments:
dst_dir -- Optional destination directory to write files to. If not
specified, then files are downloaded current directory.
Return:
Dictionary of {file_name: file_size, ..}... |
def upload(self, src_file_path, dst_file_name=None):
"""Upload the specified file to the server."""
self._check_session()
status, data = self._rest.upload_file(
'files', src_file_path, dst_file_name)
return data |
def wait_until_complete(self, timeout=None):
"""Wait until sequencer is finished.
This method blocks your application until the sequencer has completed
its operation. It returns once the sequencer has finished.
Arguments:
timeout -- Optional. Seconds to wait for sequencer to ... |
def ManagerMock(manager, *return_value):
"""
Set the results to two items:
>>> objects = ManagerMock(Post.objects, 'queryset', 'result')
>>> assert objects.filter() == objects.all()
Force an exception:
>>> objects = ManagerMock(Post.objects, Exception())
See QuerySetMock for more about h... |
def assert_chain_calls(self, *calls):
"""
Asserts that a chained method was called (parents in the chain do not
matter, nor are they tracked). Use with `mock.call`.
>>> obj.filter(foo='bar').select_related('baz')
>>> obj.assert_chain_calls(mock.call.filter(foo='bar'))
>... |
def mock_signal_receiver(signal, wraps=None, **kwargs):
"""
Temporarily attaches a receiver to the provided ``signal`` within the scope
of the context manager.
The mocked receiver is returned as the ``as`` target of the ``with``
statement.
To have the mocked receiver wrap a callable, pass the ... |
def QuerySetMock(model, *return_value):
"""
Get a SharedMock that returns self for most attributes and a new copy of
itself for any method that ordinarily generates QuerySets.
Set the results to two items:
>>> class Post(object): pass
>>> objects = QuerySetMock(Post, 'return', 'values')
>>... |
def read(self, *args, **kwargs):
'''Overridden read() method to call parse_flask_section() at the end'''
ret = configparser.SafeConfigParser.read(self, *args, **kwargs)
self.parse_flask_section()
return ret |
def readfp(self, *args, **kwargs):
'''Overridden readfp() method to call parse_flask_section() at the
end'''
ret = configparser.SafeConfigParser.readfp(self, *args, **kwargs)
self.parse_flask_section()
return ret |
def parse_flask_section(self):
'''Parse the [flask] section of your config and hand off the config
to the app in context.
Config vars should have the same name as their flask equivalent except
in all lower-case.'''
if self.has_section('flask'):
for item in self.items... |
def _load_item(self, key):
'''Load the specified item from the [flask] section. Type is
determined by the type of the equivalent value in app.default_config
or string if unknown.'''
key_u = key.upper()
default = current_app.default_config.get(key_u)
# One of the defaul... |
def _execute_migrations(self, current_version, destination_version):
"""
passed a version:
this version don't exists in the database and is younger than the last version -> do migrations up until this version
this version don't exists in the database and is older than the last ve... |
def csrf_token():
"""
Generate a token string from bytes arrays. The token in the session is user
specific.
"""
if "_csrf_token" not in session:
session["_csrf_token"] = os.urandom(128)
return hmac.new(app.secret_key, session["_csrf_token"],
digestmod=sha1).hexdigest() |
def check_csrf_token():
"""Checks that token is correct, aborting if not"""
if request.method in ("GET",): # not exhaustive list
return
token = request.form.get("csrf_token")
if token is None:
app.logger.warning("Expected CSRF Token: not present")
abort(400)
if not safe_str_c... |
def get_request(cls):
"""
Get the HTTPRequest object from thread storage or from a callee by searching
each frame in the call stack.
"""
request = cls.get_global('request')
if request:
return request
try:
stack = inspect.stack()
exc... |
def route(app_or_blueprint, rule, **options):
"""An alternative to :meth:`flask.Flask.route` or :meth:`flask.Blueprint.route` that
always adds the ``POST`` method to the allowed endpoint request methods.
You should use this for all your view functions that would need to use Sijax.
We're doing this bec... |
def _make_response(sijax_response):
"""Takes a Sijax response object and returns a
valid Flask response object."""
from types import GeneratorType
if isinstance(sijax_response, GeneratorType):
# Streaming response using a generator (non-JSON response).
# Upon returning a response, Flask... |
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... |
def register_comet_object(self, *args, **kwargs):
"""Registers all functions from the object as Comet functions
(see :ref:`comet-plugin`).
This makes mass registration of functions a lot easier.
Refer to :func:`sijax.plugin.comet.register_comet_object`
for more details -ts sign... |
def register_upload_callback(self, *args, **kwargs):
"""Registers an Upload function (see :ref:`upload-plugin`)
to handle a certain form.
Refer to :func:`sijax.plugin.upload.register_upload_callback`
for more details.
This method passes some additional arguments to your handler... |
def execute_callback(self, *args, **kwargs):
"""Executes a callback and returns the proper response.
Refer to :meth:`sijax.Sijax.execute_callback` for more details.
"""
response = self._sijax.execute_callback(*args, **kwargs)
return _make_response(response) |
def has_permission(self, request, extra_permission=None):
"""
Returns True if the given HttpRequest has permission to view
*at least one* page in the admin site.
"""
permission = request.user.is_active and request.user.is_staff
if extra_permission:
permission ... |
def as_view(self, view, cacheable=False, extra_permission=None):
"""
Wraps a view in authentication/caching logic
extra_permission can be used to require an extra permission for this view, such as a module permission
"""
def inner(request, *args, **kwargs):
if not se... |
def media(self, request, module, path):
"""
Serve static files below a given point in the directory structure.
"""
if module == 'nexus':
document_root = os.path.join(NEXUS_ROOT, 'media')
else:
document_root = self.get_module(module).media_root
pat... |
def login(self, request, form_class=None):
"Login form"
from django.contrib.auth import login as login_
from django.contrib.auth.forms import AuthenticationForm
if form_class is None:
form_class = AuthenticationForm
if request.POST:
form = form_class(req... |
def logout(self, request):
"Logs out user and redirects them to Nexus home"
from django.contrib.auth import logout
logout(request)
return HttpResponseRedirect(reverse('nexus:index', current_app=self.name)) |
def dashboard(self, request):
"Basic dashboard panel"
# TODO: these should be ajax
module_set = []
for namespace, module in self.get_modules():
home_url = module.get_home_url(request)
if hasattr(module, 'render_on_dashboard'):
# Show by default, u... |
def submit_row(context):
"""
Displays the row of buttons for delete and save.
"""
opts = context['opts']
change = context['change']
is_popup = context['is_popup']
save_as = context['save_as']
return {
'onclick_attrib': (opts.get_ordered_objects() and change
... |
def autodiscover(site=None):
"""
Auto-discover INSTALLED_APPS nexus.py modules and fail silently when
not present. This forces an import on them to register any api bits they
may want.
Specifying ``site`` will register all auto discovered modules with the new site.
"""
# Bail out if autodis... |
def handle_starttag(self, tagName, attributeList, isSelfClosing=False):
'''
Internal for parsing
'''
tagName = tagName.lower()
inTag = self._inTag
if isSelfClosing is False and tagName in IMPLICIT_SELF_CLOSING_TAGS:
isSelfClosing = True
newTag = ... |
def handle_endtag(self, tagName):
'''
Internal for parsing
'''
try:
foundIt = False
inTag = self._inTag
for i in range(len(inTag)):
if inTag[i].tagName == tagName:
foundIt = True
break
... |
def handle_data(self, data):
'''
Internal for parsing
'''
if data:
inTag = self._inTag
if len(inTag) > 0:
inTag[-1].appendText(data)
elif data.strip(): #and not self.getRoot():
# Must be text prior to or after root n... |
def handle_entityref(self, entity):
'''
Internal for parsing
'''
inTag = self._inTag
if len(inTag) > 0:
inTag[-1].appendText('&%s;' %(entity,))
else:
raise MultipleRootNodeException() |
def handle_charref(self, charRef):
'''
Internal for parsing
'''
inTag = self._inTag
if len(inTag) > 0:
inTag[-1].appendText('&#%s;' %(charRef,))
else:
raise MultipleRootNodeException() |
def handle_comment(self, comment):
'''
Internal for parsing
'''
inTag = self._inTag
if len(inTag) > 0:
inTag[-1].appendText('<!-- %s -->' %(comment,))
else:
raise MultipleRootNodeException() |
def getRootNodes(self):
'''
getRootNodes - Gets all objects at the "root" (first level; no parent). Use this if you may have multiple roots (not children of <html>)
Use this method to get objects, for example, in an AJAX request where <html> may not be your root.
Not... |
def getAllNodes(self):
'''
getAllNodes - Get every element
@return TagCollection<AdvancedTag>
'''
ret = TagCollection()
for rootNode in self.getRootNodes():
ret.append(rootNode)
ret += rootNode.getAllChildNodes()
return ret |
def getElementsByTagName(self, tagName, root='root'):
'''
getElementsByTagName - Searches and returns all elements with a specific tag name.
@param tagName <lowercase str> - A lowercase string of the tag name.
@param root <AdvancedTag/'root'> - Search... |
def getElementsByName(self, name, root='root'):
'''
getElementsByName - Searches and returns all elements with a specific name.
@param name <str> - A string of the name attribute
@param root <AdvancedTag/'root'> - Search starting at a specific node, if... |
def getElementById(self, _id, root='root'):
'''
getElementById - Searches and returns the first (should only be one) element with the given ID.
@param id <str> - A string of the id attribute.
@param root <AdvancedTag/'root'> - Search starting at a spec... |
def getElementsByClassName(self, className, root='root'):
'''
getElementsByClassName - Searches and returns all elements containing a given class name.
@param className <str> - A one-word class name
@param root <AdvancedTag/'root'> - Search starting at... |
def getElementsByAttr(self, attrName, attrValue, root='root'):
'''
getElementsByAttr - Searches the full tree for elements with a given attribute name and value combination. This is always a full scan.
@param attrName <lowercase str> - A lowercase attribute name
... |
def getElementsWithAttrValues(self, attrName, attrValues, root='root'):
'''
getElementsWithAttrValues - Returns elements with an attribute, named by #attrName contains one of the values in the list, #values
@param attrName <lowercase str> - A lowercase attribute name
@param ... |
def getElementsCustomFilter(self, filterFunc, root='root'):
'''
getElementsCustomFilter - Scan elements using a provided function
@param filterFunc <function>(node) - A function that takes an AdvancedTag as an argument, and returns True if some arbitrary criteria is met
@re... |
def getFirstElementCustomFilter(self, filterFunc, root='root'):
'''
getFirstElementCustomFilter - Scan elements using a provided function, stop and return the first match.
@see getElementsCustomFilter to match multiple elements
@param filterFunc <function>(node) - A fun... |
def contains(self, em):
'''
Checks if #em is found anywhere within this element tree
@param em <AdvancedTag> - Tag of interest
@return <bool> - If element #em is within this tree
'''
for rootNode in self.getRootNodes():
if rootNode.contains(em):
... |
def containsUid(self, uid):
'''
Check if #uid is found anywhere within this element tree
@param uid <uuid.UUID> - Uid
@return <bool> - If #uid is found within this tree
'''
for rootNode in self.getRootNodes():
if rootNode.containsUid(uid):
... |
def find(self, **kwargs):
'''
find - Perform a search of elements using attributes as keys and potential values as values
(i.e. parser.find(name='blah', tagname='span') will return all elements in this document
with the name "blah" of the tag type "span... |
def getHTML(self):
'''
getHTML - Get the full HTML as contained within this tree.
If parsed from a document, this will contain the original whitespacing.
@returns - <str> of html
@see getFormattedHTML
@see getMiniHTML
... |
def getFormattedHTML(self, indent=' '):
'''
getFormattedHTML - Get formatted and xhtml of this document, replacing the original whitespace
with a pretty-printed version
@param indent - space/tab/newline of each level of indent, or integer for how many spaces per level
... |
def getMiniHTML(self):
'''
getMiniHTML - Gets the HTML representation of this document without any pretty formatting
and disregarding original whitespace beyond the functional.
@return <str> - HTML with only functional whitespace present
'''
from .For... |
def _reset(self):
'''
_reset - reset this object. Assigned to .reset after __init__ call.
'''
HTMLParser.reset(self)
self.root = None
self.doctype = None
self._inTag = [] |
def feed(self, contents):
'''
feed - Feed contents. Use parseStr or parseFile instead.
@param contents - Contents
'''
contents = stripIEConditionals(contents)
try:
HTMLParser.feed(self, contents)
except MultipleRootNodeException:
... |
def parseFile(self, filename):
'''
parseFile - Parses a file and creates the DOM tree and indexes
@param filename <str/file> - A string to a filename or a file object. If file object, it will not be closed, you must close.
'''
self.reset()
if isinstance(... |
def parseStr(self, html):
'''
parseStr - Parses a string and creates the DOM tree and indexes.
@param html <str> - valid HTML
'''
self.reset()
if isinstance(html, bytes):
self.feed(html.decode(self.encoding))
else:
self.feed(h... |
def createElementFromHTML(cls, html, encoding='utf-8'):
'''
createElementFromHTML - Creates an element from a string of HTML.
If this could create multiple root-level elements (children are okay),
you must use #createElementsFromHTML which returns a list of element... |
def createElementsFromHTML(cls, html, encoding='utf-8'):
'''
createElementsFromHTML - Creates elements from provided html, and returns a list of the root-level elements
children of these root-level nodes are accessable via the usual means.
@param html <str> - Some html d... |
def createBlocksFromHTML(cls, html, encoding='utf-8'):
'''
createBlocksFromHTML - Returns the root level node (unless multiple nodes), and
a list of "blocks" added (text and nodes).
@return list< str/AdvancedTag > - List of blocks created. May be strings (text nodes) or... |
def handle_starttag(self, tagName, attributeList, isSelfClosing=False):
'''
internal for parsing
'''
newTag = AdvancedHTMLParser.handle_starttag(self, tagName, attributeList, isSelfClosing)
self._indexTag(newTag)
return newTag |
def reindex(self, newIndexIDs=None, newIndexNames=None, newIndexClassNames=None, newIndexTagNames=None):
'''
reindex - reindex the tree. Optionally, change what fields are indexed.
@param newIndexIDs <bool/None> - None to leave same, otherwise new value to index IDs
... |
def disableIndexing(self):
'''
disableIndexing - Disables indexing. Consider using plain AdvancedHTMLParser class.
Maybe useful in some scenarios where you want to parse, add a ton of elements, then index
and do a bunch of searching.
'''
self.indexIDs = se... |
def addIndexOnAttribute(self, attributeName):
'''
addIndexOnAttribute - Add an index for an arbitrary attribute. This will be used by the getElementsByAttr function.
You should do this prior to parsing, or call reindex. Otherwise it will be blank. "name" and "id" will have no effect.... |
def removeIndexOnAttribute(self, attributeName):
'''
removeIndexOnAttribute - Remove an attribute from indexing (for getElementsByAttr function) and remove indexed data.
@param attributeName <lowercase str> - An attribute name. Will be lowercased. "name" and "id" will have no effect.
... |
def getElementsByTagName(self, tagName, root='root', useIndex=True):
'''
getElementsByTagName - Searches and returns all elements with a specific tag name.
@param tagName <lowercase str> - A lowercase string of the tag name.
@param root <AdvancedTag/'... |
def getElementsByName(self, name, root='root', useIndex=True):
'''
getElementsByName - Searches and returns all elements with a specific name.
@param name <str> - A string of the name attribute
@param root <AdvancedTag/'root'> - Search starting at a sp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.