text:
<?php
namespace AmosCalamida\Kzoreschedule\Controller;

use TYPO3\CMS\Core\Database\DatabaseConnection;

setlocale(LC_ALL, 'de_CH.UTF-8');
$extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['kzoreschedule']);

/**
 * ProjectController
 */
class ProjectController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{

    /**
     * @var \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager
     *
     * injection of persistence manager to be able to persist manually
     *
     * @inject
     */
    protected $persistenceManager;

    /**
     * projectRepository
     *
     * injecting the project repository to create and manipulate projects
     *
     * @var \AmosCalamida\Kzoreschedule\Domain\Repository\ProjectRepository
     * @inject
     */
    protected $projectRepository = NULL;

    /**
     * Property for accessing DatabaseConnection centrally
     *
     * @var DatabaseConnection
     */
    protected $databaseConnection;

    /**
     * Constructor Function for setting up DB Connection
     *
     * @param DatabaseConnection $databaseConnection
     */

    function __construct(DatabaseConnection $databaseConnection = null)
    {

        $this->databaseConnection = $databaseConnection ?: $GLOBALS['TYPO3_DB'];

    }

    /**
     * action list
     *
     * list all projects for logged in FE User
     *
     * @return void
     */
    public function listAction()
    {
        $projects = $this->projectRepository->findByUserId($GLOBALS['TSFE']->fe_user->user['uid']);
        $this->view->assign('projects', $projects);
    }

    /**
     * action show
     *
     * Detail View of Project for Student
     *
     * @param \AmosCalamida\Kzoreschedule\Domain\Model\Project $project
     * @ignorevalidation $project
     * @return void
     */
    public function showAction(\AmosCalamida\Kzoreschedule\Domain\Model\Project $project)
    {
        $disagree = 0;
        $secretaryTouches = 0;
        foreach ($project->getChanges() as $change) {

            if ($change->getTeacherAnswer() == 0 OR $change->getTeacherAnswer() == 1) {
                $disagree++;
            }
            if ($change->getSecretaryAnswer() != 0) {
                $secretaryTouches++;
            }

        }
        ($disagree == 0) ? $teachersAgree = true : $teachersAgree = false;
        ($secretaryTouches == 0) ? $secretaryDidNotTouch = true : $secretaryDidNotTouch = false;

        $project->setUserId($this->getUserInfo($project->getUserId(), "fullname"));
        $this->view->assign('allTeachersAgree', $teachersAgree);
        $this->view->assign('secretaryDidNotTouch', $secretaryDidNotTouch);
        $this->view->assign('project', $project);
    }

    /**
     * action secretaryShow
     *
     * Detail View of Project for Secretary
     *
     * @param \AmosCalamida\Kzoreschedule\Domain\Model\Project $project
     * @return void
     */
    public function secretaryShowAction(\AmosCalamida\Kzoreschedule\Domain\Model\Project $project)
    {
        $project->setUserId($this->getUserInfo($project->getUserId(), "fullname, class"));
        $this->view->assign('project', $project);
    }

    /**
     * action new
     *
     * renders the project creation form
     *
     *
     * @return void
     */
    public function newAction()
    {

    }

