Instruction:
Can you generate a brief explanation for the following Python 3 code
def verilogTypeOfSig(signalItem):
    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 = signalItem.drivers[0]
            if not isinstance(d, (Assignment, PortItem)):
                return SIGNAL_TYPE.REG

        return SIGNAL_TYPE.WIRE

Response: Check if the signalItem is register or wire


Instruction:
Can you tell what is the following Python 3 function doing
def toHdlConversion(self, top, topName: str, saveTo: str) -> List[str]:

        return toRtl(top,
                     saveTo=saveTo,
                     name=topName,
                     serializer=self.serializer,
                     targetPlatform=self.targetPlatform)

Response: This function converts the object to the correct compile order for the HDL file.


Instruction:
Explain what the following Python 3 code does
def serializeType(self, hdlType: HdlType) -> str:

        def createTmpVar(suggestedName, dtype):
            raise NotImplementedError(
                "Can not seraialize hdl type %r into"
                "ipcore format" % (hdlType))

        return VhdlSerializer.HdlType(hdlType, VhdlSerializer.getBaseContext())

Response: Serialize a HdlType into the ipcore format.


Instruction:
Explain what the following Python 3 code does
def getVectorFromType(self, dtype) -> Union[bool, None, Tuple[int, int]]:
        if dtype == BIT:
            return False
        elif isinstance(dtype, Bits):
            return [evalParam(dtype.width) - 1, hInt(0)]

Response: Returns the vector of the given dtype.


Instruction:
Write a Python 3 script to
return the expression value of the passed in value

Response:
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)",
                val)

        ctx.createTmpVarFn = createTmpVar
        if do_eval:
            val = val.staticEval()
        val = VivadoTclExpressionSerializer.asHdl(val, ctx)
        return val


Instruction:
Can you generate a brief explanation for the following Python 3 code
def getTypeWidth(self, dtype: HdlType, do_eval=False) -> Tuple[int, Union[int, RtlSignal], bool]:
        width = dtype.width
        if isinstance(width, int):
            widthStr = str(width)
        else:
            widthStr = self.getExprVal(width, do_eval=do_eval)

        return width, widthStr, False

Response: Returns the width and the expression of the type.


Instruction:
Can you tell what is the following Python 3 function doing
def getObjDebugName(self, obj: Union[Interface, Unit, Param]) -> str:
        return obj._getFullName()

Response: Get the debug name of the object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def serialzeValueToTCL(self, val, do_eval=False) -> Tuple[str, str, bool]:
        if isinstance(val, int):
            val = hInt(val)
        if do_eval:
            val = val.staticEval()

        if isinstance(val, RtlSignalBase):
            ctx = VivadoTclExpressionSerializer.getBaseContext()
            tclVal = VivadoTclExpressionSerializer.asHdl(val, ctx)
            tclValVal = VivadoTclExpressionSerializer.asHdl(
                        val.staticEval())
            return tclVal, tclValVal, False
        else:

            tclVal = VivadoTclExpressionSerializer.asHdl(val, None)
            return tclVal, tclVal, True

Response: serialze value to TCL


Instruction:
Given the following Python 3 function, write the documentation
def nameAvailabilityCheck(obj, propName, prop):
    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))

Response: Check if the object has the given name.


Instruction:
How would you code a function in Python 3 to
register a parameter on the object.

Response:
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:
            hasName = False
        if not hasName:
            parameter._name = pName
        # add name in this scope
        parameter._registerScope(pName, self)

        if parameter.hasGenericName:
            parameter.name = pName

        if parameter._parent is None:
            parameter._parent = self

        self._params.append(parameter)


Instruction:
How would you code a function in Python 3 to
associate this object with specified clk and rst.

Response:
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 None
            self._associatedRst = rst


Instruction:
Here you have a function in Python 3, explain what it does
def _updateParamsFrom(self, otherObj:"PropDeclrCollector", updater, exclude:set, prefix:str) -> None:
        excluded = set()
        if exclude is not None:
            exclude = set(exclude)

        for myP in self._params:
            pPName = prefix + myP._scopes[self][1]
            try:
                otherP = getattr(otherObj, pPName)
                if not isinstance(otherP, Param):
                    continue
            except AttributeError:
                continue

            if exclude and otherP in exclude:
                excluded.add(otherP)
                continue
            updater(self, myP, otherP)

        if exclude is not None:
            # assert that what should be excluded really exists
            assert excluded == exclude

Response: Update all parameters which are defined on self from otherObj.


Instruction:
How would you implement a function in Python 3 that
registers a unit object on interface level object

Response:
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)


Instruction:
Implement a Python 3 function for
registering an interface object on the level object.

Response:
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

        if isPrivate:
            self._private_interfaces.append(intf)
            intf._isExtern = False
        else:
            self._interfaces.append(intf)
            intf._isExtern = True


Instruction:
Can you generate the documentation for the following Python 3 function
def _registerArray(self, name, items):
        items._parent = self
        items._name = name
        for i, item in enumerate(items):
            setattr(self, "%s_%d" % (name, i), item)

Response: Register array of items on interface level object


Instruction:
Can you tell what is the following Python 3 function doing
def _registerUnitInImpl(self, uName, u):
        self._registerUnit(uName, u)
        u._loadDeclarations()
        self._lazyLoaded.extend(u._toRtl(self._targetPlatform))
        u._signalsForMyEntity(self._ctx, "sig_" + uName)

Response: register a unit in the internal list


Instruction:
Here you have a function in Python 3, explain what it does
def singleDriver(self):
        # [TODO] no driver exception
        drv_cnt = len(self.drivers)
        if not drv_cnt:
            raise NoDriverErr(self)
        elif drv_cnt != 1:
            raise MultipleDriversErr(self)

        return self.drivers[0]

Response: Returns a single driver if signal has only one driver.


Instruction:
Can you implement a function in Python 3 that
registers potential signals to drivers and endpoints.

Response:
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.endpoints.append(self)
            elif isinstance(o, Value):
                pass
            else:
                raise NotImplementedError(
                    "Operator operands can be"
                    " only signal or values got:%r" % (o))


Instruction:
How would you implement a function in Python 3 that
creates an operator with result

Response:
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(getCtxFromOps(operands), None, resT)
        out._const = arr_all(op.operands, isConst)
        out.drivers.append(op)
        out.origin = op
        op.result = out
        op.registerSignals(outputs)
        if out._const:
            out.staticEval()
        return out


Instruction:
Make a summary of the following Python 3 code
def withIndent(self, indent=1):
        ctx = copy(self)
        ctx.indent += indent
        return ctx

Response: Create a copy of this context with increased indent.


Instruction:
Can you create a Python 3 function that
tries to connect src to interface of specified name on unit.

Response:
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, dst)


Instruction:
Explain what the following Python 3 code does
def propagateClk(obj):
    clk = obj.clk
    for u in obj._units:
        _tryConnect(clk, u, 'clk')

Response: Propagate clk signal to all units in the hierarchy


Instruction:
Create a Python 3 function for
propagating clk clock and negative reset rst_n signal to all subcomponents of obj.

Response:
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')


Instruction:
Can you generate a brief explanation for the following Python 3 code
def propagateClkRst(obj):
    clk = obj.clk
    rst = obj.rst

    for u in obj._units:
        _tryConnect(clk, u, 'clk')
        _tryConnect(~rst, u, 'rst_n')
        _tryConnect(rst, u, 'rst')

Response: Propagate clk and reset rst signal to all subcomponents


Instruction:
Can you generate the documentation for the following Python 3 function
def propagateRstn(obj):
    rst_n = obj.rst_n

    for u in obj._units:
        _tryConnect(rst_n, u, 'rst_n')
        _tryConnect(~rst_n, u, 'rst')

Response:
Propagate negative reset rst_n signal
    to all subcomponents


Instruction:
Explain what the following Python 3 code does
def propagateRst(obj):
    rst = obj.rst

    for u in obj._units:
        _tryConnect(~rst, u, 'rst_n')
        _tryConnect(rst, u, 'rst')

Response:
Propagate reset rst signal
    to all subcomponents of obj. rst


Instruction:
How would you code a function in Python 3 to
fit the given signal to the given length.

