text:
<?php
/**
 * This is a Model class for the Contract Component
 *
 * Created By : AASSOU Abdelilah
 * Date       : 03/11/2015
 * Github     : aassou
 * Twitter    : @a_aassou
 * email      : aassou.abdelilah@gmail.com
 * Description: This controller is used to create a new contract based on the customer data
 *              received form the clients-add.php url.
 */
    //classes loading begin
    function classLoad ($myClass) {
        if(file_exists('../model/'.$myClass.'.php')){
            include('../model/'.$myClass.'.php');
        }
        elseif(file_exists('../controller/'.$myClass.'.php')){
            include('../controller/'.$myClass.'.php');
        }
    }
    spl_autoload_register("classLoad");
    include('../config/config.php');
    include('../lib/image-processing.php');
    //classes loading end
    session_start();

    //post input processing
    //the action input precise which action the controller is going to prossed,
    //add action, update action or delete action
    $action = htmlentities($_POST['action']);
    $idProjet = htmlentities($_POST['idProjet']);
    //In this session variable we put all the POST, to get it in the contrats-add file
    //In case of error, and this help the user to do not put again what he filled out.
    $_SESSION['contrat-form-data'] = $_POST;
    //If we get to this current ContratActionController through ClientActionController,
    //which means, that the client data are valid, so we need to destroy the session
    //"myFormData", that stores the client data form inputs
    if( isset($_SESSION['myFormData']) ){
        unset($_SESSION['myFormData']);
    }
    //This var contains result message of CRUD action and the redirection url link
    $actionMessage = "";
    $typeMessage = "";
    $redirectLink = "";
    //class manager
    $clientManager = new ClientManager($pdo);
    $contratManager = new ContratManager($pdo);
    $contratCasLibreManager = new ContratCasLibreManager($pdo);
    $reglementPrevuManager = new ReglementPrevuManager($pdo);
    $projetManager = new ProjetManager($pdo);
    //The History Component is used in all ActionControllers to mention a historical version of each action
    $historyManager = new HistoryManager($pdo);
    //process starts
    $nomProjet = $projetManager->getProjetById($idProjet)->nom();
    //Action Add Processing Begin
    if($action == "add"){
        $codeClient = $_POST['codeClient'];
        //post input validation
        if( !empty($_POST['typeBien']) and !empty($_POST['prixNegocie']) and !empty($_POST['numero'])
         and !empty($_POST['bien']) and !empty($_POST['dateCreation']) and !empty($_POST['avance'])
         and !empty($_POST['modePaiement']) and !empty($_POST['dureePaiement']) and !empty($_POST['nombreMois'])
         and !empty($_POST['echeance']) ){
            if( !empty($_POST['prixNegocie']) ){
                $reference = 'C'.date('Ymd-his');
                $prixNegocie = htmlentities($_POST['prixNegocie']);
                $prixNegocieArabe = htmlentities($_POST['prixNegocieArabe']);
                $numero = htmlentities($_POST['numero']);
                $typeBien = htmlentities($_POST['typeBien']);
                $idBien = htmlentities($_POST['bien']);
                $dateCreation = htmlentities($_POST['dateCreation']);
                $avance = htmlentities($_POST['avance']);
                $avanceArabe = htmlentities($_POST['avanceArabe']);
                $modePaiement = htmlentities($_POST['modePaiement']);
                $dureePaiement = htmlentities($_POST['dureePaiement']);
                $nombreMois = htmlentities($_POST['nombreMois']);
                $echeance = htmlentities($_POST['echeance']);
                $idClient = htmlentities($_POST['idClient']);
                $codeContrat = uniqid().date('YmdHis');
                $societeArabe = htmlentities($_POST['societeArabe']);
                $etatBienArabe = htmlentities($_POST['etatBienArabe']);
                $facadeArabe = htmlentities($_POST['facadeArabe']);
                $articlesArabes = htmlentities($_POST['articlesArabes']);
                $created = date('Y-m-d h:i:s');
                $createdBy = $_SESSION['userMerlaTrav']->login();
                $numeroCheque = '0';
                if( isset($_POST['numeroCheque']) ){
                    $numeroCheque = htmlentities($_POST['numeroCheque']);
                }
                //SET NOTE-CLIENT SECTION BEGIN
                $note = "";
                $noteImage = "";
                if ( isset($_POST['show-note-client']) ) {
                    $note = htmlentities($_POST['note']);
                    if(file_exists($_FILES['note-client-image']['tmp_name']) || is_uploaded_file($_FILES['note-client-image']['tmp_name'])) {
                        $noteImage = imageProcessing($_FILES['note-client-image'], '/pieces/pieces_notes_clients/');
                    }
                }
                //SET NOTE-CLIENT SECTION END
                //set the datePrevu for our object end
                //CAS LIBRE PROCESSING BEGIN
                if ( $echeance != 1 ) {
                    if ( isset($_POST['show-cas-libre']) ) {
                        $dates = array();
                        $montants = array();
                        $observations = array();
                        for ( $i=1; $i<11; $i++ ) {
                            if (
                                ( isset($_POST['cas-libre-date'.$i]) and !empty($_POST['cas-libre-date'.$i]) )
                                and isset($_POST['cas-libre-montant'.$i]) and !empty($_POST['cas-libre-montant'.$i]) ) {
                                $dates[$i] = htmlentities($_POST['cas-libre-date'.$i]);
                                $montants[$i] = htmlentities($_POST['cas-libre-montant'.$i]);
                                if ( isset($_POST['cas-libre-observation'.$i]) ) {
                                    $observations[$i] = htmlentities($_POST['cas-libre-observation'.$i]);
                                }
                                $contratCasLibreManager->add(
                                    new ContratCasLibre(
                                        array(
                                            'date' => $dates[$i],
                                            'montant' => $montants[$i],
                                            'observation' => $observations[$i],
                                            'status' => 0,
                                            'codeContrat' => $codeContrat,
                                            'created' => $created,
                                            'createdBy' => $createdBy
                                        )
                                    )
                                );
                            }
                            /*if ( isset($_POST['cas-libre-montant'.$i]) ) {
                                $montants[$i] = htmlentities($_POST['cas-libre-montant'.$i]);
                            }
                            if ( isset($_POST['cas-libre-observation'.$i]) ) {
                                $observations[$i] = htmlentities($_POST['cas-libre-observation'.$i]);
                            }*/
                        }
                    }
                    else {
                        //set the datePrevu for our object begin
                        $condition = ceil( floatval($dureePaiement)/floatval($nombreMois) );
                        for ( $i=1; $i <= $condition; $i++ ) {
                            $monthsNumber = "+".$nombreMois*$i." months";
                            $datePrevu = date('Y-m-d', strtotime($monthsNumber, strtotime($dateCreation)));
                            $reglementPrevuManager->add(
                                new ReglementPrevu(
                                    array(
                                        'datePrevu' => $datePrevu,
                                        'codeContrat' => $codeContrat,
                                        'status' => 0,
                                        'created' => $created,
                                        'createdBy' =>$createdBy
                                    )
                                )
                            );
                        }
                    }
                }
                //else we have to put here our datePrevu processing
                //CAS LIBRE PROCESSING END
                //COMMISSION PROCESSING BEGIN
                if ( isset($_POST['show-commission']) ) {
                    $commissionnaire = htmlentities($_POST['commissionnaire']);
                    $montant = htmlentities($_POST['montant']);
                    $titre = htmlentities($_POST['titre']);
                    $etat = htmlentities($_POST['etat']);
                    //load class manager
                    $commissionManager = new CommissionManager($pdo);
                    //save the commission
                    $commission =
                        new Commission(
                            array('titre' => $titre,
                                'commissionnaire' => $commissionnaire,
                                'montant' => $montant,
                                'date' => $dateCreation,
                                'etat' => $etat,
                                'codeContrat' => $codeContrat,
                                'created' => $created,
                                'createdBy' => $createdBy
                            ));
                    $commissionManager->add($commission);
                }
                //COMMISSION PROCESSING END
                //create the contract object
                $contrat =
                new Contrat(
                array('reference' => $reference, 'numero' => $numero, 'dateCreation' => $dateCreation,
                'prixVente' => $prixNegocie, 'prixVenteArabe' => $prixNegocieArabe, 'avance' => $avance,
                'avanceArabe' => $avanceArabe, 'modePaiement' => $modePaiement, 'dureePaiement' => $dureePaiement,
                'nombreMois' => $nombreMois, 'echeance' => $echeance, 'note' => $note, 'imageNote' => $noteImage, 'idClient' => $idClient,
                'idProjet' => $idProjet, 'idBien' => $idBien, 'typeBien' => $typeBien, 'code' => $codeContrat,
                'numeroCheque' => $numeroCheque, 'societeArabe' => $societeArabe, 'etatBienArabe' => $etatBienArabe ,
                'facadeArabe' => $facadeArabe, 'articlesArabes' => $articlesArabes, 'created' => $created, 'createdBy' => $createdBy));
                //adding the contract object to our database
                $contratManager->add($contrat);
                //add history data to db
                $nomClient = $clientManager->getClientById($idClient)->nom();
                $history = new History(array(
                    'action' => "Ajout",
                    'target' => "Table des contrats",
                    'description' => "Ajout du contrat numéro : ".$numero.", client : ".$nomClient.", ".$typeBien." : ".$idBien.", prix : ".$prixNegocie." - Projet : ".$nomProjet,
                    'created' => $created,
                    'createdBy' => $createdBy
                ));
                //add it to db
                $historyManager->add($history);
                //in the next if elseif statement, we test the type of the property to change its status
                //and its price
                if($typeBien=="appartement"){
                    $appartementManager = new AppartementManager($pdo);
                    $appartementManager->changeStatus($idBien, "Vendu");
                    $appartementManager->updatePrix($prixNegocie, $idBien);
                }
                else if($typeBien=="localCommercial"){
                    $locauxManager = new LocauxManager($pdo);
                    $locauxManager->changeStatus($idBien, "Vendu");
                    $locauxManager->updatePrix($prixNegocie, $idBien);
                }
                //add contract note into db and show it in the dashboard
                $notesClientManager = new NotesClientManager($pdo);
                $notesClient = new NotesClient(array('note' => $note, 'created' => date('Y-m-d'),
                'idProjet' => $idProjet, 'codeContrat' => $codeContrat));
                $notesClientManager->add($notesClient);
                $actionMessage = "Opération valide : Contrat Client ajouté(e) avec succès.";
                $typeMessage = "success";
                $redirectLink = 'Location:../view/contrat.php?codeContrat='.$codeContrat;
            }
        }
        else{
            $actionMessage = "Erreur Création Contrat : Veuillez vérifier les champs saisies.";
            $typeMessage = "error";
            $redirectLink = 'Location:../view/contrats-add.php?idProjet='.$idProjet.'&codeClient='.$codeClient;
        }
    }
    //Action Add Processing End
    //Action Update Processing Begin
    else if($action == "update"){
        $idContrat = htmlentities($_POST['idContrat']);
        $codeContrat = htmlentities($_POST['codeContrat']);
        if(!empty($_POST['prixVente'])){
            $prixVente = htmlentities($_POST['prixVente']);
            $prixVenteArabe = htmlentities($_POST['prixVenteArabe']);
            $numero = htmlentities($_POST['numero']);
            $numeroCheque = htmlentities($_POST['numeroCheque']);
            $dateCreation = htmlentities($_POST['dateCreation']);
            $avance = htmlentities($_POST['avance']);
            $avanceArabe = htmlentities($_POST['avanceArabe']);
            $modePaiement = htmlentities($_POST['modePaiement']);
            $dureePaiement = htmlentities($_POST['dureePaiement']);
            $nombreMois = htmlentities($_POST['nombreMois']);
            $echeance = htmlentities($_POST['echeance']);
            $note = htmlentities($_POST['note']);
            $societeArabe = htmlentities($_POST['societeArabe']);
            $etatBienArabe = htmlentities($_POST['etatBienArabe']);
            $facadeArabe = htmlentities($_POST['facadeArabe']);
            $articlesArabes = htmlentities($_POST['articlesArabes']);
            $updatedBy = $_SESSION['userMerlaTrav']->login();
            $updated = date('Y-m-d h:i:s');
            //create classes managers
            $locauxManager = new LocauxManager($pdo);
            $appartementManager = new AppartementManager($pdo);
            //create classes
            //this contrat object is used to test the type of a property based of
            //the id of the current contrat objet
            $contrat = $contratManager->getContratById($idContrat);
            $newContrat =
            new Contrat(array('id' => $idContrat, 'numero' => $numero, 'dateCreation' => $dateCreation,
            'prixVente' => $prixVente, 'avance' => $avance, 'prixVenteArabe' => $prixVenteArabe,
            'avanceArabe' => $avanceArabe, 'modePaiement' => $modePaiement,'nombreMois' => $nombreMois,
            'dureePaiement' => $dureePaiement, 'echeance' => $echeance, 'numeroCheque' => $numeroCheque,
            'note' => $note, 'societeArabe' => $societeArabe, 'etatBienArabe' => $etatBienArabe,
            'facadeArabe' => $facadeArabe, 'articlesArabes' => $articlesArabes, 'updated' => $updated, 'updatedBy' => $updatedBy));
            //begin processing
            $contratManager->update($newContrat);
            //Update The ReglementsPrevus Table
            //We should get the number of "ReglementPrevu" to begin our process
            $createdBy = $_SESSION['userMerlaTrav']->login();
            $created = date('Y-m-d h:i:s');
            $reglementPrevuNumber  = $reglementPrevuManager->getReglementNumberByCodeContrat($codeContrat);
            if ( $reglementPrevuNumber >= 1 ) {
                $reglementPrevuManager->deleteByCodeContrat($codeContrat);
                //set the datePrevu for our object begin
                $condition = ceil( floatval($dureePaiement)/floatval($nombreMois) );
                for ( $i=1; $i <= $condition; $i++ ) {
                    $monthsNumber = "+".$nombreMois*$i." months";
                    $datePrevu = date('Y-m-d', strtotime($monthsNumber, strtotime($dateCreation)));
                    $reglementPrevuManager->add(
                        new ReglementPrevu(
                            array(
                                'datePrevu' => $datePrevu,
                                'codeContrat' => $codeContrat,
                                'status' => 0,
                                'created' => $created,
                                'createdBy' =>$createdBy
                            )
                        )
                    );
                }
                //set the datePrevu for our object end
            }
            //add history data to db
            $history = new History(array(
                'action' => "Modification",
                'target' => "Table des contrats",
                'description' => "Modification du contrat dont l'identifiant est : ".$idContrat." - Projet : ".$nomProjet,
                'created' => $created,
                'createdBy' => $createdBy
            ));
            //add it to db
            $historyManager->add($history);
            //update client's note
            $notesClientManager = new NotesClientManager($pdo);
            $notesClient = new NotesClient(array('note' => $note, 'created' => date('Y-m-d'),
            'idProjet' => $contrat->idProjet(), 'codeContrat' => $contrat->code()));
            $notesClientManager->add($notesClient);
            //test if the typeBien radio box is checked
            //if yes then we use our contrat object mentioned earlier
            if( isset($_POST['typeBien']) ){
                $typeBien = $_POST['typeBien'];
                $idBien = $_POST['bien'];
                //change status of the old contrat Bien from Réservé to Disponible
                if( $contrat->typeBien()=="appartement" ){
                    $appartementManager->changeStatus($contrat->idBien(), "Disponible");
                }
                else if( $contrat->typeBien()=="localCommercial" ){
                    $locauxManager->changeStatus($contrat->idBien(), "Disponible");
                }
                //change status of the new contrat Bien from Disponible to Vendu
                //and change the property price to the price of sold
                if( $typeBien=="appartement" ){
                    $contratManager->changerBien($idContrat, $idBien, $typeBien);
                    $appartementManager->changeStatus($idBien, "Vendu");
                    $appartementManager->updatePrix($prixVente, $idBien);
                }
                else if( $typeBien=="localCommercial" ){
                    $contratManager->changerBien($idContrat, $idBien, $typeBien);
                    $locauxManager->changeStatus($idBien, "Vendu");
                    $locauxManager->updatePrix($prixVente, $idBien);
                }
            }
            $actionMessage = "Opération Valide : Contrat modifié(e) avec succès.";
            $typeMessage = "success";
            $redirectLink = "Location:../view/contrat.php?codeContrat=".$codeContrat;
            if ( isset($_POST['source']) and $_POST['source'] == "clients-list" ) {
                $redirectLink = "Location:../view/clients-list.php";
            }
        }
        else{
            $actionMessage = "Erreur Modification Client : Vous devez remplir le champ <Prix de vente>.";
            $typeMessage = "error";
            $redirectLink = "Location:../view/contrat.php?codeContrat=".$codeContrat;
        }
    }
    //Action Update Processing End
    //Action UpdateImageNote Processing Begin
    else if ($action == "updateImageNote") {
        $codeContrat = htmlentities($_POST['codeContrat']);
        $imageNote = "";
        $idContrat = htmlentities($_POST['idContrat']);
        if(file_exists($_FILES['note-client-image']['tmp_name']) || is_uploaded_file($_FILES['note-client-image']['tmp_name'])) {
            $imageNote = imageProcessing($_FILES['note-client-image'], '/pieces/pieces_notes_clients/');
            $contratManager->updateImageNote($idContrat, $imageNote);
            $actionMessage = "Opération valide : Image Note est modifiée avec succès.";
            $typeMessage = "success";
        }
        else{
            $actionMessage = "Erreur Modification Image Note : Vous devez séléctionner un fichier.";
            $typeMessage = "error";
        }
        $redirectLink = "Location:../view/contrat.php?codeContrat=".$codeContrat."&idProjet=".$idProjet;
        if ( isset($_POST['source']) and $_POST['source'] == "clients-modification" ) {
            $redirectLink = "Location:../view/clients-modification.php";
        }
    }
    //Action UpdateImageNote Processing END
    //Action UpdateObservation Processing Begin
    else if($action=="updateObservation"){
        $idContrat = htmlentities($_POST['idContrat']);
        $codeContrat = htmlentities($_POST['codeContrat']);
        $observation = htmlentities($_POST['observation']);
        $contratManager->updateObservationClient($idContrat, $observation);
        //after the delete of our contract, we should change the property status to "Disponible"
        $actionMessage = "Opération Valide : Observation ajouté(e) avec succès.";
        $typeMessage = "success";
        $redirectLink = "Location:../view/contrat.php?codeContrat=$codeContrat";
    }
    //Action UpdateObservation Processing End
    //Action Delete Processing Begin
    else if($action=="delete"){
        $idContrat = $_POST['idContrat'];
        $contratManager->hide($idContrat);
        //add history data to db
        $createdBy = $_SESSION['userMerlaTrav']->login();
        $created = date('Y-m-d h:i:s');
        $history = new History(array(
            'action' => "Suppression",
            'target' => "Table des contrats",
            'description' => "Suppression du contrat dont l'identifiant est : ".$idContrat." - Projet : ".$nomProjet,
            'created' => $created,
            'createdBy' => $createdBy
        ));
        //add it to db
        $historyManager->add($history);
        //after the delete of our contract, we should change the property status to "Disponible"
        $actionMessage = "Opération Valide : Contrat Supprimé(e) avec succès.";
        $typeMessage = "success";
        $redirectLink = "Location:../view/contrats-desistes-list.php?idProjet=".$idProjet;
    }
    //Action Delete Processing End
    //Action Desister Processing Begin
    else if ( $action == "desister" ) {
        $idContrat  = $_POST['idContrat'];
        $contrat = $contratManager->getContratById($idContrat);
        //Change status of the old contrat Bien from "Vendu" to "Disponible"
        if( $contrat->typeBien()=="appartement" ){
            $appartementManager = new AppartementManager($pdo);
            $appartementManager->changeStatus($contrat->idBien(), "Disponible");
        }
        else if( $contrat->typeBien()=="localCommercial" ){
            $locauxManager = new LocauxManager($pdo);
            $locauxManager->changeStatus($contrat->idBien(), "Disponible");
        }
        $contratManager->desisterContrat($idContrat);
        //add history data to db
        $createdBy = $_SESSION['userMerlaTrav']->login();
        $created = date('Y-m-d h:i:s');
        $history = new History(array(
            'action' => "Désistement",
            'target' => "Table des contrats",
            'description' => "Désistement du contrat dont l'identifiant est : ".$idContrat." - Projet : ".$nomProjet,
            'created' => $created,
            'createdBy' => $createdBy
        ));
        //add it to db
        $historyManager->add($history);
        $actionMessage = "Opération valide : Le contrat est désisté avec succès.";
        $typeMessage = "success";
        $redirectLink = 'Location:../view/contrats-list.php?idProjet='.$idProjet;
        if( isset($_POST["source"]) and $_POST["source"] == "clients-search" ){
            $redirectLink = 'Location:../view/clients-search.php';
        }
    }
    //Action Desister Processing End
    //Action Activer Processing Begin
    else if ( $action == "activer" ) {
        $idContrat  = $_POST['idContrat'];
        //create classes
        $contrat = $contratManager->getContratById($idContrat);
        //test property type to decide which action to do
        if( $contrat->typeBien() == "appartement" ){
            $appartementManager = new AppartementManager($pdo);
            if( $appartementManager->getAppartementById($contrat->idBien())->status() == "Disponible" ){
                $appartementManager->changeStatus($contrat->idBien(), "Vendu");
                $contratManager->activerContrat($idContrat);
                //add history data to db
                $createdBy = $_SESSION['userMerlaTrav']->login();
                $created = date('Y-m-d h:i:s');
                $history = new History(array(
                    'action' => "Activation",
                    'target' => "Table des contrats",
                    'description' => "Activer un contrat",
                    'created' => $created,
                    'createdBy' => $createdBy
                ));
                //add it to db
                $historyManager->add($history);
                $actionMessage = "Opération valide : Le contrat est activé avec succès.";
                $typeMessage = "success";
            }
            else{
                $actionMessage = "Erreur Activation Contrat : Le bien est déjà réservé par un autre client.";
                $typeMessage = "error";
            }
        }
        else if( $contrat->typeBien()=="localCommercial" ){
            $locauxManager = new LocauxManager($pdo);
            if( $locauxManager->getLocauxById($contrat->idBien())->status()=="Disponible" ){
                $locauxManager->changeStatus($contrat->idBien(), "Vendu");
                $contratManager->activerContrat($idContrat);
                //add history data to db
                $createdBy = $_SESSION['userMerlaTrav']->login();
                $created = date('Y-m-d h:i:s');
                $history = new History(array(
                    'action' => "Activation",
                    'target' => "Table des contrats",
                    'description' => "Activation du contrat dont l'identifiant est : ".$idContrat." - Projet : ".$nomProjet,
                    'created' => $created,
                    'createdBy' => $createdBy
                ));
                //add it to db
                $historyManager->add($history);
                $actionMessage = "Opération valide : Le contrat est activé avec succès.";
                $typeMessage = "success";
            }
            else{
                $actionMessage = "Erreur Activation Contrat : Le bien est déjà réservé par un autre client.";
                $typeMessage = "error";
            }
        }
        //set the redirect link
        $redirectLink = 'Location:../view/contrats-desistes-list.php?idProjet='.$idProjet;
        if( isset($_POST["source"]) and $_POST["source"] == "clients-search" ){
            $redirectLink = 'Location:../view/clients-search.php';
        }
    }
    //Action Activer Processing End
    //Action Update Revendre Processing Begin
    else if ( $action == "revendre" ) {
        $idContrat  = $_POST['idContrat'];
        $idBien = $_POST['idBien'];
        $typeBien = $_POST['typeBien'];
        $montantRevente = $_POST['montantRevente'];
        if ( $typeBien == "appartement" ) {
            $appartementManager = new AppartementManager($pdo);
            $appartementManager->updateMontantRevente($montantRevente, $idBien);
        }
        else {
            $locauxManager = new LocauxManager($pdo);
            $locauxManager->updateMontantRevente($montantRevente, $idBien);
        }
        $contrat = $contratManager->getContratById($idContrat);
        //Change status of the old contrat Bien from "Vendu" to "Disponible"
        if( $contrat->revendre() == 0 ){
            $contratManager->updateRevendre($idContrat, 1);
        }
        else if( $contrat->revendre() == 1 ){
            $contratManager->updateRevendre($idContrat, 0);
        }
        //add history data to db
        $createdBy = $_SESSION['userMerlaTrav']->login();
        $created = date('Y-m-d h:i:s');
        $history = new History(array(
            'action' => "Modification Status Revendre",
            'target' => "Table des contrats",
            'description' => "Modification de status Revendement du contrat dont l'identifiant est : ".$idContrat." - Projet : ".$nomProjet,
            'created' => $created,
            'createdBy' => $createdBy
        ));
        //add it to db
        $historyManager->add($history);
        $actionMessage = "Opération valide : Le contrat est modifié avec succès.";
        $typeMessage = "success";
        $redirectLink = 'Location:../view/contrats-list.php?idProjet='.$idProjet;
        if( isset($_POST["source"]) and $_POST["source"] == "clients-search" ){
            $redirectLink = 'Location:../view/clients-search.php';
        }
    }
    //Action Update Revendre Processing End
    $_SESSION['contrat-action-message'] = $actionMessage;
    $_SESSION['contrat-type-message'] = $typeMessage;
    header($redirectLink);


