_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q272200 | tryReduceAnd | test | def tryReduceAnd(sig, val):
"""
Return sig and val reduced by & operator or None
if it is not possible to statically reduce expression
"""
m = sig._dtype.all_mask()
if val._isFullVld():
v = val.val
if v == m:
return sig
elif v == 0:
return val | python | {
"resource": ""
} |
q272201 | tryReduceXor | test | def tryReduceXor(sig, val):
"""
Return sig and val reduced by ^ operator or None
if it is not possible to statically reduce expression
"""
m = sig._dtype.all_mask()
if not val.vldMask:
return val
if val._isFullVld():
v = val.val
if v == m:
return ~sig
... | python | {
"resource": ""
} |
q272202 | GenericSerializer.getBaseNameScope | test | def getBaseNameScope(cls):
"""
Get root of name space
"""
s = NameScope(False)
s.setLevel(1)
s[0].update(cls._keywords_dict)
return s | python | {
"resource": ""
} |
q272203 | GenericSerializer.serializationDecision | test | def serializationDecision(cls, obj, serializedClasses,
serializedConfiguredUnits):
"""
Decide if this unit should be serialized or not eventually fix name
to fit same already serialized unit
:param obj: object to serialize
:param serializedClasses: ... | python | {
"resource": ""
} |
q272204 | GenericSerializer.HdlType | test | def HdlType(cls, typ: HdlType, ctx: SerializerCtx, declaration=False):
"""
Serialize HdlType instance
"""
if isinstance(typ, Bits):
sFn = cls.HdlType_bits
elif isinstance(typ, HEnum):
sFn = cls.HdlType_enum
elif isinstance(typ, HArray):
... | python | {
"resource": ""
} |
q272205 | GenericSerializer.IfContainer | test | def IfContainer(cls, ifc: IfContainer, ctx: SerializerCtx):
"""
Srialize IfContainer instance
"""
childCtx = ctx.withIndent()
def asHdl(statements):
return [cls.asHdl(s, childCtx) for s in statements]
try:
cond = cls.condAsHdl(ifc.cond, True, ctx... | python | {
"resource": ""
} |
q272206 | getBaseCond | test | def getBaseCond(c):
"""
if is negated return original cond and negated flag
"""
isNegated = False
try:
drivers = c.drivers
except AttributeError:
return (c, isNegated)
if len(drivers) == 1:
d = list(c.drivers)[0]
if isinstance(d, Operator) and d.operator == A... | python | {
"resource": ""
} |
q272207 | simBitsT | test | def simBitsT(width: int, signed: Union[bool, None]):
"""
Construct SimBitsT with cache
"""
k = (width, signed)
try:
return __simBitsTCache[k]
except KeyError:
t = SimBitsT(width, signed)
__simBitsTCache[k] = t
return t | python | {
"resource": ""
} |
q272208 | ConstCache.getConstName | test | def getConstName(self, val):
"""
Get constant name for value
name of constant is reused if same value was used before
"""
try:
return self._cache[val]
except KeyError:
if isinstance(val.val, int):
name = "const_%d_" % val.val
... | python | {
"resource": ""
} |
q272209 | Assignment._cut_off_drivers_of | test | def _cut_off_drivers_of(self, sig: RtlSignalBase):
"""
Cut off statements which are driver of specified signal
"""
if self.dst is sig:
self.parentStm = None
return self
else:
return None | python | {
"resource": ""
} |
q272210 | TransTmpl._loadFromArray | test | def _loadFromArray(self, dtype: HdlType, bitAddr: int) -> int:
"""
Parse HArray type to this transaction template instance
:return: address of it's end
"""
self.itemCnt = evalParam(dtype.size).val
self.children = TransTmpl(
dtype.elmType, 0, parent=self, orig... | python | {
"resource": ""
} |
q272211 | TransTmpl._loadFromHStruct | test | def _loadFromHStruct(self, dtype: HdlType, bitAddr: int):
"""
Parse HStruct type to this transaction template instance
:return: address of it's end
"""
for f in dtype.fields:
t = f.dtype
origin = f
isPadding = f.name is None
if is... | python | {
"resource": ""
} |
q272212 | TransTmpl._loadFromHType | test | def _loadFromHType(self, dtype: HdlType, bitAddr: int) -> None:
"""
Parse any HDL type to this transaction template instance
"""
self.bitAddr = bitAddr
childrenAreChoice = False
if isinstance(dtype, Bits):
ld = self._loadFromBits
elif isinstance(dtype,... | python | {
"resource": ""
} |
q272213 | TransTmpl.getItemWidth | test | def getItemWidth(self) -> int:
"""
Only for transactions derived from HArray
:return: width of item in original array
"""
if not isinstance(self.dtype, HArray):
raise TypeError()
return (self.bitAddrEnd - self.bitAddr) // self.itemCnt | python | {
"resource": ""
} |
q272214 | TransTmpl.walkFlatten | test | def walkFlatten(self, offset: int=0,
shouldEnterFn=_default_shouldEnterFn,
otherObjItCtx: ObjIteratorCtx =_DummyIteratorCtx()
) -> Generator[
Union[Tuple[Tuple[int, int], 'TransTmpl'], 'OneOfTransaction'],
None, None]:
"""
... | python | {
"resource": ""
} |
q272215 | signFix | test | def signFix(val, width):
"""
Convert negative int to positive int which has same bits set
"""
if val > 0:
msb = 1 << (width - 1)
if val & msb:
val -= mask(width) + 1
return val | python | {
"resource": ""
} |
q272216 | SwitchContainer._merge_with_other_stm | test | def _merge_with_other_stm(self, other: "IfContainer") -> None:
"""
Merge other statement to this statement
"""
merge = self._merge_statement_lists
newCases = []
for (c, caseA), (_, caseB) in zip(self.cases, other.cases):
newCases.append((c, merge(caseA, caseB)... | python | {
"resource": ""
} |
q272217 | getIndent | test | def getIndent(indentNum):
"""
Cached indent getter function
"""
try:
return _indentCache[indentNum]
except KeyError:
i = "".join([_indent for _ in range(indentNum)])
_indentCache[indentNum] = i
return i | python | {
"resource": ""
} |
q272218 | nameAvailabilityCheck | test | 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)) | python | {
"resource": ""
} |
q272219 | PropDeclrCollector._registerParameter | test | 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:... | python | {
"resource": ""
} |
q272220 | PropDeclrCollector._updateParamsFrom | test | 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... | python | {
"resource": ""
} |
q272221 | PropDeclrCollector._registerUnit | test | 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) | python | {
"resource": ""
} |
q272222 | PropDeclrCollector._registerInterface | test | 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
... | python | {
"resource": ""
} |
q272223 | PropDeclrCollector._registerArray | test | 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) | python | {
"resource": ""
} |
q272224 | RtlSignal.singleDriver | test | 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)
... | python | {
"resource": ""
} |
q272225 | Operator.staticEval | test | def staticEval(self):
"""
Recursively statistically evaluate result of this operator
"""
for o in self.operands:
o.staticEval()
self.result._val = self.evalFn() | python | {
"resource": ""
} |
q272226 | Operator.withRes | test | 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... | python | {
"resource": ""
} |
q272227 | SerializerCtx.withIndent | test | def withIndent(self, indent=1):
"""
Create copy of this context with increased indent
"""
ctx = copy(self)
ctx.indent += indent
return ctx | python | {
"resource": ""
} |
q272228 | _tryConnect | test | 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,... | python | {
"resource": ""
} |
q272229 | propagateClk | test | def propagateClk(obj):
"""
Propagate "clk" clock signal to all subcomponents
"""
clk = obj.clk
for u in obj._units:
_tryConnect(clk, u, 'clk') | python | {
"resource": ""
} |
q272230 | propagateClkRstn | test | 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') | python | {
"resource": ""
} |
q272231 | propagateClkRst | test | 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') | python | {
"resource": ""
} |
q272232 | propagateRstn | test | 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') | python | {
"resource": ""
} |
q272233 | propagateRst | test | 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') | python | {
"resource": ""
} |
q272234 | iterBits | test | 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... | python | {
"resource": ""
} |
q272235 | _serializeExclude_eval | test | 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... | python | {
"resource": ""
} |
q272236 | _serializeOnce_eval | test | 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... | python | {
"resource": ""
} |
q272237 | _serializeParamsUniq_eval | test | 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... | python | {
"resource": ""
} |
q272238 | HObjList._getFullName | test | 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 == '':
... | python | {
"resource": ""
} |
q272239 | HObjList._make_association | test | 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) | python | {
"resource": ""
} |
q272240 | simPrepare | test | 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... | python | {
"resource": ""
} |
q272241 | toSimModel | test | 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
... | python | {
"resource": ""
} |
q272242 | reconnectUnitSignalsToModel | test | 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
... | python | {
"resource": ""
} |
q272243 | simUnitVcd | test | 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... | python | {
"resource": ""
} |
q272244 | TristateAgent.onTWriteCallback__init | test | 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... | python | {
"resource": ""
} |
q272245 | PortItem.connectSig | test | 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))
... | python | {
"resource": ""
} |
q272246 | PortItem.registerInternSig | test | 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... | python | {
"resource": ""
} |
q272247 | PortItem.connectInternSig | test | 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... | python | {
"resource": ""
} |
q272248 | PortItem.getInternSig | test | 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) | python | {
"resource": ""
} |
q272249 | isEvDependentOn | test | 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 | python | {
"resource": ""
} |
q272250 | HdlSimulator._add_process | test | def _add_process(self, proc, priority) -> None:
"""
Schedule process on actual time with specified priority
"""
self._events.push(self.now, priority, proc) | python | {
"resource": ""
} |
q272251 | HdlSimulator._addHdlProcToRun | test | 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... | python | {
"resource": ""
} |
q272252 | HdlSimulator._scheduleCombUpdateDoneEv | test | 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_... | python | {
"resource": ""
} |
q272253 | HdlSimulator._scheduleApplyValues | test | 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... | python | {
"resource": ""
} |
q272254 | HdlSimulator._conflictResolveStrategy | test | 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... | python | {
"resource": ""
} |
q272255 | HdlSimulator._runCombProcesses | test | 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... | python | {
"resource": ""
} |
q272256 | HdlSimulator._runSeqProcesses | test | 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... | python | {
"resource": ""
} |
q272257 | HdlSimulator._applyValues | test | 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:... | python | {
"resource": ""
} |
q272258 | HdlSimulator.read | test | def read(self, sig) -> Value:
"""
Read value from signal or interface
"""
try:
v = sig._val
except AttributeError:
v = sig._sigInside._val
return v.clone() | python | {
"resource": ""
} |
q272259 | HdlSimulator.write | test | 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
# ... | python | {
"resource": ""
} |
q272260 | HdlSimulator.add_process | test | def add_process(self, proc) -> None:
"""
Add process to events with default priority on current time
"""
self._events.push(self.now, PRIORITY_NORMAL, proc) | python | {
"resource": ""
} |
q272261 | HdlSimulator.simUnit | test | 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... | python | {
"resource": ""
} |
q272262 | _mkOp | test | 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... | python | {
"resource": ""
} |
q272263 | ternaryOpsToIf | test | 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... | python | {
"resource": ""
} |
q272264 | VhdlSerializer_statements.HWProcess | test | 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,
... | python | {
"resource": ""
} |
q272265 | hash_distance | test | 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))) | python | {
"resource": ""
} |
q272266 | average_hash | test | 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(... | python | {
"resource": ""
} |
q272267 | distance | test | 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) | python | {
"resource": ""
} |
q272268 | setup_platform | test | 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... | python | {
"resource": ""
} |
q272269 | VizioDevice.update | test | 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._... | python | {
"resource": ""
} |
q272270 | VizioDevice.mute_volume | test | def mute_volume(self, mute):
"""Mute the volume."""
if mute:
self._device.mute_on()
else:
self._device.mute_off() | python | {
"resource": ""
} |
q272271 | VizioDevice.volume_up | test | 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) | python | {
"resource": ""
} |
q272272 | VizioDevice.volume_down | test | 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) | python | {
"resource": ""
} |
q272273 | VizioDevice.set_volume_level | test | 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)
... | python | {
"resource": ""
} |
q272274 | Board.reset | test | 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
... | python | {
"resource": ""
} |
q272275 | Board.piece_at | test | 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) | python | {
"resource": ""
} |
q272276 | Board.remove_piece_at | test | 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... | python | {
"resource": ""
} |
q272277 | Board.set_piece_at | test | 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]... | python | {
"resource": ""
} |
q272278 | Board.is_suicide_or_check_by_dropping_pawn | test | 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)... | python | {
"resource": ""
} |
q272279 | Board.was_suicide | test | 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]) | python | {
"resource": ""
} |
q272280 | Board.is_game_over | test | 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... | python | {
"resource": ""
} |
q272281 | Board.is_checkmate | test | 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 | python | {
"resource": ""
} |
q272282 | Board.is_fourfold_repetition | test | 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... | python | {
"resource": ""
} |
q272283 | Board.pop | test | 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 -= ... | python | {
"resource": ""
} |
q272284 | Board.sfen | test | 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:
... | python | {
"resource": ""
} |
q272285 | Board.push_usi | test | 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... | python | {
"resource": ""
} |
q272286 | Board.zobrist_hash | test | 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... | python | {
"resource": ""
} |
q272287 | Piece.symbol | test | 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] | python | {
"resource": ""
} |
q272288 | Piece.from_symbol | test | 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... | python | {
"resource": ""
} |
q272289 | Move.usi | test | 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... | python | {
"resource": ""
} |
q272290 | Move.from_usi | test | 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... | python | {
"resource": ""
} |
q272291 | parse_commits | test | 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... | python | {
"resource": ""
} |
q272292 | parse_commit | test | 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... | python | {
"resource": ""
} |
q272293 | load_config_from_cli | test | 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... | python | {
"resource": ""
} |
q272294 | execute_from_command_line_with_config | test | 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) | python | {
"resource": ""
} |
q272295 | argparser_add_argument | test | 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... | python | {
"resource": ""
} |
q272296 | GoodConf.load | test | 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])
... | python | {
"resource": ""
} |
q272297 | GoodConf.generate_yaml | test | 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... | python | {
"resource": ""
} |
q272298 | GoodConf.generate_markdown | test | 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:
... | python | {
"resource": ""
} |
q272299 | Value.cast | test | 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) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.