Response:
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.
    """

    whatWidth = what._dtype.bit_length()
    toWidth = where_t.bit_length()
    if toWidth == whatWidth:
        return what
    elif toWidth < whatWidth:
        # slice
        if not shrink:
            raise BitWidthErr()

        return what[toWidth:]
    else:
        if not extend:
            raise BitWidthErr()

        w = toWidth - whatWidth

        if what._dtype.signed:
            # signed extension
            msb = what[whatWidth - 1]
            ext = reduce(lambda a, b: a._concat(b), [msb for _ in range(w)])
        else:
            # 0 extend
            ext = vec(0, w)

        return ext._concat(what)


Instruction:
Create a Python 3 function for
iterating over bits in sequence

Response:
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 dense types
    """
    bw = BitWalker(sigOrVal, skipPadding, fillup)
    for _ in range(ceil(sigOrVal._dtype.bit_length() / bitsInOne)):
        yield bw.get(bitsInOne)

    bw.assertIsOnEnd()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _get(self, numberOfBits: int, doCollect: bool):
        if not isinstance(numberOfBits, int):
            numberOfBits = int(numberOfBits)

        while self.actuallyHave < numberOfBits:
            # accumulate while not has enought
            try:
                f = next(self.it)
            except StopIteration:
                if self.fillup and self.actual is not None:
                    break
                else:
                    raise NotEnoughtBitsErr()

            thisFieldLen = f._dtype.bit_length()
            if self.actual is None:
                if not doCollect and thisFieldLen <= numberOfBits:
                    numberOfBits -= thisFieldLen
                else:
                    self.actual = f
                    self.actuallyHave = thisFieldLen
            else:
                if not doCollect and self.actuallyHave < numberOfBits:
                    self.actuallyHave = thisFieldLen
                    self.actual = f
                else:
                    self.actuallyHave += thisFieldLen
                    self.actual = f._concat(self.actual)

        # slice out from actual
        actual = self.actual
        actualOffset = self.actualOffset

        if self.actuallyHave < numberOfBits:
            assert self.fillup
            if doCollect:
                t = self.actual._dtype
                fillupW = numberOfBits - self.actuallyHave
                padding_t = Bits(fillupW, signed=t.signed, negated=t.negated)
                padding = padding_t.fromPy(None)
                actual = padding._concat(actual)
            self.actuallyHave = 0

        # update about what was taken
        self.actuallyHave -= numberOfBits
        self.actualOffset += numberOfBits
        if self.actuallyHave == 0:
            self.actual = None
            self.actualOffset = 0

        if doCollect:
            if numberOfBits == 1:
                return actual[actualOffset]
            else:
                return actual[(actualOffset + numberOfBits):actualOffset]

Response: get from the actual possition


Instruction:
Create a Python 3 function to
get a chunk of bits from the current possition .

Response:
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)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _serializeOnce_eval(parentUnit, obj, isDeclaration, priv):
    clsName = parentUnit.__class__.__name__

    if isDeclaration:
        obj.name = clsName

    if priv is None:
        priv = parentUnit
    elif isDeclaration:
        # prepare entity which will not be serialized
        prepareEntity(obj, clsName, parentUnit)

    serialize = priv is parentUnit

    return serialize, priv

Response: Internal function to serialize only first obj of it s class


Instruction:
Here you have a function in Python 3, explain what it does
def _serializeParamsUniq_eval(parentUnit, obj, isDeclaration, priv):

    params = paramsToValTuple(parentUnit)

    if priv is None:
        priv = {}

    if isDeclaration:
        try:
            prevUnit = priv[params]
        except KeyError:
            priv[params] = parentUnit
            return True, priv

        prepareEntity(obj, prevUnit._entity.name, prevUnit)
        return False, priv

    return priv[params] is parentUnit, priv

Response:
Internal function to serialize only objs with uniq parameters and class
Taxonomy


Instruction:
Here you have a function in Python 3, explain what it does
def _getFullName(self):
        name = ""
        tmp = self
        while isinstance(tmp, (InterfaceBase, HObjList)):
            if hasattr(tmp, "_name"):
                n = tmp._name
            else:
                n = ''
            if name == '':
                name = n
            else:
                name = n + '.' + name
            if hasattr(tmp, "_parent"):
                tmp = tmp._parent
            else:
                tmp = None
        return name

Response: get all name hierarchy separated by.


Instruction:
How would you code a function in Python 3 to
delegate _make_association on items

Response:
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)


Instruction:
How would you explain what the following Python 3 function does
def _updateParamsFrom(self, *args, **kwargs):
        for o in self:
            o._updateParamsFrom(*args, **kwargs)

Response: update params from all the objects in this list


Instruction:
Write a Python 3 function for
creating simulation model and connect it with interfaces of original unit and decorate it with agents of original unit

Response:
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 unit which you wont prepare for simulation
    :param modelCls: class of rtl simulation model to run simulation on,
        if is None rtl sim model will be generated from unit
    :param targetPlatform: target platform for this synthes
    :param dumpModelIn: folder to where put sim model files
        (if is None sim model will be constructed only in memory)
    :param onAfterToRtl: callback fn(unit, modelCls) which will be called
        after unit will be synthesised to rtl

    :return: tuple (fully loaded unit with connected sim model,
        connected simulation model,
        simulation processes of agents
        )
    """
    if modelCls is None:
        modelCls = toSimModel(
            unit, targetPlatform=targetPlatform, dumpModelIn=dumpModelIn)
    else:
        # to instantiate hierarchy of unit
        toSimModel(unit)

    if onAfterToRtl:
        onAfterToRtl(unit, modelCls)

    reconnectUnitSignalsToModel(unit, modelCls)
    model = modelCls()
    procs = autoAddAgents(unit)
    return unit, model, procs


Instruction:
Explain what the following Python 3 code does
def toSimModel(unit, targetPlatform=DummyPlatform(), dumpModelIn=None):
    sim_code = toRtl(unit,
                     targetPlatform=targetPlatform,
                     saveTo=dumpModelIn,
                     serializer=SimModelSerializer)
    if dumpModelIn is not None:
        d = os.path.join(os.getcwd(), dumpModelIn)
        dInPath = d in sys.path
        if not dInPath:
            sys.path.insert(0, d)
        if unit._name in sys.modules:
            del sys.modules[unit._name]
        simModule = importlib.import_module(unit._name)

        if not dInPath:
            sys.path.remove(d)
    else:
        simModule = ModuleType('simModule')
        # python supports only ~100 opened brackets
        # it exceded it throws MemoryError: s_push: parser stack overflow
        exec(sim_code, simModule.__dict__)

    return simModule.__dict__[unit._name]

Response: Create a simulation model for a given unit


Instruction:
Can you tell what is the following Python 3 function doing
def reconnectUnitSignalsToModel(synthesisedUnitOrIntf, modelCls):
    obj = synthesisedUnitOrIntf
    subInterfaces = obj._interfaces

    if subInterfaces:
        for intf in subInterfaces:
            # proxies are destroyed on original interfaces and only proxies on
            # array items will remain
            reconnectUnitSignalsToModel(intf, modelCls)
    else:
        # reconnect signal from model
        s = synthesisedUnitOrIntf
        s._sigInside = getattr(modelCls, s._sigInside.name)

Response: Re - connects model signals to unit


Instruction:
Here you have a function in Python 3, explain what it does
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)" % (simModel)
    if isinstance(outputFile, str):
        d = os.path.dirname(outputFile)
        if d:
            os.makedirs(d, exist_ok=True)
        with open(outputFile, 'w') as f:
            return _simUnitVcd(simModel, stimulFunctions,
                               f, until)
    else:
        return _simUnitVcd(simModel, stimulFunctions,
                           outputFile, until)

Response: Returns a simulation object for the given model and stimul functions.


Instruction:
Write a Python 3 function that can
simulate a single unit of the vcd

Response:
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 simulation, time units are defined in HdlSimulator
    :return: hdl simulator object
    """
    sim = HdlSimulator()

    # configure simulator to log in vcd
    sim.config = VcdHdlSimConfig(outputFile)

    # run simulation, stimul processes are register after initial
    # initialization
    sim.simUnit(simModel, until=until, extraProcesses=stimulFunctions)
    return sim


Instruction:
Can you generate the documentation for the following Python 3 function
def onTWriteCallback__init(self, sim):
        yield from self.onTWriteCallback(sim)
        self.intf.t._sigInside.registerWriteCallback(
            self.onTWriteCallback,
            self.getEnable)
        self.intf.o._sigInside.registerWriteCallback(
            self.onTWriteCallback,
            self.getEnable)

Response: This method is called by the onTWriteCallback method in the class.


