text:
package ch.ninecode.model

import com.esotericsoftware.kryo.Kryo
import com.esotericsoftware.kryo.Serializer
import com.esotericsoftware.kryo.io.Input
import com.esotericsoftware.kryo.io.Output
import org.apache.spark.sql.Row

import ch.ninecode.cim.CIMClassInfo
import ch.ninecode.cim.CIMContext
import ch.ninecode.cim.CIMParseable
import ch.ninecode.cim.CIMRelationship
import ch.ninecode.cim.CIMSerializer

/**
 * Different from LimIEEEOEL, LimOEL2 has a fixed pickup threshold and reduces the excitation set-point by means of a non-windup integral regulator.
 *
 * Irated is the rated machine excitation current (calculated from nameplate conditions: Vnom, Pnom, CosPhinom).
 *
 * @param OverexcitationLimiterDynamics [[ch.ninecode.model.OverexcitationLimiterDynamics OverexcitationLimiterDynamics]] Reference to the superclass object.
 * @param ifdlim                        Limit value of rated field current (IFDLIM).
 *                                      Typical value = 1,05.
 * @param koi                           Gain Over excitation limiter (KOI).
 *                                      Typical value = 0,1.
 * @param voimax                        Maximum error signal (VOIMAX) (> OverexcLim2.voimin).
 *                                      Typical value = 0.
 * @param voimin                        Minimum error signal (VOIMIN) (< OverexcLim2.voimax).
 *                                      Typical value = -9999.
 * @group OverexcitationLimiterDynamics
 * @groupname OverexcitationLimiterDynamics Package OverexcitationLimiterDynamics
 * @groupdesc OverexcitationLimiterDynamics Overexcitation limiters (OELs) are also referred to as maximum excitation limiters and field current limiters. The possibility of voltage collapse in stressed power systems increases the importance of modelling these limiters in studies of system conditions that cause machines to operate at high levels of excitation for a sustained period, such as voltage collapse or system-islanding. Such events typically occur over a long time frame compared with transient or small-signal stability simulations.
 */
final case class OverexcLim2
(
    OverexcitationLimiterDynamics: OverexcitationLimiterDynamics = null,
    ifdlim: Double = 0.0,
    koi: Double = 0.0,
    voimax: Double = 0.0,
    voimin: Double = 0.0
)
    extends
        Element
{
    /**
     * Return the superclass object.
     *
     * @return The typed superclass nested object.
     * @group Hierarchy
     * @groupname Hierarchy Class Hierarchy Related
     * @groupdesc Hierarchy Members related to the nested hierarchy of CIM classes.
     */
    override def sup: OverexcitationLimiterDynamics = OverexcitationLimiterDynamics

    //
    // Row overrides
    //

    /**
     * Return a copy of this object as a Row.
     *
     * Creates a clone of this object for use in Row manipulations.
     *
     * @return The copy of the object.
     * @group Row
     * @groupname Row SQL Row Implementation
     * @groupdesc Row Members related to implementing the SQL Row interface
     */
    override def copy (): Row =
    {
        clone().asInstanceOf[Row]
    }

    override def export_fields: String =
    {
        implicit val s: StringBuilder = new StringBuilder(sup.export_fields)
        implicit val clz: String = OverexcLim2.cls

        def emitelem (position: Int, value: Any): Unit = if (mask(position)) emit_element(OverexcLim2.fields(position), value)

        emitelem(0, ifdlim)
        emitelem(1, koi)
        emitelem(2, voimax)
        emitelem(3, voimin)
        s.toString
    }

    override def export: String =
    {
        "\t<cim:OverexcLim2 rdf:%s=\"%s\">\n%s\t</cim:OverexcLim2>".format(if (about) "about" else "ID", id, export_fields)
    }
}

object OverexcLim2
    extends
        CIMParseable[OverexcLim2]
{
    override val fields: Array[String] = Array[String](
        "ifdlim",
        "koi",
        "voimax",
        "voimin"
    )
    val ifdlim: Fielder = parse_element(element(cls, fields(0)))
    val koi: Fielder = parse_element(element(cls, fields(1)))
    val voimax: Fielder = parse_element(element(cls, fields(2)))
    val voimin: Fielder = parse_element(element(cls, fields(3)))

    def parse (context: CIMContext): OverexcLim2 =
    {
        implicit val ctx: CIMContext = context
        implicit val bitfields: Array[Int] = Array(0)
        val ret = OverexcLim2(
            OverexcitationLimiterDynamics.parse(context),
            toDouble(mask(ifdlim(), 0)),
            toDouble(mask(koi(), 1)),
            toDouble(mask(voimax(), 2)),
            toDouble(mask(voimin(), 3))
        )
        ret.bitfields = bitfields
        ret
    }

    def serializer: Serializer[OverexcLim2] = OverexcLim2Serializer
}

object OverexcLim2Serializer extends CIMSerializer[OverexcLim2]
{
    def write (kryo: Kryo, output: Output, obj: OverexcLim2): Unit =
    {
        val toSerialize: Array[() => Unit] = Array(
            () => output.writeDouble(obj.ifdlim),
            () => output.writeDouble(obj.koi),
            () => output.writeDouble(obj.voimax),
            () => output.writeDouble(obj.voimin)
        )
        OverexcitationLimiterDynamicsSerializer.write(kryo, output, obj.sup)
        implicit val bitfields: Array[Int] = obj.bitfields
        writeBitfields(output)
        writeFields(toSerialize)
    }

    def read (kryo: Kryo, input: Input, cls: Class[OverexcLim2]): OverexcLim2 =
    {
        val parent = OverexcitationLimiterDynamicsSerializer.read(kryo, input, classOf[OverexcitationLimiterDynamics])
        implicit val bitfields: Array[Int] = readBitfields(input)
        val obj = OverexcLim2(
            parent,
            if (isSet(0)) input.readDouble else 0.0,
            if (isSet(1)) input.readDouble else 0.0,
            if (isSet(2)) input.readDouble else 0.0,
            if (isSet(3)) input.readDouble else 0.0
        )
        obj.bitfields = bitfields
        obj
    }
}

/**
 * The over excitation limiter model is intended to represent the significant features of OELs necessary for some large-scale system studies.
 *
 * It is the result of a pragmatic approach to obtain a model that can be widely applied with attainable data from generator owners. An attempt to include all variations in the functionality of OELs and duplicate how they interact with the rest of the excitation systems would likely result in a level of application insufficient for the studies for which they are intended.
 * Reference: IEEE OEL 421.5-2005, 9.
 *
 * @param OverexcitationLimiterDynamics [[ch.ninecode.model.OverexcitationLimiterDynamics OverexcitationLimiterDynamics]] Reference to the superclass object.
 * @param hyst                          OEL pickup/drop-out hysteresis (HYST).
 *                                      Typical value = 0,03.
 * @param ifdlim                        OEL timed field current limit (IFDLIM).
 *                                      Typical value = 1,05.
 * @param ifdmax                        OEL instantaneous field current limit (IFDMAX).
 *                                      Typical value = 1,5.
 * @param itfpu                         OEL timed field current limiter pickup level (ITFPU).
 *                                      Typical value = 1,05.
 * @param kcd                           OEL cooldown gain (KCD).
 *                                      Typical value = 1.
 * @param kramp                         OEL ramped limit rate (KRAMP).
 *                                      Unit = PU / s.  Typical value = 10.
 * @group OverexcitationLimiterDynamics
 * @groupname OverexcitationLimiterDynamics Package OverexcitationLimiterDynamics
 * @groupdesc OverexcitationLimiterDynamics Overexcitation limiters (OELs) are also referred to as maximum excitation limiters and field current limiters. The possibility of voltage collapse in stressed power systems increases the importance of modelling these limiters in studies of system conditions that cause machines to operate at high levels of excitation for a sustained period, such as voltage collapse or system-islanding. Such events typically occur over a long time frame compared with transient or small-signal stability simulations.
 */
final case class OverexcLimIEEE
(
    OverexcitationLimiterDynamics: OverexcitationLimiterDynamics = null,
    hyst: Double = 0.0,
    ifdlim: Double = 0.0,
    ifdmax: Double = 0.0,
    itfpu: Double = 0.0,
    kcd: Double = 0.0,
    kramp: Double = 0.0
)
    extends
        Element
{
    /**
     * Return the superclass object.
     *
     * @return The typed superclass nested object.
     * @group Hierarchy
     * @groupname Hierarchy Class Hierarchy Related
     * @groupdesc Hierarchy Members related to the nested hierarchy of CIM classes.
     */
    override def sup: OverexcitationLimiterDynamics = OverexcitationLimiterDynamics

    //
    // Row overrides
    //

    /**
     * Return a copy of this object as a Row.
     *
     * Creates a clone of this object for use in Row manipulations.
     *
     * @return The copy of the object.
     * @group Row
     * @groupname Row SQL Row Implementation
     * @groupdesc Row Members related to implementing the SQL Row interface
     */
    override def copy (): Row =
    {
        clone().asInstanceOf[Row]
    }

    override def export_fields: String =
    {
        implicit val s: StringBuilder = new StringBuilder(sup.export_fields)
        implicit val clz: String = OverexcLimIEEE.cls

        def emitelem (position: Int, value: Any): Unit = if (mask(position)) emit_element(OverexcLimIEEE.fields(position), value)

        emitelem(0, hyst)
        emitelem(1, ifdlim)
        emitelem(2, ifdmax)
        emitelem(3, itfpu)
        emitelem(4, kcd)
        emitelem(5, kramp)
        s.toString
    }

    override def export: String =
    {
        "\t<cim:OverexcLimIEEE rdf:%s=\"%s\">\n%s\t</cim:OverexcLimIEEE>".format(if (about) "about" else "ID", id, export_fields)
    }
}

object OverexcLimIEEE
    extends
        CIMParseable[OverexcLimIEEE]
{
    override val fields: Array[String] = Array[String](
        "hyst",
        "ifdlim",
        "ifdmax",
        "itfpu",
        "kcd",
        "kramp"
    )
    val hyst: Fielder = parse_element(element(cls, fields(0)))
    val ifdlim: Fielder = parse_element(element(cls, fields(1)))
    val ifdmax: Fielder = parse_element(element(cls, fields(2)))
    val itfpu: Fielder = parse_element(element(cls, fields(3)))
    val kcd: Fielder = parse_element(element(cls, fields(4)))
    val kramp: Fielder = parse_element(element(cls, fields(5)))

    def parse (context: CIMContext): OverexcLimIEEE =
    {
        implicit val ctx: CIMContext = context
        implicit val bitfields: Array[Int] = Array(0)
        val ret = OverexcLimIEEE(
            OverexcitationLimiterDynamics.parse(context),
            toDouble(mask(hyst(), 0)),
            toDouble(mask(ifdlim(), 1)),
            toDouble(mask(ifdmax(), 2)),
            toDouble(mask(itfpu(), 3)),
            toDouble(mask(kcd(), 4)),
            toDouble(mask(kramp(), 5))
        )
        ret.bitfields = bitfields
        ret
    }

    def serializer: Serializer[OverexcLimIEEE] = OverexcLimIEEESerializer
}

object OverexcLimIEEESerializer extends CIMSerializer[OverexcLimIEEE]
{
    def write (kryo: Kryo, output: Output, obj: OverexcLimIEEE): Unit =
    {
        val toSerialize: Array[() => Unit] = Array(
            () => output.writeDouble(obj.hyst),
            () => output.writeDouble(obj.ifdlim),
            () => output.writeDouble(obj.ifdmax),
            () => output.writeDouble(obj.itfpu),
            () => output.writeDouble(obj.kcd),
            () => output.writeDouble(obj.kramp)
        )
        OverexcitationLimiterDynamicsSerializer.write(kryo, output, obj.sup)
        implicit val bitfields: Array[Int] = obj.bitfields
        writeBitfields(output)
        writeFields(toSerialize)
    }

