_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q272100
Cmd.do_help
test
def do_help(self, command): """Display this help message.""" if command: doc = getattr(self, 'do_' + command).__doc__ print(cyan(doc.replace(' ' * 8, ''))) else: print(magenta('Available commands:')) print(magenta('Type "HELP <command>" to get more info.')) names = self.get_names() names.sort() for name in names: if name[:3] != 'do_':
python
{ "resource": "" }
q272101
Cmd.do_DBINFO
test
def do_DBINFO(self, *args): """Print some useful infos from Redis DB.""" info = DB.info() keys = [ 'keyspace_misses', 'keyspace_hits', 'used_memory_human', 'total_commands_processed', 'total_connections_received', 'connected_clients'] for key in keys: print('{}: {}'.format(white(key), blue(info[key]))) nb_of_redis_db
python
{ "resource": "" }
q272102
Cmd.do_DBKEY
test
def do_DBKEY(self, key): """Print raw content of a DB key. DBKEY g|u09tyzfe""" type_ = DB.type(key).decode() if type_ == 'set': out = DB.smembers(key) elif type_ == 'string':
python
{ "resource": "" }
q272103
Cmd.do_GEOHASH
test
def do_GEOHASH(self, latlon): """Compute a geohash from latitude and longitude. GEOHASH 48.1234 2.9876""" try: lat, lon
python
{ "resource": "" }
q272104
Cmd.do_GET
test
def do_GET(self, _id): """Get document from index with its id. GET 772210180J""" doc = doc_by_id(_id) if not doc: return self.error('id "{}" not found'.format(_id)) for key, value in doc.items(): if key == config.HOUSENUMBERS_FIELD: continue print('{} {}'.format(white(key), magenta(value))) if doc.get('housenumbers'): def sorter(v): try:
python
{ "resource": "" }
q272105
Cmd.do_INDEX
test
def do_INDEX(self, _id): """Get index details for a document by its id. INDEX 772210180J""" doc = doc_by_id(_id) if not doc: return self.error('id "{}" not found'.format(_id)) for field in config.FIELDS:
python
{ "resource": "" }
q272106
Cmd.do_BESTSCORE
test
def do_BESTSCORE(self, word): """Return document linked to word with higher score. BESTSCORE lilas""" key = keys.token_key(indexed_string(word)[0])
python
{ "resource": "" }
q272107
Cmd.do_STRDISTANCE
test
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:
python
{ "resource": "" }
q272108
send
test
def send(r, stream=False): """Just sends the request using its send method and returns its response. """
python
{ "resource": "" }
q272109
map
test
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 run at a time. If 1, no parallel processing. :param exception_handler: Callback function, called when
python
{ "resource": "" }
q272110
getBits_from_array
test
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 from SimBits type) which contains copy of selected bits """ inPartOffset = 0 value = Bits(end - start, None).fromPy(None) while start != end: assert start < end, (start, end) dataWordIndex = start // wordWidth v = array[dataWordIndex] if reinterpretElmToType is not None: v = v._reinterpret_cast(reinterpretElmToType) endOfWord = (dataWordIndex + 1)
python
{ "resource": "" }
q272111
reinterptet_harray_to_bits
test
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(
python
{ "resource": "" }
q272112
slice_to_SLICE
test
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 = toHVal(sliceVals.start) if sliceVals.stop is None: stop = INT.fromPy(0) else:
python
{ "resource": "" }
q272113
find_files
test
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 recursive: for root, _, files in os.walk(directory): for basename in files: if fnmatch.fnmatch(basename, pattern): filename = os.path.join(root, basename)
python
{ "resource": "" }
q272114
In
test
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:
python
{ "resource": "" }
q272115
StaticForEach
test
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). It's content is performed in every iteration. When ack is high loop will fall to next iteration """ items = list(items) itemsCnt = len(items) if itemsCnt == 0: # if there are no items there is nothing to generate return [] elif itemsCnt == 1: # if there is only one item do not generate counter logic generate return bodyFn(items[0], 0) else: # if there is multiple items we have to generate counter logic index = parentUnit._reg(name + "for_index", Bits(log2ceil(itemsCnt + 1), signed=False), defVal=0) ackSig = parentUnit._sig(name + "for_ack")
python
{ "resource": "" }
q272116
sll
test
def sll(sig, howMany) -> RtlSignalBase: "Logical shift left" width = sig._dtype.bit_length()
python
{ "resource": "" }
q272117
log2ceil
test
def log2ceil(x): """ Returns no of bits required to store x-1 for example x=8 returns 3 """ if
python
{ "resource": "" }
q272118
isPow2
test
def isPow2(num) -> bool: """ Check if number or constant is power of two """ if not isinstance(num, int):
python
{ "resource": "" }
q272119
Switch.Case
test
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 self._case_value_index,
python
{ "resource": "" }
q272120
Switch.Default
test
def Default(self, *statements): """c-like default of switch statement """ assert self.parentStm is None self.rank += 1
python
{ "resource": "" }
q272121
VcdHdlSimConfig.vcdRegisterInterfaces
test
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 parent_ = self.vcdWriter if parent is None else parent subScope = parent_.varScope(name) self._obj2scope[obj] = subScope with subScope: # register all subinterfaces for chIntf in obj._interfaces: self.vcdRegisterInterfaces(chIntf, subScope) if isinstance(obj, (Unit, SimModel)): # register interfaces from all subunits for u in obj._units:
python
{ "resource": "" }
q272122
VcdHdlSimConfig.beforeSim
test
def beforeSim(self, simulator, synthesisedUnit): """ This method is called before first step of simulation. """ vcd = self.vcdWriter vcd.date(datetime.now())
python
{ "resource": "" }
q272123
VcdHdlSimConfig.logChange
test
def logChange(self, nowTime, sig, nextVal): """ This method is called for every value change of any signal. """ try: self.vcdWriter.logChange(nowTime, sig, nextVal)
python
{ "resource": "" }
q272124
SystemCSerializer_statements.HWProcess
test
def HWProcess(cls, proc, ctx): """ Serialize HWProcess instance :param scope: name scope to prevent name collisions """ body = proc.statements childCtx = ctx.withIndent()
python
{ "resource": "" }
q272125
autoAddAgents
test
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 intf._initSimAgent() assert intf._ag is not None, intf agents = [intf._ag, ] if intf._direction == INTF_DIRECTION.MASTER: agProcs = list(map(lambda a: a.getMonitors(), agents)) elif intf._direction == INTF_DIRECTION.SLAVE:
python
{ "resource": "" }
q272126
InterfaceceImplDependentFns._getAssociatedClk
test
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
python
{ "resource": "" }
q272127
distinctBy
test
def distinctBy(iterable, fn): """ uniq operation with key selector """ s = set() for i in iterable:
python
{ "resource": "" }
q272128
groupedby
test
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)
python
{ "resource": "" }
q272129
flatten
test
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,
python
{ "resource": "" }
q272130
IfContainer._merge_nested_if_from_else
test
def _merge_nested_if_from_else(self, ifStm: "IfContainer"): """ Merge nested IfContarner form else branch to this IfContainer
python
{ "resource": "" }
q272131
removeUnconnectedSignals
test
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._interface is not None: # skip interfaces before we want to check them, # they should not be optimized out from design continue except AttributeError: pass for e in sig.drivers: # drivers of this signal are useless rm them if isinstance(e, Operator): inputs = e.operands if e.result is sig: e.result = None else: inputs = e._inputs netlist.statements.discard(e) for op in inputs: if not isinstance(op, Value): try:
python
{ "resource": "" }
q272132
checkIfIsTooSimple
test
def checkIfIsTooSimple(proc): """check if process is just unconditional assignments and it is useless to merge them""" try: a, =
python
{ "resource": "" }
q272133
tryToMerge
test
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 checkIfIsTooSimple(procB) or areSetsIntersets(procA.outputs, procB.sensitivityList) or areSetsIntersets(procB.outputs, procA.sensitivityList) or not
python
{ "resource": "" }
q272134
reduceProcesses
test
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 same structure of statements into one # to minimize number of processes for _, procs in groupedby(processes, lambda p: p.rank): for iA, pA in enumerate(procs): if pA is None: continue for iB, pB
python
{ "resource": "" }
q272135
BramPort_withoutClkAgent.onWriteReq
test
def onWriteReq(self, sim, addr, data): """ on writeReqRecieved in
python
{ "resource": "" }
q272136
toRtl
test
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 override of top unit (if is None name is derived form class name) :param serializer: serializer which should be used for to RTL conversion :param targetPlatform: metainformatins about target platform, distributed on every unit under _targetPlatform attribute before Unit._impl() is called :param saveTo: directory where files should be stored If None RTL is returned as string. :raturn: if saveTo returns RTL string else returns list of file names which were created """ if not isinstance(unitOrCls, Unit): u = unitOrCls() else: u = unitOrCls u._loadDeclarations() if name is not None: assert isinstance(name, str) u._name = name globScope = serializer.getBaseNameScope() mouduleScopes = {} # unitCls : unitobj serializedClasses = {} # (unitCls, paramsValues) : unitObj # where paramsValues are dict name:value serializedConfiguredUnits = {} doSerialize = True createFiles = saveTo is not None if createFiles: os.makedirs(saveTo, exist_ok=True) files = UniqList() else: codeBuff = [] for obj in u._toRtl(targetPlatform): doSerialize = serializer.serializationDecision( obj, serializedClasses, serializedConfiguredUnits)
python
{ "resource": "" }
q272137
name_for_process_and_mark_outputs
test
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:
python
{ "resource": "" }
q272138
cut_off_drivers_of
test
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:
python
{ "resource": "" }
q272139
RtlNetlist.sig
test
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): assert defVal._const, \ "Initial value of register has to be constant" _defVal = defVal._auto_cast(dtype) elif isinstance(defVal, Value): _defVal = defVal._auto_cast(dtype) elif isinstance(defVal, InterfaceBase): _defVal = defVal._sig else: _defVal = dtype.fromPy(defVal) if clk is not None: s = RtlSyncSignal(self, name, dtype, _defVal) if syncRst is not None and defVal is None: raise SigLvlConfErr( "Probably forgotten default value on sync signal %s", name) if syncRst is not None:
python
{ "resource": "" }
q272140
RtlNetlist.synthesize
test
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.generics.append(v) # interface set for faster lookup if isinstance(interfaces, set): intfSet = interfaces else: intfSet = set(interfaces) # create ports for s in interfaces: pi = portItemfromSignal(s, ent) pi.registerInternSig(s)
python
{ "resource": "" }
q272141
getMaxStmIdForStm
test
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:
python
{ "resource": "" }
q272142
maxStmId
test
def maxStmId(proc): """ get max statement id, used for sorting of processes in architecture """ maxId = 0 for
python
{ "resource": "" }
q272143
RdSyncedAgent.doWrite
test
def doWrite(self, sim, data): """write data to interface"""
python
{ "resource": "" }
q272144
Interface._m
test
def _m(self): """ Note that this interface will be master :return: self """ assert not hasattr(self, "_interfaces") or not self._interfaces, \ "Too
python
{ "resource": "" }
q272145
Interface._loadDeclarations
test
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() self._setAttrListener = None for i in self._interfaces: i._isExtern = self._isExtern i._loadDeclarations() for p in self._params: p.setReadOnly()
python
{ "resource": "" }
q272146
Interface._signalsForInterface
test
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 created signals :param typeTransform: optional function (type) returns modified type for signal """ sigs = [] if self._interfaces: for intf in self._interfaces: sigs.extend( intf._signalsForInterface(context, prefix, typeTransform=typeTransform)) else: if hasattr(self, '_sig'): sigs = [self._sig]
python
{ "resource": "" }
q272147
Interface._getPhysicalName
test
def _getPhysicalName(self): """Get name in HDL """ if hasattr(self, "_boundedEntityPort"): return self._boundedEntityPort.name
python
{ "resource": "" }
q272148
Interface._bit_length
test
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:
python
{ "resource": "" }
q272149
sensitivityByOp
test
def sensitivityByOp(op): """ get sensitivity type for operator """ if op == AllOps.RISING_EDGE:
python
{ "resource": "" }
q272150
OpDefinition.eval
test
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.operator):
python
{ "resource": "" }
q272151
convertBits
test
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 return sigOrVal._eq(self.getValueCls().fromPy(v, self)) elif isinstance(toType, Bits):
python
{ "resource": "" }
q272152
reinterpret_bits_to_hstruct
test
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
python
{ "resource": "" }
q272153
TransTmplWordIterator.fullWordCnt
test
def fullWordCnt(self, start: int, end: int): """Count of complete words between two addresses
python
{ "resource": "" }
q272154
TransTmplWordIterator.groupByWordIndex
test
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 in this word) """ actualW = None partsInWord = [] wordWidth = self.wordWidth for item in self.splitOnWords(transaction, offset): _actualW = item.startOfPart // wordWidth if actualW is None:
python
{ "resource": "" }
q272155
pprintInterface
test
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()), s])) file.write("\n") if isinstance(intf, HObjList): for i, p in enumerate(intf): # interfaces have already name
python
{ "resource": "" }
q272156
FrameTmpl.framesFromTransTmpl
test
def framesFromTransTmpl(transaction: 'TransTmpl', wordWidth: int, maxFrameLen: Union[int, float]=inf, maxPaddingWords: Union[int, float]=inf, trimPaddingWordsOnStart: bool=False, trimPaddingWordsOnEnd: bool=False) -> Generator[ 'FrameTmpl', None, None]: """ Convert transaction template into FrameTmpls :param transaction: transaction template used which are FrameTmpls created from :param wordWidth: width of data signal in target interface where frames will be used :param maxFrameLen: maximum length of frame in bits, if exceeded another frame will be created :param maxPaddingWords: maximum of continual padding words in frame, if exceed frame is split and words are cut of :attention: if maxPaddingWords<inf trimPaddingWordsOnEnd or trimPaddingWordsOnStart has to be True to decide where padding should be trimmed :param trimPaddingWordsOnStart: trim padding from start of frame at word granularity :param trimPaddingWordsOnEnd: trim padding from end of frame at word granularity """ isFirstInFrame = True partsPending = False startOfThisFrame = 0 assert maxFrameLen > 0 assert maxPaddingWords >= 0 if maxPaddingWords < inf: assert trimPaddingWordsOnStart or trimPaddingWordsOnEnd, \ "Padding has to be cut off somewhere" it = TransTmplWordIterator(wordWidth) lastWordI = 0 endOfThisFrame = maxFrameLen parts = [] for wordI, word in it.groupByWordIndex(transaction, 0): if wordI * wordWidth >= endOfThisFrame: # now in first+ word behind the frame # cut off padding at end of frame paddingWords = wordI - lastWordI if trimPaddingWordsOnEnd and paddingWords > maxPaddingWords: # cut off padding and align end of frame to word _endOfThisFrame = (lastWordI + 1) * wordWidth else: _endOfThisFrame = wordI * wordWidth yield FrameTmpl(transaction, wordWidth, startOfThisFrame, _endOfThisFrame, parts) # prepare for start of new frame parts = [] isFirstInFrame = True partsPending = False # start on new word startOfThisFrame = _endOfThisFrame endOfThisFrame = startOfThisFrame + maxFrameLen lastWordI = wordI # check if padding at potential end of frame can be cut off if (not isFirstInFrame and trimPaddingWordsOnEnd and wordI - lastWordI > 1): # there is too much continual padding, # cut it out and start new frame _endOfThisFrame = (lastWordI + 1) * wordWidth yield FrameTmpl(transaction, wordWidth, startOfThisFrame, _endOfThisFrame,
python
{ "resource": "" }
q272157
FrameTmpl.walkWords
test
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: generator of tuples (wordIndex, list of TransParts in this word) """ wIndex = 0 lastEnd = self.startBitAddr parts = [] for p in self.parts: end = p.startOfPart if showPadding and end != lastEnd: # insert padding while end != lastEnd: assert end >= lastEnd, (end, lastEnd) endOfWord = ceil( (lastEnd + 1) / self.wordWidth) * self.wordWidth endOfPadding = min(endOfWord, end) _p = TransPart(self, None, lastEnd, endOfPadding, 0) parts.append(_p) if endOfPadding >= endOfWord: yield (wIndex, parts) wIndex += 1 parts = [] lastEnd = endOfPadding if self._wordIndx(lastEnd) != self._wordIndx(p.startOfPart): yield (wIndex, parts) wIndex += 1 parts = [] lastEnd = p.endOfPart parts.append(p) lastEnd = p.endOfPart if lastEnd % self.wordWidth == 0: yield (wIndex, parts) wIndex += 1
python
{ "resource": "" }
q272158
FrameTmpl.packData
test
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) fieldToVal = self._fieldToTPart if fieldToVal is None: fieldToVal = self._fieldToTPart = self.fieldToDataDict( self.origin.dtype, data, {}) for _, transParts in self.walkWords(showPadding=True): actualVldMask = 0 actualVal = 0 for tPart in transParts: high, low = tPart.getBusWordBitRange() fhigh, flow = tPart.getFieldBitRange() if not tPart.isPadding: val = fieldToVal.get(tPart.tmpl.origin, None) else:
python
{ "resource": "" }
q272159
HdlStatement._clean_signal_meta
test
def _clean_signal_meta(self): """ Clean informations about enclosure for outputs and sensitivity
python
{ "resource": "" }
q272160
HdlStatement._discover_enclosure_for_statements
test
def _discover_enclosure_for_statements(statements: List['HdlStatement'], outputs: List['HdlStatement']): """ Discover enclosure for list of statements :param statements: list of statements in one code branch :param outputs: list of outputs which should be driven from this statement list :return: set of signals for which this statement list have always some driver
python
{ "resource": "" }
q272161
HdlStatement._discover_sensitivity_seq
test
def _discover_sensitivity_seq(self, signals: List[RtlSignalBase], seen: set, ctx: SensitivityCtx)\ -> None: """ Discover sensitivity for list of signals
python
{ "resource": "" }
q272162
HdlStatement._get_rtl_context
test
def _get_rtl_context(self): """ get RtlNetlist context from signals """ for sig in chain(self._inputs, self._outputs): if sig.ctx: return sig.ctx else:
python
{ "resource": "" }
q272163
HdlStatement._on_reduce
test
def _on_reduce(self, self_reduced: bool, io_changed: bool, result_statements: List["HdlStatement"]) -> None: """ Update signal IO after reuce atempt :param self_reduced: if True this object was reduced :param io_changed: if True IO of this object may changed and has to be updated :param result_statements: list of statements which are result of reduce operation on this statement """ parentStm = self.parentStm if self_reduced: was_top = parentStm is None # update signal drivers/endpoints if was_top: # disconnect self from signals ctx = self._get_rtl_context() ctx.statements.remove(self) ctx.statements.update(result_statements) for i in self._inputs: i.endpoints.discard(self) for o in self._outputs:
python
{ "resource": "" }
q272164
HdlStatement._on_merge
test
def _on_merge(self, other): """ After merging statements update IO, sensitivity and context :attention: rank is not updated """ self._inputs.extend(other._inputs) self._outputs.extend(other._outputs) if self._sensitivity is not None: self._sensitivity.extend(other._sensitivity) else: assert other._sensitivity is None if self._enclosed_for is not None: self._enclosed_for.update(other._enclosed_for) else: assert other._enclosed_for is None other_was_top = other.parentStm is None
python
{ "resource": "" }
q272165
HdlStatement._is_mergable_statement_list
test
def _is_mergable_statement_list(cls, stmsA, stmsB): """ Walk statements and compare if they can be merged into one statement list """ if stmsA is None and stmsB is None: return True elif stmsA is None or stmsB is None: return False a_it = iter(stmsA) b_it = iter(stmsB) a = _get_stm_with_branches(a_it) b = _get_stm_with_branches(b_it) while a is not None or b is not None:
python
{ "resource": "" }
q272166
HdlStatement._merge_statements
test
def _merge_statements(statements: List["HdlStatement"])\ -> Tuple[List["HdlStatement"], int]: """ Merge statements in list to remove duplicated if-then-else trees :return: tuple (list of merged statements, rank decrease due merging) :note: rank decrease is sum of ranks of reduced statements :attention: statement list has to me mergable """ order = {} for i, stm in enumerate(statements): order[stm] = i new_statements = [] rank_decrease = 0 for rank, stms in groupedby(statements, lambda s: s.rank): if rank == 0: new_statements.extend(stms) else:
python
{ "resource": "" }
q272167
HdlStatement._merge_statement_lists
test
def _merge_statement_lists(stmsA: List["HdlStatement"], stmsB: List["HdlStatement"])\ -> List["HdlStatement"]: """ Merge two lists of statements into one :return: list of merged statements """ if stmsA is None and stmsB is None: return None tmp = [] a_it = iter(stmsA) b_it = iter(stmsB) a = None b = None a_empty = False b_empty = False while not a_empty and not b_empty: while not a_empty: a = next(a_it, None)
python
{ "resource": "" }
q272168
HdlStatement._try_reduce_list
test
def _try_reduce_list(statements: List["HdlStatement"]): """ Simplify statements in the list """ io_change = False new_statements = [] for stm in statements: reduced, _io_change = stm._try_reduce() new_statements.extend(reduced)
python
{ "resource": "" }
q272169
HdlStatement._on_parent_event_dependent
test
def _on_parent_event_dependent(self): """ After parrent statement become event dependent propagate event dependency flag to child statements
python
{ "resource": "" }
q272170
HdlStatement._set_parent_stm
test
def _set_parent_stm(self, parentStm: "HdlStatement"): """ Assign parent statement and propagate dependency flags if necessary """ was_top = self.parentStm is None self.parentStm = parentStm if not self._now_is_event_dependent\ and parentStm._now_is_event_dependent: self._on_parent_event_dependent() topStatement = parentStm while topStatement.parentStm is not None: topStatement = topStatement.parentStm parent_out_add = topStatement._outputs.append parent_in_add = topStatement._inputs.append if was_top: for inp in self._inputs:
python
{ "resource": "" }
q272171
HdlStatement._register_stements
test
def _register_stements(self, statements: List["HdlStatement"], target: List["HdlStatement"]): """ Append statements to this container under conditions specified by condSet """ for stm in
python
{ "resource": "" }
q272172
HdlStatement._destroy
test
def _destroy(self): """ 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 """ ctx = self._get_rtl_context()
python
{ "resource": "" }
q272173
UnitImplHelpers._reg
test
def _reg(self, name, dtype=BIT, defVal=None, clk=None, rst=None): """ Create register in this unit :param defVal: default value of this register, if this value is specified reset of this component is used (unit has to have single interface of class Rst or Rst_n) :param clk: optional clok signal specification :param rst: optional reset signal specification :note: rst/rst_n resolution is done from signal type, if it is negated type it is rst_n :note: if clk or rst is not specifid default signal from parent unit will be used """ if clk is None: clk = getClk(self) if defVal is None: # if no value is specified reset is not required rst = None else: rst = getRst(self)._sig if isinstance(dtype, HStruct):
python
{ "resource": "" }
q272174
UnitImplHelpers._sig
test
def _sig(self, name, dtype=BIT, defVal=None): """ Create signal in this unit """ if isinstance(dtype, HStruct): if defVal is not None: raise NotImplementedError() container = dtype.fromPy(None) for f in dtype.fields: if f.name is not None: r
python
{ "resource": "" }
q272175
UnitImplHelpers._cleanAsSubunit
test
def _cleanAsSubunit(self): """Disconnect internal signals so unit can be reused by parent unit"""
python
{ "resource": "" }
q272176
walkFlattenFields
test
def walkFlattenFields(sigOrVal, skipPadding=True): """ Walk all simple values in HStruct or HArray """ t = sigOrVal._dtype if isinstance(t, Bits): yield sigOrVal elif isinstance(t, HUnion): yield from walkFlattenFields(sigOrVal._val, skipPadding=skipPadding) elif isinstance(t, HStruct): for f in t.fields: isPadding = f.name is None if not isPadding or not skipPadding: if isPadding:
python
{ "resource": "" }
q272177
HStruct_unpack
test
def HStruct_unpack(structT, data, getDataFn=None, dataWidth=None): """ opposite of packAxiSFrame """ if getDataFn is None: assert dataWidth is not None def _getDataFn(x): return toHVal(x)._auto_cast(Bits(dataWidth)) getDataFn = _getDataFn val = structT.fromPy(None) fData = iter(data) # actual is storage variable for items from frameData actualOffset = 0 actual = None for v in walkFlattenFields(val, skipPadding=False): # walk flatten fields and take values from fData and parse them to # field required = v._dtype.bit_length() if actual is None: actualOffset = 0 try: actual = getDataFn(next(fData)) except StopIteration: raise Exception("Input data too short") if dataWidth is None: dataWidth = actual._dtype.bit_length() actuallyHave = dataWidth else: actuallyHave = actual._dtype.bit_length() - actualOffset while actuallyHave < required: # collect data for this field try: d = getDataFn(next(fData))
python
{ "resource": "" }
q272178
BitsVal._convSign
test
def _convSign(self, signed): """ Convert signum, no bit manipulation just data are represented differently :param signed: if True value will be signed, if False value will be unsigned, if None value will be vector without any sign specification """ if isinstance(self, Value): return self._convSign__val(signed) else: if self._dtype.signed == signed: return self
python
{ "resource": "" }
q272179
sensitivity
test
def sensitivity(proc: HWProcess, *sensitiveTo): """ register sensitivity for process """ for s in sensitiveTo: if isinstance(s, tuple): sen, s = s if sen == SENSITIVITY.ANY:
python
{ "resource": "" }
q272180
simEvalCond
test
def simEvalCond(simulator, *conds): """ Evaluate list of values as condition """ _cond = True _vld = True for v in conds: val = bool(v.val)
python
{ "resource": "" }
q272181
connectSimPort
test
def connectSimPort(simUnit, subSimUnit, srcName, dstName, direction): """ Connect ports of simulation models by name """ if direction == DIRECTION.OUT: origPort = getattr(subSimUnit, srcName) newPort = getattr(simUnit, dstName) setattr(subSimUnit, srcName, newPort) else:
python
{ "resource": "" }
q272182
mkUpdater
test
def mkUpdater(nextVal: Value, invalidate: bool): """ Create value updater for simulation :param nextVal: instance of Value which will be asssiggned to signal :param invalidate: flag which tells if value has been compromised and if it should be invaidated :return: function(value) -> tuple(valueHasChangedFlag, nextVal) """ def updater(currentVal):
python
{ "resource": "" }
q272183
mkArrayUpdater
test
def mkArrayUpdater(nextItemVal: Value, indexes: Tuple[Value], invalidate: bool): """ 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)
python
{ "resource": "" }
q272184
vec
test
def vec(val, width, signed=None): """create hdl
python
{ "resource": "" }
q272185
ResourceAnalyzer.HWProcess
test
def HWProcess(cls, proc: HWProcess, ctx: ResourceContext) -> None: """ Gues resource usage by HWProcess """ seen = ctx.seen for stm in proc.statements: encl = stm._enclosed_for full_ev_dep = stm._is_completly_event_dependent now_ev_dep = stm._now_is_event_dependent ev_dep = full_ev_dep or now_ev_dep out_mux_dim = count_mux_inputs_for_outputs(stm) for o in stm._outputs: if o in seen: continue i = out_mux_dim[o] if isinstance(o._dtype, HArray): assert i == 1, (o, i, " only one ram port per HWProcess") for a in walk_assignments(stm, o): assert len(a.indexes) == 1, "one address per RAM port" addr = a.indexes[0] ctx.registerRAM_write_port(o, addr, ev_dep) elif ev_dep: ctx.registerFF(o) if i > 1: ctx.registerMUX(stm, o, i) elif o not in encl: ctx.registerLatch(o) if i > 1: ctx.registerMUX(stm, o, i) elif i > 1: ctx.registerMUX(stm, o, i)
python
{ "resource": "" }
q272186
evalParam
test
def evalParam(p): """ Get value of parameter """ while isinstance(p, Param): p = p.get() if isinstance(p, RtlSignalBase): return p.staticEval()
python
{ "resource": "" }
q272187
Param.set
test
def set(self, val): """ set value of this param """ assert not self.__isReadOnly, \ ("This parameter(%s) was locked" " and now it can not be changed" % self.name) assert self.replacedWith is None, \ ("This param was replaced with new one and
python
{ "resource": "" }
q272188
HTypeFromIntfMap
test
def HTypeFromIntfMap(interfaceMap): """ Generate flattened register map for HStruct :param interfaceMap: sequence of tuple (type, name) or (will create standard struct field member) interface or (will create a struct field from interface) instance of hdl type (is used as padding) tuple (list of interface, name) :param DATA_WIDTH: width of word :param terminalNodes: None or set whre
python
{ "resource": "" }
q272189
ResourceContext.finalize
test
def finalize(self): """ Resolve ports of discovered memories """ ff_to_remove = 0 res = self.resources for m, addrDict in self.memories.items(): rwSyncPorts, rSyncPorts, wSyncPorts = 0, 0, 0 rwAsyncPorts, rAsyncPorts, wAsyncPorts = 0, 0, 0 rSync_wAsyncPorts, rAsync_wSyncPorts = 0, 0 for _, (rSync, wSync, rAsync, wAsync) in addrDict.items(): if rSync: ff_to_remove += rSync * m._dtype.elmType.bit_length() # resolve port count for this addr signal rwSync = min(rSync, wSync) rSync -= rwSync wSync -= rwSync rwAsync = min(rAsync, wAsync) rAsync -= rwAsync wAsync -= rwAsync rSync_wAsync = min(rSync, wAsync)
python
{ "resource": "" }
q272190
RtlSignalOps._getIndexCascade
test
def _getIndexCascade(self): """ Find out if this signal is something indexed """ try: # now I am result of the index xxx[xx] <= source # get index op d = self.singleDriver() try: op = d.operator except AttributeError: return if op == AllOps.INDEX: # get signal on which is index applied indexedOn = d.operands[0]
python
{ "resource": "" }
q272191
HdlType.fromPy
test
def fromPy(self, v, vldMask=None): """ Construct value of this type. Delegated on value class for this type
python
{ "resource": "" }
q272192
HdlType.auto_cast
test
def auto_cast(self, sigOrVal, toType): """ Cast value or signal of this type to another compatible type. :param sigOrVal: instance of signal or value to cast :param toType: instance of HdlType to
python
{ "resource": "" }
q272193
HdlType.reinterpret_cast
test
def reinterpret_cast(self, sigOrVal, toType): """ Cast value or signal of this type to another type of same size. :param sigOrVal: instance of signal or value to cast :param toType: instance of HdlType to cast into """ try: return self.auto_cast(sigOrVal, toType) except TypeConversionErr: pass try:
python
{ "resource": "" }
q272194
walkParams
test
def walkParams(intf, discovered): """ walk parameter instances on this interface """ for si in intf._interfaces: yield from walkParams(si, discovered) for
python
{ "resource": "" }
q272195
connectPacked
test
def connectPacked(srcPacked, dstInterface, exclude=None): """ Connect 1D vector signal to this structuralized interface :param packedSrc: vector which should be connected :param dstInterface: structuralized interface where should packedSrc be connected to :param exclude: sub interfaces of self which should be excluded """ offset = 0 connections = [] for i in reversed(list(walkPhysInterfaces(dstInterface))): if exclude is not None and i in exclude: continue sig = i._sig
python
{ "resource": "" }
q272196
packIntf
test
def packIntf(intf, masterDirEqTo=DIRECTION.OUT, exclude=None): """ Concatenate all signals to one big signal, recursively :param masterDirEqTo: only signals with this direction are packed :param exclude: sequence of signals/interfaces to exclude """ if not intf._interfaces: if intf._masterDir == masterDirEqTo: return intf._sig return None res = None for i in
python
{ "resource": "" }
q272197
VerilogSerializer.hardcodeRomIntoProcess
test
def hardcodeRomIntoProcess(cls, rom): """ Due to verilog restrictions it is not posible to use array constants and rom memories has to be hardcoded as process """ processes = [] signals = [] for e in rom.endpoints: assert isinstance(e, Operator) and e.operator == AllOps.INDEX, e me, index = e.operands assert me is rom # construct output of the rom romValSig = rom.ctx.sig(rom.name, dtype=e.result._dtype) signals.append(romValSig) romValSig.hidden = False # construct process which will represent content of the rom cases = [(toHVal(i), [romValSig(v), ]) for i, v in enumerate(rom.defVal.val)] statements = [SwitchContainer(index, cases), ] for (_, (stm, )) in cases: stm.parentStm = statements[0] p = HWProcess(rom.name, statements, {index, },
python
{ "resource": "" }
q272198
Unit._toRtl
test
def _toRtl(self, targetPlatform: DummyPlatform): """ synthesize all subunits, make connections between them, build entity and component for this unit """ assert not self._wasSynthetised() self._targetPlatform = targetPlatform if not hasattr(self, "_name"): self._name = self._getDefaultName() for proc in targetPlatform.beforeToRtl: proc(self) self._ctx.params = self._buildParams() self._externInterf = [] # prepare subunits for u in self._units: yield from u._toRtl(targetPlatform) for u in self._units: subUnitName = u._name u._signalsForMyEntity(self._ctx, "sig_" + subUnitName) # prepare signals for interfaces for i in self._interfaces: signals = i._signalsForInterface(self._ctx) if i._isExtern: self._externInterf.extend(signals) for proc in targetPlatform.beforeToRtlImpl: proc(self) self._loadMyImplementations()
python
{ "resource": "" }
q272199
Unit._registerIntfInImpl
test
def _registerIntfInImpl(self, iName, intf): """ Register interface in implementation phase """ self._registerInterface(iName,
python
{ "resource": "" }