text:
<?php
namespace Chamilo\Application\Survey\Cron\ExportJob;

use Chamilo\Application\Survey\Cron\Storage\DataManager;
use Chamilo\Application\Survey\Storage\DataClass\Answer;
use Chamilo\Configuration\Configuration;
use Chamilo\Core\Repository\ContentObject\Survey\Page\Question\Matching\Storage\DataClass\Matching;
use Chamilo\Core\Repository\ContentObject\Survey\Page\Question\Matrix\Storage\DataClass\Matrix;
use Chamilo\Core\Repository\ContentObject\Survey\Page\Question\MultipleChoice\Storage\DataClass\MultipleChoice;
use Chamilo\Core\Repository\ContentObject\Survey\Page\Question\Open\Storage\DataClass\Open;
use Chamilo\Core\Repository\ContentObject\Survey\Page\Question\Rating\Storage\DataClass\Rating;
use Chamilo\Core\Repository\ContentObject\Survey\Page\Question\Select\Storage\DataClass\Select;
use Chamilo\Core\Repository\Storage\DataClass\ComplexContentObjectItem;
use Chamilo\Libraries\Architecture\Application\Application;
use Chamilo\Libraries\File\Redirect;
use Chamilo\Libraries\Mail\Mailer\MailerFactory;
use Chamilo\Libraries\Mail\ValueObject\Mail;
use Chamilo\Libraries\Platform\Translation;
use Chamilo\Libraries\Storage\Parameters\DataClassRetrievesParameters;
use Chamilo\Libraries\Storage\Query\Condition\EqualityCondition;
use Chamilo\Libraries\Storage\Query\Variable\PropertyConditionVariable;

ini_set("memory_limit", "-1");
ini_set("max_execution_time", "0");
class ExportJobManager
{
    const TYPE_EXPORT_FINISHED = 1;
    const TYPE_EXPORT_NOT_FINISHED = 2;
    const TYPE_DOCUMENT_NOT_AVAILABLE = 3;
    const TYPE_SYNCHRONIZATION_FINISHED = 4;
    const TYPE_SYNCHRONIZATION_NOT_FINISHED = 5;
    const STATUS_NO_DOCUMENT_REGISTRATION = 1;
    const STATUS_NO_DOCUMENT_CREATED = 2;
    const STATUS_DOCUMENT_CREATED = 3;
    const STATUS_ANSWERS_SYNCHRONIZED = 4;
    const STATUS_ANSWERS_NOT_SYNCHRONIZED = 5;

    private static $questions_cache;

    static function launch_job()
    {

        // $conditions = array();
        // $conditions[] = new EqualityCondition(ExportJob :: PROPERTY_UUID, '0');
        // $conditions[] = new EqualityCondition(ExportJob :: PROPERTY_STATUS, ExportJob :: STATUS_NEW);
        // $condition = new AndCondition($conditions);
        // $export_jobs = DataManager :: retrieve_export_jobs($condition);

        // $UUID = uniqid($_SERVER['SERVER_ADDR'], true);

        // echo ' UUID=' . $UUID . "\n";

        // while ($export_job = $export_jobs->next_result())
        // {
        // $export_job->set_UUID($UUID);
        // $export_job->update();
        // }

        // $conditions = array();
        // $conditions[] = new EqualityCondition(ExportJob :: PROPERTY_UUID, $UUID);
        // $conditions[] = new EqualityCondition(ExportJob :: PROPERTY_STATUS, ExportJob :: STATUS_NEW);
        // $condition = new AndCondition($conditions);
        // $export_jobs = DataManager :: retrieve_export_jobs($condition);

        // while ($export_job = $export_jobs->next_result())
        // {

        // if ($export_job->get_export_type() == ExportJob :: EXPORT_TYPE_TEMPLATE_EXPORT)
        // {

        // $export_template = DataManager ::
        // get_instance()->retrieve_export_template_by_id($export_job->get_export_template_id());

        // $condition = new EqualityCondition(Export :: PROPERTY_EXPORT_JOB_ID,
        // $export_job->get_id());

        // $export_tracker = Tracker :: get_singular_data(Export :: CLASS_NAME,
        // \Chamilo\Application\Survey\Manager :: APPLICATION_NAME, $condition);

        // $export_type = 'xlsx';
        // $export = Exporter :: factory($export_template, $export_template->get_publication_id());
        // $file = $export->save();

        // $conditions = array();
        // $conditions[] = new EqualityCondition(Registration :: PROPERTY_TYPE, Registration :: TYPE_CONTENT_OBJECT);
        // $conditions[] = new EqualityCondition(Registration :: PROPERTY_NAME, File :: get_type_name());
        // $conditions[] = new EqualityCondition(Registration :: PROPERTY_STATUS, true);
        // $condition = new AndCondition($conditions);

        // $registration = \Chamilo\Core\Admin\Storage\DataManager :: count_registrations($condition);
        // if ($registration > 0)
        // {
        // $html_object = new File();
        // $html_object->set_title($export_template->get_name());
        // $html_object->set_description($export_template->get_description());
        // $html_object->set_parent_id(0);
        // $html_object->set_owner_id($export_job->get_user_id());
        // $html_object->set_filename($export->get_file_name() . '.' . $export_type);

        // $html_object->set_in_memory_file($file);

        // if (! $html_object->create())
        // {
        // $status = self :: STATUS_NO_DOCUMENT_CREATED;
        // }
        // else
        // {
        // $status = self :: STATUS_DOCUMENT_CREATED;
        // }

        // }
        // else
        // {
        // $status = self :: STATUS_NO_DOCUMENT_REGISTRATION;

        // }
        // }
        // elseif ($export_job->get_export_type() == ExportJob :: EXPORT_TYPE_SYNCHRONIZE_ANSWERS)
        // {

        // $condition = new EqualityCondition(SynchronizeAnswer :: PROPERTY_SURVEY_PUBLICATION_ID,
        // $export_job->get_publication_id());
        // $synchronize_tracker = Tracker :: get_singular_data(SynchronizeAnswer :: CLASS_NAME,
        // \Chamilo\Application\Survey\Manager :: APPLICATION_NAME, $condition);

        // if ($synchronize_tracker)
        // {
        // $id = $export_job->get_publication_id();
        // ExportJobManager :: delete_old_tracker_data($id);
        // ExportJobManager :: update_tracker_data($id);

        // $status = self :: STATUS_ANSWERS_SYNCHRONIZED;
        // }
        // else
        // {
        // $status = self :: STATUS_ANSWERS_NOT_SYNCHRONIZED;
        // }

        // }

        // switch ($status)
        // {
        // case self :: STATUS_NO_DOCUMENT_REGISTRATION :
        // $export_job->set_status(ExportJob :: STATUS_NOT_DONE);
        // $export_job->update();
        // $export_tracker->set_status(Export :: STATUS_EXPORT_NOT_CREATED);
        // $export_tracker->set_finished(time());
        // $export_tracker->update();
        // echo ' Job NOT Done : ' . "\n";
        // echo ' Export registration id: ' . $export_template->get_export_registration_id() . "\n";
        // echo ' Template id: ' . $export_template->get_id() . "\n";
        // echo ' Publication id: ' . $export_template->get_publication_id() . "\n";
        // echo ' Job id: ' . $export_job->get_id() . "\n";
        // ExportJobManager :: send_mail($export_job->get_user_id(), ExportJobManager :: get_mail_message(self ::
        // TYPE_DOCUMENT_NOT_AVAILABLE, $export_template->get_publication_id()), $export_template);
        // break;

        // case self :: STATUS_NO_DOCUMENT_CREATED :
        // $export_job->set_status(ExportJob :: STATUS_NOT_DONE);
        // $export_job->update();
        // $export_tracker->set_status(Export :: STATUS_EXPORT_NOT_CREATED);
        // $export_tracker->set_finished(time());
        // $export_tracker->update();
        // echo ' Job NOT Done : ' . "\n";
        // echo ' Export registration id: ' . $export_template->get_export_registration_id() . "\n";
        // echo ' Template id: ' . $export_template->get_id() . "\n";
        // echo ' Publication id: ' . $export_template->get_publication_id() . "\n";
        // echo ' Job id: ' . $export_job->get_id() . "\n";
        // ExportJobManager :: send_mail($export_job->get_user_id(), ExportJobManager :: get_mail_message(self ::
        // TYPE_EXPORT_NOT_FINISHED, $export_template->get_publication_id()), $export_template);
        // break;

        // case self :: STATUS_DOCUMENT_CREATED :
        // $export_job->set_status(ExportJob :: STATUS_DONE);
        // $export_job->update();
        // $export_tracker->set_status(Export :: STATUS_EXPORT_CREATED);
        // $export_tracker->set_finished(time());
        // $export_tracker->update();
        // echo ' Job Done : ' . "\n";
        // echo ' Export registration id: ' . $export_template->get_export_registration_id() . "\n";
        // echo ' Template id: ' . $export_template->get_id() . "\n";
        // echo ' Publication id: ' . $export_template->get_publication_id() . "\n";
        // echo ' Job id: ' . $export_job->get_id() . "\n";
        // ExportJobManager :: send_mail($export_job->get_user_id(), ExportJobManager :: get_mail_message(self ::
        // TYPE_EXPORT_FINISHED, $export_template->get_publication_id(), $html_object->get_id()), $export_template);
        // break;
        // case self :: STATUS_ANSWERS_SYNCHRONIZED :
        // $export_job->set_status(ExportJob :: STATUS_DONE);
        // $export_job->update();
        // $synchronize_tracker->set_created(time());
        // $synchronize_tracker->set_status(SynchronizeAnswer :: STATUS_SYNCHRONIZED);
        // $synchronize_tracker->update();
        // echo ' SYNCHRONIZATION Job Done : ' . "\n";
        // echo ' Publication id: ' . $export_job->get_publication_id() . "\n";
        // echo ' Job id: ' . $export_job->get_id() . "\n";
        // ExportJobManager :: send_mail($export_job->get_user_id(), ExportJobManager :: get_mail_message(self ::
        // TYPE_SYNCHRONIZATION_FINISHED, $export_job->get_publication_id()));
        // break;
        // case self :: STATUS_ANSWERS_NOT_SYNCHRONIZED :
        // $export_job->set_status(ExportJob :: STATUS_DONE);
        // $export_job->update();
        // $synchronize_tracker->set_created(time());
        // $synchronize_tracker->set_status(SynchronizeAnswer :: STATUS_NOT_SYNCHRONIZED);
        // $synchronize_tracker->update();
        // echo ' SYNCHRONIZATION Job NOT Done : ' . "\n";
        // echo ' Publication id: ' . $export_job->get_publication_id() . "\n";
        // echo ' Job id: ' . $export_job->get_id() . "\n";
        // ExportJobManager :: send_mail($export_job->get_user_id(), ExportJobManager :: get_mail_message(self ::
        // TYPE_SYNCHRONIZATION_NOT_FINISHED, $export_job->get_publication_id()));
        // break;
        // default :
        // echo ' Job NOT Done : ' . "\n";
        // echo ' NO STATUS FOUND ' . "\n";
        // echo ' Template id: ' . $export_template->get_id() . "\n";
        // echo ' Publication id: ' . $export_template->get_publication_id() . "\n";
        // echo ' Job id: ' . $export_job->get_id() . "\n";
        // break;
        // }

        // }
    }