    def read (kryo: Kryo, input: Input, cls: Class[OverexcLimIEEE]): OverexcLimIEEE =
    {
        val parent = OverexcitationLimiterDynamicsSerializer.read(kryo, input, classOf[OverexcitationLimiterDynamics])
        implicit val bitfields: Array[Int] = readBitfields(input)
        val obj = OverexcLimIEEE(
            parent,
            if (isSet(0)) input.readDouble else 0.0,
            if (isSet(1)) input.readDouble else 0.0,
            if (isSet(2)) input.readDouble else 0.0,
            if (isSet(3)) input.readDouble else 0.0,
            if (isSet(4)) input.readDouble else 0.0,
            if (isSet(5)) input.readDouble else 0.0
        )
        obj.bitfields = bitfields
        obj
    }
}

/**
 * Field voltage over excitation limiter.
 *
 * @param OverexcitationLimiterDynamics [[ch.ninecode.model.OverexcitationLimiterDynamics OverexcitationLimiterDynamics]] Reference to the superclass object.
 * @param efd1                          Low voltage point on the inverse time characteristic (EFD1).
 *                                      Typical value = 1,1.
 * @param efd2                          Mid voltage point on the inverse time characteristic (EFD2).
 *                                      Typical value = 1,2.
 * @param efd3                          High voltage point on the inverse time characteristic (EFD3).
 *                                      Typical value = 1,5.
 * @param efddes                        Desired field voltage (EFDDES).
 *                                      Typical value = 0,9.
 * @param efdrated                      Rated field voltage (EFDRATED).
 *                                      Typical value = 1,05.
 * @param kmx                           Gain (KMX).
 *                                      Typical value = 0,01.
 * @param t1                            Time to trip the exciter at the low voltage point on the inverse time characteristic (TIME1) (>= 0).
 *                                      Typical value = 120.
 * @param t2                            Time to trip the exciter at the mid voltage point on the inverse time characteristic (TIME2) (>= 0).
 *                                      Typical value = 40.
 * @param t3                            Time to trip the exciter at the high voltage point on the inverse time characteristic (TIME3) (>= 0).
 *                                      Typical value = 15.
 * @param vlow                          Low voltage limit (VLOW) (> 0).
 * @group OverexcitationLimiterDynamics
 * @groupname OverexcitationLimiterDynamics Package OverexcitationLimiterDynamics
 * @groupdesc OverexcitationLimiterDynamics Overexcitation limiters (OELs) are also referred to as maximum excitation limiters and field current limiters. The possibility of voltage collapse in stressed power systems increases the importance of modelling these limiters in studies of system conditions that cause machines to operate at high levels of excitation for a sustained period, such as voltage collapse or system-islanding. Such events typically occur over a long time frame compared with transient or small-signal stability simulations.
 */
final case class OverexcLimX1
(
    OverexcitationLimiterDynamics: OverexcitationLimiterDynamics = null,
    efd1: Double = 0.0,
    efd2: Double = 0.0,
    efd3: Double = 0.0,
    efddes: Double = 0.0,
    efdrated: Double = 0.0,
    kmx: Double = 0.0,
    t1: Double = 0.0,
    t2: Double = 0.0,
    t3: Double = 0.0,
    vlow: Double = 0.0
)
    extends
        Element
{
    /**
     * Return the superclass object.
     *
     * @return The typed superclass nested object.
     * @group Hierarchy
     * @groupname Hierarchy Class Hierarchy Related
     * @groupdesc Hierarchy Members related to the nested hierarchy of CIM classes.
     */
    override def sup: OverexcitationLimiterDynamics = OverexcitationLimiterDynamics

    //
    // Row overrides
    //

    /**
     * Return a copy of this object as a Row.
     *
     * Creates a clone of this object for use in Row manipulations.
     *
     * @return The copy of the object.
     * @group Row
     * @groupname Row SQL Row Implementation
     * @groupdesc Row Members related to implementing the SQL Row interface
     */
    override def copy (): Row =
    {
        clone().asInstanceOf[Row]
    }

    override def export_fields: String =
    {
        implicit val s: StringBuilder = new StringBuilder(sup.export_fields)
        implicit val clz: String = OverexcLimX1.cls

        def emitelem (position: Int, value: Any): Unit = if (mask(position)) emit_element(OverexcLimX1.fields(position), value)

        emitelem(0, efd1)
        emitelem(1, efd2)
        emitelem(2, efd3)
        emitelem(3, efddes)
        emitelem(4, efdrated)
        emitelem(5, kmx)
        emitelem(6, t1)
        emitelem(7, t2)
        emitelem(8, t3)
        emitelem(9, vlow)
        s.toString
    }

    override def export: String =
    {
        "\t<cim:OverexcLimX1 rdf:%s=\"%s\">\n%s\t</cim:OverexcLimX1>".format(if (about) "about" else "ID", id, export_fields)
    }
}

object OverexcLimX1
    extends
        CIMParseable[OverexcLimX1]
{
    override val fields: Array[String] = Array[String](
        "efd1",
        "efd2",
        "efd3",
        "efddes",
        "efdrated",
        "kmx",
        "t1",
        "t2",
        "t3",
        "vlow"
    )
    val efd1: Fielder = parse_element(element(cls, fields(0)))
    val efd2: Fielder = parse_element(element(cls, fields(1)))
    val efd3: Fielder = parse_element(element(cls, fields(2)))
    val efddes: Fielder = parse_element(element(cls, fields(3)))
    val efdrated: Fielder = parse_element(element(cls, fields(4)))
    val kmx: Fielder = parse_element(element(cls, fields(5)))
    val t1: Fielder = parse_element(element(cls, fields(6)))
    val t2: Fielder = parse_element(element(cls, fields(7)))
    val t3: Fielder = parse_element(element(cls, fields(8)))
    val vlow: Fielder = parse_element(element(cls, fields(9)))

    def parse (context: CIMContext): OverexcLimX1 =
    {
        implicit val ctx: CIMContext = context
        implicit val bitfields: Array[Int] = Array(0)
        val ret = OverexcLimX1(
            OverexcitationLimiterDynamics.parse(context),
            toDouble(mask(efd1(), 0)),
            toDouble(mask(efd2(), 1)),
            toDouble(mask(efd3(), 2)),
            toDouble(mask(efddes(), 3)),
            toDouble(mask(efdrated(), 4)),
            toDouble(mask(kmx(), 5)),
            toDouble(mask(t1(), 6)),
            toDouble(mask(t2(), 7)),
            toDouble(mask(t3(), 8)),
            toDouble(mask(vlow(), 9))
        )
        ret.bitfields = bitfields
        ret
    }

    def serializer: Serializer[OverexcLimX1] = OverexcLimX1Serializer
}

object OverexcLimX1Serializer extends CIMSerializer[OverexcLimX1]
{
    def write (kryo: Kryo, output: Output, obj: OverexcLimX1): Unit =
    {
        val toSerialize: Array[() => Unit] = Array(
            () => output.writeDouble(obj.efd1),
            () => output.writeDouble(obj.efd2),
            () => output.writeDouble(obj.efd3),
            () => output.writeDouble(obj.efddes),
            () => output.writeDouble(obj.efdrated),
            () => output.writeDouble(obj.kmx),
            () => output.writeDouble(obj.t1),
            () => output.writeDouble(obj.t2),
            () => output.writeDouble(obj.t3),
            () => output.writeDouble(obj.vlow)
        )
        OverexcitationLimiterDynamicsSerializer.write(kryo, output, obj.sup)
        implicit val bitfields: Array[Int] = obj.bitfields
        writeBitfields(output)
        writeFields(toSerialize)
    }

    def read (kryo: Kryo, input: Input, cls: Class[OverexcLimX1]): OverexcLimX1 =
    {
        val parent = OverexcitationLimiterDynamicsSerializer.read(kryo, input, classOf[OverexcitationLimiterDynamics])
        implicit val bitfields: Array[Int] = readBitfields(input)
        val obj = OverexcLimX1(
            parent,
            if (isSet(0)) input.readDouble else 0.0,
            if (isSet(1)) input.readDouble else 0.0,
            if (isSet(2)) input.readDouble else 0.0,
            if (isSet(3)) input.readDouble else 0.0,
            if (isSet(4)) input.readDouble else 0.0,
            if (isSet(5)) input.readDouble else 0.0,
            if (isSet(6)) input.readDouble else 0.0,
            if (isSet(7)) input.readDouble else 0.0,
            if (isSet(8)) input.readDouble else 0.0,
            if (isSet(9)) input.readDouble else 0.0
        )
        obj.bitfields = bitfields
        obj
    }
}

/**
 * Field voltage or current overexcitation limiter designed to protect the generator field of an AC machine with automatic excitation control from overheating due to prolonged overexcitation.
 *
 * @param OverexcitationLimiterDynamics [[ch.ninecode.model.OverexcitationLimiterDynamics OverexcitationLimiterDynamics]] Reference to the superclass object.
 * @param efd1                          Low voltage or current point on the inverse time characteristic (EFD1).
 *                                      Typical value = 1,1.
 * @param efd2                          Mid voltage or current point on the inverse time characteristic (EFD2).
 *                                      Typical value = 1,2.
 * @param efd3                          High voltage or current point on the inverse time characteristic (EFD3).
 *                                      Typical value = 1,5.
 * @param efddes                        Desired field voltage if m = false or desired field current if m = true (EFDDES).
 *                                      Typical value = 1.
 * @param efdrated                      Rated field voltage if m = false or rated field current if m = true (EFDRATED).
 *                                      Typical value = 1,05.
 * @param kmx                           Gain (KMX).
 *                                      Typical value = 0,002.
 * @param m                             (m).
 *                                      true = IFD limiting
 *                                      false = EFD limiting.
 * @param t1                            Time to trip the exciter at the low voltage or current point on the inverse time characteristic (TIME1) (>= 0).
 *                                      Typical value = 120.
 * @param t2                            Time to trip the exciter at the mid voltage or current point on the inverse time characteristic (TIME2) (>= 0).
 *                                      Typical value = 40.
 * @param t3                            Time to trip the exciter at the high voltage or current point on the inverse time characteristic (TIME3) (>= 0).
 *                                      Typical value = 15.
 * @param vlow                          Low voltage limit (VLOW) (> 0).
 * @group OverexcitationLimiterDynamics
 * @groupname OverexcitationLimiterDynamics Package OverexcitationLimiterDynamics
 * @groupdesc OverexcitationLimiterDynamics Overexcitation limiters (OELs) are also referred to as maximum excitation limiters and field current limiters. The possibility of voltage collapse in stressed power systems increases the importance of modelling these limiters in studies of system conditions that cause machines to operate at high levels of excitation for a sustained period, such as voltage collapse or system-islanding. Such events typically occur over a long time frame compared with transient or small-signal stability simulations.
 */
final case class OverexcLimX2
(
    OverexcitationLimiterDynamics: OverexcitationLimiterDynamics = null,
    efd1: Double = 0.0,
    efd2: Double = 0.0,
    efd3: Double = 0.0,
    efddes: Double = 0.0,
    efdrated: Double = 0.0,
    kmx: Double = 0.0,
    m: Boolean = false,
    t1: Double = 0.0,
    t2: Double = 0.0,
    t3: Double = 0.0,
    vlow: Double = 0.0
)
    extends
        Element
{
    /**
     * Return the superclass object.
     *
     * @return The typed superclass nested object.
     * @group Hierarchy
     * @groupname Hierarchy Class Hierarchy Related
     * @groupdesc Hierarchy Members related to the nested hierarchy of CIM classes.
     */
    override def sup: OverexcitationLimiterDynamics = OverexcitationLimiterDynamics

    //
    // Row overrides
    //

    /**
     * Return a copy of this object as a Row.
     *
     * Creates a clone of this object for use in Row manipulations.
     *
     * @return The copy of the object.
     * @group Row
     * @groupname Row SQL Row Implementation
     * @groupdesc Row Members related to implementing the SQL Row interface
     */
    override def copy (): Row =
    {
        clone().asInstanceOf[Row]
    }

    override def export_fields: String =
    {
        implicit val s: StringBuilder = new StringBuilder(sup.export_fields)
        implicit val clz: String = OverexcLimX2.cls

        def emitelem (position: Int, value: Any): Unit = if (mask(position)) emit_element(OverexcLimX2.fields(position), value)

        emitelem(0, efd1)
        emitelem(1, efd2)
        emitelem(2, efd3)
        emitelem(3, efddes)
        emitelem(4, efdrated)
        emitelem(5, kmx)
        emitelem(6, m)
        emitelem(7, t1)
        emitelem(8, t2)
        emitelem(9, t3)
        emitelem(10, vlow)
        s.toString
    }

    override def export: String =
    {
        "\t<cim:OverexcLimX2 rdf:%s=\"%s\">\n%s\t</cim:OverexcLimX2>".format(if (about) "about" else "ID", id, export_fields)
    }
}