text:
package org.n52.iceland.ogc.ows;

import java.util.Collection;
import java.util.Set;

import com.google.common.collect.Sets;

/**
 * Class represents an OWS AllowedValues Range element
 *
 * @author Carsten Hollmann
 *
 * @since 1.0.0
 *
 */
public class OwsAllowedValuesRange implements OwsAllowedValues {

    private Set<OwsRange> values = Sets.newHashSet();

    /**
     * constructor
     *
     * @param value
     */
    public OwsAllowedValuesRange(OwsRange value) {
        addValue(value);
    }

    /**
     * constructor
     *
     * @param values
     */
    public OwsAllowedValuesRange(Collection<OwsRange> values) {
        setValues(values);
    }

    /**
     * @return the values
     */
    public Set<OwsRange> getValues() {
        return values;
    }

    /**
     * @param value
     *            the value to add
     */
    public void addValue(OwsRange value) {
        getValues().add(value);
    }

    /**
     * @param values
     *            the values to add
     */
    public void addValues(Collection<OwsRange> values) {
        getValues().addAll(values);
    }

    /**
     * @param values
     *            the values to set
     */
    private void setValues(Collection<OwsRange> values) {
        this.values = Sets.newHashSet(values);
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace WeekendRoguelike.DungeonGenerator.DataTypes
{
    public class Door
    {
        #region Private Fields

        private readonly Displacement direction;
        private readonly Displacement position;
        private bool filled = false;

        #endregion Private Fields

        #region Public Constructors

        public Door(Displacement position, Displacement direction, bool filled = false)
        {
            this.position = position;
            this.direction = direction;
            this.filled = filled;
        }

        #endregion Public Constructors

        #region Public Properties

        public Displacement Direction => direction;
        public bool Filled { get => filled; }
        public Displacement Position => position;

        #endregion Public Properties

        #region Public Methods

        public void Fill()
        {
            filled = true;
        }

        #endregion Public Methods
    }
}


text:
import type {RetryFunction} from './options.js';

type Returns<T extends (...args: any) => unknown, V> = (...args: Parameters<T>) => V;

const calculateRetryDelay: Returns<RetryFunction, number> = ({
	attemptCount,
	retryOptions,
	error,
	retryAfter,
	computedValue,
}) => {
	if (error.name === 'RetryError') {
		return 1;
	}

	if (attemptCount > retryOptions.limit) {
		return 0;
	}

	const hasMethod = retryOptions.methods.includes(error.options.method);
	const hasErrorCode = retryOptions.errorCodes.includes(error.code);
	const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode);
	if (!hasMethod || (!hasErrorCode && !hasStatusCode)) {
		return 0;
	}

	if (error.response) {
		if (retryAfter) {
			// In this case `computedValue` is `options.request.timeout`
			if (retryAfter > computedValue) {
				return 0;
			}

			return retryAfter;
		}

		if (error.response.statusCode === 413) {
			return 0;
		}
	}

	const noise = Math.random() * retryOptions.noise;
	return Math.min(((2 ** (attemptCount - 1)) * 1000), retryOptions.backoffLimit) + noise;
};

export default calculateRetryDelay;


text:
const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.setPublicPath('public')
    .setResourceRoot('../') // Turns assets paths in css relative to css file
    // .options({
    //     processCssUrls: false,
    // })
    .sass('resources/sass/frontend/app.scss', 'css/frontend.css')
    .sass('resources/sass/backend/app.scss', 'css/backend.css')
    .js('resources/js/frontend/app.js', 'js/frontend.js')
    .js([
        'resources/js/backend/before.js',
        'resources/js/backend/app.js',
        'resources/js/backend/after.js'
    ], 'js/backend.js')
    /* .scripts([
        "public/js/backend/admin.js"
    ], 'public/js/backend-custom.js')    */
    // .copyDirectory('node_modules/tinymce/plugins', 'public/js/plugins')
    // .copyDirectory('node_modules/tinymce/skins', 'public/js/skins')
    // .copyDirectory('node_modules/tinymce/themes', 'public/js/themes')
    // .copyDirectory('node_modules/tinymce/icons', 'public/js/icons')
    .extract([
        // Extract packages from node_modules to vendor.js
        'jquery',
        'bootstrap',
        'popper.js',
        'axios',
        'sweetalert2',
        'lodash',
        'datatables.net',
        'datatables.net-bs4',
        'moment',
        'moment-timezone',
        'eonasdan-bootstrap-datetimepicker-bootstrap4beta',
        'select2',
        // 'tinymce'
    ])
    .sourceMaps();

if (mix.inProduction()) {
    mix.version()
        .options({
            // Optimize JS minification process
            terser: {
                cache: true,
                parallel: true,
                sourceMap: true
            }
        });
} else {
    // Uses inline source-maps on development
    mix.webpackConfig({
        devtool: 'inline-source-map'
    });
}


text:
namespace g{namespace Uno{namespace Data{namespace Xml{struct XmlText;}}}}
namespace g{namespace Uno{namespace Data{namespace Xml{struct XmlValue;}}}}

namespace g{
namespace Uno{
namespace Data{
namespace Xml{

// public sealed class XmlText :272
// {
::g::Uno::Data::Xml::XmlLinkedNode_type* XmlText_typeof();
void XmlText__ctor_3_fn(XmlText* __this);
void XmlText__ctor_4_fn(XmlText* __this, ::g::Uno::Data::Xml::XmlValue* value);
void XmlText__CreateNewInstance_fn(XmlText* __this, ::g::Uno::Data::Xml::XmlLinkedNode** __retval);
void XmlText__New1_fn(XmlText** __retval);
void XmlText__New2_fn(::g::Uno::Data::Xml::XmlValue* value, XmlText** __retval);
void XmlText__ToString_fn(XmlText* __this, uString** __retval);

struct XmlText : ::g::Uno::Data::Xml::XmlLinkedNode
{
    void ctor_3();
    void ctor_4(::g::Uno::Data::Xml::XmlValue* value);
    static XmlText* New1();
    static XmlText* New2(::g::Uno::Data::Xml::XmlValue* value);
};
// }

}}}} // ::g::Uno::Data::Xml


text:
package spec4j.asm.signature;

/**
 * A type signature parser to make a signature visitor visit an existing
 * signature.
 *
 * @author Thomas Hallgren
 * @author Eric Bruneton
 */
public class SignatureReader {

