INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Do a reverse search. Args: lat lon. REVERSE 48. 1234 2. 9876
def do_REVERSE(self, latlon): """Do a reverse search. Args: lat lon. REVERSE 48.1234 2.9876""" lat, lon = latlon.split() for r in reverse(float(lat), float(lon)): print('{} ({} | {} km | {})'.format(white(r), blue(r.score), blue...
Print the distance score between two strings. Use | as separator. STRDISTANCE rue des lilas|porte des lilas
def do_STRDISTANCE(self, s): """Print the distance score between two strings. Use | as separator. STRDISTANCE rue des lilas|porte des lilas""" s = s.split('|') if not len(s) == 2: print(red('Malformed string. Use | between the two strings.')) return one, t...
Inspect loaded Addok config. Output all config without argument. CONFIG [ CONFIG_KEY ]
def do_CONFIG(self, name): """Inspect loaded Addok config. Output all config without argument. CONFIG [CONFIG_KEY]""" if not name: for name in self.complete_CONFIG(): self.do_CONFIG(name) return value = getattr(config, name.upper(), 'Not found.') ...
Run a Lua script. Takes the raw Redis arguments. SCRIPT script_name number_of_keys key1 key2… arg1 arg2
def do_SCRIPT(self, args): """Run a Lua script. Takes the raw Redis arguments. SCRIPT script_name number_of_keys key1 key2… arg1 arg2 """ try: name, keys_count, *args = args.split() except ValueError: print(red('Not enough arguments')) return ...
Just sends the request using its send method and returns its response.
def send(r, stream=False): """Just sends the request using its send method and returns its response. """ r.send(stream=stream) return r.response
Concurrently converts a list of Requests to Responses.
def map(requests, stream=True, pool=None, size=1, exception_handler=None): """Concurrently converts a list of Requests to Responses. :param requests: a collection of Request objects. :param stream: If False, the content will not be downloaded immediately. :param size: Specifies the number of workers to...
Concurrently converts a generator object of Requests to a generator of Responses.
def imap(requests, stream=True, pool=None, size=2, exception_handler=None): """Concurrently converts a generator object of Requests to a generator of Responses. :param requests: a generator of Request objects. :param stream: If False, the content will not be downloaded immediately. :param size: Spe...
Concurrently converts a generator object of Requests to a generator of Responses.
def imap_unordered(requests, stream=True, pool=None, size=2, exception_handler=None): """Concurrently converts a generator object of Requests to a generator of Responses. :param requests: a generator of Request objects. :param stream: If False, the content will not be downloaded immediately. :param...
Gets value of bits between selected range from memory
def getBits_from_array(array, wordWidth, start, end, reinterpretElmToType=None): """ Gets value of bits between selected range from memory :param start: bit address of start of bit of bits :param end: bit address of first bit behind bits :return: instance of BitsVal (derived ...
Cast HArray signal or value to signal or value of type Bits
def reinterptet_harray_to_bits(typeFrom, sigOrVal, bitsT): """ Cast HArray signal or value to signal or value of type Bits """ size = int(typeFrom.size) widthOfElm = typeFrom.elmType.bit_length() w = bitsT.bit_length() if size * widthOfElm != w: raise TypeConversionErr( "...
convert python slice to value of SLICE hdl type
def slice_to_SLICE(sliceVals, width): """convert python slice to value of SLICE hdl type""" if sliceVals.step is not None: raise NotImplementedError() start = sliceVals.start stop = sliceVals.stop if sliceVals.start is None: start = INT.fromPy(width) else: start = toHVa...
: return: bit range which contains data of this part on bus data signal
def getBusWordBitRange(self) -> Tuple[int, int]: """ :return: bit range which contains data of this part on bus data signal """ offset = self.startOfPart % self.parent.wordWidth return (offset + self.bit_length(), offset)
: return: bit range which contains data of this part on interface of field
def getFieldBitRange(self) -> Tuple[int, int]: """ :return: bit range which contains data of this part on interface of field """ offset = self.inFieldOffset return (self.bit_length() + offset, offset)
Apply enclosure on list of statements ( fill all unused code branches with assignments from value specified by enclosure )
def fill_stm_list_with_enclosure(parentStm: Optional[HdlStatement], current_enclosure: Set[RtlSignalBase], statements: List["HdlStatement"], do_enclose_for: List[RtlSignalBase], enclosure:...
Find files by pattern in directory
def find_files(directory, pattern, recursive=True): """ Find files by pattern in directory """ if not os.path.isdir(directory): if os.path.exists(directory): raise IOError(directory + ' is not directory') else: raise IOError(directory + " does not exists") if ...
Generate if tree for cases like ( syntax shugar for large elifs )
def SwitchLogic(cases, default=None): """ Generate if tree for cases like (syntax shugar for large elifs) ..code-block:: python if cond0: statements0 elif cond1: statements1 else: default :param case: iterable of tuples (condition, statements...
Hdl convertible in operator check if any of items in iterable equals sigOrVal
def In(sigOrVal, iterable): """ Hdl convertible in operator, check if any of items in "iterable" equals "sigOrVal" """ res = None for i in iterable: i = toHVal(i) if res is None: res = sigOrVal._eq(i) else: res = res | sigOrVal._eq(i) assert r...
Generate for loop for static items
def StaticForEach(parentUnit, items, bodyFn, name=""): """ Generate for loop for static items :param parentUnit: unit where this code should be instantiated :param items: items which this "for" itering on :param bodyFn: function which fn(item, index) or fn(item) returns (statementList, ack)...
Connect src ( signals/ interfaces/ values ) to all destinations
def connect(src, *destinations, exclude: set=None, fit=False): """ Connect src (signals/interfaces/values) to all destinations :param exclude: interfaces on any level on src or destinations which should be excluded from connection process :param fit: auto fit source width to destination width ...
Rotate left
def rol(sig, howMany) -> RtlSignalBase: "Rotate left" width = sig._dtype.bit_length() return sig[(width - howMany):]._concat(sig[:(width - howMany)])
Logical shift left
def sll(sig, howMany) -> RtlSignalBase: "Logical shift left" width = sig._dtype.bit_length() return sig[(width - howMany):]._concat(vec(0, howMany))
Returns no of bits required to store x - 1 for example x = 8 returns 3
def log2ceil(x): """ Returns no of bits required to store x-1 for example x=8 returns 3 """ if not isinstance(x, (int, float)): x = int(x) if x == 0 or x == 1: res = 1 else: res = math.ceil(math.log2(x)) return hInt(res)
Check if number or constant is power of two
def isPow2(num) -> bool: """ Check if number or constant is power of two """ if not isinstance(num, int): num = int(num) return num != 0 and ((num & (num - 1)) == 0)
Add multiple case statements from iterable of tuleles ( caseVal statements )
def addCases(self, tupesValStmnts): """ Add multiple case statements from iterable of tuleles (caseVal, statements) """ s = self for val, statements in tupesValStmnts: s = s.Case(val, statements) return s
c - like case of switch statement
def Case(self, caseVal, *statements): "c-like case of switch statement" assert self.parentStm is None caseVal = toHVal(caseVal, self.switchOn._dtype) assert isinstance(caseVal, Value), caseVal assert caseVal._isFullVld(), "Cmp with invalid value" assert caseVal not in se...
c - like default of switch statement
def Default(self, *statements): """c-like default of switch statement """ assert self.parentStm is None self.rank += 1 self.default = [] self._register_stements(statements, self.default) return self
: param stateFrom: apply when FSM is in this state: param condAndNextState: tupes ( condition newState ) last does not to have condition
def Trans(self, stateFrom, *condAndNextState): """ :param stateFrom: apply when FSM is in this state :param condAndNextState: tupes (condition, newState), last does not to have condition :attention: transitions has priority, first has the biggest :attention: if state...
: return: ( vcd type name vcd width )
def vcdTypeInfoForHType(t) -> Tuple[str, int, Callable[[RtlSignalBase, Value], str]]: """ :return: (vcd type name, vcd width) """ if isinstance(t, (SimBitsT, Bits, HBool)): return (VCD_SIG_TYPE.WIRE, t.bit_length(), vcdBitsFormatter) elif isinstance(t, HEnum): return (VCD_SIG_TYPE.RE...
Register signals from interfaces for Interface or Unit instances
def vcdRegisterInterfaces(self, obj: Union[Interface, Unit], parent: Optional[VcdVarWritingScope]): """ Register signals from interfaces for Interface or Unit instances """ if hasattr(obj, "_interfaces") and obj._interfaces: name = obj._name ...
This method is called before first step of simulation.
def beforeSim(self, simulator, synthesisedUnit): """ This method is called before first step of simulation. """ vcd = self.vcdWriter vcd.date(datetime.now()) vcd.timescale(1) self.vcdRegisterInterfaces(synthesisedUnit, None) self.vcdRegisterRemainingSigna...
This method is called for every value change of any signal.
def logChange(self, nowTime, sig, nextVal): """ This method is called for every value change of any signal. """ try: self.vcdWriter.logChange(nowTime, sig, nextVal) except KeyError: # not every signal has to be registered pass
Serialize HWProcess instance
def HWProcess(cls, proc, ctx): """ Serialize HWProcess instance :param scope: name scope to prevent name collisions """ body = proc.statements childCtx = ctx.withIndent() statemets = [cls.asHdl(s, childCtx) for s in body] proc.name = ctx.scope.checkedName...
Trim or extend scope lvl = 1 - > only one scope ( global )
def setLevel(self, lvl): """ Trim or extend scope lvl = 1 -> only one scope (global) """ while len(self) != lvl: if len(self) > lvl: self.pop() else: self.append(NameScopeItem(len(self)))
: return: how many bits is this slice selecting
def _size(self): """ :return: how many bits is this slice selecting """ assert isinstance(self, Value) return int(self.val[0]) - int(self.val[1])
Walk all interfaces on unit and instantiate agent for every interface.
def autoAddAgents(unit): """ Walk all interfaces on unit and instantiate agent for every interface. :return: all monitor/driver functions which should be added to simulation as processes """ proc = [] for intf in unit._interfaces: if not intf._isExtern: continue ...
Iterable of values to ints ( nonvalid = None )
def valuesToInts(values): """ Iterable of values to ints (nonvalid = None) """ res = [] append = res.append for d in values: if isinstance(d, int): append(d) else: append(valToInt(d)) return res
If interface has associated rst ( _n ) return it otherwise try to find rst ( _n ) on parent recursively
def _getAssociatedRst(self): """ If interface has associated rst(_n) return it otherwise try to find rst(_n) on parent recursively """ a = self._associatedRst if a is not None: return a p = self._parent assert p is not None if isinst...
If interface has associated clk return it otherwise try to find clk on parent recursively
def _getAssociatedClk(self): """ If interface has associated clk return it otherwise try to find clk on parent recursively """ a = self._associatedClk if a is not None: return a p = self._parent assert p is not None if isinstance(p, ...
: return: list of extra discovered processes
def Architecture_var(cls, v, serializerVars, extraTypes, extraTypes_serialized, ctx, childCtx): """ :return: list of extra discovered processes """ v.name = ctx.scope.checkedName(v.name, v) serializedVar = cls.SignalItem(v, childCtx, declaration=True) ...
uniq operation with key selector
def distinctBy(iterable, fn): """ uniq operation with key selector """ s = set() for i in iterable: r = fn(i) if r not in s: s.add(r) yield i
Get value from iterable where fn ( item ) and check if there is not fn ( other item )
def single(iterable, fn): """ Get value from iterable where fn(item) and check if there is not fn(other item) :raise DuplicitValueExc: when there are multiple items satisfying fn() :raise NoValueExc: when no value satisfying fn(item) found """ found = False ret = None for i in iter...
: return: generator of first n items from iterrable
def take(iterrable, howMay): """ :return: generator of first n items from iterrable """ assert howMay >= 0 if not howMay: return last = howMay - 1 for i, item in enumerate(iterrable): yield item if i == last: return
: return: generator of tuples ( isLastFlag item )
def iter_with_last(iterable): """ :return: generator of tuples (isLastFlag, item) """ # Ensure it's an iterator and get the first field iterable = iter(iterable) prev = next(iterable) for item in iterable: # Lag by one item so I know I'm not at the end yield False, prev ...
same like itertools. groupby
def groupedby(collection, fn): """ same like itertools.groupby :note: This function does not needs initial sorting like itertools.groupby :attention: Order of pairs is not deterministic. """ d = {} for item in collection: k = fn(item) try: arr = d[k] exc...
Flatten nested lists tuples generators and maps
def flatten(iterables, level=inf): """ Flatten nested lists, tuples, generators and maps :param level: maximum depth of flattening """ if level >= 0 and isinstance(iterables, (list, tuple, GeneratorType, map, zip)): level -= 1 for i in it...
Doc on parent class: meth: HdlStatement. _cut_off_drivers_of
def _cut_off_drivers_of(self, sig: RtlSignalBase): """ Doc on parent class :meth:`HdlStatement._cut_off_drivers_of` """ if len(self._outputs) == 1 and sig in self._outputs: self.parentStm = None return self # try to cut off all statements which are driver...
Doc on parent class: meth: HdlStatement. _discover_enclosure
def _discover_enclosure(self): """ Doc on parent class :meth:`HdlStatement._discover_enclosure` """ outputs = self._outputs self._ifTrue_enclosed_for = self._discover_enclosure_for_statements( self.ifTrue, outputs) elif_encls = self._elIfs_enclosed_for = [] ...
Doc on parent class: meth: HdlStatement. _discover_sensitivity
def _discover_sensitivity(self, seen: set) -> None: """ Doc on parent class :meth:`HdlStatement._discover_sensitivity` """ assert self._sensitivity is None, self ctx = self._sensitivity = SensitivityCtx() self._discover_sensitivity_sig(self.cond, seen, ctx) if ct...
Doc on parent class: meth: HdlStatement. _iter_stms
def _iter_stms(self): """ Doc on parent class :meth:`HdlStatement._iter_stms` """ yield from self.ifTrue for _, stms in self.elIfs: yield from stms if self.ifFalse is not None: yield from self.ifFalse
Doc on parent class: meth: HdlStatement. _try_reduce
def _try_reduce(self) -> Tuple[bool, List[HdlStatement]]: """ Doc on parent class :meth:`HdlStatement._try_reduce` """ # flag if IO of statement has changed io_change = False self.ifTrue, rank_decrease, _io_change = self._try_reduce_list( self.ifTrue) ...
Merge nested IfContarner form else branch to this IfContainer as elif and else branches
def _merge_nested_if_from_else(self, ifStm: "IfContainer"): """ Merge nested IfContarner form else branch to this IfContainer as elif and else branches """ self.elIfs.append((ifStm.cond, ifStm.ifTrue)) self.elIfs.extend(ifStm.elIfs) self.ifFalse = ifStm.ifFalse
: attention: statements has to be mergable ( to check use _is_mergable method )
def _merge_with_other_stm(self, other: "IfContainer") -> None: """ :attention: statements has to be mergable (to check use _is_mergable method) """ merge = self._merge_statement_lists self.ifTrue = merge(self.ifTrue, other.ifTrue) new_elifs = [] for ((c, elifA), ...
: return: True if other has same meaning as this statement
def isSame(self, other: HdlStatement) -> bool: """ :return: True if other has same meaning as this statement """ if self is other: return True if self.rank != other.rank: return False if isinstance(other, IfContainer): if self.cond is...
If signal is not driving anything remove it
def removeUnconnectedSignals(netlist): """ If signal is not driving anything remove it """ toDelete = set() toSearch = netlist.signals while toSearch: _toSearch = set() for sig in toSearch: if not sig.endpoints: try: if sig._inte...
check if process is just unconditional assignments and it is useless to merge them
def checkIfIsTooSimple(proc): """check if process is just unconditional assignments and it is useless to merge them""" try: a, = proc.statements if isinstance(a, Assignment): return True except ValueError: pass return False
Try merge procB into procA
def tryToMerge(procA: HWProcess, procB: HWProcess): """ 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 """ if (checkIfIsTooSimple(procA) or checkIf...
Try to merge processes as much is possible
def reduceProcesses(processes): """ Try to merge processes as much is possible :param processes: list of processes instances """ # sort to make order of merging same deterministic processes.sort(key=lambda x: (x.name, maxStmId(x)), reverse=True) # now try to reduce processes with nearly sam...
on writeReqRecieved in monitor mode
def onWriteReq(self, sim, addr, data): """ on writeReqRecieved in monitor mode """ self.requests.append((WRITE, addr, data))
Convert object to HDL string
def asHdl(cls, obj, ctx: HwtSerializerCtx): """ Convert object to HDL string :param obj: object to serialize :param ctx: HwtSerializerCtx instance """ if isinstance(obj, RtlSignalBase): return cls.SignalItem(obj, ctx) elif isinstance(obj, Value): ...
Entity is just forward declaration of Architecture it is not used in most HDL languages as there is no recursion in hierarchy
def Entity(cls, ent: Entity, ctx: HwtSerializerCtx): """ Entity is just forward declaration of Architecture, it is not used in most HDL languages as there is no recursion in hierarchy """ cls.Entity_prepare(ent, ctx, serialize=False) ent.name = ctx.scope.checkedName(ent....
Convert unit to RTL using specified serializer
def toRtl(unitOrCls: Unit, name: str=None, serializer: GenericSerializer=VhdlSerializer, targetPlatform=DummyPlatform(), saveTo: str=None): """ Convert unit to RTL using specified serializer :param unitOrCls: unit instance or class, which should be converted :param name: name overri...
Resolve name for process and mark outputs of statemens as not hidden
def name_for_process_and_mark_outputs(statements: List[HdlStatement])\ -> str: """ Resolve name for process and mark outputs of statemens as not hidden """ out_names = [] for stm in statements: for sig in stm._outputs: if not sig.hasGenericName: out_names....
Cut off drivers from statements
def cut_off_drivers_of(dstSignal, statements): """ Cut off drivers from statements """ separated = [] stm_filter = [] for stm in statements: stm._clean_signal_meta() d = stm._cut_off_drivers_of(dstSignal) if d is not None: separated.append(d) f = d is...
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
def statements_to_HWProcesses(statements: List[HdlStatement])\ -> Generator[HWProcess, None, None]: """ 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 poss...
* check if all signals are driven by something * mark signals with hidden = False if they are connecting statements or if they are external interface
def markVisibilityOfSignals(ctx, ctxName, signals, interfaceSignals): """ * check if all signals are driven by something * mark signals with hidden = False if they are connecting statements or if they are external interface """ for sig in signals: driver_cnt = len(sig.drivers) ...
Create new signal in this context
def sig(self, name, dtype=BIT, clk=None, syncRst=None, defVal=None): """ Create new signal in this context :param clk: clk signal, if specified signal is synthesized as SyncSignal :param syncRst: synchronous reset signal """ if isinstance(defVal, RtlSignal): ...
Build Entity and Architecture instance out of netlist representation
def synthesize(self, name, interfaces, targetPlatform): """ Build Entity and Architecture instance out of netlist representation """ ent = Entity(name) ent._name = name + "_inst" # instance name # create generics for _, v in self.params.items(): ent....
Convert python or hdl value/ signal object to hdl value/ signal object
def toHVal(op: Any, suggestedType: Optional[HdlType]=None): """Convert python or hdl value/signal object to hdl value/signal object""" if isinstance(op, Value) or isinstance(op, SignalItem): return op elif isinstance(op, InterfaceBase): return op._sig else: if isinstance(op, int)...
: param dst: is signal connected with value: param val: value object can be instance of Signal or Value
def Value(cls, val, ctx: SerializerCtx): """ :param dst: is signal connected with value :param val: value object, can be instance of Signal or Value """ t = val._dtype if isinstance(val, RtlSignalBase): return cls.SignalItem(val, ctx) c = cls.Value_t...
Get maximum _instId from all assigments in statement
def getMaxStmIdForStm(stm): """ Get maximum _instId from all assigments in statement """ maxId = 0 if isinstance(stm, Assignment): return stm._instId elif isinstance(stm, WaitStm): return maxId else: for _stm in stm._iter_stms(): maxId = max(maxId, getMaxS...
get max statement id used for sorting of processes in architecture
def maxStmId(proc): """ get max statement id, used for sorting of processes in architecture """ maxId = 0 for stm in proc.statements: maxId = max(maxId, getMaxStmIdForStm(stm)) return maxId
Collect data from interface
def monitor(self, sim): """Collect data from interface""" if self.notReset(sim) and self._enabled: self.wrRd(sim.write, 1) yield sim.waitOnCombUpdate() d = self.doRead(sim) self.data.append(d) else: self.wrRd(sim.write, 0)
write data to interface
def doWrite(self, sim, data): """write data to interface""" sim.write(data, self.intf.data)
Push data to interface
def driver(self, sim): """Push data to interface""" r = sim.read if self.actualData is NOP and self.data: self.actualData = self.data.popleft() do = self.actualData is not NOP if do: self.doWrite(sim, self.actualData) else: self.doWri...
: param val: value of python type int or None: param typeObj: instance of Integer: param vldMask: None vldMask is resolved from val if is 0 value is invalidated if is 1 value has to be valid
def fromPy(cls, val, typeObj, vldMask=None): """ :param val: value of python type int or None :param typeObj: instance of Integer :param vldMask: None vldMask is resolved from val, if is 0 value is invalidated if is 1 value has to be valid """ asse...
Note that this interface will be master
def _m(self): """ Note that this interface will be master :return: self """ assert not hasattr(self, "_interfaces") or not self._interfaces, \ "Too late to change direction of interface" self._direction = DIRECTION.asIntfDirection(DIRECTION.opposite(self._mas...
load declaratoins from _declr method This function is called first for parent and then for children
def _loadDeclarations(self): """ load declaratoins from _declr method This function is called first for parent and then for children """ if not hasattr(self, "_interfaces"): self._interfaces = [] self._setAttrListener = self._declrCollector self._declr...
Remove all signals from this interface ( used after unit is synthesized and its parent is connecting its interface to this unit )
def _clean(self, rmConnetions=True, lockNonExternal=True): """ Remove all signals from this interface (used after unit is synthesized and its parent is connecting its interface to this unit) """ if self._interfaces: for i in self._interfaces: i._clean...
generate _sig for each interface which has no subinterface if already has _sig return it instead
def _signalsForInterface(self, context, prefix='', typeTransform=None): """ generate _sig for each interface which has no subinterface if already has _sig return it instead :param context: instance of RtlNetlist where signals should be created :param prefix: name prefix for crea...
Get name in HDL
def _getPhysicalName(self): """Get name in HDL """ if hasattr(self, "_boundedEntityPort"): return self._boundedEntityPort.name else: return self._getFullName().replace('.', self._NAME_SEPARATOR)
Replace parameter on this interface ( in configuration stage )
def _replaceParam(self, p, newP): """ Replace parameter on this interface (in configuration stage) :ivar pName: actual name of param on me :ivar newP: new Param instance by which should be old replaced """ i = self._params.index(p) pName = p._scopes[self][1] ...
: note: doc in: func: ~hwt. synthesizer. interfaceLevel. propDeclCollector. _updateParamsFrom
def _updateParamsFrom(self, otherObj, updater=_default_param_updater, exclude=None, prefix=""): """ :note: doc in :func:`~hwt.synthesizer.interfaceLevel.propDeclCollector._updateParamsFrom` """ PropDeclrCollector._updateParamsFrom(self, otherObj, updater, exclud...
Sum of all width of interfaces in this interface
def _bit_length(self): """Sum of all width of interfaces in this interface""" try: interfaces = self._interfaces except AttributeError: interfaces = None if interfaces is None: # not loaded interface _intf = self._clone() _intf...
connect to another interface interface ( on rtl level ) works like self < = master in VHDL
def _connectTo(self, master, exclude=None, fit=False): """ connect to another interface interface (on rtl level) works like self <= master in VHDL """ return list(self._connectToIter(master, exclude, fit))
get sensitivity type for operator
def sensitivityByOp(op): """ get sensitivity type for operator """ if op == AllOps.RISING_EDGE: return SENSITIVITY.RISING elif op == AllOps.FALLING_EDGE: return SENSITIVITY.FALLING else: raise TypeError()
Load all operands and process them by self. _evalFn
def eval(self, operator, simulator=None): """Load all operands and process them by self._evalFn""" def getVal(v): while not isinstance(v, Value): v = v._val return v operands = list(map(getVal, operator.operands)) if isEventDependentOp(operator....
Cast signed - unsigned to int or bool
def convertBits(self, sigOrVal, toType): """ Cast signed-unsigned, to int or bool """ if isinstance(sigOrVal, Value): return convertBits__val(self, sigOrVal, toType) elif isinstance(toType, HBool): if self.bit_length() == 1: v = 0 if sigOrVal._dtype.negated else 1 ...
Reinterpret signal of type Bits to signal of type HStruct
def reinterpret_bits_to_hstruct(sigOrVal, hStructT): """ Reinterpret signal of type Bits to signal of type HStruct """ container = hStructT.fromPy(None) offset = 0 for f in hStructT.fields: t = f.dtype width = t.bit_length() if f.name is not None: s = sigOrVal...
Cast object of same bit size between to other type ( f. e. bits to struct union or array )
def reinterpretBits(self, sigOrVal, toType): """ Cast object of same bit size between to other type (f.e. bits to struct, union or array) """ if isinstance(sigOrVal, Value): return reinterpretBits__val(self, sigOrVal, toType) elif isinstance(toType, Bits): return fitTo_t(sigOrVal...
Sort items from iterators ( generators ) by alwas selecting item with lowest value ( min first )
def iterSort(iterators, cmpFn): """ 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 """ actual = [] _itera...
: 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
def groupIntoChoices(splitsOnWord, wordWidth: int, origin: OneOfTransaction): """ :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 """ def cmpWordIndex(a, b)...
Count of complete words between two addresses
def fullWordCnt(self, start: int, end: int): """Count of complete words between two addresses """ assert end >= start, (start, end) gap = max(0, (end - start) - (start % self.wordWidth)) return gap // self.wordWidth
Group transaction parts splited on words to words
def groupByWordIndex(self, transaction: 'TransTmpl', offset: int): """ Group transaction parts splited on words to words :param transaction: TransTmpl instance which parts should be grupped into words :return: generator of tuples (wordIndex, list of transaction parts ...
: return: generator of TransPart instance
def splitOnWords(self, transaction, addrOffset=0): """ :return: generator of TransPart instance """ wordWidth = self.wordWidth end = addrOffset for tmp in transaction.walkFlatten(offset=addrOffset): if isinstance(tmp, OneOfTransaction): split =...
: 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
def fromPy(cls, val, typeObj, vldMask=None): """ :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 """ vld...
Pretty print interface
def pprintInterface(intf, prefix="", indent=0, file=sys.stdout): """ Pretty print interface """ try: s = intf._sig except AttributeError: s = "" if s is not "": s = " " + repr(s) file.write("".join([getIndent(indent), prefix, repr(intf._getFullName()), ...
Convert transaction template into FrameTmpls
def framesFromTransTmpl(transaction: 'TransTmpl', wordWidth: int, maxFrameLen: Union[int, float]=inf, maxPaddingWords: Union[int, float]=inf, trimPaddingWordsOnStart: bool=False, t...
Walk enumerated words in this frame
def walkWords(self, showPadding: bool=False): """ Walk enumerated words in this frame :attention: not all indexes has to be present, only words with items will be generated when not showPadding :param showPadding: padding TransParts are also present :return: generato...
Construct dictionary { StructField: value } for faster lookup of values for fields
def fieldToDataDict(dtype, data, res): """ Construct dictionary {StructField:value} for faster lookup of values for fields """ # assert data is None or isinstance(data, dict) for f in dtype.fields: try: fVal = data[f.name] except Ke...
Pack data into list of BitsVal of specified dataWidth
def packData(self, data): """ Pack data into list of BitsVal of specified dataWidth :param data: dict of values for struct fields {fieldName: value} :return: list of BitsVal which are representing values of words """ typeOfWord = simBitsT(self.wordWidth, None) f...