Instruction:
Create a Python 3 function for
connecting to the port item on the given signal.

Response:
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))
            self.src = signal
            signal.endpoints.append(self)

        elif self.direction == DIRECTION.OUT:
            if self.dst is not None:
                raise HwtSyntaxError(
                    "Port %s is already associated with %r"
                    % (self.name, self.dst))
            self.dst = signal
            signal.drivers.append(self)

        else:
            raise NotImplementedError(self)

        signal.hidden = False
        signal.ctx.subUnits.add(self.unit)


Instruction:
Explain what the following Python 3 code does
def registerInternSig(self, signal):
        if self.direction == DIRECTION.OUT:
            if self.src is not None:
                raise HwtSyntaxError(
                    "Port %s is already associated with %s"
                    % (self.name, str(self.src)))
            self.src = signal

        elif self.direction == DIRECTION.IN:
            if self.dst is not None:
                raise HwtSyntaxError(
                    "Port %s is already associated with %s"
                    % (self.name, str(self.dst)))
            self.dst = signal

        else:
            raise NotImplementedError(self.direction)

Response: Registers an internal signal to this port item.


Instruction:
How would you implement a function in Python 3 that
connects this instance to the internal side of this instance.

Response:
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(self)
        else:
            raise NotImplementedError(d)


Instruction:
Implement a Python 3 function for
returning the canonical signal of the current object.

Response:
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)


Instruction:
Can you generate the documentation for the following Python 3 function
def isEvDependentOn(sig, process) -> bool:
    if sig is None:
        return False

    return process in sig.simFallingSensProcs\
        or process in sig.simRisingSensProcs

Response: Check if hdl process has event depenency on signal


Instruction:
Can you write a function in Python 3 where it
adds a process to the scheduler.

Response:
def _add_process(self, proc, priority) -> None:
        """
        Schedule process on actual time with specified priority
        """
        self._events.push(self.now, priority, proc)


Instruction:
Create a Python 3 function for
adding a hdl process to the execution queue.

Response:
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 the
        # end of this time
        if not self._applyValPlaned:
            # (apply on end of this time to minimalize process reevaluation)
            self._scheduleApplyValues()

        if isEvDependentOn(trigger, proc):
            if self.now == 0:
                return  # pass event dependent on startup
            self._seqProcsToRun.append(proc)
        else:
            self._combProcsToRun.append(proc)


Instruction:
Implement a Python 3 function for
initializing all the signals and processIOs for the given unit.

Response:
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.clone()
                s.simUpdateVal(self, mkUpdater(v, False))

        for u in unit._units:
            self._initUnitSignals(u)

        for p in unit._processes:
            self._addHdlProcToRun(None, p)

        for p, outputs in unit._outputs.items():
            # name has to be explicit because it may be possible that signal
            # with has this name was replaced by signal from parent/child
            containerNames = list(map(lambda x: x[0], outputs))

            class SpecificIoContainer(IoContainer):
                __slots__ = containerNames

            self._outputContainers[p] = SpecificIoContainer(outputs)


Instruction:
Create a Python 3 function to
schedule a new event to be processed when the update is done.

Response:
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_to_wake.append(self.__deleteCombUpdateDoneEv())
        self._add_process(cud, PRIORITY_AGENTS_UPDATE_DONE)
        self._combUpdateDonePlaned = True
        self.combUpdateDoneEv = cud
        return cud


Instruction:
Can you create a Python 3 function that
schedules the apply values to the signals.

Response:
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 runSeqProcesses is already scheduled
            return

        assert not self._seqProcsToRun and not self._runSeqProcessesPlaned, self.now
        self._add_process(self._runSeqProcesses(), PRIORITY_APPLY_SEQ)
        self._runSeqProcessesPlaned = True


Instruction:
Make a summary of the following Python 3 code
def _runCombProcesses(self) -> None:
        for proc in self._combProcsToRun:
            cont = self._outputContainers[proc]
            proc(self, cont)
            for sigName, sig in cont._all_signals:
                newVal = getattr(cont, sigName)
                if newVal is not None:
                    res = self._conflictResolveStrategy(newVal)
                    # prepare update
                    updater, isEvDependent = res
                    self._valuesToApply.append(
                        (sig, updater, isEvDependent, proc))
                    setattr(cont, sigName, None)
                    # else value is latched

        self._combProcsToRun = UniqList()

Response: Run all combinational processes.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _runSeqProcesses(self) -> Generator[None, None, None]:
        updates = []
        for proc in self._seqProcsToRun:
            try:
                outContainer = self._outputContainers[proc]
            except KeyError:
                # processes does not have to have outputs
                outContainer = None

            proc(self, outContainer)

            if outContainer is not None:
                updates.append(outContainer)

        self._seqProcsToRun = UniqList()
        self._runSeqProcessesPlaned = False

        for cont in updates:
            for sigName, sig in cont._all_signals:
                newVal = getattr(cont, sigName)
                if newVal is not None:
                    v = self._conflictResolveStrategy(newVal)
                    updater, _ = v
                    sig.simUpdateVal(self, updater)
                    setattr(cont, sigName, None)
        return
        yield

Response: Run all the event dependent processes and update the sequence number of events that have been applied.


Instruction:
Explain what the following Python 3 code does
def _applyValues(self) -> Generator[None, None, None]:
        va = self._valuesToApply
        self._applyValPlaned = False

        # log if there are items to log
        lav = self.config.logApplyingValues
        if va and lav:
            lav(self, va)
        self._valuesToApply = []

        # apply values to signals, values can overwrite each other
        # but each signal should be driven by only one process and
        # it should resolve value collision
        addSp = self._seqProcsToRun.append
        for s, vUpdater, isEventDependent, comesFrom in va:
            if isEventDependent:
                # now=0 and this was process initialization or async reg
                addSp(comesFrom)
            else:
                # regular combinational process
                s.simUpdateVal(self, vUpdater)

        self._runCombProcesses()

        # processes triggered from simUpdateVal can add new values
        if self._valuesToApply and not self._applyValPlaned:
            self._scheduleApplyValues()

        return
        yield

Response: Perform delta step by writing stacked values to signals


Instruction:
Can you create a Python 3 function that
reads value from signal or interface.

Response:
def read(self, sig) -> Value:
        """
        Read value from signal or interface
        """
        try:
            v = sig._val
        except AttributeError:
            v = sig._sigInside._val

        return v.clone()


Instruction:
How would you implement a function in Python 3 that
writes the given value to the specified signal or interface.

Response:
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

        # type cast of input value
        t = sig._dtype

        if isinstance(val, Value):
            v = val.clone()
            v = v._auto_cast(t)
        else:
            v = t.fromPy(val)

        # can not update value in signal directly due singnal proxies
        sig.simUpdateVal(self, lambda curentV: (
            valueHasChanged(curentV, v), v))

        if not self._applyValPlaned:
            if not (simSensProcs or
                    sig.simRisingSensProcs or
                    sig.simFallingSensProcs):
                # signal value was changed but there are no sensitive processes
                # to it because of this _applyValues is never planed
                # and should be
                self._scheduleApplyValues()
            elif (sig._writeCallbacks or
                  sig._writeCallbacksToEn):
                # signal write did not caused any change on any other signal
                # but there are still simulation agets waiting on
                # updateComplete event
                self._scheduleApplyValues()


Instruction:
Write a Python 3 function for
running simulation until specified time until.

Response:
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 handle to stop simulation
        schedule(until, PRIORITY_URGENT, raise_StopSimulation(self))

        try:
            # for all events
            while True:
                nextTime, priority, process = next_event()
                self.now = nextTime
                # process is python generator or Event
                if isinstance(process, Event):
                    process = iter(process)

                # run process or activate processes dependent on Event
                while True:
                    try:
                        ev = next(process)
                    except StopIteration:
                        break

                    # if process requires waiting put it back in queue
                    if isinstance(ev, Wait):
                        # nextTime is self.now
                        schedule(nextTime + ev.time, priority, process)
                        break
                    elif isinstance(ev, Event):
                        # process going to wait for event
                        # if ev.process_to_wake is None event was already
                        # destroyed
                        ev.process_to_wake.append(process)
                        break
                    else:
                        # else this process spoted new process
                        # and it has to be put in queue
                        schedule(nextTime, priority, ev)

        except StopSimumulation:
            return


Instruction:
Can you write a function in Python 3 where it
adds a process to the set of processes.