    /**
     * The signature to be read.
     */
    private final String signature;

    /**
     * Constructs a {@link SignatureReader} for the given signature.
     *
     * @param signature
     *            A ClassSignature, MethodTypeSignature, or
     *            FieldTypeSignature.
     */
    public SignatureReader(final String signature) {
        this.signature = signature;
    }

    /**
     * Makes the given visitor visit the signature of this
     * {@link SignatureReader}. This signature is the one specified in the
     * constructor (see {@link #SignatureReader(String) SignatureReader}). This
     * method is intended to be called on a {@link SignatureReader} that was
     * created using a ClassSignature (such as the signature
     * parameter of the {@link spec4j.asm.ClassVisitor#visit
     * ClassVisitor.visit} method) or a MethodTypeSignature (such as the
     * signature parameter of the
     * {@link spec4j.asm.ClassVisitor#visitMethod
     * ClassVisitor.visitMethod} method).
     *
     * @param v
     *            the visitor that must visit this signature.
     */
    public void accept(final SignatureVisitor v) {
        String signature = this.signature;
        int len = signature.length();
        int pos;
        char c;

        if (signature.charAt(0) == '<') {
            pos = 2;
            do {
                int end = signature.indexOf(':', pos);
                v.visitFormalTypeParameter(signature.substring(pos - 1, end));
                pos = end + 1;

                c = signature.charAt(pos);
                if (c == 'L' || c == '[' || c == 'T') {
                    pos = parseType(signature, pos, v.visitClassBound());
                }

                while ((c = signature.charAt(pos++)) == ':') {
                    pos = parseType(signature, pos, v.visitInterfaceBound());
                }
            } while (c != '>');
        } else {
            pos = 0;
        }

        if (signature.charAt(pos) == '(') {
            pos++;
            while (signature.charAt(pos) != ')') {
                pos = parseType(signature, pos, v.visitParameterType());
            }
            pos = parseType(signature, pos + 1, v.visitReturnType());
            while (pos < len) {
                pos = parseType(signature, pos + 1, v.visitExceptionType());
            }
        } else {
            pos = parseType(signature, pos, v.visitSuperclass());
            while (pos < len) {
                pos = parseType(signature, pos, v.visitInterface());
            }
        }
    }