    static function send_mail($user_id, $message, $export_template)
    {
        $user = \Chamilo\Core\User\Storage\DataManager::retrieve_user($user_id);
        $to_email = $user->get_email();

        $configuration = Configuration::getInstance();

        $name = $configuration->get_setting(array('Chamilo\Core\Admin', 'administrator_firstname')) . ' ' .
             $configuration->get_setting(array('Chamilo\Core\Admin', 'administrator_surname'));
        $email = $configuration->get_setting(array('Chamilo\Core\Admin', 'administrator_email'));

        if ($export_template)
        {
            $header = Translation::get('ExportHeader') . ' ' . $export_template->get_name();
        }
        else
        {
            $header = Translation::get('AnswerSynchronizationHeader');
        }

        $mail = new Mail($header, $message, $to_email, true, array(), array(), $name, $email, $name, $email);

        $mailerFactory = new MailerFactory(Configuration::getInstance());
        $mailer = $mailerFactory->getActiveMailer();

        try
        {
            $mailer->sendMail($mail);

            echo 'Mail send to: ' . $name . ' ' . $email . "\n";
            echo '     Message: ' . $message . "\n";
        }
        catch (\Exception $ex)
        {
            echo 'Mail not send to: ' . $name . ' ' . $email . "\n";
            echo '     Message: ' . $message . "\n";
        }
    }

    static function get_mail_message($type, $publication_id, $document_id)
    {
        $message = array();

        switch ($type)
        {
            case self::TYPE_DOCUMENT_NOT_AVAILABLE :
                $message[] = Translation::get("ExportDocumentNotAvailable");
                $click_message = Translation::get('ClickToGoToSurveyTool');
                $parameters = array();
                $parameters[Application::PARAM_CONTEXT] = \Chamilo\Application\Survey\Manager::package();
                $parameters[\Chamilo\Application\Survey\Manager::PARAM_ACTION] = \Chamilo\Application\Survey\Manager::ACTION_BROWSE;

                $redirect = new Redirect($parameters);
                $url = $redirect->getUrl();
                break;
            case self::TYPE_EXPORT_FINISHED :
                $message[] = Translation::get("ExportAvailable");
                $click_message = Translation::get('ClickTGoToExport');
                $parameters = array();
                $parameters[Application::PARAM_CONTEXT] = \Chamilo\Core\Repository\Manager::package();
                $parameters[\Chamilo\Core\Repository\Manager::PARAM_ACTION] = \Chamilo\Core\Repository\Manager::ACTION_VIEW_CONTENT_OBJECTS;
                $parameters[\Chamilo\Core\Repository\Manager::PARAM_CONTENT_OBJECT_ID] = $document_id;

                $redirect = new Redirect($parameters);
                $url = $redirect->getUrl();
                break;
            case self::TYPE_EXPORT_NOT_FINISHED :
                $message[] = Translation::get("ExportNotAvailable");
                $click_message = Translation::get('ClickToGoToExportTool');
                $parameters = array();
                $parameters[Application::PARAM_CONTEXT] = \Chamilo\Application\Survey\Manager::package();
                $parameters[\Chamilo\Application\Survey\Manager::PARAM_ACTION] = \Chamilo\Application\Survey\Manager::ACTION_EXPORT;
                $parameters[\Chamilo\Application\Survey\Manager::PARAM_PUBLICATION_ID] = $publication_id;

                $redirect = new Redirect($parameters);
                $url = $redirect->getUrl();
                break;
            case self::TYPE_SYNCHRONIZATION_FINISHED :
                $message[] = Translation::get("AnswerSynchronizationFinished");
                $click_message = Translation::get('ClickToGoToExportTool');
                $parameters = array();
                $parameters[Application::PARAM_CONTEXT] = \Chamilo\Application\Survey\Manager::package();
                $parameters[\Chamilo\Application\Survey\Manager::PARAM_ACTION] = \Chamilo\Application\Survey\Manager::ACTION_EXPORT;
                $parameters[\Chamilo\Application\Survey\Manager::PARAM_PUBLICATION_ID] = $publication_id;

                $redirect = new Redirect($parameters);
                $url = $redirect->getUrl();
                break;
            case self::TYPE_SYNCHRONIZATION_NOT_FINISHED :
                $message[] = Translation::get("AnswerSynchronizationNotFinished");
                $click_message = Translation::get('ClickToGoToExportTool');
                $parameters = array();
                $parameters[Application::PARAM_CONTEXT] = \Chamilo\Application\Survey\Manager::package();
                $parameters[\Chamilo\Application\Survey\Manager::PARAM_ACTION] = \Chamilo\Application\Survey\Manager::ACTION_EXPORT;
                $parameters[\Chamilo\Application\Survey\Manager::PARAM_PUBLICATION_ID] = $publication_id;

                $redirect = new Redirect($parameters);
                $url = $redirect->getUrl();
                break;
        }

        $message[] = '

';
        $message[] = '' . $click_message . '';

        $message[] = '

' . Translation::get('OrCopyAndPasteThisText') . ':';
        $message[] = '
' . $url . '';
        $message[] = '
';

        return implode(PHP_EOL, $message);
    }

    static public function update_tracker_data($publication_id)
    {
        $condition = new EqualityCondition(
            new PropertyConditionVariable(Answer::class_name(), Answer::PROPERTY_PUBLICATION_ID),
            $publication_id);
        $answers = DataManager::retrieves(Answer::class_name(), new DataClassRetrievesParameters($condition));

        while ($raw_answer = $answers->next_result())
        {
            $complex_question_id = $raw_answer->get_question_cid();
            $object = ExportJobManager::get_question($complex_question_id);

            $type = $object->get_type();

            switch ($type)
            {
                case MultipleChoice::get_type_name() :
                    $answer = $raw_answer->get_answer();

                    foreach ($answer as $option_id)
                    {
                        // $parameters = array();
                        // $parameters[SurveyMultipleChoiceQuestionAnswerTracker :: PROPERTY_SURVEY_PARTICIPANT_ID] =
                        // $tracker->get_survey_participant_id();
                        // $parameters[SurveyMultipleChoiceQuestionAnswerTracker :: PROPERTY_COMPLEX_QUESTION_ID] =
                        // $complex_question_id;
                        // $parameters[SurveyMultipleChoiceQuestionAnswerTracker :: PROPERTY_OPTION_ID] = $option_id;
                        // $parameters[SurveyMultipleChoiceQuestionAnswerTracker :: PROPERTY_CONTEXT_PATH] =
                        // $tracker->get_context_path();
                        // $parameters[SurveyMultipleChoiceQuestionAnswerTracker :: PROPERTY_PUBLICATION_ID] =
                        // $tracker->get_publication_id();
                        // $parameters[SurveyMultipleChoiceQuestionAnswerTracker :: PROPERTY_USER_ID] =
                        // $tracker->get_user_id();
                        // $parameters[SurveyMultipleChoiceQuestionAnswerTracker :: PROPERTY_CONTEXT_TEMPLATE_ID] =
                        // $tracker->get_context_template_id();
                        // $parameters[SurveyMultipleChoiceQuestionAnswerTracker :: PROPERTY_CONTEXT_ID] =
                        // $tracker->get_context_id();
                        // Event :: trigger(SurveyMultipleChoiceQuestionAnswerTracker ::
                        // SAVE_MULTIPLE_CHOICE_QUESTION_ANSWER_EVENT, \application\survey\Manager :: APPLICATION_NAME,
                        // $parameters);
                    }
                    break;

                case Matrix::get_type_name() :
                    $answer = $raw_answer->get_answer();

                    foreach ($answer as $ids => $match_id)
                    {
                        $ids = explode('_', $ids);
                        $option_id = $ids[1];

                        // $parameters = array();
                        // $parameters[SurveyMatrixQuestionAnswerTracker :: PROPERTY_SURVEY_PARTICIPANT_ID] =
                        // $tracker->get_survey_participant_id();
                        // $parameters[SurveyMatrixQuestionAnswerTracker :: PROPERTY_COMPLEX_QUESTION_ID] =
                        // $complex_question_id;
                        // $parameters[SurveyMatrixQuestionAnswerTracker :: PROPERTY_OPTION_ID] = $option_id;
                        // $parameters[SurveyMatrixQuestionAnswerTracker :: PROPERTY_MATCH_ID] = $match_id;
                        // $parameters[SurveyMatrixQuestionAnswerTracker :: PROPERTY_CONTEXT_PATH] =
                        // $tracker->get_context_path();
                        // $parameters[SurveyMatrixQuestionAnswerTracker :: PROPERTY_PUBLICATION_ID] =
                        // $tracker->get_publication_id();
                        // $parameters[SurveyMatrixQuestionAnswerTracker :: PROPERTY_USER_ID] = $tracker->get_user_id();
                        // $parameters[SurveyMatrixQuestionAnswerTracker :: PROPERTY_CONTEXT_TEMPLATE_ID] =
                        // $tracker->get_context_template_id();
                        // $parameters[SurveyMatrixQuestionAnswerTracker :: PROPERTY_CONTEXT_ID] =
                        // $tracker->get_context_id();
                        // Event :: trigger(SurveyMatrixQuestionAnswerTracker :: SAVE_MATRIX_QUESTION_ANSWER_EVENT,
                        // \application\survey\Manager :: APPLICATION_NAME, $parameters);
                    }
                    break;

                case Select::get_type_name() :
                    $answer = $raw_answer->get_answer();

                    foreach ($answer as $option_id)
                    {
                        // $parameters = array();
                        // $parameters[SurveySelectQuestionAnswerTracker :: PROPERTY_SURVEY_PARTICIPANT_ID] =
                        // $tracker->get_survey_participant_id();
                        // $parameters[SurveySelectQuestionAnswerTracker :: PROPERTY_COMPLEX_QUESTION_ID] =
                        // $complex_question_id;
                        // $parameters[SurveySelectQuestionAnswerTracker :: PROPERTY_OPTION_ID] = $option_id;
                        // $parameters[SurveySelectQuestionAnswerTracker :: PROPERTY_CONTEXT_PATH] =
                        // $tracker->get_context_path();
                        // $parameters[SurveySelectQuestionAnswerTracker :: PROPERTY_PUBLICATION_ID] =
                        // $tracker->get_publication_id();
                        // $parameters[SurveySelectQuestionAnswerTracker :: PROPERTY_USER_ID] = $tracker->get_user_id();
                        // $parameters[SurveySelectQuestionAnswerTracker :: PROPERTY_CONTEXT_TEMPLATE_ID] =
                        // $tracker->get_context_template_id();
                        // $parameters[SurveySelectQuestionAnswerTracker :: PROPERTY_CONTEXT_ID] =
                        // $tracker->get_context_id();
                        // Event :: trigger(SurveySelectQuestionAnswerTracker :: SAVE_SELECT_QUESTION_ANSWER_EVENT,
                        // \application\survey\Manager :: APPLICATION_NAME, $parameters);
                    }
                    break;

                case Matching::get_type_name() :
                    $answer = $raw_answer->get_answer();

                    foreach ($answer as $ids => $match_id)
                    {
                        $ids = explode('_', $ids);
                        $option_id = $ids[1];

                        // $parameters = array();
                        // $parameters[SurveyMatchingQuestionAnswerTracker :: PROPERTY_SURVEY_PARTICIPANT_ID] =
                        // $tracker->get_survey_participant_id();
                        // $parameters[SurveyMatchingQuestionAnswerTracker :: PROPERTY_COMPLEX_QUESTION_ID] =
                        // $complex_question_id;
                        // $parameters[SurveyMatchingQuestionAnswerTracker :: PROPERTY_OPTION_ID] = $option_id;
                        // $parameters[SurveyMatchingQuestionAnswerTracker :: PROPERTY_MATCH_ID] = $match_id;
                        // $parameters[SurveyMatchingQuestionAnswerTracker :: PROPERTY_CONTEXT_PATH] =
                        // $tracker->get_context_path();
                        // $parameters[SurveyMatchingQuestionAnswerTracker :: PROPERTY_PUBLICATION_ID] =
                        // $tracker->get_publication_id();
                        // $parameters[SurveyMatchingQuestionAnswerTracker :: PROPERTY_USER_ID] =
                        // $tracker->get_user_id();
                        // $parameters[SurveyMatchingQuestionAnswerTracker :: PROPERTY_CONTEXT_TEMPLATE_ID] =
                        // $tracker->get_context_template_id();
                        // $parameters[SurveyMatchingQuestionAnswerTracker :: PROPERTY_CONTEXT_ID] =
                        // $tracker->get_context_id();
                        // Event :: trigger(SurveyMatchingQuestionAnswerTracker :: SAVE_MATCHING_QUESTION_ANSWER_EVENT,
                        // \application\survey\Manager :: APPLICATION_NAME, $parameters);
                    }
                    break;

                case Open::get_type_name() :
                    $answer = $raw_answer->get_answer();

                    $text = ExportJobManager::transcode_string(array_pop($answer));
                    if (strlen(strip_tags($text)) > 0)
                    {
                        // $text = strip_tags($text);
                        // $parameters = array();
                        // $parameters[SurveyOpenQuestionAnswerTracker :: PROPERTY_SURVEY_PARTICIPANT_ID] =
                        // $tracker->get_survey_participant_id();
                        // $parameters[SurveyOpenQuestionAnswerTracker :: PROPERTY_COMPLEX_QUESTION_ID] =
                        // $complex_question_id;
                        // $parameters[SurveyOpenQuestionAnswerTracker :: PROPERTY_TEXT] = $text;
                        // $parameters[SurveyOpenQuestionAnswerTracker :: PROPERTY_CONTEXT_PATH] =
                        // $tracker->get_context_path();
                        // $parameters[SurveyOpenQuestionAnswerTracker :: PROPERTY_PUBLICATION_ID] =
                        // $tracker->get_publication_id();
                        // $parameters[SurveyOpenQuestionAnswerTracker :: PROPERTY_USER_ID] = $tracker->get_user_id();
                        // $parameters[SurveyOpenQuestionAnswerTracker :: PROPERTY_CONTEXT_TEMPLATE_ID] =
                        // $tracker->get_context_template_id();
                        // $parameters[SurveyOpenQuestionAnswerTracker :: PROPERTY_CONTEXT_ID] =
                        // $tracker->get_context_id();
                        // Event :: trigger(SurveyOpenQuestionAnswerTracker :: SAVE_OPEN_QUESTION_ANSWER_EVENT,
                        // \application\survey\Manager :: APPLICATION_NAME, $parameters);
                    }
                    break;

                case Rating::get_type_name() :

                    $answer = $raw_answer->get_answer();

                    foreach ($answer as $rating)
                    {
                        // $parameters = array();
                        // $parameters[SurveyRatingQuestionAnswerTracker :: PROPERTY_SURVEY_PARTICIPANT_ID] =
                        // $tracker->get_survey_participant_id();
                        // $parameters[SurveyRatingQuestionAnswerTracker :: PROPERTY_COMPLEX_QUESTION_ID] =
                        // $complex_question_id;
                        // $parameters[SurveyRatingQuestionAnswerTracker :: PROPERTY_RATING] = $rating;
                        // $parameters[SurveyRatingQuestionAnswerTracker :: PROPERTY_CONTEXT_PATH] =
                        // $tracker->get_context_path();
                        // $parameters[SurveyRatingQuestionAnswerTracker :: PROPERTY_PUBLICATION_ID] =
                        // $tracker->get_publication_id();
                        // $parameters[SurveyRatingQuestionAnswerTracker :: PROPERTY_USER_ID] = $tracker->get_user_id();
                        // $parameters[SurveyRatingQuestionAnswerTracker :: PROPERTY_CONTEXT_TEMPLATE_ID] =
                        // $tracker->get_context_template_id();
                        // $parameters[SurveyRatingQuestionAnswerTracker :: PROPERTY_CONTEXT_ID] =
                        // $tracker->get_context_id();
                        // Event :: trigger(SurveyRatingQuestionAnswerTracker :: SAVE_RATING_QUESTION_ANSWER_EVENT,
                        // \application\survey\Manager :: APPLICATION_NAME, $parameters);
                    }
                    break;
            }
        }
    }