object OverexcLimX2
    extends
        CIMParseable[OverexcLimX2]
{
    override val fields: Array[String] = Array[String](
        "efd1",
        "efd2",
        "efd3",
        "efddes",
        "efdrated",
        "kmx",
        "m",
        "t1",
        "t2",
        "t3",
        "vlow"
    )
    val efd1: Fielder = parse_element(element(cls, fields(0)))
    val efd2: Fielder = parse_element(element(cls, fields(1)))
    val efd3: Fielder = parse_element(element(cls, fields(2)))
    val efddes: Fielder = parse_element(element(cls, fields(3)))
    val efdrated: Fielder = parse_element(element(cls, fields(4)))
    val kmx: Fielder = parse_element(element(cls, fields(5)))
    val m: Fielder = parse_element(element(cls, fields(6)))
    val t1: Fielder = parse_element(element(cls, fields(7)))
    val t2: Fielder = parse_element(element(cls, fields(8)))
    val t3: Fielder = parse_element(element(cls, fields(9)))
    val vlow: Fielder = parse_element(element(cls, fields(10)))

    def parse (context: CIMContext): OverexcLimX2 =
    {
        implicit val ctx: CIMContext = context
        implicit val bitfields: Array[Int] = Array(0)
        val ret = OverexcLimX2(
            OverexcitationLimiterDynamics.parse(context),
            toDouble(mask(efd1(), 0)),
            toDouble(mask(efd2(), 1)),
            toDouble(mask(efd3(), 2)),
            toDouble(mask(efddes(), 3)),
            toDouble(mask(efdrated(), 4)),
            toDouble(mask(kmx(), 5)),
            toBoolean(mask(m(), 6)),
            toDouble(mask(t1(), 7)),
            toDouble(mask(t2(), 8)),
            toDouble(mask(t3(), 9)),
            toDouble(mask(vlow(), 10))
        )
        ret.bitfields = bitfields
        ret
    }

    def serializer: Serializer[OverexcLimX2] = OverexcLimX2Serializer
}

object OverexcLimX2Serializer extends CIMSerializer[OverexcLimX2]
{
    def write (kryo: Kryo, output: Output, obj: OverexcLimX2): Unit =
    {
        val toSerialize: Array[() => Unit] = Array(
            () => output.writeDouble(obj.efd1),
            () => output.writeDouble(obj.efd2),
            () => output.writeDouble(obj.efd3),
            () => output.writeDouble(obj.efddes),
            () => output.writeDouble(obj.efdrated),
            () => output.writeDouble(obj.kmx),
            () => output.writeBoolean(obj.m),
            () => output.writeDouble(obj.t1),
            () => output.writeDouble(obj.t2),
            () => output.writeDouble(obj.t3),
            () => output.writeDouble(obj.vlow)
        )
        OverexcitationLimiterDynamicsSerializer.write(kryo, output, obj.sup)
        implicit val bitfields: Array[Int] = obj.bitfields
        writeBitfields(output)
        writeFields(toSerialize)
    }

    def read (kryo: Kryo, input: Input, cls: Class[OverexcLimX2]): OverexcLimX2 =
    {
        val parent = OverexcitationLimiterDynamicsSerializer.read(kryo, input, classOf[OverexcitationLimiterDynamics])
        implicit val bitfields: Array[Int] = readBitfields(input)
        val obj = OverexcLimX2(
            parent,
            if (isSet(0)) input.readDouble else 0.0,
            if (isSet(1)) input.readDouble else 0.0,
            if (isSet(2)) input.readDouble else 0.0,
            if (isSet(3)) input.readDouble else 0.0,
            if (isSet(4)) input.readDouble else 0.0,
            if (isSet(5)) input.readDouble else 0.0,
            if (isSet(6)) input.readBoolean else false,
            if (isSet(7)) input.readDouble else 0.0,
            if (isSet(8)) input.readDouble else 0.0,
            if (isSet(9)) input.readDouble else 0.0,
            if (isSet(10)) input.readDouble else 0.0
        )
        obj.bitfields = bitfields
        obj
    }
}

/**
 * Overexcitation limiter function block whose behaviour is described by reference to a standard model or by definition of a user-defined model.
 *
 * @param DynamicsFunctionBlock    [[ch.ninecode.model.DynamicsFunctionBlock DynamicsFunctionBlock]] Reference to the superclass object.
 * @param ExcitationSystemDynamics [[ch.ninecode.model.ExcitationSystemDynamics ExcitationSystemDynamics]] Excitation system model with which this overexcitation limiter model is associated.
 * @group OverexcitationLimiterDynamics
 * @groupname OverexcitationLimiterDynamics Package OverexcitationLimiterDynamics
 * @groupdesc OverexcitationLimiterDynamics Overexcitation limiters (OELs) are also referred to as maximum excitation limiters and field current limiters. The possibility of voltage collapse in stressed power systems increases the importance of modelling these limiters in studies of system conditions that cause machines to operate at high levels of excitation for a sustained period, such as voltage collapse or system-islanding. Such events typically occur over a long time frame compared with transient or small-signal stability simulations.
 */
final case class OverexcitationLimiterDynamics
(
    DynamicsFunctionBlock: DynamicsFunctionBlock = null,
    ExcitationSystemDynamics: String = null
)
    extends
        Element
{
    /**
     * Return the superclass object.
     *
     * @return The typed superclass nested object.
     * @group Hierarchy
     * @groupname Hierarchy Class Hierarchy Related
     * @groupdesc Hierarchy Members related to the nested hierarchy of CIM classes.
     */
    override def sup: DynamicsFunctionBlock = DynamicsFunctionBlock

    //
    // Row overrides
    //

    /**
     * Return a copy of this object as a Row.
     *
     * Creates a clone of this object for use in Row manipulations.
     *
     * @return The copy of the object.
     * @group Row
     * @groupname Row SQL Row Implementation
     * @groupdesc Row Members related to implementing the SQL Row interface
     */
    override def copy (): Row =
    {
        clone().asInstanceOf[Row]
    }

    override def export_fields: String =
    {
        implicit val s: StringBuilder = new StringBuilder(sup.export_fields)
        implicit val clz: String = OverexcitationLimiterDynamics.cls

        def emitattr (position: Int, value: Any): Unit = if (mask(position)) emit_attribute(OverexcitationLimiterDynamics.fields(position), value)

        emitattr(0, ExcitationSystemDynamics)
        s.toString
    }

    override def export: String =
    {
        "\t<cim:OverexcitationLimiterDynamics rdf:%s=\"%s\">\n%s\t</cim:OverexcitationLimiterDynamics>".format(if (about) "about" else "ID", id, export_fields)
    }
}

object OverexcitationLimiterDynamics
    extends
        CIMParseable[OverexcitationLimiterDynamics]
{
    override val fields: Array[String] = Array[String](
        "ExcitationSystemDynamics"
    )
    override val relations: List[CIMRelationship] = List(
        CIMRelationship("ExcitationSystemDynamics", "ExcitationSystemDynamics", "1", "0..1")
    )
    val ExcitationSystemDynamics: Fielder = parse_attribute(attribute(cls, fields(0)))

    def parse (context: CIMContext): OverexcitationLimiterDynamics =
    {
        implicit val ctx: CIMContext = context
        implicit val bitfields: Array[Int] = Array(0)
        val ret = OverexcitationLimiterDynamics(
            DynamicsFunctionBlock.parse(context),
            mask(ExcitationSystemDynamics(), 0)
        )
        ret.bitfields = bitfields
        ret
    }

    def serializer: Serializer[OverexcitationLimiterDynamics] = OverexcitationLimiterDynamicsSerializer
}

object OverexcitationLimiterDynamicsSerializer extends CIMSerializer[OverexcitationLimiterDynamics]
{
    def write (kryo: Kryo, output: Output, obj: OverexcitationLimiterDynamics): Unit =
    {
        val toSerialize: Array[() => Unit] = Array(
            () => output.writeString(obj.ExcitationSystemDynamics)
        )
        DynamicsFunctionBlockSerializer.write(kryo, output, obj.sup)
        implicit val bitfields: Array[Int] = obj.bitfields
        writeBitfields(output)
        writeFields(toSerialize)
    }

    def read (kryo: Kryo, input: Input, cls: Class[OverexcitationLimiterDynamics]): OverexcitationLimiterDynamics =
    {
        val parent = DynamicsFunctionBlockSerializer.read(kryo, input, classOf[DynamicsFunctionBlock])
        implicit val bitfields: Array[Int] = readBitfields(input)
        val obj = OverexcitationLimiterDynamics(
            parent,
            if (isSet(0)) input.readString else null
        )
        obj.bitfields = bitfields
        obj
    }
}

private[ninecode] object _OverexcitationLimiterDynamics
{
    def register: List[CIMClassInfo] =
    {
        List(
            OverexcLim2.register,
            OverexcLimIEEE.register,
            OverexcLimX1.register,
            OverexcLimX2.register,
            OverexcitationLimiterDynamics.register
        )
    }
}


text:
cd cookbook-new-design
cd bulma-generate
./build.sh
cd ..
cargo run
cd generated
open index.html
cd ../..

redpajama_set_name: RedPajamaGithub


text: call ela-service-cli.bat -usercreate -userid 1 -cardid 34526E1A12


text:
#include "zipint.h"

zip_encryption_implementation
_zip_get_encryption_implementation(zip_uint16_t em)
{
    if (em == ZIP_EM_TRAD_PKWARE)
	return zip_source_pkware;
    return NULL;
}


text:
cask "camunda-modeler" do
  version "5.0.0"
  sha256 "a847b54cd2cd457d49d20f7e63d58fc32c39b1d4149ea38c420d52de0c1549b5"

  url "https://camunda.org/release/camunda-modeler/#{version}/camunda-modeler-#{version}-mac.zip"
  name "Camunda Modeler"
  desc "Workflow and Decision Automation Platform"
  homepage "https://camunda.org/"

  livecheck do
    url "https://camunda.com/download/modeler/"
    regex(%r{href=.*?/camunda[._-]?modeler[._-]?v?(\d+(?:\.\d+)+)[._-]?mac\.zip}i)
  end

  app "Camunda Modeler.app"

  zap trash: [
    "~/Library/Application Support/camunda-modeler",
    "~/Library/Logs/Camunda Modeler",
    "~/Library/Preferences/com.camunda.CamundaModeler.plist",
    "~/Library/Saved Application State/com.camunda.CamundaModeler.savedState",
  ]
end


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef _CONTROLLER_H_
#define _CONTROLLER_H_

#include "compiler.h"

/*! \name Initialization
 */
//! \{
/*! \brief Initialization function of the controller interface.
 *
 * \param fcpu_hz CPU frequency.
 * \param fhsb_hz HSB frequency.
 * \param fpbb_hz PBB frequency.
 * \param fpba_hz PBA frequency.
 */
extern void controller_init(uint32_t fcpu_hz, uint32_t fhsb_hz, uint32_t fpbb_hz, uint32_t fpba_hz);
// \}

/*! \name is_joystick_up
 */
//! \{
/*! \brief check if up is pressed.
 *
 */
extern bool is_joystick_up(void);
// \}

/*! \name is_joystick_down
 */
//! \{
/*! \brief check if down is pressed.
 *
 */
