text:
<?php

namespace DGAbgSistemaBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use DGAbgSistemaBundle\Entity\AbgFacturacion;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\ResultSetMapping;
use DGAbgSistemaBundle\Form\AbgFacturacionType;

/**
 * AbgFacturacion controller.
 *
 * @Route("/abgfacturacion")
 */
class AbgFacturacionController extends Controller {

    /**
     * Lists all AbgFacturacion entities.
     *
     * @Route("/", name="abgfacturacion_index")
     * @Method("GET")
     */
    public function indexAction() {
        $em = $this->getDoctrine()->getManager();
        $em->getConnection()->beginTransaction();
        $request = $this->getRequest();
        $result_sub = "";
        $result_especialida = "";
        $Experiencia = "";
        $Certificacion = "";
        $Curso = "";
        try {

            $idPersona = $this->container->get('security.context')->getToken()->getUser()->getRhPersona()->getId();
            $dql_persona = "SELECT  p.id AS id, p.nombres AS nombre, p.apellido AS apellido, p.correoelectronico AS correo, p.descripcion AS  descripcion,"
                    . " p.direccion AS direccion, p.telefonoFijo AS Tfijo, p.telefonoMovil AS movil, p.estado As estado, p.tituloProfesional AS tprofesional "
                    . " FROM DGAbgSistemaBundle:AbgPersona p WHERE p.id=" . $idPersona;
            $result_persona = $em->createQuery($dql_persona)->getArrayResult();

            $dql_tipoPago = "SELECT p.id as id, p.tipoPago As nombre "
                    . " FROM DGAbgSistemaBundle:CtlTipoPago p ORDER BY p.tipoPago ASC";
            $TipoPago = $em->createQuery($dql_tipoPago)->getArrayResult();

            $dqlfoto = "SELECT fot.src as src "
                    . " FROM DGAbgSistemaBundle:AbgFoto fot WHERE fot.abgPersona=" . $idPersona . " and fot.estado=1 and (fot.tipoFoto=0 or fot.tipoFoto=1)";
            $result_foto = $em->createQuery($dqlfoto)->getArrayResult();

            $dqlfoto = "SELECT fot.src as src, fot.estado As estado "
                    . " FROM DGAbgSistemaBundle:AbgFoto fot WHERE fot.abgPersona=" . $idPersona . " and fot.estado=1 and fot.tipoFoto=1 ";
            $fotoP = $em->createQuery($dqlfoto)->getArrayResult();

            //  return $this->render('abgpersona/panelAdministrativoAbg.html.twig', array(
            return $this->render(':abgfacturacion:panelFacturacion.html.twig', array(
                        'abgPersona' => $result_persona,
                        'usuario' => $idPersona,
                        'TipoPago' => $TipoPago,
                        'abgFoto' => $result_foto,
            ));
        } catch (\Exception $e) {
            $data['msj'] = $e->getMessage(); //"Falla al Registrar ";
            return new Response(json_encode($data));

            // echo $e->getMessage();
        }

        return $this->render('abgfacturacion/panelFacturacion.html.twig', array(
                    'abgFacturacions' => $abgFacturacions,
        ));
    }

    /**
     *
     *
     * @Route("/facturacion/data", name="admin_facturacion_data", options={"expose"=true})
     */
    public function dataFacturacionAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $start = $request->query->get('start');
        $draw = $request->query->get('draw');
        $longitud = $request->query->get('length');
        $busqueda = $request->query->get('search');

        $abogado = $request->query->get('param1');
        $servicio = $request->query->get('param2');
        $fechaini = $request->query->get('param3');
        $fechafin = $request->query->get('param4');

//        var_dump($abogado);
//        var_dump($servicio);
//        var_dump($fechaini);
//        var_dump($fechafin);

        $facturacionTotal = $em->getRepository('DGAbgSistemaBundle:AbgFacturacion')->findAll();
        $facturacion['draw'] = $draw++;
        $facturacion['data'] = array();

        $busqueda['value'] = str_replace(' ', '%', $busqueda['value']);
        $rsm = new ResultSetMapping();

        $sql = "SELECT fac.id as facturacion, "
                . "concat_ws(fac.monto, '
', '
') as monto, "
                . "concat_ws(DATE_FORMAT(fac.fecha_registro,'%d-%m-%Y'), '
', '
') as fecha_pago, "
                . "concat_ws(abo.codigo, '
', '
') as codigo, "
                . "concat_ws(fac.plazo, '
', '
') as plazo, "
                . "concat_ws(tip.tipo_pago, '
', '
') as tipo_pago, "
                . "concat_ws(fac.servicio, '
', '
') as servicio, "
                . "concat_ws(fac.id, 'Ver detalles') as link "
                . "FROM abg_facturacion fac inner join abg_persona abo on fac.abg_persona_id = abo.id "
                . "inner join ctl_tipo_pago tip on fac.abg_tipo_pago_id = tip.id "
                . "WHERE 1 = 1 ";

        if ($abogado != 'null') {
            $sql.="and fac.abg_persona_id = '$abogado' ";
        }

        if ($servicio != 'null') {
            $sql.="and fac.servicio = '$servicio' ";
        }

        if ($fechaini != "" && $fechafin != "") {
            $inicio = explode("-", $fechaini);
            $fin = explode("-", $fechafin);
            $fi = $inicio[2] . "-" . $inicio[1] . "-" . $inicio[0];
            $ff = $fin[2] . "-" . $fin[1] . "-" . $fin[0];

            $sql.="and fac.fecha_pago >= '$fi' and fac.fecha_pago <= '$ff' ";
        }

        $sql.= "ORDER BY fac.fecha_pago DESC "
                . "LIMIT $start, $longitud ";
        //echo $sql;
        $rsm->addScalarResult('facturacion', 'facturacion');
        $rsm->addScalarResult('monto', 'monto');
        $rsm->addScalarResult('fecha_pago', 'fecha_pago');
        $rsm->addScalarResult('codigo', 'codigo');
        $rsm->addScalarResult('plazo', 'plazo');
        $rsm->addScalarResult('tipo_pago', 'tipo_pago');
        $rsm->addScalarResult('servicio', 'servicio');
        $rsm->addScalarResult('link', 'link');

        $facturacion['data'] = $em->createNativeQuery($sql, $rsm)
                ->getResult();

        $rsm2 = new ResultSetMapping();

        $sql2 = "SELECT fac.id as facturacion, "
                . "concat_ws(fac.monto, '
', '
') as monto, "
                . "concat_ws(DATE_FORMAT(fac.fecha_pago,'%d-%m-%Y'), '
', '
') as fecha_pago, "
                . "concat_ws(abo.codigo, '
', '
') as codigo, "
                . "concat_ws(fac.plazo, '
', '
') as plazo, "
                . "concat_ws(tip.tipo_pago, '
', '
') as tipo_pago, "
                . "concat_ws(fac.servicio, '
', '
') as servicio, "
                . "concat_ws(fac.id, 'Ver detalles') as link "
                . "FROM abg_facturacion fac inner join abg_persona abo on fac.abg_persona_id = abo.id "
                . "inner join ctl_tipo_pago tip on fac.abg_tipo_pago_id = tip.id "
                . "WHERE 1 = 1 ";

        if ($abogado != 'null') {
            $sql2.="and fac.abg_persona_id = '$abogado' ";
        }

        if ($servicio != 'null') {
            $sql2.="and fac.servicio = '$servicio' ";
        }

        if ($fechaini != "" && $fechafin != "") {
            $inicio = explode("-", $fechaini);
            $fin = explode("-", $fechafin);
            $fi = $inicio[2] . "-" . $inicio[1] . "-" . $inicio[0];
            $ff = $fin[2] . "-" . $fin[1] . "-" . $fin[0];

            $sql2.="and fac.fecha_pago >= '$fi' and fac.fecha_pago <= '$ff' ";
        }

        $rsm2->addScalarResult('facturacion', 'facturacion');
        $rsm2->addScalarResult('monto', 'monto');
        $rsm2->addScalarResult('fecha_pago', 'fecha_pago');
        $rsm2->addScalarResult('codigo', 'codigo');
        $rsm2->addScalarResult('plazo', 'plazo');
        $rsm2->addScalarResult('tipo_pago', 'tipo_pago');
        $rsm2->addScalarResult('servicio', 'servicio');
        $rsm2->addScalarResult('link', 'link');

        $facturaciototal = $em->createNativeQuery($sql2, $rsm2)
                ->getResult();