    /**
     * action create
     *
     * get the new project object from the form, add the uid of the current FE User as userId
     * and persist it. Redirect to the detail view of the created project
     *
     * @param \AmosCalamida\Kzoreschedule\Domain\Model\Project $newProject
     * @return void
     */
    public function createAction(\AmosCalamida\Kzoreschedule\Domain\Model\Project $newProject)
    {
        $newProject->setUserId($GLOBALS['TSFE']->fe_user->user['uid']);
        $this->addFlashMessage('Verschiebungen können nun in der Tabelle unten eingetragen werden', 'Das Projekt wurde erstellt.', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
        $this->projectRepository->add($newProject);
        $this->persistenceManager->persistAll();
        $this->redirect('show', NULL, NULL, array('project' => $newProject));
    }

    /**
     * action edit
     *
     * render the edit form and assign the project object to view
     *
     * @param \AmosCalamida\Kzoreschedule\Domain\Model\Project $project
     * @ignorevalidation $project
     * @return void
     */
    public function editAction(\AmosCalamida\Kzoreschedule\Domain\Model\Project $project)
    {
        $this->view->assign('project', $project);
    }

    /**
     * action update
     *
     * update the repository object and redirect to the project detail view
     *
     * @param \AmosCalamida\Kzoreschedule\Domain\Model\Project $project
     * @return void
     */
    public function updateAction(\AmosCalamida\Kzoreschedule\Domain\Model\Project $project)
    {
        $this->addFlashMessage('Die Projektinformationen wurden aktualisiert', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
        $this->projectRepository->update($project);
        $this->redirect('show', NULL, NULL, array('project' => $project));
    }

    /**
     * action delete
     *
     * remove the project and all of its changes from repository (for Student View)
     *
     * @param \AmosCalamida\Kzoreschedule\Domain\Model\Project $project
     * @ignorevalidation $project
     * @return void
     */
    public function deleteAction(\AmosCalamida\Kzoreschedule\Domain\Model\Project $project)
    {
        $this->addFlashMessage('Das Projekt wurde gelöscht', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
        $this->projectRepository->remove($project);
        $this->redirect('studentList');
    }

    /**
     * action deleteAdmin
     *
     * remove the project and all of its changes from repository (for admin View)
     *
     * @param \AmosCalamida\Kzoreschedule\Domain\Model\Project $project
     * @ignorevalidation $project
     * @return void
     */
    public function deleteAdminAction(\AmosCalamida\Kzoreschedule\Domain\Model\Project $project)
    {
        $this->addFlashMessage('Das Projekt wurde gelöscht', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
        $this->projectRepository->remove($project);
        $this->redirect('adminList');
    }

    /**
     * action secretaryChange
     *
     * secretary action to either close or reopen a project
     * on close first check for unanswered changes
     *
     * @param \AmosCalamida\Kzoreschedule\Domain\Model\Project $project
     * @param string $modification - modification to perform (either open or close)
     * @return void
     */
    public function secretaryChangeAction(\AmosCalamida\Kzoreschedule\Domain\Model\Project $project, $modification)
    {
        $extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['kzoreschedule']);

        if ($modification == "close") { //Close Project
            // Check if there are still unhandled changes
            $changes = $project->getChanges();
            $errorCount = 0;
            foreach ($changes as $change) {
                if ($change->getSecretaryAnswer() == 0) {
                    $errorCount++;
                }
            }
            if ($errorCount > 0) {
                $this->addFlashMessage('Es ' . (($errorCount == 1) ? 'wurde' : 'wurden') . ' ' . $errorCount . ' ' . (($errorCount == 1) ? 'Verschiebung' : 'Verschiebungen') . ' gefunden, welche noch nicht beantwortet ' . (($errorCount == 1) ? 'ist' : 'sind') . '.', 'Projekt konnte nicht geschlossen werden!', \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR);
            } else {
                $project->setProgress("3");
                $this->projectRepository->update($project);
                if ($extensionConfiguration['trigger.']['closeStudent'] == 1) {
                    $this->sendNotificationEmail($project, "closeproject");
                }
                if ($extensionConfiguration['trigger.']['closeTeacher'] == 1) {
                    foreach ($project->getChanges() as $change) {
                        $this->sendNotificationEmail($change, "closeproject");
                    }
                }
                $this->addFlashMessage("Projekt erfolgreich geschlossen. Betroffene Personen wurden per Mail benachrichtigt");
            }
        }
        if ($modification == "open") { //reopen Project
            $project->setProgress("2");
            $this->projectRepository->update($project);
            $this->addFlashMessage("Projekt erfolgreich wieder geöffnet");
        }
        $this->redirect("secretaryList");
    }

    /**
     * action projectStatusAdjust
     *
     * @param \AmosCalamida\Kzoreschedule\Domain\Model\Project $project
     * @param string $level
     *
     * @return void
     */
    public function projectStatusAdjustAction(\AmosCalamida\Kzoreschedule\Domain\Model\Project $project, $level)
    {
        $extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['kzoreschedule']);

        switch ($level) {
            case 'student':
                $level = 0;
                break;

            case 'teacher':
                $level = 1;
                if ($extensionConfiguration['trigger.']['releaseTeacher'] == 1) {
                    foreach ($project->getChanges() as $change) {
                        if ($change->getEmailsProgress() == 0) {
                            $this->sendNotificationEmail($change, "releaseproject");
                        }
                    }
                }
                break;

            case 'secretary':
                $level = 2;
                break;
        }

        $project->setProgress($level);
        $this->projectRepository->update($project);
        $this->redirect("show", NULL, NULL, array('project' => $project));

    }

    /**
     * action deleteAll
     *
     * delete all projects (massive action / only available from admin panel)
     *
     * @return void
     */
    public function deleteAllAction()
    {

        $projects = $this->projectRepository->findAll();
        $projectsCount = count($projects);

        foreach ($projects as $project) {
            $this->projectRepository->remove($project);
        }

        $this->addFlashMessage("Es wurden " . $projectsCount . " Projekte gelöscht");
        $this->redirect("adminList");
    }

    /**
     * action studentList
     *
     * list all projects for student view and check the teacher and secretary answer status
     *
     * @return void
     */
    public function studentListAction()
    {

        $projects = $this->projectRepository->findByUserId($GLOBALS['TSFE']->fe_user->user['uid']);
        $this->view->assign('projects', $projects);

        $secretaryAnswers = array();
        $teacherAnswers = array();
        foreach ($projects as $project) {

            array_push($secretaryAnswers, $this->getAnswerProgress($project, "secretary"));
            array_push($teacherAnswers, $this->getAnswerProgress($project, "teacher"));

        }

        $this->view->assign('secretaryAnswers', $secretaryAnswers);
        $this->view->assign('teacherAnswers', $teacherAnswers);
    }

    /**
     * action assistantSearch
     *
     * start movement assistant
     *
     * @return void
     */
    public function assistantSearchAction()
    {

        if ($this->request->hasArgument('falloutDate')) {
            $falloutDate = $this->request->getArgument('falloutDate');
            $this->view->assign("falloutDate", $falloutDate);
        } else {
            $this->view->assign("falloutDate", "15.02.2017 11:20");
        }
        if ($this->request->hasArgument('subject')) {
            $subject = $this->request->getArgument('subject');
            $this->view->assign("subject", $subject);
        }

    }

    /**
     * action adminList
     *
     * @return void
     */
    public function adminListAction()
    {
        $projects = $this->projectRepository->findAll();
        foreach ($projects as $project) {
            $project->setUserId($this->getUserInfo($project->getUserId(), "fullname"));
        }
        $this->view->assign('projects', $projects);
    }

    /**
     * action teacherContainer
     *
     * prepare container for teacher view
     *
     * @param integer $filter - filter for results (either 0: unanswered or 1: answered)
     * @return void
     */
    public function teacherContainerAction($filter = 0)
    {

        switch ($filter) {
            case 0:
                $divfilter = 1;
                break;
            case 1:
                $divfilter = 0;
                break;
        }
        $this->view->assign("divfilter", $divfilter);

    }

    /**
     * action teacherList
     *
     * list all changes for teacher view
     *
     * @param integer $filter - filter for results (either 0: unanswered or 1: answered)
     * @return void
     */
    public function teacherListAction($filter = 0)
    {
        $id = $this->getUserInfo($GLOBALS['TSFE']->fe_user->user['uid'],"id","teacher",false,"loginname");

        $teachersCourses = getTeacherCourses($id);

        $projects = $this->projectRepository->findByPublicAndCourses($teachersCourses);
        $allowed_changes = array();
        $allowed_changes_project = array();
        $changeCount = 0;
        foreach ($projects as $project) {
            $changeCount += count($project->getChanges());
            if ($project->getProgress() > 0) {
                $project->setUserId($this->getUserInfo($project->getUserId(), "fullname"));
                foreach ($project->getChanges() as $change) {
                    array_push($allowed_changes, $change);
                    array_push($allowed_changes_project, $project);
                }
            }
        }
        if (!is_null($allowed_changes)) {
            foreach ($allowed_changes as $changeKey => $change) {

                if ($filter == 1) { // show only answered
                    if ($change->getTeacherAnswer() == 0) { // if answered
                        unset($allowed_changes[$changeKey]);
                        unset($allowed_changes_project[$changeKey]);
                    }
                } else { // show only unanswered
                    if ($change->getTeacherAnswer() != 0) { // if unanswered
                        unset($allowed_changes[$changeKey]);
                        unset($allowed_changes_project[$changeKey]);
                    }
                }
            }
            switch ($filter) {
                case 0:
                    $divfilter = 1;
                    break;
                case 1:
                    $divfilter = 0;
                    break;
            }
            $count = $changeCount - count($allowed_changes);
            $this->view->assign('changes', $allowed_changes);
            $this->view->assign('projects', $allowed_changes_project);
            $this->view->assign('divfilter', $divfilter);
            $this->view->assign('filtercount', $count);

        }
    }

    /**
     * action secretaryList
     *
     * list projects for sectretary view
     *
     * @param integer $progress - show either opened (progress: 2) or already closed projects (progress: 3)
     * @return void
     */
    public function secretaryListAction($progress = 2)
    {
        if ($progress == 2) {
            $divprogress = 3;
        } else {
            $divprogress = 2;
        }
        $projects = $this->projectRepository->findByProgress($progress);

        $secretaryAnswers = array();
        foreach ($projects as $project) {
            $project->setUserId($this->getUserInfo($project->getUserId(), "fullname,class"));
            array_push($secretaryAnswers, $this->getAnswerProgress($project, "secretary"));

        }

        $this->view->assign('secretaryAnswers', $secretaryAnswers);
        $this->view->assign('divprogress', $divprogress);
        $this->view->assign('projects', $projects);

    }

    /**
     * action secretaryPrint
     *
     * list projects for sectretary view
     *
     * @param $project \AmosCalamida\Kzoreschedule\Domain\Model\Project $project
     * @return void
     */
    public function secretaryPrintAction(\AmosCalamida\Kzoreschedule\Domain\Model\Project $project)
    {
        $project->setUserId($this->getUserInfo($project->getUserId(), "fullname,class"));
        $this->view->assign('project', $project);
    }

    /**
     * function sendNotificationEmail
     *
     * sends an email to teacher or student with outcome of project or change
     *
     * @param object $object - change or project to notify
     * @param  string $template - the template name defining the message content
     *                            (possible values: "closeproject","updateproject","releaseproject"
     *
     * @return void
     */
    public function sendNotificationEmail($object, $template = "Auto")
    {

        switch (get_class($object)) {

            case 'AmosCalamida\Kzoreschedule\Domain\Model\Change':
                //passed object is Change (Teacher Infos)
                switch ($template) {

                    case "closeproject":
                        // teacher Info on closeproject

                        switch ($object->getSecretaryAnswer()) {

                            case 1: //change denied
                                $accentColor = "#d9534f";
                                $answer = 0;
                                break;

                            case 2: //change accepted
                                $accentColor = "#5cb85c";
                                $answer = 1;
                                break;

                        }
                        $course_details = getCourseDetails($object->getCourseId(), "teacher", "complete");
                        $preheader = "Die Verschiebung Ihrer Lektion wurde vom Sekretariat " . (($answer == 0) ? "nicht bewilligt" : "bewilligt") . ".";
                        $intro = "Die Stundenverschiebung Ihrer Lektion " . $course_details->Label . " wird " . (($answer == 0) ? 'nicht durchgeführt' : 'durchgeführt') . ". Ihre Lektion findet " . (($answer == 0) ? 'normal' : 'nun') . " am " . (($answer == 0) ? $object->getOriginalLesson()->format("d.m.Y H:i") : $object->getChangedLesson()->format("d.m.Y H:i")) . " Uhr " . (($object->getRoom() == "") ? "statt. " . (($answer == 0) ? '' : 'Das ev. geänderte Zimmer entnehmen Sie bitte dem Stundenplan.') : "im Zimmer " . $object->getRoom() . " statt.");
                        $comment = $object->getSecretaryComment();
                        $outro = (($comment != "") ? "Kommentar/Auflage des Sekretariats:
" . $comment . "

" : "
") . "Freundliche Grüsse";

                        $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
                        $teacher = $this->getUserInfo($course_details->Teacher,"email,fullname","teacher",true,"kuerzel");
                        $to = array($teacher["email"] => $teacher["fullname"]);
                        $body = self::getEmailDesign(array($preheader, $intro, $outro));
                        $subject = "Entscheid der Stundenverschiebung";

                        $mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
                        $mail->setFrom($from)
                            ->setTo($to)
                            ->setSubject($subject)
                            ->setBody($body, 'text/html')
                            ->send();
                        $object->setEmailsProgress(3);
                        break;

                    case "updateproject":
                        // no info on updateproject
                        break;

                    case "releaseproject":
                        //Teacher Info on ReleaseProject

                        $course_details = getCourseDetails($object->getCourseId(), "teacher", "complete");

                        $preheader = "Eine Verschiebungsanfrage für einer Ihrer Lektionen ist eingegangen.";
                        //$intro = "Die Klasse ". $course_details->Class . " hat die Anfrage gestellt, Ihre Lektion ".$course_details->Label." von " . $object->getOriginalLesson()->format("d.m.Y H:i"). " Uhr nach ".$object->getChangedLesson()->format("d.m.Y H:i")." Uhr zu verschieben.";
                        $intro = "Eine neue Verschiebungsanfrage für eine Ihrer Lektionen ist eingegangen. Die Details der Verschiebung sowie die Möglichkeit diese zu beantworten finden Sie im Intranet.";
                        $outro = "Freundliche Grüsse";

                        $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
                        $teacher = $this->getUserInfo($course_details->Teacher,"email,fullname","teacher",true);
                        $to = array($teacher["email"] => $teacher["fullname"]);
                        $body = self::getEmailDesign(array($preheader, $intro, $outro));
                        $subject = "Neue Verschiebungsanfrage der Klasse $course_details->Class";

                        $mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
                        $mail->setFrom($from)
                            ->setTo($to)
                            ->setSubject($subject)
                            ->setBody($body, 'text/html')
                            ->send();

                        $object->setEmailsProgress(1);
                        break;

                }

                break;

            case 'AmosCalamida\Kzoreschedule\Domain\Model\Project':
                //passed object is Project (Student Infos)

                switch ($template) {

                    case "closeproject":
                        //Student Info on CloseProject

                        $changeList = "
";

                        foreach ($object->getChanges() as $change) {

                            switch ($change->getSecretaryAnswer()) {

                                case 1: //change denied
                                    $accentColor = "#d9534f";
                                    $comment = $change->getSecretaryComment();
                                    $changeList .= "
" . getCourseDetails($change->getCourseId(), "student", "label") . ": nicht bewilligt" . (($comment != "") ? "

Kommentar/Auflage des Sekretariats: " . $comment . "

" : "") . "
";
                                    break;

                                case 2: //change accepted
                                    $accentColor = "#5cb85c";
                                    $comment = $change->getSecretaryComment();
                                    $changeList .= "
" . getCourseDetails($change->getCourseId(), "student", "label") . ": bewilligt" . (($comment != "") ? "

Kommentar/Auflage des Sekretariats: " . $comment . "

" : "") . "
";
                                    break;

                            }
                            $change->setEmailsProgress(3);
                        }

                        $changeList .= "
";

                        $preheader = "Das Projekt wurde vom Sekretariat abgeschlossen.";
                        $intro = "Das eingereichte Projekt \"" . $object->getTitle() . "\" wurde vom Sekretariat geprüft. Folgender Entscheid wurde getroffen:

 $changeList";
                        $outro = "Freundliche Grüsse";

                        $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
                        $to = array($this->getUserInfo($object->getUserId(), "email") => $this->getUserInfo($object->getUserId(), "fullname"));
                        $body = self::getEmailDesign(array($preheader, $intro, $outro));
                        $subject = $object->getTitle() . ": Entscheid des Sekretariats";

                        $mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
                        $mail->setFrom($from)
                            ->setTo($to)
                            ->setSubject($subject)
                            ->setBody($body, 'text/html')
                            ->send();

                        break;

                    case "updateproject":
                        //Student Info on UpdateProject
                        $changeList = "
";

                        foreach ($object->getChanges() as $change) {

                            switch ($change->getTeacherAnswer()) {

                                case 0: //change not answered
                                    $accentColor = "#f0ad4e";
                                    $changeList .= "
" . getCourseDetails($change->getCourseId(), "student", "label") . ": Warte auf Antwort
";
                                    break;

                                case 1: //change denied
                                    $accentColor = "#d9534f";
                                    $comment = $change->getTeacherComment();
                                    $changeList .= "
" . getCourseDetails($change->getCourseId(), "student", "label") . ": Nein" . (($comment != "") ? " | " . $comment . "" : "") . "
";
                                    break;

                                case 2: //change accepted
                                    $accentColor = "#5cb85c";
                                    $comment = $change->getTeacherComment();
                                    $changeList .= "
" . getCourseDetails($change->getCourseId(), "student", "label") . ": Ja" . (($comment != "") ? " | " . $comment . "" : "") . "
";
                                    break;

                            }
                            $change->setEmailsProgress(2);
                        }

                        $changeList .= "
";

                        $preheader = "Eine Lehrperson hat soeben ihre Verschiebung im Projekt " . $object->getTitle() . " beantwortet.";
                        $intro = "Eine Verschiebung im Projekt \"" . $object->getTitle() . "\" wurde soeben von der Lehrperson beantwortet. Die aktuelle Übersicht ist hier ersichtlich:

 $changeList";
                        $outro = "Freundliche Grüsse";

                        $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
                        $to = array($this->getUserInfo($object->getUserId(), "email") => $this->getUserInfo($object->getUserId(), "fullname"));
                        $body = self::getEmailDesign(array($preheader, $intro, $outro));
                        $subject = $object->getTitle() . ": Verschiebung beantwortet";

                        $mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
                        $mail->setFrom($from)
                            ->setTo($to)
                            ->setSubject($subject)
                            ->setBody($body, 'text/html')
                            ->send();

                        break;

                    case "releaseproject":

                        // no Info on release project

                        break;

                }
                break;

        }
    }

    /**
     * function getEmailDesign
     *
     * returns the email layout with incorporated message
     *
     * @param array $message - the message divided in parts: 0 => preheader (preview text), 1 => intro (before button), 2 => outro (after button)
     *
     * @return string - html for email
     */

    public static function getEmailDesign($message)
    {

        $preheader = $message[0];
        $intro = $message[1];
        $outro = $message[2];

        $extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['kzoreschedule']);

        $css = '';

        $head = '
    <meta name="viewport" content="width=device-width" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Benachrichtigung</title>' . $css . '';

        $body = '

            ' . $preheader . '

Hallo,

' . $intro . '

                                       ' . $extensionConfiguration["button."]["text"] . '

' . $outro . '

                    ' . $extensionConfiguration["footer."]["text"] . '

 Fragen können an ' . $extensionConfiguration["footer."]["contactText"] . ' gerichtet werden.

        ';

        $html = "

        <!doctype html>

        $head
        $body

        ";

        return $html;

    }

    /**
     * function getAnswerProgress
     *
     * function to get the status of teacher and secretary answers
     *
     * @param \AmosCalamida\Kzoreschedule\Domain\Model\Project $project
     * @param  string $category - the category to get the answers from (either "secretary" or "teacher")
     *
     * @return array - progress(0 => wait, 1 => all disallowed, 2 => all allowed, 3 => partly allowed), allowed, disallowed,wait
     */
    public function getAnswerProgress(\AmosCalamida\Kzoreschedule\Domain\Model\Project $project, $category)
    {

        $allowed = 0;
        $disallowed = 0;
        $wait = 0;

        foreach ($project->getChanges() as $change) {
            switch ($category) {
                case 'teacher':
                    $answer = $change->getTeacherAnswer();
                    break;
                case 'secretary':
                    $answer = $change->getSecretaryAnswer();
                    break;
            }

            switch ($answer) {
                case 0:
                    $wait++;
                    break;

                case 2:
                    $allowed++;
                    break;

                case 1:
                    $disallowed++;
                    break;

            }

        }
        if ($wait > 0) {
            $progress_summary = 0;
        } else {
            if ($allowed > 0 && $disallowed == 0) {
                $progress_summary = 2;
            } elseif ($allowed > 0 && $disallowed > 0) {
                $progress_summary = 3;
            } elseif ($allowed == 0 && $disallowed > 0) {
                $progress_summary = 1;
            }
        }

        return $result = array($progress_summary, $allowed, $disallowed, $wait);
    }

    /**
     * Deactivate errorFlashMessage by overwriting Extbase method.
     * Important for translated error messages
     *
     * @return bool
     */
    public function getErrorFlashMessage()
    {
        return FALSE;
    }

    /**
     * function makeKZORequest
     *
     * do KZO API request
     *
     * @param string $param
     * @param string $list
     * @param string $reference - name of table-column to check for $param
     * @return string
     * @throws \Exception
     */

    function makeKZORequest($param,$reference,$list) {

        $extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['kzoreschedule']);
        $time = time();
        $apiKey = hash("sha256",$extensionConfiguration['kzo_api.']['key'].$time);
        $url = $extensionConfiguration['kzo_api.']['uri'];
        $controller = $extensionConfiguration['kzo_api.']['controller'];

        $request = "$url$controller?requestParam=$param&reference=$reference&apiKey=$apiKey&list=$list&tt=$time";
        $cSession = curl_init();
        curl_setopt($cSession,CURLOPT_URL,$request);
        curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($cSession,CURLOPT_HEADER, false);
        if(! $result = curl_exec($cSession))
        {
           $curl_error = curl_error($cSession);
        }
        if ($extensionConfiguration['api_debug.']['showDebugRequestTime']) {
            $info = curl_getinfo($cSession, CURLINFO_TOTAL_TIME);
            echo("" . (($info < 4) ? ($info < 1) ? "Reaktionszeit KZO: $info s" : "Reaktionszeit KZO: $info s" : "Reaktionszeit KZO: $info s") . "");
        }
        curl_close($cSession);
        $answer_code = json_decode($result)->code;
        if ($answer_code != 200){
            throw new \Exception("Fehler bei der Anfrage! \n Antwort KZO: ".((json_decode($result)->message != "")?json_decode($result)->message:$curl_error)."");
        }

        return json_decode($result)->body;

    }

    /**
     * function getUserInfo
     * Get all information about any FE User
     *
     *
     * @param int $id - id of FE_User
     * @param string $info - columns to get
     * @param string $list - user group
     * @param boolean $skipFELookup - skip loginname lookup (used to pass id directly)
     * @param string $reference - name of table-column to check for param ($id)
     * @return string
     */

    function getUserInfo($id,$info = "*", $list = "student",$skipFELookup = false,$reference = "loginname")
    {
        if (!$skipFELookup) {
            $data = $this->databaseConnection->fullQuoteStr($id, 'fe_users');
            $res = $this->databaseConnection->exec_SELECTquery(
                "username",
                'fe_users',
                '(uid=' . $data . ')'
            );
            $row = $this->databaseConnection->sql_fetch_assoc($res);
            $result = $this->makeKZORequest($row['username'],"loginname" , $list);
        } else {
            $result = $this->makeKZORequest($id,$reference,$list);
        }
        if ($info != "*") {
            $columns = explode(",", str_replace(' ', '', $info));
            if(count($columns) != 1) {
                $return = array();
                foreach ($columns as $column) {
                        $return[$column] = $result->$column;
                }
            } else {
                    $return = $result->$info;
            }
            return $return;
        } else {
            return $result;
        }
    }

}

/**
 * function makeRequest
 *
 * do TAM API request
 *
 * @param string $conditions
 * @return string
 * @throws \Exception
 */
function makeRequest($conditions)
{
    $mod = base64_encode(json_encode($conditions));

    $extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['kzoreschedule']);
    $user = $extensionConfiguration['tam_api.']['username'];
    $pwd = $extensionConfiguration['tam_api.']['password'];
    $uri = $extensionConfiguration['tam_api.']['uri'];
    $controller = $extensionConfiguration['tam_api.']['controller'];
    $school = 'kzo';