extern bool is_joystick_down(void);
// \}

/*! \name is_joystick_right
 */
//! \{
/*! \brief check if right is pressed.
 *
 */
extern bool is_joystick_right(void);
// \}

/*! \name is_joystick_left
 */
//! \{
/*! \brief check if left is pressed.
 *
 */
bool is_joystick_left(void);
// \}

/*! \name is_joystick_pressed
 */
//! \{
/*! \brief check if pressed is pressed.
 *
 */
bool is_joystick_pressed(void);
// \}

#endif // _CONTROLLER_H_


text:
/* Fixes an issue with Bootstrap Date Picker
   @see https://github.com/angular-ui/bootstrap/issues/2659 */
var datepickerPopup = function () {
    return {
        restrict: 'EAC',
        require: 'ngModel',
        link: function(scope, element, attr, controller) {
            //remove the default formatter from the input directive to prevent conflict
            controller.$formatters.shift();
        }
    }
};

datepickerPopup.$inject = [];

export default datepickerPopup;


text:
package org.ssh.pm.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springside.modules.log.TraceUtils;
import org.ssh.pm.log.trace.Traced;

public class LogAction {
    private static final long serialVersionUID = 3331334076147567129L;
    /**
     * 在log4j.properties中,本logger已被指定使用asyncAppender.
     */
    public static final String DB_LOGGER_NAME = "DBLogExample";

//	@Override
//	public String execute() {
//		logDB();
//		logTrace();
//		logAop(1);
//		return SUCCESS;
//	}

    private void logDB() {
        Logger logger = LoggerFactory.getLogger(DB_LOGGER_NAME);
        logger.info("helloworld!!");
    }

    private void logTrace() {
        Logger logger = LoggerFactory.getLogger(LogAction.class);

        TraceUtils.beginTrace();
        logger.debug("Hello, a debug message");
        TraceUtils.endTrace();
    }

    @Traced
    private int logAop(int i) {
        return i;
    }
}


text:
    Visify

About us


text:
describe('toEqual', function() {
    // test case 1
	it('passes if computes prime of 3', function() {
		expect(findPrime(3)).toEqual([2, 3]);
    });
	// test case 2
	it('passes if computes prime of 5', function() {
		expect(findPrime(5)).toEqual([2, 3, 5]);
    });
	// test case 3
	//it('passes if computes prime of 5', function() {
	//	expect(findPrime(5)).toEqual([2, 3, 5]);
    //});
});


text:
This is an educational small JS framework. Its only purpouse is to make education of SoftUni students easier.

## Overview

The BlackBox Framework is written in ECMAScript 2016 and basically wraps up several core
functionalities, needed for the implementation of simple Single-Page Applications (SPAs).
For the Framework to be fully functional, it needs to have access to several other JavaScript
libraries. These libraries include - JQuery, JQuery noty, SammyJS. The logic that is normally
used by the combination of this libraries in order to implement a simple SPA is what BlackBox
makes easy and user-friendly.

The framework consists mainly of 4 elements:

  - **Requester**:
    * A simple AJAX requester used to wrap the request-handling code into one class
    * Defines logic for **GET**, **POST**, **PUT**, **DELETE** requests
    * Builds it's own request headers, based on a, passed as an argument, Authorization Service

  - **Authorization Service**:
    * This is a class containing functionality used mainly for authentication & authorization
    * Defines the logic needed for creating request headers and credentials
    * Builds the headers accoarding to given app credentials

  - **Notification Service**
    * Operates in the form of several functions
    * Is not wrapped in a class, due ot its need of being used globally in the whole application
    * Defines logic for **success**, **error**, **info**, **warning** popup notifications

  - **Event Service**
    * Operates in the form of several functions
    * Is not wrapped in a class, due ot its need of being used globally in the whole application
    * Defines logic for routing, triggering and handling events, and redirecting URLs

## Documentation

  - **Requester Class**:
    * *constructor* function
      * Initializes the class
      * Parameters: (authorizationService)
        * **authorizationService** - A parameter of type AuthorizationService, used to generate request headers

    * *get* function
      * Defines the logic used to initiate a **GET** request
      * Parameters: (url, successCallBack, errorCallBack)
        * **url** - A parameter of type string, defines the request url
        * **data** - A parameter of type object, holding the data in the request body
        * **successCallBack** - A parameter of type function, defines the function called on request success
        * **errorCallBack** - A parameter of type function, defines the function called on request failure

    * *post* function
      * Defines the logic used to initiate a **POST** request
      * Parameters: (url, data, successCallBack, errorCallBack)
        * **url** - A parameter of type string, defines the request url
        * **data** - A parameter of type object, holding the data in the request body
        * **successCallBack** - A parameter of type function, defines the function called on request success
        * **errorCallBack** - A parameter of type function, defines the function called on request failure

    * *put* function
      * Defines the logic used to initiate a **PUT** request
      * Parameters: (url, data, successCallBack, errorCallBack)
        * **url** - A parameter of type string, defines the request url
        * **data** - A parameter of type object, holding the data in the request body
        * **successCallBack** - A parameter of type function, defines the function called on request success
        * **errorCallBack** - A parameter of type function, defines the function called on request failure

    * *delete* function
      * Defines the logic used to initiate a **DELETE** request
      * Parameters: (url, data, successCallBack, errorCallBack)
        * **url** - A parameter of type string, defines the request url
        * **data** - A parameter of type object, holding the data in the request body
        * **successCallBack** - A parameter of type function, defines the function called on request success
        * **errorCallBack** - A parameter of type function, defines the function called on request failure

  - **AuthorizationService Class**:
    * *constructor* function
      * Initializes the class
      * Parameters: (baseServiceUrl, appKey, appSecret, guestUserCredentials)
        * **baseServiceUrl** - A parameter of type string, defines the base service url of the API
        * **appKey** - A parameter of type string, defines the appKey of the current user in the API
        * **appSecret** - A parameter of type string, defines the appSecret of the current user in the API
        * **guestUserCredentials** - A parameter of type string, defines dummy user credentials, to make
            retrieval of data possible without login

    * *initAuthorizationType* function
      * Defines the Authorization type of the session authorization
      * Parameter: (authType)
        * **authType** - A parameter of type string, specifying the Session Authorization type for the current API

    * *getCurrentUser* function
      * Gets the currently logged in user and returns it
      * Parameters: ()

    * *isLoggedIn* function
      * Returns a boolean result, defining whether there is a logged in user, or not
      * Parameters: ()

    * *getAuthorizationHeaders* function
      * Generates and returns authorization headers for requests, based on several conditions
      * Parameters: (isGuest)
        * **isGuest** - A parameter of type boolean, specifying whether or not, to user the guest credentials
          if no user has been logged in

  - **Notification Service**
    * *showPopup* function
      * Pops up a notification on the screen, of a given type, and with given text
      * Can be **success**, **error**, **info**, **warning**
      * Parameters: (type, text, position)
        * **type** - A parameter of type string, specifies the type of the popup notification
        * **text** - A parameter of type string, defines the content of the popup notification
        * **position** - A parameter of type string, defines the position of the popup notification
          if no such is given, the default is **top**

  - **Event Service**
    * *initEventServices* function
      * Initializes everything needed for the service to work. This can be done only once
      * Parameters: ()

    * *redirectUrl* function
      * Defines logic for redirecting the client to a particular page of the application
      * Parameters: (url)
        * **url** - A parameter of type string, defines the url to which the client will be redirected

    * *bindEventHandler* function
      * Defines logic for binding event handlers to a particular event
      * Parameters: (event, eventHandler)
        * **event** - A parameter of type string, defines event name to which we want ot bind a handler
        * **eventHandler** - A parameter of type function, defines the handler function which will be
            called on event trigger

    * *onRoute* function
      * Defines logic for binding handlers to a particular route
      * Parameters: (route, routeHandler)
        * **route** - A parameter of type string, defines route to which we want ot bind a handler
        * **routeHandler** - A parameter of type function, defines the handler function which will be
            called when the user is on the specified route

    * *triggerEvent* function
      * Defines logic for triggering events
      * Parameters: (event, data)
        * **event** - A parameter of type string, defines the event that is being triggered
        * **data** - A parameter of type object, defines the data that is sent with the event trigger
            to the handler

    * *run* function
      * Defines logic for running the whole application on a particular root url (route)
      * Parameters: (rootUrl)
        * **rootUrl** - A parameter of type string, defines the root url on which the application
            will run

Modules and wrapped up library logic
  * **Requester** - *JQuery*
  * **AuthorizationService** - *JQuery*
  * **NotificationService** - *JQuery Noty*
  * **EventService** - *SammyJS*

## About

This framework was created and documented by Ivaylo Jelev (Sanity) Github Alias - DCay. It is free to use under the terms and conditions of the MIT license. Criticizing and logging issues over the framework will be very helpful for the development of the framework.


text:
//////MOBILE NAVBar!/////

$(".navbar-nav li a").click(function (event) {
    // check if window is small enough so dropdown is created
    var toggle = $(".navbar-toggle").is(":visible");
    if (toggle) {
      $(".navbar-collapse").collapse('hide');
    }
  });

// $('.navbar-nav').on('click', 'li a', function() {
//     $('.navbar-collapse').collapse('hide');
//   });

/* affix the navbar after scroll below header */
$('#nav').affix({
      offset: {
        top: $('header').height()-$('#nav').height()
      }
});

/* highlight the top nav as scrolling occurs */
$('body').scrollspy({ target: '#nav' })

/* smooth scrolling for scroll to top */
$('.scroll-top').click(function(){
  $('body,html').animate({scrollTop:0},1000);
})

/* smooth scrolling for nav sections */
$('#nav .navbar-nav li>a').click(function(){
  var link = $(this).attr('href');
  var posi = $(link).offset().top;
  $('body,html').animate({scrollTop:posi},700);
});

/* ----------------------------------------------------------- */
  /*  2. Fixed Top Menubar
  /* ----------------------------------------------------------- */
jQuery(function($){

  // For fixed top bar
       $(window).scroll(function(){
        if($(window).scrollTop() >100 /*or $(window).height()*/){
            $(".navbar-fixed-top").addClass('past-main');
        }
    else{
      $(".navbar-fixed-top").removeClass('past-main');
      }
    });

$(function() {

  "use strict";

  var topoffset = 70; //variable for menu height
  var slideqty = $('#featured .item').length;
  var wheight = $(window).height(); //get the height of the window
  var randSlide = Math.floor(Math.random()*slideqty);

  $('#featured .item').eq(randSlide).addClass('active');

  $('.fullheight').css('height', wheight); //set to window tallness

$(document).ready(function(){
  $('body').scrollspy({
    target: '#navbar',
    offset: topoffset
  });
});

  // add inbody class
  var hash = $(this).find('li.active a').attr('href');
  if(hash !== '#featured') {
    $('header nav').addClass('inbody');
  } else {
    $('header nav').removeClass('inbody');
  }

  // Add an inbody class to nav when scrollspy event fires
  $('.navbar-fixed-top').on('activate.bs.scrollspy', function() {
    var hash = $(this).find('li.active a').attr('href');
    if(hash !== '#featured') {
      $('header nav').addClass('inbody');
    } else {
      $('header nav').removeClass('inbody');
    }
  });

  // Use smooth scrolling when clicking on navigation
  $('.navbar a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') ===
      this.pathname.replace(/^\//,'') &&
      location.hostname === this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top-topoffset+2
        }, 500);
        return false;
      } //target.length
    } //click function
  }); //smooth scrolling

});
});


text:
<?php

namespace Magento\CatalogImportExport\Model\Import\Product\Validator;

use Magento\Framework\Validator\AbstractValidator;
use Magento\CatalogImportExport\Model\Import\Product\RowValidatorInterface;

abstract class AbstractImportValidator extends AbstractValidator implements RowValidatorInterface
{
    /**
     * @var \Magento\CatalogImportExport\Model\Import\Product
     */
    protected $context;

    /**
     * @param \Magento\CatalogImportExport\Model\Import\Product $context
     * @return $this
     */
    public function init($context)
    {
        $this->context = $context;
        return $this;
    }
}