    static function delete_old_tracker_data($publication_id)
    {

        // $condition = new EqualityCondition(SurveyMatrixQuestionAnswerTracker :: PROPERTY_PUBLICATION_ID,
        // $publication_id);
        // $trackers = Tracker :: get_data(SurveyMatrixQuestionAnswerTracker :: CLASS_NAME, \application\survey\Manager
        // :: APPLICATION_NAME, $condition);
        // while ($tracker = $trackers->next_result())
        // {
        // $tracker->delete();
        // }

        // $condition = new EqualityCondition(SurveyMultipleChoiceQuestionAnswerTracker :: PROPERTY_PUBLICATION_ID,
        // $publication_id);
        // $trackers = Tracker :: get_data(SurveyMultipleChoiceQuestionAnswerTracker :: CLASS_NAME,
        // \application\survey\Manager :: APPLICATION_NAME, $condition);
        // while ($tracker = $trackers->next_result())
        // {
        // $tracker->delete();
        // }

        // $condition = new EqualityCondition(SurveyMatchingQuestionAnswerTracker :: PROPERTY_PUBLICATION_ID,
        // $publication_id);
        // $trackers = Tracker :: get_data(SurveyMatchingQuestionAnswerTracker :: CLASS_NAME,
        // \application\survey\Manager :: APPLICATION_NAME, $condition);
        // while ($tracker = $trackers->next_result())
        // {
        // $tracker->delete();
        // }

        // $condition = new EqualityCondition(SurveySelectQuestionAnswerTracker :: PROPERTY_PUBLICATION_ID,
        // $publication_id);
        // $trackers = Tracker :: get_data(SurveySelectQuestionAnswerTracker :: CLASS_NAME, \application\survey\Manager
        // :: APPLICATION_NAME, $condition);
        // while ($tracker = $trackers->next_result())
        // {
        // $tracker->delete();
        // }

        // $condition = new EqualityCondition(SurveyRatingQuestionAnswerTracker :: PROPERTY_PUBLICATION_ID,
        // $publication_id);
        // $trackers = Tracker :: get_data(SurveyRatingQuestionAnswerTracker :: CLASS_NAME, \application\survey\Manager
        // :: APPLICATION_NAME, $condition);
        // while ($tracker = $trackers->next_result())
        // {
        // $tracker->delete();
        // }

        // $condition = new EqualityCondition(SurveyOpenQuestionAnswerTracker :: PROPERTY_PUBLICATION_ID,
        // $publication_id);
        // $trackers = Tracker :: get_data(SurveyOpenQuestionAnswerTracker :: CLASS_NAME, \application\survey\Manager ::
        // APPLICATION_NAME, $condition);
        // while ($tracker = $trackers->next_result())
        // {
        // $tracker->delete();
        // }
    }

    static function get_question($complex_id)
    {
        if (! isset(ExportJobManager::$questions_cache) || ! isset(ExportJobManager::$questions_cache[$complex_id]))
        {
            $complex_question = \Chamilo\Core\Repository\Storage\DataManager::retrieve_by_id(
                ComplexContentObjectItem::class_name(),
                $complex_id);
            ExportJobManager::$questions_cache[$complex_id] = $complex_question->get_ref_object();
        }
        return ExportJobManager::$questions_cache[$complex_id];
    }

    static function transcode_string($string)
    {
        $stripped_answer = trim(strip_tags(html_entity_decode($string, ENT_QUOTES, 'UTF-8')));
        $stripped_answer = str_replace(html_entity_decode(' ', ENT_COMPAT, 'UTF-8'), ' ', $stripped_answer);
        $stripped_answer = preg_replace('/[ \n\r\t]{2,}/', ' ', $stripped_answer);
        return $stripped_answer;
    }
}
?>


text:
var GamePieces = Backbone.Collection.extend({
    forward: function(from) {
        var delta = (from<32)? 8: -8;
        this.move(from,from+delta);
    },
    move: function(from,to) {
        var model=this.findWhere({sq:from});
        if (!model) return false;
        model.set({sq:to});
        // OR: model.set('sq',to);
        return true;
    }
});

var Checkers = (function() {

	var Checker = Backbone.Model.extend({
		defaults: {isKing: false}
	});

	var redStart = [1,3,5,7,8,10,12,14];
	var blackStart=[49,51,53,55,56,58,60,62];

	function makeChecker(where,color) {
		return {
			sq: where,
			color: color
		};
	}

	var Checkers = GamePieces.extend({
		model:Checker,
        gameName: 'Checker',
		initialize: function() {
			this.add(redStart.map(function(where){return makeChecker(where,'Light')}));
			this.add(blackStart.map(function(where){return makeChecker(where,'Dark')}));
		},
	});

	return Checkers;
})(); //end IIFE

var Chessmen = (function() {

	var ChessPiece = Backbone.Model.extend({
		defaults: {}
	});

    var backrow= ['R','Kt','B','Q','Kg','B','Kt','R'];
    var frontrow =['P','P','P','P','P','P','P','P'];

	function makePiece(color,piece,where) {
		return {
			sq: where,
            piece:piece,
			color: color
		};
	}

	var Chessmen = GamePieces.extend({
		model:ChessPiece,
        gameName: 'Chess',
		initialize: function() {
			this.add(backrow.concat(frontrow).map(function(name,idx){return makePiece('Light',name,idx)}));
			this.add(frontrow.concat(backrow).map(function(name,idx){return makePiece('Dark',name,idx+48)}));
		}
	});

	return Chessmen;
})(); //end IIFE

// --- Views ---
var SquareView = Backbone.View.extend({
	tagName: 'td',
	events: {'click': 'click'},
	initialize: function(opts) {
		this.n = opts.n;
        this.board = opts.board;
		this.$el.appendTo(opts.$row);
	},
	render: function(model) {
        var game = this.board.collection;
		if (model===undefined) {
				model = game.findWhere({sq:this.n}) || false;
		}
		//always:
        this.$el.removeClass('Checker Chess Light Dark');
		if (model) {
            this.$el.attr('piece',model.get('piece'));
			this.$el.addClass(model.get('color')).addClass(game.gameName);
		}
	},
	click: function(evt) {
		this.board.collection.forward(this.n);
	}
});