    $headers = generateHeaders($user, $pwd, 'gr001');

    $request = "$uri/$school/$controller?mod=$mod";

    $cSession = curl_init();
    curl_setopt($cSession,CURLOPT_URL,$request);
    curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($cSession, CURLOPT_HTTPHEADER, array("Accept:application/xml","X-gr-AuthDate:".$headers['X-gr-AuthDate'], "Authorization:".$headers['Authorization']));
    curl_setopt($cSession,CURLOPT_HEADER, false);
    if(! $result = curl_exec($cSession)) {
        $curl_error = curl_error($cSession);
    }
    if ($extensionConfiguration['api_debug.']['showDebugRequestTime']) {
        $info = curl_getinfo($cSession, CURLINFO_TOTAL_TIME);
        echo("" . (($info < 4) ? ($info < 1) ? "Reaktionszeit TAM: $info s" : "Reaktionszeit TAM: $info s" : "Reaktionszeit TAM: $info s") . "");
    }
    curl_close($cSession);
    $answer_code = json_decode($result)->code;
    if ($answer_code != 200) {
        throw new \Exception("Fehler bei der Anfrage! \n Antwort TAM: ".((json_decode($result)->body != "")?json_decode($result)->body:$curl_error)."");
    }

    return $result;
}

/**
 * function generateHeaders
 *
 * Generate Headers for Timetable REST Access
 *
 * @param string $username
 * @param string $password
 * @param string $prefix
 * @param string $hashAlgorithm
 * @return array
 */

function generateHeaders($username, $password, $prefix, $hashAlgorithm = 'sha1')
{

    $rfc_1123_date = gmdate('D, d M Y H:i:s T', time());
    $xgrdate = utf8_encode($rfc_1123_date);
    $userPasswd = base64_encode(hash($hashAlgorithm, $password, true));

    $signature = base64_encode(hash_hmac($hashAlgorithm, $userPasswd, $xgrdate));
    $auth = $prefix . " " . base64_encode($username) . ":" . $signature;
    $headers = array(
        'X-gr-AuthDate' => $xgrdate,
        'Authorization' => $auth
    );

    return $headers;

}

/**
 * function getTeacherCourses
 * Get all courses given by a teacher
 *
 * @param string $teacher - the short form of the teachers name
 * @return array
 */

function getTeacherCourses($teacher)
{
    $conditions = array('WHERE' => array("Teacher" => "$teacher"), 'ORDER' => 'Class');
    $result = makeRequest($conditions);

    $json = json_decode($result)->body;

    $teacher_courses = array();
    function checkArrayForObject($array, $id)
    {
        return array_filter($array, function ($object) use ($id) {
            return $object->ID == $id;
        });
    }

    foreach ($json as $course) {
        if (!in_array($course->ID, $teacher_courses)) {
            array_push($teacher_courses, $course->ID);
        }
    }

    return $teacher_courses;

}

/**
 * function getCourseDetails
 * Get all courses given by a teacher
 *
 * @param int $id - the id of the course
 * @param string $mode - either teacher, student or secretary (changes returned details)
 * @param string $req - the requested information (either "label", "teacher", "class")
 * @return string
 */

function getCourseDetails($id, $mode, $req)
{
    $conditions = array('WHERE' => array("ID" => "$id"), 'ORDER' => 'Subject');
    $result = makeRequest($conditions);

    $json = json_decode($result)->body;

    $course = $json[0];
    $subjects = array("T" => "Sport", "M" => "Mathematik", "D" => "Deutsch", "B" => "Biologie", "P" => "Physik", "BG" => "Bildnerisches Gestalten", "RL" => "Religion", "GR" => "Griechisch", "L" => "Lateinisch", "SP" => "Spanisch", "IT" => "Italienisch", "G" => "Geschichte", "GG" => "Geografie", "MU" => "Musik", "E" => "Englisch", "F" => "Französisch", "C" => "Chemie", "AM" => "Angewandte Mathematik", "AC" => "Anwendungen des Computers", "FB" => "Französisch Besprechung", "DB" => "Deutsch Besprechung");

    switch ($mode) {
        case "secretary":
            $course->Label = $subjects[$course->Subject] . " (" . $course->Teacher . ") [" . $course->Class . "]";
            break;

        case "teacher":
            $course->Label = $subjects[$course->Subject] . " (" . $course->Class . ")";
            break;

        case "student":
            $course->Label = $subjects[$course->Subject] . " (" . $course->Teacher . ")";
            break;
    }

    switch ($req) {
        case "label":
            return $course->Label;

            break;

        case "teacher":
            return $course->Teacher;

            break;

        case "class":
            return $course->Class;

            break;

        case "complete":
            return $course;
            break;

    }

}


text:
<post>

    <code caption="pdfVerifyTitle">
        <include src='pdfexamples/verifyTitleExample.xml' />
    </code>

</post>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TypeLite {
	/// <summary>
	/// Configures property to be ignored by the script generator.
	/// </summary>
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	public sealed class TsIgnoreAttribute : Attribute {
	}
}


text:
@interface BKPasscodeInputView () {
    BOOL _isKeyboardTypeSet;
}

@property (nonatomic, strong) UILabel           *titleLabel;
@property (nonatomic, strong) UILabel           *messageLabel;
@property (nonatomic, strong) UILabel           *errorMessageLabel;
@property (nonatomic, strong) UIControl         *passcodeField;

@end

@implementation BKPasscodeInputView

@synthesize maximumLength = _maximumLength;
@synthesize keyboardType = _keyboardType;
@synthesize passcodeField = _passcodeField;

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self _initialize];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self _initialize];
    }
    return self;
}

