sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
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...
Send a POST request.
entailment
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)): ...
Send a DELETE request.
entailment
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 ...
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 seconds (more precisely, if no bytes have been received on the underlying socket for timeout seconds). If no timeout i...
entailment
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...
Upload a single file.
entailment
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...
Upload a file using multi-part encoding.
entailment
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: ...
Upload multiple files.
entailment
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...
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 function for cases when extra control over session creation is required in an automation script that is adapted to...
entailment
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
End the client session.
entailment
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...
This isn't used in Production, but allows this module to be used as a standalone extension.
entailment
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 ...
Point media files at our media server.
entailment
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.
entailment
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 ...
Generate JSON artifacts for each page. This way we can skip generating this in other build step.
entailment
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....
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``
entailment
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...
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.
entailment
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 ...
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 server will create one. Arguments: user_name -- User name part of session ID. session_name -- Se...
entailment
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...
Attach to an existing session.
entailment
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...
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_tcsession=False: End client controller, but leave te...
entailment
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...
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 for, if not this session. Return: ...
entailment
def files(self): """Get list of files, for this session, on server.""" self._check_session() status, data = self._rest.get_request('files') return data
Get list of files, for this session, on server.
entailment
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', ...
Get the BLL version this session is connected to. Return: Version string if session started. None if session not started.
entailment
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 ...
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 for that argument. Arguments: ...
entailment
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). ...
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). kwattrs -- Optional keyword attributes (name=value pairs). Return: ...
entailment
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). ...
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). kwattrs -- Optional keyword attributes (name=value pairs). Return: ...
entailment
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))
Delete the specified object. Arguments: handle -- Handle of object to delete.
entailment
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') ...
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') Arguments: command -- Command to execute. para...
entailment
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', {...
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', {'location': '//10.1.2.3/1/2'}) Arguments: handle...
entailment
def chassis(self): """Get list of chassis known to test session.""" self._check_session() status, data = self._rest.get_request('chassis') return data
Get list of chassis known to test session.
entailment
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...
Get information about the specified chassis.
entailment
def connections(self): """Get list of connections.""" self._check_session() status, data = self._rest.get_request('connections') return data
Get list of connections.
entailment
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...
Get Boolean connected status of the specified chassis.
entailment
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...
Establish connection to one or more chassis. Arguments: chassis_list -- List of chassis (IP addresses or DNS names) Return: List of chassis addresses.
entailment
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_...
Remove connection with one or more chassis. Arguments: chassis_list -- List of chassis (IP addresses or DNS names)
entailment
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...
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 command. object type -- get info about the...
entailment
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() ...
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.
entailment
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 ...
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 path is downloaded to current direc...
entailment
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, ..}...
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, ..}
entailment
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
Upload the specified file to the server.
entailment
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 ...
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 finish. If this time is exceeded, th...
entailment
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...
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 how this works.
entailment
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')) >...
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')) >>> obj.assert_chain_calls(mock.call.select_related('baz'))...
entailment
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 ...
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 callable as the ``wraps`` keyword argument. All other keyword ar...
entailment
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') >>...
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') >>> assert list(objects.filter()) == list(objects.all(...
entailment
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
Overridden read() method to call parse_flask_section() at the end
entailment
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
Overridden readfp() method to call parse_flask_section() at the end
entailment
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...
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.
entailment
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...
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.
entailment
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...
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 version -> do nothing, is a unpredictable behavior this version exists in the d...
entailment
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()
Generate a token string from bytes arrays. The token in the session is user specific.
entailment
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...
Checks that token is correct, aborting if not
entailment
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...
Get the HTTPRequest object from thread storage or from a callee by searching each frame in the call stack.
entailment
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...
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 because Sijax uses ``POST`` for data passing, which ...
entailment
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...
Takes a Sijax response object and returns a valid Flask response object.
entailment
def register_comet_callback(self, *args, **kwargs): """Registers a single Comet callback function (see :ref:`comet-plugin`). Refer to :func:`sijax.plugin.comet.register_comet_callback` for more details - its signature differs slightly. This method's signature is the same, excep...
Registers a single Comet callback function (see :ref:`comet-plugin`). Refer to :func:`sijax.plugin.comet.register_comet_callback` for more details - its signature differs slightly. This method's signature is the same, except that the first argument that :func:`sijax.plugin.come...
entailment
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...
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 signature differs slightly. This method's signature is t...
entailment
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...
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 functions - the ``flask.request.files`` object. ...
entailment
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)
Executes a callback and returns the proper response. Refer to :meth:`sijax.Sijax.execute_callback` for more details.
entailment
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 ...
Returns True if the given HttpRequest has permission to view *at least one* page in the admin site.
entailment
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...
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
entailment
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...
Serve static files below a given point in the directory structure.
entailment
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...
Login form
entailment
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))
Logs out user and redirects them to Nexus home
entailment
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...
Basic dashboard panel
entailment
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 ...
Displays the row of buttons for delete and save.
entailment
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...
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.
entailment
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 = ...
Internal for parsing
entailment
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 ...
Internal for parsing
entailment
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...
Internal for parsing
entailment
def handle_entityref(self, entity): ''' Internal for parsing ''' inTag = self._inTag if len(inTag) > 0: inTag[-1].appendText('&%s;' %(entity,)) else: raise MultipleRootNodeException()
Internal for parsing
entailment
def handle_charref(self, charRef): ''' Internal for parsing ''' inTag = self._inTag if len(inTag) > 0: inTag[-1].appendText('&#%s;' %(charRef,)) else: raise MultipleRootNodeException()
Internal for parsing
entailment
def handle_comment(self, comment): ''' Internal for parsing ''' inTag = self._inTag if len(inTag) > 0: inTag[-1].appendText('<!-- %s -->' %(comment,)) else: raise MultipleRootNodeException()
Internal for parsing
entailment
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...
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. Note: If there are multiple root nodes (i.e. no <ht...
entailment
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
getAllNodes - Get every element @return TagCollection<AdvancedTag>
entailment
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...
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 starting at a specific node, if provided. if string 'root', the root of the p...
entailment
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...
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 provided. if string 'root' [default], the root of the parsed tree will ...
entailment
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...
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 specific node, if provided. if string 'root' [default], the root of the ...
entailment
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...
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 a specific node, if provided. if string 'root' [default], the root of the parsed ...
entailment
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 ...
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 @param attrValue <str> - Expected value of attribute @param ...
entailment
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 ...
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 attrValues set<str> - A set of all valid values. @return - TagCollection of all m...
entailment
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...
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 @return - TagCollection of all matching elements
entailment
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...
getFirstElementCustomFilter - Scan elements using a provided function, stop and return the first match. @see getElementsCustomFilter to match multiple elements @param filterFunc <function>(node) - A function that takes an AdvancedTag as an argument, and returns True if some arbitrary crite...
entailment
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): ...
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
entailment
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): ...
Check if #uid is found anywhere within this element tree @param uid <uuid.UUID> - Uid @return <bool> - If #uid is found within this tree
entailment
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...
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" ) Arguments are key = value, or key...
entailment
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 ...
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
entailment
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 ...
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 @return - <str> Formatted html @...
entailment
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...
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
entailment
def _reset(self): ''' _reset - reset this object. Assigned to .reset after __init__ call. ''' HTMLParser.reset(self) self.root = None self.doctype = None self._inTag = []
_reset - reset this object. Assigned to .reset after __init__ call.
entailment
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: ...
feed - Feed contents. Use parseStr or parseFile instead. @param contents - Contents
entailment
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(...
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.
entailment
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...
parseStr - Parses a string and creates the DOM tree and indexes. @param html <str> - valid HTML
entailment
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...
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 elements created. @param html <str> - Some html data @param e...
entailment
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...
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 data @param encoding <str> - Encoding to use for document ...
entailment
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...
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 AdvancedTag (tags) NOTE: Results may be checked b...
entailment
def handle_starttag(self, tagName, attributeList, isSelfClosing=False): ''' internal for parsing ''' newTag = AdvancedHTMLParser.handle_starttag(self, tagName, attributeList, isSelfClosing) self._indexTag(newTag) return newTag
internal for parsing
entailment
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 ...
reindex - reindex the tree. Optionally, change what fields are indexed. @param newIndexIDs <bool/None> - None to leave same, otherwise new value to index IDs @parma newIndexNames <bool/None> - None to leave same, otherwise new value to index names @param newI...
entailment
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...
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.
entailment
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....
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. @param attributeName <lowercase str> - An attrib...
entailment
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. ...
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.
entailment
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/'...
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 starting at a specific node, if provided. if string 'root', the root of the p...
entailment
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...
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 provided. if string 'root', the root of the parsed tree will be used. ...
entailment