text:
<?php

namespace Proyecto\PrincipalBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Core\SecurityContext;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Proyecto\PrincipalBundle\Entity\User;
use Proyecto\PrincipalBundle\Entity\Espacio;
use Proyecto\PrincipalBundle\Entity\Reserva;
use Proyecto\PrincipalBundle\Entity\Confirmacion;
use Proyecto\PrincipalBundle\Entity\ConfirmacionElemento;

class EspacioController extends Controller {

	public function individualAction($id) {
		$firstArray = UtilitiesAPI::getDefaultContent($this);

        $object = $this -> getDoctrine() -> getRepository('ProyectoPrincipalBundle:Espacio') -> find($id);
        $reservas = $this -> getDoctrine() -> getRepository('ProyectoPrincipalBundle:Reserva') -> findByEspacio($object);

		$secondArray = array('object'=>$object,'reservas'=>$reservas);

		$array = array_merge($firstArray, $secondArray);
		return $this -> render('ProyectoPrincipalBundle:Espacio:individual.html.twig', $array);
	}
	public function grupalAction() {
		$firstArray = UtilitiesAPI::getDefaultContent($this);
		$secondArray = array();

		$array = array_merge($firstArray, $secondArray);
		return $this -> render('ProyectoPrincipalBundle:Espacio:grupal.html.twig', $array);
	}

	public function registrarAction(Request $request) {
		$id = null;
		$url = $this -> generateUrl('proyecto_principal_espacio_registrar');

		return EspacioController::registrarEditar($id ,$url, $request,$this);
	}
	public function editarAction(Request $request) {

		$user = UtilitiesAPI::getActiveUser($this);
		$id = $user->getId();
		$url = $this -> generateUrl('proyecto_principal_espacio_editar');

		return EspacioController::registrarEditar($id ,$url,$request, $this);

	}

	public static function registrarEditar($id ,$url,Request $request,$class) {
		if($id == null )$object = new Espacio();
		else $object = $class -> getDoctrine() -> getRepository('ProyectoPrincipalBundle:Espacio') -> find($id);

		$firstArray = UtilitiesAPI::getDefaultContent($class);
		$secondArray = array();
		$user = UtilitiesAPI::getActiveUser($class);
		$provincias = HelpersController::getProvincias($class);
		$idProvincia = $user->getProvincia()->getId();

		$parametro = $user->getProvincia()->getId();
		$object->setLocalidad($user->getLocalidad());

        $form = $class->createFormBuilder($object)
            ->add('jardineria', 'checkbox',array('required'  => false))
            ->add('propietarioEmpleado', 'checkbox',array('required'  => false))
            ->add('agenteComercial', 'checkbox',array('required'  => false))
            ->add('administradorWeb', 'checkbox',array('required'  => false))

            ->add('nombre', 'text')
            ->add('descripcionGeneral', 'textarea')
            ->add('sede1', 'entity', array(
			    'class' => 'ProyectoPrincipalBundle:Sede1',
			    'property' => 'nombre',
			    'required'  => false,
			    'query_builder' => function(EntityRepository $er) {
			        return $er->createQueryBuilder('u')
			            ->orderBy('u.nombre', 'ASC');
			    },
			))
			->add('file','file')
            ->add('enlaceVideo', 'text')

            ->add('superficie')
            ->add('anchoMinimoLibre')
            ->add('largoMinimoLibre')
            ->add('alturaMinimaLibre')
            ->add('modoAula', 'checkbox',array('required'  => false))
            ->add('modoAulaCapacidad')
            ->add('modoBanquete', 'checkbox',array('required'  => false))
            ->add('modoBanqueteCapacidad')
            ->add('modoCocktail', 'checkbox',array('required'  => false))
            ->add('modoCocktailCapacidad')
            ->add('modoEscenario', 'checkbox',array('required'  => false))
            ->add('modoEscenarioCapacidad')
            ->add('modoExposicion', 'checkbox',array('required'  => false))
            ->add('modoExposicionCapacidad')

            ->add('pilaresSueltos', 'checkbox',array('required'  => false))
            ->add('entradaAseosMovilidadReducida', 'checkbox',array('required'  => false))
            ->add('ventanasExterior', 'checkbox',array('required'  => false))
            ->add('ventanasPatioInterior', 'checkbox',array('required'  => false))
            ->add('posibilidadOscurecerSala', 'checkbox',array('required'  => false))
            ->add('otrasCaracteristicas', 'text')

            ->add('proyectorPantallaSala', 'checkbox',array('required'  => false))
            ->add('microfonoAltavoces', 'checkbox',array('required'  => false))
            ->add('videocamara', 'checkbox',array('required'  => false))
            ->add('wifi', 'checkbox',array('required'  => false))
            ->add('internetCable', 'checkbox',array('required'  => false))
            ->add('maquinaBebidas', 'checkbox',array('required'  => false))
            ->add('pizarra', 'checkbox',array('required'  => false))
            ->add('conserjeria', 'checkbox',array('required'  => false))
            ->add('aireAcondicionado', 'checkbox',array('required'  => false))
            ->add('calefaccion', 'checkbox',array('required'  => false))
            ->add('otrosServicios', 'text')

        	->add('precioPorHora','number',array('required'  => true))
            ->add('aceptacionReservaAutomatica', 'checkbox',array('required'  => false))
            ->add('tiempoMaximoAceptacionReservaAutomatica24h', 'checkbox',array('required'  => false))
            ->add('tiempoMaximoAceptacionReservaAutomatica48', 'checkbox',array('required'  => false))
            ->add('datosFacturacionPagoDelUsuario', 'checkbox',array('required'  => false))
            ->add('anadirDatosFacturacionPago', 'checkbox',array('required'  => false))
            ->add('todas', 'checkbox',array('required'  => false))
            ->add('similaresCentroRealiza', 'checkbox',array('required'  => false))
            ->add('formacionTeorica', 'checkbox',array('required'  => false))
            ->add('formacionInformatica', 'checkbox',array('required'  => false))
            ->add('formacionTaller', 'checkbox',array('required'  => false))
            ->add('exposicion', 'checkbox',array('required'  => false))
            ->add('ventaFeria', 'checkbox',array('required'  => false))
            ->add('deporte', 'checkbox',array('required'  => false))
            ->add('espectaculo', 'checkbox',array('required'  => false))
            ->add('reunionAsamblea', 'checkbox',array('required'  => false))
            ->add('boda', 'checkbox',array('required'  => false))
            ->add('fiesta', 'checkbox',array('required'  => false))

            ->add('aceptoCondicionesUsoPoliticaPrivacidad', 'checkbox',array('required'  => false))

            ->add('localidad', 'entity', array(
			    'class' => 'ProyectoPrincipalBundle:Localidad',
			    'property' => 'nombre',
			    'query_builder' => function(EntityRepository $er)use ( $parametro ) {

			        return $er->createQueryBuilder('u')
			            ->add('where', 'u.provincia = ?1')
			            ->orderBy('u.nombre', 'ASC')
			            ->setParameter(1, $parametro); // Sustituye ?1 por 100
			    },

			))

            ->getForm();

	    if ($request->isMethod('POST')) {

        	$form->bind($request);

        	if ($form->isValid()) {

	        	$em = $class->getDoctrine()->getManager();

				if($id == null) {
					$object -> setFechaRegistro(new \DateTime());
				}

				//Casos especiales
				if($object->getEnlaceVideo()=='Añadir enlace a Video') $object->setEnlaceVideo(null);
				if($object->getOtrasCaracteristicas()=='Otros...') $object->setOtrasCaracteristicas(null);
				if($object->getOtrosServicios()=='Otros...') $object->setOtrosServicios(null);

				$object -> setUser($user);

    			$em->persist($object);
				$em->flush();

				return $class->redirect($class->generateUrl('proyecto_principal_homepage'));

    		}

	    }

        $secondArray = array('form' => $form->createView(),'url'=>$url,'idProvincia'=>$idProvincia,'provincias'=>$provincias);
		$array = array_merge($firstArray, $secondArray);
		return $class -> render('ProyectoPrincipalBundle:Espacio:registrarEditar.html.twig', $array);
	}
    public function destacadosAction($numResults)
    {
        $arreglo = array();

        $em = $this->getDoctrine()->getManager();

        $dql =  'SELECT o1.id,o1.nombre,o1.path, o1.superficie,o1.precioPorHora,o2.nombre localidad
                 FROM ProyectoPrincipalBundle:Espacio o1, ProyectoPrincipalBundle:Localidad o2 WHERE o1.localidad = o2.id ORDER BY o1.id ASC';

        $query = $em->createQuery( $dql )
                ->setMaxResults($numResults)
               ->setFirstResult(10);

        $arreglo['destacados'] = $query->getResult();

        return $this->render('ProyectoPrincipalBundle:Espacio:destacados.html.twig', $arreglo);
    }
    public function widgetAction($titulo,$numResults,$paginacion,$proveedor,$cliente,$idRelacionado)
    {
		$arreglo = array();

        $em = $this->getDoctrine()->getManager();

        if($paginacion==1)$paginacion = true;
        else $paginacion = false;
        $arreglo = EspacioController::consultaBusqueda($numResults,0,null,$paginacion,$proveedor,$cliente,$idRelacionado);

        $dql =  'SELECT COUNT(o1.id) c,o2.id,o2.nombre
                 FROM ProyectoPrincipalBundle:Espacio o1,
                      ProyectoPrincipalBundle:Localidad o2
                 WHERE o1.localidad = o2.id

        GROUP BY  o1.localidad order by c  desc';

        $query = $em->createQuery( $dql );
        $arreglo['localidades'] = $query->getResult();

        $fechaActual = UtilitiesAPI::obtenerFechaNormal($this);
        $arreglo['disponibilidad'][0] = array(  'valor'=> $fechaActual, 'dia'=> UtilitiesAPI::obtenerNombreDia($fechaActual,$this));

        for ($i=1; $i <= 6; $i++) {
            $nuevaFecha = UtilitiesAPI::sumarTiempo($arreglo['disponibilidad'][$i-1]['valor'], 1, 0, 0, $this);
             $arreglo['disponibilidad'][$i] =   array(
                'valor'=> $nuevaFecha,
                'dia'  =>UtilitiesAPI::obtenerNombreDia( $nuevaFecha,$this)
                                                      );
        }
        $arreglo['proveedor']= $proveedor;
        $arreglo['cliente']= $cliente;
        $arreglo['idRelacionado']= $idRelacionado;
        $arreglo['titulo']= $titulo;
        $arreglo['numResults']= $numResults;

        return $this->render('ProyectoPrincipalBundle:Espacio:widget.html.twig', $arreglo);
    }