        $facturacion['recordsTotal'] = count($facturaciototal);
        $facturacion['recordsFiltered'] = count($facturaciototal);

        return new Response(json_encode($facturacion));
    }

    /**
     * Creates a new AbgFacturacion entity.
     *
     * @Route("/new", name="abgfacturacion_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request) {
        $abgFacturacion = new AbgFacturacion();
        $form = $this->createForm('DGAbgSistemaBundle\Form\AbgFacturacionType', $abgFacturacion);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($abgFacturacion);
            $em->flush();

            return $this->redirectToRoute('abgfacturacion_show', array('id' => $abgFacturacion->getId()));
        }

        return $this->render('abgfacturacion/new.html.twig', array(
                    'abgFacturacion' => $abgFacturacion,
                    'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a AbgFacturacion entity.
     *
     * @Route("/{id}", name="abgfacturacion_show")
     * @Method("GET")
     */
    public function showAction(AbgFacturacion $abgFacturacion) {
        $deleteForm = $this->createDeleteForm($abgFacturacion);

        return $this->render('abgfacturacion/show.html.twig', array(
                    'abgFacturacion' => $abgFacturacion,
                    'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing AbgFacturacion entity.
     *
     * @Route("/{id}/edit", name="abgfacturacion_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, AbgFacturacion $abgFacturacion) {
        $deleteForm = $this->createDeleteForm($abgFacturacion);
        $editForm = $this->createForm('DGAbgSistemaBundle\Form\AbgFacturacionType', $abgFacturacion);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($abgFacturacion);
            $em->flush();

            return $this->redirectToRoute('abgfacturacion_edit', array('id' => $abgFacturacion->getId()));
        }

        return $this->render('abgfacturacion/edit.html.twig', array(
                    'abgFacturacion' => $abgFacturacion,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a AbgFacturacion entity.
     *
     * @Route("/{id}", name="abgfacturacion_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, AbgFacturacion $abgFacturacion) {
        $form = $this->createDeleteForm($abgFacturacion);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($abgFacturacion);
            $em->flush();
        }

        return $this->redirectToRoute('abgfacturacion_index');
    }

    /**
     * Creates a form to delete a AbgFacturacion entity.
     *
     * @param AbgFacturacion $abgFacturacion The AbgFacturacion entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(AbgFacturacion $abgFacturacion) {
        return $this->createFormBuilder()
                        ->setAction($this->generateUrl('abgfacturacion_delete', array('id' => $abgFacturacion->getId())))
                        ->setMethod('DELETE')
                        ->getForm()
        ;
    }

    /**
     * @Route("/abogados_solverificacion/get", name="abogados_solverificacion", options={"expose"=true})
     * @Method("GET")
     */
    public function getAbogadosSolverificacionAction() {
        $request = $this->getRequest();
        $busqueda = $request->query->get('q');

        $em = $this->getDoctrine()->getEntityManager();
        $dql = "SELECT p.id AS idAbg,CONCAT(p.nombres, '  ', p.apellido)   AS nombre "
                . "FROM DGAbgSistemaBundle:AbgPersona p "
                . "WHERE  upper(CONCAT(p.nombres,' ',p.apellido)) LIKE upper(:busqueda)  "
                . "ORDER BY p.nombres ASC ";

        $array = $em->createQuery($dql)
                ->setParameters(array('busqueda' => "%" . $busqueda . "%"))
                ->setMaxResults(10)
                ->getResult();

        if (count($array > 0)) {
            $data['data'] = $array;
        } else {
            $data['data'] = array('id' => 0, 'nombre' => ' Nueva empresa');
        }
        return new Response(json_encode($data));
    }

    /**
     * @Route("/facturacion", name="facturacion", options={"expose"=true})
     * @Method("POST")
     */
    public function FacturacionAction() {

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

        try {
            $idUser = $this->container->get('security.context')->getToken()->getUser()->getId();
            parse_str($request->get('dato'), $datos);

            $Persona = $em->getRepository("DGAbgSistemaBundle:AbgPersona")->find($datos['Sabogados']);
            $TipoPago = $em->getRepository("DGAbgSistemaBundle:CtlTipoPago")->find($datos['STipoPago']);
            $abgFacturacion = new AbgFacturacion();
            $abgFacturacion->setAbgPersona($Persona);
            $abgFacturacion->setAbgTipoPago($TipoPago);
            $abgFacturacion->setFechaPago(new \DateTime("now"));
            $abgFacturacion->setIdUser($idUser);
            $abgFacturacion->setMonto($datos['txtcosto']);
            $abgFacturacion->setPlazo($datos['Splazo']);
            $abgFacturacion->setServicio($datos['STipoServicio']);
            $abgFacturacion->setDescripcion($datos['txtdescripcion']);
            $em->persist($abgFacturacion);
            $em->flush();
            $data['msj'] = "datos registrados";
            return new Response(json_encode($data));
        } catch (\Exception $e) {
            $data['msj'] = $e->getMessage(); //"Falla al Registrar ";
            return new Response(json_encode($data));
        }
    }

    /**
     * @Route("/consulta_fact/get", name="consulta_fact", options={"expose"=true})
     * @Method("GET")
     */
    public function getConsultaFactAction() {
        $request = $this->getRequest();
        $busqueda = $request->query->get('q');
        try {
            $em = $this->getDoctrine()->getEntityManager();

            parse_str($request->get('dato'), $datos);

            $sql = "SELECT p.id AS idAbg, CONCAT(p.nombres, '  ', p.apellido)   AS nombre, f.id As idFact, f.monto AS monto, f.plazo As plazo, "
                    . " f.servicio As servicio, tp.tipo_pago As tipoPago, f.descripcion As descripcion, date_format(f.fecha_pago, '%d/%m/%Y') As fechaPago "
                    . " FROM  abg_persona p "
                    . " JOIN  abg_facturacion f"
                    . " ON  p.id=f.abg_persona_id AND p.id=" . $datos['Sabogado'] . "  AND f.fecha_pago >=" . $datos['txtFechaInicio'] . "  OR  f.fecha_pago <=" . $datos['txtFechaFin']
                    . " JOIN  ctl_tipo_pago tp "
                    . " ON  tp.id=f.abg_tipo_pago_id"
                    . " ORDER BY p.nombres ASC ";
            $stm = $this->container->get('database_connection')->prepare($sql);
            $stm->execute();
            $data['facturacion'] = $stm->fetchAll();

            return new Response(json_encode($data));
        } catch (\Exception $e) {
            $data['msj'] = $e->getMessage(); //"Falla al Registrar ";
            return new Response(json_encode($data));
        }
    }

    /**
     * @Route("/plan_pago/pago/{id}", name="planpago", options={"expose"=true})
     * @Method("GET")
     */
    public function PlanPagoAction(Request $request) {
        try {
            $em = $this->getDoctrine()->getManager();
            $idPersona = $this->container->get('security.context')->getToken()->getUser()->getRhPersona()->getId();
            $codigo = $request->get('id');

            $dql_departamento = "SELECT  tp.id AS id, tp.tipoPago AS nombre"
                    . " FROM DGAbgSistemaBundle:CtlTipoPago tp WHERE tp.id  <> 5 AND tp.id  <> 3 AND tp.id  <> 6 AND tp.id  <> 7";
            $tipoPago = $em->createQuery($dql_departamento)->getArrayResult();

            $comprobante = $em->getRepository("DGAbgSistemaBundle:AbgFacturacion")->findByAbgPersona($idPersona);
            $trial = 0;
            if ($comprobante) {
                $trial = $comprobante[0]->getAbgTipoPago()->getId();
            }

            //     return $this->render('abgfacturacion/planPago.html.twig', array('tipoPago' => $tipoPago,'trial'=>$trial));
            return $this->render('abgfacturacion/pay.html.twig', array('tipoPago' => $tipoPago, 'trial' => $trial));
        } catch (\Exception $e) {
            $data['msj'] = $e->getMessage(); //"Falla al Registrar ";
            return new Response(json_encode($data));
        }
    }

    /**
     * @Route("/metodo/data/pago", name="metodo_pago", options={"expose"=true})
     * @Method("POST")
     */
    public function MetodoPagoAction() {

        try {
            $em = $this->getDoctrine()->getManager();
            $request = $this->getRequest();

            /*    var_dump($request->get('hplan'));
              var_dump($request->get('rMetodo'));
              exit(); */

            $idPersona = $this->container->get('security.context')->getToken()->getUser()->getRhPersona()->getId();
            $idUser = $this->container->get('security.context')->getToken()->getUser()->getId();

            $Persona = $em->getRepository("DGAbgSistemaBundle:AbgPersona")->find($idPersona);
            $Usuario = $em->getRepository("DGAbgSistemaBundle:CtlUsuario")->find($idUser);

            $factura = $em->getRepository("DGAbgSistemaBundle:AbgFacturacion")->findByAbgPersona($idPersona);

            $abgFacturacionTrial = new AbgFacturacion();
            $abgFacturacion = new AbgFacturacion();

            $nombreimagen2 = "";
            //     if (count($comprobante) == 0) {
            $path2 = $this->container->getParameter('photo.comprobante');

            $date = new \DateTime("now");

            $abgFacturacion->setAbgPersona($Persona);
            $abgFacturacion->setIdUser(null);
            $abgFacturacion->setFechaRegistro(new \DateTime("now"));
            // 14 dias gratis
            if (count($factura) == 0) {
             /*   var_dump(count($factura));
            exit();*/
                $tipo_pago = $em->getRepository("DGAbgSistemaBundle:CtlTipoPago")->find(5);
                $fechaPago = date_add($date, date_interval_create_from_date_string('14 days'));
           $abgFacturacionTrial->setAbgPersona($Persona);
            $abgFacturacionTrial->setIdUser(null);
            $abgFacturacionTrial->setFechaRegistro(new \DateTime("now"));
                $abgFacturacionTrial->setFechaPago($fechaPago);
                $abgFacturacionTrial->setAbgTipoPago($tipo_pago);
                $abgFacturacionTrial->setMonto(00.00);
                $abgFacturacionTrial->setPlazo(14);
                $abgFacturacionTrial->setServicio('Bienvenida');
                $abgFacturacionTrial->setDescripcion('Directorio de abogados de El Salvador te regala 14 dias de bienvenida por la suscripcion dentro del periodo de ..');
                $abgFacturacionTrial->setComprobante(null);
                $abgFacturacionTrial->setAprobado(1);
               $em->persist($abgFacturacionTrial);
                $em->flush();
            }
         $abgFacturacion->setAbgPersona($Persona);
            $abgFacturacion->setIdUser(null);
            $abgFacturacion->setFechaRegistro(new \DateTime("now"));
            if ($request->get('hplan') != null) {
                switch ($request->get('hplan')) {
                    /* case 1:
                      $tipo_pago = $em->getRepository("DGAbgSistemaBundle:CtlTipoPago")->find(5);
                      $fechaPago = date_add($date, date_interval_create_from_date_string('14 days'));

                      $abgFacturacion->setFechaPago($fechaPago);
                      $abgFacturacion->setAbgTipoPago($tipo_pago);
                      $abgFacturacion->setMonto(00.00);
                      $abgFacturacion->setPlazo(14);
                      $abgFacturacion->setServicio('Bienvenida');
                      $abgFacturacion->setDescripcion('14 dias de bienvenida');
                      $abgFacturacion->setComprobante(null);
                      $abgFacturacion->setAprobado(1);

                      break; */
                    case 1:
                        $tipo_pago = $em->getRepository("DGAbgSistemaBundle:CtlTipoPago")->find($request->get('rMetodo'));
                        // $fechaPago = date_add($date, date_interval_create_from_date_string('90 days'));
                      /*  $nombreimagen = $_FILES['imagen']['name'];
                        $tipo = $_FILES['imagen']['type'];
                        $extension = explode('/', $tipo);
                        $nombreimagen2.="." . $extension[1];
                        $fecha = date('Y-m-dHis');
                        $nombreArchivo = $nombreimagen . "-" . $fecha . $nombreimagen2;
                        $nombreSERVER = str_replace(" ", "", $nombreArchivo);

                        $resultados = move_uploaded_file($_FILES["imagen"]["tmp_name"], $path2 . $nombreSERVER);
                        if ($resultados) {
                            $path = "Photos/comprobante/";
                            $nombreBASE = $path . $nombreArchivo;
                        }*/
                       $abgFacturacion->setFechaPago(null);
                        $abgFacturacion->setAbgTipoPago($tipo_pago);
                        $abgFacturacion->setMonto(09.99);
                        $abgFacturacion->setPlazo(30);
                        $abgFacturacion->setServicio('Personal');
                        $abgFacturacion->setDescripcion('Suscripcion por un periodo de 30 dias');
                     //   $abgFacturacion->setComprobante($nombreBASE);
                        $abgFacturacion->setAprobado(0);

                        break;
                    case 2:

                        $tipo_pago = $em->getRepository("DGAbgSistemaBundle:CtlTipoPago")->find($request->get('rMetodo'));
                       /* $nombreimagen = $_FILES['imagen']['name'];
                        $tipo = $_FILES['imagen']['type'];
                        $extension = explode('/', $tipo);
                        $nombreimagen2.="." . $extension[1];
                        $fecha = date('Y-m-dHis');
                        $nombreArchivo = $nombreimagen . "-" . $fecha . $nombreimagen2;
                        $nombreSERVER = str_replace(" ", "", $nombreArchivo);

                        $resultados = move_uploaded_file($_FILES["imagen"]["tmp_name"], $path2 . $nombreSERVER);
                        if ($resultados) {
                            $path = "Photos/comprobante/";
                            $nombreBASE = $path . $nombreArchivo;
                        }
                     */
                        $abgFacturacion->setAbgTipoPago($tipo_pago);
                        $abgFacturacion->setMonto(27.99);
                        $abgFacturacion->setPlazo(90);
                        $abgFacturacion->setServicio('Personal');
                        $abgFacturacion->setDescripcion('Suscripcion por un periodo de 90 dias');
                      //  $abgFacturacion->setComprobante($nombreBASE);
                        $abgFacturacion->setAprobado(0);
                        break;

                    case 3:

                   /*     $tipo_pago = $em->getRepository("DGAbgSistemaBundle:CtlTipoPago")->find($request->get('rMetodo'));
                        $nombreimagen = $_FILES['imagen']['name'];
                        $tipo = $_FILES['imagen']['type'];
                        $extension = explode('/', $tipo);
                        $nombreimagen2.="." . $extension[1];
                        $fecha = date('Y-m-dHis');
                        $nombreArchivo = $nombreimagen . "-" . $fecha . $nombreimagen2;
                        $nombreSERVER = str_replace(" ", "", $nombreArchivo);

                        $resultados = move_uploaded_file($_FILES["imagen"]["tmp_name"], $path2 . $nombreSERVER);
                        if ($resultados) {
                            $path = "Photos/comprobante/";
                            $nombreBASE = $path . $nombreArchivo;
                        }
*/
                        $abgFacturacion->setAbgTipoPago($tipo_pago);
                        $abgFacturacion->setMonto(54.96);
                        $abgFacturacion->setPlazo(180);
                        $abgFacturacion->setServicio('Personal');
                        $abgFacturacion->setDescripcion('Suscripcion por un periodo de 180 dias');
                  //     $abgFacturacion->setComprobante($nombreBASE);
                        $abgFacturacion->setAprobado(0);

                        break;
                    case 4:

                   /*     $tipo_pago = $em->getRepository("DGAbgSistemaBundle:CtlTipoPago")->find($request->get('rMetodo'));
                        $nombreimagen = $_FILES['imagen']['name'];
                        $tipo = $_FILES['imagen']['type'];
                        $extension = explode('/', $tipo);
                        $nombreimagen2.="." . $extension[1];
                        $fecha = date('Y-m-dHis');
                        $nombreArchivo = $nombreimagen . "-" . $fecha . $nombreimagen2;
                        $nombreSERVER = str_replace(" ", "", $nombreArchivo);

                        $resultados = move_uploaded_file($_FILES["imagen"]["tmp_name"], $path2 . $nombreSERVER);
                        if ($resultados) {
                            $path = "Photos/comprobante/";
                            $nombreBASE = $path . $nombreArchivo;
                        }
*/
                        $abgFacturacion->setAbgTipoPago($tipo_pago);
                        $abgFacturacion->setMonto(99.99);
                        $abgFacturacion->setPlazo(360);
                        $abgFacturacion->setServicio('Personal');
                        $abgFacturacion->setDescripcion('Suscripcion por un periodo de 360 dias');
                //        $abgFacturacion->setComprobante($nombreBASE);
                        $abgFacturacion->setAprobado(0);

                        break;
                }
                $em->persist($abgFacturacion);
                $em->flush();

                $Persona->setEstadoMetodoPago(1);
                $em->merge($Persona);
                $em->flush();

                $Usuario->setEstadoCorreo(1);
                $em->merge($Usuario);
                $em->flush();

                $data['estado'] = true;
            } else {
                $data['estado'] = false;
            }

            return new Response(json_encode($data));
        } catch (\Exception $e) {
            $data['error'] = $e->getMessage(); //"Falla al Registrar ";
            return new Response(json_encode($data));
        }
    }

}


text:
package org.datanucleus.samples.compoundidentity;

import java.io.Serializable;
import java.util.StringTokenizer;

/**
 * Sample target class with another PC object as part of the PK (1-1/1-N uni relation).
 */
public class CompoundSingleTarget
{
    private int id; // PK
    private CompoundHolder holder; // PK

    private double value;

    public CompoundSingleTarget(CompoundHolder source, double value)
    {
        super();
        this.holder = source;
        this.value = value;
    }

    public final int getId()
    {
        return id;
    }

    public final void setId(int id)
    {
        this.id = id;
    }

    public final CompoundHolder getHolder()
    {
        return holder;
    }

    public final void setHolder(CompoundHolder holder)
    {
        this.holder = holder;
    }

    public final double getValue()
    {
        return value;
    }

    public final void setValue(double value)
    {
        this.value = value;
    }

    public static class Id implements Serializable
    {
        private static final long serialVersionUID = -3337471931525836066L;
        public int id;
        public CompoundHolder.Id holder;

        public Id()
        {
        }

        public Id(String s)
        {
            StringTokenizer token = new StringTokenizer(s,"::");
            this.id = Integer.valueOf(token.nextToken()).intValue();
            this.holder = new CompoundHolder.Id(token.nextToken());
        }

        public String toString()
        {
            return "" + id + "::" + holder.toString();
        }

        public int hashCode()
        {
            return id ^ holder.hashCode();
        }

        public boolean equals(Object other)
        {
            if (other != null && (other instanceof Id))
            {
                Id k = (Id)other;
                return k.id == this.id && this.holder.equals(k.holder);
            }
            return false;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
I18n::Backend::ActiveRecord::Translation.create!(
  [
    {locale: "nl", key: "propertyStates.underConstruction", value: "In aanbouw"},
    {locale: "nl", key: "propertyStates.brandNew", value: "Nieuwbouw"},
    {locale: "nl", key: "propertyStates.segundaMano", value: "Bestaand"},
    {locale: "nl", key: "propertyStates.nuevo", value: "Nieuw"},
    {locale: "nl", key: "propertyStates.enConstruccion", value: "In aanbouw"},
    {locale: "nl", key: "propertyStates.aReformar", value: "Opknapper"},

    {locale: "nl", key: "propertyOrigin.bank", value: "Bankbezit"},
    {locale: "nl", key: "propertyOrigin.new", value: "Nieuwbouw"},
    {locale: "nl", key: "propertyOrigin.private", value: "Privé verkoop"},
    {locale: "nl", key: "propertyLabels.sold", value: "Verkocht"},
    {locale: "nl", key: "propertyLabels.reserved", value: "Gereserveerd"},

    {locale: "nl", key: "extras.aireAcondicionado", value: "Airconditioning"},
    {locale: "nl", key: "extras.alarma", value: "Alarm"},
    {locale: "nl", key: "extras.amueblado", value: "Meubels"},
    {locale: "nl", key: "extras.armariosEmpotrados", value: "Inbouwkasten"},
    {locale: "nl", key: "extras.ascensor", value: "Lift"},
    {locale: "nl", key: "extras.balcon", value: "Balkon"},
    {locale: "nl", key: "extras.banoTurco", value: "Stoom Bad"},
    {locale: "nl", key: "extras.calefaccionCentral", value: "Centrale verwarming"},
    {locale: "nl", key: "extras.calefaccionElectrica", value: "Electrische verwarming"},
    {locale: "nl", key: "extras.calefaccionPropano", value: "Gas verwarming"},
    {locale: "nl", key: "extras.cocinaIndependiente", value: "Onafhankelijke keuken"},
    {locale: "nl", key: "extras.electrodomesticos", value: "Witgoed"},
    {locale: "nl", key: "extras.energiaSolar", value: "Zonne energie"},
    {locale: "nl", key: "extras.garajeComunitario", value: "Gemeenschappelijke garage"},
    {locale: "nl", key: "extras.garajePrivado", value: "Privé Garage"},
    {locale: "nl", key: "extras.gresCeramica", value: "Keramische Vloer"},
    {locale: "nl", key: "extras.horno", value: "Oven"},
    {locale: "nl", key: "extras.jacuzzi", value: "Jacuzzi"},
    {locale: "nl", key: "extras.jardinComunitario", value: "Gemeenschappelijke tuin"},
    {locale: "nl", key: "extras.jardinPrivado", value: "Privé tuin"},
    {locale: "nl", key: "extras.lavadero", value: "waskamer"},
    {locale: "nl", key: "extras.lavadora", value: "Wasmachine"},
    {locale: "nl", key: "extras.microondas", value: "Magnetron"},
    {locale: "nl", key: "extras.nevera", value: "Koelkast"},
    {locale: "nl", key: "extras.parquet", value: "Houten vloer"},
    {locale: "nl", key: "extras.piscinaClimatizada", value: "Verwarmd zwembad"},
    {locale: "nl", key: "extras.piscinaComunitaria", value: "Gemeenschappelijk zwembad"},
    {locale: "nl", key: "extras.piscinaPrivada", value: "Privé zwembad"},
    {locale: "nl", key: "extras.porche", value: "Terras"},
    {locale: "nl", key: "extras.puertaBlindada", value: "Stalen deur"},
    {locale: "nl", key: "extras.sauna", value: "Sauna"},
    {locale: "nl", key: "extras.servPorteria", value: "Verzorg dienst"},
    {locale: "nl", key: "extras.sueloMarmol", value: "Marmeren vloer"},
    {locale: "nl", key: "extras.terraza", value: "Terras"},
    {locale: "nl", key: "extras.trastero", value: "Opslag"},
    {locale: "nl", key: "extras.tv", value: "TV"},
    {locale: "nl", key: "extras.videoportero", value: "Video Entry-telefoon"},
    {locale: "nl", key: "extras.vigilancia", value: "Beveiliging"},
    {locale: "nl", key: "extras.vistasAlMar", value: "Zeezicht"},
    {locale: "nl", key: "extras.zComunitaria", value: "Gemeenshappelijke tuin"},
    {locale: "nl", key: "extras.zonaDeportiva", value: "Sportgelegenheid"},
    {locale: "nl", key: "extras.cercaDeServicios", value: "Dichtbij winkels"},
    {locale: "nl", key: "extras.calefaccionGasCiudad", value: "Centrale gas verwarming"},
    {locale: "nl", key: "extras.calefaccionGasoleo", value: "Diesel Verwarming"},
    {locale: "nl", key: "extras.zonasInfantiles", value: "Speeltuin"},
    {locale: "nl", key: "extras.sueloRadiante", value: "Vloerverwarming"},
    {locale: "nl", key: "extras.semiamueblado", value: "Semi gemeubuleerd"},
    {locale: "nl", key: "extras.chimenea", value: "Open haard"},
    {locale: "nl", key: "extras.barbacoa", value: "Barbecue"},
    # {locale: "nl", key: "extras.porsche", value: "Terras"},
    {locale: "nl", key: "extras.solarium", value: "Solarium"},
    {locale: "nl", key: "extras.patioInterior", value: "Achtertuin"},
    {locale: "nl", key: "extras.vistasALaMontana", value: "Uitzicht op bergen"},
    {locale: "nl", key: "extras.vistasAlJardin", value: "Zicht op tuin"},
    {locale: "nl", key: "extras.urbanizacion", value: "Urbanisatie"},
    {locale: "nl", key: "extras.zonaTranquila", value: "Stille omgeving"},
    {locale: "nl", key: "propertyTypes.apartamento", value: "Appartement"},
    {locale: "nl", key: "propertyTypes.chaletIndependiente", value: "Chalet"},
    {locale: "nl", key: "propertyTypes.bungalow", value: "Bungalow"},
    {locale: "nl", key: "propertyTypes.inversion", value: "Investering"},
    {locale: "nl", key: "propertyTypes.solar", value: "Land"},
    {locale: "nl", key: "propertyTypes.duplex", value: "Duplex"},
    {locale: "nl", key: "propertyTypes.piso", value: "Flat"},
    {locale: "nl", key: "propertyTypes.hotel", value: "Hotel"},
    {locale: "nl", key: "propertyTypes.chaletAdosado", value: "Twee onder een kap"},
    {locale: "nl", key: "propertyTypes.atico", value: "Penthouse"},
    {locale: "nl", key: "propertyTypes.estudio", value: "Studio"},
    {locale: "nl", key: "propertyTypes.garaje", value: "Garage"},
    {locale: "nl", key: "propertyTypes.local", value: "Commercieel pand"},
    {locale: "nl", key: "propertyTypes.trastero", value: "Landhuis"},
    {locale: "nl", key: "propertyTypes.casaRural", value: "Plattelandshuis"},
    {locale: "nl", key: "propertyTypes.edificioResidencial", value: "Residentieel gebouw"},
    {locale: "nl", key: "propertyTypes.villa", value: "Villa"}
  ]
)


text:
from __future__ import unicode_literals

import jsonfield.fields
from django.db import migrations, models
import uuid

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Payment',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('payu_order_id', models.CharField(max_length=255, verbose_name='PayU order ID')),
                ('pos_id', models.CharField(max_length=255, verbose_name='PayU POS ID')),
                ('customer_ip', models.CharField(max_length=255, verbose_name='customer IP')),
                ('created', models.DateTimeField(auto_now_add=True, verbose_name='creation date')),
                ('status', models.CharField(choices=[('NEW', 'New'), ('PENDING', 'Pending'), ('WAITING_FOR_CONFIRMATION', 'Waiting for confirmation'), ('COMPLETED', 'Completed'), ('CANCELED', 'Canceled'), ('REJECTED', 'Rejected')], default='NEW', max_length=255, verbose_name='status')),
                ('total', models.PositiveIntegerField(verbose_name='total')),
                ('description', models.TextField(blank=True, null=True, verbose_name='description')),
                ('products', jsonfield.fields.JSONField(blank=True, default='', verbose_name='products')),
                ('notes', models.TextField(blank=True, null=True, verbose_name='notes')),
            ],
            options={
                'verbose_name_plural': 'payments',
                'verbose_name': 'payment',
            },
        ),
    ]


text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
(function (deps, factory) {
    if (typeof module === 'object' && typeof module.exports === 'object') {
        var v = factory(require, exports); if (v !== undefined) module.exports = v;
    }
    else if (typeof define === 'function' && define.amd) {
        define(deps, factory);
    }
})(["require", "exports", './BaseEvent'], function (require, exports) {
    var BaseEvent = require('./BaseEvent');
    /**
     * The LoaderEvent...
     *
     * @class LoaderEvent
     * @extends BaseEvent
     * @param type {string} The type of event. The type is case-sensitive.
     * @param [bubbles=false] {boolean} Indicates whether an event is a bubbling event. If the event can bubble, this value is true; otherwise it is false.
     * Note: With event-bubbling you can let one Event subsequently call on every ancestor ({{#crossLink "EventDispatcher/parent:property"}}{{/crossLink}})
     * (containers of containers of etc.) of the {{#crossLink "DisplayObjectContainer"}}{{/crossLink}} that originally dispatched the Event, all the way up to the surface ({{#crossLink "Stage"}}{{/crossLink}}). Any classes that do not have a parent cannot bubble.
     * @param [cancelable=false] {boolean} Indicates whether the behavior associated with the event can be prevented. If the behavior can be canceled, this value is true; otherwise it is false.
     * @param [data=null] {any} Use to pass any type of data with the event.
     * @module StructureJS
     * @submodule event
     * @requires Extend
     * @requires BaseEvent
     * @constructor
     * @author Robert S. (www.codeBelt.com)
     */
    var LoaderEvent = (function (_super) {
        __extends(LoaderEvent, _super);
        function LoaderEvent(type, bubbles, cancelable, data) {
            if (bubbles === void 0) { bubbles = false; }
            if (cancelable === void 0) { cancelable = false; }
            if (data === void 0) { data = null; }
            _super.call(this, type, bubbles, cancelable, data);
        }
        /**
         * The LoaderEvent.COMPLETE constant defines the value of the type property of an loader event object.
         *
         * @event COMPLETE
         * @type {string}
         * @static
         */
        LoaderEvent.COMPLETE = 'LoaderEvent.complete';
        /**
         * The LoaderEvent.LOAD_COMPLETE constant defines the value of the type property of an loader event object.
         *
         * @event LOAD_COMPLETE
         * @type {string}
         * @static
         */
        LoaderEvent.LOAD_COMPLETE = 'LoaderEvent.loadComplete';
        /**
         * The LoaderEvent.ERROR constant defines the value of the type property of an loader event object.
         *
         * @event ERROR
         * @type {string}
         * @static
         */
        LoaderEvent.ERROR = 'LoaderEvent.error';
        return LoaderEvent;
    })(BaseEvent);
    return LoaderEvent;
});


text:
Google Cloud Aiplatform SDK
=============================================

.. automodule:: google.cloud.aiplatform
    :members:
    :show-inheritance:


text:
"""Module encapsulating Zmake wrapper object."""
import atexit
import difflib
import functools
import logging
import os
import pathlib
import re
import shutil
import subprocess
import tempfile
from typing import Dict, Optional, Set, Union

import zmake.build_config
import zmake.compare_builds
import zmake.generate_readme
import zmake.jobserver
import zmake.modules
import zmake.multiproc
import zmake.project
import zmake.util as util
import zmake.version

ninja_warnings = re.compile(r"^(\S*: )?warning:.*")
ninja_errors = re.compile(r"error:.*")

def ninja_stdout_log_level_override(line, current_log_level):
    """Update the log level for ninja builds if we hit an error.

    Ninja builds prints everything to stdout, but really we want to start
    logging things to CRITICAL

    Args:
        line: The line that is about to be logged.
        current_log_level: The active logging level that would be used for the
          line.
    """
    # pylint: disable=too-many-return-statements
    # Output lines from Zephyr that are not normally useful
    # Send any lines that start with these strings to INFO
    cmake_suppress = [
        "-- ",  # device tree messages
        "Loaded configuration",
        "Including boilerplate",
        "Parsing ",
        "No change to configuration",
        "No change to Kconfig header",
    ]

    # Herewith a long list of things which are really for debugging, not
    # development. Return logging.DEBUG for each of these.

    # ninja puts progress information on stdout
    if line.startswith("["):
        return logging.DEBUG
    # we don't care about entering directories since it happens every time
    if line.startswith("ninja: Entering directory"):
        return logging.DEBUG
    # we know the build stops from the compiler messages and ninja return code
    if line.startswith("ninja: build stopped"):
        return logging.DEBUG
    # someone prints a *** SUCCESS *** message which we don't need
    if line.startswith("***"):
        return logging.DEBUG
    # dopey ninja puts errors on stdout, so fix that. It does not look
    # likely that it will be fixed upstream:
    # https://github.com/ninja-build/ninja/issues/1537
    # Try to drop output about the device tree
    if any(line.startswith(x) for x in cmake_suppress):
        return logging.INFO
    # this message is a bit like make failing. We already got the error output.
    if line.startswith("FAILED: CMakeFiles"):
        return logging.INFO
    # if a particular file fails it shows the build line used, but that is not
    # useful except for debugging.
    if line.startswith("ccache"):
        return logging.DEBUG
    if ninja_warnings.match(line):
        return logging.WARNING
    if ninja_errors.match(line):
        return logging.ERROR
    # When we see "Memory region" go into INFO, and stay there as long as the
    # line starts with \S+:
    if line.startswith("Memory region"):
        return logging.INFO
    if current_log_level == logging.INFO and line.split()[0].endswith(":"):
        return current_log_level
    if current_log_level == logging.WARNING:
        return current_log_level
    return logging.ERROR

def cmake_log_level_override(line, default_log_level):
    """Update the log level for cmake output if we hit an error.

    Cmake prints some messages that are less than useful during
    development.

    Args:
        line: The line that is about to be logged.
        default_log_level: The default logging level that will be used for the
          line.
    """
    # Strange output from Zephyr that we normally ignore
    if line.startswith("Including boilerplate"):
        return logging.DEBUG
    if line.startswith("devicetree error:"):
        return logging.ERROR
    if ninja_warnings.match(line):
        return logging.WARNING
    if ninja_errors.match(line):
        return logging.ERROR
    return default_log_level

def get_process_failure_msg(proc):
    """Creates a suitable failure message if something exits badly

    Args:
        proc: subprocess.Popen object containing the thing that failed

    Returns:
        Failure message as a string:
    """
    return "Execution failed (return code={}): {}\n".format(
        proc.returncode, util.repr_command(proc.args)
    )

class Zmake:
    """Wrapper class encapsulating zmake's supported operations.

    The invocations of the constructor and the methods actually comes
    from the main function.  The command line arguments are translated
    such that dashes are replaced with underscores and applied as
    keyword arguments to the constructor and the method, and the
    subcommand invoked becomes the method run.

    As such, you won't find documentation for each method's parameters
    here, as it would be duplicate of the help strings from the
    command line.  Run "zmake --help" for full documentation of each
    parameter.

    Properties:
        executor: a zmake.multiproc.Executor object for submitting
            tasks to.
        _sequential: True to check the results of each build job sequentially,
            before launching more, False to just do this after all jobs complete
    """

    # pylint: disable=too-many-instance-attributes

    def __init__(
        self,
        checkout=None,
        jobserver: Optional[zmake.jobserver.JobClient] = None,
        jobs=0,
        goma=False,
        gomacc="/mnt/host/depot_tools/.cipd_bin/gomacc",
        modules_dir=None,
        zephyr_base=None,
    ):
        zmake.multiproc.LogWriter.reset()
        self.logger = logging.getLogger(self.__class__.__name__)
        self._checkout = checkout
        self.goma = goma
        self.gomacc = gomacc
        if zephyr_base:
            self.zephyr_base = zephyr_base
        else:
            self.zephyr_base = (
                self.checkout / "src" / "third_party" / "zephyr" / "main"
            )

        if modules_dir:
            self.module_paths = zmake.modules.locate_from_directory(modules_dir)
        else:
            self.module_paths = zmake.modules.locate_from_checkout(
                self.checkout
            )

        if jobserver:
            self.jobserver = jobserver
        else:
            self.jobserver = zmake.jobserver.GNUMakeJobServer(jobs=jobs)

        self.executor = zmake.multiproc.Executor()
        self._sequential = self.jobserver.is_sequential() and not goma
        self.failed_projects = []

    @property
    def checkout(self):
        """Returns the location of the cros checkout."""
        if not self._checkout:
            self._checkout = util.locate_cros_checkout()
        return self._checkout.resolve()

    def _resolve_projects(
        self,
        project_names,
        all_projects=False,
    ) -> Set[zmake.project.Project]:
        """Finds all projects for the specified command line flags.

        Returns a list of projects.
        """
        found_projects = zmake.project.find_projects(
            self.module_paths["ec"] / "zephyr"
        )
        if all_projects:
            projects = set(found_projects.values())
        else:
            projects = set()
            for project_name in project_names:
                try:
                    projects.add(found_projects[project_name])
                except KeyError as e:
                    raise KeyError(
                        "No project named {}".format(project_name)
                    ) from e
        return projects

    def configure(
        self,
        project_names,
        build_dir=None,
        toolchain=None,
        build_after_configure=False,
        clobber=False,
        bringup=False,
        coverage=False,
        allow_warnings=False,
        all_projects=False,
        extra_cflags=None,
        delete_intermediates=False,
        static_version=False,
        save_temps=False,
        wait_for_executor=True,
    ):
        """Locate and configure the specified projects."""
        # Resolve build_dir if needed.
        if not build_dir:
            build_dir = self.module_paths["ec"] / "build" / "zephyr"

        projects = self._resolve_projects(
            project_names,
            all_projects=all_projects,
        )
        for project in projects:
            project_build_dir = (
                pathlib.Path(build_dir) / project.config.project_name
            )
            self.executor.append(
                func=functools.partial(
                    self._configure,
                    project=project,
                    build_dir=project_build_dir,
                    toolchain=toolchain,
                    build_after_configure=build_after_configure,
                    clobber=clobber,
                    bringup=bringup,
                    coverage=coverage,
                    allow_warnings=allow_warnings,
                    extra_cflags=extra_cflags,
                    delete_intermediates=delete_intermediates,
                    static_version=static_version,
                    save_temps=save_temps,
                )
            )
            if self._sequential:
                result = self.executor.wait()
                if result:
                    return result
        non_test_projects = [p for p in projects if not p.config.is_test]
        if len(non_test_projects) > 1 and coverage and build_after_configure:
            result = self.executor.wait()
            if result:
                return result
            result = self._merge_lcov_files(
                projects=non_test_projects,
                build_dir=build_dir,
                output_file=build_dir / "all_builds.info",
            )
            if result:
                self.failed_projects.append(str(build_dir / "all_builds.info"))
                return result
        elif wait_for_executor:
            result = self.executor.wait()
            if result:
                return result

        return 0

    def build(
        self,
        project_names,
        build_dir=None,
        toolchain=None,
        clobber=False,
        bringup=False,
        coverage=False,
        allow_warnings=False,
        all_projects=False,
        extra_cflags=None,
        delete_intermediates=False,
        static_version=False,
        save_temps=False,
    ):
        """Locate and build the specified projects."""
        return self.configure(
            project_names,
            build_dir=build_dir,
            toolchain=toolchain,
            clobber=clobber,
            bringup=bringup,
            coverage=coverage,
            allow_warnings=allow_warnings,
            all_projects=all_projects,
            extra_cflags=extra_cflags,
            build_after_configure=True,
            delete_intermediates=delete_intermediates,
            static_version=static_version,
            save_temps=save_temps,
        )

    def compare_builds(
        self,
        ref1,
        ref2,
        project_names,
        toolchain=None,
        all_projects=False,
        extra_cflags=None,
        keep_temps=False,
    ):
        """Compare EC builds at two commits."""
        temp_dir = tempfile.mkdtemp(prefix="zcompare-")
        if not keep_temps:
            atexit.register(shutil.rmtree, temp_dir)
        else:
            self.logger.info("Temporary dir %s will be retained", temp_dir)

        projects = self._resolve_projects(
            project_names,
            all_projects=all_projects,
        )

        self.logger.info("Compare zephyr builds")

        cmp_builds = zmake.compare_builds.CompareBuilds(temp_dir, ref1, ref2)

        for checkout in cmp_builds.checkouts:
            self.logger.info(
                "Checkout %s: full hash %s", checkout.ref, checkout.full_ref
            )

        cmp_builds.do_checkouts(self.zephyr_base, self.module_paths)

        for checkout in cmp_builds.checkouts:
            # Now that the sources have been checked out, transform the
            # zephyr-base and module-paths to use the temporary directory
            # created by BuildInfo.
            for module_name in self.module_paths.keys():
                new_path = checkout.modules_dir / module_name
                transformed_module = {module_name: new_path}
                self.module_paths.update(transformed_module)

            self.zephyr_base = checkout.zephyr_dir

            self.logger.info("Building projects at %s", checkout.ref)
            result = self.configure(
                project_names,
                build_dir=None,
                toolchain=toolchain,
                clobber=False,
                bringup=False,
                coverage=False,
                allow_warnings=False,
                all_projects=all_projects,
                extra_cflags=extra_cflags,
                build_after_configure=True,
                delete_intermediates=False,
                static_version=True,
                save_temps=False,
                wait_for_executor=False,
            )
            if not result:
                result = self.executor.wait()
            if result:
                self.logger.error(
                    "compare-builds failed to build all projects at %s",
                    checkout.ref,
                )
                return result

        self.failed_projects = cmp_builds.check_binaries(projects)

        if len(self.failed_projects) == 0:
            self.logger.info("Zephyr compare builds successful:")
            for checkout in cmp_builds.checkouts:
                self.logger.info("   %s: %s", checkout.ref, checkout.full_ref)

        return len(self.failed_projects)

    def test(  # pylint: disable=unused-argument
        self,
        project_names,
    ):
        """Build and run tests for the specified projects.

        Using zmake to run tests is no longer supported. Use twister.
        """
        self.logger.error(
            "zmake test is deprecated. Use twister -T zephyr/test/<test_dir>."
        )

        return 0

    def testall(
        self,
    ):
        """Build and run tests for all projects.

        Using zmake to run tests is no longer supported. Use twister.
        """
        self.logger.error(
            "zmake testall is deprecated. To build all packages, use zmake build -a."
        )
        return self.test([])

    def _configure(
        self,
        project,
        build_dir: pathlib.Path,
        toolchain=None,
        build_after_configure=False,
        clobber=False,
        bringup=False,
        coverage=False,
        allow_warnings=False,
        extra_cflags=None,
        delete_intermediates=False,
        static_version=False,
        save_temps=False,
    ):
        """Set up a build directory to later be built by "zmake build"."""
        try:
            with self.jobserver.get_job():
                # Clobber build directory if requested.
                if clobber and build_dir.exists():
                    self.logger.info(
                        "Clearing build directory %s due to --clobber",
                        build_dir,
                    )
                    shutil.rmtree(build_dir)

                generated_include_dir = (build_dir / "include").resolve()
                base_config = zmake.build_config.BuildConfig(
                    cmake_defs={
                        "CMAKE_EXPORT_COMPILE_COMMANDS": "ON",
                        "DTS_ROOT": str(self.module_paths["ec"] / "zephyr"),
                        "SYSCALL_INCLUDE_DIRS": str(
                            self.module_paths["ec"]
                            / "zephyr"
                            / "include"
                            / "drivers"
                        ),
                        "USER_CACHE_DIR": str(
                            self.module_paths["ec"]
                            / "build"
                            / "zephyr"
                            / "user-cache"
                        ),
                        "ZEPHYR_BASE": str(self.zephyr_base),
                        "ZMAKE_INCLUDE_DIR": str(generated_include_dir),
                        "ZMAKE_PROJECT_NAME": project.config.project_name,
                        **(
                            {"EXTRA_EC_VERSION_FLAGS": "--static"}
                            if static_version
                            else {}
                        ),
                        **(
                            {"EXTRA_CFLAGS": "-save-temps=obj"}
                            if save_temps
                            else {}
                        ),
                    },
                )

                # Prune the module paths to just those required by the project.
                module_paths = project.prune_modules(self.module_paths)

                module_config = zmake.modules.setup_module_symlinks(
                    build_dir / "modules", module_paths
                )

                # Symlink the Zephyr base into the build directory so it can
                # be used in the build phase.
                util.update_symlink(self.zephyr_base, build_dir / "zephyr_base")

                dts_overlay_config = project.find_dts_overlays(module_paths)

                toolchain_support = project.get_toolchain(
                    module_paths, override=toolchain
                )
                toolchain_config = toolchain_support.get_build_config()

                if bringup:
                    base_config |= zmake.build_config.BuildConfig(
                        kconfig_defs={"CONFIG_PLATFORM_EC_BRINGUP": "y"}
                    )
                if coverage:
                    base_config |= zmake.build_config.BuildConfig(
                        kconfig_defs={"CONFIG_COVERAGE": "y"}
                    )
                if allow_warnings:
                    base_config |= zmake.build_config.BuildConfig(
                        cmake_defs={"ALLOW_WARNINGS": "ON"}
                    )
                if extra_cflags:
                    base_config |= zmake.build_config.BuildConfig(
                        cmake_defs={"EXTRA_CFLAGS": extra_cflags},
                    )
                if self.goma:
                    base_config |= zmake.build_config.BuildConfig(
                        cmake_defs={
                            "CMAKE_C_COMPILER_LAUNCHER": self.gomacc,
                            "CMAKE_CXX_COMPILER_LAUNCHER": self.gomacc,
                        },
                    )

                if not build_dir.exists():
                    build_dir.mkdir()
                if not generated_include_dir.exists():
                    generated_include_dir.mkdir()
                self.logger.info(
                    "Building %s in %s.", project.config.project_name, build_dir
                )
                # To reconstruct a Project object later, we need to know the
                # name and project directory.
                (build_dir / "project_name.txt").write_text(
                    project.config.project_name
                )
                util.update_symlink(
                    project.config.project_dir, build_dir / "project"
                )

                wait_funcs = []
                for build_name, build_config in project.iter_builds():
                    config: zmake.build_config.BuildConfig = (
                        base_config
                        | toolchain_config
                        | module_config
                        | dts_overlay_config
                        | build_config
                    )

                    wait_func = self.executor.append(
                        func=functools.partial(
                            self._configure_one_build,
                            config=config,
                            build_dir=build_dir,
                            build_name=build_name,
                            project=project,
                        )
                    )
                    wait_funcs.append(wait_func)
            # Outside the with...get_job above.
            for wait_func in wait_funcs:
                wait_func()

            if build_after_configure:
                self._build(
                    build_dir=build_dir,
                    project=project,
                    coverage=coverage,
                    static_version=static_version,
                    delete_intermediates=delete_intermediates,
                )
            return 0
        except Exception:
            self.failed_projects.append(project.config.project_name)
            raise

    def _configure_one_build(
        self,
        config,
        build_dir,
        build_name,
        project,
    ):
        """Run cmake and maybe ninja on one build dir."""
        with self.jobserver.get_job():
            config_json = config.as_json()
            config_json_file = build_dir / f"cfg-{build_name}.json"
            if config_json_file.is_file():
                if config_json_file.read_text() == config_json:
                    self.logger.info(
                        "Skip reconfiguring %s:%s due to previous cmake run of "
                        "equivalent configuration.  Run with --clobber if this "
                        "optimization is undesired.",
                        project.config.project_name,
                        build_name,
                    )
                    return 0
                config_json_file.unlink()

            output_dir = build_dir / "build-{}".format(build_name)
            if output_dir.exists():
                self.logger.info(
                    "Clobber %s due to configuration changes.",
                    output_dir,
                )
                shutil.rmtree(output_dir)

            self.logger.info(
                "Configuring %s:%s.",
                project.config.project_name,
                build_name,
            )

            kconfig_file = build_dir / "kconfig-{}.conf".format(build_name)
            proc = config.popen_cmake(
                self.jobserver,
                project.config.project_dir,
                output_dir,
                kconfig_file,
                stdin=subprocess.DEVNULL,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                encoding="utf-8",
                errors="replace",
            )
            job_id = "{}:{}".format(project.config.project_name, build_name)
            zmake.multiproc.LogWriter.log_output(
                self.logger,
                logging.DEBUG,
                proc.stdout,
                log_level_override_func=cmake_log_level_override,
                job_id=job_id,
            )
            zmake.multiproc.LogWriter.log_output(
                self.logger,
                logging.ERROR,
                proc.stderr,
                log_level_override_func=cmake_log_level_override,
                job_id=job_id,
            )
            if proc.wait():
                raise OSError(get_process_failure_msg(proc))
            config_json_file.write_text(config_json)
            return 0

    def _build(
        self,
        build_dir,
        project: zmake.project.Project,
        coverage=False,
        static_version=False,
        delete_intermediates=False,
    ):
        """Build a pre-configured build directory."""

        with self.jobserver.get_job():
            dirs: Dict[str, pathlib.Path] = {}

            build_dir = build_dir.resolve()

            # Compute the version string.
            version_string = zmake.version.get_version_string(
                project.config.project_name,
                build_dir / "zephyr_base",
                zmake.modules.locate_from_directory(build_dir / "modules"),
                static=static_version,
            )

            # The version header needs to generated during the build phase
            # instead of configure, as the tree may have changed since
            # configure was run.
            zmake.version.write_version_header(
                version_string,
                build_dir / "include" / "ec_version.h",
                "zmake",
                static=static_version,
            )

            gcov = "gcov.sh-not-found"
            wait_funcs = []
            for build_name, _ in project.iter_builds():
                dirs[build_name] = build_dir / "build-{}".format(build_name)
                gcov = dirs[build_name] / "gcov.sh"
                wait_func = self.executor.append(
                    func=functools.partial(
                        self._build_one_dir,
                        build_name=build_name,
                        dirs=dirs,
                        coverage=coverage,
                        project=project,
                    )
                )
                wait_funcs.append(wait_func)
        # Outside the with...get_job above.
        for wait_func in wait_funcs:
            wait_func()

        with self.jobserver.get_job():
            # Run the packer.
            packer_work_dir = build_dir / "packer"
            output_dir = build_dir / "output"
            for newdir in output_dir, packer_work_dir:
                if not newdir.exists():
                    newdir.mkdir()

            # For non-tests, they won't link with coverage, so don't pack the
            # firmware. Also generate a lcov file.
            if coverage and not project.config.is_test:
                self._run_lcov(
                    build_dir,
                    output_dir / "zephyr.info",
                    initial=True,
                    gcov=gcov,
                )
            else:
                for output_file, output_name in project.packer.pack_firmware(
                    packer_work_dir,
                    self.jobserver,
                    dirs,
                    version_string=version_string,
                ):
                    shutil.copy2(output_file, output_dir / output_name)
                    self.logger.debug("Output file '%s' created.", output_file)

            if delete_intermediates:
                outdir = build_dir / "output"
                for child in build_dir.iterdir():
                    if child != outdir:
                        logging.debug("Deleting %s", child)
                        if not child.is_symlink() and child.is_dir():
                            shutil.rmtree(child)
                        else:
                            child.unlink()
            return 0

    def _build_one_dir(self, build_name, dirs, coverage, project):
        """Builds one sub-dir of a configured project (build-ro, etc)."""

        with self.jobserver.get_job():
            cmd = ["/usr/bin/ninja", "-C", dirs[build_name].as_posix()]
            if self.goma:
                # Go nuts ninja, goma does the heavy lifting!
                cmd.append("-j1024")
            elif self._sequential:
                cmd.append("-j1")
            # Only tests will actually build with coverage enabled.
            if coverage and not project.config.is_test:
                cmd.append("all.libraries")
            self.logger.info(
                "Building %s:%s: %s",
                project.config.project_name,
                build_name,
                util.repr_command(cmd),
            )
            proc = self.jobserver.popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                encoding="utf-8",
                errors="replace",
                # TODO(b/239619222): Filter os.environ for ninja.
                env=os.environ,
            )
            job_id = "{}:{}".format(project.config.project_name, build_name)
            dirs[build_name].mkdir(parents=True, exist_ok=True)
            build_log = open(  # pylint:disable=consider-using-with
                dirs[build_name] / "build.log",
                "w",
            )
            out = zmake.multiproc.LogWriter.log_output(
                logger=self.logger,
                log_level=logging.INFO,
                file_descriptor=proc.stdout,
                log_level_override_func=ninja_stdout_log_level_override,
                job_id=job_id,
                tee_output=build_log,
            )
            err = zmake.multiproc.LogWriter.log_output(
                self.logger,
                logging.ERROR,
                proc.stderr,
                job_id=job_id,
            )

            if proc.wait():
                raise OSError(get_process_failure_msg(proc))

            # Let all output be produced before exiting
            out.wait()
            err.wait()
            return 0

    def _run_lcov(
        self,
        build_dir,
        lcov_file,
        initial=False,
        gcov: Union[os.PathLike, str] = "",
    ):
        gcov = os.path.abspath(gcov)
        if initial:
            self.logger.info("Running (initial) lcov on %s.", build_dir)
        else:
            self.logger.info("Running lcov on %s.", build_dir)
        cmd = [
            "/usr/bin/lcov",
            "--gcov-tool",
            gcov,
            "-q",
            "-o",
            "-",
            "-c",
            "-d",
            build_dir,
            "-t",
            build_dir.stem,
            "--rc",
            "lcov_branch_coverage=1",
        ]
        if initial:
            cmd += ["-i"]
        proc = self.jobserver.popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            encoding="utf-8",
            errors="replace",
        )
        zmake.multiproc.LogWriter.log_output(
            self.logger,
            logging.WARNING,
            proc.stderr,
            job_id="{}-lcov".format(build_dir),
        )

        with open(lcov_file, "w") as outfile:
            for line in proc.stdout:
                if line.startswith("SF:"):
                    path = line[3:].rstrip()
                    outfile.write("SF:%s\n" % os.path.realpath(path))
                else:
                    outfile.write(line)
        if proc.wait():
            raise OSError(get_process_failure_msg(proc))

        return 0

    def _merge_lcov_files(self, projects, build_dir, output_file):
        all_lcov_files = []
        for project in projects:
            project_build_dir = (
                pathlib.Path(build_dir) / project.config.project_name
            )
            all_lcov_files.append(project_build_dir / "output" / "zephyr.info")
        # Merge info files into a single lcov.info
        self.logger.info("Merging coverage data into %s.", output_file)
        cmd = [
            "/usr/bin/lcov",
            "-o",
            output_file,
            "--rc",
            "lcov_branch_coverage=1",
        ]
        for info in all_lcov_files:
            cmd += ["-a", info]
        proc = self.jobserver.popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            encoding="utf-8",
            errors="replace",
        )
        zmake.multiproc.LogWriter.log_output(
            self.logger, logging.ERROR, proc.stderr, job_id="lcov"
        )
        zmake.multiproc.LogWriter.log_output(
            self.logger, logging.DEBUG, proc.stdout, job_id="lcov"
        )
        if proc.wait():
            raise OSError(get_process_failure_msg(proc))
        return 0

    def list_projects(self, fmt, search_dir):
        """List project names known to zmake on stdout.

        Args:
            fmt: The formatting string to print projects with.
            search_dir: Directory to start the search for
                BUILD.py files at.
        """
        if not search_dir:
            search_dir = self.module_paths["ec"] / "zephyr"

        for project in zmake.project.find_projects(search_dir).values():
            print(fmt.format(config=project.config), end="")

        return 0

    def generate_readme(self, output_file, diff=False):
        """Re-generate the auto-generated README file.

        Args:
            output_file: A pathlib.Path; to be written only if changed.
            diff: Instead of writing out, report the diff.
        """
        expected_contents = zmake.generate_readme.generate_readme()

        if output_file.is_file():
            current_contents = output_file.read_text()
            if expected_contents == current_contents:
                return 0
            if diff:
                self.logger.error(
                    "The auto-generated README.md differs from the expected contents:"
                )
                for line in difflib.unified_diff(
                    current_contents.splitlines(keepends=True),
                    expected_contents.splitlines(keepends=True),
                    str(output_file),
                ):
                    self.logger.error(line.rstrip())
                self.logger.error('Run "zmake generate-readme" to fix this.')
                return 1

        if diff:
            self.logger.error(
                'The README.md file does not exist.  Run "zmake generate-readme".'
            )
            return 1

        output_file.write_text(expected_contents)
        return 0