var BoardView = Backbone.View.extend({
	id:'checkerboard',
	tagName: 'table',
	initialize: function() {
		this.collection.on('change:sq',this.render,this);
		this.squares = [];//subviews
		var n=0;
		for (var i=0; i<8; ++i) {
			var $row = $('<tr>').appendTo(this.$el);
			for (var j=0; j<8; ++j) {
				var opts = {
					board: this,
					className: ((i%2==j%2)?'odd':'even'),
					$row: $row,
					n: n++
				}
				this.squares.push(new SquareView(opts));
			}
		}
		this.$el.appendTo('body');
	},
	render: function(model) {
		console.log("refreshing...");
		if (!model)
			this.squares.forEach(function(sq){sq.render()}); //render all
		else { //render just changed squares
			var newSq = model.get('sq');
			var oldSq = model.previous('sq');
			this.squares[newSq].render(model);
			this.squares[oldSq].render(false);
		}
	},
    changeGame: function(coll) {
        this.collection.off('change:sq');
        coll.on('change:sq',this.render,this);
        this.collection = coll;
        this.render();
    }
});

// ---- Routes ----
var Router = Backbone.Router.extend({
  games: { //store one of each game:
    checkers: new Checkers(),
    chess: new Chessmen()
  },
  board: null, // will need to be an instance of BoardView
  routes: {
    '': 'checkers',
    'checkers': 'checkers',
    'chess': 'chess',
    'about': 'about'
  },
  switchTo: function(gameName) {
  	// If there is not yet a board, make one with the appropriate game type
  	// and save it as 'this.board'.

  	// Once there is a board, change the game it represents to be one of the two
  	// stored collections:
  	// this.games.checkers or this.games.chess
  	// Make sure the board re-renders after any changes.

  },
  checkers: function () {
    this.switchTo('checkers');
  },
  chess: function () {
    this.switchTo('chess');
  }
});

function start() {
  window.app = new Router();
  Backbone.history.start();
}

$(start);

redpajama_set_name: RedPajamaGithub


text:
using System;
using NServiceBus.SimpleInjector;
using SimpleInjector.Lifestyles;

namespace NServiceBus
{
    using NServiceBus.Container;

    /// <summary>
    /// Extension method class to allow configuration of existing container
    /// </summary>
    public static class ConfigurationExtensionMethods
    {
        /// <summary>
        /// Use the a pre-configured SimpleInjector contains
        /// </summary>
        /// <param name="customizations"></param>
        /// <param name="container">The existing container to use.</param>
        public static void UseExistingContainer(this ContainerCustomizations customizations, global::SimpleInjector.Container container)
        {
            if (!container.Options.AllowOverridingRegistrations)
                throw new ArgumentException("Invalid container configuration - must set Options.AllowOverridingRegistrations to true");
            if (!(container.Options.DefaultScopedLifestyle is AsyncScopedLifestyle))
                throw new ArgumentException("Invalid container configuration - must set DefaultScopedLifestyle to AsyncScopedLifestyle");
            if (!(container.Options.PropertySelectionBehavior is ImplicitPropertyInjectionExtensions.ImplicitPropertyInjectionBehavior))
                throw new ArgumentException("Invalid container - must set properties to be autowired (by calling Options.AutoWirePropertiesImplicitly())");

            customizations.Settings.Set<ContainerHolder>(new ContainerHolder(container));
        }
    }
}


text:
namespace {
   bool hlsl_inited = false;

   bool ___inited() {
      if (!hlsl_inited) {
         hlsl_inited = Hlsl2Glsl_Initialize();
      }
      if (!hlsl_inited) {
         return false;
      }
      return true;
   }
   bool ___deinit() {
      if (hlsl_inited) {
         Hlsl2Glsl_Shutdown();
      }
      hlsl_inited = false;
      return true;
   }

   M4::HLSLFunction* FindFunction(M4::HLSLRoot* root, const char* name);

   std::string GetShader(sgContextPtr context, ShHandle handle, const char* entry, const char* shader, GLSLTarget version) {
      ETargetVersion vers = ETargetGLSL_ES_100;
      switch (version) {
         case GLSLTarget100:
            vers = ETargetGLSL_ES_100;
            break;
         case GLSLTarget110:
            vers = ETargetGLSL_110;
            break;
         case GLSLTarget120:
            vers = ETargetGLSL_120;
            break;
         case GLSLTarget140:
            vers = ETargetGLSL_140;
            break;
         case GLSLTarget300:
            vers = ETargetGLSL_330;
            break;

         default:
            break;
      }
      unsigned option = ETranslateOpPropogateOriginalAttribNames | ETranslateOpForceBuiltinAttribNames;
      M4::HLSLRoot *root = context->current_context->tree.GetRoot();
      M4::HLSLFunction* entryFunction = FindFunction(root, entry);
      if (entryFunction == nullptr)
      {
         throw GenerateException(std::string("Not found entry -- ") + std::string(entry));
      }
      {
         bool haveMoreOneColor = false;
         sgAttribute attr = GetAttribute(context, entry, haveMoreOneColor);
         Hlsl2Glsl_SetUserAttributeNames (handle,
                                          &attr.sematic[0],
                                          &attr.names[0],
                                          attr.names.size());
         if (!haveMoreOneColor) {
            option |= ETranslateOpUseGlFragColor;
         }
      }
      if (!Hlsl2Glsl_Parse(handle, shader, vers, 0, 0)) {
         Hlsl2Glsl_Parse(handle, shader, vers, 0, 0);
         Hlsl2Glsl_DestructCompiler(handle);
         throw GenerateException(std::string("Cannot parse HLSL shader:") + Hlsl2Glsl_GetInfoLog(handle));
      }
      if (!Hlsl2Glsl_Translate(handle, entry, vers, option)) {
         Hlsl2Glsl_DestructCompiler(handle);
         throw GenerateException(std::string("Cannot translate HLSL shader") + Hlsl2Glsl_GetInfoLog(handle));
      }
      std::string result = Hlsl2Glsl_GetShader(handle);
      Hlsl2Glsl_DestructCompiler(handle);
      return result;
   }

   M4::HLSLFunction* FindFunction(M4::HLSLRoot* root, const char* name)
   {
      M4::HLSLStatement* statement = root->statement;
      while (statement != NULL)
      {
         if (statement->nodeType == M4::HLSLNodeType_Function)
         {
            M4::HLSLFunction* function = static_cast<M4::HLSLFunction*>(statement);
            if (strcmp(function->name, name) == 0)
            {
               return function;
            }
         }
         statement = statement->nextStatement;
      }
      return NULL;
   }

   M4::HLSLStruct* FindStruct(M4::HLSLRoot* root, const char* name)
   {
      M4::HLSLStatement* statement = root->statement;
      while (statement != NULL)
      {
         if (statement->nodeType == M4::HLSLNodeType_Struct)
         {
            M4::HLSLStruct* structDeclaration = static_cast<M4::HLSLStruct*>(statement);
            if (strcmp(structDeclaration->name, name) == 0)
            {
               return structDeclaration;
            }
         }
         statement = statement->nextStatement;
      }
      return NULL;
   }
   struct SemanticPair {
      const char*             name;
      const EAttribSemantic   semantic;
      SemanticPair(const char* name, const EAttribSemantic semantic):name(name), semantic(semantic){}
   };
   SemanticPair semantics_map[] = {
      SemanticPair("POSITION", EAttrSemPosition),
      SemanticPair("POSITION0", EAttrSemPosition),
      SemanticPair("POSITION1", EAttrSemPosition1),
      SemanticPair("POSITION2", EAttrSemPosition2),
      SemanticPair("POSITION3", EAttrSemPosition3),
      SemanticPair("NORMAL", EAttrSemNormal),
      SemanticPair("NORMAL0", EAttrSemNormal),
      SemanticPair("NORMAL1", EAttrSemNormal1),
      SemanticPair("NORMAL2", EAttrSemNormal2),
      SemanticPair("NORMAL3", EAttrSemNormal3),
      SemanticPair("COLOR", EAttrSemColor0),
      SemanticPair("COLOR0", EAttrSemColor0),
      SemanticPair("COLOR1", EAttrSemColor1),
      SemanticPair("COLOR2", EAttrSemColor2),
      SemanticPair("COLOR3", EAttrSemColor3),
      SemanticPair("TANGENT", EAttrSemTangent),
      SemanticPair("TANGENT0", EAttrSemTangent),
      SemanticPair("TANGENT1", EAttrSemTangent1),
      SemanticPair("TANGENT2", EAttrSemTangent2),
      SemanticPair("TANGENT3", EAttrSemTangent3),
      SemanticPair("BINORMAL", EAttrSemBinormal),
      SemanticPair("BINORMAL0", EAttrSemBinormal),
      SemanticPair("BINORMAL1", EAttrSemBinormal1),
      SemanticPair("BINORMAL2", EAttrSemBinormal2),
      SemanticPair("BINORMAL3", EAttrSemBinormal3),
      SemanticPair("BLENDWEIGHT", EAttrSemBlendWeight),
      SemanticPair("BLENDWEIGHT0", EAttrSemBlendWeight),
      SemanticPair("BLENDWEIGHT1", EAttrSemBlendWeight1),
      SemanticPair("BLENDWEIGHT2", EAttrSemBlendWeight2),
      SemanticPair("BLENDWEIGHT3", EAttrSemBlendWeight3),
      SemanticPair("BLENDINDICES", EAttrSemBlendIndices),
      SemanticPair("BLENDINDICES0", EAttrSemBlendIndices),
      SemanticPair("BLENDINDICES1", EAttrSemBlendIndices1),
      SemanticPair("BLENDINDICES2", EAttrSemBlendIndices2),
      SemanticPair("BLENDINDICES3", EAttrSemBlendIndices3),
      SemanticPair("TEXCOORD", EAttrSemTex0),
      SemanticPair("TEXCOORD0", EAttrSemTex0),
      SemanticPair("TEXCOORD1", EAttrSemTex1),
      SemanticPair("TEXCOORD2", EAttrSemTex2),
      SemanticPair("TEXCOORD3", EAttrSemTex3),
      SemanticPair("TEXCOORD4", EAttrSemTex4),
      SemanticPair("TEXCOORD5", EAttrSemTex5),
      SemanticPair("TEXCOORD6", EAttrSemTex6),
      SemanticPair("TEXCOORD7", EAttrSemTex7),
      SemanticPair("TEXCOORD8", EAttrSemTex8),
      SemanticPair("TEXCOORD9", EAttrSemTex9),
   };

   EAttribSemantic GetSemantic(const char* txt) {
      if (txt == 0)
         return EAttrSemNone;
      for(SemanticPair sem : semantics_map) {
         if (strcmp(txt, sem.name) == 0)
            return sem.semantic;
      }
      return EAttrSemNone;
   }
   size_t GetAttributeSize(EAttribSemantic type){
      switch(type){
         case EAttrSemPosition:return 16;
         case EAttrSemPosition1:return 16;
         case EAttrSemPosition2:return 16;
         case EAttrSemPosition3:return 16;
         case EAttrSemNormal:return 16;
         case EAttrSemNormal1:return 16;
         case EAttrSemNormal2:return 16;
         case EAttrSemNormal3:return 16;
         case EAttrSemColor0:return 16;
         case EAttrSemColor1:return 16;
         case EAttrSemColor2:return 16;
         case EAttrSemColor3:return 16;
         case EAttrSemTex0:return 8;
         case EAttrSemTex1:return 8;
         case EAttrSemTex2:return 8;
         case EAttrSemTex3:return 8;
         case EAttrSemTex4:return 8;
         case EAttrSemTex5:return 8;
         case EAttrSemTex6:return 8;
         case EAttrSemTex7:return 8;
         case EAttrSemTex8:return 8;
         case EAttrSemTex9:return 8;
         default:
            return 0;
      }
   }

