text
stringlengths
81
112k
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 def parse(self, data=None, table_name=None): """Parse the lines from index i :param data: optional, store the parsed resu...
Split the string with respect of quotes 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...
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) 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 i...
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. def is_visible(self): "...
Main function, called from CLI script :return: 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', ...
Build a node tree. 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)...
Add this method because django doesn't validate correctly because required fields are excluded. def validate_unique(self): """ Add this method because django doesn't validate correctly because required fields are excluded. """ unique_checks, date_checks = self.instance._...
:param tenant: tenant url :param user: user's email :param password: user's password :param zone_name: (optional) zone_name :return: def prepare_monitor(tenant=tenant, user=user, password=password, organization=organization, zone_name=zone_name): """ :param tenant: tenant url :param user: u...
Hierapp instance, with environment dependencies: - can be launched within short timeout - auto-destroys shortly def launch(self, timeout=2): """ Hierapp instance, with environment dependencies: - can be launched within short timeout - auto-destroys shortly """ ...
Do not initialize again since everything is ready to launch app. :return: Initialized monitor instance 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.ap...
Create Image from raw dictionary data. 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 ...
Convert Image into raw dictionary data. 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 }
Create Term from raw dictionary data. 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'] ter...
Convert Term into raw dictionary data. 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 }
Return set of common words between two word sets. 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
Create WordSet from raw dictionary data. 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, tit...
Convert WordSet into raw dictionary data. 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] }
Create a new release in github 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...
Hooks into Sphinx's ``builder-inited`` event. 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") ...
Hooks into Sphinx's ``config-inited`` event. 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 e...
Hooks into Sphinx's ``doctree-read`` event. 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_mappi...
Hooks into Sphinx's ``build-finished`` event. 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"): ...
Styles ``autoclass`` entries. Adds ``abstract`` prefix to abstract classes. 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: ...
Styles ``automethod`` entries. Adds ``abstract`` prefix to abstract methods. Adds link to originating class for inherited methods. def handle_method(signature_node, module, object_name, cache): """ Styles ``automethod`` entries. Adds ``abstract`` prefix to abstract methods. Adds link to ori...
Hooks into Sphinx's ``doctree-read`` event. 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 s...
Hooks into Sphinx's ``builder-inited`` event. Used for copying over CSS files to theme directory. 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" ...
Sets up Sphinx extension. 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_classi...
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 def init_xena(api, logger, owner, ip=None, port=57911): """ Create ...
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 def add_chassis(self, chassis, port=22611, password...
Get inventory for all chassis. def inventory(self): """ Get inventory for all chassis. """ for chassis in self.chassis_list.values(): chassis.inventory(modules_inventory=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: True - take forcefully. False - fail if port is reserved by other user ...
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. def start_traffic(self, blocking=False, *ports): """ Start traffic on list of ports...
Stop traffic on list of ports. :param ports: list of ports to stop traffic on. Default - all session ports. 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...
:return: dictionary {name: object} of all ports. 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 por...
Get chassis inventory. :param modules_inventory: True - read modules inventory, false - don't read. 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...
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 ...
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. def start_traffic(self, blocking=False, *ports): """ Start traffic on list of ports...
:return: dictionary {index: object} of all modules. 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')}
Get module inventory. 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_attribut...
:return: dictionary {index: object} of all ports. 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')}
This is a runner wrapping the cyclotron "run" implementation. It takes an additional parameter to provide a custom asyncio mainloop. 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 mai...
Decorator to registering you Admin class. 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 a boolean if a user has edit access to the glitter object/page this object is on. 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 wi...
The 'change' admin view for this model. 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 %(...
Determine the HttpResponse for the change_view stage. 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 = _( ...
A field could be found for this term, try to get filter string for it. 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 operatio...
Translate the Q tree into a filter string to search for, or None if no results possible. 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 ...
r"""The name of the script, callable from the command line. 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
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. def node_is_result_assignment(node: a...
Node does nothing. 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)
Function does nothing - is just ``pass`` or docstring. 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)
Adds "parent" attribute to all child nodes of passed node. Code taken from https://stackoverflow.com/a/43311383/1286705 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 """ ...
Generates a list of lines that the passed node covers, relative to the marked lines list - i.e. start of function is line 0. 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 f...
Finds all nodes that are before the ``max_line_number`` and are not docstrings or ``pass``. 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 [ ...
Finds all nodes that are after the ``min_line_number`` 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 lines that contain a string in a tree, usually a function. These lines will be ignored when searching for blank lines. 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 wh...
Run everything required for checking this function. Returns: A generator of errors. Raises: ValidationError: A non-recoverable linting error is found. def check_all(self) -> Generator[AAAError, None, None]: """ Run everything required for checking this function...
Raises: ValidationError: AAA01 when no act block is found and AAA02 when multiple act blocks are found. def load_act_node(self) -> ActNode: """ Raises: ValidationError: AAA01 when no act block is found and AAA02 when multiple act blocks are found....
Raises: IndexError: when ``offset`` takes the request out of bounds of this Function's lines. 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 ...
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: ...
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. def mark_bl(self) -> int: """ Mark unprocessed lines that have no content and no string nodes covering t...
Function enhance Enhance the object with new item or enhanced items def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ self.update({'puppetclasses': SubDict(self.api, self.objName, self...
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 def getParamFromEnv(self, var, default=''): """ Function getPara...
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 ...
Queue one or more payload for execution after its runner is started 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(paylo...
Execute one payload after its runner is started and return its output 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)
Run all runners, blocking until completion or error 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...
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. def formfield_for_dbfield(self, db_field, **kwargs): """ Hook for specifying the form Field instance for a given database Field ...
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...
Check if given regex is of type ECMA 262 or not. :rtype: bool 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...
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 def convert_ecma_regex_to_python(value): """Convert ECMA 262 regex to Py...
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 def convert_python_regex_to_ecma(value, flags=[]): ...
Populate values to fields. Skip non-existing. 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: ...
Get field associated with given attribute. 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)
Explicitly validate all the fields. 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 ...
Iterate through fields as `(attribute_name, field_instance)`. 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, clsat...
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. def iterate_with_name(cls): """Iterate over fields, but also give `...
Cast value to `int`, e.g. from string or long 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 `bool`. def parse_value(self, value): """Cast value to `bool`.""" parsed = super(BoolField, self).parse_value(value) return bool(parsed) if parsed is not None else None
Cast value to proper collection. def parse_value(self, values): """Cast value to proper collection.""" result = self.get_default_value() if not values: return result if not isinstance(values, list): return values return [self._cast_value(value) for val...
Parse value to proper model type. def parse_value(self, value): """Parse value to proper model type.""" if not isinstance(value, dict): return value embed_type = self._get_embed_type() return embed_type(**value)
Cast `time` object to string. def to_struct(self, value): """Cast `time` object to string.""" if self.str_format: return value.strftime(self.str_format) return value.isoformat()
Parse string into instance of `time`. def parse_value(self, value): """Parse string into instance of `time`.""" if value is None: return value if isinstance(value, datetime.time): return value return parse(value).timetz()
Cast `date` object to string. def to_struct(self, value): """Cast `date` object to string.""" if self.str_format: return value.strftime(self.str_format) return value.strftime(self.default_format)
Parse string into instance of `datetime`. def parse_value(self, value): """Parse string into instance of `datetime`.""" if isinstance(value, datetime.datetime): return value if value: return parse(value) else: return None
Validate value. def validate(self, value): """Validate value.""" if self.exclusive: if value <= self.minimum_value: tpl = "'{value}' is lower or equal than minimum ('{min}')." raise ValidationError( tpl.format(value=value, min=self.minimum...
Modify field schema. def modify_schema(self, field_schema): """Modify field schema.""" field_schema['minimum'] = self.minimum_value if self.exclusive: field_schema['exclusiveMinimum'] = True
Validate value. def validate(self, value): """Validate value.""" if self.exclusive: if value >= self.maximum_value: tpl = "'{val}' is bigger or equal than maximum ('{max}')." raise ValidationError( tpl.format(val=value, max=self.maximum_va...
Modify field schema. def modify_schema(self, field_schema): """Modify field schema.""" field_schema['maximum'] = self.maximum_value if self.exclusive: field_schema['exclusiveMaximum'] = True
Validate value. def validate(self, value): """Validate value.""" flags = self._calculate_flags() try: result = re.search(self.pattern, value, flags) except TypeError as te: raise ValidationError(*te.args) if not result: raise ValidationError...
Modify field schema. def modify_schema(self, field_schema): """Modify field schema.""" field_schema['pattern'] = utilities.convert_python_regex_to_ecma( self.pattern, self.flags)
Validate value. def validate(self, value): """Validate value.""" len_ = len(value) if self.minimum_value is not None and len_ < self.minimum_value: tpl = "Value '{val}' length is lower than allowed minimum '{min}'." raise ValidationError(tpl.format( val=...
Modify field schema. def modify_schema(self, field_schema): """Modify field schema.""" if self.minimum_value: field_schema['minLength'] = self.minimum_value if self.maximum_value: field_schema['maxLength'] = self.maximum_value
Cast instance of model to python structure. :param model: Model to be casted. :rtype: ``dict`` def to_struct(model): """Cast instance of model to python structure. :param model: Model to be casted. :rtype: ``dict`` """ model.validate() resp = {} for _, name, field in model.itera...
Set up any environment changes requested (e.g., Python path and Django settings), then run this command. If the command raises a ``CommandError``, intercept it and print it sensibly to stderr. def run_from_argv(self, argv): """ Set up any environment changes requested (e.g., Pyt...
Create and return the ``OptionParser`` which will be used to parse the arguments to this command. def create_parser(self, prog_name, subcommand): """ Create and return the ``OptionParser`` which will be used to parse the arguments to this command. """ parser = argparse....
Load rst file and sanitize it for PyPI. Remove unsupported github tags: - code-block directive - travis ci build badge def rst(filename): ''' Load rst file and sanitize it for PyPI. Remove unsupported github tags: - code-block directive - travis ci build badge ''' content = ...
A simple shortcut to render a ``script`` tag to a static javascript file def javascript(filename, type='text/javascript'): '''A simple shortcut to render a ``script`` tag to a static javascript file''' if '?' in filename and len(filename.split('?')) is 2: filename, params = filename.split('?') ...
A shortcut to render a ``script`` tag for the packaged jQuery def jquery_js(version=None, migrate=False): '''A shortcut to render a ``script`` tag for the packaged jQuery''' version = version or settings.JQUERY_VERSION suffix = '.min' if not settings.DEBUG else '' libs = [js_lib('jquery-%s%s.js' % (ver...
Include Django.js javascript library in the page def django_js(context, jquery=True, i18n=True, csrf=True, init=True): '''Include Django.js javascript library in the page''' return { 'js': { 'minified': not settings.DEBUG, 'jquery': _boolean(jquery), 'i18n': _boolean...