text:
<!--
  ~ Copyright (c) 2008-2019 Haulmont.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<window xmlns="http://schemas.haulmont.com/cuba/screen/window.xsd">
    <data>
        <collection id="customersSystemDc"
                    class="com.haulmont.cuba.web.testmodel.sales.Customer"
                    view="customer-with-systems">
            <loader id="customersLd">
                <query><![CDATA[select e from test$Customer e]]></query>
            </loader>
        </collection>

        <collection id="customersWithoutSystemDc"
                    class="com.haulmont.cuba.web.testmodel.sales.Customer"
                    view="customer-without-systems">
            <loader id="customersLd">
                <query><![CDATA[select e from test$Customer e]]></query>
            </loader>
        </collection>

        <collection id="customersWithoutViewDc"
                    class="com.haulmont.cuba.web.testmodel.sales.Customer">
            <loader id="customersLd">
                <query><![CDATA[select e from test$Customer e]]></query>
            </loader>
        </collection>

        <collection id="goodsInfoDc"
                    class="com.haulmont.cuba.web.testmodel.sample.GoodInfo"/>
    </data>

    <layout spacing="true">
        <dataGrid id="dataGridAll" width="100%" height="100%" dataContainer="customersWithoutSystemDc">
            <columns includeAll="true"/>
        </dataGrid>

        <dataGrid id="dataGridSystem" width="100%" height="100%" dataContainer="customersSystemDc">
            <columns includeAll="true"/>
        </dataGrid>

        <groupTable id="dataGridExclude" width="100%" height="100%" dataContainer="customersSystemDc">
            <columns includeAll="true" exclude="createTs, address"/>
        </groupTable>

        <dataGrid id="dataGridEmb" width="100%" height="100%" dataContainer="customersSystemDc">
            <columns includeAll="true">
                <column property="address.city"/>
                <column property="address.zip"/>
            </columns>
        </dataGrid>

        <dataGrid id="dataGridOverriding" width="100%" height="100%" dataContainer="customersSystemDc">
            <columns includeAll="true">
                <column property="name" sortable="false"/>
            </columns>
        </dataGrid>

        <dataGrid id="dataGridNonPersist" width="100%" height="100%" dataContainer="goodsInfoDc">
            <columns includeAll="true" exclude="isFragile"/>
        </dataGrid>

        <dataGrid id="dataGridWithoutView" width="100%" height="100%" dataContainer="customersWithoutViewDc">
            <columns includeAll="true"/>
        </dataGrid>
    </layout>
</window>