   void FillStructure(sgAttribute &result, const M4::HLSLType& type, M4::HLSLRoot* root) {
      if (type.baseType == M4::HLSLBaseType_UserDefined) {
         M4::HLSLStruct* structDeclaration = FindStruct(root, type.typeName);
         M4::HLSLStructField* field = structDeclaration->field;
         while (field != NULL)
         {
            if (field->type.baseType == M4::HLSLBaseType_UserDefined) {
               FillStructure(result, field->type, root);
            } else {
               result.names.push_back(field->name);
               result.sematic.push_back(GetSemantic(field->semantic));
               result.size.push_back(GetAttributeSize(result.sematic.back()));
            }
            field = field->nextField;
         }
      }
   }
}

sgAttribute GetAttribute(sgContextPtr context, const char* entry, bool& haveMoreOneColor) {
   sgAttribute result;
   M4::HLSLRoot *root = context->current_context->tree.GetRoot();
   M4::HLSLFunction* entryFunction = FindFunction(root, entry);
   if (entryFunction == 0)
      return result;
   haveMoreOneColor = false;
   M4::HLSLArgument* argument = entryFunction->argument;
   int colorSemanticCount = 0;
   while (argument != NULL)
   {
      if (argument->type.baseType == M4::HLSLBaseType_UserDefined) {
         FillStructure(result, argument->type, root);
      } else {
         result.names.push_back(argument->name);
         EAttribSemantic semantic = GetSemantic(argument->semantic);
         result.sematic.push_back(semantic);
         result.size.push_back(GetAttributeSize(result.sematic.back()));
      }
      argument = argument->nextArgument;
   }
   if(entryFunction->returnType.baseType == M4::HLSLBaseType_Float4) {
      return result;
   } else if (entryFunction->returnType.baseType == M4::HLSLBaseType_UserDefined) {
      M4::HLSLStruct* structDeclaration = FindStruct(root, entryFunction->returnType.typeName);
      M4::HLSLStructField* field = structDeclaration->field;
      while (field != NULL)
      {
         EAttribSemantic semantic = GetSemantic(field->semantic);
         if (semantic >= EAttrSemColor0 && semantic <= EAttrSemColor3) {
            ++colorSemanticCount;
         }
         field = field->nextField;
      }
      haveMoreOneColor = colorSemanticCount > 1;
   }
   return result;
}

std::vector<sgUniform> GetAllUniforms(sgContextPtr context) {
   std::vector<sgUniform> result;
   M4::HLSLRoot *root = context->current_context->tree.GetRoot();
   M4::HLSLStatement* statement = root->statement;
   while (statement != NULL)
   {
      if (statement->nodeType == M4::HLSLNodeType_Declaration)
      {
         M4::HLSLDeclaration* declaration = static_cast<M4::HLSLDeclaration*>(statement);
         while(declaration) {
            sgUniform added;
            added.name = declaration->name;
            added.type = (sgUniform::sgUniformType)declaration->type.baseType;
            added.UpdateSize();
            if (added.size >= 0) {
               if (declaration->type.array && declaration->type.arraySize){
                  int offset_begin = declaration->bufferOffset;
                  int offset_end = declaration->type.arraySize->bufferOffset;
                  if (offset_begin >= 0 && offset_end >= 0) {
                     const char* data_begin = &(context->current_effect[offset_begin]);
                     const char* data_end = &(context->current_effect[offset_end]);
                     int count = 0;
                     while (data_begin != data_end) {
                        if (std::isdigit(data_begin[0])){
                           count *= 10;
                           count += data_begin[0] - '0';
                        }
                        data_begin++;
                     }
                     added.size *= count;
                  }
               }
               result.push_back(added);
            }
            declaration = declaration->nextDeclaration;
         }
      } else if (statement->nodeType == M4::HLSLNodeType_Struct) {
         M4::HLSLStruct* struct_type = static_cast<M4::HLSLStruct*>(statement);
         if (struct_type){
            sgUniform added_root;
            added_root.name = struct_type->name;
            added_root.type = sgUniform::sgUniformTypeStruct;
            M4::HLSLStructField* field = struct_type->field;
            while(field) {
               sgUniform added;
               added.name = field->name;
               added.type = (sgUniform::sgUniformType)field->type.baseType;
               added.UpdateSize();
               if (added.size >= 0) {
                  added_root.childs.push_back(added);
               }
               field = field->nextField;
            }
            added_root.UpdateSize();
            if (added_root.size >= 0) {
               result.push_back(added_root);
            }
         }
      }
      statement = statement->nextStatement;
   }
   return result;
}

void UpdateUniformMap(sgContextPtr context, std::map<int, sgUniform> &map, M4::HLSLFunction* func)
{
   const M4::Array<const char*> result = context->current_context->parser.GetUseGlobalVariableInFunction(func);
   for(int i = 0; i < result.GetSize(); i++)
   {
      for (int u_index = 0; u_index < context->all_uniforms.size(); u_index++) {
         if (context->all_uniforms[u_index].name == result[i]){
            map[u_index] = context->all_uniforms[u_index];
            break;
         }
      }
   }
}

std::vector<M4::HLSLFunction*> GetUsedGlobalFunction(sgContextPtr context, M4::HLSLFunction* func, M4::HLSLRoot *root)
{
   std::vector<M4::HLSLFunction*> result;
   const M4::Array<const char*> functions = context->current_context->parser.GetUseGlobalFunctionInFunction(func);
   for(int i = 0; i < functions.GetSize(); i++)
   {
      M4::HLSLFunction* function = FindFunction(root, functions[i]);
      if (function) {
         result.push_back(function);
      }
   }
   return result;
}

std::map<int, sgUniform> GetUniform(sgContextPtr context, const char* entry) {
   std::map<int, sgUniform> result;
   M4::HLSLRoot *root = context->current_context->tree.GetRoot();
   M4::HLSLFunction* entryFunction = FindFunction(root, entry);
   if (entryFunction == 0)
      return result;
   UpdateUniformMap(context, result, entryFunction);
   std::vector<M4::HLSLFunction*> functions = GetUsedGlobalFunction(context, entryFunction, root);
   for(M4::HLSLFunction* function : functions) {
      std::map<int, sgUniform> other_result = GetUniform(context, function->name);
      for(std::pair<int, sgUniform> kvp : other_result) {
         result[kvp.first] = kvp.second;
      }
   }
   return result;
}

std::string GetGLSLShaderFrag(sgContextPtr context, const char* entry, const char* shader, GLSLTarget version) {
   if (!___inited()) {
      throw InitException("Cannot init hlsl2glsl");
   }
   ShHandle handle = Hlsl2Glsl_ConstructCompiler(EShLangFragment);

   return GetShader(context, handle, entry, shader, version);
}

std::string GetGLSLShaderVert(sgContextPtr context, const char* entry, const char* shader, GLSLTarget version) {
   if (!___inited()) {
      throw InitException("Cannot init hlsl2glsl");
   }
   ShHandle handle = Hlsl2Glsl_ConstructCompiler(EShLangVertex);
   return GetShader(context, handle, entry, shader, version);
}

std::string GetGLSLShader(sgContextPtr context, const char* entry, const char* shader, sgShaderType type, GLSLTarget version){
   switch (type) {
      case sgShaderTypeFrag:
         return GetGLSLShaderFrag(context, entry, shader, version);
         break;
      case sgShaderTypeVertex:
         return GetGLSLShaderVert(context, entry, shader, version);
         break;
      default:
         throw new std::bad_function_call();
         break;
   }
}

void GLSLShaderDeinit() {
   ___deinit();
}


text:
package io.quarkus.micrometer.runtime.binder.vertx;

import java.util.HashMap;
import java.util.Map;

import io.micrometer.core.instrument.LongTaskTimer;
import io.micrometer.core.instrument.MeterRegistry;
import io.vertx.core.net.SocketAddress;
import io.vertx.core.spi.metrics.TCPMetrics;

public class VertxTcpMetrics extends VertxNetworkMetrics
        implements TCPMetrics<Map<String, Object>> {

    private static final String CONNECTED_SOCKET_SAMPLE = "CONNECTED_SOCKET_SAMPLE";

    final String nameConnections;

    VertxTcpMetrics(MeterRegistry registry, String prefix) {
        super(registry, prefix);
        nameConnections = prefix + ".connections";
    }

    /**
     * Called when a client has connected, which is applicable for TCP connections.
     * <p>
     * The remote name of the client is a best effort to provide the name of the
     * remote host, i.e. if the name is specified at creation time, this name will be
     * used otherwise it will be the remote address.
     *
     * @param remoteAddress the remote address of the client
     * @param remoteName the remote name of the client
     * @return a map for socket metric context
     */
    @Override
    public Map<String, Object> connected(SocketAddress remoteAddress, String remoteName) {
        Map<String, Object> socketMetric = new HashMap<>();
        socketMetric.put(CONNECTED_SOCKET_SAMPLE,
                LongTaskTimer.builder(nameConnections).register(registry).start());
        return socketMetric;
    }

    /**
     * Called when a client has disconnected, which is applicable for TCP
     * connections.
     *
     * @param socketMetric a Map for socket metric context or null
     * @param remoteAddress the remote address of the client
     */
    @Override
    public void disconnected(Map<String, Object> socketMetric, SocketAddress remoteAddress) {
        if (socketMetric == null) {
            return;
        }
        LongTaskTimer.Sample sample = (LongTaskTimer.Sample) socketMetric.get(CONNECTED_SOCKET_SAMPLE);
        if (sample != null) {
            sample.stop();
        }
    }
}