Response:
def add_process(self, proc) -> None:
        """
        Add process to events with default priority on current time
        """
        self._events.push(self.now, PRIORITY_NORMAL, proc)


Instruction:
Implement a function in Python 3 to
run simulation for a single unit instance

Response:
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 extraProcesses:
            add_proc(p(self))

        self._initUnitSignals(synthesisedUnit)
        self.run(until)


Instruction:
Given the following Python 3 function, write the documentation
def _mkOp(fn):
    def op(*operands, key=None) -> RtlSignalBase:
        """
        :param operands: variadic parameter of input uperands
        :param key: optional function applied on every operand
            before processing
        """
        assert operands, operands
        top = None
        if key is not None:
            operands = map(key, operands)

        for s in operands:
            if top is None:
                top = s
            else:
                top = fn(top, s)
        return top

    return op

Response: Create a variadic operator function that applies fn to each element of the input uperands and returns the result of the function fn.


Instruction:
Write a Python 3 script for
checking if the signalItem is register or wire

Response:
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


Instruction:
Implement a function in Python 3 to
convert all ternary operators to IfContainers

Response:
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.singleDriver()
                if not isinstance(d, Operator) or d.operator != AllOps.TERNARY:
                    raise DoesNotContainsTernary()
                else:
                    ops = d.operands
                    ifc = IfContainer(ops[0],
                                      [Assignment(ops[1], st.dst)],
                                      [Assignment(ops[2], st.dst)]
                                      )
                    stms.append(ifc)
                    continue

            except (MultipleDriversErr, DoesNotContainsTernary):
                pass
            except NoDriverErr:
                assert (hasattr(st.src, "_interface")
                        and st.src._interface is not None)\
                    or st.src.defVal.vldMask, st.src

        stms.append(st)
    return stms


Instruction:
Write a Python 3 function for
serializing HWProcess objects as VHDL

Response:
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,
                                     lambda x: isinstance(x,
                                                          (IfContainer,
                                                           SwitchContainer,
                                                           WhileContainer,
                                                           WaitStm)))

        sensitivityList = sorted(
            map(lambda s: cls.sensitivityListItem(s, ctx),
                proc.sensitivityList))

        if hasToBeVhdlProcess:
            childCtx = ctx.withIndent()
        else:
            childCtx = copy(ctx)

        def createTmpVarFn(suggestedName, dtype):
            s = RtlSignal(None, None, dtype, virtualOnly=True)
            s.name = ctx.scope.checkedName(suggestedName, s)
            s.hidden = False
            serializedS = cls.SignalItem(s, childCtx, declaration=True)
            extraVars.append(s)
            extraVarsSerialized.append(serializedS)
            return s

        childCtx.createTmpVarFn = createTmpVarFn

        statemets = [cls.asHdl(s, childCtx) for s in body]
        proc.name = ctx.scope.checkedName(proc.name, proc)

        extraVarsInit = []
        for s in extraVars:
            if isinstance(s.defVal, RtlSignalBase) or s.defVal.vldMask:
                a = Assignment(s.defVal, s, virtualOnly=True)
                extraVarsInit.append(cls.Assignment(a, childCtx))
            else:
                assert s.drivers, s
            for d in s.drivers:
                extraVarsInit.append(cls.asHdl(d, childCtx))

        _hasToBeVhdlProcess = hasToBeVhdlProcess
        hasToBeVhdlProcess = extraVars or hasToBeVhdlProcess

        if hasToBeVhdlProcess and not _hasToBeVhdlProcess:
            # add indent because we did not added it before because we did not
            # know t
            oneIndent = getIndent(1)
            statemets = list(map(lambda x: oneIndent + x, statemets))

        return cls.processTmpl.render(
            indent=getIndent(ctx.indent),
            name=proc.name,
            hasToBeVhdlProcess=hasToBeVhdlProcess,
            extraVars=extraVarsSerialized,
            sensitivityList=", ".join(sensitivityList),
            statements=extraVarsInit + statemets
        )


Instruction:
Write a Python 3 function for
computing the hamming distance between two hashes

Response:
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)))


Instruction:
Can you write a function in Python 3 where it
computes the average hash of the given image.

Response:
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(image.getdata())

    avg = sum(pixels) / len(pixels)

    # Compute the hash based on each pixels value compared to the average.
    bits = "".join(map(lambda pixel: '1' if pixel > avg else '0', pixels))
    hashformat = "0{hashlength}x".format(hashlength=hash_size ** 2 // 4)
    return int(bits, 2).__format__(hashformat)


Instruction:
Write a Python 3 function that can
compute the hamming distance between two images

Response:
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)


Instruction:
Can you tell what is the following Python 3 function doing
def setup_platform(hass, config, add_entities, discovery_info=None):
    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)
    device = VizioDevice(host, token, name, volume_step, device_type)
    if device.validate_setup() is False:
        _LOGGER.error("Failed to set up Vizio platform, "
                      "please check if host and API key are correct")
        return
    elif (token is None or token == "") and device_type == "tv":
        _LOGGER.error("Failed to set up Vizio platform, "
                      "if device_class is 'tv' then an auth_token needs "
                      "to be provided, otherwise if device_class is "
                      "'soundbar' then add the right device_class to config")
        return

    if config.get(CONF_SUPPRESS_WARNING):
        from requests.packages import urllib3
        _LOGGER.warning("InsecureRequestWarning is disabled "
                        "because of Vizio platform configuration")
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    add_entities([device], True)

Response: Setup the Vizio media player platform.


Instruction:
Can you create a Python 3 function that
updates the state of the current state of the object.

Response:
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._max_volume

            input_ = self._device.get_current_input()
            if input_ is not None:
                self._current_input = input_.meta_name

            inputs = self._device.get_inputs()
            if inputs is not None:
                self._available_inputs = [input_.name for input_ in inputs]

        else:
            if is_on is None:
                self._state = None
            else:
                self._state = STATE_OFF

            self._volume_level = None
            self._current_input = None
            self._available_inputs = None


Instruction:
Create a Python 3 function for
increasing the volume of the device.

Response:
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)


Instruction:
Explain what the following Python 3 code does
def volume_down(self):
        self._volume_level -= self._volume_step / self._max_volume
        self._device.vol_down(num=self._volume_step)

Response: Decreasing volume of the device.


Instruction:
Explain what the following Python 3 code does
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
                BB_A3 | BB_A7 | BB_I3 | BB_I7, # SILVER
                BB_A4 | BB_A6 | BB_I4 | BB_I6, # GOLD
                BB_B2 | BB_H8,                 # BISHOP
                BB_B8 | BB_H2,                 # ROOK
                BB_A5 | BB_I5,                 # KING
                BB_VOID,                       # PROM_PAWN
                BB_VOID,                       # PROM_LANCE
                BB_VOID,                       # PROM_KNIGHT
                BB_VOID,                       # PROM_SILVER
                BB_VOID,                       # PROM_BISHOP
                BB_VOID,                       # PROM_ROOK
        ]

        self.pieces_in_hand = [collections.Counter(), collections.Counter()]

        self.occupied = Occupied(BB_RANK_G | BB_H2 | BB_H8 | BB_RANK_I, BB_RANK_A | BB_B2 | BB_B8 | BB_RANK_C)

        self.king_squares = [I5, A5]
        self.pieces = [NONE for i in SQUARES]

        for i in SQUARES:
            mask = BB_SQUARES[i]
            for piece_type in PIECE_TYPES:
                if mask & self.piece_bb[piece_type]:
                    self.pieces[i] = piece_type

        self.turn = BLACK
        self.move_number = 1
        self.captured_piece_stack = collections.deque()
        self.move_stack = collections.deque()
        self.incremental_zobrist_hash = self.board_zobrist_hash(DEFAULT_RANDOM_ARRAY)
        self.transpositions = collections.Counter((self.zobrist_hash(), ))

Response: Restores the starting position.


Instruction:
Can you create a Python 3 function that
gets the piece at the given square.

Response:
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)


Instruction:
Explain what the following Python 3 code does
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_SQUARES[square]

        self.piece_bb[piece_type] ^= mask

        color = int(bool(self.occupied[WHITE] & mask))

        self.pieces[square] = NONE
        self.occupied.ixor(mask, color, square)

        # Update incremental zobrist hash.
        if color == BLACK:
            piece_index = (piece_type - 1) * 2
        else:
            piece_index = (piece_type - 1) * 2 + 1
        self.incremental_zobrist_hash ^= DEFAULT_RANDOM_ARRAY[81 * piece_index + 9 * rank_index(square) + file_index(square)]