- (void)_initialize
{
    self.backgroundColor = [UIColor clearColor];

    _enabled = YES;
    _passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
    _keyboardType = UIKeyboardTypeNumberPad;
    _maximumLength = 0;

    _titleLabel = [[UILabel alloc] init];
    [[self class] configureTitleLabel:_titleLabel];
    [self addSubview:_titleLabel];

    _messageLabel = [[UILabel alloc] init];
    [[self class] configureMessageLabel:_messageLabel];
    [self addSubview:_messageLabel];

    _errorMessageLabel = [[UILabel alloc] init];
    [[self class] configureErrorMessageLabel:_errorMessageLabel];
    _errorMessageLabel.hidden = YES;
    [self addSubview:_errorMessageLabel];
}

+ (void)configureTitleLabel:(UILabel *)aLabel
{
    aLabel.backgroundColor = [UIColor clearColor];
    aLabel.numberOfLines = 1;
    aLabel.textAlignment = NSTextAlignmentCenter;
    aLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    aLabel.font = [UIFont boldSystemFontOfSize:15.0f];
}

+ (void)configureMessageLabel:(UILabel *)aLabel
{
    aLabel.backgroundColor = [UIColor clearColor];
    aLabel.numberOfLines = 0;
    aLabel.textAlignment = NSTextAlignmentCenter;
    aLabel.lineBreakMode = NSLineBreakByWordWrapping;
    aLabel.font = [UIFont systemFontOfSize:15.0f];
}

+ (void)configureErrorMessageLabel:(UILabel *)aLabel
{
    aLabel.backgroundColor = [UIColor clearColor];
    aLabel.numberOfLines = 0;
    aLabel.textAlignment = NSTextAlignmentCenter;
    aLabel.lineBreakMode = NSLineBreakByWordWrapping;
    aLabel.backgroundColor = [UIColor colorWithRed:0.63 green:0.2 blue:0.13 alpha:1];
    aLabel.textColor = [UIColor whiteColor];
    aLabel.font = [UIFont systemFontOfSize:15.0f];

    aLabel.layer.cornerRadius = 10.0f;
    aLabel.layer.masksToBounds = YES;
}

- (void)setPasscodeStyle:(BKPasscodeInputViewPasscodeStyle)passcodeStyle
{
    if (_passcodeStyle != passcodeStyle) {
        _passcodeStyle = passcodeStyle;

        if (_passcodeField) {
            _passcodeField = nil;
            [self passcodeField];       // load passcode field immediately if already exists before.
        }
    }
}

- (UIControl *)passcodeField
{
    if (nil == _passcodeField) {

        switch (_passcodeStyle) {
            case BKPasscodeInputViewNumericPasscodeStyle:
            {
                if (_maximumLength == 0) {
                    _maximumLength = kDefaultNumericPasscodeMaximumLength;
                }

                if (NO == _isKeyboardTypeSet) {
                    _keyboardType = UIKeyboardTypeNumberPad;
                }

                BKPasscodeField *passcodeField = [[BKPasscodeField alloc] init];
                passcodeField.delegate = self;
                passcodeField.keyboardType = _keyboardType;
                passcodeField.maximumLength = _maximumLength;
                [passcodeField addTarget:self action:@selector(passcodeControlEditingChanged:) forControlEvents:UIControlEventEditingChanged];

                [self setPasscodeField:passcodeField];
                break;
            }

            case BKPasscodeInputViewNormalPasscodeStyle:
            {
                if (_maximumLength == 0) {
                    _maximumLength = kDefaultNormalPasscodeMaximumLength;
                }

                if (NO == _isKeyboardTypeSet) {
                    _keyboardType = UIKeyboardTypeASCIICapable;
                }

                UITextField *textField = [[UITextField alloc] init];
                textField.delegate = self;
                textField.borderStyle = UITextBorderStyleRoundedRect;
                textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
                textField.autocorrectionType = UITextAutocorrectionTypeNo;
                textField.spellCheckingType = UITextSpellCheckingTypeNo;
                textField.enablesReturnKeyAutomatically = YES;
                textField.keyboardType = _keyboardType;
                textField.secureTextEntry = YES;
                textField.font = [UIFont systemFontOfSize:25.0f];
                textField.clearButtonMode = UITextFieldViewModeWhileEditing;
                textField.returnKeyType = UIReturnKeyDone;

                [self setPasscodeField:textField];
                break;
            }
        }
    }

    return _passcodeField;
}

- (void)setPasscodeField:(UIControl *)passcodeField
{
    if (_passcodeField != passcodeField) {

        [_passcodeField removeFromSuperview];
        _passcodeField = passcodeField;
        if (_passcodeField) {
            [self addSubview:_passcodeField];
        }
        [self setNeedsLayout];
    }
}

- (void)setMaximumLength:(NSUInteger)maximumLength
{
    _maximumLength = maximumLength;

    if ([_passcodeField isKindOfClass:[BKPasscodeField class]]) {
        [(BKPasscodeField *)_passcodeField setMaximumLength:maximumLength];
    }
}

- (void)setKeyboardType:(UIKeyboardType)keyboardType
{
    _isKeyboardTypeSet = YES;
    _keyboardType = keyboardType;
    [(id<UITextInputTraits>)_passcodeField setKeyboardType:keyboardType];
}

- (void)setTitle:(NSString *)title
{
    self.titleLabel.text = title;
    [self setNeedsLayout];
}

- (NSString *)title
{
    return self.titleLabel.text;
}

- (void)setMessage:(NSString *)message
{
    self.messageLabel.text = message;
    self.messageLabel.hidden = NO;

    self.errorMessageLabel.text = nil;
    self.errorMessageLabel.hidden = YES;

    [self setNeedsLayout];
}

- (NSString *)message
{
    return self.messageLabel.text;
}

- (void)setErrorMessage:(NSString *)errorMessage
{
    self.errorMessageLabel.text = errorMessage;
    self.errorMessageLabel.hidden = NO;

    self.messageLabel.text = nil;
    self.messageLabel.hidden = YES;

    [self setNeedsLayout];
}

- (NSString *)errorMessage
{
    return self.errorMessageLabel.text;
}

- (NSString *)passcode
{
    switch (self.passcodeStyle) {
        case BKPasscodeInputViewNumericPasscodeStyle:
            return [(BKPasscodeField *)self.passcodeField passcode];
        case BKPasscodeInputViewNormalPasscodeStyle:
            return [(UITextField *)self.passcodeField text];
    }
}

- (void)setPasscode:(NSString *)passcode
{
    switch (self.passcodeStyle) {
        case BKPasscodeInputViewNumericPasscodeStyle:
            [(BKPasscodeField *)self.passcodeField setPasscode:passcode];
            break;
        case BKPasscodeInputViewNormalPasscodeStyle:
             [(UITextField *)self.passcodeField setText:passcode];
             break;
    }
}

#pragma mark - UIView

- (CGFloat)labelPasscodeSpace
{
    return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? kLabelPasscodeSpacePortrait : kLabelPasscodeSpaceLandscape;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    // layout passcode control to center
    [self.passcodeField sizeToFit];

    if ([self.passcodeField isKindOfClass:[UITextField class]]) {
        self.passcodeField.frame = CGRectMake(0, 0, self.frame.size.width - kTextLeftRightSpace * 2.0f, CGRectGetHeight(self.passcodeField.frame) + 10.0f);
    }

    self.passcodeField.center = CGPointMake(CGRectGetWidth(self.frame) * 0.5f, CGRectGetHeight(self.frame) * 0.5f);

    CGFloat maxTextWidth = self.frame.size.width - (kTextLeftRightSpace * 2.0f);
    CGFloat labelPasscodeSpace = [self labelPasscodeSpace];

    // layout title label
    _titleLabel.frame = CGRectMake(kTextLeftRightSpace, 0, maxTextWidth, self.frame.size.height);
    [_titleLabel sizeToFit];

    CGRect rect = _titleLabel.frame;
    rect.origin.x = floorf((self.frame.size.width - CGRectGetWidth(rect)) * 0.5f);
    rect.origin.y = CGRectGetMinY(self.passcodeField.frame) - labelPasscodeSpace - CGRectGetHeight(_titleLabel.frame);

    _titleLabel.frame = rect;

    // layout message label
    if (!_messageLabel.hidden) {
        _messageLabel.frame = CGRectMake(kTextLeftRightSpace, CGRectGetMaxY(self.passcodeField.frame) + labelPasscodeSpace, maxTextWidth, self.frame.size.height);
        [_messageLabel sizeToFit];

        rect = _messageLabel.frame;
        rect.origin.x = floorf((self.frame.size.width - CGRectGetWidth(rect)) * 0.5f);
        _messageLabel.frame = rect;
    }

    // layout error message label
    if (!_errorMessageLabel.hidden) {
        _errorMessageLabel.frame = CGRectMake(0, CGRectGetMaxY(self.passcodeField.frame) + labelPasscodeSpace,
                                              maxTextWidth - kErrorMessageLeftRightPadding * 2.0f,
                                              self.frame.size.height);
        [_errorMessageLabel sizeToFit];

        rect = _errorMessageLabel.frame;
        rect.size.width += (kErrorMessageLeftRightPadding * 2.0f);
        rect.size.height += (kErrorMessageTopBottomPadding * 2.0f);
        rect.origin.x = floorf((self.frame.size.width - rect.size.width) * 0.5f);

        _errorMessageLabel.frame = rect;
    }
}

#pragma mark - UIResponder

- (BOOL)canBecomeFirstResponder
{
    return [self.passcodeField canBecomeFirstResponder];
}

- (BOOL)becomeFirstResponder
{
    return [self.passcodeField becomeFirstResponder];
}

- (BOOL)canResignFirstResponder
{
    return [self.passcodeField canResignFirstResponder];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.passcodeField becomeFirstResponder];
}

#pragma mark - Actions

- (void)passcodeControlEditingChanged:(id)sender
{
    if (![self.passcodeField isKindOfClass:[BKPasscodeField class]]) {
        return;
    }

    BKPasscodeField *passcodeField = (BKPasscodeField *)self.passcodeField;

    if (passcodeField.passcode.length == passcodeField.maximumLength) {
        if ([self.delegate respondsToSelector:@selector(passcodeInputViewDidFinish:)]) {
            [self.delegate passcodeInputViewDidFinish:self];
        }
    }
}

#pragma mark - BKPasscodeFieldDelegate

- (BOOL)passcodeField:(BKPasscodeField *)aPasscodeField shouldInsertText:(NSString *)aText
{
    return self.isEnabled;
}

- (BOOL)passcodeFieldShouldDeleteBackward:(BKPasscodeField *)aPasscodeField
{
    return self.isEnabled;
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (self.isEnabled == NO) {
        return NO;
    }

    NSUInteger length = textField.text.length - range.length + string.length;
    if (length > self.maximumLength) {
        return NO;
    }

    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (self.isEnabled == NO) {
        return NO;
    }

    if ([self.delegate respondsToSelector:@selector(passcodeInputViewDidFinish:)]) {
        [self.delegate passcodeInputViewDidFinish:self];
        return NO;
    } else {
        return YES; // default behavior
    }
}

#pragma mark - NSCopying

- (id)copyWithZone:(NSZone *)zone
{
    BKPasscodeInputView *view = [[[self class] alloc] initWithFrame:self.bounds];
    view.delegate = self.delegate;
    view.autoresizingMask = self.autoresizingMask;
    view.passcodeStyle = self.passcodeStyle;
    view.keyboardType = self.keyboardType;
    view.maximumLength = self.maximumLength;

    return view;
}

@end