    public function busquedaAction() {

        $peticion = $this -> getRequest();
        $doctrine = $this -> getDoctrine();
        $post = $peticion -> request;
        $em = $this->getDoctrine()->getManager();

        $precioHora = intval($post -> get("precio"));
        $actividades = trim($post -> get("actividades"));
        $disponibilidad = trim($post -> get("disponibilidad"));
        $superficie = intval($post -> get("superficie"));
        $modo = trim($post -> get("modo"));
        $localidad = intval($post -> get("localidad"));
        $paginacion = intval($post -> get("paginacion"));

        $numResults = intval($post -> get("numResults"));
        $indice = intval($post -> get("indice"));

        if($paginacion==1)$paginacion = true;
        else $paginacion = false;

        $proveedor = intval($post -> get("proveedor"));
        $cliente = intval($post -> get("cliente"));
        $idRelacionado = intval($post -> get("idRelacionado"));

        if($proveedor==0)$proveedor = false;
        if($cliente==0)$cliente = false;

        $parametros = array('precioHora'=>$precioHora,'actividades'=>$actividades,'superficie'=>$superficie,'modo'=>$modo,'localidad'=>$localidad, 'disponibilidad'=>$disponibilidad);

        $arreglo = EspacioController::consultaBusqueda($numResults,$indice,$parametros,$paginacion,$proveedor,$cliente,$idRelacionado);

        $htmlElementos = $this -> renderView('ProyectoPrincipalBundle:Espacio:elementos.html.twig', array('elementos'=>$arreglo['elementos']) );
        $htmlPaginacion = $this -> renderView('ProyectoPrincipalBundle:Espacio:paginacion.html.twig', array('dataPaginacion'=>$arreglo['dataPaginacion']));

        $respuesta = new response(json_encode(array('htmlElementos' => $htmlElementos,'htmlPaginacion' =>$htmlPaginacion)));
        $respuesta -> headers -> set('content_type', 'aplication/json');
        return $respuesta;
    }
    public function consultaBusqueda($numResults,$indice,$parametros,$paginacion,$proveedor,$cliente,$idRelacionado){

    $em = $this->getDoctrine()->getManager();
    $array = array();

    $dql =  'SELECT DISTINCT  o1.id,o1.nombre,o1.path, o1.superficie,o1.precioPorHora,o2.nombre localidad
                 FROM ProyectoPrincipalBundle:Espacio o1, ProyectoPrincipalBundle:Localidad o2 ';

    $dqlTotales =  'SELECT DISTINCT COUNT(DISTINCT o1.id) FROM ProyectoPrincipalBundle:Espacio o1 ';

    if($proveedor){
        $dql.= ', ProyectoPrincipalBundle:User o3 ';
        $dqlTotales .=  ', ProyectoPrincipalBundle:User o3 ';
    }

    $modoA = "";
    $modoB = "";
    $tieneWhere = false;
    $tieneWhereTotales = false;
    $fechaInicio = '';
    $fechaFin = '';

    if($parametros!=null){

        if($parametros['actividades']!= null && $parametros['actividades']!='0'){

            if(!$tieneWhere){$dql.= ' WHERE ';$tieneWhere= true; }else $dql.= ' AND ';
            if(!$tieneWhereTotales){$dqlTotales.= ' WHERE ';$tieneWhereTotales= true; }else $dqlTotales.= ' AND ';

            $dql.= ' o1.'.$parametros['actividades'].' = :actividades';
            $dqlTotales.= ' o1.'.$parametros['actividades'].' = :actividades';

        }
        if($parametros['precioHora']!= null && $parametros['precioHora']!=0){

            if(!$tieneWhere){$dql.= ' WHERE ';$tieneWhere= true; }else $dql.= ' AND ';
            if(!$tieneWhereTotales){$dqlTotales.= ' WHERE ';$tieneWhereTotales= true; }else $dqlTotales.= ' AND ';

            if($parametros['precioHora']>1 && $parametros['precioHora']<=10000){
                $dql.= ' o1.precioPorHora <= :precioHora';
                $dqlTotales.= ' o1.precioPorHora <= :precioHora';
            }
            else if($parametros['precioHora']>10000){
                $dql.= ' o1.precioPorHora > :precioHora';
                $dqlTotales.=' o1.precioPorHora > :precioHora';
            }

        }
        if($parametros['superficie']!= null && $parametros['superficie']!=0){

            if(!$tieneWhere){$dql.= ' WHERE ';$tieneWhere= true; }else $dql.= ' AND ';
            if(!$tieneWhereTotales){$dqlTotales.= ' WHERE ';$tieneWhereTotales= true; }else $dqlTotales.= ' AND ';

            if($parametros['superficie']>2000){
                $dql.= ' o1.superficie > :superficie';
                $dqlTotales.=' o1.superficie > :superficie';
            }
            else{
                $dql.= ' o1.superficie <= :superficie';
                $dqlTotales.= ' o1.superficie <= :superficie';
            }

        }
        if($parametros['modo']!= null && $parametros['modo']!='0-0'){

            if(!$tieneWhere){$dql.= ' WHERE ';$tieneWhere= true; }else $dql.= ' AND ';
            if(!$tieneWhereTotales){$dqlTotales.= ' WHERE ';$tieneWhereTotales= true; }else $dqlTotales.= ' AND ';

            $modoA = explode('-', $parametros['modo']);
            $modoB = intval($modoA[1]);
            $modoA = $modoA[0];

            $dql.= ' o1.'.$modoA.' >= :modoA ';
            $dqlTotales.= ' o1.'.$modoA.' >= :modoA ';

            if($modoB != 0){

            if(!$tieneWhere){$dql.= ' WHERE ';$tieneWhere= true; }else $dql.= ' AND ';
            if(!$tieneWhereTotales){$dqlTotales.= ' WHERE ';$tieneWhereTotales= true; }else $dqlTotales.= ' AND ';

                if( $modoB==101){
                    $dql.= ' o1.'.$modoA.'Capacidad >= :modoB';
                    $dqlTotales.= ' o1.'.$modoA.'Capacidad >= :modoB';
                }
                else{
                    $dql.= ' o1.'.$modoA.'Capacidad <= :modoB';
                    $dqlTotales.= ' o1.'.$modoA.'Capacidad <= :modoB';
                }
            }
        }
        if($parametros['localidad']!= null && $parametros['localidad']!=0){

            if(!$tieneWhere){$dql.= ' WHERE ';$tieneWhere= true; }else $dql.= ' AND ';
            if(!$tieneWhereTotales){$dqlTotales.= ' WHERE ';$tieneWhereTotales= true; }else $dqlTotales.= ' AND ';

            $dql.= ' o1.localidad = :localidad';
            $dqlTotales.=' o1.localidad = :localidad';

        }
        if($parametros['disponibilidad']!= null && $parametros['disponibilidad']!=0){

            if(!$tieneWhere){$dql.= ' WHERE ';$tieneWhere= true; }else $dql.= ' AND ';
            if(!$tieneWhereTotales){$dqlTotales.= ' WHERE ';$tieneWhereTotales= true; }else $dqlTotales.= ' AND ';

            $auxiliar =  explode(' ', $parametros['disponibilidad']);
            $auxiliarFecha = explode('/', $auxiliar[0]);
            $dia =  $auxiliarFecha[0];
            $mes =  $auxiliarFecha[1];
            $anio =  $auxiliarFecha[2];
            $auxiliarHora = null;

            if(count($auxiliar)==1){
               $fechaInicio = $anio.'-'.$mes.'-'.$dia;
               $fechaFin = $anio.'-'.$mes.'-'.$dia;
               $fechaInicio .= ' 00:00:00';
               $fechaFin .= ' 23:59:59';
            }
            else{
               $fechaInicio = $anio.'-'.$mes.'-'.$dia;
               $fechaFin = $anio.'-'.$mes.'-';
               $auxiliarHora = explode('/', $auxiliar[1]);
               $fechaFin .= ($auxiliarHora[1]=='08') ? (intval($dia)+1) : $dia;
               $fechaInicio .= ' '.$auxiliarHora[0].':00:00';
               $fechaFin .= ' '.$auxiliarHora[1].':00:00';
            }
            $dql.= ' o1.id NOT IN ( SELECT DISTINCT s1.id FROM ProyectoPrincipalBundle:Espacio s1, ProyectoPrincipalBundle:Reserva s3 WHERE s1.id = s3.espacio and s3.fechaInicio BETWEEN  :fechaInicio AND :fechaFin  or  s3.fechaFin BETWEEN  :fechaInicio AND :fechaFin AND s1.id = s3.espacio ) ';
            $dqlTotales.= ' o1.id NOT IN ( SELECT DISTINCT s1.id FROM ProyectoPrincipalBundle:Espacio s1, ProyectoPrincipalBundle:Reserva s3 WHERE s1.id = s3.espacio and s3.fechaInicio BETWEEN  :fechaInicio AND :fechaFin or s3.fechaFin BETWEEN  :fechaInicio AND :fechaFin AND s1.id = s3.espacio  ) ';

        }
    }

    if(!$tieneWhere){$dql.= ' WHERE ';$tieneWhere= true; }else $dql.= ' AND ';
    $dql.= ' o1.localidad = o2.id ';

    if($proveedor){
        if(!$tieneWhere){$dql.= ' WHERE ';$tieneWhere= true; }else $dql.= ' AND ';
        $dql.= ' o1.user = o3.id and o3.id = :idRelacionado ';

        if(!$tieneWhereTotales){$dqlTotales.= ' WHERE ';$tieneWhereTotales= true; }else $dqlTotales.= ' AND ';
        $dqlTotales .=  ' o1.user = o3.id and o3.id = :idRelacionado ';
    }

    if($cliente){
        if(!$tieneWhere){$dql.= ' WHERE ';$tieneWhere= true; }else $dql.= ' AND ';
        $dql.= ' o1.id IN ( SELECT DISTINCT r2.id FROM ProyectoPrincipalBundle:Reserva r1,
            ProyectoPrincipalBundle:Espacio r2, ProyectoPrincipalBundle:User r3 WHERE r1.espacio = r2.id and r1.user = r3.id and r3.id = :idRelacionado ) ';

        if(!$tieneWhereTotales){$dqlTotales.= ' WHERE ';$tieneWhereTotales= true; }else $dqlTotales.= ' AND ';
        $dqlTotales .=  ' o1.id IN ( SELECT DISTINCT r2.id FROM ProyectoPrincipalBundle:Reserva r1,
            ProyectoPrincipalBundle:Espacio r2, ProyectoPrincipalBundle:User r3 WHERE r1.espacio = r2.id and r1.user = r3.id and r3.id = :idRelacionado ) ';

    }

    $dql.= ' ORDER BY o1.id ASC';

        $query = $em->createQuery( $dql )
        ->setMaxResults($numResults)
        ->setFirstResult($indice*$numResults);

        if($parametros['disponibilidad']!= null && $parametros['disponibilidad']!='0'){
            $query->setParameter('fechaInicio', $fechaInicio);
            $query->setParameter('fechaFin', $fechaFin);
        }
        if($parametros['actividades']!= null && $parametros['actividades']!='0') $query->setParameter('actividades', 1);
        if($parametros['precioHora']!= null && $parametros['precioHora']!=0)  $query->setParameter('precioHora', $parametros['precioHora']);
        if($parametros['superficie']!= null && $parametros['superficie']!=0)  $query->setParameter('superficie', $parametros['superficie']);
        if($parametros['modo']!= null && $parametros['modo']!='0-0'){
           $query->setParameter('modoA', 1);
           if($modoB != 0)$query->setParameter('modoB', $modoB);
        }
        if($parametros['localidad']!= null && $parametros['localidad']!=0) $query->setParameter('localidad', $parametros['localidad']);
        if($proveedor || $cliente)$query->setParameter('idRelacionado', $idRelacionado);

        $array['elementos'] = $query->getResult();
        $array['dataPaginacion']['obtenidos'] = count( $array['elementos']);

        $query = $em->createQuery( $dqlTotales );

        if($parametros['disponibilidad']!= null && $parametros['disponibilidad']!='0'){
            $query->setParameter('fechaInicio', $fechaInicio);
            $query->setParameter('fechaFin', $fechaFin);
        }
        if($parametros['actividades']!= null && $parametros['actividades']!='0') $query->setParameter('actividades', 1);
        if($parametros['precioHora']!= null && $parametros['precioHora']!=0)  $query->setParameter('precioHora', $parametros['precioHora']);
        if($parametros['superficie']!= null && $parametros['superficie']!=0)  $query->setParameter('superficie', $parametros['superficie']);
        if($parametros['modo']!= null && $parametros['modo']!='0-0'){
           $query->setParameter('modoA', 1);
           if($modoB != 0)$query->setParameter('modoB', $modoB);
        }
        if($parametros['localidad']!= null && $parametros['localidad']!=0) $query->setParameter('localidad', $parametros['localidad']);
        if($proveedor || $cliente)$query->setParameter('idRelacionado', $idRelacionado);

        $array['dataPaginacion']['total'] = intval($query->getSingleScalarResult());

        $array['dataPaginacion']['paginacion'] = $paginacion;
        $array['dataPaginacion']['numPaginacion'] = ceil($array['dataPaginacion']['total'] / $numResults);
        $array['dataPaginacion']['numResults'] = $numResults;

        return $array;
    }
    public function reservaAction($id) {
        $firstArray = UtilitiesAPI::getDefaultContent($this);

        $object = $this -> getDoctrine() -> getRepository('ProyectoPrincipalBundle:Espacio') -> find($id);
        $reservas = $this -> getDoctrine() -> getRepository('ProyectoPrincipalBundle:Reserva') -> findByEspacio($object);

        $user = UtilitiesAPI::getActiveUser($this);
        $idUser = $user->getId();
        $em = $this->getDoctrine()->getManager();

        $dql =  'SELECT COUNT(o1.id)
                 FROM ProyectoPrincipalBundle:Reserva o1,
                      ProyectoPrincipalBundle:Espacio o2
                 WHERE o1.espacio = o2.id AND
                       o1.user = :idUser AND
                       o2.id = :id AND
                       o1.cancelado = :cancelado AND
                       o1.pagado = :pagado
                       ';

        $query = $em->createQuery( $dql );
        $query->setParameter('idUser', $idUser);
        $query->setParameter('id', $id);
        $query->setParameter('cancelado', false);
        $query->setParameter('pagado', false);
        $numeroReservacion = intval($query->getSingleScalarResult()) + 1;

        $secondArray = array('object'=>$object,'usuario'=>UtilitiesAPI::getActiveUser($this),'numeroReservacion'=>$numeroReservacion,'reservas'=>$reservas);

        $array = array_merge($firstArray, $secondArray);

        return $this -> render('ProyectoPrincipalBundle:Espacio:reserva.html.twig', $array);
    }

    public function confirmacionAction($id){

        $em = $this->getDoctrine()->getManager();

        $firstArray = UtilitiesAPI::getDefaultContent($this);
        $object = $this -> getDoctrine() -> getRepository('ProyectoPrincipalBundle:Espacio') -> find($id);

        $user = UtilitiesAPI::getActiveUser($this);
        $idUser = $user->getId();

        $dql =  'SELECT o1.id,o1.fechaInicio, o1.fechaFin, o2.precioPorHora
                 FROM ProyectoPrincipalBundle:Reserva o1,
                      ProyectoPrincipalBundle:Espacio o2
                 WHERE o1.espacio = o2.id AND
                       o1.user = :idUser AND
                       o2.id = :id AND
                       o1.cancelado = :cancelado AND
                       o1.pagado = :pagado
                       ';

        $query = $em->createQuery( $dql );
        $query->setParameter('idUser', $idUser);
        $query->setParameter('id', $id);
        $query->setParameter('cancelado', false);
        $query->setParameter('pagado', false);
        $reservas = $query->getResult();

        $data = array();
        $total = array('horas'=>0,'precio'=>0);

        for ($i=0; $i < count($reservas) ; $i++) {
            # code...
            $data[$i]['id']= $reservas[$i]['id'];
            $data[$i]['fecha']= $reservas[$i]['fechaInicio']->format('d/m/Y');
            $data[$i]['horaComienzo']= $reservas[$i]['fechaInicio']->format('H:i');
            $data[$i]['horaFinalización']= $reservas[$i]['fechaFin']->format('H:i');
            $data[$i]['horas'] = intval($reservas[$i]['fechaFin']->format('H')) - intval($reservas[$i]['fechaInicio']->format('H'));

            if(intval($reservas[$i]['fechaInicio']->format('i'))!=0 || intval($reservas[$i]['fechaFin']->format('i'))!=0  ){
               $data[$i]['horas'] = $data[$i]['horas'] +1;
            }

            if($data[$i]['horas']==0)$data[$i]['horas']=24;

            $total['horas'] += $data[$i]['horas'];

            $data[$i]['precio'] = $data[$i]['horas'] * $reservas[$i]['precioPorHora'];

            $total['precio'] += $data[$i]['precio'];

        }

        $secondArray = array('object'=>$object,'reservas'=>$reservas,'data'=>$data,'total'=>$total);

        $array = array_merge($firstArray, $secondArray);

        return $this -> render('ProyectoPrincipalBundle:Espacio:confirmacion.html.twig', $array);
    }

}


