Search is not available for this dataset
text
stringlengths
75
104k
def _tryConnect(src, unit, intfName): """ Try connect src to interface of specified name on unit. Ignore if interface is not present or if it already has driver. """ try: dst = getattr(unit, intfName) except AttributeError: return if not dst._sig.drivers: connect(src,...
def propagateClk(obj): """ Propagate "clk" clock signal to all subcomponents """ clk = obj.clk for u in obj._units: _tryConnect(clk, u, 'clk')
def propagateClkRstn(obj): """ Propagate "clk" clock and negative reset "rst_n" signal to all subcomponents """ clk = obj.clk rst_n = obj.rst_n for u in obj._units: _tryConnect(clk, u, 'clk') _tryConnect(rst_n, u, 'rst_n') _tryConnect(~rst_n, u, 'rst')
def propagateClkRst(obj): """ Propagate "clk" clock and reset "rst" signal to all subcomponents """ clk = obj.clk rst = obj.rst for u in obj._units: _tryConnect(clk, u, 'clk') _tryConnect(~rst, u, 'rst_n') _tryConnect(rst, u, 'rst')
def propagateRstn(obj): """ Propagate negative reset "rst_n" signal to all subcomponents """ rst_n = obj.rst_n for u in obj._units: _tryConnect(rst_n, u, 'rst_n') _tryConnect(~rst_n, u, 'rst')
def propagateRst(obj): """ Propagate reset "rst" signal to all subcomponents """ rst = obj.rst for u in obj._units: _tryConnect(~rst, u, 'rst_n') _tryConnect(rst, u, 'rst')
def fitTo_t(what: Union[RtlSignal, Value], where_t: HdlType, extend: bool=True, shrink: bool=True): """ Slice signal "what" to fit in "where" or arithmetically (for signed by MSB / unsigned, vector with 0) extend "what" to same width as "where" little-endian impl. """ whatW...
def iterBits(sigOrVal: Union[RtlSignal, Value], bitsInOne: int=1, skipPadding: bool=True, fillup: bool=False): """ 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...
def _get(self, numberOfBits: int, doCollect: bool): """ :param numberOfBits: number of bits to get from actual possition :param doCollect: if False output is not collected just iterator moves in structure """ if not isinstance(numberOfBits, int): numberOfB...
def get(self, numberOfBits: int) -> Union[RtlSignal, Value]: """ :param numberOfBits: number of bits to get from actual possition :return: chunk of bits of specified size (instance of Value or RtlSignal) """ return self._get(numberOfBits, True)
def _serializeExclude_eval(parentUnit, obj, isDeclaration, priv): """ Always decide not to serialize obj :param priv: private data for this function first unit of this class :return: tuple (do serialize this object, next priv) """ if isDeclaration: # prepare entity which will not be ser...
def _serializeOnce_eval(parentUnit, obj, isDeclaration, priv): """ Decide to serialize only first obj of it's class :param priv: private data for this function (first object with class == obj.__class__) :return: tuple (do serialize this object, next priv) where priv is private data for...
def _serializeParamsUniq_eval(parentUnit, obj, isDeclaration, priv): """ 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) """ params = paramsToValTuple(p...
def _getFullName(self): """get all name hierarchy separated by '.' """ name = "" tmp = self while isinstance(tmp, (InterfaceBase, HObjList)): if hasattr(tmp, "_name"): n = tmp._name else: n = '' if name == '': ...
def _make_association(self, *args, **kwargs): """ Delegate _make_association on items :note: doc in :func:`~hwt.synthesizer.interfaceLevel.propDeclCollector._make_association` """ for o in self: o._make_association(*args, **kwargs)
def _updateParamsFrom(self, *args, **kwargs): """ :note: doc in :func:`~hwt.synthesizer.interfaceLevel.propDeclCollector._updateParamsFrom` """ for o in self: o._updateParamsFrom(*args, **kwargs)
def simPrepare(unit: Unit, modelCls: Optional[SimModel]=None, targetPlatform=DummyPlatform(), dumpModelIn: str=None, onAfterToRtl=None): """ Create simulation model and connect it with interfaces of original unit and decorate it with agents :param unit: interface level uni...
def toSimModel(unit, targetPlatform=DummyPlatform(), dumpModelIn=None): """ Create a simulation model for unit :param unit: interface level unit which you wont prepare for simulation :param targetPlatform: target platform for this synthes :param dumpModelIn: folder to where put sim model files ...
def reconnectUnitSignalsToModel(synthesisedUnitOrIntf, modelCls): """ Reconnect model signals to unit to run simulation with simulation model but use original unit interfaces for communication :param synthesisedUnitOrIntf: interface where should be signals replaced from signals from modelCls ...
def simUnitVcd(simModel, stimulFunctions, outputFile=sys.stdout, until=100 * Time.ns): """ Syntax sugar If outputFile is string try to open it as file :return: hdl simulator object """ assert isinstance(simModel, SimModel), \ "Class of SimModel is required (got %r)" % (si...
def _simUnitVcd(simModel, stimulFunctions, outputFile, until): """ :param unit: interface level unit to simulate :param stimulFunctions: iterable of function(env) (simpy environment) which are driving the simulation :param outputFile: file where vcd will be dumped :param time: endtime of sim...
def oscilate(sig, period=10 * Time.ns, initWait=0): """ Oscillative simulation driver for your signal (usually used as clk generator) """ def oscillateStimul(s): s.write(False, sig) halfPeriod = period / 2 yield s.wait(initWait) while True: yield s.wait(h...
def onTWriteCallback__init(self, sim): """ Process for injecting of this callback loop into simulator """ yield from self.onTWriteCallback(sim) self.intf.t._sigInside.registerWriteCallback( self.onTWriteCallback, self.getEnable) self.intf.o._sigIns...
def connectSig(self, signal): """ Connect to port item on subunit """ if self.direction == DIRECTION.IN: if self.src is not None: raise HwtSyntaxError( "Port %s is already associated with %r" % (self.name, self.src)) ...
def registerInternSig(self, signal): """ Connect internal signal to port item, this connection is used by simulator and only output port items will be connected """ if self.direction == DIRECTION.OUT: if self.src is not None: raise HwtSyntaxErr...
def connectInternSig(self): """ connet signal from internal side of of this component to this port """ d = self.direction if d == DIRECTION.OUT: self.src.endpoints.append(self) elif d == DIRECTION.IN or d == DIRECTION.INOUT: self.dst.drivers.append...
def getInternSig(self): """ return signal inside unit which has this port """ d = self.direction if d == DIRECTION.IN: return self.dst elif d == DIRECTION.OUT: return self.src else: raise NotImplementedError(d)
def isEvDependentOn(sig, process) -> bool: """ Check if hdl process has event depenency on signal """ if sig is None: return False return process in sig.simFallingSensProcs\ or process in sig.simRisingSensProcs
def _add_process(self, proc, priority) -> None: """ Schedule process on actual time with specified priority """ self._events.push(self.now, priority, proc)
def _addHdlProcToRun(self, trigger: SimSignal, proc) -> None: """ Add hdl process to execution queue :param trigger: instance of SimSignal :param proc: python generator function representing HDL process """ # first process in time has to plan executing of apply values on...
def _initUnitSignals(self, unit: Unit) -> None: """ * Inject default values to simulation * Instantiate IOs for every process """ # set initial value to all signals and propagate it for s in unit._ctx.signals: if s.defVal.vldMask: v = s.defVal...
def _scheduleCombUpdateDoneEv(self) -> Event: """ Schedule combUpdateDoneEv event to let agents know that current delta step is ending and values from combinational logic are stable """ assert not self._combUpdateDonePlaned, self.now cud = Event(self) cud.process_...
def _scheduleApplyValues(self) -> None: """ Apply stashed values to signals """ assert not self._applyValPlaned, self.now self._add_process(self._applyValues(), PRIORITY_APPLY_COMB) self._applyValPlaned = True if self._runSeqProcessesPlaned: # if runS...
def _conflictResolveStrategy(self, newValue: set)\ -> Tuple[Callable[[Value], bool], bool]: """ This functions resolves write conflicts for signal :param actionSet: set of actions made by process """ invalidate = False resLen = len(newValue) if resLe...
def _runCombProcesses(self) -> None: """ Delta step for combinational processes """ for proc in self._combProcsToRun: cont = self._outputContainers[proc] proc(self, cont) for sigName, sig in cont._all_signals: newVal = getattr(cont, sig...
def _runSeqProcesses(self) -> Generator[None, None, None]: """ Delta step for event dependent processes """ updates = [] for proc in self._seqProcsToRun: try: outContainer = self._outputContainers[proc] except KeyError: # pr...
def _applyValues(self) -> Generator[None, None, None]: """ Perform delta step by writing stacked values to signals """ va = self._valuesToApply self._applyValPlaned = False # log if there are items to log lav = self.config.logApplyingValues if va and lav:...
def read(self, sig) -> Value: """ Read value from signal or interface """ try: v = sig._val except AttributeError: v = sig._sigInside._val return v.clone()
def write(self, val, sig: SimSignal)-> None: """ Write value to signal or interface. """ # get target RtlSignal try: simSensProcs = sig.simSensProcs except AttributeError: sig = sig._sigInside simSensProcs = sig.simSensProcs # ...
def run(self, until: float) -> None: """ Run simulation until specified time :note: can be used to run simulation again after it ends from time when it ends """ assert until > self.now events = self._events schedule = events.push next_event = events.pop ...
def add_process(self, proc) -> None: """ Add process to events with default priority on current time """ self._events.push(self.now, PRIORITY_NORMAL, proc)
def simUnit(self, synthesisedUnit: Unit, until: float, extraProcesses=[]): """ Run simulation for Unit instance """ beforeSim = self.config.beforeSim if beforeSim is not None: beforeSim(self, synthesisedUnit) add_proc = self.add_process for p in extra...
def _mkOp(fn): """ Function to create variadic operator function :param fn: function to perform binary operation """ def op(*operands, key=None) -> RtlSignalBase: """ :param operands: variadic parameter of input uperands :param key: optional function applied on every operand...
def systemCTypeOfSig(signalItem): """ Check if is register or wire """ if signalItem._const or\ arr_any(signalItem.drivers, lambda d: isinstance(d, HdlStatement) and d._now_is_event_dependent): return SIGNAL_TYPE.REG else: return SIGNAL_TYPE.WIRE
def ternaryOpsToIf(statements): """Convert all ternary operators to IfContainers""" stms = [] for st in statements: if isinstance(st, Assignment): try: if not isinstance(st.src, RtlSignalBase): raise DoesNotContainsTernary() d = st.src...
def HWProcess(cls, proc, ctx): """ Serialize HWProcess objects as VHDL :param scope: name scope to prevent name collisions """ body = proc.statements extraVars = [] extraVarsSerialized = [] hasToBeVhdlProcess = arr_any(body, ...
def hash_distance(left_hash, right_hash): """Compute the hamming distance between two hashes""" if len(left_hash) != len(right_hash): raise ValueError('Hamming distance requires two strings of equal length') return sum(map(lambda x: 0 if x[0] == x[1] else 1, zip(left_hash, right_hash)))
def average_hash(image_path, hash_size=8): """ Compute the average hash of the given image. """ with open(image_path, 'rb') as f: # Open the image, resize it and convert it to black & white. image = Image.open(f).resize((hash_size, hash_size), Image.ANTIALIAS).convert('L') pixels = list(...
def distance(image_path, other_image_path): """ Compute the hamming distance between two images""" image_hash = average_hash(image_path) other_image_hash = average_hash(other_image_path) return hash_distance(image_hash, other_image_hash)
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Vizio media player platform.""" host = config.get(CONF_HOST) token = config.get(CONF_ACCESS_TOKEN) name = config.get(CONF_NAME) volume_step = config.get(CONF_VOLUME_STEP) device_type = config.get(CONF_DEVICE_CLASS...
def update(self): """Retrieve latest state of the device.""" is_on = self._device.get_power_state() if is_on: self._state = STATE_ON volume = self._device.get_current_volume() if volume is not None: self._volume_level = float(volume) / self._...
def mute_volume(self, mute): """Mute the volume.""" if mute: self._device.mute_on() else: self._device.mute_off()
def volume_up(self): """Increasing volume of the device.""" self._volume_level += self._volume_step / self._max_volume self._device.vol_up(num=self._volume_step)
def volume_down(self): """Decreasing volume of the device.""" self._volume_level -= self._volume_step / self._max_volume self._device.vol_down(num=self._volume_step)
def set_volume_level(self, volume): """Set volume level.""" if self._volume_level is not None: if volume > self._volume_level: num = int(self._max_volume * (volume - self._volume_level)) self._volume_level = volume self._device.vol_up(num=num) ...
def reset(self): '''Restores the starting position.''' self.piece_bb = [ BB_VOID, # NONE BB_RANK_C | BB_RANK_G, # PAWN BB_A1 | BB_I1 | BB_A9 | BB_I9, # LANCE BB_A2 | BB_A8 | BB_I2 | BB_I8, # KNIGHT ...
def piece_at(self, square): '''Gets the piece at the given square.''' mask = BB_SQUARES[square] color = int(bool(self.occupied[WHITE] & mask)) piece_type = self.piece_type_at(square) if piece_type: return Piece(piece_type, color)
def remove_piece_at(self, square, into_hand=False): '''Removes a piece from the given square if present.''' piece_type = self.piece_type_at(square) if piece_type == NONE: return if into_hand: self.add_piece_into_hand(piece_type, self.turn) mask = BB_SQU...
def set_piece_at(self, square, piece, from_hand=False, into_hand=False): '''Sets a piece at the given square. An existing piece is replaced.''' if from_hand: self.remove_piece_from_hand(piece.piece_type, self.turn) self.remove_piece_at(square, into_hand) self.pieces[square]...
def is_suicide_or_check_by_dropping_pawn(self, move): ''' Checks if the given move would move would leave the king in check or put it into check. ''' self.push(move) is_suicide = self.was_suicide() is_check_by_dropping_pawn = self.was_check_by_dropping_pawn(move)...
def was_suicide(self): ''' Checks if the king of the other side is attacked. Such a position is not valid and could only be reached by an illegal move. ''' return self.is_attacked_by(self.turn, self.king_squares[self.turn ^ 1])
def is_game_over(self): ''' Checks if the game is over due to checkmate, stalemate or fourfold repetition. ''' # Stalemate or checkmate. try: next(self.generate_legal_moves().__iter__()) except StopIteration: return True # Fourfol...
def is_checkmate(self): '''Checks if the current position is a checkmate.''' if not self.is_check(): return False try: next(self.generate_legal_moves().__iter__()) return False except StopIteration: return True
def is_fourfold_repetition(self): ''' a game is ended if a position occurs for the fourth time on consecutive alternating moves. ''' zobrist_hash = self.zobrist_hash() # A minimum amount of moves must have been played and the position # in question must have appe...
def push(self, move): ''' Updates the position with the given move and puts it onto a stack. Null moves just increment the move counters, switch turns and forfeit en passant capturing. No validation is performed. For performance moves are assumed to be at least pseudo leg...
def pop(self): ''' Restores the previous position and returns the last move from the stack. ''' move = self.move_stack.pop() # Update transposition table. self.transpositions.subtract((self.zobrist_hash(), )) # Decrement move number. self.move_number -= ...
def sfen(self): ''' Gets an SFEN representation of the current position. ''' sfen = [] empty = 0 # Position part. for square in SQUARES: piece = self.piece_at(square) if not piece: empty += 1 else: ...
def set_sfen(self, sfen): ''' Parses a SFEN and sets the position from it. Rasies `ValueError` if the SFEN string is invalid. ''' # Ensure there are six parts. parts = sfen.split() if len(parts) != 4: raise ValueError('sfen string should consist of 6 p...
def push_usi(self, usi): ''' Parses a move in standard coordinate notation, makes the move and puts it on the the move stack. Raises `ValueError` if neither legal nor a null move. Returns the move. ''' move = Move.from_usi(usi) self.push(move) retu...
def zobrist_hash(self, array=None): ''' Returns a Zobrist hash of the current position. ''' # Hash in the board setup. zobrist_hash = self.board_zobrist_hash(array) if array is None: array = DEFAULT_RANDOM_ARRAY if self.turn == WHITE: zob...
def symbol(self): ''' Gets the symbol `p`, `l`, `n`, etc. ''' if self.color == BLACK: return PIECE_SYMBOLS[self.piece_type].upper() else: return PIECE_SYMBOLS[self.piece_type]
def from_symbol(cls, symbol): ''' Creates a piece instance from a piece symbol. Raises `ValueError` if the symbol is invalid. ''' if symbol.lower() == symbol: return cls(PIECE_SYMBOLS.index(symbol), WHITE) else: return cls(PIECE_SYMBOLS.index(symbo...
def usi(self): ''' Gets an USI string for the move. For example a move from 7A to 8A would be `7a8a` or `7a8a+` if it is a promotion. ''' if self: if self.drop_piece_type: return '{0}*{1}'.format(PIECE_SYMBOLS[self.drop_piece_type].upper(), SQU...
def from_usi(cls, usi): ''' Parses an USI string. Raises `ValueError` if the USI string is invalid. ''' if usi == '0000': return cls.null() elif len(usi) == 4: if usi[1] == '*': piece = Piece.from_symbol(usi[0]) retu...
def parse_commits(data): '''Accept a string and parse it into many commits. Parse and yield each commit-dictionary. This function is a generator. ''' raw_commits = RE_COMMIT.finditer(data) for rc in raw_commits: full_commit = rc.groups()[0] parts = RE_COMMIT.match(full_commit).gr...
def parse_commit(parts): '''Accept a parsed single commit. Some of the named groups require further processing, so parse those groups. Return a dictionary representing the completely parsed commit. ''' commit = {} commit['commit'] = parts['commit'] commit['tree'] = parts['tree'] pare...
def run_git_log(git_dir=None, git_since=None): '''run_git_log([git_dir]) -> File Run `git log --numstat --pretty=raw` on the specified git repository and return its stdout as a pseudo-File.''' import subprocess if git_dir: command = [ 'git', '--git-dir=' + git_dir, ...
def main(doc, timeout, size, debug, allow_codes, whitelist): """ Examples: simple call $ vl README.md Adding debug outputs $ vl README.md --debug Adding a custom timeout for each url. time on seconds. $ vl README.md -t 3 Adding a custom size param, to add throttle n requests per...
def load_config_from_cli(config: GoodConf, argv: List[str]) -> List[str]: """Loads config, checking CLI arguments for a config file""" # Monkey patch Django's command parser from django.core.management.base import BaseCommand original_parser = BaseCommand.create_parser def patched_parser(self, pro...
def execute_from_command_line_with_config(config: GoodConf, argv: List[str]): """Load's config then runs Django's execute_from_command_line""" with load_config_from_cli(config, argv) as args: from django.core.management import execute_from_command_line execute_from_command_line(args)
def argparser_add_argument(parser: argparse.ArgumentParser, config: GoodConf): """Adds argument for config to existing argparser""" help = "Config file." if config.file_env_var: help += (" Can also be configured via the " "environment variable: {}".format(config.file_env_var)) i...
def _load_config(path: str) -> dict: """ Given a file path, parse it based on its extension (YAML or JSON) and return the values as a Python dictionary. JSON is the default if an extension can't be determined. """ __, ext = os.path.splitext(path) if ext in ['.yaml', '.yml']: import r...
def load(self, filename: str = None): """Find config file and set values""" if filename: self.config_file = _find_file(filename) else: if self.file_env_var and self.file_env_var in os.environ: self.config_file = _find_file(os.environ[self.file_env_var]) ...
def generate_yaml(cls, **override): """ Dumps initial config in YAML """ import ruamel.yaml yaml = ruamel.yaml.YAML() yaml_str = StringIO() yaml.dump(cls.get_initial(**override), stream=yaml_str) yaml_str.seek(0) dict_from_yaml = yaml.load(yaml_str...
def generate_markdown(cls): """ Documents values in markdown """ lines = [] if cls.__doc__: lines.extend(['# {}'.format(cls.__doc__), '']) for k, v in cls._values.items(): lines.append('* **{}** '.format(k)) if v.required: ...
def cast(self, val: str): """converts string to type requested by `cast_as`""" try: return getattr(self, 'cast_as_{}'.format( self.cast_as.__name__.lower()))(val) except AttributeError: return self.cast_as(val)
def list_dates_between(first_date, last_date): """Returns all dates from first to last included.""" return [first_date + timedelta(days=n) for n in range(1 + (last_date - first_date).days)]
def parse_date(s): """Fast %Y-%m-%d parsing.""" try: return datetime.date(int(s[:4]), int(s[5:7]), int(s[8:10])) except ValueError: # other accepted format used in one-day data set return datetime.datetime.strptime(s, '%d %B %Y').date()
def load_file(self, currency_file): """To be subclassed if alternate methods of loading data. """ if currency_file.startswith(('http://', 'https://')): content = urlopen(currency_file).read() else: with open(currency_file, 'rb') as f: content = f.r...
def _set_missing_to_none(self, currency): """Fill missing rates of a currency with the closest available ones.""" rates = self._rates[currency] first_date, last_date = self.bounds[currency] for date in list_dates_between(first_date, last_date): if date not in rates: ...
def _compute_missing_rates(self, currency): """Fill missing rates of a currency. This is done by linear interpolation of the two closest available rates. :param str currency: The currency to fill missing rates for. """ rates = self._rates[currency] # tmp will store the...
def _get_rate(self, currency, date): """Get a rate for a given currency and date. :type date: datetime.date >>> from datetime import date >>> c = CurrencyConverter() >>> c._get_rate('USD', date=date(2014, 3, 28)) 1.375... >>> c._get_rate('BGN', date=date(2010, 1...
def convert(self, amount, currency, new_currency='EUR', date=None): """Convert amount from a currency to another one. :param float amount: The amount of `currency` to convert. :param str currency: The currency to convert from. :param str new_currency: The currency to convert to. ...
def grouper(iterable, n, fillvalue=None): """Group iterable by n elements. >>> for t in grouper('abcdefg', 3, fillvalue='x'): ... print(''.join(t)) abc def gxx """ return list(zip_longest(*[iter(iterable)] * n, fillvalue=fillvalue))
def animate(frames, interval, name, iterations=2): """Animate given frame for set number of iterations. Parameters ---------- frames : list Frames for animating interval : float Interval between two frames name : str Name of animation iterations : int, optional ...
def tostring(self, cnf): """Convert Cnf object ot Dimacs cnf string cnf: Cnf object In the converted Cnf there will be only numbers for variable names. The conversion guarantees that the variables will be numbered alphabetically. """ self.varname...
def reduceCnf(cnf): """ I just found a remarkably large bug in my SAT solver and found an interesting solution. Remove all b | -b (-b | b) & (b | -a) & (-b | a) & (a | -a) becomes (b | -a) & (-b | a) Remove all (-e) & (-e) (-e | a) & (-e | a) & (-e | a) & (-e | a) becomes (-...
def load(self, name): """[DEPRECATED] Load the polynomial series for `name` and return it.""" s = self.sets.get(name) if s is None: self.sets[name] = s = np.load(self.path('jpl-%s.npy' % name)) return s
def position(self, name, tdb, tdb2=0.0): """[DEPRECATED] Compute the position of `name` at time ``tdb [+ tdb2]``. The position is returned as a NumPy array ``[x y z]``. The barycentric dynamical time `tdb` argument should be a float. If there are many dates you want computed, then make...
def position_and_velocity(self, name, tdb, tdb2=0.0): """[DEPRECATED] Compute the position and velocity of `name` at ``tdb [+ tdb2]``. The position and velocity are returned in a 2-tuple:: ([x y z], [xdot ydot zdot]) The barycentric dynamical time `tdb` argument should be a float....