Response: Removes a piece from the given square if present.


Instruction:
Make a summary of the following Python 3 code
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] = piece.piece_type

        mask = BB_SQUARES[square]

        piece_type = piece.piece_type

        self.piece_bb[piece_type] |= mask

        if piece_type == KING:
            self.king_squares[piece.color] = square

        self.occupied.ixor(mask, piece.color, square)

        # Update incremental zorbist hash.
        if piece.color == BLACK:
            piece_index = (piece.piece_type - 1) * 2
        else:
            piece_index = (piece.piece_type - 1) * 2 + 1
        self.incremental_zobrist_hash ^= DEFAULT_RANDOM_ARRAY[81 * piece_index + 9 * rank_index(square) + file_index(square)]

Response: Sets a piece at the given square. An existing piece is replaced.


Instruction:
Implement a Python 3 function for
checking if the given move would leave the king in check or put it into check.

Response:
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)
        self.pop()
        return is_suicide or is_check_by_dropping_pawn


Instruction:
Implement a function in Python 3 to
check if the king of the other side is attacked.

Response:
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])


Instruction:
Write a Python 3 script for
checking if the game is over due to checkmate stalemate or fourfold repetition.

Response:
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

        # Fourfold repetition.
        if self.is_fourfold_repetition():
            return True

        return False


Instruction:
Make a summary of the following Python 3 code
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

Response: Checks if the current position is a checkmate.


Instruction:
Can you write a function in Python 3 where it
returns True if the game is ended if a position occurs for the fourth time on consecutive alternating moves.

Response:
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 appeared at least four times.
        if self.transpositions[zobrist_hash] < 4:
            return False

        return True