    /**
     * Makes the given visitor visit the signature of this
     * {@link SignatureReader}. This signature is the one specified in the
     * constructor (see {@link #SignatureReader(String) SignatureReader}). This
     * method is intended to be called on a {@link SignatureReader} that was
     * created using a FieldTypeSignature, such as the
     * signature parameter of the
     * {@link spec4j.asm.ClassVisitor#visitField ClassVisitor.visitField}
     * or {@link spec4j.asm.MethodVisitor#visitLocalVariable
     * MethodVisitor.visitLocalVariable} methods.
     *
     * @param v
     *            the visitor that must visit this signature.
     */
    public void acceptType(final SignatureVisitor v) {
        parseType(this.signature, 0, v);
    }

    /**
     * Parses a field type signature and makes the given visitor visit it.
     *
     * @param signature
     *            a string containing the signature that must be parsed.
     * @param pos
     *            index of the first character of the signature to parsed.
     * @param v
     *            the visitor that must visit this signature.
     * @return the index of the first character after the parsed signature.
     */
    private static int parseType(final String signature, int pos,
            final SignatureVisitor v) {
        char c;
        int start, end;
        boolean visited, inner;
        String name;

        switch (c = signature.charAt(pos++)) {
        case 'Z':
        case 'C':
        case 'B':
        case 'S':
        case 'I':
        case 'F':
        case 'J':
        case 'D':
        case 'V':
            v.visitBaseType(c);
            return pos;

        case '[':
            return parseType(signature, pos, v.visitArrayType());

        case 'T':
            end = signature.indexOf(';', pos);
            v.visitTypeVariable(signature.substring(pos, end));
            return end + 1;

        default: // case 'L':
            start = pos;
            visited = false;
            inner = false;
            for (;;) {
                switch (c = signature.charAt(pos++)) {
                case '.':
                case ';':
                    if (!visited) {
                        name = signature.substring(start, pos - 1);
                        if (inner) {
                            v.visitInnerClassType(name);
                        } else {
                            v.visitClassType(name);
                        }
                    }
                    if (c == ';') {
                        v.visitEnd();
                        return pos;
                    }
                    start = pos;
                    visited = false;
                    inner = true;
                    break;

                case '<':
                    name = signature.substring(start, pos - 1);
                    if (inner) {
                        v.visitInnerClassType(name);
                    } else {
                        v.visitClassType(name);
                    }
                    visited = true;
                    top: for (;;) {
                        switch (c = signature.charAt(pos)) {
                        case '>':
                            break top;
                        case '*':
                            ++pos;
                            v.visitTypeArgument();
                            break;
                        case '+':
                        case '-':
                            pos = parseType(signature, pos + 1,
                                    v.visitTypeArgument(c));
                            break;
                        default:
                            pos = parseType(signature, pos,
                                    v.visitTypeArgument('='));
                            break;
                        }
                    }
                }
            }
        }
    }
}


text:
sap.ui.define([
	"sap/ui/core/UIComponent"
], function(UIComponent) {
	"use strict";

	return UIComponent.extend("sap.ui.webc.fiori.sample.ProductSwitch.Component", {

		metadata: {
			manifest: "json"
		}

	});
});


text:
package org.springframework.cloud.sleuth.instrument.web.client.feign;

import java.lang.reflect.Field;

import feign.Client;
import feign.Feign;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ReflectionUtils;

/**
 * {@link BeanPostProcessor} that ensures that each {@link Feign.Builder} has a trace
 * representation of a {@link Client}.
 *
 * @author Marcin Grzejszczak
 * @since 3.0.2
 */
public class TraceFeignBuilderBeanPostProcessor implements BeanPostProcessor {

	private final BeanFactory beanFactory;

	public TraceFeignBuilderBeanPostProcessor(BeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (bean instanceof Feign.Builder) {
			Field client = ReflectionUtils.findField(Feign.Builder.class, "client");
			ReflectionUtils.makeAccessible(client);
			Feign.Builder delegate = (Feign.Builder) bean;
			Client clientInDelegate = (Client) ReflectionUtils.getField(client, delegate);
			if (clientInDelegate instanceof LazyClient || clientInDelegate instanceof LazyTracingFeignClient) {
				return bean;
			}
			delegate.client(new LazyClient(this.beanFactory, clientInDelegate));
			return bean;
		}
		return bean;
	}

}


text:
#ifndef Arduino_h
#define Arduino_h

#define FX450

#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

typedef bool boolean;
typedef uint8_t byte;
typedef uint16_t word;

// some libraries and sketches depend on this AVR stuff,
// assuming Arduino.h or WProgram.h automatically includes it...
//
#include "avr/pgmspace.h"
#include "avr/interrupt.h"
#include "avr/io.h"

#include "binary.h"
#include "itoa.h"

#ifdef __cplusplus
extern "C"{
#endif // __cplusplus

// Include Atmel headers
#include "sam.h"

#include "wiring_constants.h"

#define clockCyclesPerMicrosecond() ( SystemCoreClock / 1000000L )
#define clockCyclesToMicroseconds(a) ( ((a) * 1000L) / (SystemCoreClock / 1000L) )
#define microsecondsToClockCycles(a) ( (a) * (SystemCoreClock / 1000000L) )

void yield( void ) ;

/* system functions */
int main( void );
void init( void );

/* sketch */
void setup( void ) ;
void loop( void ) ;

#include "WVariant.h"

#ifdef __cplusplus
} // extern "C"
#endif

// The following headers are for C++ only compilation
#ifdef __cplusplus
  #include "WCharacter.h"
  #include "WString.h"
  #include "Tone.h"
  #include "WMath.h"
  #include "HardwareSerial.h"
  #include "pulse.h"
#endif
#include "delay.h"
#ifdef __cplusplus
  #include "Uart.h"
#endif

// Include board variant
#include "variant.h"

#include "wiring.h"
#include "wiring_digital.h"
#include "wiring_analog.h"
#include "wiring_shift.h"
#include "WInterrupts.h"

// undefine stdlib's abs if encountered
#ifdef abs
#undef abs
#endif // abs

#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
#define abs(x) ((x)>0?(x):-(x))
#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))
#define round(x)     ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))
#define radians(deg) ((deg)*DEG_TO_RAD)
#define degrees(rad) ((rad)*RAD_TO_DEG)
#define sq(x) ((x)*(x))

#define interrupts() __enable_irq()
#define noInterrupts() __disable_irq()

#define lowByte(w) ((uint8_t) ((w) & 0xff))
#define highByte(w) ((uint8_t) ((w) >> 8))

#define bitRead(value, bit) (((value) >> (bit)) & 0x01)
#define bitSet(value, bit) ((value) |= (1UL << (bit)))
#define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
#define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit))

#define bit(b) (1UL << (b))

#if (ARDUINO_SAMD_VARIANT_COMPLIANCE >= 10606)
// Interrupts
#define digitalPinToInterrupt(P)   ( P )
#endif

// USB Device
#include "USB/USBDesc.h"
#include "USB/USBCore.h"
#include "USB/USBAPI.h"
#include "USB/USB_host.h"

#endif // Arduino_h


text:
#ifndef __QUEUE_MODEL_H__
#define __QUEUE_MODEL_H__

#include "fixed_types.h"
#include "subsecond_time.h"

#include <iostream>

class QueueModel
{
public:
   QueueModel() {}
   virtual ~QueueModel() {}

   virtual SubsecondTime computeQueueDelay(SubsecondTime pkt_time, SubsecondTime processing_time, core_id_t requester = INVALID_CORE_ID) = 0;

   static QueueModel* create(String name, UInt32 id, String model_type, SubsecondTime min_processing_time);
};

#endif /* __QUEUE_MODEL_H__ */


text:
package discovery

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestRegister(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Register Suite")
}


text:
/*****************************************************************************/
/**
 *  @file   TCPBarrier.cpp
 *  @author Naohisa Sakamoto
 */
/*****************************************************************************/
#include "TCPBarrier.h"
#include <kvs/DebugNew>
#include <kvs/TCPSocket>

namespace { const int BARRIER_BUFFER_SIZE = 12; }

namespace kvs
{

/*===========================================================================*/
/**
 *  @brief  Constructs a new TCPBarrier class.
 *  @param  ip [in] IP address
 *  @param  port [in] port number
 */
/*===========================================================================*/
TCPBarrier::TCPBarrier( const kvs::IPAddress& ip, int port )
{
    m_client = new kvs::TCPSocket( ip, port );
    if( !m_client->isConnected() )
    {
        kvsMessageError("Cannot connect to the barrier server.");
    }
}

/*===========================================================================*/
/**
 *  @brief  Destroys the TCPBarrier class.
 */
/*===========================================================================*/
TCPBarrier::~TCPBarrier()
{
    if( m_client ) delete m_client;
}

/*===========================================================================*/
/**
 *  @brief  Wait for the connections.
 */
/*===========================================================================*/
void TCPBarrier::wait()
{
    char send_buffer[::BARRIER_BUFFER_SIZE]; sprintf( send_buffer, "BARRIER" );
//        m_client->disableBlocking();
    m_client->send( send_buffer, ::BARRIER_BUFFER_SIZE );

    m_mutex.lock();

    char recv_buffer[::BARRIER_BUFFER_SIZE];
//        m_client->enableBlocking();
    int size = m_client->receive( recv_buffer, ::BARRIER_BUFFER_SIZE );

    if( size > 0 ) m_mutex.unlock();
}

} // end of namespace kvs


text:
package de.slisson.mps.editor.aec.behavior;

/*Generated by MPS */

import jetbrains.mps.smodel.runtime.BehaviorDescriptor;
import java.util.Arrays;
import jetbrains.mps.smodel.runtime.interpreted.BehaviorAspectInterpreted;

public class BehaviorAspectDescriptor implements jetbrains.mps.smodel.runtime.BehaviorAspectDescriptor {
  private static String[] stringSwitchCases_846f5o_a0a0a = new String[]{"de.slisson.mps.editor.aec.structure.AbstractEditorComponent", "de.slisson.mps.editor.aec.structure.ConcreteEditorComponent"};