text:
class SessionsController < ApplicationController
  def new
  end

  def create
    auth = request.env["omniauth.auth"]

    # Finding an existing or creating a new User object when logging in with Twitter
    if user = User.find_by(provider: auth["provider"], uid: auth["uid"])

    else
      user = User.create_with_omniauth(auth)
      user.set_friends
    end
    # Assigning Session
    session[:user_id] = user.id
    current_user.access_token = auth.credentials.token
    current_user.access_token_secret = auth.credentials.secret
    current_user.save

    redirect_to "/users/#{current_user.neo_id}", :notice => "You've been signed in. | "
  end

  def destroy
    session.clear
    redirect_to root_url, :notice => "You've been signed out."
  end
end


text:
/**
 * Execute PHP function within NodeJS application
 * @package exec-php
 * @version 0.0.6
 */

let fs   = require('fs'),
    path = require('path'),
    cli  = require('./lib/cli.js'),
    exec = require('child_process').exec

/**
 * Create exec-php object that contain user php functions.
 * @param {string} file, Path to user php file.
 * @param {string} bin, Path to php bin file.
 * @param {function} callback, Callback function.
 *  @arg {mixed} error message.
 *  @arg {object} methods Collection of user php functions.
 *  @arg {string} printed string on requiring user php file.
 */
module.exports = (file, bin, callback) => {
    if (!callback) {
        if (typeof bin === 'function') {
            callback = bin
            bin = null
        } else {
            callback = function() {}
        }
    }

    if (!bin) {
        bin = 'php'
    }

    let absFile = file
    let tmpPath = process.cwd()
    let tmpParents = Object.values(require.cache)
        .filter(m => {
            if (!m.children || !m.children.length)
                return

            return m.children.includes(module)
        })

    if (tmpParents && tmpParents.length)
        tmpPath = tmpParents[0].path

    absFile = path.resolve(tmpPath, file)

    let cacheName = `{#CACHE#}${absFile}`

    if (require.cache[cacheName])
        return callback.apply(this, require.cache[cacheName])

    if(!fs.existsSync(absFile))
        throw new Error(`File '${file}' not found.`)

    let token = '{#SEPARATOR#}';
    let sc = `include '${absFile}'; echo '${token}'; echo json_encode(get_defined_functions()['user']);`
    let cmd = [bin, `-r "${sc}";`].join(' ')
    let output = null

    exec(cmd, {cwd: path.dirname(absFile)}, (err, sout, serr) => {
        if (err)
            return callback(err)

        let souts = sout.split(token)

        output = souts[0]

        let funcs = JSON.parse(souts[1])
        let php = {}
        funcs.forEach(func => {
            if (func.includes('\\'))
                return

            php[func] = ((file, bin, func) => {
                return function() {
                    let args = Array.prototype.slice.call(arguments, 0)
                    cli.execute(file, bin, func, args)
                }
            })(absFile, bin, func)
        })

        require.cache[cacheName] = [false, php, output]
        callback(false, php, output)
    })
}


text:
using System;
using System.Configuration;
using System.Net;
using System.Text;
using System.Collections.Generic;

namespace iNQUIRE.Helper
{
    public abstract class JP2HelperBase : IJP2Helper
    {
        public string ApplicationBaseUri { get { return JP2ConfigHelper.ApplicationBaseUri; } }
        public string ResolverUri { get { return JP2ConfigHelper.ResolverUri; } }

        public string ViewerUri { get { return JP2ConfigHelper.ViewerUri; } }
        public string DeepZoomViewerFile { get { return JP2ConfigHelper.DeepZoomViewerFile; } }
        public string DeepZoomQueryParameter { get { return JP2ConfigHelper.DeepZoomQueryParameter; } }
        public int ZoomViewerHeightPx { get { return JP2ConfigHelper.ZoomViewerHeightPx; } }
        public string MediaDirectory { get { return JP2ConfigHelper.MediaDirectory; } }

        public string ProxyResolverFile { get { return JP2ConfigHelper.ProxyResolverFile; } }
        // public string ProxyViewerFile { get { return JP2ConfigHelper.ProxyViewerFile; } }

        public abstract string MakeJP2ImageUri(string jp2resolver, string id, int level, int w, int h);

        public abstract string GetJpeg2000Metadata(string id, bool use_reverse_proxy);

        /*private string _viewerReverseProxy;
        public string ViewerReverseProxy
        {
            get
            {
                if (String.IsNullOrEmpty(_viewerReverseProxy))
                    _viewerReverseProxy = String.Format("{0}{1}", ApplicationBaseUri, ProxyViewerFile);
                return _viewerReverseProxy;
            }
        }*/

        private string _resolverReverseProxy;
        public string ResolverReverseProxy
        {
            get
            {
                if (String.IsNullOrEmpty(_resolverReverseProxy))
                    _resolverReverseProxy = String.Format("{0}{1}", ApplicationBaseUri, ProxyResolverFile);
                return _resolverReverseProxy;
            }
        }

        private string _deepZoomViewerReverseProxy;
        public string DeepZoomViewerReverseProxy
        {
            get
            {
                if (String.IsNullOrEmpty(_deepZoomViewerReverseProxy))
                    _deepZoomViewerReverseProxy = String.Format("{0}{1}", ApplicationBaseUri, DeepZoomViewerFile);
                return _deepZoomViewerReverseProxy;
            }
        }

        public virtual string ReadJpeg2000Metadata(string metadata_uri, string id)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(metadata_uri);

                try
                {
                    var response = (HttpWebResponse)request.GetResponse(); // async here? as this will be blocking, and if djatoka server slow or down then thread poll will lock up
                    // but if async will return straight away so hmm we do need this data immediately for presenting the thumbnail..

                    #region async code
                    //HttpWebRequest webRequest;

                    //void StartWebRequest()
                    //{
                    //    webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
                    //}

                    //void FinishWebRequest(IAsyncResult result)
                    //{
                    //    webRequest.EndGetResponse(result);
                    //}
                    #endregion

                    using (var resStream = response.GetResponseStream())
                    {
                        // throw new Exception("test");
                        int count = 0;
                        var sb = new StringBuilder();
                        var buf = new byte[8192];

                        do
                        {
                            // fill the buffer with data
                            if (resStream != null)
                                count = resStream.Read(buf, 0, buf.Length);

                            // make sure we read some data
                            if (count != 0) // translate from bytes to ASCII text continue building the string
                                sb.Append(Encoding.UTF8.GetString(buf, 0, count));

                        } while (count > 0); // any more data to read?

                        return sb.ToString();
                    }

                }
                catch (Exception ex)
                {
                    LogHelper.StatsLog(null, "ReadJpeg2000Metadata()", String.Format("Failed for id {0}: , Message: {1}, Uri: {2}", id, ex.Message, metadata_uri), null, null);
                    throw new Exception("Couldn't get JPEG2000 Metadata", ex);
                }
            }
            catch (Exception e)
            {
                return String.Format("{{ 'identifier': '{0}', 'imagefile': '{0}', 'width': '1', 'height': '1', 'dwtLevels': '0', 'levels': '0', 'compositingLayerCount': '0' }}", id);
            }
        }

        public virtual String GetImageUri(ImageMetadata imd, string media_directory, double w_img, double h_img)
        {
            string img_src = "";

            if (imd == null)
                return img_src;

            if (imd.Width > 1 )
            {
                double w = imd.Width;
                double h = imd.Height;
                int levels = imd.Levels;

                double ar = w / h;

                if (w > h)
                    h_img = Math.Round((double)w_img / ar); // landscape
                else
                    w_img = Math.Round((double)h_img * ar); // portrait or square

                // calculate level needed, as only using probably around 300-500px images can just take the level
                // above the level which is below the desired size, wouldn't be good logic for requesting higher
                // res images, as the jump would be too great (eg small jump from 192 to 394px but much bigger eg 1536 to 3072px)
                var level = 0;

                for (var i = levels; i > -1; i--)
                {
                    // alert('i: ' + i + ', w_img: ' + w_img + ', w: ' + w + ', h_img: ' + h_img + ', h: ' + h);
                    if ((w < w_img) && (h < h_img))
                    {
                        level = i + 1;
                        break;
                    }
                    w = w / 2;
                    h = h / 2;
                }

                int r_x = Convert.ToInt32(w * 2);
                int r_y = Convert.ToInt32(h * 2);

                img_src = MakeJP2ImageUri(ResolverUri, imd.Identifier, level, r_y, r_x);
            }
            else
            {
                var file = imd.Imagefile;
                if (IsAudioOrVideo(file))
                    file = System.IO.Path.ChangeExtension(file, ".jpg"); // replace audio/video file extension with .jpg so thumbnail can be read for metadata

                img_src = String.Format("{0}{1}.ashx?maxwidth={2}&maxheight={3}", media_directory, file, w_img, h_img);
            }

            return img_src;
        }

        public static bool IsAudioOrVideo(string filename)
        {
            var vid_aud_ext = new List<string>() { ".ogg", ".ogv", ".oga", ".wmv", ".mp4", ".mp3", ".mov", ".webm" };
            foreach (string ext in vid_aud_ext)
            {
                if (filename.EndsWith(ext))
                    return true;
            }
            return false;
        }
    }
}


text:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';
import { PublicHomeComponent } from './public-home/public-home.component';
import { PublicLoginComponent } from './public-login/public-login.component';
import { PublicPostViewComponent } from './public-post-view/public-post-view.component';
import { AdminPostListComponent } from './admin-post-list/admin-post-list.component';
import { AdminPostFormComponent } from './admin-post-form/admin-post-form.component';
import { AdminPostViewComponent } from './admin-post-view/admin-post-view.component';
import { AdminPostEditComponent } from './admin-post-edit/admin-post-edit.component';
import { AuthGuard } from './auth/auth.guard';