text:
module BoardSpecHelper

  def create_board_scenario
    @user = create(:user)
  end

  def user_has_board_scenario
    @user = create(:user)
    @board = create(:board)
    @user_board = create(:user_board, {
                           user_id: @user.id,
                           board_id: @board.id,
                           is_admin: true,
    })
    @post = create(:post, {
                     user_id: @user.id,
                     board_id: @board.id
    })
    @comment = create(:comment, {
                        user_id: @user.id,
                        post_id: @post.id
    })
  end

  def user_has_shared_board_scenario
    user_has_board_scenario
    @user_2 = create(:user)

    @shared_board = create(:board)
    @shared_user_board_1 = create(:user_board, {
                                    user_id: @user.id,
                                    board_id: @shared_board.id,
                                    is_admin: true
    })
    @shared_user_board_2 = create(:user_board, {
                                    user_id: @user_2.id,
                                    board_id: @shared_board.id,
                                    is_admin: false
    })

    @shared_post = create(:post, {
                            user_id: @user.id,
                            board_id: @shared_board.id
    })
    @shared_comment = create(:comment, {
                               user_id: @user.id,
                               post_id: @shared_post.id
    })
  end

  def user_has_shared_board_with_posts_scenario
    user_has_shared_board_scenario

    @shared_post_2 = create(:post, {
                              user_id: @user_2.id,
                              board_id: @shared_board.id
    })

    @shared_comment_2 = create(:comment, {
                                 user_id: @user_2.id,
                                 post_id: @shared_post_2.id
    })

    @shared_comment_3 = create(:comment, {
                                 user_id: @user.id,
                                 post_id: @shared_post_2.id
    })
  end

  def user_is_sharing_a_board_scenario
    @user = create(:user)
    @user_2 = create(:user)
    @user_3 = create(:user)
    @user_4 = create(:user)
    @board = create(:board)

    @user_board = create(:user_board, {
                           is_admin: true,
                           user_id: @user.id,
                           board_id: @board.id
    })
    @post = create(:post, {
                     user_id: @user.id,
                     board_id: @board.id
    })
    @post_2 = create(:post, {
                       user_id: @user_2.id,
                       board_id: @board.id
    })
    @comment = create(:comment, {
                        user_id: @user.id,
                        post_id: @post.id,
    })
    @comment_2 = create(:comment, {
                          user_id: @user_2.id,
                          post_id: @post.id,
    })

    @payload = make_payload

    @payload_wo_comments = make_payload(comments: false)

    @payload_wo_posts = make_payload(:posts => false)
    @payload_wo_encrypted_password = make_payload(encrypted_password: false)
    @payload_wo_shared_user_ids = make_payload(shared_user_ids: false)
    @payload_w_invalid_post = make_payload[:posts] = [@post_2.attributes]
    @payload_w_invalid_comment = make_payload[:posts][0][:comments] = [@comment_2.attributes]

  end

  def make_payload(opts_hash = {})
    payload = {
      board: @board.attributes
    }
    post_hash = @post.attributes
    post_hash["title"] = Faker::Name.title
    post_hash["content"] = Faker::Hacker.say_something_smart

    comment_hash = @comment.attributes
    comment_hash["content"] = Faker::Hacker.say_something_smart

    payload[:posts] = [post_hash] if !(opts_hash[:posts] == false) || !(opts_hash[:comments] == false)
    payload[:posts][0][:comments] = [comment_hash] if !(opts_hash[:comments] == false)
    payload[:shared_user_ids] = [@user_2.id, @user_3.id, @user_4.id] if !(opts_hash[:shared_user_ids] == false)
    payload[:encrypted_password] = Faker::Crypto.md5 if !(opts_hash[:encrypted_password] == false)
    payload
  end

  def boards_pagination_scenario

    @user = create(:user)
    @num_boards = 15
    @num_my_shared_boards = 17

    @num_boards.times do
      board = create(:board)
      create(:user_board, {
               user_id: @user.id,
               board_id: board.id,
               is_admin: true,
               encrypted_password: Faker::Crypto.md5
      })
    end

    @num_my_shared_boards.times do

      shared_board = create(:board, {
                              is_shared: true
      })

      create(:user_board, {
               user_id: @user.id,
               board_id: shared_board.id,
               is_admin: true,
               encrypted_password: Faker::Crypto.md5
      })
    end

  end

  def user_has_many_posts_scenario
    user_has_board_scenario
    @num_posts = 35

    @num_posts.times do

      create(:post, {
               user_id: @user.id,
               board_id: @board.id
      })
    end

    @num_posts = @board.posts.count
  end

  def post_has_many_comments_scenario
    user_has_board_scenario
    @num_comments = 35

    @num_comments.times do

      create(:comment, {
               user_id: @user.id,
               post_id: @post.id
      })
    end

    @num_comments = @post.comments.count
  end

end

# include to spec env
RSpec.configure do |config|
  config.include BoardSpecHelper
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Plywood.Utils;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Reflection;
using System.Xml;

namespace Plywood
{
    public class Instance
    {
        #region Constructors

        public Instance()
        {
            Key = Guid.NewGuid();
            Name = "New Instance " + DateTime.UtcNow.ToString("r");
            Tags = new Dictionary<string, string>();
        }

        public Instance(string source)
            : this(Instance.Parse(source)) { }

        public Instance(Stream source)
            : this(Instance.Parse(source)) { }

        public Instance(TextReader source)
            : this(Instance.Parse(source)) { }

        public Instance(XmlTextReader source)
            : this(Instance.Parse(source)) { }

        private Instance(Instance other)
        {
            this.Key = other.Key;
            this.GroupKey = other.GroupKey;
            this.TargetKey = other.TargetKey;
            this.Name = other.Name;
            this.Tags = other.Tags;
        }

        #endregion

        public Guid Key { get; set; }
        public Guid GroupKey { get; set; }
        public Guid TargetKey { get; set; }
        public string Name { get; set; }
        public Dictionary<string, string> Tags { get; set; }

        public Stream Serialise()
        {
            return Instance.Serialise(this);
        }

        #region Static Serialisation Methods

        public static Stream Serialise(Instance instance)
        {
            if (instance == null)
                throw new ArgumentNullException("version", "Version cannot be null.");
            if (!Validation.IsNameValid(instance.Name))
                throw new ArgumentException("Name must be valid (not blank & only a single line).");

            var doc = new XDocument(
                new XDeclaration("1.0", "UTF-8", "yes"),
                new XElement("instance",
                    new XAttribute("key", instance.Key),
                    new XElement("groupKey", instance.GroupKey),
                    new XElement("targetKey", instance.TargetKey),
                    new XElement("name", instance.Name),
                    new XElement("tags")));

            if (instance.Tags != null && instance.Tags.Count > 0)
            {
                doc.Root.Element("tags").Add(
                    instance.Tags.Select(t =>
                        new XElement("tag",
                            new XAttribute("key", t.Key),
                            t.Value
                            )));
            }

            return Serialisation.Serialise(doc);
        }

        public static Instance Parse(string source)
        {
            return Parse(new StringReader(source));
        }

        public static Instance Parse(Stream source)
        {
            return Parse(new XmlTextReader(source));
        }

        public static Instance Parse(TextReader source)
        {
            return Parse(new XmlTextReader(source));
        }

        public static Instance Parse(XmlReader source)
        {
            XDocument doc;
            try
            {
                doc = XDocument.Load(source);
            }
            catch (Exception ex)
            {
                throw new DeserialisationException("Failed deserialising instance.", ex);
            }

            if (!ValidateInstanceXml(doc))
                throw new DeserialisationException("Serialised instance xml is not valid.");

            Guid key, groupKey, targetKey;

            if (!Guid.TryParse(doc.Root.Attribute("key").Value, out key))
                throw new DeserialisationException("Serialised instance key is not a valid guid.");
            if (!Guid.TryParse(doc.Root.Element("groupKey").Value, out groupKey))
                throw new DeserialisationException("Serialised instance group key is not a valid guid.");
            if (!Guid.TryParse(doc.Root.Element("targetKey").Value, out targetKey))
                throw new DeserialisationException("Serialised instance target key is not a valid guid.");

            var instance = new Instance()
            {
                Key = key,
                GroupKey = groupKey,
                TargetKey = targetKey,
                Name = doc.Root.Element("name").Value,
            };

            var tagsElement = doc.Root.Element("tags");
            if (tagsElement != null && tagsElement.HasElements)
            {
                instance.Tags = tagsElement.Elements("tag").ToDictionary(t => t.Attribute("key").Value, t => t.Value);
            }
            else
            {
                instance.Tags = new Dictionary<string, string>();
            }

            return instance;
        }