Instruction:
Explain what the following Python 3 code does
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 legal. Otherwise there is no guarantee that the previous
        board state can be restored. To check it yourself you can use:
        >>> move in board.pseudo_legal_moves
        True
        '''
        # Increment move number.
        self.move_number += 1

        # Remember game state.
        captured_piece = self.piece_type_at(move.to_square) if move else NONE
        self.captured_piece_stack.append(captured_piece)
        self.move_stack.append(move)

        # On a null move simply swap turns.
        if not move:
            self.turn ^= 1
            return

        if move.drop_piece_type:
            # Drops.
            piece_type = move.drop_piece_type
            from_hand = True
        else:
            # Promotion.
            piece_type = self.piece_type_at(move.from_square)
            from_hand = False

            if move.promotion:
                piece_type = PIECE_PROMOTED[piece_type]

            # Remove piece from target square.
            self.remove_piece_at(move.from_square, False)

        # Put piece on target square.
        self.set_piece_at(move.to_square, Piece(piece_type, self.turn), from_hand, True)

        # Swap turn.
        self.turn ^= 1

        # Update transposition table.
        self.transpositions.update((self.zobrist_hash(), ))

Response: Pushes a piece onto the stack.


Instruction:
Here you have a function in Python 3, explain what it does
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 -= 1

        # Restore state.
        captured_piece_type = self.captured_piece_stack.pop()
        captured_piece_color = self.turn

        # On a null move simply swap the turn.
        if not move:
            self.turn ^= 1
            return move

        # Restore the source square.
        piece_type = self.piece_type_at(move.to_square)
        if move.promotion:
            piece_type = PIECE_PROMOTED.index(piece_type)

        if move.from_square is None:
            self.add_piece_into_hand(piece_type, self.turn ^ 1)
        else:
            self.set_piece_at(move.from_square, Piece(piece_type, self.turn ^ 1))

        # Restore target square.
        if captured_piece_type:
            self.remove_piece_from_hand(captured_piece_type, captured_piece_color ^ 1)
            self.set_piece_at(move.to_square, Piece(captured_piece_type, captured_piece_color))
        else:
            self.remove_piece_at(move.to_square)

        # Swap turn.
        self.turn ^= 1

        return move

Response: Restores the previous position and returns the last move from the stack.


Instruction:
Write a Python 3 function that can
get an SFEN representation of the current position.

Response:
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:
                if empty:
                    sfen.append(str(empty))
                    empty = 0
                sfen.append(piece.symbol())

            if BB_SQUARES[square] & BB_FILE_1:
                if empty:
                    sfen.append(str(empty))
                    empty = 0

                if square != I1:
                    sfen.append('/')

        sfen.append(' ')

        # Side to move.
        if self.turn == WHITE:
            sfen.append('w')
        else:
            sfen.append('b')

        sfen.append(' ')

        # Pieces in hand
        pih_len = 0
        for color in COLORS:
            p = self.pieces_in_hand[color]
            pih_len += len(p)
            for piece_type in sorted(p.keys(), reverse=True):
                if p[piece_type] >= 1:
                    if p[piece_type] > 1:
                        sfen.append(str(p[piece_type]))
                    piece = Piece(piece_type, color)
                    sfen.append(piece.symbol())
        if pih_len == 0:
            sfen.append('-')

        sfen.append(' ')

        # Move count
        sfen.append(str(self.move_number))

        return ''.join(sfen)


Instruction:
Can you generate the documentation for the following Python 3 function
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 parts: {0}'.format(repr(sfen)))

        # Ensure the board part is valid.
        rows = parts[0].split('/')
        if len(rows) != 9:
            raise ValueError('expected 9 rows in position part of sfen: {0}'.format(repr(sfen)))

        # Validate each row.
        for row in rows:
            field_sum = 0
            previous_was_digit = False
            previous_was_plus = False

            for c in row:
                if c in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
                    if previous_was_digit:
                        raise ValueError('two subsequent digits in position part of sfen: {0}'.format(repr(sfen)))
                    if previous_was_plus:
                        raise ValueError('Cannot promote squares in position part of sfen: {0}'.format(repr(sfen)))
                    field_sum += int(c)
                    previous_was_digit = True
                    previous_was_plus = False
                elif c == '+':
                    if previous_was_plus:
                        raise ValueError('Double promotion prefixes in position part of sfen: {0}'.format(repr(sfen)))
                    previous_was_digit = False
                    previous_was_plus = True
                elif c.lower() in ['p', 'l', 'n', 's', 'g', 'b', 'r', 'k']:
                    field_sum += 1
                    if previous_was_plus and (c.lower() == 'g' or c.lower() == 'k'):
                      raise ValueError('Gold and King cannot promote in position part of sfen: {0}')
                    previous_was_digit = False
                    previous_was_plus = False
                else:
                    raise ValueError('invalid character in position part of sfen: {0}'.format(repr(sfen)))

            if field_sum != 9:
                raise ValueError('expected 9 columns per row in position part of sfen: {0}'.format(repr(sfen)))

        # Check that the turn part is valid.
        if not parts[1] in ['b', 'w']:
            raise ValueError("expected 'b' or 'w' for turn part of sfen: {0}".format(repr(sfen)))

        # Check pieces in hand is valid.
        # TODO: implement with checking parts[2]

        # Check that the fullmove number part is valid.
        # 0 is allowed for compability but later replaced with 1.
        if int(parts[3]) < 0:
            raise ValueError('fullmove number must be positive: {0}'.format(repr(sfen)))

        # Clear board.
        self.clear()

        # Put pieces on the board.
        square_index = 0
        previous_was_plus = False
        for c in parts[0]:
            if c in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
                square_index += int(c)
            elif c == '+':
                previous_was_plus = True
            elif c == '/':
                pass
            else:
                piece_symbol = c
                if previous_was_plus:
                  piece_symbol = '+' + piece_symbol
                self.set_piece_at(square_index, Piece.from_symbol(piece_symbol))
                square_index += 1
                previous_was_plus = False

        # Set the turn.
        if parts[1] == 'w':
            self.turn = WHITE
        else:
            self.turn = BLACK

        # Set the pieces in hand
        self.pieces_in_hand = [collections.Counter(), collections.Counter()]
        if parts[2] != '-':
            piece_count = 0
            for c in parts[2]:
                if c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
                    piece_count *= 10
                    piece_count += int(c)
                else:
                    piece = Piece.from_symbol(c)
                    if piece_count == 0:
                        piece_count = 1
                    self.add_piece_into_hand(piece.piece_type, piece.color, piece_count)
                    piece_count = 0

        # Set the mover counters.
        self.move_number = int(parts[3]) or 1

        # Reset the transposition table.
        self.transpositions = collections.Counter((self.zobrist_hash(), ))

Response: Parses a SFEN string and sets the position from it.


Instruction:
Write a Python 3 function that can
push a new entry in the move stack and returns the new move.

Response:
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)
        return move


Instruction:
Implement a Python 3 function for
returning a Zobrist hash of the current position.

Response:
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:
            zobrist_hash ^= array[2268]

        # pieces in hand pattern is
        # 19 * 5 * 5 * 5 * 5 * 3 * 3 = 106875 < pow(2, 17)
        # just checking black side is okay in normal state
        i = (
                self.pieces_in_hand[BLACK][ROOK] * 35625 +
                self.pieces_in_hand[BLACK][BISHOP] * 11875 +
                self.pieces_in_hand[BLACK][GOLD] * 2375 +
                self.pieces_in_hand[BLACK][SILVER] * 475 +
                self.pieces_in_hand[BLACK][KNIGHT] * 95 +
                self.pieces_in_hand[BLACK][LANCE] * 19 +
                self.pieces_in_hand[BLACK][PAWN])
        bit = bit_scan(i)
        while bit != -1 and bit is not None:
            zobrist_hash ^= array[2269 + bit]
            bit = bit_scan(i, bit + 1)

        return zobrist_hash


Instruction:
Implement a Python 3 function for
getting the symbol of the current piece.

Response:
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]


Instruction:
How would you explain what the following Python 3 function does
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(symbol.lower()), BLACK)

Response: Creates a piece instance from a piece symbol.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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(), SQUARE_NAMES[self.to_square])
            else:
                return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square] + \
                       ('+' if self.promotion else '')
        else:
            return '0000'

Response: Gets an USI string for the current locale.


Instruction:
Write a Python 3 function that can
parse an USI string and returns a new object.

Response:
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])
                return cls(None, SQUARE_NAMES.index(usi[2:4]), False, piece.piece_type)
            else:
                return cls(SQUARE_NAMES.index(usi[0:2]), SQUARE_NAMES.index(usi[2:4]))
        elif len(usi) == 5 and usi[4] == '+':
            return cls(SQUARE_NAMES.index(usi[0:2]), SQUARE_NAMES.index(usi[2:4]), True)
        else:
            raise ValueError('expected usi string to be of length 4 or 5')


Instruction:
Create a Python 3 function for
accepting a string and parse it into many commits. Parse and yield each commit - dictionary. This function is a generator.

Response:
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).groupdict()
        parsed_commit = parse_commit(parts)
        yield parsed_commit


Instruction:
Given the following Python 3 function, write the documentation
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']
    parent_block = parts['parents']
    commit['parents'] = [
        parse_parent_line(parentline)
        for parentline in
        parent_block.splitlines()
    ]
    commit['author'] = parse_author_line(parts['author'])
    commit['committer'] = parse_committer_line(parts['committer'])
    message_lines = [
        parse_message_line(msgline)
        for msgline in
        parts['message'].split("\n")
    ]
    commit['message'] = "\n".join(
        msgline
        for msgline in
        message_lines
        if msgline is not None
    )
    commit['changes'] = [
        parse_numstat_line(numstat)
        for numstat in
        parts['numstats'].splitlines()
    ]
    return commit

Response: Accept a parsed single commit.


Instruction:
How would you explain what the following Python 3 function does
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,
            'log',
            '--numstat',
            '--pretty=raw'
        ]
    else:
        command = ['git', 'log', '--numstat', '--pretty=raw']
    if git_since is not None:
        command.append('--since=' + git_since)
    raw_git_log = subprocess.Popen(
        command,
        stdout=subprocess.PIPE
    )
    if sys.version_info < (3, 0):
        return raw_git_log.stdout
    else:
        return raw_git_log.stdout.read().decode('utf-8', 'ignore')

Response:
Run git log on the specified
Taxonomy git repository and return its stdout as a pseudo - File.


Instruction:
Create a Python 3 function for
loading config from CLI arguments and returns a list of config file names

Response:
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, prog_name, subcommand):
        parser = original_parser(self, prog_name, subcommand)
        argparser_add_argument(parser, config)
        return parser

    BaseCommand.create_parser = patched_parser

    try:
        parser = argparse.ArgumentParser(add_help=False)
        argparser_add_argument(parser, config)

        config_arg, default_args = parser.parse_known_args(argv)
        config.load(config_arg.config)
        yield default_args
    finally:
        # Put that create_parser back where it came from or so help me!
        BaseCommand.create_parser = original_parser


Instruction:
Can you tell what is the following Python 3 function doing
def execute_from_command_line_with_config(config: GoodConf, argv: List[str]):
    with load_config_from_cli(config, argv) as args:
        from django.core.management import execute_from_command_line
        execute_from_command_line(args)

Response: Load s config then runs Django s execute_from_command_line


Instruction:
How would you explain what the following Python 3 function does
def argparser_add_argument(parser: argparse.ArgumentParser, config: GoodConf):
    help = "Config file."
    if config.file_env_var:
        help += (" Can also be configured via the "
                 "environment variable: {}".format(config.file_env_var))
    if config.default_files:
        help += (" Defaults to the first file that exists from "
                 "[{}].".format(', '.join(config.default_files)))
    parser.add_argument('-C', '--config', metavar='FILE', help=help)

Response: Adds an argument for config to an argument parser


Instruction:
Write a Python 3 script to
load a configuration file into a dictionary.

Response:
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 ruamel.yaml
        loader = ruamel.yaml.safe_load
    else:
        loader = json.load
    with open(path) as f:
        config = loader(f)
    return config


Instruction:
Create a Python 3 function for
loading config file and set values

Response:
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])
            if not self.config_file:
                for filename in self.default_files:
                    self.config_file = _find_file(filename, require=False)
                    if self.config_file:
                        break
        if self.config_file:
            config = _load_config(self.config_file)
            log.info("Loading config from %s", self.config_file)
        else:
            config = {}
            log.info("No config file specified. "
                     "Loading with environment variables.")
        self.set_values(config)


Instruction:
Here you have a function in Python 3, explain what it does
def generate_yaml(cls, **override):
        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)
        if cls.__doc__:
            dict_from_yaml.yaml_set_start_comment(
                '\n' + cls.__doc__ + '\n\n')
        for k in dict_from_yaml.keys():
            if cls._values[k].help:
                dict_from_yaml.yaml_set_comment_before_after_key(
                    k, before='\n' + cls._values[k].help)
        yaml_str = StringIO()
        yaml.dump(dict_from_yaml, yaml_str)
        yaml_str.seek(0)
        return yaml_str.read()

Response: Generates a YAML string of the current configuration.


Instruction:
How would you explain what the following Python 3 function does
def generate_markdown(cls):
        lines = []
        if cls.__doc__:
            lines.extend(['# {}'.format(cls.__doc__), ''])
        for k, v in cls._values.items():
            lines.append('* **{}**  '.format(k))
            if v.required:
                lines[-1] = lines[-1] + '_REQUIRED_  '
            if v.help:
                lines.append('  {}  '.format(v.help))
            lines.append('  type: `{}`  '.format(v.cast_as.__name__))
            if v.default is not None:
                lines.append('  default: `{}`  '.format(v.default))
        return '\n'.join(lines)

Response: Generates a markdown string for the class.


Instruction:
How would you explain what the following Python 3 function does
def cast(self, val: str):
        try:
            return getattr(self, 'cast_as_{}'.format(
                self.cast_as.__name__.lower()))(val)
        except AttributeError:
            return self.cast_as(val)

Response: converts string to type requested by cast_as


Instruction:
Implement a function in Python 3 to
return all dates from first to last included.

Response:
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)]


Instruction:
Given the following Python 3 function, write the documentation
def parse_date(s):
    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()

Response: Fast %Y - m - d parsing.


Instruction:
Write a Python 3 function that can
load the data from a file.

Response:
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.read()

        if currency_file.endswith('.zip'):
            self.load_lines(get_lines_from_zip(content))
        else:
            self.load_lines(content.decode('utf-8').splitlines())


Instruction:
Can you write a function in Python 3 where it
fills missing rates of a currency with the closest available ones.

Response:
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:
                rates[date] = None

        if self.verbose:
            missing = len([r for r in itervalues(rates) if r is None])
            if missing:
                print('{0}: {1} missing rates from {2} to {3} ({4} days)'.format(
                    currency, missing, first_date, last_date,
                    1 + (last_date - first_date).days))


Instruction:
Can you create a Python 3 function that
computes the missing rates for a given currency.

Response:
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 closest rates forward and backward
        tmp = defaultdict(lambda: [None, None])

        for date in sorted(rates):
            rate = rates[date]
            if rate is not None:
                closest_rate = rate
                dist = 0
            else:
                dist += 1
                tmp[date][0] = closest_rate, dist

        for date in sorted(rates, reverse=True):
            rate = rates[date]
            if rate is not None:
                closest_rate = rate
                dist = 0
            else:
                dist += 1
                tmp[date][1] = closest_rate, dist

        for date in sorted(tmp):
            (r0, d0), (r1, d1) = tmp[date]
            rates[date] = (r0 * d1 + r1 * d0) / (d0 + d1)
            if self.verbose:
                print(('{0}: filling {1} missing rate using {2} ({3}d old) and '
                       '{4} ({5}d later)').format(currency, date, r0, d0, r1, d1))


Instruction:
Write a Python 3 script to
get a rate for a given currency and date.

Response:
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, 11, 21))
        Traceback (most recent call last):
        RateNotFoundError: BGN has no rate for 2010-11-21
        """
        if currency == self.ref_currency:
            return 1.0

        if date not in self._rates[currency]:
            first_date, last_date = self.bounds[currency]

            if not self.fallback_on_wrong_date:
                raise RateNotFoundError('{0} not in {1} bounds {2}/{3}'.format(
                    date, currency, first_date, last_date))

            if date < first_date:
                fallback_date = first_date
            elif date > last_date:
                fallback_date = last_date
            else:
                raise AssertionError('Should never happen, bug in the code!')

            if self.verbose:
                print(r'/!\ {0} not in {1} bounds {2}/{3}, falling back to {4}'.format(
                    date, currency, first_date, last_date, fallback_date))

            date = fallback_date

        rate = self._rates[currency][date]
        if rate is None:
            raise RateNotFoundError('{0} has no rate for {1}'.format(currency, date))
        return rate


Instruction:
Explain what the following Python 3 code does
def convert(self, amount, currency, new_currency='EUR', date=None):
        for c in currency, new_currency:
            if c not in self.currencies:
                raise ValueError('{0} is not a supported currency'.format(c))

        if date is None:
            date = self.bounds[currency].last_date
        else:
            try:
                date = date.date()  # fallback if input was a datetime object
            except AttributeError:
                pass

        r0 = self._get_rate(currency, date)
        r1 = self._get_rate(new_currency, date)

        return float(amount) / r0 * r1

Response: Convert amount from a currency to another currency.


Instruction:
Write a Python 3 function that can
group iterable by n elements.

Response:
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))


Instruction:
Given the following Python 3 function, write the documentation
def animate(frames, interval, name, iterations=2):
    for i in range(iterations):
        for frame in frames:
            frame = get_coded_text(frame)
            output = "\r{0} {1}".format(frame, name)
            sys.stdout.write(output)
            sys.stdout.write(CLEAR_LINE)
            sys.stdout.flush()
            time.sleep(0.001 * interval)

Response: Animate given frames for set number of iterations.


Instruction:
Can you create a Python 3 function that
converts the object to string

Response:
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_dict = {}
        self.varobj_dict = {}

        varis = set()
        for d in cnf.dis:
            for v in d:
                varis.add(v.name)

        ret = "p cnf %d %d" % (len(varis), len(cnf.dis))

        varis = dict(list(zip(sorted(list(varis)),list(map(str,list(range(1,len(varis)+1)))))))

        for v in varis:
            vo = Variable(v)
            self.varname_dict[vo] = varis[v]
            self.varobj_dict[varis[v]] = vo

        for d in cnf.dis:
            ret += "\n"
            vnamelist = []
            for v in d:
                vnamelist.append(("-" if v.inverted else "") + varis[v.name])
            ret += " ".join(vnamelist) + " 0"

        return ret


Instruction:
How would you code a function in Python 3 to
load the polynomial series for name and return it.

Response:
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


Instruction:
Implement a Python 3 function for
computing the position of name at time tdb + tdb2.

Response:
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 `tdb` an
        array, which is more efficient than calling this method multiple
        times; the return value will be a two-dimensional array giving a
        row of values for each coordinate.

        For extra precision, the time can be split into two floats; a
        popular choice is to use `tdb` for the integer or half-integer
        date, and `tdb2` to hold the remaining fraction.

        Consult the `names` attribute of this ephemeris for the values
        of `name` it supports, such as ``'mars'`` or ``'earthmoon'``.

        """
        bundle = self.compute_bundle(name, tdb, tdb2)
        return self.position_from_bundle(bundle)


Instruction:
How would you code a function in Python 3 to
compute the position and velocity of a name at a given dynamical time.

Response:
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.
        If there are many dates you want computed, then make `tdb` an
        array, which is more efficient than calling this method multiple
        times; the return values will be two-dimensional arrays giving a
        row of values for each coordinate.

        For extra precision, the time can be split into two floats; a
        popular choice is to use `tdb` for the integer or half-integer
        date, and `tdb2` to hold the remaining fraction.

        Consult the `names` attribute of this ephemeris for the values
        of `name` it supports, such as ``'mars'`` or ``'earthmoon'``.

        """
        bundle = self.compute_bundle(name, tdb, tdb2)
        position = self.position_from_bundle(bundle)
        velocity = self.velocity_from_bundle(bundle)
        return position, velocity


Instruction:
Implement a function in Python 3 to
compute the Chebyshev intermediate values for a specific entry in the set of available Chebyshev entries.

Response:
def compute_bundle(self, name, tdb, tdb2=0.0):
        """[DEPRECATED] Return a tuple of coefficients and parameters for `tdb`.

        The return value is a tuple that bundles together the
        coefficients and other Chebyshev intermediate values that are
        needed for the computation of either the position or velocity.
        The bundle can then be passed to either `position_from_bundle()`
        or `velocity_from_bundle()` to finish the computation.  See the
        package-level documentation for details; most users will simply
        call `position()` or `position_and_velocity()` instead.

        The barycentric dynamical time `tdb` argument should be a float.
        If there are many dates you want computed, then make `tdb` an
        array, which is more efficient than calling this method multiple
        times; the return values will be arrays providing a value for
        each time in `tdb`.

        For extra precision, the time can be split into two floats; a
        popular choice is to use `tdb` for the integer or half-integer
        date, and `tdb2` to hold the remaining fraction.

        Consult the `names` attribute of this ephemeris for the values
        of `name` it supports, such as ``'mars'`` or ``'earthmoon'``.

        """
        input_was_scalar = getattr(tdb, 'shape', ()) == ()
        if input_was_scalar:
            tdb = np.array((tdb,))
        # no need to deal with tdb2; numpy broadcast will add fine below.

        coefficient_sets = self.load(name)
        number_of_sets, axis_count, coefficient_count = coefficient_sets.shape

        jalpha, jomega = self.jalpha, self.jomega
        days_per_set = (jomega - jalpha) / number_of_sets
        # to keep precision, first subtract, then add
        index, offset = divmod((tdb - jalpha) + tdb2, days_per_set)
        index = index.astype(int)

        if (index < 0).any() or (number_of_sets < index).any():
            raise DateError('ephemeris %s only covers dates %.1f through %.1f'
                            % (self.name, jalpha, jomega))

        omegas = (index == number_of_sets)
        index[omegas] -= 1
        offset[omegas] += days_per_set

        coefficients = np.rollaxis(coefficient_sets[index], 1)

        # Chebyshev recurrence:

        T = np.empty((coefficient_count, len(index)))
        T[0] = 1.0
        T[1] = t1 = 2.0 * offset / days_per_set - 1.0
        twot1 = t1 + t1
        for i in range(2, coefficient_count):
            T[i] = twot1 * T[i-1] - T[i-2]

        bundle = coefficients, days_per_set, T, twot1
        return bundle


Instruction:
Write a Python 3 function that can
return the position of the entry in the given bundle.

Response:
def position_from_bundle(self, bundle):
        """[DEPRECATED] Return position, given the `coefficient_bundle()` return value."""

        coefficients, days_per_set, T, twot1 = bundle
        return (T.T * coefficients).sum(axis=2)


Instruction:
Write a Python 3 script for
returning velocity given the coefficient_bundle return value.

Response:
def velocity_from_bundle(self, bundle):
        """[DEPRECATED] Return velocity, given the `coefficient_bundle()` return value."""

        coefficients, days_per_set, T, twot1 = bundle
        coefficient_count = coefficients.shape[2]

        # Chebyshev derivative:

        dT = np.empty_like(T)
        dT[0] = 0.0
        dT[1] = 1.0
        dT[2] = twot1 + twot1
        for i in range(3, coefficient_count):
            dT[i] = twot1 * dT[i-1] - dT[i-2] + T[i-1] + T[i-1]
        dT *= 2.0
        dT /= days_per_set

        return (dT.T * coefficients).sum(axis=2)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def read_record(self, n):
        self.file.seek(n * K - K)
        return self.file.read(K)

Response: Return record n as 1 234 bytes.


Instruction:
Write a Python 3 function that can
write data to file record n.

Response:
def write_record(self, n, data):
        """Write `data` to file record `n`; records are indexed from 1."""
        self.file.seek(n * K - K)
        return self.file.write(data)


Instruction:
Given the following Python 3 function, write the documentation
def map_words(self, start, end):
        i, j = 8 * start - 8, 8 * end
        try:
            fileno = self.file.fileno()
        except (AttributeError, io.UnsupportedOperation):
            fileno = None
        if fileno is None:
            skip = 0
            self.file.seek(i)
            m = self.file.read(j - i)
        else:
            skip = i % mmap.ALLOCATIONGRANULARITY
            r = mmap.ACCESS_READ
            m = mmap.mmap(fileno, length=j-i+skip, access=r, offset=i-skip)
        if sys.version_info > (3,):
            m = memoryview(m)  # so further slicing can return views
        return m, skip

Response: Return a memory - map of the elements start through end.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def comments(self):
        record_numbers = range(2, self.fward)
        if not record_numbers:
            return ''
        data = b''.join(self.read_record(n)[0:1000] for n in record_numbers)
        try:
            return data[:data.find(b'\4')].decode('ascii').replace('\0', '\n')
        except IndexError:
            raise ValueError('DAF file comment area is missing its EOT byte')
        except UnicodeDecodeError:
            raise ValueError('DAF file comment area is not ASCII text')

Response: Return the text inside the comment area of the file.


Instruction:
Here you have a function in Python 3, explain what it does
def read_array(self, start, end):
        f = self.file
        f.seek(8 * (start - 1))
        length = 1 + end - start
        data = f.read(8 * length)
        return ndarray(length, self.endian + 'd', data)

Response: Return a numpy array from start to end inclusive indexed from 1.


Instruction:
Can you tell what is the following Python 3 function doing
def map_array(self, start, end):
        if self._array is None:
            self._map, skip = self.map_words(1, self.free - 1)
            assert skip == 0
            self._array = ndarray(self.free - 1, self.endian + 'd', self._map)
        return self._array[start - 1 : end]

Response: Return a numpy array from start to end inclusive indexed from 1.


Instruction:
Create a Python 3 function to
yield the number of summaries and data for each record.

Response:
def summary_records(self):
        """Yield (record_number, n_summaries, record_data) for each record.

        Readers will only use the second two values in each tuple.
        Writers can update the record using the `record_number`.

        """
        record_number = self.fward
        unpack = self.summary_control_struct.unpack
        while record_number:
            data = self.read_record(record_number)
            next_number, previous_number, n_summaries = unpack(data[:24])
            yield record_number, n_summaries, data
            record_number = int(next_number)


Instruction:
Write a Python 3 function for
yielding name value pairs for each summary in the file.

Response:
def summaries(self):
        """Yield (name, (value, value, ...)) for each summary in the file."""
        length = self.summary_length
        step = self.summary_step
        for record_number, n_summaries, summary_data in self.summary_records():
            name_data = self.read_record(record_number + 1)
            for i in range(0, int(n_summaries) * step, step):
                j = self.summary_control_struct.size + i
                name = name_data[i:i+step].strip()
                data = summary_data[j:j+length]
                values = self.summary_struct.unpack(data)
                yield name, values


Instruction:
Write a Python 3 function that can
add a new array to the DAF file.

Response:
def add_array(self, name, values, array):
        """Add a new array to the DAF file.

        The summary will be initialized with the `name` and `values`,
        and will have its start word and end word fields set to point to
        where the `array` of floats has been appended to the file.

        """
        f = self.file
        scs = self.summary_control_struct

        record_number = self.bward
        data = bytearray(self.read_record(record_number))
        next_record, previous_record, n_summaries = scs.unpack(data[:24])

        if n_summaries < self.summaries_per_record:
            summary_record = record_number
            name_record = summary_record + 1
            data[:24] = scs.pack(next_record, previous_record, n_summaries + 1)
            self.write_record(summary_record, data)
        else:
            summary_record = ((self.free - 1) * 8 + 1023) // 1024 + 1
            name_record = summary_record + 1
            free_record = summary_record + 2

            n_summaries = 0
            data[:24] = scs.pack(summary_record, previous_record, n_summaries)
            self.write_record(record_number, data)

            summaries = scs.pack(0, record_number, 1).ljust(1024, b'\0')
            names = b'\0' * 1024
            self.write_record(summary_record, summaries)
            self.write_record(name_record, names)

            self.bward = summary_record
            self.free = (free_record - 1) * 1024 // 8 + 1

        start_word = self.free
        f.seek((start_word - 1) * 8)
        array = numpy_array(array)  # TODO: force correct endian
        f.write(array.view())
        end_word = f.tell() // 8

        self.free = end_word + 1
        self.write_file_record()

        values = values[:self.nd + self.ni - 2] + (start_word, end_word)

        base = 1024 * (summary_record - 1)
        offset = int(n_summaries) * self.summary_step
        f.seek(base + scs.size + offset)
        f.write(self.summary_struct.pack(*values))
        f.seek(base + 1024 + offset)
        f.write(name[:self.summary_length].ljust(self.summary_step, b' '))


Instruction:
How would you implement a function in Python 3 that
closes this SPK file.

Response:
def close(self):
        """Close this SPK file."""
        self.daf.file.close()
        for segment in self.segments:
            if hasattr(segment, '_data'):
                del segment._data
        self.daf._array = None
        self.daf._map = None


Instruction:
Write a Python 3 function for
returning a textual description of the segment.

Response:
def describe(self, verbose=True):
        """Return a textual description of the segment."""
        center = titlecase(target_names.get(self.center, 'Unknown center'))
        target = titlecase(target_names.get(self.target, 'Unknown target'))
        text = ('{0.start_jd:.2f}..{0.end_jd:.2f}  {1} ({0.center})'
                ' -> {2} ({0.target})'.format(self, center, target))
        if verbose:
            text += ('\n  frame={0.frame} data_type={0.data_type} source={1}'
                     .format(self, self.source.decode('ascii')))
        return text


Instruction:
Create a Python 3 function for
computing the component values for the time tdb plus tdb2.

Response:
def compute(self, tdb, tdb2=0.0):
        """Compute the component values for the time `tdb` plus `tdb2`."""
        for position in self.generate(tdb, tdb2):
            return position


Instruction:
How would you explain what the following Python 3 function does
def describe(self, verbose=True):
        body = titlecase(target_names.get(self.body, 'Unknown body'))
        text = ('{0.start_jd:.2f}..{0.end_jd:.2f} frame={0.frame}'
                '  {1} ({0.body})'.format(self, body))
        if verbose:
            text += ('\n  data_type={0.data_type} source={1}'
                     .format(self, self.source.decode('ascii')))
        return text

Response: Return a textual description of the segment.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _load(self):
        if self.data_type == 2:
            component_count = 3
        else:
            raise ValueError('only binary PCK data type 2 is supported')

        init, intlen, rsize, n = self.daf.read_array(self.end_i - 3, self.end_i)
        initial_epoch = jd(init)
        interval_length = intlen / S_PER_DAY
        coefficient_count = int(rsize - 2) // component_count
        coefficients = self.daf.map_array(self.start_i, self.end_i - 4)

        coefficients.shape = (int(n), int(rsize))
        coefficients = coefficients[:,2:]  # ignore MID and RADIUS elements
        coefficients.shape = (int(n), component_count, coefficient_count)
        coefficients = rollaxis(coefficients, 1)
        return initial_epoch, interval_length, coefficients

Response: Load the PCK data into memory using a NumPy array.