const routes: Routes = [

  /* Redirect */
  { path: '', redirectTo: '/', pathMatch: 'full' },

  /* Public */
  { path: '', component: PublicHomeComponent },
  { path: 'login', component: PublicLoginComponent },
  { path: 'post/:url', component: PublicPostViewComponent },

  /* Admin */
  {
    path: 'admin',
    canActivate: [AuthGuard],
    children: [
      { path: '', component: AdminPostListComponent },
      { path: 'posts', component: AdminPostListComponent },
      { path: 'new-post', component: AdminPostFormComponent },
      {
        path: 'post',
        children: [
          { path: 'edit/:id', component: AdminPostEditComponent },
          { path: 'view/:id', component: AdminPostViewComponent },
        ],
      },
    ],
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}


text:
Professores

Os melhores professores, formando uma equipe altamente qualificada, sempre disponível e com o objetivo de ajudar você a se preparar para o futuro!

Plataforma de ensino adaptativo

Plataforma contendo aulas, simulados e outras questões para praticar. As interações do aluno são registradas gerando relatórios que permitem avaliar o processo de aprendizagem, possibilitando oferecer conteúdos e tarefas personalizadas para suprir as carências observadas. Também disponibiliza acesso para os diferentes tipos de usuário: gestor, professor, aluno e responsável.

videoaulas

As videoaulas estão formatadas de modo claro e objetivo. Há resoluções de questões selecionadas de edições anteriores da Prova Brasil, destacando os principais conteúdos cobrados por tais avalições e o melhor modo de responder a elas.


text:
#ifndef __CPU_RUBYTEST_RUBYTESTER_HH__
#define __CPU_RUBYTEST_RUBYTESTER_HH__

#include <iostream>
#include <string>

#include "cpu/rubytest/CheckTable.hh"
#include "mem/mem_object.hh"
#include "mem/packet.hh"
#include "mem/ruby/common/DataBlock.hh"
#include "mem/ruby/common/Global.hh"
#include "mem/ruby/common/SubBlock.hh"
#include "mem/ruby/system/RubyPort.hh"
#include "params/RubyTester.hh"

class RubyTester : public MemObject
{
  public:
    class CpuPort : public SimpleTimingPort
    {
      private:
        RubyTester *tester;

      public:
        CpuPort(const std::string &_name, RubyTester *_tester, int _idx)
            : SimpleTimingPort(_name, _tester), tester(_tester), idx(_idx)
        {}

        int idx;

      protected:
        virtual bool recvTiming(PacketPtr pkt);
        virtual Tick recvAtomic(PacketPtr pkt);
    };

    struct SenderState : public Packet::SenderState
    {
        SubBlock* subBlock;
        Packet::SenderState *saved;

        SenderState(Address addr, int size,
                    Packet::SenderState *sender_state = NULL)
            : saved(sender_state)
        {
            subBlock = new SubBlock(addr, size);
        }

        ~SenderState()
        {
            delete subBlock;
        }
    };

    typedef RubyTesterParams Params;
    RubyTester(const Params *p);
    ~RubyTester();

    virtual Port *getPort(const std::string &if_name, int idx = -1);

    Port* getCpuPort(int idx);

    virtual void init();

    void wakeup();

    void incrementCheckCompletions() { m_checks_completed++; }

    void printStats(std::ostream& out) const {}
    void clearStats() {}
    void printConfig(std::ostream& out) const {}

    void print(std::ostream& out) const;

  protected:
    class CheckStartEvent : public Event
    {
      private:
        RubyTester *tester;

      public:
        CheckStartEvent(RubyTester *_tester)
            : Event(CPU_Tick_Pri), tester(_tester)
        {}
        void process() { tester->wakeup(); }
        virtual const char *description() const { return "RubyTester tick"; }
    };

    CheckStartEvent checkStartEvent;

  private:
    void hitCallback(NodeID proc, SubBlock* data);

    void checkForDeadlock();

    // Private copy constructor and assignment operator
    RubyTester(const RubyTester& obj);
    RubyTester& operator=(const RubyTester& obj);

    CheckTable* m_checkTable_ptr;
    Vector<Time> m_last_progress_vector;

    uint64 m_checks_completed;
    std::vector<CpuPort*> ports;
    uint64 m_checks_to_complete;
    int m_deadlock_threshold;
    int m_num_cpu_sequencers;
    int m_wakeup_frequency;
};

inline std::ostream&
operator<<(std::ostream& out, const RubyTester& obj)
{
    obj.print(out);
    out << std::flush;
    return out;
}

#endif // __CPU_RUBYTEST_RUBYTESTER_HH__


text:
package jdo.order.model.status;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.NotNull;

import jdo.model.BasePersistentModel;
import jdo.order.model.Order;
import jdo.order.model.OrderItem;

@Entity
public class OrderStatus extends BasePersistentModel {

	/**
	 *
	 */
	private static final long	serialVersionUID	= 1L;
	@NotNull
	@ManyToOne
	private OrderStatusType		describedBy;
	@ManyToOne
	private OrderItem			statusForItem;
	@ManyToOne
	private Order				statusForOrder;
	@NotNull
	@Temporal(TemporalType.TIMESTAMP)
	private Date				statusOn;

	public OrderStatusType getDescribedBy() {
		return describedBy;
	}

	public OrderItem getStatusForItem() {
		return statusForItem;
	}

	public Order getStatusForOrder() {
		return statusForOrder;
	}

	public Date getStatusOn() {
		return statusOn;
	}

	@AssertTrue
	public boolean onlyOrderOrItemSet() {
		return (((statusForItem == null) && (statusForOrder != null)) || ((statusForItem != null) && (statusForOrder == null)));
	}

	public void setDescribedBy(OrderStatusType describedBy) {
		this.describedBy = describedBy;
	}

	public void setStatusForItem(OrderItem conditionForItem) {
		this.statusForItem = conditionForItem;
	}

	public void setStatusForOrder(Order conditionForOrder) {
		this.statusForOrder = conditionForOrder;
	}

	public void setStatusOn(Date statusOn) {
		this.statusOn = statusOn;
	}
}


text:
<?php

namespace Valet;

use Exception;
use Illuminate\Container\Container;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Output\ConsoleOutput;

/**
 * Define constants.
 */
if (! defined('VALET_HOME_PATH')) {
    define('VALET_HOME_PATH', $_SERVER['HOME'].'/.config/valet');
}
if (! defined('VALET_STATIC_PREFIX')) {
    define('VALET_STATIC_PREFIX', '41c270e4-5535-4daa-b23e-c269744c2f45');
}

define('VALET_LOOPBACK', '127.0.0.1');
define('VALET_SERVER_PATH', realpath(__DIR__.'/../../server.php'));
define('VALET_LEGACY_HOME_PATH', $_SERVER['HOME'].'/.valet');

define('BREW_PREFIX', (new CommandLine())->runAsUser('printf $(brew --prefix)'));

define('ISOLATED_PHP_VERSION', 'ISOLATED_PHP_VERSION');

/**
 * Output the given text to the console.
 *
 * @param  string  $output
 * @return void
 */
function info($output)
{
    output('<info>'.$output.'</info>');
}

/**
 * Output the given text to the console.
 *
 * @param  string  $output
 * @return void
 */
function warning($output)
{
    output('<fg=red>'.$output.'</>');
}

/**
 * Output a table to the console.
 *
 * @param  array  $headers
 * @param  array  $rows
 * @return void
 */
function table(array $headers = [], array $rows = [])
{
    $table = new Table(new ConsoleOutput);

    $table->setHeaders($headers)->setRows($rows);

    $table->render();
}

/**
 * Output the given text to the console.
 *
 * @param  string  $output
 * @return void
 */
function output($output)
{
    if (isset($_ENV['APP_ENV']) && $_ENV['APP_ENV'] === 'testing') {
        return;
    }

    (new ConsoleOutput())->writeln($output);
}

if (! function_exists('resolve')) {
    /**
     * Resolve the given class from the container.
     *
     * @param  string  $class
     * @return mixed
     */
    function resolve($class)
    {
        return Container::getInstance()->make($class);
    }
}

/**
 * Swap the given class implementation in the container.
 *
 * @param  string  $class
 * @param  mixed  $instance
 * @return void
 */
function swap($class, $instance)
{
    Container::getInstance()->instance($class, $instance);
}

if (! function_exists('retry')) {
    /**
     * Retry the given function N times.
     *
     * @param  int  $retries
     * @param  callable  $retries
     * @param  int  $sleep
     * @return mixed
     */
    function retry($retries, $fn, $sleep = 0)
    {
        beginning:
        try {
            return $fn();
        } catch (Exception $e) {
            if (! $retries) {
                throw $e;
            }

            $retries--;

            if ($sleep > 0) {
                usleep($sleep * 1000);
            }

            goto beginning;
        }
    }
}

/**
 * Verify that the script is currently running as "sudo".
 *
 * @return void
 */
function should_be_sudo()
{
    if (! isset($_SERVER['SUDO_USER'])) {
        throw new Exception('This command must be run with sudo.');
    }
}

if (! function_exists('tap')) {
    /**
     * Tap the given value.
     *
     * @param  mixed  $value
     * @param  callable  $callback
     * @return mixed
     */
    function tap($value, callable $callback)
    {
        $callback($value);

        return $value;
    }
}

if (! function_exists('ends_with')) {
    /**
     * Determine if a given string ends with a given substring.
     *
     * @param  string  $haystack
     * @param  string|array  $needles
     * @return bool
     */
    function ends_with($haystack, $needles)
    {
        foreach ((array) $needles as $needle) {
            if (substr($haystack, -strlen($needle)) === (string) $needle) {
                return true;
            }
        }

        return false;
    }
}

if (! function_exists('starts_with')) {
    /**
     * Determine if a given string starts with a given substring.
     *
     * @param  string  $haystack
     * @param  string|string[]  $needles
     * @return bool
     */
    function starts_with($haystack, $needles)
    {
        foreach ((array) $needles as $needle) {
            if ((string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0) {
                return true;
            }
        }

        return false;
    }
}

/**
 * Get the user.
 */
function user()
{
    if (! isset($_SERVER['SUDO_USER'])) {
        return $_SERVER['USER'];
    }

    return $_SERVER['SUDO_USER'];
}


text:
"""
    If you are looking for original implementation of TF-IDF based word replacing, you can access it via the following link.
    nlpaug's implementation is slight different from original implementation in random behavior section.
    https://github.com/google-research/uda/blob/master/text/augmentation/word_level_augment.py
"""

import os
import math
import numpy as np

from nlpaug.model.word_stats import WordStatistics

class TfIdf(WordStatistics):
    WORD_2_IDF_FILE_NAME = "tfidfaug_w2idf.txt"
    WORD_2_TFIDF_FILE_NAME = "tfidfaug_w2tfidf.txt"

    def __init__(self, model_path=None, normalize=True, cache=True):
        super().__init__(cache)
        self.w2idf = {}

        self.tokens = []
        self.tfidf_scores = []
        self.w2tfidf = {}

        if model_path:
            self.read(model_path)
        self.normalize = normalize

    @classmethod
    def _normalize(cls, data):
        """
            Quoted from https://arxiv.org/pdf/1904.12848.pdf.
            // We set a high probability for replacing words with low TF-IDF scores and
            // set a low probability for replacing words with high TF-IDF scores
        """
        data = data.max() - np.copy(data)
        if data.sum() == 0:
            return [0]
        return data / data.sum()

    def cal_tfidf(self, word_idxes, tokens, normalize=True):
        """
            Different from traditional TF-IDF calculation, original authors treat handle single token is separately.
            Even though they are same, they will calculate TF-IDF separately. Possible reason is that they want
            to guarantee random behavior independently.
        """
        tfidf = []
        for idx in word_idxes:
            token = tokens[idx]
            tfidf.append(self.w2idf[token] / len(tokens))

        tfidf = np.array(tfidf)

        if normalize:
            return self._normalize(tfidf)

        return tfidf

    def cal_idf(self, docs_tokens):
        # Find number of documents where token t appears
        word_cnt_in_doc = {}
        for tokens in docs_tokens:
            for t in tokens:
                if t not in word_cnt_in_doc:
                    word_cnt_in_doc[t] = 0
                word_cnt_in_doc[t] += 1

        idf = {}
        for t, doc_cnt in word_cnt_in_doc.items():
            idf[t] = math.log(len(docs_tokens) / doc_cnt)

        return idf

    def train(self, data):
        self.w2idf = self.cal_idf(data)
        self.tokens = []
        self.tfidf_scores = []
        self.w2tfidf = {}

        # Build word to TF-IDF score mapping
        for tokens in data:
            for t in tokens:
                if t not in self.w2tfidf:
                    self.w2tfidf[t] = 0
                self.w2tfidf[t] += 1 / len(tokens) * self.w2idf[t]

        if self.normalize:
            tfidf_scores = list(self.w2tfidf.values())
            tfidf_scores = self._normalize(np.array(tfidf_scores))
            for i, t in enumerate(self.w2tfidf):
                self.w2tfidf[t] = tfidf_scores[i]

        self.tokens = list(self.w2tfidf.keys())
        self.tfidf_scores = list(self.w2tfidf.values())

    def save(self, model_path):
        with open(os.path.join(model_path, self.WORD_2_IDF_FILE_NAME), "w", encoding="utf-8") as f:
            for w, s in self.w2idf.items():
                f.write(str(w) + ' ' + str(s) + '\n')

        with open(os.path.join(model_path, self.WORD_2_TFIDF_FILE_NAME), "w", encoding="utf-8") as f:
            for w, s in self.w2tfidf.items():
                f.write(str(w) + ' ' + str(s) + '\n')

    def read(self, model_path):
        self.w2idf = {}
        self.w2tfidf = {}

        with open(os.path.join(model_path, self.WORD_2_IDF_FILE_NAME), 'r', encoding="utf-8") as f:
            for line in f.readlines():
                # Fix https://github.com/makcedward/nlpaug/issues/201
                try:
                    w, s = line.split(' ')
                except:
                    raise ValueError('line may include more than 1 space. Please check {}'.format(line))
                self.w2idf[w] = float(s)

        with open(os.path.join(model_path, self.WORD_2_TFIDF_FILE_NAME), 'r', encoding="utf-8") as f:
            for line in f.readlines():
                # Fix https://github.com/makcedward/nlpaug/issues/201
                try:
                    w, s = line.split(' ')
                except:
                    raise ValueError('line may include more than 1 space. Please check {}'.format(line))
                self.w2tfidf[w] = float(s)
        self.tokens = list(self.w2tfidf.keys())
        self.tfidf_scores = list(self.w2tfidf.values())

    def predict(self, data, top_k):
        target_idxes = self.choice(self.tokens, p=self.tfidf_scores, size=top_k)
        target_words = [self.tokens[i] for i in target_idxes]
        return target_words


text:
<!DOCTYPE html>
{% load compress %}
{% load static %}
{% load bootstrap3 %}
{% load i18n %}

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{% block title %}{% endblock %} [GTARacing.net]</title>
  {% bootstrap_css %}

  {% block bootstrap3_extra_head %}
    <link rel="stylesheet" type="text/css"
          href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" />
    {% compress css %}
      <link rel="stylesheet" type="text/css"
            href="{% static "bootstrap-multiselect/dist/css/bootstrap-multiselect.css" %}" />
      <link rel="stylesheet" type="text/css"
            href="{% static "bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.css" %}" />
    <link rel="stylesheet" type="text/css"
          href="{% static "global.css" %}" />
    <link rel="stylesheet" type="text/css"
          href="{% static "bootstrap-combobox.css" %}" />
    <link rel="stylesheet" type="text/css"
          href="{% static "bootstrap-dialog.css" %}" />
      <link rel="stylesheet" type="text/css"
            href="{% static "xbbcode/xbbcode.css" %}" />
    {% endcompress %}
    <link rel="apple-touch-icon" sizes="57x57" href="{% static "/fav2/apple-icon-57x57.png" %}">
    <link rel="apple-touch-icon" sizes="60x60" href="{% static "/fav2/apple-icon-60x60.png" %}">
    <link rel="apple-touch-icon" sizes="72x72" href="{% static "/fav2/apple-icon-72x72.png" %}">
    <link rel="apple-touch-icon" sizes="76x76" href="{% static "/fav2/apple-icon-76x76.png" %}">
    <link rel="apple-touch-icon" sizes="114x114" href="{% static "/fav2/apple-icon-114x114.png" %}">
    <link rel="apple-touch-icon" sizes="120x120" href="{% static "/fav2/apple-icon-120x120.png" %}">
    <link rel="apple-touch-icon" sizes="144x144" href="{% static "/fav2/apple-icon-144x144.png" %}">
    <link rel="apple-touch-icon" sizes="152x152" href="{% static "/fav2/apple-icon-152x152.png" %}">
    <link rel="apple-touch-icon" sizes="180x180" href="{% static "/fav2/apple-icon-180x180.png" %}">
    <link rel="icon" type="image/png" sizes="192x192"  href="{% static "/fav2/android-icon-192x192.png" %}">
    <link rel="icon" type="image/png" sizes="32x32" href="{% static "/fav2/favicon-32x32.png" %}">
    <link rel="icon" type="image/png" sizes="96x96" href="{% static "/fav2/favicon-96x96.png" %}">
    <link rel="icon" type="image/png" sizes="16x16" href="{% static "/fav2/favicon-16x16.png" %}">
    <link rel="manifest" href="{% static "/fav2/manifest.json" %}">
    <link href="https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:700" rel="stylesheet">

    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="{% static "/fav2/ms-icon-144x144.png" %}">
    <meta name="theme-color" content="#ffffff">
  {% endblock %}
  {% block trax_extra_head %}{% endblock %}

{% block bootstrap3_content %}

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
          Toggle navigation

        </button>

GTARacing.net

Tracks

Vehicles

Players

              Tools

                Random grid generator...

                Create a hotlapping event...

            {% if request.user.is_authenticated %}

                {{ request.user }}

My page

Log out

            {% else %}
               Login/Register

Returning user?
Login here:

                  <form class="navbar-form" action="{% url "login" %}" method="post">
                    {% csrf_token %}<input type="hidden" name="next" value="/">
                    Username: <input class="form-control" type="text" name="username">

                    Password: <input class="form-control" type="password" name="password">

                    <button type="submit" class="btn btn-primary">Login</button>
                  </form>

New on this site?

                  Register now!

            {% endif %}

{% autoescape off %}{% bootstrap_messages %}{% endautoescape %}
    {% block content %}nothing here.{% endblock %}

  {% compress js %}

  {% endcompress %}
  {% block trax_extra_script %}{% endblock %}
{% endblock %}


text:
package uk.gov.hmrc.ct.computations

import uk.gov.hmrc.ct.box.{CtBoxIdentifier, CtOptionalInteger, Input}

case class CP36(value: Option[Int]) extends CtBoxIdentifier(name = "Administration and office expenses") with CtOptionalInteger with Input

object CP36 {

  def apply(int: Int): CP36 = CP36(Some(int))

}


text:
import React from 'react';

// components
import BrowsersList from './BrowsersList';

function IE() {
  return (

          Welcome, please use one of our preferred browsers

        <BrowsersList />

          Those button link to the official browser webpages. You can choose platform and language there.

  );
}

export default IE;


text:
package com.tngtech.archunit.junit.internal;

import java.lang.annotation.Retention;

import com.tngtech.archunit.ArchConfiguration;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchIgnore;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.junit.internal.ArchUnitRunnerInternal.SharedCache;
import com.tngtech.archunit.lang.ArchRule;
import com.tngtech.archunit.testutil.ArchConfigurationRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunNotifier;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;

import static com.tngtech.archunit.core.domain.TestUtils.importClassesWithContext;
import static com.tngtech.archunit.junit.internal.ArchUnitRunnerRunsRuleFieldsTest.ArchTestWithPrivateInstanceField.PRIVATE_RULE_FIELD_NAME;
import static com.tngtech.archunit.junit.internal.ArchUnitRunnerRunsRuleFieldsTest.IgnoredArchTest.RULE_ONE_IN_IGNORED_TEST;
import static com.tngtech.archunit.junit.internal.ArchUnitRunnerRunsRuleFieldsTest.IgnoredArchTest.RULE_TWO_IN_IGNORED_TEST;
import static com.tngtech.archunit.junit.internal.ArchUnitRunnerRunsRuleFieldsTest.SomeArchTest.FAILING_FIELD_NAME;
import static com.tngtech.archunit.junit.internal.ArchUnitRunnerRunsRuleFieldsTest.SomeArchTest.IGNORED_FIELD_NAME;
import static com.tngtech.archunit.junit.internal.ArchUnitRunnerRunsRuleFieldsTest.SomeArchTest.SATISFIED_FIELD_NAME;
import static com.tngtech.archunit.junit.internal.ArchUnitRunnerRunsRuleFieldsTest.WrongArchTestWrongFieldType.NO_RULE_AT_ALL_FIELD_NAME;
import static com.tngtech.archunit.junit.internal.ArchUnitRunnerTestUtils.BE_SATISFIED;
import static com.tngtech.archunit.junit.internal.ArchUnitRunnerTestUtils.NEVER_BE_SATISFIED;
import static com.tngtech.archunit.junit.internal.ArchUnitRunnerTestUtils.newRunnerFor;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class ArchUnitRunnerRunsRuleFieldsTest {
    @Rule
    public final MockitoRule mockitoRule = MockitoJUnit.rule();
    @Rule
    public final ArchConfigurationRule archConfigurationRule = new ArchConfigurationRule();

    @Mock
    private SharedCache cache;
    @Mock
    private ClassCache classCache;

    @Mock
    private RunNotifier runNotifier;

    @Captor
    private ArgumentCaptor<Description> descriptionCaptor;

    @Captor
    private ArgumentCaptor<Failure> failureCaptor;

    @InjectMocks
    private ArchUnitRunnerInternal runner = ArchUnitRunnerTestUtils.newRunnerFor(SomeArchTest.class);

    private final JavaClasses cachedClasses = importClassesWithContext(Object.class);

    @Before
    public void setUp() {
        when(cache.get()).thenReturn(classCache);
        when(classCache.getClassesToAnalyzeFor(any(Class.class), any(ClassAnalysisRequest.class))).thenReturn(cachedClasses);
    }

    @Test
    public void should_find_children() {
        assertThat(runner.getChildren()).as("Rules defined in Test Class").hasSize(3);
    }

    @Test
    public void should_start_rule() {
        ArchTestExecution satisfiedRule = getRule(SATISFIED_FIELD_NAME);

        runner.runChild(satisfiedRule, runNotifier);

        verify(runNotifier).fireTestStarted(descriptionCaptor.capture());
        assertThat(descriptionCaptor.getValue().toString()).contains(SATISFIED_FIELD_NAME);
    }

    @Test
    public void should_accept_satisfied_rule() {
        ArchTestExecution satisfiedRule = getRule(SATISFIED_FIELD_NAME);

        runner.runChild(satisfiedRule, runNotifier);

        verifyTestFinishedSuccessfully(SATISFIED_FIELD_NAME);
    }

    @Test
    public void should_allow_instance_fields_of_all_visibility() {
        ArchUnitRunnerInternal runner = newRunnerFor(ArchTestWithPrivateInstanceField.class, cache);

        runner.runChild(ArchUnitRunnerTestUtils.getRule(PRIVATE_RULE_FIELD_NAME, runner), runNotifier);

        verifyTestFinishedSuccessfully(PRIVATE_RULE_FIELD_NAME);
    }

    @Test
    public void should_allow_instance_field_in_abstract_base_class() {
        ArchUnitRunnerInternal runner = newRunnerFor(ArchTestWithAbstractBaseClass.class, cache);

        runner.runChild(ArchUnitRunnerTestUtils.getRule(AbstractBaseClass.INSTANCE_FIELD_NAME, runner), runNotifier);

        verifyTestFinishedSuccessfully(AbstractBaseClass.INSTANCE_FIELD_NAME);
    }

    @Test
    public void should_fail_on_wrong_field_type() {
        ArchUnitRunnerInternal runner = newRunnerFor(WrongArchTestWrongFieldType.class, cache);

        assertThatThrownBy(
                () -> runner.runChild(ArchUnitRunnerTestUtils.getRule(NO_RULE_AT_ALL_FIELD_NAME, runner), runNotifier)
        )
                .hasMessage("Rule field %s.%s to check must be of type %s",
                        WrongArchTestWrongFieldType.class.getSimpleName(), NO_RULE_AT_ALL_FIELD_NAME, ArchRule.class.getSimpleName());
    }

    @Test
    public void should_fail_unsatisfied_rule() {
        ArchTestExecution satisfiedRule = getRule(FAILING_FIELD_NAME);

        runner.runChild(satisfiedRule, runNotifier);

        verify(runNotifier).fireTestFailure(failureCaptor.capture());
        Failure failure = failureCaptor.getValue();
        assertThat(failure.getDescription().toString()).contains(FAILING_FIELD_NAME);
        assertThat(failure.getException()).isInstanceOf(AssertionError.class);
    }

    @Test
    public void should_skip_ignored_rule() {
        ArchTestExecution satisfiedRule = getRule(IGNORED_FIELD_NAME);

        runner.runChild(satisfiedRule, runNotifier);

        verify(runNotifier).fireTestIgnored(descriptionCaptor.capture());
        assertThat(descriptionCaptor.getValue().toString()).contains(IGNORED_FIELD_NAME);
    }

    @Test
    public void should_skip_ignored_test() {
        ArchUnitRunnerInternal runner = newRunnerFor(IgnoredArchTest.class, cache);

        runner.runChild(ArchUnitRunnerTestUtils.getRule(RULE_ONE_IN_IGNORED_TEST, runner), runNotifier);
        runner.runChild(ArchUnitRunnerTestUtils.getRule(RULE_TWO_IN_IGNORED_TEST, runner), runNotifier);

        verify(runNotifier, times(2)).fireTestIgnored(descriptionCaptor.capture());

        assertThat(descriptionCaptor.getAllValues()).extractingResultOf("getMethodName")
                .contains(RULE_ONE_IN_IGNORED_TEST, RULE_TWO_IN_IGNORED_TEST);
    }

    @Test
    public void should_pass_annotations_of_rule_field() {
        ArchUnitRunnerInternal runner = newRunnerFor(ArchTestWithFieldWithAdditionalAnnotation.class, cache);

        runner.runChild(ArchUnitRunnerTestUtils.getRule(ArchTestWithFieldWithAdditionalAnnotation.TEST_FIELD_NAME, runner), runNotifier);

        verify(runNotifier).fireTestFinished(descriptionCaptor.capture());
        Description description = descriptionCaptor.getValue();
        assertThat(description.getAnnotation(SomeAnnotation.class)).as("expected annotation").isNotNull();
    }

    @Test
    public void underscores_in_field_name_are_replaced_with_blanks_if_property_is_set_to_true() {
        ArchUnitRunnerInternal runner = newRunnerFor(ArchTestWithFieldWithUnderscoresInName.class, cache);

        ArchConfiguration.get().setProperty(DisplayNameResolver.JUNIT_DISPLAYNAME_REPLACE_UNDERSCORES_BY_SPACES_PROPERTY_NAME, "true");

        runner.runChild(ArchUnitRunnerTestUtils.getRule(ArchTestWithFieldWithUnderscoresInName.TEST_FIELD_NAME, runner), runNotifier);

        verify(runNotifier).fireTestFinished(descriptionCaptor.capture());
        Description description = descriptionCaptor.getValue();
        assertThat(description.getDisplayName()).as("expected display name").startsWith("some test Field(");
    }

    @Test
    public void original_field_name_is_used_as_displayname_if_property_is_set_to_false() {
        ArchUnitRunnerInternal runner = newRunnerFor(ArchTestWithFieldWithUnderscoresInName.class, cache);

        ArchConfiguration.get().setProperty(DisplayNameResolver.JUNIT_DISPLAYNAME_REPLACE_UNDERSCORES_BY_SPACES_PROPERTY_NAME, "false");

        runner.runChild(ArchUnitRunnerTestUtils.getRule(ArchTestWithFieldWithUnderscoresInName.TEST_FIELD_NAME, runner), runNotifier);

        verify(runNotifier).fireTestFinished(descriptionCaptor.capture());
        Description description = descriptionCaptor.getValue();
        assertThat(description.getDisplayName()).as("expected display name").startsWith("some_test_Field(");
    }

    private ArchTestExecution getRule(String name) {
        return ArchUnitRunnerTestUtils.getRule(name, runner);
    }

    private void verifyTestFinishedSuccessfully(String expectedDescriptionMethodName) {
        verifyTestFinishedSuccessfully(runNotifier, descriptionCaptor, expectedDescriptionMethodName);
    }

    static void verifyTestFinishedSuccessfully(RunNotifier runNotifier, ArgumentCaptor<Description> descriptionCaptor,
            String expectedDescriptionMethodName) {
        verify(runNotifier, never()).fireTestFailure(any(Failure.class));
        verify(runNotifier).fireTestFinished(descriptionCaptor.capture());
        Description description = descriptionCaptor.getValue();
        assertThat(description.getMethodName()).isEqualTo(expectedDescriptionMethodName);
    }

    @AnalyzeClasses(packages = "some.pkg")
    public static class SomeArchTest {
        static final String SATISFIED_FIELD_NAME = "someSatisfiedRule";
        static final String FAILING_FIELD_NAME = "someFailingRule";
        static final String IGNORED_FIELD_NAME = "someIgnoredRule";

        @ArchTest
        public static final ArchRule someSatisfiedRule = classes().should(BE_SATISFIED);

        @ArchTest
        public static final ArchRule someFailingRule = classes().should(NEVER_BE_SATISFIED);

        @ArchIgnore
        @ArchTest
        public static final ArchRule someIgnoredRule = classes().should(NEVER_BE_SATISFIED);
    }

    @SuppressWarnings("WeakerAccess")
    @AnalyzeClasses(packages = "some.pkg")
    public static class ArchTestWithPrivateInstanceField {
        static final String PRIVATE_RULE_FIELD_NAME = "privateField";

        @ArchTest
        private ArchRule privateField = classes().should(BE_SATISFIED);
    }

    @SuppressWarnings("WeakerAccess")
    @AnalyzeClasses(packages = "some.pkg")
    public static class ArchTestWithAbstractBaseClass extends AbstractBaseClass {
    }

    abstract static class AbstractBaseClass {
        static final String INSTANCE_FIELD_NAME = "abstractBaseClassInstanceField";

        @ArchTest
        ArchRule abstractBaseClassInstanceField = classes().should(BE_SATISFIED);
    }

    @AnalyzeClasses(packages = "some.pkg")
    public static class WrongArchTestWrongFieldType {
        static final String NO_RULE_AT_ALL_FIELD_NAME = "noRuleAtAll";

        @ArchTest
        public static Object noRuleAtAll = new Object();
    }

    @ArchIgnore
    @AnalyzeClasses(packages = "some.pkg")
    public static class IgnoredArchTest {
        static final String RULE_ONE_IN_IGNORED_TEST = "someRuleOne";
        static final String RULE_TWO_IN_IGNORED_TEST = "someRuleTwo";

        @ArchTest
        public static final ArchRule someRuleOne = classes().should(NEVER_BE_SATISFIED);

        @ArchTest
        public static final ArchRule someRuleTwo = classes().should(NEVER_BE_SATISFIED);
    }

    @AnalyzeClasses(packages = "some.pkg")
    public static class ArchTestWithFieldWithAdditionalAnnotation {
        static final String TEST_FIELD_NAME = "annotatedTestField";

        @SomeAnnotation
        @ArchTest
        public static final ArchRule annotatedTestField = classes().should(NEVER_BE_SATISFIED);
    }

    @AnalyzeClasses(packages = "some.pkg")
    public static class ArchTestWithFieldWithUnderscoresInName {
        static final String TEST_FIELD_NAME = "some_test_Field";

        @ArchTest
        public static final ArchRule some_test_Field = classes().should(NEVER_BE_SATISFIED);
    }

    @Retention(RUNTIME)
    @interface SomeAnnotation {
    }
}


text:
require File.expand_path('../../test_helper', __FILE__)

class HostLocalesTest < integration_test_suite_parent_class

  include RouteTranslator::ConfigurationHelper

  def setup
    config_host_locales('*.es' => 'es', 'ru.*.com' => 'ru')
    Dummy::Application.reload_routes!
  end

  def teardown
    config_host_locales({})
    Dummy::Application.reload_routes!
  end

  def test_root_path
    ## root of es com
    host! 'www.testapp.es'
    get '/'
    assert_equal 'es', @response.body
    assert_response :success

    ## root of ru com
    host! 'ru.testapp.com'
    get '/'
    assert_equal 'ru', @response.body
    assert_response :success
  end

  def test_explicit_path
    ## native es route on es com
    host! 'www.testapp.es'
    get '/dummy'
    assert_equal 'es', @response.body
    assert_response :success

    ## ru route on es com
    host! 'www.testapp.es'
    get URI.escape('/ru/манекен')
    assert_equal 'ru', @response.body
    assert_response :success

    ## native ru route on ru com
    host! 'ru.testapp.com'
    get URI.escape('/манекен')
    assert_equal 'ru', @response.body
    assert_response :success

    ## es route on ru com
    host! 'ru.testapp.com'
    get '/es/dummy'
    assert_equal 'es', @response.body
    assert_response :success
  end

end


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

<title>groovy.jmx.builder (groovy 2.1.7 API)</title>
<META NAME="keywords" CONTENT="groovy.jmx.builder package">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<link href="../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../groovy.ico" type="image/x-icon" rel="icon">

      Overview
    Package
      Class

      Deprecated
      Index
      Help

    Groovy 2.1.7

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Package groovy.jmx.builder

 Classes for the JMX Builder.

    Interface Summary

        JmxEventEmitterMBean
        This is the management interface for JmxEventEmitter.

    Class Summary

        JmxAttributeInfoManager
        This class is responsible for assembling JMX Attribute Info from the meta map.

        JmxBeanExportFactory
        This factory returns a container node for all other nodes that are used to collect meta data for resources that
 are exported to the MBeanServer for management.

        JmxBeanFactory
        This factory returns the bean() node.

        JmxBeanInfoManager
        The JmxBeanInfoManager creates fully-described model mbean info object using the underlying meta map.

        JmxBeansFactory
        @author vladimir

        JmxBuilder
        This is JmxBuilder's factory builder class.

        JmxBuilderModelMBean
        The JmxBuilderModelMBean is the MBean class that proxies exported POGO/POJO inside the MBeanServer.

        JmxBuilderTools
        This is a utility class used as a helper for JmxBuilder.

        JmxClientConnectorFactory
        This is the factory for node JmxBuilder.connectorClient.

        JmxEmitterFactory
        This class is the factory for the emitter node.

        JmxEventEmitter
        The JmxEventEmitter is a JMX Broadcaster class that is used to send generic events on the MBeanServer's
 event bus.

        JmxEventListener
        The JmxEventListener class is used by the builder to listen to events on the event bus.

        JmxListenerFactory
        This factory class is used to create an listener() node for JmxBuilder.

        JmxMetaMapBuilder
        The JmxMetaMapBuilder class is used to collect meta data passed in JmxBuilder nodes.

        JmxOperationInfoManager
        This class is responsible for assembling JMX Operation Info from the meta map.

        JmxServerConnectorFactory
        This is the server connector factory used for node JmxBuilder.connectorServer().

        JmxTimerFactory
        The JmxTimerFactory class generates a timer() node for JmxBuilder.

    Exception Summary

        JmxBuilderException
        Runtime exception used by JmxBuilder.

Copyright &copy; 2003-2013 The Codehaus. All rights reserved.