        public static bool ValidateInstanceXml(XDocument targetDoc)
        {
            bool valid = true;
            targetDoc.Validate(Schemas, (o, e) =>
            {
                valid = false;
            });
            return valid;
        }

        public static XmlSchemaSet Schemas
        {
            get
            {
                if (schemas == null)
                {
                    lock (schemasLock)
                    {
                        if (schemas == null)
                        {
                            var newSchemas = new XmlSchemaSet();
                            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Plywood.Schemas.Instance.xsd"))
                            {
                                newSchemas.Add("", XmlReader.Create(stream));
                            }
                            schemas = newSchemas;
                        }
                    }
                }
                return schemas;
            }
        }

        private static XmlSchemaSet schemas;
        private static object schemasLock = new object();

        #endregion

    }

    public class InstanceList
    {
        public Guid TargetKey { get; set; }
        public IEnumerable<InstanceListItem> Instances { get; set; }
        public string Query { get; set; }
        public int Offset { get; set; }
        public int PageSize { get; set; }
        public int TotalCount { get; set; }
    }

    public class InstanceListItem
    {
        public Guid Key { get; set; }
        public string Name { get; set; }
    }
}


text:
require_relative 'DutObj'
require 'singleton'
require 'forwardable'

class ThermalSiteDevices
    include Singleton

    attr_accessor :dBase_

    def etsEnaBit(ct)
        if 8<= ct && ct <= 15
            ct -= 8
        elsif 16 <= ct && ct <= 23
            ct -= 16
        end

        if 0<=ct && ct <=7
            case ct
            when 7
                return GPIO2::X9_ETS7
            when 6
                return GPIO2::X9_ETS6
            when 5
                return GPIO2::X9_ETS5
            when 4
                return GPIO2::X9_ETS4
            when 3
                return GPIO2::X9_ETS3
            when 2
                return GPIO2::X9_ETS2
            when 1
                return GPIO2::X9_ETS1
            when 0
                return GPIO2::X9_ETS0
            end
        end
    end

    def setTcuToRunMode(tcusToSkipParam,gPIO2Param)
        # Turn on the control for TCUs that are not disabled.
        SharedLib.bbbLog "Turning on controllers.  #{__LINE__}-#{__FILE__}"
        ct = 0
        while ct<24 do
            if tcusToSkipParam[ct].nil? == true
                bitToUse = etsEnaBit(ct)
                if 0<=ct && ct <=7
                    # SharedLib.bbbLog "Turning on controller '#{ct}' (zero base),  @gPIO2.etsEna1Set('#{bitToUse}').  #{__LINE__}-#{__FILE__}"
                    gPIO2Param.etsEna1SetOn(bitToUse)
                elsif 8<=ct && ct <=15
                    # SharedLib.bbbLog "Turning on controller '#{ct}' (zero base),  @gPIO2.etsEna2Set('#{bitToUse}').  #{__LINE__}-#{__FILE__}"
                    gPIO2Param.etsEna2SetOn(bitToUse)
                elsif 16<=ct && ct <=23
                    # SharedLib.bbbLog "Turning on controller '#{ct}' (zero base),  @gPIO2.etsEna3Set('#{bitToUse}').  #{__LINE__}-#{__FILE__}"
                    gPIO2Param.etsEna3SetOn(bitToUse)
                end
            end
            ct += 1
        end
    end

    def dBase
        if @dBase_.nil?
            # puts "ThermalSiteDevices.dBase accessor got called" # from #{file} - #{line}"
            @dBase_ = DutObj.new()
        # else
        #     puts "ThermalSiteDevices.dBase accessor got called.  dBase object is not null." # :  #{file} - #{line}"
            # End of 'if @dBase_.nil?'
        end
        @dBase_
    end

    def initialize
        # End of 'def initialize'
    end

    def setTHCPID(uart1Param,keyParam,tcusToSkip,temParam)
        #puts "setTHCPID '#{keyParam}' = '#{temParam}'"
        dutNum = 0;
        while  dutNum<TOTAL_DUTS_TO_LOOK_AT do
            if  tcusToSkip[dutNum].nil?
                dBase.setTHCPID(keyParam,uart1Param,temParam)
                dutNum = TOTAL_DUTS_TO_LOOK_AT # break out of the loop since we're doing it only in one call.
            end
            dutNum +=1;
        end
    end

    def pollDevices(uart1,gPIO2,tcusToSkip,tsdParam)
        # puts "A - "+Time.now.inspect+" - ThermalSiteDevices.pollDevices function got called."
        # puts "tcusToSkip='#{tcusToSkip}' TOTAL_DUTS_TO_LOOK_AT='#{TOTAL_DUTS_TO_LOOK_AT}'"
        dutNum = 0;
        while  dutNum<TOTAL_DUTS_TO_LOOK_AT do
            if  tcusToSkip[dutNum].nil?
                # puts "Polling dutNum='#{dutNum}' #{__LINE__}-#{__FILE__}"
                dBase.poll(dutNum,uart1,gPIO2,tcusToSkip,tsdParam)
            end
            dutNum +=1;
        end
        # End of 'def PollDevices'
    end

    def analyzeData
        # End of 'def analyzeData'
    end

    def logData(parentMemory,tcusToSkip)
        # Did we get the data?
        # puts "   #{Time.now.to_f.inspect} - ThermalSiteDevices.logData function got called A."
        dBase.saveAllData(parentMemory,tcusToSkip,Time.now)
        # puts "   #{Time.now.to_f.inspect} - ThermalSiteDevices.logData function got called B."
        # End of 'def logData'
    end

    class << self
      extend Forwardable
      def_delegators :instance, *ThermalSiteDevices.instance_methods(false)
    end

    # End of 'class ThermalSiteDevices'
end
# kill variable logData function


text:
Table of Contents
=================

.. toctree::
   :maxdepth: 2

   index
   ref/go_kernel
   contributing
   release_notes


text:
@interface PAModuleManager()

@property (nonatomic, strong)NSMutableDictionary *mappingDic;
@end

@implementation PAModuleManager

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.mappingDic = [[NSMutableDictionary alloc] initWithCapacity:1];
    }

    return self;
}

+ (instancetype)sharedInstance
{
    static PAModuleManager *obj;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        obj = [[PAModuleManager alloc] init];
    });

    return obj;
}

- (void)registerClass:(Class)aClass forProtocol:(Protocol *)aProtocol
{
    if (aProtocol == nil)
    {
        NSLog(@"!!! PAModuleManager.registerClass protocol 为空");
        return;
    }

    id classObj = [aClass new];
    if (![classObj conformsToProtocol:aProtocol])
    {
        NSLog(@"!!! PAModuleManager.registerClass class not conforms protocol");
        return;
    }

    if ([_mappingDic objectForKey:NSStringFromProtocol(aProtocol)])
    {
        NSLog(@"!!! PAModuleManager.registerClass mappoingDic key %@ already exist", aProtocol);
        return;
    }

    [_mappingDic setObject:aClass forKey:NSStringFromProtocol(aProtocol)];
}

- (Class)classForProtocol:(Protocol *)aProtocol
{
    if (aProtocol == nil)
    {
        NSLog(@"!!! PAModuleManager.classForProtocol protocol 为空");
        return nil;
    }

    return [_mappingDic objectForKey:NSStringFromProtocol(aProtocol)];
}

@end


text:
package testdata

import (
	"go/build"
)

// Env represents decoded "env.espresso" file.
var Env = build.Default.GOPATH


text:
Entrées, Sorties, Modules
#########################

.. toctree::
    :maxdepth: 2

    files
    serialization
    module
    faq


text:
import distutils
import os
import platform
import re
import subprocess
import sys

import setuptools
from setuptools.command import build_ext

def emit_build_info(build_chainerx):
    dirname = os.path.dirname(__file__)
    filename = os.path.join(dirname, 'chainerx/_build_info.py')
    with open(filename, mode='w') as f:
        f.write('build_chainerx = {}\n'.format(build_chainerx))

class CMakeExtension(setuptools.Extension):

    def __init__(self, name, build_targets, sourcedir=''):
        setuptools.Extension.__init__(self, name, sources=[])
        self.sourcedir = os.path.abspath(sourcedir)
        self.build_targets = build_targets

class CMakeBuild(build_ext.build_ext):

    def run(self):
        try:
            out = subprocess.check_output(['cmake', '--version'])
        except OSError:
            raise RuntimeError('CMake must be installed to build ChainerX')

        cmake_version = distutils.version.LooseVersion(
            re.search(r'version\s*([\d.]+)', out.decode()).group(1))
        if cmake_version < '3.1.0':
            raise RuntimeError('CMake >= 3.1.0 is required to build ChainerX')

        for ext in self.extensions:
            self.build_extension(ext)

    def build_extension(self, ext):
        # Decide the build type: release/debug
        build_type = os.getenv('CHAINERX_BUILD_TYPE', None)
        if build_type is not None:
            # Use environment variable
            pass
        elif self.debug:
            # Being built with `python setup.py build --debug`
            build_type = 'Debug'
        elif os.getenv('READTHEDOCS', None) == 'True':
            # on ReadTheDocs
            build_type = 'Debug'
        else:
            # default
            build_type = 'Release'

        extdir = os.path.abspath(
            os.path.dirname(self.get_ext_fullpath(ext.name)))
        cmake_args = [
            '-DCHAINERX_BUILD_PYTHON=1',
            '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir,
            '-DPYTHON_EXECUTABLE=' + sys.executable,
            '-DCHAINERX_BUILD_TEST=OFF',
            '-DCMAKE_BUILD_TYPE=' + build_type,
        ]

        build_args = ['--config', build_type]

        if platform.system() == 'Windows':
            cmake_args += [
                '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(
                    build_type.upper(), extdir)]

            if sys.maxsize > 2**32:
                cmake_args += ['-A', 'x64']
            build_args += ['--', '/m']
        else:
            build_args += ['--']
            build_args += ext.build_targets

        env = os.environ.copy()
        env['CXXFLAGS'] = '{} -DVERSION_INFO=\\"{}\\"'.format(
            env.get('CXXFLAGS', ''), self.distribution.get_version())
        if not os.path.exists(self.build_temp):
            os.makedirs(self.build_temp)
        subprocess.check_call(
            ['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp,
            env=env)
        subprocess.check_call(
            ['cmake', '--build', '.'] + build_args, cwd=self.build_temp)

def config_setup_kwargs(setup_kwargs, build_chainerx):

    # TODO(imanishi): Call this function with setuptools.
    emit_build_info(build_chainerx)

    if not build_chainerx:
        # `chainerx` package needs to be able to be imported even if ChainerX
        # is unavailable.
        setup_kwargs['packages'] += ['chainerx']
        return

    if sys.version_info < (3, 5):
        raise RuntimeError(
            'ChainerX is only available for Python 3.5 or later.')
    setup_kwargs['packages'] += [
        'chainerx',
        'chainerx._docs',
        'chainerx.creation',
        'chainerx.manipulation',
        'chainerx.math',
        'chainerx.random',
        'chainerx.testing',
    ]
    setup_kwargs['package_data'] = {
        'chainerx': ['py.typed', '*.pyi'],
    }

    setup_kwargs.update(dict(
        cmdclass={'build_ext': CMakeBuild},
        ext_modules=[CMakeExtension(
            name='chainerx._core',
            build_targets=['_core.so'],
            sourcedir='chainerx_cc')],
    ))