@classmethod<EOL><INDENT>def from_conf(cls, path=None, **overrides):<DEDENT>

from onedrive import portalocker<EOL>import yaml<EOL>if path is None:<EOL><INDENT>path = cls.conf_path_default<EOL>log.debug('<STR_LIT>', path)<EOL><DEDENT>path = os.path.expanduser(path)<EOL>with open(path, '<STR_LIT:rb>') as src:<EOL><INDENT>portalocker.lock(src, portalocker.LOCK_SH)<EOL>yaml_str = src.read()<EOL>portalocker.unlock(src)<EOL><DEDENT>conf = yaml.safe_load(yaml_str)<EOL>conf.setdefault('<STR_LIT>', path)<EOL>conf_cls = dict()<EOL>for ns, keys in cls.conf_update_keys.viewitems():<EOL><INDENT>for k in keys:<EOL><INDENT>try:<EOL><INDENT>v = conf.get(ns, dict()).get(k)<EOL><DEDENT>except AttributeError:<EOL><INDENT>if not cls.conf_raise_structure_errors: raise<EOL>raise KeyError((<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' ).format(ns=ns, k=k, path=path))<EOL><DEDENT>if v is not None: conf_cls['<STR_LIT>'.format(ns, k)] = conf[ns][k]<EOL><DEDENT><DEDENT>conf_cls.update(overrides)<EOL>if isinstance(conf.get('<STR_LIT>', dict()).get('<STR_LIT:id>'), (int, long)):<EOL><INDENT>log.warn( '<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>', path )<EOL>cid = conf['<STR_LIT>']['<STR_LIT:id>']<EOL>if not re.search(r'<STR_LIT>'.format(cid), yaml_str)and re.search(r'<STR_LIT>'.format(cid), yaml_str):<EOL><INDENT>cid = int('<STR_LIT>'.format(cid))<EOL><DEDENT>conf['<STR_LIT>']['<STR_LIT:id>'] = '<STR_LIT>'.format(cid)<EOL><DEDENT>self = cls(**conf_cls)<EOL>self.conf_save = conf['<STR_LIT>']<EOL>return self<EOL>

Initialize instance from YAML configuration file,
                writing updates (only to keys, specified by "conf_update_keys") back to it.


session.headers.update({<EOL>'<STR_LIT:Content-Type>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>})<EOL>return session<EOL>

Add content type header to the session.

:param: requests.sessions.Session session: A session.
:return: A session with modified headers.
:rtype: requests.sessions.Session


def set_delivery_system(self, store, postcode, fulfilment_method=FULFILMENT_METHOD.DELIVERY):

method = '<STR_LIT>' if fulfilment_method == FULFILMENT_METHOD.DELIVERY else '<STR_LIT>'<EOL>params = {<EOL>'<STR_LIT>': method,<EOL>'<STR_LIT>': postcode,<EOL>'<STR_LIT>': store.store_id<EOL>}<EOL>return self.__post('<STR_LIT>', json=params)<EOL>

Set local cookies by initialising the delivery system on the remote.
Requires a store ID and a delivery postcode.

:param Store store: Store id.
:param string postcode: A postcode.
:return: A response having initialised the delivery system.
:rtype: requests.Response


return self.get_stores(postcode).local_store<EOL>

Search for domino pizza stores using a postcode. This will only search
for local stores indicating delivery status and payment details.

:param string postcode: A postcode.
:return: A response containing stores matching the postcode.
:rtype: requests.Response


response = self.__get('<STR_LIT>')<EOL>return Basket(response.json())<EOL>

Retrieve the basket for the current session.

:return: A response containing the basket for the current session.
:rtype: requests.Response


def add_pizza_to_basket(self, item, variant=VARIANT.MEDIUM, quantity=<NUM_LIT:1>):

item_variant = item[variant]<EOL>ingredients = item_variant['<STR_LIT>'].update([<NUM_LIT>, <NUM_LIT>])<EOL>params = {<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': quantity,<EOL>'<STR_LIT>': variant,<EOL>'<STR_LIT>': item.item_id,<EOL>'<STR_LIT>': ingredients,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': [],<EOL>'<STR_LIT>': <NUM_LIT:0><EOL>}<EOL>return self.__post('<STR_LIT>', json=params)<EOL>

Add a pizza to the current basket.

:param Item item: Item from menu.
:param int variant: Item SKU id. Some defaults are defined in the VARIANT enum.
:param int quantity: The quantity of pizza to be added.
:return: A response having added a pizza to the current basket.
:rtype: requests.Response


with open('<STR_LIT>') as infile:<EOL><INDENT>return infile.read()<EOL><DEDENT>


def seek(self, offset, whence=<NUM_LIT:0>):

if self.closed:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if whence == SEEK_SET:<EOL><INDENT>pos = offset<EOL><DEDENT>elif whence == SEEK_CUR:<EOL><INDENT>pos = self.pos + offset<EOL><DEDENT>elif whence == SEEK_END:<EOL><INDENT>pos = self.size + offset<EOL><DEDENT>if not <NUM_LIT:0> <= pos <= self.size:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(pos, self.size))<EOL><DEDENT>self.pos = pos<EOL>return self.pos<EOL>

Same as `file.seek()` but for the slice. Returns a value between
`self.start` and `self.size` inclusive.

raises:
    ValueError if the new seek position is not between 0 and
    `self.size`.


return self.start + self.size - <NUM_LIT:1><EOL>

The end position of the slice. The slice will not read or write if the
new position is ahead of this value.


def __exit__(self, exc_type, exc_value, exc_tb):

<EOL>if self._debug >= <NUM_LIT:1> and exc_type is not None:<EOL><INDENT>traceback.print_exception(exc_type, exc_value, exc_tb,<EOL>file=sys.stderr)<EOL>sys.exit('<STR_LIT>' %<EOL>(self.method, self.ext_cls.__module__,<EOL>self.ext_cls.__name__))<EOL>return False<EOL><DEDENT>self.ext_cls = None<EOL>return exc_type and issubclass(exc_type, Exception)<EOL>

Called upon exit from the context manager.  Implements the
debugging output.

:param exc_type: The exception type.  If no exception was
                 generated, will be ``None``.
:param exc_value: The exception value.  If no exception was
                  generated, will be ``None``.
:param exc_tb: The exception traceback.  If no exception was
               generated, will be ``None``.

:returns: A ``True`` value if any exception should be ignored,
          ``False`` otherwise.  Will return ``True`` for all
          ``Exception`` subclasses unless debugging is
          enabled.


if cls._extension_classes is None:<EOL><INDENT>exts = {}<EOL>for ext in entry.points[NAMESPACE_EXTENSIONS]:<EOL><INDENT>exts.setdefault(ext.priority, [])<EOL>exts[ext.priority].append(ext)<EOL><DEDENT>cls._extension_classes = list(utils.iter_prio_dict(exts))<EOL><DEDENT>return cls._extension_classes<EOL>

Retrieve the extension classes in priority order.

:returns: A list of extension classes, in proper priority
          order.


def post_step(self, ctxt, step, idx, result):

debugger = ExtensionDebugger('<STR_LIT>')<EOL>for ext in self.exts:<EOL><INDENT>with debugger(ext):<EOL><INDENT>ext.post_step(ctxt, step, idx, result)<EOL><DEDENT><DEDENT>return result<EOL>

Called after executing a step.

:param ctxt: An instance of ``timid.context.Context``.
:param step: An instance of ``timid.steps.Step`` describing
             the step that was executed.
:param idx: The index of the step in the list of steps.
:param result: An instance of ``timid.steps.StepResult``
               describing the result of executing the step.
               May be altered by the extension, e.g., to set
               the ``ignore`` attribute.

:returns: The ``result`` parameter, for convenience.


pass<EOL>

Called after reading steps, prior to adding them to the list of
test steps.  This allows an extension to alter the list (in
place).

:param ctxt: An instance of ``timid.context.Context``.
:param steps: A list of ``timid.steps.Step`` instances.


<EOL>self.method = method<EOL>self.ext_cls = None<EOL>debug = os.environ.get('<STR_LIT>')<EOL>if debug is None:<EOL><INDENT>self._debug = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>self._debug = max(<NUM_LIT:0>, int(debug))<EOL><DEDENT>except ValueError:<EOL><INDENT>self._debug = <NUM_LIT:1><EOL><DEDENT><DEDENT>self.debug(<NUM_LIT:2>, '<STR_LIT>' % self.method)<EOL>

Initialize an ``ExtensionDebugger`` instance.

:param where: A string indicating the name of the extension
              method that will be called.


pass<EOL>

An integer value.  This provides a primitive means of controlling
the order in which extensions will be called.  The higher the
number, the later the modifier will be applied.

This must be a class attribute, not a property.


return None<EOL>

Called prior to executing a step.

:param ctxt: An instance of ``timid.context.Context``.
:param step: An instance of ``timid.steps.Step`` describing
             the step to be executed.
:param idx: The index of the step in the list of steps.

:returns: A ``True`` value if the step is to be skipped.  Any
          ``False`` value (including ``None``) will result in
          the step being executed as normal.


debugger = ExtensionDebugger('<STR_LIT>')<EOL>for ext in self.exts:<EOL><INDENT>with debugger(ext):<EOL><INDENT>ext.read_steps(ctxt, steps)<EOL><DEDENT><DEDENT>return steps<EOL>

Called after reading steps, prior to adding them to the list of
test steps.  Extensions are able to alter the list (in place).

:param ctxt: An instance of ``timid.context.Context``.
:param steps: A list of ``timid.steps.Step`` instances.

:returns: The ``steps`` parameter, for convenience.


def __init__(self, step_addr, action, modifiers=None, name=None,<EOL>description=None):

self.step_addr = step_addr<EOL>self.action = action<EOL>self.modifiers = modifiers or []<EOL>self.name = name or action.__class__.__name__<EOL>self.description = description<EOL>

Initialize a ``Step`` instance.

:param step_addr: The address of the step in the test
                  configuration.
:param action: An ``Action`` instance.
:param modifiers: A list of ``Modifier`` instances, in the
                  order in which processing should be
                  performed.  Optional.
:param name: A name for the step.  Optional.
:param description: A description of the step.  Optional.


def action_conf(self, ctxt, action_class, action_name, config, step_addr):

return config<EOL>

A modifier hook function.  This is called in priority order prior
to initializing the ``Action`` for the step.  This allows a
modifier to alter the configuration to be fed to the action.

:param ctxt: The context object.
:param action_class: The ``Action`` subclass the modifier is
                     modifying.  This method should not
                     attempt to initialize the action.
:param action_name: The name of the action.
:param config: The configuration for the action.  This may be
               a scalar value (e.g., "run: command"), a list,
               or a dictionary.  If the configuration provided
               is invalid for the action, a ``ConfigError``
               should be raised.
:param step_addr: The address of the step in the test
                  configuration.  Should be passed to the
                  ``ConfigError``.

:returns: The configuration for the action, optionally
          modified.  If the configuration is not modified,
          ``config`` must be returned unchanged.  The default
          implementation of this method does so.


return self._ignore or False<EOL>

Determine whether an error result should be ignored.


def post_call(self, ctxt, result, action, post_mod, pre_mod):

return result<EOL>

A modifier hook function.  This is called in reverse-priority
order after invoking the ``Action`` for the step.  This allows
a modifier to inspect or alter the result of the step.

:param ctxt: The context object.
:param result: The result of the action.  This will be a
               ``StepResult`` object.
:param action: The action that was performed.
:param post_mod: A list of modifiers following this modifier
                 in the list of modifiers that is applicable
                 to the action.  This list is in priority
                 order.
:param pre_mod: A list of modifiers preceding this modifier in
                the list of modifiers that is applicable to
                the action.  This list is in priority order.

:returns: The result for the action, optionally modified.  If
          the result is not modified, ``result`` must be
          returned unchanged.  The default implementation of
          this method does so.


pass<EOL>

An integer value.  This provides a primitive means of controlling
the order of application of modifiers.  The higher the number,
the later the modifier will be applied.  The action has a
priority equivalent to positive infinity.

This must be a class attribute, not a property.


def __init__(self, fname, idx, key=None):

self.fname = fname<EOL>self.idx = idx<EOL>self.key = key<EOL>self._str = None<EOL>

Initialize a ``StepAddress`` instance.

:param fname: The file name of the YAML file.
:param idx: The index of the step within the file, or within
            the designated key of the file.
:param key: A key within the file.  If the file consists of a
            single list, this should be ``None`` (the
            default).


def __init__(self, ctxt, name, config, step_addr):

<EOL>self.validate_conf(name, config, step_addr)<EOL>self.name = name<EOL>self.config = config<EOL>self.step_addr = step_addr<EOL>

Initialize the action or modifier.  This should process and store
the configuration provided.

:param ctxt: The context object.
:param name: The name.
:param config: The configuration.  This may be a scalar value
               (e.g., "run: command"), a list, or a
               dictionary.  If the configuration provided is
               invalid, a ``ConfigError`` should be raised.
:param step_addr: The address of the step in the test
                  configuration.  Should be passed to the
                  ``ConfigError``.


<EOL>super(SensitiveDictAction, self).__init__(<EOL>ctxt, name, config, step_addr)<EOL>self.set_vars = {}<EOL>for key, value in config.get('<STR_LIT>', {}).items():<EOL><INDENT>self.set_vars[key] = ctxt.template(value)<EOL><DEDENT>self.unset_vars = set(config.get('<STR_LIT>', []))<EOL>self.sensitive_vars = set(config.get('<STR_LIT>', []))<EOL>self.files = [ctxt.template(fn) for fn in config.get('<STR_LIT>', [])]<EOL>self.dirname = os.path.dirname(step_addr.fname) or os.curdir<EOL>

Initialize a ``SensitiveDictAction`` instance.

:param ctxt: The context object.
:param name: The name of the action.
:param config: The configuration for the action.  This may be
               a scalar value (e.g., "run: command"), a list,
               or a dictionary.  If the configuration provided
               is invalid for the action, a ``ConfigError``
               should be raised.
:param step_addr: The address of the step in the test
                  configuration.  Should be passed to the
                  ``ConfigError``.


return self.cls(ctxt, self.name, self.conf, step_addr)<EOL>

Initialize the item.  This calls the class constructor with the
appropriate arguments and returns the initialized object.

:param ctxt: The context object.
:param step_addr: The address of the step in the test
                  configuration.


self._namespaces = {}<EOL>


<EOL>self.namespace = namespace<EOL>self._entrypoints = {}<EOL>for ep in pkg_resources.iter_entry_points(namespace):<EOL><INDENT>self._entrypoints.setdefault(ep.name, [])<EOL>self._entrypoints[ep.name].append(ep)<EOL><DEDENT>self._epcache = {}<EOL>self._eplist = None<EOL>

Initialize a ``NamespaceCache``.

:param namespace: The namespace to cache.


<EOL>if (name not in self._entrypoints or<EOL>self._epcache.get(name) is _unavailable):<EOL><INDENT>raise KeyError(name)<EOL><DEDENT>if name not in self._epcache:<EOL><INDENT>error = None<EOL>for ep in self._entrypoints[name]:<EOL><INDENT>try:<EOL><INDENT>self._epcache[name] = ep.load()<EOL><DEDENT>except (ImportError, AttributeError,<EOL>pkg_resources.UnknownExtra):<EOL><INDENT>if error is None:<EOL><INDENT>error = sys.exc_info()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._epcache[name] = _unavailable<EOL>if error is None:<EOL><INDENT>raise KeyError(name)<EOL><DEDENT>six.reraise(*error)<EOL><DEDENT><DEDENT>return self._epcache[name]<EOL>

Retrieve the designated entrypoint object.

:param name: The name of the entrypoint.

:returns: The loaded object referenced by the entrypoint.


def __init__(self, verbose=<NUM_LIT:1>, debug=False, cwd=None):

<EOL>self.verbose = verbose<EOL>self.debug = debug<EOL>self.variables = utils.SensitiveDict()<EOL>self.environment = environment.Environment(cwd=cwd)<EOL>self.steps = []<EOL>self._jinja = jinja2.Environment()<EOL>self._jinja.globals['<STR_LIT>'] = self.environment<EOL>


def emit(self, msg, level=<NUM_LIT:1>, debug=False):

<EOL>if debug:<EOL><INDENT>if not self.debug:<EOL><INDENT>return<EOL><DEDENT>stream = sys.stderr<EOL><DEDENT>else:<EOL><INDENT>if self.verbose < level:<EOL><INDENT>return<EOL><DEDENT>stream = sys.stdout<EOL><DEDENT>print(msg, file=stream)<EOL>stream.flush()<EOL>

Emit a message to the user.

:param msg: The message to emit.  If ``debug`` is ``True``,
            the message will be emitted to ``stderr`` only if
            the ``debug`` attribute is ``True``.  If ``debug``
            is ``False``, the message will be emitted to
            ``stdout`` under the control of the ``verbose``
            attribute.
:param level: Ignored if ``debug`` is ``True``.  The message
              will only be emitted if the ``verbose``
              attribute is greater than or equal to the value
              of this parameter.  Defaults to 1.
:param debug: If ``True``, marks the message as a debugging
              message.  The message will only be emitted if
              the ``debug`` attribute is ``True``.


<EOL>if not isinstance(string, six.string_types):<EOL><INDENT>return lambda ctxt: string<EOL><DEDENT>expr = self._jinja.compile_expression(string)<EOL>return lambda ctxt: expr(ctxt.variables)<EOL>

Interpret an expression string.  This returns a callable taking
one argument--this context--and returning the result of
evaluating the expression.

:param string: The expression.

:returns: A callable of one argument that will return the
          desired expression.


<EOL>result.ignore = self.config<EOL>return result<EOL>

A modifier hook function.  This is called in reverse-priority
order after invoking the ``Action`` for the step.  This allows
a modifier to inspect or alter the result of the step.

:param ctxt: The context object.
:param result: The result of the action.  This will be a
               ``StepResult`` object.
:param action: The action that was performed.
:param post_mod: A list of modifiers following this modifier
                 in the list of modifiers that is applicable
                 to the action.  This list is in priority
                 order.
:param pre_mod: A list of modifiers preceding this modifier in
                the list of modifiers that is applicable to
                the action.  This list is in priority order.

:returns: The result for the action, optionally modified.  If
          the result is not modified, ``result`` must be
          returned unchanged.  This implementation alters the
          ``ignore`` property of the ``result`` object to
          match the configured value.


def __init__(self, option_strings, dest, **kwargs):

<EOL>allow_type = kwargs.pop('<STR_LIT>', False)<EOL>super(DictAction, self).__init__(option_strings, dest, **kwargs)<EOL>self.allow_type = allow_type<EOL>

Initialize a ``DictAction`` object.

:param option_strings: A list of option strings.
:param dest: The target attribute to store the option values
             in.
:param allow_type: A boolean indicating whether the value type
                   may be designated.  If ``False``, the value
                   type is always treated as a string.


self._value.add(item)<EOL>self._rebuild()<EOL>

Add a new item to the ``SetVariable`` instance.

:param item: The item to add.


pass<EOL>

The abstract type the value should be represented as, e.g.,
``collections.Set`` or ``collections.Sequence``.


def declare_set(self, name, sep=os.pathsep):

self._declare_special(name, sep, SetVariable)<EOL>

Declare an environment variable as a set-like special variable.
This can be used even if the environment variable is not
present.

:param name: The name of the environment variable that should
             be considered set-like.
:param sep: The separator to be used.  Defaults to the value
            of ``os.pathsep``.


if not value:<EOL><INDENT>value = self._coerce()<EOL><DEDENT>elif isinstance(value, six.string_types):<EOL><INDENT>value = self._coerce(value.split(self._sep))<EOL><DEDENT>else:<EOL><INDENT>value = self._coerce(value)<EOL><DEDENT>self._value = value<EOL>

Alert method used when the variable's value in an ``Environment``
instance has been altered.

:param value: The new value to set the value to.


<EOL>if name not in self._data:<EOL><INDENT>raise KeyError(name)<EOL><DEDENT>if name in self._special:<EOL><INDENT>return self._special[name]<EOL><DEDENT>return self._data[name]<EOL>

Retrieve the value of a variable from the environment.  If the
variable has been declared as a list-like variable, the return
value will be a list of strings; otherwise, it will be a
string.

:param name: The name of the variable to retrieve.

:returns: The value of the designated variable.


return self._env._data.get(self._var) or '<STR_LIT>'<EOL>

Obtain a string form of the ``EnvListVariable`` instance.

:returns: The string form of the variable.


return len(self._value)<EOL>

Obtain the length of an ``EnvListVariable`` instance.

:returns: The number of elements in the variable.


self._value[idx] = value<EOL>self._rebuild()<EOL>

Set an item on the ``ListVariable`` instance.

:param idx: The index or index-like object (e.g., slice) to
            set.
:param value: The value to set it to.


return self._value[idx]<EOL>

Retrieve an item from a ``ListVariable`` instance.

:param idx: The index or index-like object (e.g., slice) to
            retrieve.

:returns: The value at the designated index.


del self._value[idx]<EOL>self._rebuild()<EOL>

Delete an item from the ``ListVariable`` instance.

:param idx: The index or index-like object (e.g., slice) to
            delete.


return len(self._parent)<EOL>

Obtain the length of a ``MaskedDict`` instance.

:returns: The number of keys in the dictionary.


return frozenset(self._sensitive)<EOL>

Retrieve a set of the "sensitive" keys, keys for which the data
should be treated as sensitive.  This will be a copy;
modifications will not affect the set.


return self.__class__(self._data.copy(), self._sensitive.copy())<EOL>

Retrieve a copy of the sensitive dictionary.  Note that this is a
shallow copy.


def schema_validate(instance, schema, exc_class, *prefix, **kwargs):

try:<EOL><INDENT>jsonschema.validate(instance, schema)<EOL><DEDENT>except jsonschema.ValidationError as exc:<EOL><INDENT>path = '<STR_LIT:/>'.join((a if isinstance(a, six.string_types) else '<STR_LIT>' % a)<EOL>for a in itertools.chain(prefix, exc.path))<EOL>message = '<STR_LIT>' % (path, exc.message)<EOL>raise exc_class(message, **kwargs)<EOL><DEDENT>

Schema validation helper.  Performs JSONSchema validation.  If a
schema validation error is encountered, an exception of the
designated class is raised with the validation error message
appropriately simplified and passed as the sole positional
argument.

:param instance: The object to schema validate.
:param schema: The schema to use for validation.
:param exc_class: The exception class to raise instead of the
                  ``jsonschema.ValidationError`` exception.
:param prefix: Positional arguments are interpreted as a list of
               keys to prefix to the path contained in the
               validation error.
:param kwargs: Keyword arguments to pass to the exception
               constructor.


if not os.path.isabs(path):<EOL><INDENT>path = os.path.join(cwd, path)<EOL><DEDENT>return os.path.abspath(path)<EOL>

Canonicalizes a path relative to a given working directory.  That
is, the path, if not absolute, is interpreted relative to the
working directory, then converted to absolute form.

:param cwd: The working directory.
:param path: The path to canonicalize.

:returns: The absolute path.


return self._parent.sensitive<EOL>


return six.text_type(dict(self))<EOL>

Obtain a string form of a ``MaskedDict`` instance.

:returns: The string form of the ``MaskedDict`` instance.


def assert_connected(self, conn, client):

Assert that a connection is connected to a client.


def abortConnection():<EOL><INDENT>protocol._fake_connection_aborted = True<EOL>transport.loseConnection()<EOL><DEDENT>patch_if_missing(transport, '<STR_LIT>', abortConnection)<EOL>

Patch abortConnection() onto the transport if it doesn't already have it.
(`Agent` assumes its transport has this.)


from twisted.internet import reactor<EOL>return deferLater(reactor, <NUM_LIT:0>, lambda: r)<EOL>

Wait zero seconds to give the reactor a chance to work.

Returns its (optional) argument, so it's useful as a callback.


return FakeServerEndpoint(self)<EOL>

Get an endpoint that connects clients to this server.


assert self.pending, "<STR_LIT>"<EOL>if reason is None:<EOL><INDENT>reason = ConnectionRefusedError()<EOL><DEDENT>self._accept_d.errback(reason)<EOL>


return self._finished_d<EOL>

Wait for the both sides of the connection to close.


def row_to_dict(self, row, allele, alternate_alleles):

def _variant_sbid(**kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>return '<STR_LIT>'.format(**kwargs).upper()<EOL><DEDENT>if allele == '<STR_LIT:.>':<EOL><INDENT>allele = row.REF or allele<EOL><DEDENT>genomic_coordinates = {<EOL>'<STR_LIT>': self.genome_build,<EOL>'<STR_LIT>': row.CHROM,<EOL>'<STR_LIT:start>': row.POS,<EOL>'<STR_LIT>': row.POS + len(row.REF) - <NUM_LIT:1><EOL>}<EOL>variant_sbid = _variant_sbid(allele=allele,<EOL>**genomic_coordinates)<EOL>return {<EOL>'<STR_LIT>': genomic_coordinates,<EOL>'<STR_LIT>': variant_sbid,<EOL>'<STR_LIT>': allele,<EOL>'<STR_LIT>': row.ID,<EOL>'<STR_LIT>': row.REF,<EOL>'<STR_LIT>': alternate_alleles,<EOL>'<STR_LIT:info>': self._parse_info(row.INFO),<EOL>'<STR_LIT>': row.QUAL,<EOL>'<STR_LIT>': row.FILTER<EOL>}<EOL>


def _alt(alt):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not alt:<EOL><INDENT>return '<STR_LIT:.>'<EOL><DEDENT>else:<EOL><INDENT>return str(alt)<EOL><DEDENT><DEDENT>if not self._next:<EOL><INDENT>row = next(self.reader)<EOL>alternate_alleles = list(map(_alt, row.ALT))<EOL>for allele in alternate_alleles:<EOL><INDENT>self._next.append(<EOL>self.row_to_dict(<EOL>row,<EOL>allele=allele,<EOL>alternate_alleles=alternate_alleles))<EOL><DEDENT>self._line_number += <NUM_LIT:1><EOL><DEDENT>return self._next.pop()<EOL>

Expands multiple alleles into one record each
using an internal buffer (_next).


return layout()<EOL>

Render the layout depending on the pathname.


if self._oauth_client_secret:<EOL><INDENT>try:<EOL><INDENT>oauth_token = flask.request.cookies[self.TOKEN_COOKIE_NAME]<EOL>requests.post(<EOL>urljoin(self._api_host, self.OAUTH2_REVOKE_TOKEN_PATH),<EOL>data={<EOL>'<STR_LIT>': self._oauth_client_id,<EOL>'<STR_LIT>': self._oauth_client_secret,<EOL>'<STR_LIT>': oauth_token<EOL>})<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>response = flask.redirect('<STR_LIT:/>')<EOL>self.clear_cookies(response)<EOL>return response<EOL>


kwargs['<STR_LIT>'] = params<EOL>return self.request('<STR_LIT:GET>', url, **kwargs)<EOL>

Issues an HTTP GET across the wire via the Python requests
        library. See *request()* for information on keyword args.


kwargs['<STR_LIT:data>'] = data<EOL>return self.request('<STR_LIT>', url, **kwargs)<EOL>

Issues an HTTP DELETE across the wire via the Python requests
        library. See *request* for information on keyword args.


alignment = {"<STR_LIT:left>": '<STR_LIT>',<EOL>"<STR_LIT:right>": '<STR_LIT>',<EOL>"<STR_LIT>": '<STR_LIT>',<EOL>"<STR_LIT>": '<STR_LIT>'}<EOL>row2 = [alignment[a] + c for c, a in zip(row, colaligns)]<EOL>return row2<EOL>

Prefix every cell in a row with an HTML alignment attribute.


types = [_type(s, has_invisible) for s in strings]<EOL>return reduce(_more_generic, types, int)<EOL>

The least generic type all column values are convertible to.

>>> _column_type(["1", "2"]) is _int_type
True
>>> _column_type(["1", "2.3"]) is _float_type
True
>>> _column_type(["1", "2.3", "four"]) is _text_type
True
>>> _column_type(["four", '\u043f\u044f\u0442\u044c']) is _text_type
True
>>> _column_type([None, "brux"]) is _text_type
True
>>> _column_type([1, 2, None]) is _int_type
True


def _format(val, valtype, floatfmt, missingval="<STR_LIT>"):

if val is None:<EOL><INDENT>return missingval<EOL><DEDENT>if valtype in [int, _binary_type, _text_type]:<EOL><INDENT>return "<STR_LIT>".format(val)<EOL><DEDENT>elif valtype is float:<EOL><INDENT>return format(float(val), floatfmt)<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>".format(val)<EOL><DEDENT>


def _normalize_tabular_data(tabular_data, headers, sort=True):

if hasattr(tabular_data, "<STR_LIT>") and hasattr(tabular_data, "<STR_LIT>"):<EOL><INDENT>if hasattr(tabular_data.values, "<STR_LIT>"):<EOL><INDENT>keys = list(tabular_data.keys())<EOL>rows = list(izip_longest(*list(tabular_data.values())))<EOL><DEDENT>elif hasattr(tabular_data, "<STR_LIT:index>"):<EOL><INDENT>keys = list(tabular_data.keys())<EOL>vals = tabular_data.values<EOL>names = tabular_data.index<EOL>rows = [[v] + list(row) for v, row in zip(names, vals)]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if headers == "<STR_LIT>":<EOL><INDENT>headers = list(map(_text_type, keys))  <EOL><DEDENT><DEDENT>else:  <EOL><INDENT>rows = list(tabular_data)<EOL>if headers == "<STR_LIT>" and len(rows) > <NUM_LIT:0>:  <EOL><INDENT>headers = list(map(_text_type, list(range(len(rows[<NUM_LIT:0>])))))<EOL><DEDENT><DEDENT>if headers == "<STR_LIT>" and len(rows) > <NUM_LIT:0>:<EOL><INDENT>headers = list(map(_text_type, rows[<NUM_LIT:0>]))  <EOL>rows = rows[<NUM_LIT:1>:]<EOL><DEDENT>headers = list(headers)<EOL>rows = list(map(list, rows))<EOL>if sort and len(rows) > <NUM_LIT:1>:<EOL><INDENT>rows = sorted(rows, key=lambda x: x[<NUM_LIT:0>])<EOL><DEDENT>if headers and len(rows) > <NUM_LIT:0>:<EOL><INDENT>nhs = len(headers)<EOL>ncols = len(rows[<NUM_LIT:0>])<EOL>if nhs < ncols:<EOL><INDENT>headers = ["<STR_LIT>"] * (ncols - nhs) + headers<EOL><DEDENT><DEDENT>return rows, headers<EOL>

Transform a supported data type to a list of lists, and a list of headers.

Supported tabular data types:

* list-of-lists or another iterable of iterables

* 2D NumPy arrays

* dict of iterables (usually used with headers="keys")

* pandas.DataFrame (usually used with headers="keys")

The first row can be used as headers if headers="firstrow",
column indices can be used as headers if headers="keys".


def _padleft(width, s, has_invisible=True):

iwidth = width + len(s) - len(_strip_invisible(s))if has_invisible else width<EOL>fmt = "<STR_LIT>" % iwidth<EOL>return fmt.format(s)<EOL>


def _line_segment_with_colons(linefmt, align, colwidth):

fill = linefmt.hline<EOL>w = colwidth<EOL>if align in ["<STR_LIT:right>", "<STR_LIT>"]:<EOL><INDENT>return (fill[<NUM_LIT:0>] * (w - <NUM_LIT:1>)) + "<STR_LIT::>"<EOL><DEDENT>elif align == "<STR_LIT>":<EOL><INDENT>return "<STR_LIT::>" + (fill[<NUM_LIT:0>] * (w - <NUM_LIT:2>)) + "<STR_LIT::>"<EOL><DEDENT>elif align == "<STR_LIT:left>":<EOL><INDENT>return "<STR_LIT::>" + (fill[<NUM_LIT:0>] * (w - <NUM_LIT:1>))<EOL><DEDENT>else:<EOL><INDENT>return fill[<NUM_LIT:0>] * w<EOL><DEDENT>

Return a segment of a horizontal line with optional colons which
    indicate column's alignment (as in `pipe` output format).


if has_invisible and(isinstance(string, _text_type) or isinstance(string, _binary_type)):<EOL><INDENT>string = _strip_invisible(string)<EOL><DEDENT>if string is None:<EOL><INDENT>return _none_type<EOL><DEDENT>elif _isint(string):<EOL><INDENT>return _int_type<EOL><DEDENT>elif _isnumber(string):<EOL><INDENT>return float<EOL><DEDENT>elif isinstance(string, _binary_type):<EOL><INDENT>return _binary_type<EOL><DEDENT>else:<EOL><INDENT>return _text_type<EOL><DEDENT>

The least generic type (type(None), int, float, str, unicode).

>>> _type(None) is type(None)
True
>>> _type("foo") is type("")
True
>>> _type("1") is type(1)
True
>>> _type('\x1b[31m42\x1b[0m') is type(42)
True
>>> _type('\x1b[31m42\x1b[0m') is type(42)
True


def _build_line(colwidths, padding, begin, fill, sep, end):

cells = [fill * (w + <NUM_LIT:2> * padding) for w in colwidths]<EOL>return _build_row(cells, <NUM_LIT:0>, begin, sep, end)<EOL>

Return a string which represents a horizontal line.


def naturalsize(value, binary=False, gnu=False, format='<STR_LIT>'):

if gnu:<EOL><INDENT>suffix = suffixes['<STR_LIT>']<EOL><DEDENT>elif binary:<EOL><INDENT>suffix = suffixes['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>suffix = suffixes['<STR_LIT>']<EOL><DEDENT>base = <NUM_LIT> if (gnu or binary) else <NUM_LIT:1000><EOL>bytes = float(value)<EOL>if bytes == <NUM_LIT:1> and not gnu:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>elif bytes < base and not gnu:<EOL><INDENT>return '<STR_LIT>' % bytes<EOL><DEDENT>elif bytes < base and gnu:<EOL><INDENT>return '<STR_LIT>' % bytes<EOL><DEDENT>for i, s in enumerate(suffix):<EOL><INDENT>unit = base ** (i + <NUM_LIT:2>)<EOL>if bytes < unit and not gnu:<EOL><INDENT>return (format + '<STR_LIT>') % ((base * bytes / unit), s)<EOL><DEDENT>elif bytes < unit and gnu:<EOL><INDENT>return (format + '<STR_LIT:%s>') % ((base * bytes / unit), s)<EOL><DEDENT><DEDENT>if gnu:<EOL><INDENT>return (format + '<STR_LIT:%s>') % ((base * bytes / unit), s)<EOL><DEDENT>return (format + '<STR_LIT>') % ((base * bytes / unit), s)<EOL>

Format a number of byteslike a human readable filesize (eg. 10 kB).  By
    default, decimal suffixes (kB, MB) are used.  Passing binary=true will use
    binary suffixes (KiB, MiB) are used and the base will be 2**10 instead of
    10**3.  If ``gnu`` is True, the binary argument is ignored and GNU-style
    (ls -sh style) prefixes are used (K, M) with the 2**10 definition.
    Non-gnu modes are compatible with jinja2's ``filesizeformat`` filter.


def evaluate(self, data=None, data_type='<STR_LIT:string>', is_list=False):

payload = {<EOL>'<STR_LIT:data>': data,<EOL>'<STR_LIT>': self.expr,<EOL>'<STR_LIT>': data_type,<EOL>'<STR_LIT>': is_list<EOL>}<EOL>res = self._client.post('<STR_LIT>', payload)<EOL>return res['<STR_LIT:result>']<EOL>

Evaluates the expression with the provided context and format.


def _combine(self, other, conn='<STR_LIT>'):

f = Filter()<EOL>f.deepcopy = self.deepcopy and other.filters<EOL>if f.deepcopy:<EOL><INDENT>self_filters = copy.deepcopy(self.filters)<EOL>other_filters = copy.deepcopy(other.filters)<EOL><DEDENT>else:<EOL><INDENT>self_filters = self.filters<EOL>other_filters = other.filters<EOL><DEDENT>if not self.filters:<EOL><INDENT>f.filters = other_filters<EOL><DEDENT>elif not other.filters:<EOL><INDENT>f.filters = self_filters<EOL><DEDENT>elif conn in self.filters[<NUM_LIT:0>]:<EOL><INDENT>f.filters = self_filters<EOL>f.filters[<NUM_LIT:0>][conn].extend(other_filters)<EOL><DEDENT>elif conn in other.filters[<NUM_LIT:0>]:<EOL><INDENT>f.filters = other_filters<EOL>f.filters[<NUM_LIT:0>][conn].extend(self_filters)<EOL><DEDENT>else:<EOL><INDENT>f.filters = [{conn: self_filters + other_filters}]<EOL><DEDENT>return f<EOL>

OR and AND will create a new Filter, with the filters from both Filter
objects combined with the connector `conn`.


if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.__iter__()<EOL><DEDENT>if self._cursor == len(self):<EOL><INDENT>raise StopIteration()<EOL><DEDENT>if self._buffer_idx == len(self._buffer):<EOL><INDENT>self.execute(self._page_offset + self._buffer_idx)<EOL>self._buffer_idx = <NUM_LIT:0><EOL><DEDENT>self._cursor += <NUM_LIT:1><EOL>self._buffer_idx += <NUM_LIT:1><EOL>return self._buffer[self._buffer_idx - <NUM_LIT:1>]<EOL>

Allows the Query object to be an iterable.

This method will iterate through a cached result set
and fetch successive pages as required.

A `StopIteration` exception will be raised when there aren't
any more results available or when the requested result
slice range or limit has been fetched.

Returns: The next result.


self._dataset_id = dataset_id<EOL>self._data_url = '<STR_LIT>'.format(dataset_id)<EOL>self._query = query<EOL>self._genome_build = genome_build<EOL>self._result_class = result_class<EOL>self._fields = fields<EOL>self._exclude_fields = exclude_fields<EOL>self._entities = entities<EOL>self._ordering = ordering<EOL>self._debug = debug<EOL>self._error = error<EOL>if filters:<EOL><INDENT>if isinstance(filters, Filter):<EOL><INDENT>filters = [filters]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>filters = []<EOL><DEDENT>self._filters = filters<EOL>self._response = None<EOL>self._limit = limit<EOL>self._page_size = int(page_size)<EOL>self._page_offset = None<EOL>self._slice = None<EOL>if self._limit < <NUM_LIT:0>:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>if self._page_size <= <NUM_LIT:0>:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>self._client = kwargs.get('<STR_LIT>') or self._client or client<EOL>

Creates a new Query object.

:Parameters:
  - `dataset_id`: Unique ID of dataset to query.
  - `query` (optional): An optional query string.
  - `genome_build`: The genome build to use for the query.
  - `result_class` (optional): Class of object returned by query.
  - `fields` (optional): List of specific fields to retrieve.
  - `exclude_fields` (optional): List of specific fields to exclude.
  - `entities` (optional): List of entity tuples to filter on.
  - `ordering` (optional): List of fields to order the results by.
  - `filters` (optional): Filter or List of filter objects.
  - `limit` (optional): Maximum number of query results to return.
  - `page_size` (optional): Number of results to fetch per query page.
  - `debug` (optional): Sends debug information to the API.


<EOL>return self.total<EOL>

Returns the total number of results returned by a query.
The count is dependent on the filters, but independent of any limit.
It is like SQL:
   SELECT COUNT(*) FROM <table> [WHERE condition].
See also __len__ for a function that is dependent on limit.


data = []<EOL>for f in filters:<EOL><INDENT>if isinstance(f, Filter):<EOL><INDENT>if f.filters:<EOL><INDENT>data.extend(cls._process_filters(f.filters))<EOL><DEDENT><DEDENT>elif isinstance(f, dict):<EOL><INDENT>key = list(f.keys())[<NUM_LIT:0>]<EOL>val = f[key]<EOL>if isinstance(val, dict):<EOL><INDENT>filter_filters = cls._process_filters([val])<EOL>if len(filter_filters) == <NUM_LIT:1>:<EOL><INDENT>filter_filters = filter_filters[<NUM_LIT:0>]<EOL><DEDENT>data.append({key: filter_filters})<EOL><DEDENT>else:<EOL><INDENT>data.append({key: cls._process_filters(val)})<EOL><DEDENT><DEDENT>else:<EOL><INDENT>data.extend((f,))<EOL><DEDENT><DEDENT>return data<EOL>

Takes a list of filters and returns JSON

        :Parameters:
        - `filters`: List of Filters, (key, val) tuples, or dicts

        Returns: List of JSON API filters


def migrate(self, target, follow=True, **kwargs):

from solvebio import Dataset<EOL>from solvebio import DatasetMigration<EOL>if isinstance(target, Dataset):<EOL><INDENT>target_id = target.id<EOL><DEDENT>else:<EOL><INDENT>target_id = target<EOL><DEDENT>limit = kwargs.pop('<STR_LIT>', None)<EOL>if not limit and self._limit < float('<STR_LIT>'):<EOL><INDENT>limit = self._limit<EOL><DEDENT>params = self._build_query(limit=limit)<EOL>params.pop('<STR_LIT>', None)<EOL>params.pop('<STR_LIT>', None)<EOL>migration = DatasetMigration.create(<EOL>source_id=self._dataset_id,<EOL>target_id=target_id,<EOL>source_params=params,<EOL>client=self._client,<EOL>**kwargs)<EOL>if follow:<EOL><INDENT>migration.follow()<EOL><DEDENT>return migration<EOL>

Migrate the data from the Query to a target dataset.

Valid optional kwargs include:

* target_fields
* include_errors
* validation_params
* metadata
* commit_mode


f = list(filters)<EOL>if kwargs:<EOL><INDENT>f += [Filter(**kwargs)]<EOL><DEDENT>return self._clone(filters=f)<EOL>

Returns this Query instance with the query args combined with
existing set with AND.

kwargs are simply passed to a new Filter object and combined to any
other filters with AND.

By default, everything is combined using AND. If you provide
multiple filters in a single filter call, those are ANDed
together. If you provide multiple filters in multiple filter
calls, those are ANDed together.

If you want something different, use the F class which supports
``&`` (and), ``|`` (or) and ``~`` (not) operators. Then call
filter once with the resulting Filter instance.


if not isinstance(queries, list):<EOL><INDENT>queries = [queries]<EOL><DEDENT>self._queries = queries<EOL>self._client = kwargs.get('<STR_LIT>') or self._client or client<EOL>


if get_credentials():<EOL><INDENT>delete_credentials()<EOL>_print_msg('<STR_LIT>')<EOL><DEDENT>_print_msg('<STR_LIT>')<EOL>

Delete's the user's locally-stored credentials.


email = user['<STR_LIT:email>']<EOL>domain = user['<STR_LIT>']['<STR_LIT>']<EOL>role = user['<STR_LIT>']<EOL>print('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>.format(domain, email, role))<EOL>

Prints information about the current user.


try:<EOL><INDENT>import IPython  <EOL><DEDENT>except ImportError:<EOL><INDENT>_print("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return False<EOL><DEDENT>if hasattr(IPython, "<STR_LIT>"):<EOL><INDENT>if IPython.version_info > (<NUM_LIT:5>, <NUM_LIT:0>, <NUM_LIT:0>, '<STR_LIT>'):<EOL><INDENT>return launch_ipython_5_shell(args)<EOL><DEDENT><DEDENT>_print("<STR_LIT>"<EOL>.format(IPython.__version__))<EOL>return launch_ipython_legacy_shell(args)<EOL>

Open the SolveBio shell (IPython wrapper)


return self.request('<STR_LIT>', self['<STR_LIT:url>'], params=params)<EOL>

Lists all items in a class that you have access to


return self.get(email_pgp_pub_field=email_pgp_pub_field)<EOL>


if model._meta.app_label == '<STR_LIT>':<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return '<STR_LIT:default>'<EOL>


sql, params = super(DecryptedCol, self).as_sql(compiler, connection)<EOL>sql = self.target.get_decrypt_sql(connection) % (sql, self.target.get_cast_sql())<EOL>return sql, params<EOL>


return '<STR_LIT>'<EOL>

Value stored in the database is hexadecimal.


def get_col(self, alias, output_field=None):

if output_field is None:<EOL><INDENT>output_field = self<EOL><DEDENT>if alias != self.model._meta.db_table or output_field != self:<EOL><INDENT>return DecryptedCol(<EOL>alias,<EOL>self,<EOL>output_field<EOL>)<EOL><DEDENT>else:<EOL><INDENT>return self.cached_col<EOL><DEDENT>


def pre_save(self, model_instance, add):

if self.original:<EOL><INDENT>original_value = getattr(model_instance, self.original)<EOL>setattr(model_instance, self.attname, original_value)<EOL><DEDENT>return super(HashMixin, self).pre_save(model_instance, add)<EOL>


def get_placeholder(self, value=None, compiler=None, connection=None):

return self.encrypt_sql.format(get_setting(connection, '<STR_LIT>'))<EOL>

Tell postgres to encrypt this field using PGP.


def get_placeholder(self, value, compiler, connection):

raise NotImplementedError('<STR_LIT>')<EOL>


lhs, lhs_params = self.process_lhs(qn, connection)<EOL>rhs, rhs_params = self.process_rhs(qn, connection)<EOL>params = lhs_params + rhs_params<EOL>rhs = self.lhs.field.encrypt_sql % rhs<EOL>return ('<STR_LIT>'.format(lhs, rhs)), params<EOL>

Responsible for creating the lookup with the digest SQL.

        Modify the right hand side expression to compare the value passed
        to a hash.


return '<STR_LIT:e>' + cls.pgm()<EOL>

Generates available Encapsulated PGM address.


return '<STR_LIT>'.format(rand_str())<EOL>


if f is not None:<EOL><INDENT>if isinstance(f, six.string_types):<EOL><INDENT>if '<STR_LIT:name>' in kwargs:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>kwargs['<STR_LIT:name>'] = f<EOL><DEDENT>else:<EOL><INDENT>return rpc(**kwargs)(f)<EOL><DEDENT><DEDENT>return functools.partial(_rpc, **kwargs)<EOL>


return type(obj).__name__<EOL>


def make_repr(obj, params=None, keywords=None, data=None, name=None,<EOL>reprs=None):

opts = []<EOL>if params is not None:<EOL><INDENT>opts.append('<STR_LIT:U+002CU+0020>'.join(<EOL>_repr_attr(obj, attr, data, reprs) for attr in params))<EOL><DEDENT>if keywords is not None:<EOL><INDENT>opts.append('<STR_LIT:U+002CU+0020>'.join(<EOL>'<STR_LIT>' % (attr, _repr_attr(obj, attr, data, reprs))<EOL>for attr in keywords))<EOL><DEDENT>if name is None:<EOL><INDENT>name = class_name(obj)<EOL><DEDENT>return '<STR_LIT>' % (name, '<STR_LIT:U+002CU+0020>'.join(opts))<EOL>

Generates a string of object initialization code style.  It is useful
    for custom __repr__ methods::

       class Example(object):

           def __init__(self, param, keyword=None):
               self.param = param
               self.keyword = keyword

           def __repr__(self):
               return make_repr(self, ['param'], ['keyword'])

    See the representation of example object::

       >>> Example('hello', keyword='world')
       Example('hello', keyword='world')


def work(self, socket, call, args, kwargs, topics=()):

task_id = uuid4_bytes()<EOL>reply_socket, topics = self.replier(socket, topics, call.reply_to)<EOL>if reply_socket:<EOL><INDENT>channel = (call.call_id, task_id, topics)<EOL><DEDENT>else:<EOL><INDENT>channel = (None, None, None)<EOL><DEDENT>f, rpc_spec = self.find_call_target(call)<EOL>if rpc_spec.reject_if.__get__(self.app)(call, topics):<EOL><INDENT>reply_socket and self.reject(reply_socket, call.call_id, topics)<EOL>return<EOL><DEDENT>reply_socket and self.accept(reply_socket, channel)<EOL>success = False<EOL>with self.catch_exceptions():<EOL><INDENT>try:<EOL><INDENT>val = self.call(call, args, kwargs, f, rpc_spec)<EOL><DEDENT>except:<EOL><INDENT>exc_info = sys.exc_info()<EOL>self.raise_(reply_socket, channel, exc_info)<EOL>reraise(*exc_info)<EOL><DEDENT>success = True<EOL><DEDENT>if not success:<EOL><INDENT>return<EOL><DEDENT>if isinstance(val, Iterator):<EOL><INDENT>vals = val<EOL>with self.catch_exceptions():<EOL><INDENT>try:<EOL><INDENT>try:<EOL><INDENT>val = next(vals)<EOL><DEDENT>except StopIteration:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self.send_reply(reply_socket, YIELD, val, *channel)<EOL>for val in vals:<EOL><INDENT>self.send_reply(reply_socket, YIELD, val, *channel)<EOL><DEDENT><DEDENT>self.send_reply(reply_socket, BREAK, None, *channel)<EOL><DEDENT>except:<EOL><INDENT>exc_info = sys.exc_info()<EOL>self.raise_(reply_socket, channel, exc_info)<EOL>reraise(*exc_info)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>self.send_reply(reply_socket, RETURN, val, *channel)<EOL><DEDENT>

Calls a function and send results to the collector.  It supports
        all of function actions.  A function could return, yield, raise any
        packable objects.


method = reply.method<EOL>call_id = reply.call_id<EOL>task_id = reply.task_id<EOL>if method & ACK:<EOL><INDENT>try:<EOL><INDENT>result_queue = self.result_queues[call_id]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise KeyError('<STR_LIT>')<EOL><DEDENT>if method == ACCEPT:<EOL><INDENT>worker_info = value<EOL>result = RemoteResult(self, call_id, task_id, worker_info)<EOL>self.results[call_id][task_id] = result<EOL>result_queue.put_nowait(result)<EOL><DEDENT>elif method == REJECT:<EOL><INDENT>result_queue.put_nowait(None)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>result = self.results[call_id][task_id]<EOL>result.set_reply(reply.method, value)<EOL><DEDENT>

Dispatches the reply to the proper queue.


poller = zmq.Poller()<EOL>for socket in self.sockets:<EOL><INDENT>poller.register(socket, zmq.POLLIN)<EOL><DEDENT>group = self.greenlet_group<EOL>msgs = []<EOL>capture = msgs.extend<EOL>def accept(socket, call, args, kwargs, topics):<EOL><INDENT>group.spawn(self.work, socket, call, args, kwargs, topics)<EOL>group.join(<NUM_LIT:0>)<EOL><DEDENT>def reject(socket, call, topics):<EOL><INDENT>__, call_id, reply_to, __, __ = call<EOL>reply_socket, topics = self.replier(socket, topics, reply_to)<EOL>self.reject(reply_socket, call_id, topics)<EOL><DEDENT>def reject_if(call, topics):<EOL><INDENT>if self.reject_if(call, topics):<EOL><INDENT>return True<EOL><DEDENT>try:<EOL><INDENT>__, rpc_spec = self.find_call_target(call)<EOL><DEDENT>except KeyError:<EOL><INDENT>return True<EOL><DEDENT>return rpc_spec.reject_if.__get__(self.app)(call, topics)<EOL><DEDENT>try:<EOL><INDENT>while True:<EOL><INDENT>for socket, event in safe(poller.poll):<EOL><INDENT>assert event & zmq.POLLIN<EOL>del msgs[:]<EOL>try:<EOL><INDENT>header, payload, topics = recv(socket, capture=capture)<EOL>call = parse_call(header)<EOL>if group.full() or reject_if(call, topics):<EOL><INDENT>reject(socket, call, topics)<EOL>continue<EOL><DEDENT>args, kwargs = self.unpack(payload)<EOL><DEDENT>except:<EOL><INDENT>handle = self.malformed_message_handler<EOL>if handle is not None:<EOL><INDENT>exc_info = sys.exc_info()<EOL>handle(self, exc_info, msgs[:])<EOL><DEDENT>del handle<EOL>continue<EOL><DEDENT>accept(socket, call, args, kwargs, topics)<EOL><DEDENT>try:<EOL><INDENT>del header, payload, topics<EOL>del call<EOL>del args, kwargs<EOL><DEDENT>except UnboundLocalError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>group.kill()<EOL><DEDENT>

Runs the worker.  While running, an RPC service is online.


def reject(self, reply_socket, call_id, topics=()):

info = self.info or b'<STR_LIT>'<EOL>self.send_raw(reply_socket, REJECT, info, call_id, b'<STR_LIT>', topics)<EOL>


The default exception handler for :class:`Worker`.  It just raises
    the given ``exc_info``.


return BOOL.fromPy(pyVal)<EOL>

create hdl bool value (for example bool value in vhdl)


for i in items:<EOL><INDENT>if not isinstance(i, Value):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>

:return: True if all arguments are instances of Value class else False


return self._dtype.reinterpret_cast(self, toT)<EOL>


def __init__(self, val, dtype, vldMask, updateTime=-<NUM_LIT:1>):

self.val = val<EOL>self._dtype = dtype<EOL>self.vldMask = vldMask<EOL>self.updateTime = updateTime<EOL>

:param val: pythonic value representing this value
:param dtype: data type object from which this value was derived from
:param vldMask: validity mask for value
:param updateTime: simulation time when this value vas created


container = hStructT.fromPy(None)<EOL>offset = <NUM_LIT:0><EOL>for f in hStructT.fields:<EOL><INDENT>t = f.dtype<EOL>width = t.bit_length()<EOL>if f.name is not None:<EOL><INDENT>s = sigOrVal[(width + offset):offset]<EOL>s = s._reinterpret_cast(t)<EOL>setattr(container, f.name, s)<EOL><DEDENT>offset += width<EOL><DEDENT>return container<EOL>

Reinterpret signal of type Bits to signal of type HStruct


if isinstance(index, int):<EOL><INDENT>index = INT.fromPy(index)<EOL><DEDENT>else:<EOL><INDENT>assert isinstance(self, Value)<EOL>assert index._dtype == INT, index._dtype<EOL><DEDENT>if not isinstance(value, Value):<EOL><INDENT>value = self._dtype.elmType.fromPy(value)<EOL><DEDENT>else:<EOL><INDENT>assert value._dtype == self._dtype.elmType, (<EOL>value._dtype, self._dtype.elmType)<EOL><DEDENT>return self._setitem__val(index, value)<EOL>

Only syntax sugar for user, not used inside HWT

* In HW design is not used (__getitem__ returns "reference"
    and it is used)

* In simulator is used _setitem__val directly


try:<EOL><INDENT>kv = key.val<EOL>if not key._isFullVld():<EOL><INDENT>raise KeyError()<EOL><DEDENT>else:<EOL><INDENT>if kv >= self._dtype.size:<EOL><INDENT>raise KeyError()<EOL><DEDENT><DEDENT>return self.val[kv].clone()<EOL><DEDENT>except KeyError:<EOL><INDENT>return self._dtype.elmType.fromPy(None)<EOL><DEDENT>

:atention: this will clone item from array, iterate over .val
    if you need to modify items


t = sigOrVal._dtype<EOL>if isinstance(t, Bits):<EOL><INDENT>yield sigOrVal<EOL><DEDENT>elif isinstance(t, HUnion):<EOL><INDENT>yield from walkFlattenFields(sigOrVal._val, skipPadding=skipPadding)<EOL><DEDENT>elif isinstance(t, HStruct):<EOL><INDENT>for f in t.fields:<EOL><INDENT>isPadding = f.name is None<EOL>if not isPadding or not skipPadding:<EOL><INDENT>if isPadding:<EOL><INDENT>v = f.dtype.fromPy(None)<EOL><DEDENT>else:<EOL><INDENT>v = getattr(sigOrVal, f.name)<EOL><DEDENT>yield from walkFlattenFields(v)<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(t, HArray):<EOL><INDENT>for item in sigOrVal:<EOL><INDENT>yield from walkFlattenFields(item)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise NotImplementedError(t)<EOL><DEDENT>

Walk all simple values in HStruct or HArray


if sliceVals.step is not None:<EOL><INDENT>raise NotImplementedError()<EOL><DEDENT>start = sliceVals.start<EOL>stop = sliceVals.stop<EOL>if sliceVals.start is None:<EOL><INDENT>start = INT.fromPy(width)<EOL><DEDENT>else:<EOL><INDENT>start = toHVal(sliceVals.start)<EOL><DEDENT>if sliceVals.stop is None:<EOL><INDENT>stop = INT.fromPy(<NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>stop = toHVal(sliceVals.stop)<EOL><DEDENT>startIsVal = isinstance(start, Value)<EOL>stopIsVal = isinstance(stop, Value)<EOL>indexesAreValues = startIsVal and stopIsVal<EOL>if indexesAreValues:<EOL><INDENT>updateTime = max(start.updateTime, stop.updateTime)<EOL><DEDENT>else:<EOL><INDENT>updateTime = -<NUM_LIT:1><EOL><DEDENT>return Slice.getValueCls()((start, stop), SLICE, <NUM_LIT:1>, updateTime)<EOL>

convert python slice to value of SLICE hdl type


assert isinstance(self, Value)<EOL>return int(self.val[<NUM_LIT:0>]) - int(self.val[<NUM_LIT:1>])<EOL>

:return: how many bits is this slice selecting


return slice(int(self.val[<NUM_LIT:0>]), int(self.val[<NUM_LIT:1>]))<EOL>


super(HEnum, self).__init__()<EOL>self.name = name<EOL>self._allValues = tuple(valueNames)<EOL>for name in valueNames:<EOL><INDENT>v = self.fromPy(name)<EOL>assert not hasattr(self, name)<EOL>setattr(self, name, v)<EOL><DEDENT>

:param name: name for this type
:param valueNames: sequence of string which will be used as names
    for enum members


return int(<NUM_LIT:2> ** self.bit_length())<EOL>

:return: how many values can have specified type


@classmethod<EOL><INDENT>def fromPy(cls, val, typeObj, vldMask=None):<DEDENT>

vld = int(val is not None)<EOL>if not vld:<EOL><INDENT>assert vldMask is None or vldMask == <NUM_LIT:0><EOL>val = False<EOL><DEDENT>else:<EOL><INDENT>if vldMask == <NUM_LIT:0>:<EOL><INDENT>val = False<EOL>vld = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>val = bool(val)<EOL><DEDENT><DEDENT>return cls(val, typeObj, vld)<EOL>

:param val: value of python type bool or None
:param typeObj: instance of HdlType
:param vldMask: None vldMask is resolved from val,
    if is 0 value is invalidated
    if is 1 value has to be valid


return <NUM_LIT:1> << <NUM_LIT:32><EOL>


if vldMask == <NUM_LIT:0>:<EOL><INDENT>val = None<EOL><DEDENT>return cls(val, typeObj)<EOL>

:param val: None or dict {field name: field value}
:param typeObj: instance of String HdlType
:param vldMask: if is None validity is resolved from val
    if is 0 value is invalidated
    if is 1 value has to be valid


assert isinstance(val, str) or val is None<EOL>vld = <NUM_LIT:0> if val is None else <NUM_LIT:1><EOL>if not vld:<EOL><INDENT>assert vldMask is None or vldMask == <NUM_LIT:0><EOL>val = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>if vldMask == <NUM_LIT:0>:<EOL><INDENT>val = "<STR_LIT>"<EOL>vld = <NUM_LIT:0><EOL><DEDENT><DEDENT>return cls(val, typeObj, vld)<EOL>

:param val: python string or None
:param typeObj: instance of String HdlType
:param vldMask: if is None validity is resolved from val
    if is 0 value is invalidated
    if is 1 value has to be valid


try:<EOL><INDENT>itemSize = self.elmType.bit_length<EOL><DEDENT>except AttributeError:<EOL><INDENT>itemSize = None<EOL><DEDENT>if itemSize is None:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>s = self.size<EOL>if isinstance(s, RtlSignalBase):<EOL><INDENT>s = int(s.staticEval())<EOL><DEDENT>return s * itemSize()<EOL>


assert int(key) > <NUM_LIT:0>, key  <EOL>from hwt.hdl.types.array import HArray<EOL>return HArray(self, key)<EOL>

[] operator to create an array of this type.


raise NotImplementedError()<EOL>

:attention: Overrode in implementation of concrete HdlType.

:return: class for value derived from this type


def statementsAreSame(statements: List[HdlStatement]) -> bool:

iterator = iter(statements)<EOL>try:<EOL><INDENT>first = next(iterator)<EOL><DEDENT>except StopIteration:<EOL><INDENT>return True<EOL><DEDENT>return all(first.isSame(rest) for rest in iterator)<EOL>

:return: True if all statements are same


ctx = self._get_rtl_context()<EOL>for i in self._inputs:<EOL><INDENT>i.endpoints.discard(self)<EOL><DEDENT>for o in self._outputs:<EOL><INDENT>o.drivers.remove(self)<EOL><DEDENT>ctx.statements.remove(self)<EOL>

Disconnect this statement from signals and delete it from RtlNetlist context

:attention: signal endpoints/drivers will be altered
    that means they can not be used for iteration


@internal<EOL><INDENT>def _discover_enclosure(self) -> None:<DEDENT>

raise NotImplementedError("<STR_LIT>"<EOL>"<STR_LIT>", self.__class__, self)<EOL>

Discover all outputs for which is this steement enclosed _enclosed_for property
(has driver in all code branches)


self._inputs.extend(other._inputs)<EOL>self._outputs.extend(other._outputs)<EOL>if self._sensitivity is not None:<EOL><INDENT>self._sensitivity.extend(other._sensitivity)<EOL><DEDENT>else:<EOL><INDENT>assert other._sensitivity is None<EOL><DEDENT>if self._enclosed_for is not None:<EOL><INDENT>self._enclosed_for.update(other._enclosed_for)<EOL><DEDENT>else:<EOL><INDENT>assert other._enclosed_for is None<EOL><DEDENT>other_was_top = other.parentStm is None<EOL>if other_was_top:<EOL><INDENT>other._get_rtl_context().statements.remove(other)<EOL>for s in other._inputs:<EOL><INDENT>s.endpoints.discard(other)<EOL>s.endpoints.append(self)<EOL><DEDENT>for s in other._outputs:<EOL><INDENT>s.drivers.discard(other)<EOL>s.drivers.append(self)<EOL><DEDENT><DEDENT>

After merging statements update IO, sensitivity and context

:attention: rank is not updated


@internal<EOL><INDENT>@staticmethod<EOL>def _merge_statement_lists(stmsA: List["<STR_LIT>"], stmsB: List["<STR_LIT>"])-> List["<STR_LIT>"]:<DEDENT>

if stmsA is None and stmsB is None:<EOL><INDENT>return None<EOL><DEDENT>tmp = []<EOL>a_it = iter(stmsA)<EOL>b_it = iter(stmsB)<EOL>a = None<EOL>b = None<EOL>a_empty = False<EOL>b_empty = False<EOL>while not a_empty and not b_empty:<EOL><INDENT>while not a_empty:<EOL><INDENT>a = next(a_it, None)<EOL>if a is None:<EOL><INDENT>a_empty = True<EOL>break<EOL><DEDENT>elif a.rank == <NUM_LIT:0>:<EOL><INDENT>tmp.append(a)<EOL>a = None<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>while not b_empty:<EOL><INDENT>b = next(b_it, None)<EOL>if b is None:<EOL><INDENT>b_empty = True<EOL>break<EOL><DEDENT>elif b.rank == <NUM_LIT:0>:<EOL><INDENT>tmp.append(b)<EOL>b = None<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if a is not None or b is not None:<EOL><INDENT>a._merge_with_other_stm(b)<EOL>tmp.append(a)<EOL>a = None<EOL>b = None<EOL><DEDENT><DEDENT>return tmp<EOL>

Merge two lists of statements into one

:return: list of merged statements


if not self._is_completly_event_dependent:<EOL><INDENT>self._is_completly_event_dependent = True<EOL>for stm in self._iter_stms():<EOL><INDENT>stm._on_parent_event_dependent()<EOL><DEDENT><DEDENT>

After parrent statement become event dependent
propagate event dependency flag to child statements


def isSameStatementList(stmListA: List[HdlStatement],<EOL>stmListB: List[HdlStatement]) -> bool:

if stmListA is stmListB:<EOL><INDENT>return True<EOL><DEDENT>if stmListA is None or stmListB is None:<EOL><INDENT>return False<EOL><DEDENT>for a, b in zip(stmListA, stmListB):<EOL><INDENT>if not a.isSame(b):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>

:return: True if two lists of HdlStatement instances are same


def __init__(self, name, dtype, defVal=None, virtualOnly=False):

self.name = name<EOL>self._dtype = dtype<EOL>self.virtualOnly = virtualOnly<EOL>if defVal is None:<EOL><INDENT>defVal = dtype.fromPy(None)<EOL><DEDENT>self.defVal = defVal<EOL>self._setDefValue()<EOL>

:param name: name for better orientation in netlists
    (used only in serialization)
:param dtype: data type of this signal
:param defVal: value for initialization
:param virtualOnly: flag indicates that this assignments is only
    virtual and should not be added into
    netlist, because it is only for internal notation


outputs = self._outputs<EOL>self._ifTrue_enclosed_for = self._discover_enclosure_for_statements(<EOL>self.ifTrue, outputs)<EOL>elif_encls = self._elIfs_enclosed_for = []<EOL>for _, stms in self.elIfs:<EOL><INDENT>e = self._discover_enclosure_for_statements(<EOL>stms, outputs)<EOL>elif_encls.append(e)<EOL><DEDENT>self._ifFalse_enclosed_for = self._discover_enclosure_for_statements(<EOL>self.ifFalse, outputs)<EOL>assert self._enclosed_for is None<EOL>encl = self._enclosed_for = set()<EOL>for s in self._ifTrue_enclosed_for:<EOL><INDENT>enclosed = True<EOL>for elif_e in elif_encls:<EOL><INDENT>if s not in elif_e:<EOL><INDENT>enclosed = False<EOL>break<EOL><DEDENT><DEDENT>if enclosed and s in self._ifFalse_enclosed_for:<EOL><INDENT>encl.add(s)<EOL><DEDENT><DEDENT>

Doc on parent class :meth:`HdlStatement._discover_enclosure`


@internal<EOL><INDENT>def _merge_with_other_stm(self, other: "<STR_LIT>") -> None:<DEDENT>

merge = self._merge_statement_lists<EOL>self.ifTrue = merge(self.ifTrue, other.ifTrue)<EOL>new_elifs = []<EOL>for ((c, elifA), (_, elifB)) in zip(self.elIfs, other.elIfs):<EOL><INDENT>new_elifs.append((c,  merge(elifA, elifB)))<EOL><DEDENT>self.elIfs = new_elifs<EOL>self.ifFalse = merge(self.ifFalse, other.ifFalse)<EOL>other.ifTrue = []<EOL>other.elIfs = []<EOL>other.ifFalse = None<EOL>self._on_merge(other)<EOL>

:attention: statements has to be mergable (to check use _is_mergable method)


@internal<EOL><INDENT>def _fill_enclosure(self, enclosure: Dict[RtlSignalBase, HdlStatement]):<DEDENT>

pass<EOL>


def __init__(self, src, dst, indexes=None, virtualOnly=False,<EOL>parentStm=None,<EOL>sensitivity=None,<EOL>is_completly_event_dependent=False):

super(Assignment, self).__init__(<EOL>parentStm,<EOL>sensitivity,<EOL>is_completly_event_dependent)<EOL>self.src = src<EOL>isReal = not virtualOnly<EOL>if not isinstance(src, Value):<EOL><INDENT>self._inputs.append(src)<EOL>if isReal:<EOL><INDENT>src.endpoints.append(self)<EOL><DEDENT><DEDENT>self.dst = dst<EOL>if not isinstance(dst, Value):<EOL><INDENT>self._outputs.append(dst)<EOL>if isReal:<EOL><INDENT>dst.drivers.append(self)<EOL><DEDENT><DEDENT>self.indexes = indexes<EOL>if indexes:<EOL><INDENT>for i in indexes:<EOL><INDENT>if not isinstance(i, Value):<EOL><INDENT>self._inputs.append(i)<EOL>if isReal:<EOL><INDENT>i.endpoints.append(self)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self._instId = Assignment._nextInstId()<EOL>if not virtualOnly:<EOL><INDENT>dst.ctx.statements.add(self)<EOL><DEDENT>

:param dst: destination to assign to
:param src: source which is assigned from
:param indexes: description of index selector on dst
    (list of Index/Slice objects) (f.e. [[0], [1]] means  dst[0][1])
:param virtualOnly: flag indicates that this assignments
    is only virtual and should not be added into
    netlist, because it is only for internal notation


if not self._is_completly_event_dependent:<EOL><INDENT>self._is_completly_event_dependent = True<EOL><DEDENT>

After parrent statement become event dependent


self.dst._val = self.src.staticEval()<EOL>


@internal<EOL><INDENT>def _loadFromHStream(self, dtype: HStream, bitAddr: int) -> int:<DEDENT>

ch = TransTmpl(dtype.elmType, <NUM_LIT:0>, parent=self, origin=self.origin)<EOL>self.children.append(ch)<EOL>return bitAddr + dtype.elmType.bit_length()<EOL>

Parse HUnion type to this transaction template instance

:return: address of it's end


def __exit__(self, exc_type, exc_val, exc_tb):

self.actual = self.parents.pop()<EOL>self.onParentNames.pop()<EOL>


def _loadFromHType(self, dtype: HdlType, bitAddr: int) -> None:

self.bitAddr = bitAddr<EOL>childrenAreChoice = False<EOL>if isinstance(dtype, Bits):<EOL><INDENT>ld = self._loadFromBits<EOL><DEDENT>elif isinstance(dtype, HStruct):<EOL><INDENT>ld = self._loadFromHStruct<EOL><DEDENT>elif isinstance(dtype, HArray):<EOL><INDENT>ld = self._loadFromArray<EOL><DEDENT>elif isinstance(dtype, HStream):<EOL><INDENT>ld = self._loadFromHStream<EOL><DEDENT>elif isinstance(dtype, HUnion):<EOL><INDENT>ld = self._loadFromUnion<EOL>childrenAreChoice = True<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>", dtype)<EOL><DEDENT>self.bitAddrEnd = ld(dtype, bitAddr)<EOL>self.childrenAreChoice = childrenAreChoice<EOL>

Parse any HDL type to this transaction template instance


@internal<EOL><INDENT>def _loadFromUnion(self, dtype: HdlType, bitAddr: int) -> int:<DEDENT>

for field in dtype.fields.values():<EOL><INDENT>ch = TransTmpl(field.dtype, <NUM_LIT:0>, parent=self, origin=field)<EOL>self.children.append(ch)<EOL><DEDENT>return bitAddr + dtype.bit_length()<EOL>


@internal<EOL><INDENT>def _loadFromBits(self, dtype: HdlType, bitAddr: int):<DEDENT>

return bitAddr + dtype.bit_length()<EOL>

Parse Bits type to this transaction template instance

:return: address of it's end


def walkFlatten(self, offset: int=<NUM_LIT:0>,<EOL>shouldEnterFn=_default_shouldEnterFn,<EOL>otherObjItCtx: ObjIteratorCtx =_DummyIteratorCtx()<EOL>) -> Generator[<EOL>Union[Tuple[Tuple[int, int], '<STR_LIT>'], '<STR_LIT>'],<EOL>None, None]:

t = self.dtype<EOL>base = self.bitAddr + offset<EOL>end = self.bitAddrEnd + offset<EOL>shouldEnter, shouldYield = shouldEnterFn(self)<EOL>if shouldYield:<EOL><INDENT>yield ((base, end), self)<EOL><DEDENT>if shouldEnter:<EOL><INDENT>if isinstance(t, Bits):<EOL><INDENT>pass<EOL><DEDENT>elif isinstance(t, HStruct):<EOL><INDENT>for ch in self.children:<EOL><INDENT>with otherObjItCtx(ch.origin.name):<EOL><INDENT>yield from ch.walkFlatten(<EOL>offset,<EOL>shouldEnterFn,<EOL>otherObjItCtx)<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(t, HArray):<EOL><INDENT>itemSize = (self.bitAddrEnd - self.bitAddr) // self.itemCnt<EOL>for i in range(self.itemCnt):<EOL><INDENT>with otherObjItCtx(i):<EOL><INDENT>yield from self.children.walkFlatten(<EOL>base + i * itemSize,<EOL>shouldEnterFn,<EOL>otherObjItCtx)<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(t, HUnion):<EOL><INDENT>yield OneOfTransaction(self, offset, shouldEnterFn,<EOL>self.children)<EOL><DEDENT>elif isinstance(t, HStream):<EOL><INDENT>assert len(self.children) == <NUM_LIT:1><EOL>yield StreamTransaction(self, offset, shouldEnterFn,<EOL>self.children[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>raise TypeError(t)<EOL><DEDENT><DEDENT>

Walk fields in instance of TransTmpl

:param offset: optional offset for all children in this TransTmpl
:param shouldEnterFn: function (transTmpl) which returns True
    when field should be split on it's children
:param shouldEnterFn: function(transTmpl) which should return
    (shouldEnter, shouldUse) where shouldEnter is flag that means
    iterator should look inside of this actual object
    and shouldUse flag means that this field should be used
    (=generator should yield it)
:return: generator of tuples ((startBitAddress, endBitAddress),
    TransTmpl instance)


for _, stms in self.cases:<EOL><INDENT>yield from stms<EOL><DEDENT>if self.default is not None:<EOL><INDENT>yield from self.default<EOL><DEDENT>

Doc on parent class :meth:`HdlStatement._iter_stms`


@internal<EOL><INDENT>def _try_reduce(self) -> Tuple[List["<STR_LIT>"], bool]:<DEDENT>

io_change = False<EOL>new_cases = []<EOL>for val, statements in self.cases:<EOL><INDENT>_statements, rank_decrease, _io_change = self._try_reduce_list(<EOL>statements)<EOL>io_change |= _io_change<EOL>self.rank -= rank_decrease<EOL>new_cases.append((val, _statements))<EOL><DEDENT>self.cases = new_cases<EOL>if self.default is not None:<EOL><INDENT>self.default, rank_decrease, _io_change = self._try_reduce_list(<EOL>self.default)<EOL>self.rank -= rank_decrease<EOL>io_change |= _io_change<EOL><DEDENT>reduce_self = not self._condHasEffect()<EOL>if reduce_self:<EOL><INDENT>if self.cases:<EOL><INDENT>res = self.cases[<NUM_LIT:0>][<NUM_LIT:1>]<EOL><DEDENT>elif self.default is not None:<EOL><INDENT>res = self.default<EOL><DEDENT>else:<EOL><INDENT>res = []<EOL><DEDENT><DEDENT>else:<EOL><INDENT>res = [self, ]<EOL><DEDENT>self._on_reduce(reduce_self, io_change, res)<EOL>if not self.default:<EOL><INDENT>t = self.switchOn._dtype<EOL>if isinstance(t, HEnum):<EOL><INDENT>dom_size = t.domain_size()<EOL>val_cnt = len(t._allValues)<EOL>if len(self.cases) == val_cnt and val_cnt < dom_size:<EOL><INDENT>_, stms = self.cases.pop()<EOL>self.default = stms<EOL><DEDENT><DEDENT><DEDENT>return res, io_change<EOL>

Doc on parent class :meth:`HdlStatement._try_reduce`


def getBusWordBitRange(self) -> Tuple[int, int]:

offset = self.startOfPart % self.parent.wordWidth<EOL>return (offset + self.bit_length(), offset)<EOL>

:return: bit range which contains data of this part on bus data signal


return self.endOfPart - self.startOfPart<EOL>


def getFieldBitRange(self) -> Tuple[int, int]:

offset = self.inFieldOffset<EOL>return (self.bit_length() + offset, offset)<EOL>

:return: bit range which contains data of this part on interface
    of field


@internal<EOL><INDENT>def _wordIndx(self, addr: int):<DEDENT>

return floor(addr / self.wordWidth)<EOL>

convert bit address to index of word where this address is


def __init__(self, origin, wordWidth, startBitAddr, endBitAddr,<EOL>transParts):

self.origin = origin<EOL>self.wordWidth = wordWidth<EOL>assert startBitAddr <= endBitAddr<EOL>self.startBitAddr = startBitAddr<EOL>self.endBitAddr = endBitAddr<EOL>self.parts = transParts<EOL>self._fieldToTPart = None<EOL>for p in self.parts:<EOL><INDENT>p.parent = self<EOL>assert p.startOfPart >= startBitAddr, (p, startBitAddr)<EOL>assert p.endOfPart <= endBitAddr, (p, endBitAddr)<EOL><DEDENT>

:param origin: instance of HType (usually HStruct)
    from which this FrameTmpl was generated from
:param wordWidth: width of word on interface
    where this template should be used
:param startBitAddr: bit offset where this frame starts
:param endBitAddr: bit offset where this frame ends
    (bit index of first bit behind this frame)
:param transParts: instances of TransPart which are parts of this frame


def fullWordCnt(self, start: int, end: int):

assert end >= start, (start, end)<EOL>gap = max(<NUM_LIT:0>, (end - start) - (start % self.wordWidth))<EOL>return gap // self.wordWidth<EOL>

Count of complete words between two addresses


actual = []<EOL>_iterators = []<EOL>for i, it in enumerate(iterators):<EOL><INDENT>try:<EOL><INDENT>a = next(it)<EOL>_iterators.append((i, it))<EOL>actual.append(a)<EOL><DEDENT>except StopIteration:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>while True:<EOL><INDENT>if not _iterators:<EOL><INDENT>return<EOL><DEDENT>elif len(_iterators) == <NUM_LIT:1>:<EOL><INDENT>originIndex, it = _iterators[<NUM_LIT:0>]<EOL>yield originIndex, actual[<NUM_LIT:0>]<EOL>for item in it:<EOL><INDENT>yield originIndex, item<EOL><DEDENT>return<EOL><DEDENT>minimum = None<EOL>minimumIndex = None<EOL>secondMin = None<EOL>for i, val in enumerate(actual):<EOL><INDENT>skipSecMinCheck = False<EOL>if minimum is None:<EOL><INDENT>minimum = val<EOL>minimumIndex = i<EOL><DEDENT>elif cmpFn(val, minimum):<EOL><INDENT>secondMin = minimum<EOL>minimum = val<EOL>minimumIndex = i<EOL>skipSecMinCheck = True<EOL><DEDENT>elif not skipSecMinCheck and (<EOL>secondMin is None or cmpFn(val, secondMin)):<EOL><INDENT>secondMin = val<EOL><DEDENT><DEDENT>actualI, actualIt = _iterators[minimumIndex]<EOL>while not cmpFn(secondMin, minimum):<EOL><INDENT>yield (actualI, minimum)<EOL>try:<EOL><INDENT>minimum = next(actualIt)<EOL><DEDENT>except StopIteration:<EOL><INDENT>minimum = None<EOL>break<EOL><DEDENT><DEDENT>if minimum is None:<EOL><INDENT>del _iterators[minimumIndex]<EOL>del actual[minimumIndex]<EOL><DEDENT>else:<EOL><INDENT>actual[minimumIndex] = minimum<EOL><DEDENT><DEDENT>

Sort items from iterators(generators) by alwas selecting item
with lowest value (min first)

:return: generator of tuples (origin index, item) where origin index
    is index of iterator in "iterators" from where item commes from


def groupIntoChoices(splitsOnWord, wordWidth: int, origin: OneOfTransaction):

def cmpWordIndex(a, b):<EOL><INDENT>return a.startOfPart // wordWidth < b.startOfPart // wordWidth<EOL><DEDENT>actual = None<EOL>itCnt = len(splitsOnWord)<EOL>for i, item in iterSort(splitsOnWord, cmpWordIndex):<EOL><INDENT>_actualW = item.startOfPart // wordWidth<EOL>if actual is None:<EOL><INDENT>actual = ChoicesOfFrameParts(item.startOfPart, origin)<EOL>actual.extend(<EOL>ChoiceOfFrameParts(actual,<EOL>origin.possibleTransactions[_i])<EOL>for _i in range(itCnt))<EOL>actualW = _actualW<EOL><DEDENT>elif _actualW > actualW:<EOL><INDENT>actual.resolveEnd()<EOL>yield actual<EOL>actual = ChoicesOfFrameParts(item.startOfPart, origin)<EOL>actual.extend(<EOL>ChoiceOfFrameParts(actual,<EOL>origin.possibleTransactions[_i])<EOL>for _i in range(itCnt))<EOL>actualW = _actualW<EOL><DEDENT>actual[i].append(item)<EOL><DEDENT>if actual is not None:<EOL><INDENT>actual.setIsLast(True)<EOL>actual.resolveEnd()<EOL>yield actual<EOL><DEDENT>

:param splitsOnWord: list of lists of parts (fields splited on word
    boundaries)
:return: generators of ChoicesOfFrameParts for each word
    which are not crossing word boundaries


for o in self.operands:<EOL><INDENT>o.staticEval()<EOL><DEDENT>self.result._val = self.evalFn()<EOL>

Recursively statistically evaluate result of this operator


def eval(self, operator, simulator=None):

def getVal(v):<EOL><INDENT>while not isinstance(v, Value):<EOL><INDENT>v = v._val<EOL><DEDENT>return v<EOL><DEDENT>operands = list(map(getVal, operator.operands))<EOL>if isEventDependentOp(operator.operator):<EOL><INDENT>operands.append(simulator.now)<EOL><DEDENT>elif operator.operator == AllOps.IntToBits:<EOL><INDENT>operands.append(operator.result._dtype)<EOL><DEDENT>return self._evalFn(*operands)<EOL>

Load all operands and process them by self._evalFn


if op == AllOps.RISING_EDGE:<EOL><INDENT>return SENSITIVITY.RISING<EOL><DEDENT>elif op == AllOps.FALLING_EDGE:<EOL><INDENT>return SENSITIVITY.FALLING<EOL><DEDENT>else:<EOL><INDENT>raise TypeError()<EOL><DEDENT>


for item in iterable:<EOL><INDENT>if fn(item):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

:return: True if fn(item) for any item else False


def find_files(directory, pattern, recursive=True):

if not os.path.isdir(directory):<EOL><INDENT>if os.path.exists(directory):<EOL><INDENT>raise IOError(directory + '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>raise IOError(directory + "<STR_LIT>")<EOL><DEDENT><DEDENT>if recursive:<EOL><INDENT>for root, _, files in os.walk(directory):<EOL><INDENT>for basename in files:<EOL><INDENT>if fnmatch.fnmatch(basename, pattern):<EOL><INDENT>filename = os.path.join(root, basename)<EOL>yield filename<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>root = directory<EOL>for basename in os.listdir(root):<EOL><INDENT>if fnmatch.fnmatch(basename, pattern):<EOL><INDENT>filename = os.path.join(root, basename)<EOL>if os.path.isfile(filename):<EOL><INDENT>yield filename<EOL><DEDENT><DEDENT><DEDENT><DEDENT>


def __init__(self, sigOrVal: Union[RtlSignal, Value],<EOL>skipPadding: bool=True,<EOL>fillup: bool=False):

self.it = walkFlattenFields(sigOrVal, skipPadding=skipPadding)<EOL>self.fillup = fillup<EOL>self.actuallyHave = <NUM_LIT:0><EOL>self.actual = None<EOL>self.actualOffset = <NUM_LIT:0><EOL>

:param skipPadding: if true padding is skipped in dense types


def iterBits(sigOrVal: Union[RtlSignal, Value], bitsInOne: int=<NUM_LIT:1>,<EOL>skipPadding: bool=True, fillup: bool=False):

bw = BitWalker(sigOrVal, skipPadding, fillup)<EOL>for _ in range(ceil(sigOrVal._dtype.bit_length() / bitsInOne)):<EOL><INDENT>yield bw.get(bitsInOne)<EOL><DEDENT>bw.assertIsOnEnd()<EOL>

Iterate over bits in vector

:param sigOrVal: signal or value to iterate over
:param bitsInOne: number of bits in one part
:param skipPadding: if true padding is skipped in dense types


if not hasattr(self, "<STR_LIT>"):<EOL><INDENT>self._interfaces = []<EOL><DEDENT>if not hasattr(self, "<STR_LIT>"):<EOL><INDENT>self._private_interfaces = []<EOL><DEDENT>if not hasattr(self, "<STR_LIT>"):<EOL><INDENT>self._units = []<EOL><DEDENT>self._setAttrListener = self._declrCollector<EOL>self._declr()<EOL>self._setAttrListener = None<EOL>for i in self._interfaces:<EOL><INDENT>self._loadInterface(i, True)<EOL><DEDENT>for u in self._units:<EOL><INDENT>u._loadDeclarations()<EOL><DEDENT>for p in self._params:<EOL><INDENT>p.setReadOnly()<EOL><DEDENT>

Load all declarations from _decl() method, recursively
for all interfaces/units.


i = cls.__instCntr<EOL>cls.__instCntr += <NUM_LIT:1><EOL>return i<EOL>


@internal<EOL>def statements_to_HWProcesses(statements: List[HdlStatement])-> Generator[HWProcess, None, None]:

<EOL>statements = copy(statements)<EOL>processes = []<EOL>while statements:<EOL><INDENT>stm = statements.pop()<EOL>proc_statements = [stm, ]<EOL>ps = _statements_to_HWProcesses(proc_statements, True)<EOL>processes.extend(ps)<EOL><DEDENT>yield from reduceProcesses(processes)<EOL>

Pack statements into HWProcess instances,
* for each out signal resolve it's drivers and collect them
* split statements if there is and combinational loop
* merge statements if it is possible
* resolve sensitivitilists
* wrap into HWProcess instance
* for every IO of process generate name if signal has not any


return self.naryOp(AllOps.EQ, tv(self)._eq, other)<EOL>

__eq__ is not overloaded because it will destroy hashability of object


@internal<EOL>def tryToMerge(procA: HWProcess, procB: HWProcess):

if (checkIfIsTooSimple(procA) or<EOL>checkIfIsTooSimple(procB) or<EOL>areSetsIntersets(procA.outputs, procB.sensitivityList) or<EOL>areSetsIntersets(procB.outputs, procA.sensitivityList) or<EOL>not HdlStatement._is_mergable_statement_list(procA.statements, procB.statements)):<EOL><INDENT>raise IncompatibleStructure()<EOL><DEDENT>procA.statements = HdlStatement._merge_statement_lists(<EOL>procA.statements, procB.statements)<EOL>procA.outputs.extend(procB.outputs)<EOL>procA.inputs.extend(procB.inputs)<EOL>procA.sensitivityList.extend(procB.sensitivityList)<EOL>return procA<EOL>

Try merge procB into procA

:raise IncompatibleStructure: if merge is not possible
:attention: procA is now result if merge has succeed
:return: procA which is now result of merge


@internal<EOL><INDENT>def _registerArray(self, name, items):<DEDENT>

items._parent = self<EOL>items._name = name<EOL>for i, item in enumerate(items):<EOL><INDENT>setattr(self, "<STR_LIT>" % (name, i), item)<EOL><DEDENT>

Register array of items on interface level object


@internal<EOL><INDENT>def _registerParameter(self, pName, parameter) -> None:<DEDENT>

nameAvailabilityCheck(self, pName, parameter)<EOL>try:<EOL><INDENT>hasName = parameter._name is not None<EOL><DEDENT>except AttributeError:<EOL><INDENT>hasName = False<EOL><DEDENT>if not hasName:<EOL><INDENT>parameter._name = pName<EOL><DEDENT>parameter._registerScope(pName, self)<EOL>if parameter.hasGenericName:<EOL><INDENT>parameter.name = pName<EOL><DEDENT>if parameter._parent is None:<EOL><INDENT>parameter._parent = self<EOL><DEDENT>self._params.append(parameter)<EOL>

Register Param object on interface level object


@internal<EOL>def nameAvailabilityCheck(obj, propName, prop):

if getattr(obj, propName, None) is not None:<EOL><INDENT>raise IntfLvlConfErr("<STR_LIT>" % <EOL>(obj, propName, repr(getattr(obj, propName)), prop))<EOL><DEDENT>


def _paramsShared(self, exclude=None, prefix="<STR_LIT>") -> MakeParamsShared:

return MakeParamsShared(self, exclude=exclude, prefix=prefix)<EOL>

Auto-propagate params by name to child components and interfaces
Usage:

.. code-block:: python

    with self._paramsShared():
        # your interfaces and unit which should share all params with "self" there

:param exclude: params which should not be shared
:param prefix: prefix which should be added to name of child parameters
    before parameter name matching


for si in intf._interfaces:<EOL><INDENT>yield from walkParams(si, discovered)<EOL><DEDENT>for p in intf._params:<EOL><INDENT>if p not in discovered:<EOL><INDENT>discovered.add(p)<EOL>yield p<EOL><DEDENT><DEDENT>

walk parameter instances on this interface


for pi in self._entity.ports:<EOL><INDENT>pi.connectInternSig()<EOL><DEDENT>for i in chain(self._interfaces, self._private_interfaces):<EOL><INDENT>i._clean()<EOL><DEDENT>

Disconnect internal signals so unit can be reused by parent unit


def _updateParamsFrom(self, otherObj, updater=_default_param_updater,<EOL>exclude=None, prefix="<STR_LIT>"):

PropDeclrCollector._updateParamsFrom(self, otherObj, updater, exclude, prefix)<EOL>

:note: doc in :func:`~hwt.synthesizer.interfaceLevel.propDeclCollector._updateParamsFrom`


try:<EOL><INDENT>interfaces = self._interfaces<EOL><DEDENT>except AttributeError:<EOL><INDENT>interfaces = None<EOL><DEDENT>if interfaces is None:<EOL><INDENT>_intf = self._clone()<EOL>_intf._loadDeclarations()<EOL>interfaces = _intf._interfaces<EOL><DEDENT>if interfaces:<EOL><INDENT>w = <NUM_LIT:0><EOL>for i in interfaces:<EOL><INDENT>w += i._bit_length()<EOL><DEDENT>return w<EOL><DEDENT>else:<EOL><INDENT>return self._dtype.bit_length()<EOL><DEDENT>

Sum of all width of interfaces in this interface


if hasattr(self, "<STR_LIT>"):<EOL><INDENT>return self._boundedEntityPort.name<EOL><DEDENT>else:<EOL><INDENT>return self._getFullName().replace('<STR_LIT:.>', self._NAME_SEPARATOR)<EOL><DEDENT>


self._setAttrListener = None<EOL>self._associatedClk = None<EOL>self._associatedRst = None<EOL>self._parent = None<EOL>super().__init__()<EOL>self._masterDir = masterDir<EOL>self._direction = INTF_DIRECTION.UNKNOWN<EOL>self._ctx = None<EOL>if loadConfig:<EOL><INDENT>self._loadConfig()<EOL><DEDENT>self._isExtern = False<EOL>self._isAccessible = True<EOL>self._ag = None<EOL>

This constructor is called when constructing new interface,
it is usually done manually while creating Unit or
automatically while extracting interfaces from UnitWithSoure

:param masterDir: direction which this interface should have for master
:param multiplyedBy: this can be instance of integer or Param,
    this mean the interface is array of the interfaces
    where multiplyedBy is the size
:param loadConfig: do load config in __init__


return HObjList._getFullName(self)<EOL>


def _make_association(self, *args, **kwargs):

for o in self:<EOL><INDENT>o._make_association(*args, **kwargs)<EOL><DEDENT>

Delegate _make_association on items

:note: doc in :func:`~hwt.synthesizer.interfaceLevel.propDeclCollector._make_association`


def op(*operands, key=None) -> RtlSignalBase:<EOL><INDENT>"""<STR_LIT>"""<EOL>assert operands, operands<EOL>top = None<EOL>if key is not None:<EOL><INDENT>operands = map(key, operands)<EOL><DEDENT>for s in operands:<EOL><INDENT>if top is None:<EOL><INDENT>top = s<EOL><DEDENT>else:<EOL><INDENT>top = fn(top, s)<EOL><DEDENT><DEDENT>return top<EOL><DEDENT>return op<EOL>

Function to create variadic operator function

:param fn: function to perform binary operation


return self._sig.__le__(other)<EOL>


return self._sig.__ge__(other)<EOL>


assert self._isAccessible<EOL>return self._sig(source)<EOL>

connect this signal to driver

:attention: it is not call of function it is operator of assignment
:return: list of assignments


return self._sig.__and__(other)<EOL>

& operator - logical 'and' for one bit signals and hBool
bitwise and for wider signals


Process for injecting of this callback loop into simulator


return self.intf.vld._sigInside<EOL>


return self.intf.rd._sigInside<EOL>


r = sim.read<EOL>if self.actualData is NOP and self.data:<EOL><INDENT>self.actualData = self.data.popleft()<EOL><DEDENT>doSend = self.actualData is not NOP<EOL>if self.actualData is not self._lastWritten:<EOL><INDENT>if doSend:<EOL><INDENT>self.doWrite(sim, self.actualData)<EOL><DEDENT>else:<EOL><INDENT>self.doWrite(sim, None)<EOL><DEDENT>self._lastWritten = self.actualData<EOL><DEDENT>en = self.notReset(sim)<EOL>vld = int(en and doSend)<EOL>if self._lastVld is not vld:<EOL><INDENT>self.wrVld(sim.write, vld)<EOL>self._lastVld = vld<EOL><DEDENT>if not self._enabled:<EOL><INDENT>sim.add_process(self.checkIfRdWillBeValid(sim))<EOL>return<EOL><DEDENT>yield sim.waitOnCombUpdate()<EOL>rd = self.isRd(r)<EOL>assert rd.vldMask, (sim.now, self.intf,<EOL>"<STR_LIT>")<EOL>if not vld:<EOL><INDENT>return<EOL><DEDENT>if rd.val:<EOL><INDENT>if self._debugOutput is not None:<EOL><INDENT>self._debugOutput.write("<STR_LIT>" % (<EOL>self.intf._getFullName(),<EOL>sim.now,<EOL>self.actualData))<EOL><DEDENT>a = self.actualData<EOL>if self.data:<EOL><INDENT>self.actualData = self.data.popleft()<EOL><DEDENT>else:<EOL><INDENT>self.actualData = NOP<EOL><DEDENT>onDriverWriteAck = getattr(self, "<STR_LIT>", None)<EOL>if onDriverWriteAck is not None:<EOL><INDENT>onDriverWriteAck(sim)<EOL><DEDENT>onDone = getattr(a, "<STR_LIT>", None)<EOL>if onDone is not None:<EOL><INDENT>onDone(sim)<EOL><DEDENT><DEDENT>

Push data to interface

set vld high and wait on rd in high then pass new data


def pullUpAfter(sig, initDelay=<NUM_LIT:6> * Time.ns):

def _pullDownAfter(s):<EOL><INDENT>s.write(False, sig)<EOL>yield s.wait(initDelay)<EOL>s.write(True, sig)<EOL><DEDENT>return _pullDownAfter<EOL>

:return: Simulation driver which keeps signal value low for initDelay then
    it sets value to 1


clk = obj.clk<EOL>rst = obj.rst<EOL>for u in obj._units:<EOL><INDENT>_tryConnect(clk, u, '<STR_LIT>')<EOL>_tryConnect(~rst, u, '<STR_LIT>')<EOL>_tryConnect(rst, u, '<STR_LIT>')<EOL><DEDENT>

Propagate "clk" clock and reset "rst" signal to all subcomponents


rst_n = obj.rst_n<EOL>for u in obj._units:<EOL><INDENT>_tryConnect(rst_n, u, '<STR_LIT>')<EOL>_tryConnect(~rst_n, u, '<STR_LIT>')<EOL><DEDENT>

Propagate negative reset "rst_n" signal
to all subcomponents


clk = obj.clk<EOL>for u in obj._units:<EOL><INDENT>_tryConnect(clk, u, '<STR_LIT>')<EOL><DEDENT>

Propagate "clk" clock signal to all subcomponents


@internal<EOL>def _serializeParamsUniq_eval(parentUnit, obj, isDeclaration, priv):

params = paramsToValTuple(parentUnit)<EOL>if priv is None:<EOL><INDENT>priv = {}<EOL><DEDENT>if isDeclaration:<EOL><INDENT>try:<EOL><INDENT>prevUnit = priv[params]<EOL><DEDENT>except KeyError:<EOL><INDENT>priv[params] = parentUnit<EOL>return True, priv<EOL><DEDENT>prepareEntity(obj, prevUnit._entity.name, prevUnit)<EOL>return False, priv<EOL><DEDENT>return priv[params] is parentUnit, priv<EOL>

Decide to serialize only objs with uniq parameters and class

:param priv: private data for this function
    ({frozen_params: obj})

:return: tuple (do serialize this object, next priv)


def registerMUX(self, stm: Union[HdlStatement, Operator], sig: RtlSignal,<EOL>inputs_cnt: int):

assert inputs_cnt > <NUM_LIT:1><EOL>res = self.resources<EOL>w = sig._dtype.bit_length()<EOL>k = (ResourceMUX, w, inputs_cnt)<EOL>res[k] = res.get(k, <NUM_LIT:0>) + <NUM_LIT:1><EOL>self.resource_for_object[(stm, sig)] = k<EOL>

mux record is in format (self.MUX, n, m)
where n is number of bits of this mux
and m is number of possible inputs


@internal<EOL><INDENT>def serialzeValueToTCL(self, val, do_eval=False) -> Tuple[str, str, bool]:<DEDENT>

if isinstance(val, int):<EOL><INDENT>val = hInt(val)<EOL><DEDENT>if do_eval:<EOL><INDENT>val = val.staticEval()<EOL><DEDENT>if isinstance(val, RtlSignalBase):<EOL><INDENT>ctx = VivadoTclExpressionSerializer.getBaseContext()<EOL>tclVal = VivadoTclExpressionSerializer.asHdl(val, ctx)<EOL>tclValVal = VivadoTclExpressionSerializer.asHdl(<EOL>val.staticEval())<EOL>return tclVal, tclValVal, False<EOL><DEDENT>else:<EOL><INDENT>tclVal = VivadoTclExpressionSerializer.asHdl(val, None)<EOL>return tclVal, tclVal, True<EOL><DEDENT>


@internal<EOL><INDENT>def getTypeWidth(self, dtype: HdlType, do_eval=False) -> Tuple[int, Union[int, RtlSignal], bool]:<DEDENT>

width = dtype.width<EOL>if isinstance(width, int):<EOL><INDENT>widthStr = str(width)<EOL><DEDENT>else:<EOL><INDENT>widthStr = self.getExprVal(width, do_eval=do_eval)<EOL><DEDENT>return width, widthStr, False<EOL>


@classmethod<EOL><INDENT>def HWProcess(cls, proc, ctx):<DEDENT>

body = proc.statements<EOL>extraVars = []<EOL>extraVarsSerialized = []<EOL>hasToBeVhdlProcess = extraVars orarr_any(body,<EOL>lambda x: isinstance(x,<EOL>(IfContainer,<EOL>SwitchContainer,<EOL>WhileContainer,<EOL>WaitStm)) or<EOL>(isinstance(x, Assignment) and<EOL>x.indexes))<EOL>anyIsEventDependnt = arr_any(<EOL>proc.sensitivityList, lambda s: isinstance(s, Operator))<EOL>sensitivityList = sorted(<EOL>map(lambda s: cls.sensitivityListItem(s, ctx,<EOL>anyIsEventDependnt),<EOL>proc.sensitivityList))<EOL>if hasToBeVhdlProcess:<EOL><INDENT>childCtx = ctx.withIndent()<EOL><DEDENT>else:<EOL><INDENT>childCtx = ctx<EOL><DEDENT>def createTmpVarFn(suggestedName, dtype):<EOL><INDENT>s = SignalItem(None, dtype, virtualOnly=True)<EOL>s.name = childCtx.scope.checkedName(suggestedName, s)<EOL>s.hidden = False<EOL>serializedS = cls.SignalItem(s, childCtx, declaration=True)<EOL>extraVars.append(s)<EOL>extraVarsSerialized.append(serializedS)<EOL>return s<EOL><DEDENT>childCtx.createTmpVarFn = createTmpVarFn<EOL>statemets = [cls.asHdl(s, childCtx) for s in body]<EOL>if hasToBeVhdlProcess:<EOL><INDENT>proc.name = ctx.scope.checkedName(proc.name, proc)<EOL><DEDENT>extraVarsInit = []<EOL>for s in extraVars:<EOL><INDENT>a = Assignment(s.defVal, s, virtualOnly=True)<EOL>extraVarsInit.append(cls.Assignment(a, childCtx))<EOL><DEDENT>return cls.processTmpl.render(<EOL>indent=getIndent(ctx.indent),<EOL>name=proc.name,<EOL>hasToBeVhdlProcess=hasToBeVhdlProcess,<EOL>extraVars=extraVarsSerialized,<EOL>sensitivityList="<STR_LIT>".join(sensitivityList),<EOL>statements=extraVarsInit + statemets<EOL>)<EOL>


processes = []<EOL>signals = []<EOL>for e in rom.endpoints:<EOL><INDENT>assert isinstance(e, Operator) and e.operator == AllOps.INDEX, e<EOL>me, index = e.operands<EOL>assert me is rom<EOL>romValSig = rom.ctx.sig(rom.name, dtype=e.result._dtype)<EOL>signals.append(romValSig)<EOL>romValSig.hidden = False<EOL>cases = [(toHVal(i), [romValSig(v), ])<EOL>for i, v in enumerate(rom.defVal.val)]<EOL>statements = [SwitchContainer(index, cases), ]<EOL>for (_, (stm, )) in cases:<EOL><INDENT>stm.parentStm = statements[<NUM_LIT:0>] <EOL><DEDENT>p = HWProcess(rom.name, statements, {index, },<EOL>{index, }, {romValSig, })<EOL>processes.append(p)<EOL>def replaceOrigRomIndexExpr(x):<EOL><INDENT>if x is e.result:<EOL><INDENT>return romValSig<EOL><DEDENT>else:<EOL><INDENT>return x<EOL><DEDENT><DEDENT>for _e in e.result.endpoints:<EOL><INDENT>_e.operands = tuple(map(replaceOrigRomIndexExpr, _e.operands))<EOL>e.result = romValSig<EOL><DEDENT><DEDENT>return processes, signals<EOL>

Due to verilog restrictions it is not posible to use array constants
and rom memories has to be hardcoded as process


@classmethod<EOL><INDENT>def Value(cls, val, ctx: SerializerCtx):<DEDENT>

t = val._dtype<EOL>if isinstance(val, RtlSignalBase):<EOL><INDENT>return cls.SignalItem(val, ctx)<EOL><DEDENT>c = cls.Value_try_extract_as_const(val, ctx)<EOL>if c:<EOL><INDENT>return c<EOL><DEDENT>if isinstance(t, Slice):<EOL><INDENT>return cls.Slice_valAsHdl(t, val, ctx)<EOL><DEDENT>elif isinstance(t, HArray):<EOL><INDENT>return cls.HArrayValAsHdl(t, val, ctx)<EOL><DEDENT>elif isinstance(t, Bits):<EOL><INDENT>return cls.Bits_valAsHdl(t, val, ctx)<EOL><DEDENT>elif isinstance(t, HBool):<EOL><INDENT>return cls.Bool_valAsHdl(t, val, ctx)<EOL><DEDENT>elif isinstance(t, HEnum):<EOL><INDENT>return cls.HEnumValAsHdl(t, val, ctx)<EOL><DEDENT>elif isinstance(t, Integer):<EOL><INDENT>return cls.Integer_valAsHdl(t, val, ctx)<EOL><DEDENT>elif isinstance(t, String):<EOL><INDENT>return cls.String_valAsHdl(t, val, ctx)<EOL><DEDENT>else:<EOL><INDENT>raise SerializerException(<EOL>"<STR_LIT>"<EOL>% (val))<EOL><DEDENT>

:param dst: is signal connected with value
:param val: value object, can be instance of Signal or Value


try:<EOL><INDENT>return _indentCache[indentNum]<EOL><DEDENT>except KeyError:<EOL><INDENT>i = "<STR_LIT>".join([_indent for _ in range(indentNum)])<EOL>_indentCache[indentNum] = i<EOL>return i<EOL><DEDENT>


@classmethod<EOL><INDENT>def serializationDecision(cls, obj, serializedClasses,<EOL>serializedConfiguredUnits):<DEDENT>

isDeclaration = isinstance(obj, Entity)<EOL>isDefinition = isinstance(obj, Architecture)<EOL>if isDeclaration:<EOL><INDENT>unit = obj.origin<EOL><DEDENT>elif isDefinition:<EOL><INDENT>unit = obj.entity.origin<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT>assert isinstance(unit, Unit)<EOL>sd = unit._serializeDecision<EOL>if sd is None:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>prevPriv = serializedClasses.get(unit.__class__, None)<EOL>seriazlize, nextPriv = sd(unit, obj, isDeclaration, prevPriv)<EOL>serializedClasses[unit.__class__] = nextPriv<EOL>return seriazlize<EOL><DEDENT>

Decide if this unit should be serialized or not eventually fix name
to fit same already serialized unit

:param obj: object to serialize
:param serializedClasses: dict {unitCls : unitobj}
:param serializedConfiguredUnits: (unitCls, paramsValues) : unitObj
    where paramsValues are named tuple name:value


stms = []<EOL>for st in statements:<EOL><INDENT>if isinstance(st, Assignment):<EOL><INDENT>try:<EOL><INDENT>if not isinstance(st.src, RtlSignalBase):<EOL><INDENT>raise DoesNotContainsTernary()<EOL><DEDENT>d = st.src.singleDriver()<EOL>if not isinstance(d, Operator) or d.operator != AllOps.TERNARY:<EOL><INDENT>raise DoesNotContainsTernary()<EOL><DEDENT>else:<EOL><INDENT>ops = d.operands<EOL>ifc = IfContainer(ops[<NUM_LIT:0>],<EOL>[Assignment(ops[<NUM_LIT:1>], st.dst)],<EOL>[Assignment(ops[<NUM_LIT:2>], st.dst)]<EOL>)<EOL>stms.append(ifc)<EOL>continue<EOL><DEDENT><DEDENT>except (MultipleDriversErr, DoesNotContainsTernary):<EOL><INDENT>pass<EOL><DEDENT>except NoDriverErr:<EOL><INDENT>assert (hasattr(st.src, "<STR_LIT>")<EOL>and st.src._interface is not None)or st.src.defVal.vldMask, st.src<EOL><DEDENT><DEDENT>stms.append(st)<EOL><DEDENT>return stms<EOL>

Convert all ternary operators to IfContainers


body = proc.statements<EOL>extraVars = []<EOL>extraVarsSerialized = []<EOL>hasToBeVhdlProcess = arr_any(body,<EOL>lambda x: isinstance(x,<EOL>(IfContainer,<EOL>SwitchContainer,<EOL>WhileContainer,<EOL>WaitStm)))<EOL>sensitivityList = sorted(<EOL>map(lambda s: cls.sensitivityListItem(s, ctx),<EOL>proc.sensitivityList))<EOL>if hasToBeVhdlProcess:<EOL><INDENT>childCtx = ctx.withIndent()<EOL><DEDENT>else:<EOL><INDENT>childCtx = copy(ctx)<EOL><DEDENT>def createTmpVarFn(suggestedName, dtype):<EOL><INDENT>s = RtlSignal(None, None, dtype, virtualOnly=True)<EOL>s.name = ctx.scope.checkedName(suggestedName, s)<EOL>s.hidden = False<EOL>serializedS = cls.SignalItem(s, childCtx, declaration=True)<EOL>extraVars.append(s)<EOL>extraVarsSerialized.append(serializedS)<EOL>return s<EOL><DEDENT>childCtx.createTmpVarFn = createTmpVarFn<EOL>statemets = [cls.asHdl(s, childCtx) for s in body]<EOL>proc.name = ctx.scope.checkedName(proc.name, proc)<EOL>extraVarsInit = []<EOL>for s in extraVars:<EOL><INDENT>if isinstance(s.defVal, RtlSignalBase) or s.defVal.vldMask:<EOL><INDENT>a = Assignment(s.defVal, s, virtualOnly=True)<EOL>extraVarsInit.append(cls.Assignment(a, childCtx))<EOL><DEDENT>else:<EOL><INDENT>assert s.drivers, s<EOL><DEDENT>for d in s.drivers:<EOL><INDENT>extraVarsInit.append(cls.asHdl(d, childCtx))<EOL><DEDENT><DEDENT>_hasToBeVhdlProcess = hasToBeVhdlProcess<EOL>hasToBeVhdlProcess = extraVars or hasToBeVhdlProcess<EOL>if hasToBeVhdlProcess and not _hasToBeVhdlProcess:<EOL><INDENT>oneIndent = getIndent(<NUM_LIT:1>)<EOL>statemets = list(map(lambda x: oneIndent + x, statemets))<EOL><DEDENT>return cls.processTmpl.render(<EOL>indent=getIndent(ctx.indent),<EOL>name=proc.name,<EOL>hasToBeVhdlProcess=hasToBeVhdlProcess,<EOL>extraVars=extraVarsSerialized,<EOL>sensitivityList="<STR_LIT:U+002CU+0020>".join(sensitivityList),<EOL>statements=extraVarsInit + statemets<EOL>)<EOL>

Serialize HWProcess objects as VHDL

:param scope: name scope to prevent name collisions


def logChange(self, nowTime, sig, nextVal):

try:<EOL><INDENT>hwProc = self.registered[sig]<EOL><DEDENT>except KeyError:<EOL><INDENT>return<EOL><DEDENT>if hwProc.actualTime < nowTime:<EOL><INDENT>a = hwProc.actualTime<EOL>if a < <NUM_LIT:0>:<EOL><INDENT>a = <NUM_LIT:0><EOL><DEDENT>delay = int(nowTime - a)<EOL>if delay > <NUM_LIT:0>:<EOL><INDENT>hwProc.statements.append(<EOL>WaitStm(int(delay) // <NUM_LIT:1000>)<EOL>)<EOL>hwProc.actualTime = nowTime<EOL><DEDENT><DEDENT>try:<EOL><INDENT>nextVal._dtype.forceVector = hwProc.driverFor._dtype.forceVector<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>hwProc.statements.extend(<EOL>connect(nextVal, hwProc.driverFor)<EOL>)<EOL>

This method is called for every value change of any signal.


def logApplyingValues(self, simulator, values):


@internal<EOL>def mkArrayUpdater(nextItemVal: Value, indexes: Tuple[Value],<EOL>invalidate: bool):

def updater(currentVal):<EOL><INDENT>if len(indexes) > <NUM_LIT:1>:<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>_nextItemVal = nextItemVal.clone()<EOL>if invalidate:<EOL><INDENT>_nextItemVal.vldMask = <NUM_LIT:0><EOL><DEDENT>index = indexes[<NUM_LIT:0>]<EOL>change = valueHasChanged(currentVal._getitem__val(index), _nextItemVal)<EOL>currentVal._setitem__val(index, _nextItemVal)<EOL>return (change, currentVal)<EOL><DEDENT>return updater<EOL>

Create value updater for simulation for value of array type

:param nextVal: instance of Value which will be asssiggned to signal
:param indexes: tuple on indexes where value should be updated
    in target array

:return: function(value) -> tuple(valueHasChangedFlag, nextVal)


@internal<EOL>def sensitivity(proc: HWProcess, *sensitiveTo):

for s in sensitiveTo:<EOL><INDENT>if isinstance(s, tuple):<EOL><INDENT>sen, s = s<EOL>if sen == SENSITIVITY.ANY:<EOL><INDENT>s.simSensProcs.add(proc)<EOL><DEDENT>elif sen == SENSITIVITY.RISING:<EOL><INDENT>s.simRisingSensProcs.add(proc)<EOL><DEDENT>elif sen == SENSITIVITY.FALLING:<EOL><INDENT>s.simFallingSensProcs.add(proc)<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError(sen)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>s.simSensProcs.add(proc)<EOL><DEDENT><DEDENT>


def assertValSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):

seq1 = allValuesToInts(seq1)<EOL>self.assertSequenceEqual(seq1, seq2, msg, seq_type)<EOL>

An equality assertion for ordered sequences (like lists and tuples).
For the purposes of this function, a valid ordered sequence type is one
which can be indexed, has a length, and has an equality operator.

Args:

:param seq1: can contain instance of values or nested list of them
:param seq2: items are not converted
:param seq_type: The expected datatype of the sequences, or None if no
    datatype should be enforced.
:param msg: Optional message to use on failure instead of a list of
    differences.


def registerWriteCallback(self, callback, getEnFn) -> int:

index = len(self._writeCallbacks)<EOL>self._writeCallbacks.append(None)<EOL>self._writeCallbacksToEn.append((index, callback, getEnFn))<EOL>return index<EOL>

Register writeCallback for signal.
Registration is evaluated at the end of deltastep of simulator.

:param callback: simulation process represented by function(simulator)
    which should be called after update of this signal
:param getEnFn: function() to get initial value for enable of callback


def simUpdateVal(self, simulator, valUpdater):

dirtyFlag, newVal = valUpdater(self._oldVal)<EOL>if dirtyFlag:<EOL><INDENT>self._val = newVal<EOL>newVal.updateTime = simulator.now<EOL>log = simulator.config.logChange<EOL>if log:<EOL><INDENT>log(simulator.now, self, newVal)<EOL><DEDENT>self.simPropagateChanges(simulator)<EOL><DEDENT>

Method called by simulator to update new value for this object