text:
/*MENU*/
.lotusui30 .lotusMenu .lotusTree .dijitTreeRow {
  margin: 0;
  padding: 4px 20px;
  color: #bbb !important;
  font-weight: bold;
  line-height: 1.5;
  text-shadow: 0 1px 1px #121212;
  outline: none;
  overflow: hidden;
  text-overflow: ellipsis;
}
.lotusui30 .lotusMenu .lotusTree .dijitTreeRow.lotusSelected {
  position: relative;
  margin: 0;
  padding: 4px 20px 4px 35px;
  color: #fff;
  background-color: #1f7cae;
  border: 0;
  border-right: 1px solid #222;
  text-shadow: 0 -1px 0 #121212;
  -moz-box-shadow:0 1px 1px #52acdB inset, 0 -1px 0 #000 inset;
  -webkit-box-shadow:0 1px 1px #52acdB inset, 0 -1px 0 #000 inset;
  box-shadow:0 1px 1px #52acdB inset, 0 -1px 0 #000 inset;}
.lotusui30 .lotusMenu .lotusTree .dijitTreeRow a.dijitTreeLabel {color:#bbb !important;}
.lotusui30 .lotusMenu .lotusTree .dijitTreeRow.lotusSelected a {color:#fff !important; text-decoration:none;}
.lotusui30 .lotusMenu .lotusTree .dijitTreeExpando,
.lotusui30 .lotusMenu .lotusTree .lotusSelected .dijitTreeExpando {margin-left:0; position:relative; right:-2px;}
.lotusui30 .lotusMenu .lotusTree .dijitTreeExpandoOpened {background-position:4px -1256px; filter:alpha(opacity=75); opacity:0.75;}
.lotusui30 .lotusMenu .lotusTree .dijitTreeExpandoClosed {background-position:4px -1352px; filter:alpha(opacity=75); opacity:0.75;}
.lotusui30 .lotusMenu .lotusTree .lotusSelected .dijitTreeExpandoOpened {background-position: 4px -1256px; filter:alpha(opacity=100); opacity:1;}
.lotusui30 .lotusMenu .lotusTree .lotusSelected .dijitTreeExpandoClosed {background-position: 4px -1352px; filter:alpha(opacity=100); opacity:1;}
.lotusui30 .lotusMenu .lotusTree .dijitTreeRowUnselected.dijitTreeNodeHover .dijitTreeExpandoOpened {filter:alpha(opacity=100); opacity:1;}
.lotusui30 .lotusMenu .lotusTree .dijitTreeRowUnselected.dijitTreeNodeHover .dijitTreeExpandoClosed {filter:alpha(opacity=100); opacity:1;}
.lotusui30 .lotusMenu .lotusTree .dijitTreeRowUnselected.dijitTreeNodeHover {
  background-color: #2a2c2f !important;
  -moz-box-shadow: 0 1px 0 #242628 inset, 0 -1px 0 #242628 inset;
  -webkit-box-shadow: 0 1px 0 #242628 inset, 0 -1px 0 #242628 inset;
  box-shadow: 0 1px 0 #242628 inset, 0 -1px 0 #242628 inset;
}
.lotusui30 .lotusMenu .lotusTree .dijitTreeRowUnselected.dijitTreeNodeHover a.dijitTreeLabel {color:#fff !important; text-decoration:none;}

/*TOOLTIP*/
.lotusui30dojo .dijitTooltipContainer {
  -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
  -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
}

/*POPUP*/
.lotusui30dojo .dijitMenuActive .dijitMenuItemHover,
.lotusui30dojo .dijitMenuActive .dijitMenuItemSelected {
  /*for language selector*/
  background-color: #e9f1f3 !important;
}


text:
using BlogEngine.Core.Data.Contracts;
using BlogEngine.Core.Data.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Dynamic;
using System.Web.Hosting;

namespace BlogEngine.Core.Data
{
    /// <summary>
    /// Blog repository
    /// </summary>
    public class BlogRepository : IBlogRepository
    {
        /// <summary>
        /// Get blog list
        /// </summary>
        /// <param name="take">Number of items to take</param>
        /// <param name="skip">Number of items to skip</param>
        /// <param name="filter">Filter expression</param>
        /// <param name="order">Order expression</param>
        /// <returns>List of blogs</returns>
        public IEnumerable<Models.Blog> Find(int take = 10, int skip = 0, string filter = "", string order = "")
        {
            // sub-blogs not allowed to see other blogs
            if (!(Blog.CurrentInstance.IsPrimary && Security.IsAdministrator))
                throw new UnauthorizedAccessException();

            if (take == 0) take = Blog.Blogs.Count;
            if (string.IsNullOrEmpty(filter)) filter = "1==1";
            if (string.IsNullOrEmpty(order)) order = "Name";

            var items = new List<Models.Blog>();
            var query = Blog.Blogs.AsQueryable().Where(filter);

            foreach (var item in query.OrderBy(order).Skip(skip).Take(take))
                items.Add(ToJson((Blog)item));

            return items;
        }

        /// <summary>
        /// Find blog by id
        /// </summary>
        /// <param name="id">Id</param>
        /// <returns>Blog</returns>
        public Models.Blog FindById(Guid id)
        {
            // sub-blogs not allowed to see other blogs
            if (!(Blog.CurrentInstance.IsPrimary && Security.IsAdministrator))
                throw new UnauthorizedAccessException();

            var blog = Blog.Blogs.Where(b => b.Id == id).FirstOrDefault();
            return ToJson(blog);
        }

        /// <summary>
        /// Add new blog
        /// </summary>
        /// <param name="item">Blog item</param>
        /// <returns>Saved blog with new ID</returns>
        public Models.Blog Add(BlogItem item)
        {
            // has to be on primary blog and be an admin
            // or blog allows create new on self registration
            if (!(Blog.CurrentInstance.IsPrimary && (Security.IsAdministrator || BlogSettings.Instance.CreateBlogOnSelfRegistration)))
                throw new UnauthorizedAccessException();

            string message;
            if (!BlogGenerator.ValidateProperties(item.Name, item.UserName, item.Email, out message))
                throw new ApplicationException(message);

            var coreBlog = BlogGenerator.CreateNewBlog(item.Name, item.UserName, item.Email, item.Password, out message);

            if (coreBlog == null || !string.IsNullOrWhiteSpace(message))
                throw new ApplicationException("Failed to create the new blog.");

            return ToJson(coreBlog);
        }

        /// <summary>
        /// Update blog
        /// </summary>
        /// <param name="blog">Blog to update</param>
        /// <returns>True on success</returns>
        public bool Update(Models.Blog blog)
        {
            // sub-blogs not allowed to see other blogs
            if (!(Blog.CurrentInstance.IsPrimary && Security.IsAdministrator))
                throw new UnauthorizedAccessException();
            try
            {
                var coreBlog = Blog.Blogs.Where(b => b.Id == blog.Id).FirstOrDefault();
                return Save(coreBlog, blog);
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Delete item
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>True on success</returns>
        public bool Remove(Guid id)
        {
            // sub-blogs not allowed to see other blogs
            if (!(Blog.CurrentInstance.IsPrimary && Security.IsAdministrator))
                throw new UnauthorizedAccessException();
            try
            {
                var blog = Blog.Blogs.Where(b => b.Id == id).FirstOrDefault();
                blog.Delete();
                blog.Save();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        #region Private methods

        static bool Save(Blog coreBlog, BlogEngine.Core.Data.Models.Blog jsonBlog)
        {
            coreBlog.Id = jsonBlog.Id;
            coreBlog.Name = jsonBlog.Name;
            coreBlog.StorageContainerName = jsonBlog.StorageContainerName;
            coreBlog.Hostname = jsonBlog.Hostname;
            coreBlog.IsAnyTextBeforeHostnameAccepted = jsonBlog.IsAnyTextBeforeHostnameAccepted;
            coreBlog.VirtualPath = jsonBlog.VirtualPath;
            coreBlog.IsActive = jsonBlog.IsActive;
            coreBlog.IsSiteAggregation = jsonBlog.IsSiteAggregation;
            coreBlog.IsPrimary = jsonBlog.IsPrimary;
            //coreBlog.StorageLocation = PhysicalStorageLocation = HostingEnvironment.MapPath(blog.StorageLocation);
            coreBlog.Save();
            return true;
        }

        static BlogEngine.Core.Data.Models.Blog ToJson(Blog blog)
        {
            var jb = new BlogEngine.Core.Data.Models.Blog
            {
                Id = blog.Id,
                Name = blog.Name,
                StorageContainerName = blog.StorageContainerName,
                Hostname = blog.Hostname,
                IsAnyTextBeforeHostnameAccepted = blog.IsAnyTextBeforeHostnameAccepted,
                VirtualPath = blog.VirtualPath,
                IsActive = blog.IsActive,
                IsSiteAggregation = blog.IsSiteAggregation,
                IsPrimary = blog.IsPrimary,
                RelativeWebRoot = blog.RelativeWebRoot,
                AbsoluteWebRoot = blog.AbsoluteWebRoot,
                PhysicalStorageLocation = HostingEnvironment.MapPath(blog.StorageLocation),
                CanUserEdit = blog.CanUserEdit,
                CanUserDelete = blog.CanUserDelete
            };

            return jb;
        }

        #endregion
    }
}


text:
\begin{figure}[H]
\centering
\includegraphics[width=6in]{figs/run_53/run_53_turb_visc_total_vs_r_meshscatter}
\caption{Scatter plot of non-equilibrium based $\nu_T$ vs radius at $z/c$=9.50, $V_{free}$=19.08, station 6.}
\label{fig:run_53_turb_visc_total_vs_r_meshscatter}
\end{figure}


text:
<!DOCTYPE html>

    <link href="css/awsdocs.css" rel="stylesheet" type="text/css">

    <meta charset="utf-8">

AWS::SSM::MaintenanceWindow

The AWS::SSM::MaintenanceWindow resource represents general information about a
                        Maintenance Window for AWS Systems Manager. Maintenance Windows let you define a schedule
                        for when to
                        perform potentially disruptive actions on your instances—such as patching an operating
                        system (OS), updating drivers, or installing software. Each Maintenance Window has
                        a schedule, a
                        duration, a set of registered targets, and a set of registered tasks. For more information,
                        see
                         Systems Manager Maintenance
                           Windows in the AWS Systems Manager User Guide and
                           CreateMaintenanceWindow in the AWS Systems Manager API Reference.

Syntax

To declare this entity in your AWS CloudFormation template, use the following syntax:

JSON

{
  "Type" : "AWS::SSM::MaintenanceWindow",
  "Properties" : {
    "Name" : String,
    "Description" : String,
    "AllowUnassociatedTargets" : Boolean,
    "Schedule" : String,
    "Duration" : Integer,
    "Cutoff" : Integer,
    "StartDate" : String,,
    "EndDate" : String,,
    "ScheduleTimezone" : String
  }
}

YAML

Type: "AWS::SSM::MaintenanceWindow"
Properties:
  Name: String
  Description: String
  AllowUnassociatedTargets: Boolean
  Schedule: String
  Duration: Integer
  Cutoff: Integer
  StartDate: String
  EndDate: String
  ScheduleTimezone: String

Properties

Name

The name of the Maintenance Window.

                                 Required: Yes

                                 Type: String

                                 Update requires: No
                                    interruption

Description

A description of the Maintenance Window.

                                 Required: No

                                 Type: String

                                 Update requires: No
                                    interruption

AllowUnassociatedTargets

Enables a Maintenance Window task to execute on managed instances, even if you
                                 haven't registered those instances as targets. If this is enabled, then you must specify
                                 the unregistered instances (by instance ID) when you register a task with the
                                 Maintenance Window.

                                 Required: Yes

                                 Type: Boolean

                                 Update requires: No
                                    interruption

Schedule

The schedule of the Maintenance Window in the form of a cron or rate
                                 expression.

                                 Required: Yes

                                 Type: String

                                 Update requires: No
                                    interruption

Duration

The duration of the Maintenance Window in hours.

                                 Required: Yes

                                 Type: Integer

                                 Update requires: No
                                    interruption

Cutoff

The number of hours before the end of the Maintenance Window that Systems Manager
                                 stops
                                 scheduling new tasks for execution.

                                 Required: Yes

                                 Type: Integer

                                 Update requires: No
                                    interruption

StartDate

The date and time, in ISO-8601 Extended format, for when you want the Maintenance
                                 Window to become active. StartDate allows you to delay activation of the Maintenance
                                 Window until the specified future date.

                                 Required: No

                                 Type: String

                                 Update requires: No
                                    interruption

EndDate

The date and time, in ISO-8601 Extended format, for when you want the Maintenance
                                 Window to become inactive. EndDate allows you to set a date and time in the future
                                 when
                                 the Maintenance Window will no longer run.

                                 Required: No

                                 Type: String

                                 Update requires: No
                                    interruption

ScheduleTimezone

The time zone that the scheduled Maintenance Window executions are based on, in
                                 Internet Assigned Numbers Authority (IANA) format. For example: "America/Los_Angeles",
                                 "etc/UTC", or "Asia/Seoul". For more information, see the Time Zone Database on the IANA
                                 website.

                                 Required: No

                                 Type: String

                                 Update requires: No
                                    interruption

Return Values

Ref

When you pass the logical ID of an AWS::SSM::MaintenanceWindow resource to
                        the intrinsic Ref function, the function returns the maintenance window ID,
                        such as mw-abcde1234567890yz.

For more information about using the Ref function, see Ref.

See Also

AWS::SSM::MaintenanceWindowTarget

AWS::SSM::MaintenanceWindowTask

 CreateMaintenanceWindow in the AWS Systems Manager API
                                    Reference


text:
package org.deviceconnect.android.libmedia.streaming.rtsp;

public class RtspClientException extends RuntimeException {
    private RtspResponse.Status mStatus;

    public RtspClientException(String message, RtspResponse.Status status) {
        super(message);
        mStatus = status;
    }

    public RtspClientException(String message, Throwable cause, RtspResponse.Status status) {
        super(message, cause);
        mStatus = status;
    }

    public RtspClientException(Throwable cause, RtspResponse.Status status) {
        super(cause);
        mStatus = status;
    }

    public RtspResponse.Status getStatus() {
        return mStatus;
    }
}


text:
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Beatmaps.Drawables;

namespace osu.Game.Screens.Multi.Components
{
    public class MultiplayerBackgroundSprite : MultiplayerComposite
    {
        private readonly BeatmapSetCoverType beatmapSetCoverType;
        private UpdateableBeatmapBackgroundSprite sprite;

        public MultiplayerBackgroundSprite(BeatmapSetCoverType beatmapSetCoverType = BeatmapSetCoverType.Cover)
        {
            this.beatmapSetCoverType = beatmapSetCoverType;
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            InternalChild = sprite = CreateBackgroundSprite();

            Playlist.CollectionChanged += (_, __) => updateBeatmap();

            updateBeatmap();
        }

        private void updateBeatmap()
        {
            sprite.Beatmap.Value = Playlist.FirstOrDefault()?.Beatmap.Value;
        }

        protected virtual UpdateableBeatmapBackgroundSprite CreateBackgroundSprite() => new UpdateableBeatmapBackgroundSprite(beatmapSetCoverType) { RelativeSizeAxes = Axes.Both };
    }
}


text:
(function () {

    'use strict';

    var controller_name = "cryptonomica.controller.openPGPOnline";

// add to:
// index.html +
// controller.js +
// router.js + ( url: '/openPGPOnline')

    var controller = angular.module(controller_name, []);

// https://docs.angularjs.org/api/ng/provider/$logProvider
    controller.config(function ($logProvider) {
            // $logProvider.debugEnabled(false);
            $logProvider.debugEnabled(true);
        }
    );

    controller.controller(controller_name, [
        '$scope',
        '$sce',
        '$rootScope',
        '$http',
        'GApi',
        'GAuth',
        'GData',
        '$state',
        // 'uiUploader',
        '$log',
        '$cookies',
        '$timeout',
        '$window',
        '$stateParams',
        function openPGPOnlineCtrl($scope,    // <- name for debugging
                                   $sce,
                                   $rootScope,
                                   $http,
                                   GApi,
                                   GAuth,
                                   GData,
                                   $state,
                                   // uiUploader,
                                   $log,
                                   $cookies,
                                   $timeout,
                                   $window,
                                   $stateParams) {

            /*
            * in the view add id with controller name to parent div:
            * <div id="openPGPOnlineCtrl">
            * use this id to access $scope in browser console:
            * angular.element(document.getElementById('openPGPOnlineCtrl')).scope();
            * for example: for example: $scope = angular.element(document.getElementById('openPGPOnlineCtrl')).scope();
            * */

            // $log.debug("openPGPOnline controller started"); //
            // $timeout($rootScope.progressbar.complete(), 1000);

            // --- Alerts:
            $scope.alertDanger = null;  // red
            $scope.alertWarning = null; // yellow
            $scope.alertInfo = null;    // blue
            $scope.alertSuccess = null; // green
            //
            $scope.error = {};
            //

            $scope.prefillCreateKeyForm = function () {

                if ($rootScope.gapi && $rootScope.gapi.user) {
                    $log.debug($rootScope.gapi.user);
                }

                $scope.createKeyForm = {};
                $scope.createKeyForm.name;
                $scope.createKeyForm.firstName;
                $scope.createKeyForm.lastName;
                $scope.createKeyForm.userEmail;

                if ($rootScope.gapi && $rootScope.gapi.user && $rootScope.gapi.user.email) {
                    $scope.createKeyForm.userEmail = $rootScope.gapi.user.email;
                }

                if ($rootScope.currentUser) {

                    if ($rootScope.currentUser.firstName) {
                        $scope.createKeyForm.firstName = $rootScope.currentUser.firstName;
                    }

                    if ($rootScope.currentUser.lastName) {
                        $scope.createKeyForm.lastName = $rootScope.currentUser.lastName;
                    }

                    $scope.name = $scope.createKeyForm.firstName + " " + $scope.createKeyForm.lastName;

                } else if ($rootScope.gapi && $rootScope.gapi.user && $rootScope.gapi.user.name) {
                    $scope.name = $rootScope.gapi.user.name
                }

                // $scope.$apply();
            };
            $scope.prefillCreateKeyForm();

            $scope.publicKey;
            $scope.verifyPublicKeyData = function () {

                $scope.keyUploadErrorMessage = null;
                $scope.keyUploadSuccessMessage = null;

                // $scope.pgpPublicKeyDataError = null; // use this:
                if ($rootScope.stringIsNullUndefinedOrEmpty($scope.pgpPublicKeyUploadForm.asciiArmored)) {
                    $scope.keyUploadErrorMessage = "Key string is null or empty";
                    return false;
                }

                if ($scope.pgpPublicKeyUploadForm.asciiArmored.includes("PGP PRIVATE KEY BLOCK")) {
                    $scope.keyUploadErrorMessage = "(!) THIS IS PRIVATE KEY, DO NOT UPLOAD (!)";
                    // $scope.$apply(); not here
                    return false;
                }

                try {
                    $scope.pgpPublicKeyData = $rootScope.readPublicKeyData($scope.pgpPublicKeyUploadForm.asciiArmored);
                } catch (error) {
                    $log.debug(error);
                    $scope.keyUploadErrorMessage = "This is not a valid OpenPGP public key";
                    return false;
                }

                if ($scope.stringIsNullUndefinedOrEmpty($scope.pgpPublicKeyData.userId)) {
                    $scope.keyUploadErrorMessage = "User ID is empty";
                    return false;
                }

                if ($scope.pgpPublicKeyData.bitsSize < 2048) {
                    $scope.keyUploadErrorMessage = "Key size is " + $scope.pgpPublicKeyData.bitsSize + "but min. 2048 required";
                    return false;
                }
                return true;
            };

            $scope.addPublicKeyToProfile = function () {

                $scope.pgpPublicKeyUploadForm = {};
                $scope.pgpPublicKeyUploadForm.asciiArmored = $("#pubkeyShow").val();
                $log.info($scope.pgpPublicKeyUploadForm);

                if ($scope.verifyPublicKeyData()) {
                    $rootScope.progressbar.start(); // <<<<<<<<<<<
                    GApi.executeAuth('pgpPublicKeyAPI', 'uploadNewPGPPublicKey',
                        $scope.pgpPublicKeyUploadForm // -> net.cryptonomica.forms.PGPPublicKeyUploadForm
                    )
                        .then(function (pgpPublicKeyUploadReturn) {
                            console.log("pgpPublicKeyUploadReturn: ");
                            $log.info(pgpPublicKeyUploadReturn);
                            $scope.keyUploadSuccessMessage = pgpPublicKeyUploadReturn.messageToUser;
                        })
                        .catch(function (error) {
                            console.log("error: ");
                            $log.info(error);
                            $scope.keyUploadErrorMessage = error.message.replace("java.lang.Exception: ", ""); // resp.message or resp.error.message - java.lang.Exception:
                        })
                        .finally(function () {
                            // $scope.$apply();
                            $timeout($rootScope.progressbar.complete(), 1000);
                        });
                } else {
                    $log.error("public key verification failed");
                }

            }; // end of $scope.keyUpload

            $scope.toggleShowPassword = function (passwordElementId, iconId) {
                const passphrase = document.getElementById(passwordElementId);
                const showPasswordIcon = document.getElementById(iconId);
                if (passphrase.type === "password") {
                    passphrase.type = "text";
                    showPasswordIcon.className = "eye icon";
                    showPasswordIcon.title = "click to hide password";
                } else {
                    passphrase.type = "password";
                    showPasswordIcon.className = "eye slash icon";
                    showPasswordIcon.title = "click to show password";
                }
            }

            // ----- SIGN
            $scope.textToSign = "This is a test message we want to sign.";
            $scope.signText = function () {

                $('#signMessage').click(function (event) {

                    $("#signOrEncryptMessageError").text("");

                    $scope.textToSign = $scope.textToSign.trim();

                    if ($scope.messageToSign.toString().length === 0) {
                        $("#signOrEncryptMessageError").text("Message to sign is empty").css('color', 'red');
                        return;
                    }

                    var privateKeyArmored = $("#privkeyShow").val();

                    if (privateKeyArmored.toString().length === 0) {
                        $("#signOrEncryptMessageError").text("Private key is empty").css('color', 'red');
                        return;
                    }

                    var passphrase = $("#passphrase").val();
                    if (passphrase.toString().length === 0) {
                        $("#signOrEncryptMessageError").text("Password for private key is empty").css('color', 'red');
                        return;
                    }

                    var privateKeyEncrypted;
                    try {
                        privateKeyEncrypted = openpgp.key.readArmored(privateKeyArmored).keys[0];
                        if (typeof privateKeyEncrypted === 'undefined' || privateKeyEncrypted === null) {
                            $("#signOrEncryptMessageError").text("Private key is invalid").css('color', 'red');
                            return;
                        }
                        privateKeyEncrypted.decrypt(passphrase); // boolean
                    } catch (error) {
                        console.log("sign message error:");
                        console.log(error);
                        $("#signOrEncryptMessageError").text(error).css('color', 'red');
                    }

                    var privateKeyDecrypted = privateKeyEncrypted;

                    var signObj = {
                        data: messageToSign, // cleartext input to be signed
                        privateKeys: privateKeyDecrypted, // array of keys or single key with decrypted secret key data to sign cleartext
                        armor: true // (optional) if the return value should be ascii armored or the message object
                    };
                    var signedMessageObj = {};
                    // see: https://openpgpjs.org/openpgpjs/doc/openpgp.js.html#line285
                    // https://openpgpjs.org/openpgpjs/doc/module-openpgp.html
                    openpgp.sign(signObj)
                        .then(function (res) { //
                            // @return {Promise<String|CleartextMessage>} ASCII armored message or the message of type CleartextMessage
                            signedMessageObj = res;

                            console.log(JSON.stringify(signedMessageObj));

                            console.log(signedMessageObj.data);

                            $("#signedMessage").val(signedMessageObj.data);
                            console.log("signedMessageObj.data.length: ", signedMessageObj.data.length);

                            onSignedMessageChange();

                        })
                        .catch(function (error) {
                            console.log("sign message error:");
                            console.log(error);
                            ("#signOrEncryptMessageError").text(error).css('color', 'red');
                        });
                });

            }

            $timeout($rootScope.progressbar.complete(), 1000);
        } // end of Ctrl

    ]);

})();


text:
import { expect, describe, it } from '@jest/globals';
import { HistoryDialogComponent } from './history-dialog.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { SharedModule } from '../../modules/shared/shared.module';
import { NgxTestWrapper } from '../../../../../testing/wrapper';
import { mount } from '../../../../../testing/utils';
import { MockModule, MockComponent } from 'ng-mocks';
import { NO_ERRORS_SCHEMA } from '@angular/core';

describe('HistoryDialogComponent', () => {
  let wrapper: NgxTestWrapper<HistoryDialogComponent>;

  beforeEach(async() => {
    wrapper = await mount({
      component: HistoryDialogComponent,
      imports: [
        MockModule(SharedModule),
      ],
      schemas: [ NO_ERRORS_SCHEMA ],
    });
  });

  it('should create', () => {
    expect(wrapper.componentInstance).toBeTruthy();
  });

  it('should render correctly', () => {
    expect(wrapper.element).toMatchSnapshot();
  });
});


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Snowdrops and snowflakes 34. 1956

#### Original name
null

### Remarks
null


text:
<?php
namespace App\Helpers;
use App\Models\Click;
use App\Models\Link;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class StatsHelper {
    function __construct($link_id, $left_bound, $right_bound) {
        $this->link_id = $link_id;
        $this->left_bound_parsed = Carbon::parse($left_bound);
        $this->right_bound_parsed = Carbon::parse($right_bound);

        if (!$this->left_bound_parsed->lte($this->right_bound_parsed)) {
            // If left bound is not less than or equal to right bound
            throw new \Exception('Invalid bounds.');
        }

        $days_diff = $this->left_bound_parsed->diffInDays($this->right_bound_parsed);
        $max_days_diff = env('_ANALYTICS_MAX_DAYS_DIFF') ?: 365;

        if ($days_diff > $max_days_diff) {
            throw new \Exception('Bounds too broad.');
        }
    }

    public function getBaseRows() {
        /**
        * Fetches base rows given left date bound, right date bound, and link id
        *
        * @param integer $link_id
        * @param string $left_bound
        * @param string $right_bound
        *
        * @return DB rows
        */

        return DB::table('clicks')
            ->where('link_id', $this->link_id)
            ->where('created_at', '>=', $this->left_bound_parsed)
            ->where('created_at', '<=', $this->right_bound_parsed);
    }

    public function getDayStats() {
        // Return stats by day from the last 30 days
        // date => x
        // clicks => y
        $stats = $this->getBaseRows()
            ->select(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d') AS x, count(*) AS y"))
            ->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))
            ->orderBy('x', 'asc')
            ->get();

        return $stats;
    }

    public function getCountryStats() {
        $stats = $this->getBaseRows()
            ->select(DB::raw("country AS label, count(*) AS clicks"))
            ->groupBy('country')
            ->orderBy('clicks', 'desc')
            ->get();

        return $stats;
    }

    public function getRefererStats() {
        $stats = $this->getBaseRows()
            ->select(DB::raw("COALESCE(referer_host, 'Direct') as label, count(*) as clicks"))
            ->groupBy('referer_host')
            ->orderBy('clicks', 'desc')
            ->get();

        return $stats;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="period_indicators">
        <item>T1</item>
        <item>T2</item>
        <item>S1</item>
        <item>X1</item>
        <item>T3</item>
        <item>T4</item>
        <item>Y1</item>
        <item>Abs</item>
    </array>
    <array name="theme_array">
        <item>Light</item>
        <item>Dark</item>
    </array>
    <array name="accent_color_array">
        <item>@color/material_pink_200</item>
        <item>@color/material_pink_300</item>
        <item>@color/material_pink_400</item>
        <item>@color/material_pink_500</item>
        <item>@color/material_pink_600</item>
        <item>@color/material_pink_700</item>
        <item>@color/material_red_200</item>
        <item>@color/material_red_300</item>
        <item>@color/material_red_400</item>
        <item>@color/material_red_500</item>
        <item>@color/material_red_600</item>
        <item>@color/material_red_700</item>
        <item>@color/material_purple_200</item>
        <item>@color/material_purple_300</item>
        <item>@color/material_purple_400</item>
        <item>@color/material_purple_500</item>
        <item>@color/material_purple_600</item>
        <item>@color/material_purple_700</item>
        <item>@color/material_blue_200</item>
        <item>@color/material_blue_300</item>
        <item>@color/material_blue_400</item>
        <item>@color/material_blue_500</item>
        <item>@color/material_blue_600</item>
        <item>@color/material_blue_700</item>
        <item>@color/material_cyan_200</item>
        <item>@color/material_cyan_300</item>
        <item>@color/material_cyan_400</item>
        <item>@color/material_cyan_500</item>
        <item>@color/material_cyan_600</item>
        <item>@color/material_cyan_700</item>
        <item>@color/material_teal_200</item>
        <item>@color/material_teal_300</item>
        <item>@color/material_teal_400</item>
        <item>@color/material_teal_500</item>
        <item>@color/material_teal_600</item>
        <item>@color/material_teal_700</item>
        <item>@color/material_green_200</item>
        <item>@color/material_green_300</item>
        <item>@color/material_green_400</item>
        <item>@color/material_green_500</item>
        <item>@color/material_green_600</item>
        <item>@color/material_green_700</item>
        <item>@color/material_light_green_200</item>
        <item>@color/material_light_green_300</item>
        <item>@color/material_light_green_400</item>
        <item>@color/material_light_green_500</item>
        <item>@color/material_light_green_600</item>
        <item>@color/material_light_green_700</item>
        <item>@color/material_yellow_200</item>
        <item>@color/material_yellow_300</item>
        <item>@color/material_yellow_400</item>
        <item>@color/material_yellow_500</item>
        <item>@color/material_yellow_600</item>
        <item>@color/material_yellow_700</item>
        <item>@color/material_orange_200</item>
        <item>@color/material_orange_300</item>
        <item>@color/material_orange_400</item>
        <item>@color/material_orange_500</item>
        <item>@color/material_orange_600</item>
        <item>@color/material_orange_700</item>
        <item>@color/material_deep_orange_200</item>
        <item>@color/material_deep_orange_300</item>
        <item>@color/material_deep_orange_400</item>
        <item>@color/material_deep_orange_500</item>
        <item>@color/material_deep_orange_600</item>
        <item>@color/material_deep_orange_700</item>
        <item>@color/material_brown_200</item>
        <item>@color/material_brown_300</item>
        <item>@color/material_brown_400</item>
        <item>@color/material_brown_500</item>
        <item>@color/material_brown_600</item>
        <item>@color/material_brown_700</item>
        <item>@color/material_grey_200</item>
        <item>@color/material_grey_300</item>
        <item>@color/material_grey_400</item>
        <item>@color/material_grey_500</item>
        <item>@color/material_grey_600</item>
        <item>@color/material_grey_700</item>
        <item>@color/material_blue_grey_200</item>
        <item>@color/material_blue_grey_300</item>
        <item>@color/material_blue_grey_400</item>
        <item>@color/material_blue_grey_500</item>
        <item>@color/material_blue_grey_600</item>
    </array>
</resources>


text:
<?php

namespace Curator\Provider;

use Curator\Controller\IntegrationUtils;
use Silex\Application;
use Silex\ControllerProviderInterface;

class MiscRoutes implements ControllerProviderInterface {
  public function connect(Application $app) {
    $this->registerServiceControllers($app);

    $c = $app['controllers_factory'];

    $c->get('/integration-utils/init-secret', 'controller.integration_utils:initHmacSecret');

    return $c;
  }

  protected function registerServiceControllers(Application $app) {
    $app['controller.integration_utils'] = $app->share(function ($app) {
      return new IntegrationUtils();
    });
  }
}


text:
MathJax.Localization.addTranslation("ca",null,{
  menuTitle: "catal\u00E0",
  version: "2.7.0-beta",
  isLoaded: true,
  domains: {
    "_": {
        version: "2.7.0-beta",
        isLoaded: true,
        strings: {
          CookieConfig: "MathJax ha trobat una galeta de configuraci\u00F3 d'usuari que inclou codi que s'ha d'executar. Voleu executar-lo?",
          MathProcessingError: "Error en processament d'expressi\u00F3 matem\u00E0tica",
          MathError: "Error d'expressi\u00F3 matem\u00E0tica",
          LoadFile: "Carregant %1",
          Loading: "Carregant",
          LoadFailed: "No s'ha pogut carregar el fitxer: %1",
          ProcessMath: "Processant expressi\u00F3: %1%%",
          Processing: "Processant",
          TypesetMath: "Formatejant expressi\u00F3: %1%%",
          Typesetting: "Formatejant",
          MathJaxNotSupported: "El vostre navegador no suporta MathJax"
        }
    },
    "FontWarnings": {},
    "HTML-CSS": {},
    "HelpDialog": {},
    "MathML": {},
    "MathMenu": {},
    "TeX": {}
  },
  plural: function (n) {
      if (n === 1) {return 1} // one
      return 2; // other
    },
  number: function (n) {
      return String(n).replace(".", ","); // replace dot by comma
    }
});

MathJax.Ajax.loadComplete("[MathJax]/localization/ca/ca.js");


text:
package com.dremio.exec.planner.logical;

import org.apache.calcite.plan.Convention;
import org.apache.calcite.plan.RelOptRule;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.logical.LogicalFilter;

/**
 * Rule that converts a {@link org.apache.calcite.rel.logical.LogicalFilter} to a Dremio "filter" operation.
 */
public class FilterRule extends RelOptRule {
  public static final RelOptRule INSTANCE = new FilterRule();

  private FilterRule() {
    super(RelOptHelper.any(LogicalFilter.class, Convention.NONE), "FilterRule");
  }

  @Override
  public void onMatch(RelOptRuleCall call) {
    final LogicalFilter filter = (LogicalFilter) call.rel(0);
    final RelNode input = filter.getInput();
    //final RelTraitSet traits = filter.getTraitSet().plus(Rel.LOGICAL);
    final RelNode convertedInput = convert(input, input.getTraitSet().plus(Rel.LOGICAL).simplify());
    call.transformTo(new FilterRel(filter.getCluster(), convertedInput.getTraitSet(), convertedInput, filter.getCondition()));
  }
}