  public BehaviorAspectDescriptor() {
  }

  public BehaviorDescriptor getDescriptor(String fqName) {
    switch (Arrays.binarySearch(stringSwitchCases_846f5o_a0a0a, fqName)) {
      case 0:
        return new AbstractEditorComponent_BehaviorDescriptor();
      case 1:
        return new ConcreteEditorComponent_BehaviorDescriptor();
      default:
        return BehaviorAspectInterpreted.getInstance().getDescriptor(fqName);
    }
  }
}


text:
<?php
    session_start();

    include 'pdo.php';
    $callback = 'index.php';
    if(isset($_POST['login-guru'])){
        $username=$_POST['username'];
        $password=$_POST['password'];
        $query = "select * from guru where id_guru='".$username."' and password='".$password."'";
        $exec = $pdo->query($query);
        if($exec = $pdo->query("select count(id_guru) from guru where id_guru='".$username."' and password='".$password."'")->fetchColumn()>0){
            foreach($pdo->query($query) as $row){
                $_SESSION["username"] = $username; // buat session username.
                header("location:".$_POST['url']); // Re-direct ke main.php
                exit;
            }
        }else{
            header("location:index.php?error=Username Atau PIN yang anda inputkan salah");
        }
    }

    if(isset($_GET["logout"])){
       session_destroy();
       header("location:index.php");
    }

    if(isset($_GET["from"])){
          $callback = $_GET["from"];
    }
    if(isset($_SESSION["username"])){
        $exec = $pdo->query("select privileges from guru where id_guru='".$_SESSION["username"]."'");
        foreach($exec as $row){
            if ($row[0]=="admin"){
                header("location:tu/");
            }elseif($row[0]=="guru"){
                header("location:guru");
            }else{
                header("location:minat.php");
            }
        }
    }
?>
<!DOCTYPE html>

        <title>Penjurusan Siswa SMA Online</title>

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link href="res/css/bootstrap.min.css" rel="stylesheet" media="screen">
        <link href="res/css/roboto.min.css" rel="stylesheet">
        <link href="res/css/material-fullpalette.min.css" rel="stylesheet">
        <link href="res/css/ripples.min.css" rel="stylesheet">

        <link href="res/css/home.css" rel="stylesheet">

        <?php
                    if(isset($_GET["error"])){
                ?>

                            <button type="button" class="close" data-dismiss="alert">×</button>
                            <?php echo $_GET["error"]; ?>

                <?php
                    }
        ?>

SMA

                          Login

                                        <form class="form" role="form" method="post" action="index.php" accept-charset="UTF-8" id="login-nav">

                                                <input type="hidden" name="url" value="<?php echo $callback; ?>">
                                                NIK
                                                <input type="text" name="username" class="form-control floating-label" id="exampleInputEmail2" placeholder="NIK" style="color:#fff" required>

                                                PIN
                                                <input type="password" name="password" class="form-control floating-label" id="exampleInputPassword2" placeholder="PIN" style="color:#fff" required>

Lupa PIN

                                              <button type="submit" class="btn btn-primary btn-block" name="login-guru" value="login">Masuk</button>

                                              <input type="checkbox"> Tetap Masuk

                                        </form>

Penentuan Jurusan SMA Online

Selamat datang siswa/siswi yang akan memilih jurusan.
                    siswa/siswi dapat memilih jurusan dengan melakukan login untuk memilih jurusan yang dikehendaki

                        <form method="post" action="login.php">

                                <input type="hidden" name="url" value="login.php">
                                <input class="form-control floating-label" id="focusedInput" type="text" placeholder="Nomor Induk Siswa Nasional(NISN)" name="username" style="color:#fff;text-align:center" required>

