sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def read_stats(self): """ Read current statistics from chassis. :return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}} """ self.tx_statistics = TgnObjectsDict() for port in self.session.ports.values(): for stream in p...
Read current statistics from chassis. :return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}}
entailment
def read_stats(self): """ Read current statistics from chassis. :return: dictionary {tpld full index {group name {stat name: stat value}}} """ self.statistics = TgnObjectsDict() for port in self.session.ports.values(): for tpld in port.tplds.values(): ...
Read current statistics from chassis. :return: dictionary {tpld full index {group name {stat name: stat value}}}
entailment
def get_user_sets(client_id, user_id): """Find all user sets.""" data = api_call('get', 'users/{}/sets'.format(user_id), client_id=client_id) return [WordSet.from_dict(wordset) for wordset in data]
Find all user sets.
entailment
def print_user_sets(wordsets, print_terms): """Print all user sets by title. If 'print_terms', also prints all terms of all user sets. :param wordsets: List of WordSet. :param print_terms: If True, also prints all terms of all user sets. """ if not wordsets: print('No sets found') else: ...
Print all user sets by title. If 'print_terms', also prints all terms of all user sets. :param wordsets: List of WordSet. :param print_terms: If True, also prints all terms of all user sets.
entailment
def get_common_terms(*api_envs): """Get all term duplicates across all user word sets as a list of (title of first word set, title of second word set, set of terms) tuples.""" common_terms = [] # pylint: disable=no-value-for-parameter wordsets = get_user_sets(*api_envs) # pylint: enable=no-value...
Get all term duplicates across all user word sets as a list of (title of first word set, title of second word set, set of terms) tuples.
entailment
def print_common_terms(common_terms): """Print common terms for each pair of word sets. :param common_terms: Output of get_common_terms(). """ if not common_terms: print('No duplicates') else: for set_pair in common_terms: set1, set2, terms = set_pair print('{...
Print common terms for each pair of word sets. :param common_terms: Output of get_common_terms().
entailment
def delete_term(set_id, term_id, access_token): """Delete the given term.""" api_call('delete', 'sets/{}/terms/{}'.format(set_id, term_id), access_token=access_token)
Delete the given term.
entailment
def add_term(set_id, term, access_token): """Add the given term to the given set. :param term: Instance of Term. """ api_call('post', 'sets/{}/terms'.format(set_id), term.to_dict(), access_token=access_token)
Add the given term to the given set. :param term: Instance of Term.
entailment
def reset_term_stats(set_id, term_id, client_id, user_id, access_token): """Reset the stats of a term by deleting and re-creating it.""" found_sets = [user_set for user_set in get_user_sets(client_id, user_id) if user_set.set_id == set_id] if len(found_sets) != 1: raise ValueError(...
Reset the stats of a term by deleting and re-creating it.
entailment
def createController(self, key, attributes, ipmi, printer=False): """ Function createController Create a controller node @param key: The host name or ID @param attributes:The payload of the host creation @param printer: - False for no creation progression message ...
Function createController Create a controller node @param key: The host name or ID @param attributes:The payload of the host creation @param printer: - False for no creation progression message - True to get creation progression printed on STDOUT ...
entailment
def waitPuppetCatalogToBeApplied(self, key, sleepTime=5): """ Function waitPuppetCatalogToBeApplied Wait for puppet catalog to be applied @param key: The host name or ID @return RETURN: None """ # Wait for puppet catalog to be applied loop_stop = False wh...
Function waitPuppetCatalogToBeApplied Wait for puppet catalog to be applied @param key: The host name or ID @return RETURN: None
entailment
def createVM(self, key, attributes, printer=False): """ Function createVM Create a Virtual Machine The creation of a VM with libVirt is a bit complexe. We first create the element in foreman, the ask to start before the result of the creation. To do so, we make async cal...
Function createVM Create a Virtual Machine The creation of a VM with libVirt is a bit complexe. We first create the element in foreman, the ask to start before the result of the creation. To do so, we make async calls to the API and check the results @param key: The hos...
entailment
def get(router, organization, email): """ :rtype: User """ log.info("Getting user: %s" % email) resp = router.get_users(org_id=organization.id).json() ids = [x['id'] for x in resp if x['email'] == email] if len(ids): user = User(organization, ids[0]).i...
:rtype: User
entailment
def construct(self, mapping: dict, **kwargs): """ Construct an object from a mapping :param mapping: the constructor definition, with ``__type__`` name and keyword arguments :param kwargs: additional keyword arguments to pass to the constructor """ assert '__type__' not ...
Construct an object from a mapping :param mapping: the constructor definition, with ``__type__`` name and keyword arguments :param kwargs: additional keyword arguments to pass to the constructor
entailment
def load_name(absolute_name: str): """Load an object based on an absolute, dotted name""" path = absolute_name.split('.') try: __import__(absolute_name) except ImportError: try: obj = sys.modules[path[0]] except KeyError: ...
Load an object based on an absolute, dotted name
entailment
def patch(self, path, value=None): """ Set specified value to yaml path. Example: patch('application/components/child/configuration/__locator.application-id','777') Will change child app ID to 777 """ # noinspection PyShadowingNames def pathGet(dictionary, path): ...
Set specified value to yaml path. Example: patch('application/components/child/configuration/__locator.application-id','777') Will change child app ID to 777
entailment
async def _await_all(self): """Async component of _run""" delay = 0.0 # we run a top-level nursery that automatically reaps/cancels for us async with trio.open_nursery() as nursery: while self.running.is_set(): await self._start_payloads(nursery=nursery) ...
Async component of _run
entailment
async def _start_payloads(self, nursery): """Start all queued payloads""" with self._lock: for coroutine in self._payloads: nursery.start_soon(coroutine) self._payloads.clear() await trio.sleep(0)
Start all queued payloads
entailment
def contains_list(longer, shorter): """Check if longer list starts with shorter list""" if len(longer) <= len(shorter): return False for a, b in zip(shorter, longer): if a != b: return False return True
Check if longer list starts with shorter list
entailment
def load(f, dict_=dict): """Load and parse toml from a file object An additional argument `dict_` is used to specify the output type """ if not f.read: raise ValueError('The first parameter needs to be a file object, ', '%r is passed' % type(f)) return loads(f.read()...
Load and parse toml from a file object An additional argument `dict_` is used to specify the output type
entailment
def loads(content, dict_=dict): """Parse a toml string An additional argument `dict_` is used to specify the output type """ if not isinstance(content, basestring): raise ValueError('The first parameter needs to be a string object, ', '%r is passed' % type(content)) ...
Parse a toml string An additional argument `dict_` is used to specify the output type
entailment
def convert(self, line=None, is_end=True): """Read the line content and return the converted value :param line: the line to feed to converter :param is_end: if set to True, will raise an error if the line has something remaining. """ if line is not None: self...
Read the line content and return the converted value :param line: the line to feed to converter :param is_end: if set to True, will raise an error if the line has something remaining.
entailment
def parse(self, data=None, table_name=None): """Parse the lines from index i :param data: optional, store the parsed result to it when specified :param table_name: when inside a table array, it is the table name """ temp = self.dict_() sub_table = None is_array =...
Parse the lines from index i :param data: optional, store the parsed result to it when specified :param table_name: when inside a table array, it is the table name
entailment
def split_string(self, string, splitter='.', allow_empty=True): """Split the string with respect of quotes""" i = 0 rv = [] need_split = False while i < len(string): m = re.compile(_KEY_NAME).match(string, i) if not need_split and m: i = m....
Split the string with respect of quotes
entailment
def transform_source(text): '''removes a "where" clause which is identified by the use of "where" as an identifier and ends at the first DEDENT (i.e. decrease in indentation)''' toks = tokenize.generate_tokens(StringIO(text).readline) result = [] where_clause = False for toktype, tokvalue, _, _,...
removes a "where" clause which is identified by the use of "where" as an identifier and ends at the first DEDENT (i.e. decrease in indentation)
entailment
def is_visible(self): """ Return a boolean if the page is visible in navigation. Pages must have show in navigation set. Regular pages must be published (published and have a current version - checked with `is_published`), pages with a glitter app associated don't need any page ...
Return a boolean if the page is visible in navigation. Pages must have show in navigation set. Regular pages must be published (published and have a current version - checked with `is_published`), pages with a glitter app associated don't need any page versions.
entailment
def main(args=sys.argv[1:]): """ Main function, called from CLI script :return: """ import mcpartools parser = argparse.ArgumentParser() parser.add_argument('-V', '--version', action='version', version=mcpartools.__version__) parser.add_arg...
Main function, called from CLI script :return:
entailment
def build_node_tree(self, source_paths): """ Build a node tree. """ import uqbar.apis root = PackageNode() # Build node tree, top-down for source_path in sorted( source_paths, key=lambda x: uqbar.apis.source_path_to_package_path(x) ): ...
Build a node tree.
entailment
def validate_unique(self): """ Add this method because django doesn't validate correctly because required fields are excluded. """ unique_checks, date_checks = self.instance._get_unique_checks(exclude=[]) errors = self.instance._perform_unique_checks(unique_checks) ...
Add this method because django doesn't validate correctly because required fields are excluded.
entailment
def prepare_monitor(tenant=tenant, user=user, password=password, organization=organization, zone_name=zone_name): """ :param tenant: tenant url :param user: user's email :param password: user's password :param zone_name: (optional) zone_name :return: """ router = PrivatePath(tenant, veri...
:param tenant: tenant url :param user: user's email :param password: user's password :param zone_name: (optional) zone_name :return:
entailment
def launch(self, timeout=2): """ Hierapp instance, with environment dependencies: - can be launched within short timeout - auto-destroys shortly """ self.start_time = time.time() self.end_time = time.time() instance = self.app.launch(environment=self.env) ...
Hierapp instance, with environment dependencies: - can be launched within short timeout - auto-destroys shortly
entailment
def clone(self): """ Do not initialize again since everything is ready to launch app. :return: Initialized monitor instance """ return Monitor(org=self.org, app=self.app, env=self.env)
Do not initialize again since everything is ready to launch app. :return: Initialized monitor instance
entailment
def from_dict(raw_data): """Create Image from raw dictionary data.""" url = None width = None height = None try: url = raw_data['url'] width = raw_data['width'] height = raw_data['height'] except KeyError: raise ValueError('...
Create Image from raw dictionary data.
entailment
def to_dict(self): """Convert Image into raw dictionary data.""" if not self.url: return None return { 'url': self.url, 'width': self.width, 'height': self.height }
Convert Image into raw dictionary data.
entailment
def from_dict(raw_data): """Create Term from raw dictionary data.""" try: definition = raw_data['definition'] term_id = raw_data['id'] image = Image.from_dict(raw_data['image']) rank = raw_data['rank'] term = raw_data['term'] return...
Create Term from raw dictionary data.
entailment
def to_dict(self): """Convert Term into raw dictionary data.""" return { 'definition': self.definition, 'id': self.term_id, 'image': self.image.to_dict(), 'rank': self.rank, 'term': self.term }
Convert Term into raw dictionary data.
entailment
def has_common(self, other): """Return set of common words between two word sets.""" if not isinstance(other, WordSet): raise ValueError('Can compare only WordSets') return self.term_set & other.term_set
Return set of common words between two word sets.
entailment
def from_dict(raw_data): """Create WordSet from raw dictionary data.""" try: set_id = raw_data['id'] title = raw_data['title'] terms = [Term.from_dict(term) for term in raw_data['terms']] return WordSet(set_id, title, terms) except KeyError: ...
Create WordSet from raw dictionary data.
entailment
def to_dict(self): """Convert WordSet into raw dictionary data.""" return { 'id': self.set_id, 'title': self.title, 'terms': [term.to_dict() for term in self.terms] }
Convert WordSet into raw dictionary data.
entailment
def release(ctx, yes, latest): """Create a new release in github """ m = RepoManager(ctx.obj['agile']) api = m.github_repo() if latest: latest = api.releases.latest() if latest: click.echo(latest['tag_name']) elif m.can_release('sandbox'): branch = m.info['bra...
Create a new release in github
entailment
def on_builder_inited(app): """ Hooks into Sphinx's ``builder-inited`` event. """ app.cache_db_path = ":memory:" if app.config["uqbar_book_use_cache"]: logger.info(bold("[uqbar-book]"), nonl=True) logger.info(" initializing cache db") app.connection = uqbar.book.sphinx.create...
Hooks into Sphinx's ``builder-inited`` event.
entailment
def on_config_inited(app, config): """ Hooks into Sphinx's ``config-inited`` event. """ extension_paths = config["uqbar_book_extensions"] or [ "uqbar.book.extensions.GraphExtension" ] app.uqbar_book_extensions = [] for extension_path in extension_paths: module_name, _, class_...
Hooks into Sphinx's ``config-inited`` event.
entailment
def on_doctree_read(app, document): """ Hooks into Sphinx's ``doctree-read`` event. """ literal_blocks = uqbar.book.sphinx.collect_literal_blocks(document) cache_mapping = uqbar.book.sphinx.group_literal_blocks_by_cache_path(literal_blocks) node_mapping = {} use_cache = bool(app.config["uqba...
Hooks into Sphinx's ``doctree-read`` event.
entailment
def on_build_finished(app, exception): """ Hooks into Sphinx's ``build-finished`` event. """ if not app.config["uqbar_book_use_cache"]: return logger.info("") for row in app.connection.execute("SELECT path, hits FROM cache ORDER BY path"): path, hits = row if not hits: ...
Hooks into Sphinx's ``build-finished`` event.
entailment
def handle_class(signature_node, module, object_name, cache): """ Styles ``autoclass`` entries. Adds ``abstract`` prefix to abstract classes. """ class_ = getattr(module, object_name, None) if class_ is None: return if class_ not in cache: cache[class_] = {} attribut...
Styles ``autoclass`` entries. Adds ``abstract`` prefix to abstract classes.
entailment
def handle_method(signature_node, module, object_name, cache): """ Styles ``automethod`` entries. Adds ``abstract`` prefix to abstract methods. Adds link to originating class for inherited methods. """ *class_names, attr_name = object_name.split(".") # Handle nested classes class_ = modul...
Styles ``automethod`` entries. Adds ``abstract`` prefix to abstract methods. Adds link to originating class for inherited methods.
entailment
def on_doctree_read(app, document): """ Hooks into Sphinx's ``doctree-read`` event. """ cache: Dict[type, Dict[str, object]] = {} for desc_node in document.traverse(addnodes.desc): if desc_node.get("domain") != "py": continue signature_node = desc_node.traverse(addnodes.d...
Hooks into Sphinx's ``doctree-read`` event.
entailment
def on_builder_inited(app): """ Hooks into Sphinx's ``builder-inited`` event. Used for copying over CSS files to theme directory. """ local_css_path = pathlib.Path(__file__).parent / "uqbar.css" theme_css_path = ( pathlib.Path(app.srcdir) / app.config.html_static_path[0] / "uqbar.css" ...
Hooks into Sphinx's ``builder-inited`` event. Used for copying over CSS files to theme directory.
entailment
def setup(app) -> Dict[str, Any]: """ Sets up Sphinx extension. """ app.connect("doctree-read", on_doctree_read) app.connect("builder-inited", on_builder_inited) app.add_css_file("uqbar.css") app.add_node( nodes.classifier, override=True, html=(visit_classifier, depart_classifier) ...
Sets up Sphinx extension.
entailment
def init_xena(api, logger, owner, ip=None, port=57911): """ Create XenaManager object. :param api: cli/rest :param logger: python logger :param owner: owner of the scripting session :param ip: rest server IP :param port: rest server TCP port :return: Xena object :rtype: XenaApp """ ...
Create XenaManager object. :param api: cli/rest :param logger: python logger :param owner: owner of the scripting session :param ip: rest server IP :param port: rest server TCP port :return: Xena object :rtype: XenaApp
entailment
def add_chassis(self, chassis, port=22611, password='xena'): """ Add chassis. XenaManager-2G -> Add Chassis. :param chassis: chassis IP address :param port: chassis port number :param password: chassis password :return: newly created chassis :rtype: xenamanager....
Add chassis. XenaManager-2G -> Add Chassis. :param chassis: chassis IP address :param port: chassis port number :param password: chassis password :return: newly created chassis :rtype: xenamanager.xena_app.XenaChassis
entailment
def inventory(self): """ Get inventory for all chassis. """ for chassis in self.chassis_list.values(): chassis.inventory(modules_inventory=True)
Get inventory for all chassis.
entailment
def reserve_ports(self, locations, force=False, reset=True): """ Reserve ports and reset factory defaults. XenaManager-2G -> Reserve/Relinquish Port. XenaManager-2G -> Reserve Port. :param locations: list of ports locations in the form <ip/slot/port> to reserve :param force: Tr...
Reserve ports and reset factory defaults. XenaManager-2G -> Reserve/Relinquish Port. XenaManager-2G -> Reserve Port. :param locations: list of ports locations in the form <ip/slot/port> to reserve :param force: True - take forcefully. False - fail if port is reserved by other user ...
entailment
def start_traffic(self, blocking=False, *ports): """ Start traffic on list of ports. :param blocking: True - start traffic and wait until traffic ends, False - start traffic and return. :param ports: list of ports to start traffic on. Default - all session ports. """ for chassi...
Start traffic on list of ports. :param blocking: True - start traffic and wait until traffic ends, False - start traffic and return. :param ports: list of ports to start traffic on. Default - all session ports.
entailment
def stop_traffic(self, *ports): """ Stop traffic on list of ports. :param ports: list of ports to stop traffic on. Default - all session ports. """ for chassis, chassis_ports in self._per_chassis_ports(*self._get_operation_ports(*ports)).items(): chassis.stop_traffic(*chass...
Stop traffic on list of ports. :param ports: list of ports to stop traffic on. Default - all session ports.
entailment
def ports(self): """ :return: dictionary {name: object} of all ports. """ ports = {} for chassis in self.chassis_list.values(): ports.update({str(p): p for p in chassis.get_objects_by_type('port')}) return ports
:return: dictionary {name: object} of all ports.
entailment
def inventory(self, modules_inventory=False): """ Get chassis inventory. :param modules_inventory: True - read modules inventory, false - don't read. """ self.c_info = self.get_attributes() for m_index, m_portcounts in enumerate(self.c_info['c_portcounts'].split()): ...
Get chassis inventory. :param modules_inventory: True - read modules inventory, false - don't read.
entailment
def reserve_ports(self, locations, force=False, reset=True): """ Reserve ports and reset factory defaults. XenaManager-2G -> Reserve/Relinquish Port. XenaManager-2G -> Reset port. :param locations: list of ports locations in the form <module/port> to reserve :param force: True ...
Reserve ports and reset factory defaults. XenaManager-2G -> Reserve/Relinquish Port. XenaManager-2G -> Reset port. :param locations: list of ports locations in the form <module/port> to reserve :param force: True - take forcefully, False - fail if port is reserved by other user ...
entailment
def start_traffic(self, blocking=False, *ports): """ Start traffic on list of ports. :param blocking: True - start traffic and wait until traffic ends, False - start traffic and return. :param ports: list of ports to start traffic on. Default - all session ports. """ self._traf...
Start traffic on list of ports. :param blocking: True - start traffic and wait until traffic ends, False - start traffic and return. :param ports: list of ports to start traffic on. Default - all session ports.
entailment
def modules(self): """ :return: dictionary {index: object} of all modules. """ if not self.get_objects_by_type('module'): self.inventory() return {int(c.index): c for c in self.get_objects_by_type('module')}
:return: dictionary {index: object} of all modules.
entailment
def inventory(self): """ Get module inventory. """ self.m_info = self.get_attributes() if 'NOTCFP' in self.m_info['m_cfptype']: a = self.get_attribute('m_portcount') m_portcount = int(a) else: m_portcount = int(self.get_attribute('m_cfpconfig').split(...
Get module inventory.
entailment
def ports(self): """ :return: dictionary {index: object} of all ports. """ if not self.get_objects_by_type('port'): self.inventory() return {int(p.index.split('/')[1]): p for p in self.get_objects_by_type('port')}
:return: dictionary {index: object} of all ports.
entailment
def run(entry_point, drivers, loop = None): ''' This is a runner wrapping the cyclotron "run" implementation. It takes an additional parameter to provide a custom asyncio mainloop. ''' program = setup(entry_point, drivers) dispose = program.run() if loop == None: loop = asyncio.get_event...
This is a runner wrapping the cyclotron "run" implementation. It takes an additional parameter to provide a custom asyncio mainloop.
entailment
def register(model, admin=None, category=None): """ Decorator to registering you Admin class. """ def _model_admin_wrapper(admin_class): site.register(model, admin_class=admin_class) if category: site.register_block(model, category) return admin_class return _model_adm...
Decorator to registering you Admin class.
entailment
def has_glitter_edit_permission(self, request, obj): """ Return a boolean if a user has edit access to the glitter object/page this object is on. """ # We're testing for the edit permission here with the glitter object - not the current # object, not the change permission. Once ...
Return a boolean if a user has edit access to the glitter object/page this object is on.
entailment
def change_view(self, request, object_id, form_url='', extra_context=None): """The 'change' admin view for this model.""" obj = self.get_object(request, unquote(object_id)) if obj is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % { ...
The 'change' admin view for this model.
entailment
def response_change(self, request, obj): """Determine the HttpResponse for the change_view stage.""" opts = self.opts.app_label, self.opts.model_name pk_value = obj._get_pk_val() if '_continue' in request.POST: msg = _( 'The %(name)s block was changed success...
Determine the HttpResponse for the change_view stage.
entailment
def get_filter_item(name: str, operation: bytes, value: bytes) -> bytes: """ A field could be found for this term, try to get filter string for it. """ assert isinstance(name, str) assert isinstance(value, bytes) if operation is None: return filter_format(b"(%s=%s)", [name, value]) e...
A field could be found for this term, try to get filter string for it.
entailment
def get_filter(q: tldap.Q, fields: Dict[str, tldap.fields.Field], pk: str): """ Translate the Q tree into a filter string to search for, or None if no results possible. """ # check the details are valid if q.negated and len(q.children) == 1: op = b"!" elif q.connector == tldap.Q.AND:...
Translate the Q tree into a filter string to search for, or None if no results possible.
entailment
def program_name(self): r"""The name of the script, callable from the command line. """ name = "-".join( word.lower() for word in uqbar.strings.delimit_words(type(self).__name__) ) return name
r"""The name of the script, callable from the command line.
entailment
def node_is_result_assignment(node: ast.AST) -> bool: """ Args: node: An ``ast`` node. Returns: bool: ``node`` corresponds to the code ``result =``, assignment to the ``result `` variable. Note: Performs a very weak test that the line starts with 'result =' rather ...
Args: node: An ``ast`` node. Returns: bool: ``node`` corresponds to the code ``result =``, assignment to the ``result `` variable. Note: Performs a very weak test that the line starts with 'result =' rather than testing the tokens.
entailment
def node_is_noop(node: ast.AST) -> bool: """ Node does nothing. """ return isinstance(node.value, ast.Str) if isinstance(node, ast.Expr) else isinstance(node, ast.Pass)
Node does nothing.
entailment
def function_is_noop(function_node: ast.FunctionDef) -> bool: """ Function does nothing - is just ``pass`` or docstring. """ return all(node_is_noop(n) for n in function_node.body)
Function does nothing - is just ``pass`` or docstring.
entailment
def add_node_parents(root: ast.AST) -> None: """ Adds "parent" attribute to all child nodes of passed node. Code taken from https://stackoverflow.com/a/43311383/1286705 """ for node in ast.walk(root): for child in ast.iter_child_nodes(node): child.parent = node
Adds "parent" attribute to all child nodes of passed node. Code taken from https://stackoverflow.com/a/43311383/1286705
entailment
def build_footprint(node: ast.AST, first_line_no: int) -> Set[int]: """ Generates a list of lines that the passed node covers, relative to the marked lines list - i.e. start of function is line 0. """ return set( range( get_first_token(node).start[0] - first_line_no, ...
Generates a list of lines that the passed node covers, relative to the marked lines list - i.e. start of function is line 0.
entailment
def filter_arrange_nodes(nodes: List[ast.stmt], max_line_number: int) -> List[ast.stmt]: """ Finds all nodes that are before the ``max_line_number`` and are not docstrings or ``pass``. """ return [ node for node in nodes if node.lineno < max_line_number and not isinstance(node, ast.Pass) ...
Finds all nodes that are before the ``max_line_number`` and are not docstrings or ``pass``.
entailment
def filter_assert_nodes(nodes: List[ast.stmt], min_line_number: int) -> List[ast.stmt]: """ Finds all nodes that are after the ``min_line_number`` """ return [node for node in nodes if node.lineno > min_line_number]
Finds all nodes that are after the ``min_line_number``
entailment
def find_stringy_lines(tree: ast.AST, first_line_no: int) -> Set[int]: """ Finds all lines that contain a string in a tree, usually a function. These lines will be ignored when searching for blank lines. """ str_footprints = set() for node in ast.walk(tree): if isinstance(node, ast.Str):...
Finds all lines that contain a string in a tree, usually a function. These lines will be ignored when searching for blank lines.
entailment
def check_all(self) -> Generator[AAAError, None, None]: """ Run everything required for checking this function. Returns: A generator of errors. Raises: ValidationError: A non-recoverable linting error is found. """ # Function def if funct...
Run everything required for checking this function. Returns: A generator of errors. Raises: ValidationError: A non-recoverable linting error is found.
entailment
def load_act_node(self) -> ActNode: """ Raises: ValidationError: AAA01 when no act block is found and AAA02 when multiple act blocks are found. """ act_nodes = ActNode.build_body(self.node.body) if not act_nodes: raise ValidationError(self...
Raises: ValidationError: AAA01 when no act block is found and AAA02 when multiple act blocks are found.
entailment
def get_line_relative_to_node(self, target_node: ast.AST, offset: int) -> str: """ Raises: IndexError: when ``offset`` takes the request out of bounds of this Function's lines. """ return self.lines[target_node.lineno - self.node.lineno + offset]
Raises: IndexError: when ``offset`` takes the request out of bounds of this Function's lines.
entailment
def mark_def(self) -> int: """ Marks up this Function's definition lines (including decorators) into the ``line_markers`` attribute. Returns: Number of lines found for the definition. Note: Does not spot the closing ``):`` of a function when it occurs on...
Marks up this Function's definition lines (including decorators) into the ``line_markers`` attribute. Returns: Number of lines found for the definition. Note: Does not spot the closing ``):`` of a function when it occurs on its own line. Note: ...
entailment
def mark_bl(self) -> int: """ Mark unprocessed lines that have no content and no string nodes covering them as blank line BL. Returns: Number of blank lines found with no stringy parent node. """ counter = 0 stringy_lines = find_stringy_lines(self.nod...
Mark unprocessed lines that have no content and no string nodes covering them as blank line BL. Returns: Number of blank lines found with no stringy parent node.
entailment
def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ self.update({'puppetclasses': SubDict(self.api, self.objName, self.payloadObj, self.key, SubItemPuppetClasses)}) ...
Function enhance Enhance the object with new item or enhanced items
entailment
def getParamFromEnv(self, var, default=''): """ Function getParamFromEnv Search a parameter in the host environment @param var: the var name @param hostgroup: the hostgroup item linked to this host @param default: default value @return RETURN: the value """ ...
Function getParamFromEnv Search a parameter in the host environment @param var: the var name @param hostgroup: the hostgroup item linked to this host @param default: default value @return RETURN: the value
entailment
def getUserData(self, hostgroup, domain, defaultPwd='', defaultSshKey='', proxyHostname='', tplFolder='metadata/templates/'): """ Function getUserData Generate a userdata script for me...
Function getUserData Generate a userdata script for metadata server from Foreman API @param domain: the domain item linked to this host @param hostgroup: the hostgroup item linked to this host @param defaultPwd: the default password if no password is specified ...
entailment
def register_payload(self, *payloads, flavour: ModuleType): """Queue one or more payload for execution after its runner is started""" for payload in payloads: self._logger.debug('registering payload %s (%s)', NameRepr(payload), NameRepr(flavour)) self.runners[flavour].register_pa...
Queue one or more payload for execution after its runner is started
entailment
def run_payload(self, payload, *, flavour: ModuleType): """Execute one payload after its runner is started and return its output""" return self.runners[flavour].run_payload(payload)
Execute one payload after its runner is started and return its output
entailment
def run(self): """Run all runners, blocking until completion or error""" self._logger.info('starting all runners') try: with self._lock: assert not self.running.set(), 'cannot re-run: %s' % self self.running.set() thread_runner = self.runne...
Run all runners, blocking until completion or error
entailment
def formfield_for_dbfield(self, db_field, **kwargs): """ Hook for specifying the form Field instance for a given database Field instance. If kwargs are given, they're passed to the form Field's constructor. """ formfield = super().formfield_for_dbfield(db_field, **kwargs...
Hook for specifying the form Field instance for a given database Field instance. If kwargs are given, they're passed to the form Field's constructor.
entailment
def compare_schemas(one, two): """Compare two structures that represents JSON schemas. For comparison you can't use normal comparison, because in JSON schema lists DO NOT keep order (and Python lists do), so this must be taken into account during comparison. Note this wont check all configurations...
Compare two structures that represents JSON schemas. For comparison you can't use normal comparison, because in JSON schema lists DO NOT keep order (and Python lists do), so this must be taken into account during comparison. Note this wont check all configurations, only first one that seems to mat...
entailment
def is_ecma_regex(regex): """Check if given regex is of type ECMA 262 or not. :rtype: bool """ parts = regex.split('/') if len(parts) == 1: return False if len(parts) < 3: raise ValueError('Given regex isn\'t ECMA regex nor Python regex.') parts.pop() parts.append('')...
Check if given regex is of type ECMA 262 or not. :rtype: bool
entailment
def convert_ecma_regex_to_python(value): """Convert ECMA 262 regex to Python tuple with regex and flags. If given value is already Python regex it will be returned unchanged. :param string value: ECMA regex. :return: 2-tuple with `regex` and `flags` :rtype: namedtuple """ if not is_ecma_r...
Convert ECMA 262 regex to Python tuple with regex and flags. If given value is already Python regex it will be returned unchanged. :param string value: ECMA regex. :return: 2-tuple with `regex` and `flags` :rtype: namedtuple
entailment
def convert_python_regex_to_ecma(value, flags=[]): """Convert Python regex to ECMA 262 regex. If given value is already ECMA regex it will be returned unchanged. :param string value: Python regex. :param list flags: List of flags (allowed flags: `re.I`, `re.M`) :return: ECMA 262 regex :rtype: ...
Convert Python regex to ECMA 262 regex. If given value is already ECMA regex it will be returned unchanged. :param string value: Python regex. :param list flags: List of flags (allowed flags: `re.I`, `re.M`) :return: ECMA 262 regex :rtype: str
entailment
def populate(self, **values): """Populate values to fields. Skip non-existing.""" values = values.copy() fields = list(self.iterate_with_name()) for _, structure_name, field in fields: if structure_name in values: field.__set__(self, values.pop(structure_name)...
Populate values to fields. Skip non-existing.
entailment
def get_field(self, field_name): """Get field associated with given attribute.""" for attr_name, field in self: if field_name == attr_name: return field raise errors.FieldNotFound('Field not found', field_name)
Get field associated with given attribute.
entailment
def validate(self): """Explicitly validate all the fields.""" for name, field in self: try: field.validate_for_object(self) except ValidationError as error: raise ValidationError( "Error for field '{name}'.".format(name=name), ...
Explicitly validate all the fields.
entailment
def iterate_over_fields(cls): """Iterate through fields as `(attribute_name, field_instance)`.""" for attr in dir(cls): clsattr = getattr(cls, attr) if isinstance(clsattr, BaseField): yield attr, clsattr
Iterate through fields as `(attribute_name, field_instance)`.
entailment
def iterate_with_name(cls): """Iterate over fields, but also give `structure_name`. Format is `(attribute_name, structue_name, field_instance)`. Structure name is name under which value is seen in structure and schema (in primitives) and only there. """ for attr_name, fi...
Iterate over fields, but also give `structure_name`. Format is `(attribute_name, structue_name, field_instance)`. Structure name is name under which value is seen in structure and schema (in primitives) and only there.
entailment
def parse_value(self, value): """Cast value to `int`, e.g. from string or long""" parsed = super(IntField, self).parse_value(value) if parsed is None: return parsed return int(parsed)
Cast value to `int`, e.g. from string or long
entailment