INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Check if is register or wire
def verilogTypeOfSig(signalItem): """ Check if is register or wire """ driver_cnt = len(signalItem.drivers) if signalItem._const or driver_cnt > 1 or\ arr_any(signalItem.drivers, _isEventDependentDriver): return SIGNAL_TYPE.REG else: if driver_cnt == 1: d = sig...
: param top: object which is represenation of design: param topName: name which should be used for ipcore: param saveTo: path of directory where generated files should be stored
def toHdlConversion(self, top, topName: str, saveTo: str) -> List[str]: """ :param top: object which is represenation of design :param topName: name which should be used for ipcore :param saveTo: path of directory where generated files should be stored :return: list of file name...
: see: doc of method on parent class
def serializeType(self, hdlType: HdlType) -> str: """ :see: doc of method on parent class """ def createTmpVar(suggestedName, dtype): raise NotImplementedError( "Can not seraialize hdl type %r into" "ipcore format" % (hdlType)) return...
: see: doc of method on parent class
def getVectorFromType(self, dtype) -> Union[bool, None, Tuple[int, int]]: """ :see: doc of method on parent class """ if dtype == BIT: return False elif isinstance(dtype, Bits): return [evalParam(dtype.width) - 1, hInt(0)]
: see: doc of method on parent class
def getExprVal(self, val, do_eval=False): """ :see: doc of method on parent class """ ctx = VhdlSerializer.getBaseContext() def createTmpVar(suggestedName, dtype): raise NotImplementedError( "Width value can not be converted do ipcore format (%r)", ...
: see: doc of method on parent class
def getTypeWidth(self, dtype: HdlType, do_eval=False) -> Tuple[int, Union[int, RtlSignal], bool]: """ :see: doc of method on parent class """ width = dtype.width if isinstance(width, int): widthStr = str(width) else: widthStr = self.getExprVal(widt...
: see: doc of method on parent class
def getObjDebugName(self, obj: Union[Interface, Unit, Param]) -> str: """ :see: doc of method on parent class """ return obj._getFullName()
: see: doc of method on parent class
def serialzeValueToTCL(self, val, do_eval=False) -> Tuple[str, str, bool]: """ :see: doc of method on parent class """ if isinstance(val, int): val = hInt(val) if do_eval: val = val.staticEval() if isinstance(val, RtlSignalBase): ctx =...
Check if not redefining property on obj
def nameAvailabilityCheck(obj, propName, prop): """ Check if not redefining property on obj """ if getattr(obj, propName, None) is not None: raise IntfLvlConfErr("%r already has property %s old:%s new:%s" % (obj, propName, repr(getattr(obj, propName)), prop))
Register Param object on interface level object
def _registerParameter(self, pName, parameter) -> None: """ Register Param object on interface level object """ nameAvailabilityCheck(self, pName, parameter) # resolve name in this scope try: hasName = parameter._name is not None except AttributeError:...
Auto - propagate params by name to child components and interfaces Usage:
def _paramsShared(self, exclude=None, prefix="") -> MakeParamsShared: """ Auto-propagate params by name to child components and interfaces Usage: .. code-block:: python with self._paramsShared(): # your interfaces and unit which should share all params with ...
Associate this object with specified clk/ rst
def _make_association(self, clk=None, rst=None) -> None: """ Associate this object with specified clk/rst """ if clk is not None: assert self._associatedClk is None self._associatedClk = clk if rst is not None: assert self._associatedRst is No...
Update all parameters which are defined on self from otherObj
def _updateParamsFrom(self, otherObj:"PropDeclrCollector", updater, exclude:set, prefix:str) -> None: """ Update all parameters which are defined on self from otherObj :param otherObj: other object which Param instances should be updated :param updater: updater function(self, myParamete...
Register unit object on interface level object
def _registerUnit(self, uName, unit): """ Register unit object on interface level object """ nameAvailabilityCheck(self, uName, unit) assert unit._parent is None unit._parent = self unit._name = uName self._units.append(unit)
Register interface object on interface level object
def _registerInterface(self, iName, intf, isPrivate=False): """ Register interface object on interface level object """ nameAvailabilityCheck(self, iName, intf) assert intf._parent is None intf._parent = self intf._name = iName intf._ctx = self._ctx ...
Register array of items on interface level object
def _registerArray(self, name, items): """ Register array of items on interface level object """ items._parent = self items._name = name for i, item in enumerate(items): setattr(self, "%s_%d" % (name, i), item)
: attention: unit has to be parametrized before it is registered ( some components can change interface by parametrization )
def _registerUnitInImpl(self, uName, u): """ :attention: unit has to be parametrized before it is registered (some components can change interface by parametrization) """ self._registerUnit(uName, u) u._loadDeclarations() self._lazyLoaded.extend(u._toRtl(self....
Returns a first driver if signal has only one driver.
def singleDriver(self): """ Returns a first driver if signal has only one driver. """ # [TODO] no driver exception drv_cnt = len(self.drivers) if not drv_cnt: raise NoDriverErr(self) elif drv_cnt != 1: raise MultipleDriversErr(self) ...
Register potential signals to drivers/ endpoints
def registerSignals(self, outputs=[]): """ Register potential signals to drivers/endpoints """ for o in self.operands: if isinstance(o, RtlSignalBase): if o in outputs: o.drivers.append(self) else: o.endp...
Recursively statistically evaluate result of this operator
def staticEval(self): """ Recursively statistically evaluate result of this operator """ for o in self.operands: o.staticEval() self.result._val = self.evalFn()
Create operator with result signal
def withRes(opDef, operands, resT, outputs=[]): """ Create operator with result signal :ivar resT: data type of result signal :ivar outputs: iterable of singnals which are outputs from this operator """ op = Operator(opDef, operands) out = RtlSignal(g...
Create copy of this context with increased indent
def withIndent(self, indent=1): """ Create copy of this context with increased indent """ ctx = copy(self) ctx.indent += indent return ctx
Try connect src to interface of specified name on unit. Ignore if interface is not present or if it already has driver.
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,...
Propagate clk clock signal to all subcomponents
def propagateClk(obj): """ Propagate "clk" clock signal to all subcomponents """ clk = obj.clk for u in obj._units: _tryConnect(clk, u, 'clk')
Propagate clk clock and negative reset rst_n signal to all subcomponents
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')
Propagate clk clock and reset rst signal to all subcomponents
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')
Propagate negative reset rst_n signal to all subcomponents
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')
Propagate reset rst signal to all subcomponents
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')
Slice signal what to fit in where or arithmetically ( for signed by MSB/ unsigned vector with 0 ) extend what to same width as where
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...
Iterate over bits in vector
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...
: param numberOfBits: number of bits to get from actual possition: param doCollect: if False output is not collected just iterator moves in structure
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...
: param numberOfBits: number of bits to get from actual possition: return: chunk of bits of specified size ( instance of Value or RtlSignal )
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)
Always decide not to serialize obj
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...
Decide to serialize only first obj of it s class
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...
Decide to serialize only objs with uniq parameters and class
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...
get all name hierarchy separated by.
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 == '': ...
Delegate _make_association on items
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)
: note: doc in: func: ~hwt. synthesizer. interfaceLevel. propDeclCollector. _updateParamsFrom
def _updateParamsFrom(self, *args, **kwargs): """ :note: doc in :func:`~hwt.synthesizer.interfaceLevel.propDeclCollector._updateParamsFrom` """ for o in self: o._updateParamsFrom(*args, **kwargs)
Create simulation model and connect it with interfaces of original unit and decorate it with agents
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...
Create a simulation model for unit
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 ...
Reconnect model signals to unit to run simulation with simulation model but use original unit interfaces for communication
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 ...
Syntax sugar If outputFile is string try to open it as file
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...
: 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 simulation time units are defined in HdlSimulator: return: hdl simulator object
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...
Oscillative simulation driver for your signal ( usually used as clk generator )
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...
Process for injecting of this callback loop into simulator
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...
Connect to port item on subunit
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)) ...
Connect internal signal to port item this connection is used by simulator and only output port items will be connected
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...
connet signal from internal side of of this component to this port
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...
return signal inside unit which has this port
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)
Check if hdl process has event depenency on signal
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
Schedule process on actual time with specified priority
def _add_process(self, proc, priority) -> None: """ Schedule process on actual time with specified priority """ self._events.push(self.now, priority, proc)
Add hdl process to execution queue
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...
* Inject default values to simulation
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...
Schedule combUpdateDoneEv event to let agents know that current delta step is ending and values from combinational logic are stable
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_...
Apply stashed values to signals
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...
This functions resolves write conflicts for signal
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...
Delta step for combinational processes
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...
Delta step for event dependent processes
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...
Perform delta step by writing stacked values to signals
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:...
Read value from signal or interface
def read(self, sig) -> Value: """ Read value from signal or interface """ try: v = sig._val except AttributeError: v = sig._sigInside._val return v.clone()
Write value to signal or interface.
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 # ...
Run simulation until specified time: note: can be used to run simulation again after it ends from time when it ends
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 ...
Add process to events with default priority on current time
def add_process(self, proc) -> None: """ Add process to events with default priority on current time """ self._events.push(self.now, PRIORITY_NORMAL, proc)
Run simulation for Unit instance
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...
Function to create variadic operator function
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...
Check if is register or wire
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
Convert all ternary operators to IfContainers
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...
Serialize HWProcess objects as VHDL
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, ...
Compute the hamming distance between two hashes
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)))
Compute the average hash of the given image.
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(...
Compute the hamming distance between two images
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)
Set up the Vizio media player platform.
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...
Retrieve latest state of the device.
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._...
Mute the volume.
def mute_volume(self, mute): """Mute the volume.""" if mute: self._device.mute_on() else: self._device.mute_off()
Increasing volume of the device.
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)
Decreasing volume of the device.
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)
Set volume level.
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) ...
Restores the starting position.
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 ...
Gets the piece at the given square.
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)
Removes a piece from the given square if present.
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...
Sets a piece at the given square. An existing piece is replaced.
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]...
Checks if the given move would move would leave the king in check or put it into check.
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)...
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.
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])
Checks if the game is over due to checkmate stalemate or fourfold repetition.
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...
Checks if the current position is a checkmate.
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
a game is ended if a position occurs for the fourth time on consecutive alternating moves.
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...
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 legal. Otherwise there is no guarantee that the previous board state can be re...
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...
Restores the previous position and returns the last move from the stack.
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 -= ...
Gets an SFEN representation of the current position.
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: ...
Parses a SFEN and sets the position from it. Rasies ValueError if the SFEN string is invalid.
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...
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.
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...
Returns a Zobrist hash of the current position.
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...
Gets the symbol p l n etc.
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]
Creates a piece instance from a piece symbol. Raises ValueError if the symbol is invalid.
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...
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.
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...
Parses an USI string. Raises ValueError if the USI string is invalid.
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...
Accept a string and parse it into many commits. Parse and yield each commit - dictionary. This function is a generator.
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...
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.
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...
run_git_log ( [ git_dir ] ) - > File
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, ...
Examples: simple call $ vl README. md
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...