                            <input class="btn btn-primary" type="submit" value="MASUK" name="login-siswa">
                        </form>

V 0.2

Background Image from ABANKIRENK Creative with Common License

© 2014 Kelompok 13  ~ Metode AHP


text:
"""
Django settings for radar project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0+(xztsv-4@9q$zs0cvz0u3il&fj5aai68_5@&=)!y0q)n5zxk'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

TEMPLATE_DIRS = (
    BASE_DIR + '/radar/templates/'
)

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ws4redis',
    'radar'
)

# Websocket URL.
WEBSOCKET_URL = '/ws/'

# Set the number of seconds each message shall persisted
WS4REDIS_EXPIRE = 3600

# This setting is required to override the Django's main loop, when running in
# development mode, such as ./manage runserver
WSGI_APPLICATION = 'ws4redis.django_runserver.application'

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'radar.urls'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = '/home/pranav/workbase/radar/radar/static/'


text:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
        "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>
    <display-name>
        <![CDATA[ struts servicebroker ]]>
    </display-name>
    <description>
        <![CDATA[   ]]>
    </description>

    <!-- ==== Form Bean Definitions ==== -->

    <form-beans>
        <form-bean name="messageForm" type="org.appcelerator.struts.example.MessageForm"/>
    </form-beans>

    <!-- ==== Action Mapping Definitions ==== -->
    <action-mappings>

        <!-- Display any other page (Logon, MainMenu) - Wildcards must come first! -->

        <!--
        <action
                path="/*"
                forward="/{1}.jsp">
        </action>
        -->

        <action
                path="/servicebroker"
                type="org.appcelerator.struts.example.MessageAction">
            <forward
                    name="Success"
                    path="/.jsp"/>
        </action>

        <action
                path="appcelerator.status.report"
                type="org.apache.struts.mock.MockAction">
        </action>

        <action
                path="app.test.message.request"
                type="org.appcelerator.struts.example.MessageAction"
                name="messageForm">
            <forward
                    name="Success"
                    path="app.test.message.response"/>
        </action>

        <action
                path="app.test.piglatin.request"
                type="org.appcelerator.struts.example.PiglatinAction"
                name="messageForm">
            <forward
                    name="Success"
                    path="app.test.piglatin.response"/>
        </action>

        <action
                path="/PigLatinTranslation"
                name="messageForm"
                type="org.appcelerator.struts.example.PiglatinAction"
                scope="request">
            <forward
                    name="Success"
                    path="/Translate.jsp"/>

        </action>

        <!-- Process a user logon -->
        <!--
        <action
                path="/SubmitLogon"
                type="org.apache.struts.apps.mailreader.actions.LogonAction"
                name="LogonForm"
                scope="request"
                cancellable="true"
                validate="true"
                input="Logon">
            <exception
                    key="expired.password"
                    type="org.apache.struts.apps.mailreader.dao.ExpiredPasswordException"
                    path="/ChangePassword.do"/>
            <forward
                    name="Success"
                    path="/MainMenu.do"/>
        </action>
 -->
    </action-mappings>

    <!-- ==== Controller Configuration ==== -->

    <controller
            processorClass="org.appcelerator.struts.AppceleratorRequestProcessor"
            pagePattern="$M$P"
            inputForward="true"/>

</struts-config>


text:
{% extends "base.html" %}

{% block content %}
<link type="text/css" rel="stylesheet" href="{{ url_for('dashboard.static', filename='dashboard.css') }}"  />

Dashboard

Global Commands

			Command ID
			Name
			URL

		{% for command in global_commands %}

			{{ command.cmd_id }}
			{{ command.name }}
			{{ command.url }}

		{% endfor %}

User Commands

	Add New Command

{% endblock %}


text:
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    # @param {ListNode} head
    # @param {integer} val
    # @return {ListNode}
    def removeElements(self, head, val):
        dummy = ListNode(float("-inf"))
        dummy.next = head
        prev, curr = dummy, dummy.next

        while curr:
            if curr.val == val:
                prev.next = curr.next
            else:
                prev = curr

            curr = curr.next

        return dummy.next


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>com.github.rvesse.airline.builder (Airline - Library 2.1.1-SNAPSHOT API)</title>
<meta name="date" content="2016-01-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.github.rvesse.airline.builder

Class Summary

Class
Description

AbstractBuilder<T>

Abstract base class for builders

AliasBuilder<C>

CliBuilder<C>

Builder for CLIs

GroupBuilder<C>

ParserBuilder<C>

Builder for parser configurations

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2012–2016. All rights reserved.


text:
<?php

namespace Genesis\API\Traits\Request\Payout;

use Genesis\API\Constants\DateTimeFormat;
use Genesis\API\Constants\Transaction\Parameters\Payout\MoneyTransferTypes;
use Genesis\Exceptions\InvalidArgument;

/**
 * Trait MoneyTransferPayoutAttributes
 * @package Genesis\API\Traits\Request\Payout
 *
 * @method string getMoneyTransferType()
 * @method string getMoneyTransferSenderAccountNumber()
 * @method string getMoneyTransferSenderFirstName()
 * @method string getMoneyTransferSenderLastName()
 * @method string getMoneyTransferSenderCountry()
 * @method string getMoneyTransferSenderCity()
 * @method string getMoneyTransferSenderZipCode()
 * @method string getMoneyTransferSenderAddress1()
 * @method string getMoneyTransferSenderState()
 *
 * @method $this setMoneyTransferSenderFirstName($value)
 * @method $this setMoneyTransferSenderLastName($value)
 * @method $this setMoneyTransferSenderCountry($value)
 * @method $this setMoneyTransferSenderCity($value)
 * @method $this setMoneyTransferSenderZipCode($value)
 * @method $this setMoneyTransferSenderAddress1($value)
 * @method $this setMoneyTransferSenderState($value)
 *
 */
trait MoneyTransferPayoutAttributes
{
    /**
     * The type of money transfer. It can be account_to_account, person_to_person, wallet_transfer, funds_transfer
     * @var string $money_transfer_type
     */
    protected $money_transfer_type;

    /**
     * Sender account number
     * @var string $money_transfer_sender_account_number
     */
    protected $money_transfer_sender_account_number;

    /**
     * Must contain valid birth date of the sender.
     * @var \DateTime $money_transfer_sender_birth_date
     */
    protected $money_transfer_sender_birth_date;

    /**
     * Must contain a valid Service Provider Name. Only alphanumeric characters are allowed (including spaces).
     * @var string $money_transfer_service_provider_name
     */
    protected $money_transfer_service_provider_name;

    /**
     * Sender first name
     * @var string $money_transfer_sender_first_name
     */
    protected $money_transfer_sender_first_name;

    /**
     * Sender last name
     * @var string $money_transfer_sender_last_name
     */
    protected $money_transfer_sender_last_name;

    /**
     * Sender Country code in ISO 3166
     * @var string $money_transfer_sender_country
     */
    protected $money_transfer_sender_country;

    /**
     * Sender City
     * @var string $money_transfer_sender_city
     */
    protected $money_transfer_sender_city;

    /**
     * Sender ZIP code
     * @var string $money_transfer_sender_zip_code
     */
    protected $money_transfer_sender_zip_code;

    /**
     * Sender Primary address
     * @var string $money_transfer_sender_address1
     */
    protected $money_transfer_sender_address1;

    /**
     * Sender State code in ISO 3166-2, required for USA and Canada
     * @var string $money_transfer_sender_state
     */
    protected $money_transfer_sender_state;

    /**
     * @param string $value
     * @throws InvalidArgument
     */
    public function setMoneyTransferType($value)
    {
        if ($value === null) {
            $this->money_transfer_type = null;

            return $this;
        }

        $this->allowedOptionsSetter(
            'money_transfer_type',
            MoneyTransferTypes::getAllowedMoneyTransferTypes(),
            $value,
            'Invalid value for type parameter.'
        );

        return $this;
    }

    /**
     * Accept any of supported formats for birthdate
     *
     * @param string $value
     * @return $this
     * @throws InvalidArgument
     */
    public function setMoneyTransferSenderBirthDate($value)
    {
        if (empty($value)) {
            $this->money_transfer_sender_birth_date = null;

            return $this;
        }

        return $this->parseDate(
            'money_transfer_sender_birth_date',
            DateTimeFormat::getAll(),
            $value,
            'Invalid value given for Birth Date.'
        );
    }

    /**
     * Format BirtDate accordingly
     * @return string|null
     */
    public function getMoneyTransferSenderBirthDate()
    {
        return (empty($this->money_transfer_sender_birth_date)) ? null :
            $this->money_transfer_sender_birth_date->format(DateTimeFormat::DD_MM_YYYY_L_HYPHENS);
    }

    /**
     * @param $value
     * @return $this
     * @throws InvalidArgument
     */
    public function setMoneyTransferSenderAccountNumber($value)
    {
        return $this->setLimitedString(
            'money_transfer_sender_account_number',
            $value,
            null,
            self::MONEY_TRANSFER_SENDER_ACCOUNT_NUMBER_MAX_LENGTH
        );
    }

    /**
     * @param $value
     * @return $this
     * @throws InvalidArgument
     */
    public function setMoneyTransferServiceProviderName($value)
    {
        return $this->setLimitedString(
            'money_transfer_service_provider_name',
            $value,
            null,
            self::MONEY_TRANSFER_SERVICE_PROVIDER_NAME_MAX_LENGTH
        );
    }

    /**
     * Return Money Transfer payout structure
     * @return array
     */
    protected function getMoneyTransferPayoutStructure()
    {
        return [
            'type'                  => $this->money_transfer_type,
            'sender_account_number' => $this->money_transfer_sender_account_number,
            'sender_birth_date'     => $this->getMoneyTransferSenderBirthDate(),
            'service_provider_name' => $this->money_transfer_service_provider_name,
            'sender_address'        => [
                'first_name' => $this->money_transfer_sender_first_name,
                'last_name'  => $this->money_transfer_sender_last_name,
                'country'    => $this->money_transfer_sender_country,
                'city'       => $this->money_transfer_sender_city,
                'zip_code'   => $this->money_transfer_sender_zip_code,
                'address1'   => $this->money_transfer_sender_address1,
                'state'      => $this->money_transfer_sender_state
            ]
        ];
    }

    /**
     * Attributes to check if Money Transfer Type is set
     * @return array
     */
    protected function requiredMoneyTransferFieldsConditional()
    {
        return [
            'money_transfer_type' => [
                'money_transfer_sender_account_number',
                'money_transfer_sender_first_name',
                'money_transfer_sender_last_name',
                'money_transfer_sender_country',
                'money_transfer_sender_city',
                'money_transfer_sender_zip_code',
                'money_transfer_sender_address1',
            ],
            'money_transfer_sender_country' => [
                'US' => ['money_transfer_sender_state'],
                'CA' => ['money_transfer_sender_state']
            ]
        ];
    }
}


text:
<?php

namespace ZFTest\ContentNegotiation;

use PHPUnit_Framework_TestCase as TestCase;
use Zend\EventManager\EventManager;
use Zend\Http\Request;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\RouteMatch;
use ZF\ContentNegotiation\ContentTypeFilterListener;

class ContentTypeFilterListenerTest extends TestCase
{
    public function setUp()
    {
        $this->listener   = new ContentTypeFilterListener();
        $this->event      = new MvcEvent();
        $this->event->setTarget(new TestAsset\ContentTypeController());
        $this->event->setRequest(new Request());
        $this->event->setRouteMatch(new RouteMatch([
            'controller' => __NAMESPACE__ . '\TestAsset\ContentTypeController',
        ]));
    }

    public function testListenerDoesNothingIfNoConfigurationExistsForController()
    {
        $this->assertNull($this->listener->onRoute($this->event));
    }

    public function testListenerDoesNothingIfRequestContentTypeIsInControllerWhitelist()
    {
        $contentType = 'application/vnd.zf.v1.foo+json';
        $this->listener->setConfig([
            'ZFTest\ContentNegotiation\TestAsset\ContentTypeController' => [
                $contentType,
            ],
        ]);
        $this->event->getRequest()->getHeaders()->addHeaderLine('content-type', $contentType);
        $this->assertNull($this->listener->onRoute($this->event));
    }

    public function testListenerReturnsApiProblemResponseIfRequestContentTypeIsNotInControllerWhitelist()
    {
        $contentType = 'application/vnd.zf.v1.foo+json';
        $this->listener->setConfig([
            'ZFTest\ContentNegotiation\TestAsset\ContentTypeController' => [
                'application/xml',
            ],
        ]);
        $request = $this->event->getRequest();
        $request->getHeaders()->addHeaderLine('content-type', $contentType);
        $request->setContent('<?xml version="1.0"?><foo><bar>baz</bar></foo>');

        $response = $this->listener->onRoute($this->event);
        $this->assertInstanceOf('ZF\ApiProblem\ApiProblemResponse', $response);
        $this->assertContains('Invalid content-type', $response->getApiProblem()->detail);
    }

    public function testAttachesToDispatchEventAtHighPriority()
    {
        $events = new EventManager();
        $this->listener->attach($events);
        $listeners = $events->getListeners('route');
        $this->assertEquals(1, count($listeners));
        $this->assertTrue($listeners->hasPriority(-625));
        $callback = $listeners->getIterator()->current()->getCallback();
        $this->assertEquals([$this->listener, 'onRoute'], $callback);
    }

    /**
     * @group 66
     */
    public function testCastsObjectBodyContentToStringBeforeWorkingWithIt()
    {
        $contentType = 'application/vnd.zf.v1.foo+json';
        $this->listener->setConfig([
            'ZFTest\ContentNegotiation\TestAsset\ContentTypeController' => [
                $contentType,
            ],
        ]);
        $request = $this->event->getRequest();

        $request->getHeaders()->addHeaderLine('content-type', $contentType);
        $request->setContent(new TestAsset\BodyContent());

        $this->assertNull($this->listener->onRoute($this->event));
    }
}


text:
package jlibs.xml.sax.binding;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Santhosh Kumar T
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface NamespaceContext{
    public Entry[] value();
}


text:
/*
 * decaffeinate suggestions:
 * DS102: Remove unnecessary code created because of implicit returns
 * DS208: Avoid top-level this
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
 */
import Spine from './spine'

Spine.Model.Local = {
  extended() {
    const testLocalStorage = 'spine' + new Date().getTime();
    try {
      localStorage.setItem(testLocalStorage, testLocalStorage);
      localStorage.removeItem(testLocalStorage);
    } catch (e) {
      return;
    }

    this.change(this.saveLocal);
    return this.fetch(this.loadLocal);
  },

  saveLocal() {
    const result = JSON.stringify(this);
    return localStorage[this.className] = result;
  },

  loadLocal(options = {}){
    if (!options.hasOwnProperty('clear')) { options.clear = true; }
    const result = localStorage[this.className];
    return this.refresh(result || [], options);
  }
};

export default Spine.Model.Local;


text:
var fs = require('fs')

function bufferToStdout (gl, width, height) {
  // Write output
  var pixels = new Uint8Array(width * height * 4)
  gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels)
  process.stdout.write(['P3\n# gl.ppm\n', width, ' ', height, '\n255\n'].join(''))
  for (var i = 0; i < pixels.length; i += 4) {
    process.stdout.write(pixels[i] + ' ' + pixels[i + 1] + ' ' + pixels[i + 2] + ' ')
  }
}

function bufferToFile (gl, width, height, filename) {
  var file = fs.createWriteStream(filename)

  // Write output
  var pixels = new Uint8Array(width * height * 4)
  gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels)
  file.write(['P3\n# gl.ppm\n', width, ' ', height, '\n255\n'].join(''))
  for (var i = 0; i < pixels.length; i += 4) {
    file.write(pixels[i] + ' ' + pixels[i + 1] + ' ' + pixels[i + 2] + ' ')
  }
}

function drawTriangle (gl) {
  var buffer = gl.createBuffer()
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-2, -2, -2, 4, 4, -2]), gl.STREAM_DRAW)
  gl.enableVertexAttribArray(0)
  gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0)
  gl.drawArrays(gl.TRIANGLES, 0, 3)
  gl.bindBuffer(gl.ARRAY_BUFFER, null)
  gl.disableVertexAttribArray(0)
  gl.deleteBuffer(buffer)
}

function loadShader (gl, shaderSource, shaderType) {
  var shader = gl.createShader(shaderType)
  gl.shaderSource(shader, shaderSource)
  gl.compileShader(shader)

  // Check the compile status
  var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
  if (!compiled) {
    // Something went wrong during compilation; get the error
    var lastError = gl.getShaderInfoLog(shader)
    console.log("*** Error compiling shader '" + shader + "':" + lastError)
    gl.deleteShader(shader)
    return null
  }

  return shader
}

function createProgram (gl, shaders, optAttribs, optLocations) {
  var program = gl.createProgram()
  shaders.forEach(function (shader) {
    gl.attachShader(program, shader)
  })
  if (optAttribs) {
    optAttribs.forEach(function (attrib, ndx) {
      gl.bindAttribLocation(
        program,
        optLocations ? optLocations[ndx] : ndx,
        attrib)
    })
  }
  gl.linkProgram(program)

  // Check the link status
  var linked = gl.getProgramParameter(program, gl.LINK_STATUS)
  if (!linked) {
    // something went wrong with the link
    var lastError = gl.getProgramInfoLog(program)
    console.log('Error in program linking:' + lastError)

    gl.deleteProgram(program)
    return null
  }
  return program
}

function createProgramFromSources (gl, shaderSources, optAttribs, optLocations) {
  var defaultShaderType = [
    'VERTEX_SHADER',
    'FRAGMENT_SHADER'
  ]

  var shaders = []
  for (var ii = 0; ii < shaderSources.length; ++ii) {
    shaders.push(loadShader(gl, shaderSources[ii], gl[defaultShaderType[ii]]))
  }
  return createProgram(gl, shaders, optAttribs, optLocations)
}

module.exports.bufferToStdout = bufferToStdout
module.exports.bufferToFile = bufferToFile
module.exports.drawTriangle = drawTriangle
module.exports.loadShader = loadShader
module.exports.createProgram = createProgram
module.exports.createProgramFromSources = createProgramFromSources


text: git archive --format=tar.gz -o galaxycash.tar.gz --prefix=/galaxycash/ HEAD .


text:
package message.event;

import lodsve.core.configuration.EnableLodsve;
import lodsve.core.event.EventPublisher;
import lodsve.core.event.annotations.AsyncEvent;
import lodsve.core.event.annotations.Events;
import lodsve.core.event.annotations.SyncEvent;
import lodsve.core.event.listener.EventListener;
import lodsve.core.event.module.BaseEvent;
import lodsve.core.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 日志事件监听器.
 *
 * @author sunhao(sunhao.java@gmail.com)
 * @version V1.0
 * @createTime 13-4-27 上午5:07
 */
@Component
@Events(
        async = {@AsyncEvent(name = "查询", event = QueryEvent.class)},
        sync = {@SyncEvent(name = "查看", event = ViewEvent.class)}
)
@EnableLodsve
public class LoggerListener implements EventListener {
    @Autowired
    private EventPublisher eventPublisher;

    @Override
    public void handleEvent(BaseEvent baseEvent) throws RuntimeException {
        String description = eventPublisher.evalName(baseEvent.getClass()) + ": " + baseEvent.getSource().toString();

        System.out.println("发生在: " + DateUtils.formatDate(baseEvent.getEventTime(), DateUtils.DEFAULT_PATTERN) + ", " + description);
    }
}


text:
FactoryGirl.define do
  factory :user do
      fullname "Crowdhoster Tester"
      sequence(:email) { |n| "test#{n}@crowdhoster.com" }
      password "testPass"
      password_confirmation "testPass"

      trait :admin do
        admin true
        email 'admin_test@crowdhoster.com'
      end
  end
end


text: Poenaru Radu-Constantin 343C1


text:
<?php
/**
 * Serializable Iterator usages(用例)
 */

namespace LanguageStatement\LanguageExtension\PredefinedInterface\Serializable;

use LanguageStatement\LanguageExtension\PredefinedInterface\ArrayAccess\testArrayAccess;

class testSerializable implements \Serializable
{
    protected $property;

    public function __construct($param=null)
    {
        $this->property=$param;
    }

    public function getProperty(){
        return $this->property;
    }

    public function serialize()
    {
        return (string)($this->property*2);
    }

    public function unserialize($serialized)
    {
        $this->property=(int)$serialized/2;
    }
}
// 实例化
$serializable=new testSerializable(111);
var_dump($serializable);
// 序列化
$serializableStr=serialize($serializable);
var_dump($serializableStr);
// 反序列化
$serializable=unserialize($serializableStr);
var_dump($serializable);


text:
<!--
  Copyright 2018 The Android Open Source Project

  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

      https://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.
  -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M-278.33,-902.17h76v76h-76z"/>
    <path
        android:fillColor="#FF000000"
        android:pathData="M2,2v20h20L22,2L2,2zM20,20L4,20L4,10h16v10zM20,8h-8L12,5h8v3z"/>
</vector>


text:
<?php

namespace Lokhman\Silex\Console\Command\Assetic;

use Assetic\Asset\AssetCollectionInterface;
use Assetic\Asset\AssetInterface;
use Assetic\Util\VarUtils;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\LockableTrait;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Dump command for Assetic library.
 *
 * @author Alexander Lokhman <alex.lokhman@gmail.com>
 *
 * @link https://github.com/lokhman/silex-assetic
 */
class DumpCommand extends Command
{
    use LockableTrait;

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('assetic:dump')
            ->setDescription('Dumps all assets to the filesystem')
            ->addOption('no-debug', null, InputOption::VALUE_NONE, 'Switch debug mode off');
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (!$this->lock()) {
            $output->writeln('<error>The command is already running in another process.</error>');

            return 0;
        }

        $app = $this->getApplication()->getContainer();

        $verbose = function ($asset) use ($output) {
            $output->writeln(sprintf('<fg=cyan>%s/%s</>', $asset->getSourceRoot() ?: '[unknown root]',
                $asset->getSourcePath() ?: '[unknown path]'));
        };

        $assetic = $app['assetic'];
        if (false === $dir = realpath($app['assetic.options']['output_dir'])) {
            $dir = $app['assetic.options']['output_dir'];
        }

        if ($input->getOption('no-debug')) {
            $assetic->setDebug(false);
        }

        $output->writeln(sprintf('Dumping all assets to <comment>%s</comment>.', $dir));
        $output->writeln(sprintf('Debug mode is <comment>%s</comment>.'.PHP_EOL, $assetic->isDebug() ? 'on' : 'off'));

        $app['assetic.dump'](true, function (AssetInterface $asset) use ($output, $verbose) {
            $path = VarUtils::resolve($asset->getTargetPath(), $asset->getVars(), $asset->getValues());
            $output->writeln(sprintf('<comment>%s</comment> <info>[file+]</info> %s', date('H:i:s'), $path));

            if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
                if ($asset instanceof AssetCollectionInterface) {
                    foreach ($asset as $leaf) {
                        $verbose($leaf);
                    }
                } else {
                    $verbose($asset);
                }
            }
        });
    }
}


text:
package net.liftweb {
package example {
package comet {

import net.liftweb.actor._
import scala.xml.{NodeSeq, Text}

import net.liftweb._
import http._
import js._
import JsCmds._

import common._
import util._
import Helpers._

case class BuildStatus(progress: Int, url: Box[String])

// a singleton that builds a "thing"
object ThingBuilder extends LiftActor {
  def boot() {
    LiftRules.dispatch.append {
      case Req("getit":: Nil, _, GetRequest) =>
        () => Full(XmlResponse(<info>Here's some info</info>))
    }
  }

  protected def messageHandler =
    {
      case a: LiftActor =>
        this ! (a, 1)

      case (a: LiftActor, x: Int) if x >= 10 =>
        a ! BuildStatus(100, Full("/getit"))

      case (a: LiftActor, i: Int) =>
        a ! BuildStatus(i * 10, Empty)
        ActorPing.schedule(this, (a, i + 1), 2 seconds)

      case _ =>
    }

}

// A CometActor that keeps the user updated
class LongTime extends CometActor {
  private var url: Box[String] = Empty
  private var progress: Int = 0

  // a CometActor that has not been displayed for
  // 2 minutes is destroyed
  override def lifespan: Box[TimeSpan] = Full(2 minutes)

  // get messages from the ThingBuilder
  override def highPriority = {
    case BuildStatus(p, Empty) =>
      this.progress = p
      reRender(false)

    case BuildStatus(_, Full(u)) =>
      url = Full(u)
      progress = 100
      reRender(false)
      partialUpdate(RedirectTo(u))
  }

  // start the job
  override def localSetup() {
    ThingBuilder ! this
    super.localSetup()
  }

  // display the progress or a link to the result
  def render =
  url match {
    case Full(where) =>
      Your job is complete.  Click Me
    case _ =>
      We're working on your job... it's {progress}% complete
  }
}
}
}
}


text:
#include "object_heap.h"

#include "assert.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define ASSERT	assert

#define LAST_FREE	-1
#define ALLOCATED	-2

/*
 * Expands the heap
 * Return 0 on success, -1 on error
 */
static int object_heap_expand( object_heap_p heap )
{
    int i;
    void *new_heap_index;
    int next_free;
    int new_heap_size = heap->heap_size + heap->heap_increment;

    new_heap_index = (void *) realloc( heap->heap_index, new_heap_size * heap->object_size );
    if ( NULL == new_heap_index )
    {
        return -1; /* Out of memory */
    }
    heap->heap_index = new_heap_index;
    next_free = heap->next_free;
    for(i = new_heap_size; i-- > heap->heap_size; )
    {
        object_base_p obj = (object_base_p) (heap->heap_index + i * heap->object_size);
        obj->id = i + heap->id_offset;
        obj->next_free = next_free;
        next_free = i;
    }
    heap->next_free = next_free;
    heap->heap_size = new_heap_size;
    return 0; /* Success */
}

/*
 * Return 0 on success, -1 on error
 */
int object_heap_init( object_heap_p heap, int object_size, int id_offset)
{
    heap->object_size = object_size;
    heap->id_offset = id_offset & OBJECT_HEAP_OFFSET_MASK;
    heap->heap_size = 0;
    heap->heap_increment = 16;
    heap->heap_index = NULL;
    heap->next_free = LAST_FREE;
    return object_heap_expand(heap);
}

/*
 * Allocates an object
 * Returns the object ID on success, returns -1 on error
 */
int object_heap_allocate( object_heap_p heap )
{
    object_base_p obj;
    if ( LAST_FREE == heap->next_free )
    {
        if( -1 == object_heap_expand( heap ) )
        {
            return -1; /* Out of memory */
        }
    }
    ASSERT( heap->next_free >= 0 );

    obj = (object_base_p) (heap->heap_index + heap->next_free * heap->object_size);
    heap->next_free = obj->next_free;
    obj->next_free = ALLOCATED;
    return obj->id;
}

/*
 * Lookup an object by object ID
 * Returns a pointer to the object on success, returns NULL on error
 */
object_base_p object_heap_lookup( object_heap_p heap, int id )
{
    object_base_p obj;
    if ( (id < heap->id_offset) || (id > (heap->heap_size+heap->id_offset)) )
    {
        return NULL;
    }
    id &= OBJECT_HEAP_ID_MASK;
    obj = (object_base_p) (heap->heap_index + id * heap->object_size);

	/* Check if the object has in fact been allocated */
	if ( obj->next_free != ALLOCATED )
    {
        return NULL;
    }
    return obj;
}

/*
 * Iterate over all objects in the heap.
 * Returns a pointer to the first object on the heap, returns NULL if heap is empty.
 */
object_base_p object_heap_first( object_heap_p heap, object_heap_iterator *iter )
{
    *iter = -1;
    return object_heap_next( heap, iter );
}

/*
 * Iterate over all objects in the heap.
 * Returns a pointer to the next object on the heap, returns NULL if heap is empty.
 */
object_base_p object_heap_next( object_heap_p heap, object_heap_iterator *iter )
{
    object_base_p obj;
    int i = *iter + 1;
    while ( i < heap->heap_size)
    {
        obj = (object_base_p) (heap->heap_index + i * heap->object_size);
        if (obj->next_free == ALLOCATED)
        {
            *iter = i;
            return obj;
        }
        i++;
    }
    *iter = i;
    return NULL;
}

/*
 * Frees an object
 */
void object_heap_free( object_heap_p heap, object_base_p obj )
{
    /* Don't complain about NULL pointers */
    if (NULL != obj)
    {
        /* Check if the object has in fact been allocated */
        ASSERT( obj->next_free == ALLOCATED );

        obj->next_free = heap->next_free;
        heap->next_free = obj->id & OBJECT_HEAP_ID_MASK;
    }
}

/*
 * Destroys a heap, the heap must be empty.
 */
void object_heap_destroy( object_heap_p heap )
{
    object_base_p obj;
    int i;
    /* Check if heap is empty */
    for (i = 0; i < heap->heap_size; i++)
    {
        /* Check if object is not still allocated */
        obj = (object_base_p) (heap->heap_index + i * heap->object_size);
        ASSERT( obj->next_free != ALLOCATED );
    }
    free(heap->heap_index);
    heap->heap_size = 0;
    heap->heap_index = NULL;
    heap->next_free = LAST_FREE;
}


text:
<!DOCTYPE html>

        @include('common.head', array('title', 'GradList - Frequently Asked Questions') )
        {{ HTML::style('css/policy.css') }}
        {{ HTML::style('css/main.css') }}
        {{ HTML::style('css/base.css') }}

Frequently Asked Questions

How can I be sure that I control who sees my details?

We don't share your name, age or email address with anyone at all. Employers are able to look for people whose credentials match what they are looking for – but they don't get to find out who those people actually are. They can then request to contact people on the basis of their experience and achievements through the GradList email system - which is still anonymous.

So the only way they can find out who you are is if you decide to reply to the email they send you – and we hope that you will want to!

How much will this service cost me to use?

We charge a total of £0000.0000 per user per year. Yup, that's right: its 100% free.

Which charities can I choose to support?

We give you a selection of five or six options when you sign up. They might change occasionally but, because we are all about expanding opportunities, they all work with young people, helping them to fulfil their potential.

How can I be sure that employers will not use GradList as a spam service?

We have lots of measures in place to make sure our users don't get spammed; it's really important to us. So we personally vet every email that employers ask us to send and we also take a look at how many people it is going to. If it seems like too many then we might ask the employer to be more specific.

Besides this, we charge employers to get in touch with you – that's how we are able to support our partner charities. So its not worthwhile an employer to sending a message to people who aren't suited to working with them.

What if there is some information I don't want to disclose?

That's totally fine. There are some basic details (like name, email address, university) that we really do need – but besides these, it's really up to you. Clearly, we hope that you will want to give us all the information that you can; the more there is to go on, the higher the chance that you will be sought out by the job that is right for you!

© GradList Ltd. 2014. All rights reserved.

	{{ link_to_route('terms', 'Terms of Use', [], ['id'=>'terms_link']) }}
	{{ link_to_route('policy', 'Privacy Policy', [], ['id'=>'privacy_link']) }}
	{{ link_to_route('faq', 'FAQ') }}

        {{ HTML::script('js/log_in.js') }}


text:
#ifndef UNIVPLAN_SRC_UNIVPLAN_UNIVPLANBUILDER_UNIVPLANBUILDER_EXT_GS_SCAN_H_
#define UNIVPLAN_SRC_UNIVPLAN_UNIVPLANBUILDER_UNIVPLANBUILDER_EXT_GS_SCAN_H_

#include <memory>
#include <vector>

#include "univplan/proto/universal-plan.pb.h"
#include "univplan/univplanbuilder/univplanbuilder-node.h"
#include "univplan/univplanbuilder/univplanbuilder-scan-task.h"

namespace univplan {

class UnivPlanBuilderExtGSScan : public UnivPlanBuilderNode {
 public:
  UnivPlanBuilderExtGSScan();
  virtual ~UnivPlanBuilderExtGSScan();

  typedef std::unique_ptr<UnivPlanBuilderExtGSScan> uptr;

  std::unique_ptr<UnivPlanBuilderPlanNodePoly> ownPlanNode() override;

  void from(const UnivPlanPlanNodePoly &node) override;

  void setScanRelId(uint32_t id);
  void setColumnsToRead(const std::vector<int32_t> &nArray);
  void setKeyColumnIndexes(const std::vector<int32_t> &nArray);
  void setFilterExpr(UnivPlanBuilderExprTree::uptr expr);
  std::unique_ptr<UnivPlanBuilderScanTask> addScanTaskAndGetBuilder();
  // set magma index info
  void setScanIndex(bool index);
  void setIndexScanType(ExternalScanType type);
  void setDirectionType(ExternalScanDirection direction);
  void setIndexName(const char *indexName);
  void addIndexQual(UnivPlanBuilderExprTree::uptr exprTree);

 private:
  UnivPlanExtGSScan *ref;
  std::unique_ptr<UnivPlanExtGSScan> planNode;
};

}  // namespace univplan

#endif  // UNIVPLAN_SRC_UNIVPLAN_UNIVPLANBUILDER_UNIVPLANBUILDER_EXT_GS_SCAN_H_


text:
require 'quickmr/processor_base'
require 'quickmr/mapper'
require 'quickmr/splitter'
require 'quickmr/merger'
require 'quickmr/reducer'
require 'quickmr/demultiplexer'
require 'quickmr/multiplexer'
require 'quickmr/line_reader'

class Job < ProcessorBase
	@@job_no = 0
	def self.define(name = "Job#{@@job_no += 1}", &setup)
		job = Class.new(Job) do
			@@setup = setup
			def setup
				instance_exec(&@@setup)
			end
		end
		Object.const_set(name, job)
		job
	end

	def self.start
		Tribe.root.spawn(self)
	end

	def initialize(options)
		@logger = Logger.new(STDERR)
		@logger.level = Logger::WARN
		super options.merge(logger: @logger)

		@mappers = []
		@reducers = []

		setup

		fail 'no mappers defined' if @mappers.empty?
		fail 'no reducers defined' if @reducers.empty?

		@splitters = []
		@mergers = []

		@reducers.each do |reducer|
			merger = spawn(Merger)
			merger.connect(reducer)
			@mergers << merger
		end

		@mappers.each do |mapper|
			splitter = spawn(Splitter, queue_no: @mergers.length)
			mapper.connect(splitter)
			@splitters << splitter
		end

		@mergers.each.with_index do |merger, merger_no|
			queues = @splitters.map do |splitter|
				splitter.queues[merger_no]
			end
			merger.deliver_message! :flush!, queues
		end

		@output = spawn(Demultiplexer, input_no: @reducers.length)
		@reducers.each do |reducer|
			reducer.connect(@output)
		end
		@output.connect(self, :output)

		@input = spawn(Multiplexer)
		@input.connect(@mappers)
	end

	def mapper(count, &block)
		count.times do
			@mappers << spawn(Mapper.define(&block))
		end
	end

	def reducer(count, &block)
		count.times do
			@reducers << spawn(Reducer.define(&block))
		end
	end

	def output(&block)
		@on_output = block
	end

	def read_files_by_line(files, max_lines = nil)
		if max_lines
			max_lines = (max_lines.to_f / files.length).ceil
		end

		input = spawn(Demultiplexer, input_no: files.length)
		input.connect(self)

		files.each do |file_name|
			line_reader = spawn(LineRader, max_lines: max_lines)
			line_reader.connect(input)
			line_reader.deliver_message! :read_file, file_name
		end
	end

	def process(key, value)
		deliver_message!(:data, [key, value])
	end

	def flush!
		deliver_message! :data, nil # flush
	end

	def wait_done
		while alive? do sleep 0.1 end
	end

	def show_info
		@logger.level = Logger::INFO
	end

	def show_debug
		@logger.level = Logger::DEBUG
	end

private

	def on_data(event)
		debug{"input: #{event.data}"}
		@input.deliver_message! :data, event.data
	end

	def on_output(event)
		if not event.data
			shutdown!
			return
		end
		@on_output.call(*event.data) if @on_output
	end
end


text:
'use strict';
myApp.controller('introController', ['$scope', '$timeout', '$location', '$cordovaDevice', 'deviceAuthService',
    function($scope, $timeout, $location, $cordovaDevice, deviceAuthService) {

        $scope.platforms = "Android";
        $scope.device = "60a40bb7e2972603";

        $scope.introInit = function() {

            document.addEventListener("deviceready", function() {

                var platforms = $cordovaDevice.getPlatform();
                var device = $cordovaDevice.getUUID();

                deviceAuthService.getDeviceAuthService(device, platforms).then(function(results) {

                    if (results.data) {
                        //alert(results.data.Email + " || " + device + " || " + platforms);
                        $location.path('/views/home');

                    } else {
                        //alert(results.data + " || " + $scope.device + " || " + $scope.platforms);
                        $location.path('/views/register');

                    }

                }, function(response) {
                    var errors = [];
                    for (var key in response.data.Message) {
                        for (var i = 0; i < response.data.Message[key].length; i++) {
                            errors.push(response.data.Message[key][i]);
                        }
                    }
                    var message = "Failed to register user due to:" + errors.join(' ');
                    alert(message);
                });

            }, false);

            // deviceAuthService.getDeviceAuthService($scope.device, $scope.platforms).then(function(results) {

            //     if (results.data) {

            //         $location.path('/views/home');

            //     } else {

            //         $location.path('/views/register');

            //     }

            // }, function(response) {
            //     var errors = [];
            //     if (response.data.ModelState) {
            //         for (var key in response.data.ModelState) {
            //             for (var i = 0; i < response.data.ModelState[key].length; i++) {
            //                 errors.push(response.data.ModelState[key][i]);
            //             }
            //         }
            //     } else {
            //         errors.push(response.data.Message);
            //     }
            //     var message = "Failed to register user due to:" + errors.join(' ');
            //     alert(message);
            // });

        }

    }
]);


text:
package com.xiaomi.infra.galaxy.vision.model;

public class AgeInfo {
    private int age;
    private float confidence;

    public float getConfidence() {
        return confidence;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setConfidence(float confidence) {
        this.confidence = confidence;
    }

}


text:
require "active_support"
require "active_support/core_ext/string"

class Reciper
  require "reciper/helpers"
  include Reciper::Helpers

  attr_reader :name, :recipe_path, :ruby_app_path

  # Initialize the recipe with the paths. It will clone the ruby_app_template_path to a path that we will run the migration.
  #
  # name - the recipe name
  # recipe_path - the recipe path (absolute or relative to the current path)
  # ruby_app_template_path - the ruby app template path (it will be cloned and it will run the migrations on this copy)
  #
  # Examples
  #
  #   Recipe.new("My freaking awesome recipe", "~/Code/recipe", "~/Code/rails_app/path")
  #
  # Returns a recipe instance with all paths configured
  def initialize(name, recipe_path, ruby_app_template_path)
    @name = name
    @recipe_path = recipe_path
    @ruby_app_path = File.join(".", "tmp", name.parameterize("_"))

    if File.directory?(@ruby_app_path)
      FileUtils.rm_rf(@ruby_app_path)
    end

    FileUtils.mkdir_p("tmp")

    FileUtils.cp_r(ruby_app_template_path, @ruby_app_path)
  end

  # Executes a recipe inside the block.
  #
  # Examples
  #
  #   recipe.execute do
  #     run_rake_task("db:migrate")
  #     copy_file("file.rb", :as => "user.rb")
  #   end
  #
  # Returns nothing.
  def execute(&block)
    if block_given?
      instance_eval(&block)
    end
  end
end