text:
<?php

/**
 * Created by PhpStorm.
 * User: Godluck Akyoo
 * Date: 2/29/2016
 * Time: 4:17 PM
 */
class Ohkr extends CI_Controller
{
    private $data;
    private $controller;

    public function __construct()
    {
        parent::__construct();

        $this->load->model(array("Ohkr_model", "Perm_model", "User_model"));
        log_message('debug', 'Ohkr controller initialized');
        //$this->load->library("Db_exp");

        $this->controller = $this->router->fetch_class();
    }

    /**
     * Check login
     *
     * @return response
     */
    function is_logged_in()
    {
        if (!$this->ion_auth->logged_in()) {
            // redirect them to the login page
            redirect('auth/login', 'refresh');
        }
    }

    /**
     * @param $method_name
     * Check if user has permission
     */
    function has_allowed_perm($method_name)
    {
        if (!perms_role($this->controller, $method_name)) {
            show_error("You are not allowed to view this page", 401, "Unauthorized");
        }
    }

    public function index()
    {
        $this->disease_list();
    }

    //list diseases
    function disease_list()
    {
        $this->data['title'] = "Diseases List";

        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        $config = array(
            'base_url' => $this->config->base_url("ohkr/disease_list"),
            'total_rows' => $this->Ohkr_model->count_disease(),
            'uri_segment' => 3,
        );

        $this->pagination->initialize($config);
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

        $this->data['disease_list'] = $this->Ohkr_model->find_all_disease($this->pagination->per_page, $page);
        $this->data["links"] = $this->pagination->create_links();

        //render view
        $this->load->view('header', $this->data);
        $this->load->view("ohkr/list_disease");
        $this->load->view('footer');
    }

    //add new disease
    public function add_new_disease()
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        $data['title'] = "Add new";
        $data['species'] = $this->Ohkr_model->find_all_species(100, 0);
        $data['groups'] = $this->User_model->find_user_groups();

        $this->form_validation->set_rules("name", $this->lang->line("label_disease_name"), "required");
        $this->form_validation->set_rules("specie", $this->lang->line("label_specie_name"), "required");
        $this->form_validation->set_rules("description", $this->lang->line("label_description"), "required");
        $this->form_validation->set_rules("group[]", $this->lang->line("label_recipient_group"), "required");
        $this->form_validation->set_rules("message[]", $this->lang->line("label_alert_message"), "required");

        if ($this->form_validation->run() === FALSE) {

            $this->load->view('header', $data);
            $this->load->view("ohkr/add_new_disease", $data);
            $this->load->view('footer');

        } else {
            $disease = array(
                "title" => $this->input->post("name"),
                "specie_id" => $this->input->post("specie"),
                "description" => $this->input->post("description"),
                "date_created" => date("Y-m-d H:i:s")
            );

            $alert_groups = $this->input->post("group");
            $alert_messages = $this->input->post("message");

            $this->db->trans_start();
            $disease_id = $this->Ohkr_model->add_disease($disease);

            for ($i = 0; $i < count($alert_messages); $i++) {
                $message = array(
                    "disease_id" => $disease_id,
                    "group_id" => $alert_groups[$i],
                    "message" => $alert_messages[$i],
                    "type" => "TEXT",
                    "status" => "Enabled",
                    "date_created" => date("Y-m-d H:i:s")
                );
                $this->Ohkr_model->create_response_sms($message);
            }
            $this->db->trans_complete();

            if ($this->db->trans_status()) {
                file_get_contents(base_url("api/v3/intel/set_epi_map"));
                $this->session->set_flashdata("message", display_message($this->lang->line("add_disease_successful")));
            } else {
                $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_add_disease")));
            }
            redirect("ohkr/add_new_disease");
        }
    }

    /**
     * edit disease
     *
     * @param $disease_id
     */
    public function edit_disease($disease_id)
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        if (!$disease_id) {
            $this->session->set_flashdata("message", display_message($this->lang->line("select_disease_to_edit")));
            redirect("ohkr/disease_list");
            exit;
        }

        $data['title'] = "Edit Disease";
        $data['species'] = $this->Ohkr_model->find_all_species(100, 0);
        $data['disease'] = $this->Ohkr_model->get_disease_by_id($disease_id);
        $data['messages'] = $this->Ohkr_model->find_response_sms_by_disease_id($disease_id);

        $this->form_validation->set_rules("name", $this->lang->line("label_disease_name"), "required");
        $this->form_validation->set_rules("specie", $this->lang->line("label_specie_name"), "required");
        $this->form_validation->set_rules("description", $this->lang->line("label_description"), "required");
        $this->form_validation->set_rules("group", $this->lang->line("label_recipient_group"), "required");
        $this->form_validation->set_rules("message", $this->lang->line("label_alert_message"), "required");

        if ($this->form_validation->run() === FALSE) {

            $this->load->view('header', $data);
            $this->load->view("ohkr/edit_disease", $data);
            $this->load->view('footer');
        } else {
            $disease = array(
                "title" => $this->input->post("name"),
                "specie_id" => $this->input->post("specie"),
                "description" => $this->input->post("description")
            );

            if ($this->Ohkr_model->update_disease($disease_id, $disease)) {
                file_get_contents(base_url("api/v3/intel/set_epi_map"));
                $this->session->set_flashdata("message", display_message($this->lang->line("edit_disease_successful")));
            } else {
                $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_edit_disease")));
            }
            redirect("ohkr/edit_disease/" . $disease_id, "refresh");
        }

    }

    /**
     * @param $disease_id
     */
    function delete_disease($disease_id)
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        if (!$disease_id) {
            $this->session->set_flashdata("message", display_message($this->lang->line("select_disease_to_delete")));
            redirect("ohkr/disease_list");
            exit;
        }

        if ($this->Ohkr_model->delete_disease($disease_id)) {
            file_get_contents(base_url("api/v3/intel/set_epi_map"));
            $this->session->set_flashdata("message", display_message($this->lang->line("delete_disease_successful")));
        } else {
            $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_delete_disease")));
        }
        redirect("ohkr/disease_list", "refresh");
    }

    public function species_list()
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        $config = array(
            'base_url' => $this->config->base_url("ohkr/species_list"),
            'total_rows' => $this->Ohkr_model->count_species(),
            'uri_segment' => 3,
        );

        $this->pagination->initialize($config);
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

        $data['species'] = $this->Ohkr_model->find_all_species($this->pagination->per_page, $page);
        $data["links"] = $this->pagination->create_links();

        //render view
        $data['title'] = "Species List";
        $this->load->view('header', $data);
        $this->load->view("ohkr/list_species", $data);
        $this->load->view('footer');
    }

    public function add_new_specie()
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        $data['title'] = "Add new specie";

        $this->form_validation->set_rules("specie", $this->lang->line("label_specie"),
            "required|is_unique[" . $this->config->item("table_species") . ".title]");

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('header', $data);
            $this->load->view("ohkr/add_new_specie", $data);
            $this->load->view('footer');
        } else {
            $specie = array(
                "title" => $this->input->post("specie")
            );

            if ($this->Ohkr_model->add_specie($specie)) {
                file_get_contents(base_url("api/v3/intel/set_epi_map"));
                $this->session->set_flashdata("message", display_message($this->lang->line("add_specie_successful")));
            } else {
                $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_add_specie")));
            }
            redirect("ohkr/add_new_specie");
        }
    }

    public function edit_specie($specie_id)
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        if (!$specie_id) {
            $this->session->set_flashdata("message", display_message($this->lang->line("select_specie_to_edit")));
            redirect("ohkr/species_list");
            exit;
        }

        $data['title'] = "Edit specie";
        $data['specie'] = $this->Ohkr_model->get_specie_by_id($specie_id);

        $this->form_validation->set_rules("specie", $this->lang->line("label_specie"), "required");

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('header', $data);
            $this->load->view("ohkr/edit_specie");
            $this->load->view('footer');
        } else {
            $specie = array(
                "title" => $this->input->post("specie")
            );

            if ($this->Ohkr_model->update_specie($specie_id, $specie)) {
                file_get_contents(base_url("api/v3/intel/set_epi_map"));
                $this->session->set_flashdata("message", display_message($this->lang->line("edit_specie_successful")));
            } else {
                $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_edit_specie")));
            }
            redirect("ohkr/edit_specie/" . $specie_id);
        }
    }

    function delete_specie($specie_id)
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        if (!$specie_id) {
            $this->session->set_flashdata("message", display_message($this->lang->line("select_specie_to_delete")));
            redirect("ohkr/species_list");
            exit;
        }

        if ($this->Ohkr_model->delete_specie($specie_id)) {
            file_get_contents(base_url("api/v3/intel/set_epi_map"));
            $this->session->set_flashdata("message", display_message($this->lang->line("delete_specie_successful")));
        } else {
            $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_delete_specie")));
        }
        redirect("ohkr/species_list", "refresh");
    }

    /**
     * symptom lists
     */
    public function symptoms_list()
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        $config = array(
            'base_url' => $this->config->base_url("ohkr/symptoms_list"),
            'total_rows' => $this->Ohkr_model->count_symptoms(),
            'uri_segment' => 3,
        );

        $this->pagination->initialize($config);
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

        $data['symptoms'] = $this->Ohkr_model->find_all_symptoms($this->pagination->per_page, $page);
        $data["links"] = $this->pagination->create_links();

        //render view
        $data['title'] = "Symptoms List";
        $this->load->view('header', $data);
        $this->load->view("ohkr/list_symptom");
        $this->load->view('footer');
    }

    //add new symptom
    function add_new_symptom()
    {
        $data['title'] = "Add Clinical Manifestation";

        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        $this->form_validation->set_rules("name", $this->lang->line("label_symptom_name"), "required");
        $this->form_validation->set_rules("code", $this->lang->line("label_symptom_code"), "required");

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('header', $data);
            $this->load->view("ohkr/add_new_symptom", $data);
            $this->load->view('footer');
        } else {
            $symptoms = array(
                "title" => $this->input->post("name"),
                "code" => $this->input->post("code"),
                "description" => $this->input->post("description")
            );

            if ($this->Ohkr_model->add_symptom($symptoms)) {
                file_get_contents(base_url("api/v3/intel/set_epi_map"));
                $this->session->set_flashdata("message", display_message($this->lang->line("add_symptom_successful")));
            } else {
                $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_add_symptom")));
            }
            redirect("ohkr/add_new_symptom");
        }
    }

    /*edit symptom
     * @param $symptom_id
     */
    public function edit_symptom($symptom_id)
    {
        //check login
        $this->is_logged_in();

        //check permission
        //$this->has_allowed_perm($this->router->fetch_method());

        if (!$symptom_id) {
            $this->session->set_flashdata("message", display_message($this->lang->line("select_symptom_to_edit")));
            redirect("ohkr/symptoms_list");
            exit;
        }

        $data['title'] = "Edit symptom";
        $data['symptom'] = $this->Ohkr_model->get_symptom_by_id($symptom_id);

        $this->form_validation->set_rules("name", $this->lang->line("label_symptom_name"), "required");

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('header', $data);
            $this->load->view("ohkr/edit_symptom", $data);
            $this->load->view('footer');
        } else {
            $symptoms = array(
                "title" => $this->input->post("name"),
                "code" => $this->input->post("code"),
                "description" => $this->input->post("description")
            );

            if ($this->Ohkr_model->update_symptom($symptom_id, $symptoms)) {
                file_get_contents(base_url("api/v3/intel/set_epi_map"));
                $this->session->set_flashdata("message", display_message($this->lang->line("edit_symptom_successful")));
            } else {
                $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_edit_symptom")));
            }
            redirect("ohkr/edit_symptom/" . $symptom_id);
        }
    }

    function delete_symptom($symptom_id)
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        if (!$symptom_id) {
            $this->session->set_flashdata("message", display_message($this->lang->line("select_symptom_to_delete")));
            redirect("ohkr/symptoms_list");
            exit;
        }

        if ($this->Ohkr_model->delete_symptom($symptom_id)) {
            file_get_contents(base_url("api/v3/intel/set_epi_map"));
            $this->session->set_flashdata("message", display_message($this->lang->line("delete_symptom_successful")));
        } else {
            $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_delete_symptom")));
        }
        redirect("ohkr/symptoms_list", "refresh");
    }

    //disease symptoms
    public function disease_symptoms_list($disease_id)
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        $data['title'] = "Disease Symptoms";
        $data['disease'] = $this->Ohkr_model->get_disease_by_id($disease_id);
        $data['symptoms'] = $this->Ohkr_model->find_disease_symptoms($disease_id);

        $this->load->view('header', $data);
        $this->load->view("ohkr/disease_symptoms_list");
        $this->load->view('footer');
    }

    public function add_disease_symptom($disease_id)
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        if (!$disease_id) {
            $this->session->set_flashdata("message", display_message($this->lang->line("select_disease_to_add")));
            redirect("ohkr/disease_symptoms_list/" . $disease_id);
            exit;
        }

        $data['title'] = "Add Disease Symptom";
        $data['disease'] = $this->Ohkr_model->get_disease_by_id($disease_id);
        $data['symptoms'] = $this->Ohkr_model->find_all_symptoms(100, 0);

        $this->form_validation->set_rules("symptom", $this->lang->line("label_symptom_name"), "required");
        $this->form_validation->set_rules("importance", "Importance", "required");

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('header', $data);
            $this->load->view("ohkr/add_disease_symptom");
            $this->load->view('footer');
        } else {
            $symptoms = array(
                "symptom_id" => $this->input->post("symptom"),
                "disease_id" => $disease_id,
                "importance" => $this->input->post("importance")
            );

            if ($this->Ohkr_model->add_disease_symptom($symptoms)) {
                file_get_contents(base_url("api/v3/intel/set_epi_map"));
                $this->session->set_flashdata("message", display_message($this->lang->line("add_symptom_successful")));
            } else {
                $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_add_symptom")));
            }
            redirect("ohkr/disease_symptoms_list/" . $disease_id, "refresh");
        }
    }

    public function edit_disease_symptom($disease_id, $disease_symptom_id)
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        if (!$disease_symptom_id) {
            $this->session->set_flashdata("message", display_message($this->lang->line("select_symptom_to_edit")));
            redirect("ohkr/disease_symptoms_list/" . $disease_id);
            exit;
        }

        $data['title'] = "Edit Disease Symptom";
        $data['symptoms'] = $this->Ohkr_model->find_all_symptoms(100, 0);
        $data['disease'] = $this->Ohkr_model->get_disease_by_id($disease_id);

        $disease_symptom = $this->Ohkr_model->get_disease_symptom_by_id($disease_symptom_id);
        $data['symptom'] = $this->Ohkr_model->get_symptom_by_id($disease_symptom->symptom_id);
        $data['importance'] = $disease_symptom->importance;
        $data['disease_symptom_id'] = $disease_symptom_id;

        //form validation
        $this->form_validation->set_rules("symptom", $this->lang->line("label_symptom_name"), "required");
        $this->form_validation->set_rules("importance", "Importance", "required");

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('header', $data);
            $this->load->view("ohkr/edit_disease_symptom");
            $this->load->view('footer');
        } else {
            $symptoms = array(
                "symptom_id" => $this->input->post("symptom"),
                "disease_id" => $disease_id,
                "importance" => $this->input->post("importance")
            );

            if ($this->Ohkr_model->update_disease_symptom($disease_symptom_id, $symptoms)) {
                file_get_contents(base_url("api/v3/intel/set_epi_map"));
                $this->session->set_flashdata("message", display_message($this->lang->line("edit_symptom_successful")));
            } else {
                $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_edit_symptom")));
            }
            redirect("ohkr/disease_symptoms_list/" . $disease_id, "refresh");
        }
    }

    function delete_disease_symptom($disease_id, $disease_symptom_id)
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        if (!$disease_symptom_id) {
            $this->session->set_flashdata("message", display_message($this->lang->line("select_symptom_to_delete")));
            redirect("ohkr/disease_symptoms_list/" . $disease_id);
            exit;
        }

        if ($this->Ohkr_model->delete_disease_symptom($disease_symptom_id)) {
            file_get_contents(base_url("api/v3/intel/set_epi_map"));
            $this->session->set_flashdata("message", display_message($this->lang->line("delete_symptom_successful")));
        } else {
            $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_delete_symptom")));
        }
        redirect("ohkr/disease_symptoms_list/" . $disease_id);
    }

    //disease symptoms
    public function disease_faq($disease_id)
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        $data['title'] = "Disease FAQ";
        $data['disease'] = $this->Ohkr_model->get_disease_by_id($disease_id);
        $data['faq'] = $this->Ohkr_model->find_disease_faq($disease_id);

        $this->load->view('header', $data);
        $this->load->view("ohkr/disease_faq");
        $this->load->view('footer');
    }

    public function add_disease_faq($disease_id)
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        if (!$disease_id) {
            $this->session->set_flashdata("message", display_message($this->lang->line("select_disease_to_add")));
            redirect("ohkr/disease_faq/" . $disease_id);
            exit;
        }

        $data['title'] = "Add Disease FAQ";
        $data['disease'] = $this->Ohkr_model->get_disease_by_id($disease_id);

        $this->form_validation->set_rules("question", $this->lang->line("label_question"), "required");
        $this->form_validation->set_rules("answer", $this->lang->line("label_answer"), "required");

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('header', $data);
            $this->load->view("ohkr/add_disease_faq");
            $this->load->view('footer');
        } else {
            $faq = array(
                "disease_id" => $disease_id,
                "question" => $this->input->post("question"),
                "answer" => $this->input->post("answer")
            );

            if ($this->Ohkr_model->add_disease_faq($faq)) {
                $this->session->set_flashdata("message", display_message($this->lang->line("add_faq_successful")));
            } else {
                $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_add_faq")));
            }
            redirect("ohkr/disease_faq/" . $disease_id, "refresh");
        }
    }

    public function edit_disease_faq($disease_id, $faq_id)
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        if (!$faq_id) {
            $this->session->set_flashdata("message", display_message($this->lang->line("select_faq_to_edit")));
            redirect("ohkr/disease_faq/" . $disease_id);
            exit;
        }

        $data['title'] = "Edit Disease Faq";
        $data['disease'] = $this->Ohkr_model->get_disease_by_id($disease_id);

        $data['faq'] = $this->Ohkr_model->get_disease_faq_by_id($faq_id);

        //form validation
        $this->form_validation->set_rules("question", $this->lang->line("label_question"), "required");
        $this->form_validation->set_rules("answer", $this->lang->line("label_answer"), "required");

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('header', $data);
            $this->load->view("ohkr/edit_disease_faq");
            $this->load->view('footer');
        } else {
            $faq = array(
                "question" => $this->input->post("question"),
                "answer" => $this->input->post("answer")
            );

            if ($this->Ohkr_model->update_disease_faq($faq_id, $faq)) {
                $this->session->set_flashdata("message", display_message($this->lang->line("edit_faq_successful")));
            } else {
                $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_edit_faq")));
            }
            redirect("ohkr/disease_faq/" . $disease_id, "refresh");
        }
    }

    function delete_disease_faq($disease_id, $faq_id)
    {
        //check login
        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        if (!$faq_id) {
            $this->session->set_flashdata("message", display_message($this->lang->line("select_faq_to_delete")));
            redirect("ohkr/disease_faq/" . $disease_id);
            exit;
        }

        if ($this->Ohkr_model->delete_disease_faq($faq_id)) {
            $this->session->set_flashdata("message", display_message($this->lang->line("delete_faq_successful")));
        } else {
            $this->session->set_flashdata("message", display_message($this->lang->line("error_failed_to_delete_faq")));
        }
        redirect("ohkr/disease_faq/" . $disease_id);
    }

    public function manage_specie_disease()
    {

        $this->save_dbexp_post_vars();

        $ele_id = $this->session->userdata['post']['ele_id'];
        $arr = $this->Perm_model->get_field_data('specie_id,disease_id', 'diseases_symptoms', $ele_id);

        $cond = " specie_id = '" . $arr['specie_id'] . "' AND disease_id = '" . $arr['disease_id'] . "'";

        $available_symptoms = $this->get_available_symptoms($arr);

        $this->db_exp->set_table('diseases_symptoms');
        $this->db_exp->set_hidden($arr);
        $this->db_exp->set_hidden('date_created');
        $this->db_exp->set_search_condition($cond);

        $action = $this->input->post('action');
        if ($action == 'insert' || $action == 'edit') {
            $this->db_exp->set_select('symptom_id', $available_symptoms);
            $this->db_exp->set_hidden('id');
        } else {
            $this->db_exp->set_db_select('symptom_id', 'symptoms', 'id', 'name');
        }
        $this->db_exp->render('row_list');

    }

    private function get_available_symptoms($arr)
    {

        $s_arr = array();
        $submitted_symptoms = $this->Ohkr_model->get_submitted_symptoms($arr);
        foreach ($submitted_symptoms as $val) {

            $id = $val['symptom_id'];
            $s_arr[$id] = '';
        }

        $a_arr = array();
        $available_symptoms = $this->Ohkr_model->get_all_symptoms();
        foreach ($available_symptoms as $val) {

            if ($val['id'] == 0) continue;

            $id = $val['id'];
            $name = $val['name'];
            $a_arr[$id] = $name;
        }

        $tmp = array_diff_key($a_arr, $s_arr);
        //print_r($tmp);
        return $tmp;
    }

    public function save_dbexp_post_vars()
    {
        $post = $this->input->post();
        $db_exp_submit = $this->input->post('db_exp_submit_engaged');
        if (!empty ($db_exp_submit) || @$post ['action'] == 'insert' || @$post ['action'] == 'edit') {
        } else {
            $this->session->set_userdata('post', $post);
        }
    }

    public function add_new_response_sms($disease_id)
    {

        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        if (!$disease_id) {
            $this->session->set_flashdata("message", display_message($this->lang->line("select_disease_to_edit")));
            redirect("ohkr/disease_list");
            exit;
        }

        $data['title'] = "Add New Disease Alert SMS";
        $data['disease_id'] = $disease_id;

        $data['groups'] = $this->User_model->find_user_groups();

        $this->form_validation->set_rules("group", $this->lang->line("label_recipient_group"), "required");
        $this->form_validation->set_rules("message", $this->lang->line("label_alert_message"), "required");
        $this->form_validation->set_rules("status", $this->lang->line("label_status"), "required");

        if ($this->form_validation->run() === FALSE) {

            $this->load->view('header', $data);
            $this->load->view("ohkr/add_response_sms", $data);
            $this->load->view('footer');
        } else {
            $message = array(
                "disease_id" => $disease_id,
                "group_id" => $this->input->post("group"),
                "message" => $this->input->post("message"),
                "type" => "TEXT",
                "status" => "Enabled",
                "date_created" => date("Y-m-d H:i:s")
            );

            if ($this->Ohkr_model->create_response_sms($message)) {
                $this->session->set_flashdata("message", display_message("Alert SMS was successfully created"));
            } else {
                $this->session->set_flashdata("message", display_message("warning", "Failed to add new alert SMS"));
            }
            redirect("ohkr/add_new_response_sms/" . $disease_id);
        }
    }

    public function edit_response_sms($sms_id)
    {

        $this->is_logged_in();

        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        if (!$sms_id) {
            $this->session->set_flashdata("message", display_message($this->lang->line("select_disease_to_edit")));
            redirect("ohkr/disease_list");
            exit;
        }

        $data['title'] = "Edit Disease Response SMS";
        $data['message'] = $this->Ohkr_model->find_response_sms_by_id($sms_id);
        $data['groups'] = $this->User_model->find_user_groups();

        $this->form_validation->set_rules("group", $this->lang->line("label_recipient_group"), "required");
        $this->form_validation->set_rules("message", $this->lang->line("label_alert_message"), "required");

        if ($this->form_validation->run() === FALSE) {

            $this->load->view('header', $data);
            $this->load->view("ohkr/edit_response_sms", $data);
            $this->load->view('footer');
        } else {
            $message = array(
                "group_id" => $this->input->post("group"),
                "message" => $this->input->post("message"),
                "status" => "Enabled",
                "date_modified" => date("Y-m-d H:i:s")
            );

            if ($this->Ohkr_model->update_response_sms($sms_id, $message)) {
                $this->session->set_flashdata("message", display_message("Alert SMS was successfully updated"));
            } else {
                $this->session->set_flashdata("message", display_message("warning", "Failed to update alert SMS"));
            }
            redirect("ohkr/edit_response_sms/" . $sms_id);
        }
    }

    public function delete_response_sms($sms_id)
    {
        //check permission
        $this->has_allowed_perm($this->router->fetch_method());

        $message = $this->Ohkr_model->find_response_sms_by_id($sms_id);

        if ($this->Ohkr_model->delete_response_sms($sms_id)) {
            $this->session->set_flashdata("message", display_message("Alert SMS was successfully deleted"));
        } else {
            $this->session->set_flashdata("message", display_message("warning", "Failed to delete alert SMS"));
        }
        redirect("ohkr/edit_disease/" . $message->disease_id);
    }
}


text:
require 'spec_helper'
module Alf
  module Algebra
    describe Rename, 'heading' do

      let(:operand){
        an_operand.with_heading(:id => Integer, :name => String)
      }
      let(:op){
        a_lispy.rename(operand, :name => :foo)
      }

      subject{ op.heading }

      let(:expected){
        Heading[:id => Integer, :foo => String]
      }

      it { should eq(expected) }

    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
using System.Diagnostics;
using System.Windows.Documents;
using System.Windows.Navigation;

namespace KyleHughes.AboutDialog.WPF
{
    internal sealed class ExternalHyperlink : Hyperlink
    {
        public ExternalHyperlink()
        {
            RequestNavigate += ExternalHyperlink_RequestNavigate;
        }

        private void ExternalHyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(NavigateUri.AbsoluteUri);
        }
    }
}


text:
from .. import np, TIME_MAJOR, DTYPE
from ..nn.base import Layer

class Attention(Layer):
    FLOAT_MIN = -100000.0

    def __init__(self, keys, values, values_length, base_name=None,
                 name=None, **kwargs):
        self.keys = keys
        self.values = values
        self.values_length = values_length
        self.seq_mask = np.zeros(self.values.shape[:2], DTYPE)

        self.time_axis = 0 if TIME_MAJOR else 1
        for i, j in enumerate(self.values_length):
            if TIME_MAJOR:
                self.seq_mask[:j, i] = 1
            else:
                self.seq_mask[i, :j] = 1

        super(Attention, self).__init__(['weights', 'biases', 'v_att'],
                                        base_name, name, **kwargs)

    def compute_scores(self, query):
        att_query = np.matmul(query, self.params['weights']) \
                    + self.params['biases']
        energies = self.params['v_att'] * np.tanh(self.keys + np.expand_dims(
            att_query, self.time_axis))
        energies = np.sum(energies, 2)
        energies = energies * self.seq_mask + (
            (1.0 - self.seq_mask) * self.FLOAT_MIN)

        # Stabilize energies first and then exp
        energies = energies - np.max(energies, axis=self.time_axis,
                                     keepdims=True)
        unnormalized_scores = np.exp(energies) * self.seq_mask

        scores_normalized = unnormalized_scores / unnormalized_scores.sum(
            axis=self.time_axis, keepdims=True)

        context = np.expand_dims(scores_normalized, 2) * self.values
        context = np.sum(context, axis=self.time_axis)

        return scores_normalized, context


text:
START_ATF_NAMESPACE
    struct AINetVtbl
    {
        void *(WINAPIV *__vecDelDtor)(struct AINet *_this, unsigned int);
    };
END_ATF_NAMESPACE


text:
@class DBTEAMLOGNamespaceRelativePathLogInfo;

NS_ASSUME_NONNULL_BEGIN

#pragma mark - API Object

///
/// The `NamespaceRelativePathLogInfo` struct.
///
/// Namespace relative path details.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBTEAMLOGNamespaceRelativePathLogInfo : NSObject <DBSerializable, NSCopying>

#pragma mark - Instance fields

/// Namespace ID.
@property (nonatomic, readonly, copy, nullable) NSString *nsId;

/// A path relative to the specified namespace ID.
@property (nonatomic, readonly, copy, nullable) NSString *relativePath;

/// True if the namespace is shared.
@property (nonatomic, readonly, nullable) NSNumber *isSharedNamespace;

#pragma mark - Constructors

///
/// Full constructor for the struct (exposes all instance variables).
///
/// @param nsId Namespace ID.
/// @param relativePath A path relative to the specified namespace ID.
/// @param isSharedNamespace True if the namespace is shared.
///
/// @return An initialized instance.
///
- (instancetype)initWithNsId:(nullable NSString *)nsId
                relativePath:(nullable NSString *)relativePath
           isSharedNamespace:(nullable NSNumber *)isSharedNamespace;

///
/// Convenience constructor (exposes only non-nullable instance variables with
/// no default value).
///
///
/// @return An initialized instance.
///
- (instancetype)initDefault;

- (instancetype)init NS_UNAVAILABLE;

@end

#pragma mark - Serializer Object

///
/// The serialization class for the `NamespaceRelativePathLogInfo` struct.
///
@interface DBTEAMLOGNamespaceRelativePathLogInfoSerializer : NSObject

///
/// Serializes `DBTEAMLOGNamespaceRelativePathLogInfo` instances.
///
/// @param instance An instance of the `DBTEAMLOGNamespaceRelativePathLogInfo`
/// API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBTEAMLOGNamespaceRelativePathLogInfo` API object.
///
+ (nullable NSDictionary<NSString *, id> *)serialize:(DBTEAMLOGNamespaceRelativePathLogInfo *)instance;

///
/// Deserializes `DBTEAMLOGNamespaceRelativePathLogInfo` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBTEAMLOGNamespaceRelativePathLogInfo` API object.
///
/// @return An instantiation of the `DBTEAMLOGNamespaceRelativePathLogInfo`
/// object.
///
+ (DBTEAMLOGNamespaceRelativePathLogInfo *)deserialize:(NSDictionary<NSString *, id> *)dict;

@end

NS_ASSUME_NONNULL_END


text:
/**
 * A web worker that interfaces with the main thread by taking actions,
 * diffing the dom and pushing dom patches to main thread
 */

function diff() {
  const patch = 'derp'
  self.postMessage({
    type: 'patch',
    payload: { patch },
  });
}

self.addEventListener('message', ({ data }) => {
  diff(data)
});


text:
package com.nandemokaki.model;

import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
 * MODEL autogen macro
 * EmailAck
 * @auther KIM
*/
@Entity
@Table(name="EMAIL_ACK")
public class EmailAck implements Serializable {
	public static final String TABLE = "EMAIL_ACK";

	/** 送信番号 */
	@Id
	@Column(name = "SEND_NO")
	public Integer sendNo;

	/** 送信時刻 */
	@Column(name = "SEND_TIME")
	public Timestamp sendTime;

	/** 元JPGファイル名 */
	@Column(name = "MOTO_JPG_NM")
	public String motoJpgNm;

	/** 受信時刻 */
	@Column(name = "RECV_TIME")
	public Timestamp recvTime;

	/** 閲覧回数 */
	@Column(name = "RECV_CNT")
	public Integer recvCnt;

}


text:
require './model/master.rb'
require './helpers/xslt_generation'
require 'openssl'
require 'json'

userx = User.first

# If there are no users, create a first user
if !userx
    puts "No users in the database, creating a first user. \n"

    username = ENV['SRP_ADMIN']
    if (!username)
        puts "Please enter username (default: administrator):  "
        username = gets.chomp
    end
    username = "administrator" if username == ""

    puts "Generating random password and adding the Administrator with username #{username}..."

    password = rand(36**10).to_s(36)

    exists = User.first(:username => username)

    if exists
        puts "That username already exists. Please use reset_pw.rb to reset a password"
    else
        user = User.new
        user.username = username
        user.password = password
        user.type = "Administrator"
        user.auth_type = "Local"
        user.save

        puts "Please use the following login credentials"
        puts "\t \t \t ****  #{username} : #{password} ****"

    end
else
    puts "Skipping username creation (users exist), please use the create_user.rb script to add a user."
end

find_i = true
do_findings = ENV['SRP_FINDINGS']
if (do_findings)
    # Disable Findings via environment variable if set to "n"
    if (do_findings == "n" or do_findings == "no")
        find_i = false
    end
else
    # Otherwise prompt for user input.
    puts "Would you like to initialize the database with templated findings? (Y/n)"
    find_i = gets.chomp
    if (find_i == "" or find_i.downcase == "y" or find_i.downcase == "yes")
        find_i = true
    end
end

if (find_i)
    puts "Importing Templated Findings template_findings.json..."

    file = File.new('./templates/template_findings.json',"rb")
    json = ""
    while(line_j = file.gets)
        json = json + line_j
    end
    line = JSON.parse(json)

    line.each do |j|
        j["id"] = nil

        finding = TemplateFindings.first(:title => j["title"])

        j["approved"] = true
        f = TemplateFindings.first_or_create(j)
        f.save
    end
else
    puts "Skipping templated finding import. Use the UI to import templated findings."
end

# add the Default templates into the DB
templates = Xslt.first

if !templates
    # Add default risk scoring report template  --------------------
    puts "Adding the Default Generic Risk Scoring Report Template"
    xslt_file = "./templates/#{rand(36**36).to_s(36)}.xslt"
    docx = "./templates/Serpico - GenericRiskScoring.docx"

    xslt = generate_xslt(docx)
    if xslt =~ /Error file DNE/
        return "ERROR!!!!!!"
    end

    # open up a file handle and write the attachment
    File.open(xslt_file, 'wb') {|f| f.write(xslt) }

    # delete the file data from the attachment
    datax = Hash.new
    datax["docx_location"] = "#{docx}"
    datax["xslt_location"] = "#{xslt_file}"
    datax["description"] =  "Generic Risk Scoring Report"
    datax["report_type"] = "Default Template - Generic Risk Scoring"
    report = Xslt.new(datax)
    report.save
    # --------------------------------------------------------------

    # Add default DREAD report template ----------------------------
    puts "Adding the Default DREAD Report Template"
    xslt_file = "./templates/#{rand(36**36).to_s(36)}.xslt"
    docx = "./templates/Serpico - Report.docx"

    xslt = generate_xslt(docx)
    if xslt =~ /Error file DNE/
        return "ERROR!!!!!!"
    end

    # open up a file handle and write the attachment
    File.open(xslt_file, 'wb') {|f| f.write(xslt) }

    # delete the file data from the attachment
    datax = Hash.new
    datax["docx_location"] = "#{docx}"
    datax["xslt_location"] = "#{xslt_file}"
    datax["description"] = 	"Default Serpico Report - DREAD Scoring"
    datax["report_type"] = "Default Template - DREAD Scoring"
    report = Xslt.new(datax)
    report.save
    # --------------------------------------------------------------

    # Add default CVSS report template -----------------------------
    puts "Adding the Default CVSS Report Template"
    xslt_file = "./templates/#{rand(36**36).to_s(36)}.xslt"
    docx = "./templates/CVSS_Template.docx"

    xslt = generate_xslt(docx)
    if xslt =~ /Error file DNE/
        return "ERROR!!!!!!"
    end

    # open up a file handle and write the attachment
    File.open(xslt_file, 'wb') {|f| f.write(xslt) }

    # delete the file data from the attachment
    datax = Hash.new
    datax["docx_location"] = "#{docx}"
    datax["xslt_location"] = "#{xslt_file}"
    datax["description"] = 	"Default CVSS Report"
    datax["report_type"] = "Default CVSS Report"
    report = Xslt.new(datax)
    report.save
    # --------------------------------------------------------------

    # Add default CVSS3 report template ----------------------------
    puts "Adding the Default CVSSv3 Report Template"
    xslt_file = "./templates/#{rand(36**36).to_s(36)}.xslt"
    docx = "./templates/Default CVSS 3 Report.docx"

    xslt = generate_xslt(docx)
    if xslt =~ /Error file DNE/
        return "ERROR!!!!!!"
    end

    # open up a file handle and write the attachment
    File.open(xslt_file, 'wb') {|f| f.write(xslt) }

    # delete the file data from the attachment
    datax = Hash.new
    datax["docx_location"] = "#{docx}"
    datax["xslt_location"] = "#{xslt_file}"
    datax["description"] = 	"Default CVSSv3 Report"
    datax["report_type"] = "Default CVSSv3 Report"
    report = Xslt.new(datax)
    report.save
    # --------------------------------------------------------------

    # Add default NIST800 report template --------------------------
    puts "Adding the Serpico Default NIST800 Template"
    #xslt_file = "./templates/#{rand(36**36).to_s(36)}.xslt"
    xslt_file = "./templates/nist800.xslt"
    docx = "./templates/Default NIST800 Report.docx"

    xslt = generate_xslt(docx)
    if xslt =~ /Error file DNE/
        return "ERROR!!!!!!"
    end

    # open up a file handle and write the attachment
    File.open(xslt_file, 'wb') {|f| f.write(xslt) }

    # delete the file data from the attachment
    datax = Hash.new
    datax["docx_location"] = "#{docx}"
    datax["xslt_location"] = "#{xslt_file}"
    datax["description"] = 	"Default NIST800 Report"
    datax["report_type"] = "Default NIST800 Report"
    report = Xslt.new(datax)
    report.save
    # --------------------------------------------------------------

    # Add default Finding template ---------------------------------
    puts "Adding the Serpico Default Finding Template"

    xslt_file = "./templates/#{rand(36**36).to_s(36)}.xslt"
    docx = "./templates/Serpico - Risk Finding.docx"

    xslt = generate_xslt(docx)
    if xslt =~ /Error file DNE/
        return "ERROR!!!!!!"
    end

    # open up a file handle and write the attachment
    File.open(xslt_file, 'wb') {|f| f.write(xslt) }

    datax = Hash.new
    datax["docx_location"] = "#{docx}"
    datax["xslt_location"] = "#{xslt_file}"
    datax["description"] = 	"Default Serpico Finding"
    datax["report_type"] = "Default Finding"
    report = Xslt.new(datax)
    report.save
    # --------------------------------------------------------------

    puts "Adding the Serpico Default Status Template"

    xslt_file = "./templates/#{rand(36**36).to_s(36)}.xslt"
    docx = "./templates/Serpico - Finding.docx"

    xslt = generate_xslt(docx)
    if xslt =~ /Error file DNE/
        return "ERROR!!!!!!"
    end

    # open up a file handle and write the attachment
    File.open(xslt_file, 'wb') {|f| f.write(xslt) }

    # delete the file data from the attachment
    datax = Hash.new
    datax["docx_location"] = "#{docx}"
    datax["xslt_location"] = "#{xslt_file}"
    datax["description"] = 	"Default Serpico Status"
    datax["report_type"] = "Default Status"
    datax["status_template"] = true
    report = Xslt.new(datax)
    report.save
    # --------------------------------------------------------------

else
    puts "Skipping XSLT creation, templates exist."
end

# create the SSL cert
puts "Creating self-signed SSL certificate, you should really have a legitimate one."

name = "/C=US/ST=MD/L=MD/O=MD/CN=serpico"
ca   = OpenSSL::X509::Name.parse(name)
key = OpenSSL::PKey::RSA.new(1024)

crt = OpenSSL::X509::Certificate.new
crt.version = 2
crt.serial  = rand(10**10)
crt.subject = ca
crt.issuer = ca
crt.public_key = key.public_key
crt.not_before = Time.now
crt.not_after  = Time.now + 1 * 365 * 24 * 60 * 60 # 1 year

ef = OpenSSL::X509::ExtensionFactory.new
ef.subject_certificate = crt
ef.issuer_certificate = crt
crt.extensions = [
    ef.create_extension("basicConstraints","CA:TRUE", true),
    ef.create_extension("subjectKeyIdentifier", "hash"),
]
crt.add_extension ef.create_extension("authorityKeyIdentifier",
                                      "keyid:always,issuer:always")
crt.sign key, OpenSSL::Digest::SHA1.new

File.open("./cert.pem", "w") do |f|
    f.write crt.to_pem
end

File.open("./key.pem", "w") do |f|
    f.write key.to_pem
end

# Copying the default configurations over
puts "Copying configuration settings over."
File.open("./config.json", "w") do |f|
    f.write File.open("./config.json.defaults", "rb").read
end


text:
/**
 * @class Ext.sparkline.Discrete
 *
 * Plots a series of thin vertical lines based upon the input {@link #values} array.
 *
 * See {@link Ext.sparkline.Base the base class} for a simple example.
 */
Ext.define('Ext.sparkline.Discrete', {
    extend: 'Ext.sparkline.BarBase',

    alias: 'widget.sparklinediscrete',

    config: {

        /**
         * @cfg {Number} lineHeight Height of each line in pixels - Defaults to 30% of the graph height.
         */
        lineHeight: 'auto',

        /**
         * @cfg {String} thresholdColor Colour to use in combination with {@link #thresholdValue}
         */
        thresholdColor: null,

        /**
         * @cfg {Number} thresholdValue Values less than this value will be drawn using {@link #thresholdColor} instead of lineColor
         */
        thresholdValue: 0,

        /**
         * @cfg {Number} [chartRangeMax] The maximum value to use for the range of Y values of the chart - Defaults to the maximum value supplied.
         */
        chartRangeMax: null,

        /**
         * @cfg {Number} [chartRangeMin] The minimum value to use for the range of Y values of the chart - Defaults to the minimum value supplied.
         */
        chartRangeMin: null,

        /**
         * @cfg {Boolean} chartRangeClip If true then the y values supplied to plot will be clipped to fall
         * between {@link #chartRangeMin} and {@link #chartRangeMax} - By default chartRangeMin/Max just ensure that the chart
         * spans at least that range of values, but does not constrain it.
         */
        chartRangeClip: false,

        tipTpl: new Ext.XTemplate('{prefix}{value}{suffix}')
    },

    // Ensure values is an array of numbers
    applyValues: function(newValues) {
        newValues = Ext.Array.map(Ext.Array.from(newValues), Number);
        this.disabled = !(newValues && newValues.length);
        return newValues;
    },

    onUpdate: function () {
        var me = this,
            values = me.values,
            chartRangeMin = me.getChartRangeMin(),
            chartRangeMax = me.getChartRangeMax(),
            chartRangeClip = me.getChartRangeClip();

        me.callParent(arguments);

        me.regionShapes = {};
        me.min = Math.min.apply(Math, values);
        me.max = Math.max.apply(Math, values);
        me.range = me.max - me.min;
        me.width = me.getWidth();
        me.interval = Math.floor(me.width / values.length);
        me.itemWidth = me.width / values.length;
        if (chartRangeMin != null && (chartRangeClip || chartRangeMin < me.min)) {
            me.min = chartRangeMin;
        }
        if (chartRangeMax != null && (chartRangeClip || chartRangeMax > me.max)) {
            me.max = chartRangeMax;
        }
        if (me.canvas) {
            if (me.getLineHeight() === 'auto') {
                me.setLineHeight(Math.round(me.getHeight() * 0.3));
            }
        }
    },

    getRegion: function (x, y) {
        return Math.floor(x / this.itemWidth);
    },

    getRegionFields: function (region) {
        return {
            isNull: this.values[region] === undefined,
            value: this.values[region],
            offset: region
        };
    },

    renderRegion: function (valuenum, highlight) {
        var me = this,
            values = me.values,
            min = me.min,
            max = me.max,
            range = me.range,
            interval = me.interval,
            canvas = me.canvas,
            canvasHeight = me.getHeight(),
            lineHeight = me.getLineHeight(),
            pheight = canvasHeight - lineHeight,
            ytop, val, color, x,
            thresholdColor = me.getThresholdColor();

        val = Ext.Number.constrain(values[valuenum], min, max);
        x = valuenum * interval;
        ytop = Math.round(pheight - pheight * ((val - min) / range));
        color = (thresholdColor && val < me.getThresholdValue()) ? thresholdColor : me.getLineColor();
        if (highlight) {
            color = me.calcHighlightColor(color);
        }
        canvas.drawLine(x, ytop, x, ytop + lineHeight, color).append();
    }
});


text:
package client

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/gunsluo/go-example/opentracing/pkg/internal"
	"github.com/gunsluo/go-example/opentracing/pkg/trace"
	"github.com/opentracing/opentracing-go"
	"github.com/sirupsen/logrus"
)

// AccountClient is a remote client that implements customer.Interface
type AccountClient struct {
	logger     logrus.FieldLogger
	accountURL string
	client     *http.Client
	//tracer   opentracing.Tracer
	//client   *tracing.HTTPAccountClient
}

// NewAccountClient creates a new customer.AccountClient
func NewAccountClient(tracer opentracing.Tracer, logger logrus.FieldLogger, accountURL string) *AccountClient {
	return &AccountClient{
		logger: logger,
		client: &http.Client{
			Transport: trace.NewTransport(tracer,
				trace.TransportComponentName("Customer Client"))},
		accountURL: accountURL,
	}
}

// Get implements customer.Interface#Get as an RPC
func (c *AccountClient) GetAccount(ctx context.Context, id string) (*internal.Account, error) {
	c.logger.WithField("account id", id).Info("Getting customer")

	url := fmt.Sprintf(c.accountURL+"/account?id=%s", id)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	// important
	req = req.WithContext(ctx)

	res, err := c.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	if res.StatusCode != http.StatusOK {
		body, err := ioutil.ReadAll(res.Body)
		if err != nil {
			return nil, err
		}
		return nil, errors.New(string(body))
	}

	var a internal.Account
	decoder := json.NewDecoder(res.Body)
	err = decoder.Decode(&a)
	if err != nil {
		return nil, err
	}

	return &a, nil
}


text:
UPDATE csm_application SET DECLARATIVE_FLAG='0';

ALTER TABLE CSM_PROTECTION_ELEMENT DROP COLUMN PROTECTION_ELEMENT_TYPE_ID;
ALTER TABLE CSM_PROTECTION_ELEMENT ADD COLUMN PROTECTION_ELEMENT_TYPE VARCHAR(100);
ALTER TABLE CSM_PG_PE alter COLUMN UPDATE_DATE type date;
ALTER TABLE CSM_APPLICATION alter COLUMN APPLICATION_NAME type VARCHAR(255);
ALTER TABLE CSM_APPLICATION alter COLUMN APPLICATION_NAME set  NOT NULL;
ALTER TABLE CSM_GROUP alter COLUMN GROUP_NAME type VARCHAR(255);
ALTER TABLE CSM_GROUP alter COLUMN GROUP_NAME set NOT NULL;
ALTER TABLE CSM_PROTECTION_ELEMENT ADD constraint  UQ_PE_OBJECT_ID_ATTRIBUTE_APP_ID UNIQUE(PROTECTION_ELEMENT_NAME, ATTRIBUTE, APPLICATION_ID);

ALTER TABLE CSM_APPLICATION ADD COLUMN DATABASE_URL VARCHAR(100);
ALTER TABLE CSM_APPLICATION ADD COLUMN DATABASE_USER_NAME VARCHAR(100);
ALTER TABLE CSM_APPLICATION ADD COLUMN DATABASE_PASSWORD VARCHAR(100);
ALTER TABLE CSM_APPLICATION ADD COLUMN DATABASE_DIALECT VARCHAR(100);
ALTER TABLE CSM_APPLICATION ADD COLUMN DATABASE_DRIVER VARCHAR(100);

UPDATE csm_pg_pe SET UPDATE_DATE=NULL;


text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;

namespace Microsoft.Azure.Management.Sql
{
    /// <summary>
    /// The Windows Azure SQL Database management API provides a RESTful set of
    /// web services that interact with Windows Azure SQL Database services to
    /// manage your databases. The API enables users to create, retrieve,
    /// update, and delete databases and servers.
    /// </summary>
    public static partial class ServerUpgradeOperationsExtensions
    {
        /// <summary>
        /// Cancel a pending upgrade for the Azure SQL Database server.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.Sql.IServerUpgradeOperations.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Required. The name of the Resource Group to which the server
        /// belongs.
        /// </param>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server to cancel
        /// upgrade.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public static AzureOperationResponse Cancel(this IServerUpgradeOperations operations, string resourceGroupName, string serverName)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IServerUpgradeOperations)s).CancelAsync(resourceGroupName, serverName);
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <summary>
        /// Cancel a pending upgrade for the Azure SQL Database server.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.Sql.IServerUpgradeOperations.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Required. The name of the Resource Group to which the server
        /// belongs.
        /// </param>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server to cancel
        /// upgrade.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public static Task<AzureOperationResponse> CancelAsync(this IServerUpgradeOperations operations, string resourceGroupName, string serverName)
        {
            return operations.CancelAsync(resourceGroupName, serverName, CancellationToken.None);
        }

        /// <summary>
        /// Returns information about Upgrade status of an Azure SQL Database
        /// Server.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.Sql.IServerUpgradeOperations.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Required. The name of the Resource Group to which the server
        /// belongs.
        /// </param>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server to upgrade.
        /// </param>
        /// <returns>
        /// Represents the response to a Get request for Upgrade status of an
        /// Azure SQL Database Server.
        /// </returns>
        public static ServerUpgradeGetResponse Get(this IServerUpgradeOperations operations, string resourceGroupName, string serverName)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IServerUpgradeOperations)s).GetAsync(resourceGroupName, serverName);
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <summary>
        /// Returns information about Upgrade status of an Azure SQL Database
        /// Server.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.Sql.IServerUpgradeOperations.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Required. The name of the Resource Group to which the server
        /// belongs.
        /// </param>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server to upgrade.
        /// </param>
        /// <returns>
        /// Represents the response to a Get request for Upgrade status of an
        /// Azure SQL Database Server.
        /// </returns>
        public static Task<ServerUpgradeGetResponse> GetAsync(this IServerUpgradeOperations operations, string resourceGroupName, string serverName)
        {
            return operations.GetAsync(resourceGroupName, serverName, CancellationToken.None);
        }

        /// <summary>
        /// Start an Azure SQL Database Server Upgrade.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.Sql.IServerUpgradeOperations.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Required. The name of the Resource Group to which the server
        /// belongs.
        /// </param>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server to upgrade.
        /// </param>
        /// <param name='parameters'>
        /// Required. The required parameters for the Azure SQL Database Server
        /// Upgrade.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public static AzureOperationResponse Start(this IServerUpgradeOperations operations, string resourceGroupName, string serverName, ServerUpgradeStartParameters parameters)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IServerUpgradeOperations)s).StartAsync(resourceGroupName, serverName, parameters);
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <summary>
        /// Start an Azure SQL Database Server Upgrade.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.Sql.IServerUpgradeOperations.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Required. The name of the Resource Group to which the server
        /// belongs.
        /// </param>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server to upgrade.
        /// </param>
        /// <param name='parameters'>
        /// Required. The required parameters for the Azure SQL Database Server
        /// Upgrade.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public static Task<AzureOperationResponse> StartAsync(this IServerUpgradeOperations operations, string resourceGroupName, string serverName, ServerUpgradeStartParameters parameters)
        {
            return operations.StartAsync(resourceGroupName, serverName, parameters, CancellationToken.None);
        }
    }
}


text:
<?php defined('SYSPATH') OR die('No direct script access.');

abstract class Core_Breadcrumbs {

	/**
	 * @var  string  Filename of View template
	 */
	protected static $_template = 'breadcrumbs/default';

	/**
	 * @var  array  Breadcrumb items as URI => name
	 */
	protected static $_items = array();

	/**
	 * Sets(add) breadcrumbs
	 *
	 * @param   mixed   $uri    Item URI or array of items
	 * @param   string  $title  Item title
	 * @return  void
	 */
	public static function set($uri, $title = NULL)
	{
		if (is_array($uri))
		{
			self::$_items += $uri;
		}
		else
		{
			self::$_items[$uri] = $title;
		}
	}

	/**
	 * Generate (uses controller data) and add items
	 *
	 * @param   Controller  $controller
	 * @return  void
	 * @uses    Controller
	 * @uses    Route
	 * @uses    Request
	 * @uses    Inflector
	 */
	public static function set_auto(Controller $controller)
	{
		$request  = $controller->request;
		$route    = $request->route();
		$defaults = $route->defaults();

		$default_action = isset($defaults['action']) ? $defaults['action'] : Route::$default_action;
		$default_action_exist = method_exists($controller, 'action_'.$default_action);

		$title = Inflector::decamelize($request->directory().' '.$request->controller());

		// Set controller item
		if ($default_action_exist)
		{
			$uri = $route->uri(array(
				'directory'  => $request->directory(),
				'controller' => $request->controller(),
				'action'     => $default_action,
			));
			self::set($uri, $title);
		}
		else
		{
			self::set($request->uri(), $title);
		}
		/**
		 * Set action item. Not add default action:
		 * action_index: `Articles`, action_edit: `Articles / Edit`
		 */
		if ($request->action() != $default_action)
		{
			$title = Inflector::humanize($request->action());
			self::set($request->uri(), $title);
		}
	}

	/**
	 * Gets breadcrumbs
	 *
	 * @param   string  $key
	 * @return  mixed
	 */
	public static function get($key = NULL)
	{
		if (empty($key))
		{
			return self::$_items;
		}
		elseif (isset(self::$_items[$key]))
		{
			return array($key, self::$_items[$key]);
		}
	}

	/**
	 * Gets or sets default View template name
	 *
	 * @param   string  $name
	 * @return  mixed
	 */
	public static function template($name = NULL)
	{
		if (empty($name))
		{
			return self::$_template;
		}
		self::$_template = (string) $name;
	}

} // End Breadcrumbs


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

import static com.jayway.restassured.RestAssured.expect;
import static com.jayway.restassured.RestAssured.given;
import static com.jayway.restassured.path.json.JsonPath.from;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ws.rs.core.Response.Status;
import javax.xml.registry.InvalidRequestException;

import org.camunda.bpm.engine.history.HistoricDetail;
import org.camunda.bpm.engine.history.HistoricDetailQuery;
import org.camunda.bpm.engine.history.HistoricFormField;
import org.camunda.bpm.engine.history.HistoricVariableUpdate;
import org.camunda.bpm.engine.impl.calendar.DateTimeUtil;
import org.camunda.bpm.engine.rest.AbstractRestServiceTest;
import org.camunda.bpm.engine.rest.helper.MockHistoricVariableUpdateBuilder;
import org.camunda.bpm.engine.rest.helper.MockProvider;
import org.camunda.bpm.engine.rest.helper.VariableTypeHelper;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.engine.variable.type.SerializableValueType;
import org.camunda.bpm.engine.variable.type.ValueType;
import org.camunda.bpm.engine.variable.value.ObjectValue;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;

import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;

/**
 * @author Roman Smirnov
 *
 */
public abstract class AbstractHistoricDetailRestServiceQueryTest extends AbstractRestServiceTest {

  protected static final String HISTORIC_DETAIL_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/detail";

  protected static final String HISTORIC_DETAIL_COUNT_RESOURCE_URL = HISTORIC_DETAIL_RESOURCE_URL + "/count";

  protected HistoricDetailQuery mockedQuery;

  protected HistoricVariableUpdate historicUpdateMock;
  protected MockHistoricVariableUpdateBuilder historicUpdateBuilder;

  protected HistoricFormField historicFormFieldMock;

  @Before
  public void setUpRuntimeData() {
    List<HistoricDetail> details = new ArrayList<HistoricDetail>();

    historicUpdateBuilder = MockProvider.mockHistoricVariableUpdate();
    historicUpdateMock = historicUpdateBuilder.build();
    historicFormFieldMock = MockProvider.createMockHistoricFormField();

    details.add(historicUpdateMock);
    details.add(historicFormFieldMock);

    mockedQuery = setUpMockedDetailsQuery(details);
  }

  protected HistoricDetailQuery setUpMockedDetailsQuery(List<HistoricDetail> detailMocks) {
    HistoricDetailQuery mock = mock(HistoricDetailQuery.class);
    when(mock.list()).thenReturn(detailMocks);
    when(mock.count()).thenReturn((long) detailMocks.size());

    when(processEngine.getHistoryService().createHistoricDetailQuery()).thenReturn(mock);
    return mock;
  }

  @Test
  public void testEmptyQuery() {
    String queryKey = "";
    given()
      .queryParam("processInstanceId", queryKey)
    .then()
      .expect()
        .statusCode(Status.OK.getStatusCode())
      .when()
        .get(HISTORIC_DETAIL_RESOURCE_URL);
  }

  @Test
  public void testNoParametersQuery() {
    expect()
      .statusCode(Status.OK.getStatusCode())
    .when()
      .get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).list();
    verify(mockedQuery).disableBinaryFetching();
    verifyNoMoreInteractions(mockedQuery);
  }

  @Test
  public void testNoParametersQueryDisableObjectDeserialization() {
    given()
      .queryParam("deserializeValues", false)
    .expect()
      .statusCode(Status.OK.getStatusCode())
    .when()
      .get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).list();
    verify(mockedQuery).disableBinaryFetching();
    verify(mockedQuery).disableCustomObjectDeserialization();
    verifyNoMoreInteractions(mockedQuery);
  }

  @Test
  public void testInvalidSortingOptions() {
    executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST);
    executeAndVerifySorting("processInstanceId", "anInvalidSortOrderOption", Status.BAD_REQUEST);
  }

  protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) {
    given()
      .queryParam("sortBy", sortBy)
      .queryParam("sortOrder", sortOrder)
    .then()
      .expect()
        .statusCode(expectedStatus.getStatusCode())
      .when()
        .get(HISTORIC_DETAIL_RESOURCE_URL);
  }

  @Test
  public void testSortOrderParameterOnly() {
    given()
    .queryParam("sortOrder", "asc")
  .then()
    .expect()
      .statusCode(Status.BAD_REQUEST.getStatusCode())
      .contentType(ContentType.JSON)
      .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
      .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required"))
    .when()
      .get(HISTORIC_DETAIL_RESOURCE_URL);
  }

  @Test
  public void testSortingParameters() {
    InOrder inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("processInstanceId", "asc", Status.OK);
    inOrder.verify(mockedQuery).orderByProcessInstanceId();
    inOrder.verify(mockedQuery).asc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("processInstanceId", "desc", Status.OK);
    inOrder.verify(mockedQuery).orderByProcessInstanceId();
    inOrder.verify(mockedQuery).desc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("variableName", "asc", Status.OK);
    inOrder.verify(mockedQuery).orderByVariableName();
    inOrder.verify(mockedQuery).asc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("variableName", "desc", Status.OK);
    inOrder.verify(mockedQuery).orderByVariableName();
    inOrder.verify(mockedQuery).desc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("formPropertyId", "asc", Status.OK);
    inOrder.verify(mockedQuery).orderByFormPropertyId();
    inOrder.verify(mockedQuery).asc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("formPropertyId", "desc", Status.OK);
    inOrder.verify(mockedQuery).orderByFormPropertyId();
    inOrder.verify(mockedQuery).desc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("variableType", "asc", Status.OK);
    inOrder.verify(mockedQuery).orderByVariableType();
    inOrder.verify(mockedQuery).asc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("variableType", "desc", Status.OK);
    inOrder.verify(mockedQuery).orderByVariableType();
    inOrder.verify(mockedQuery).desc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("variableRevision", "asc", Status.OK);
    inOrder.verify(mockedQuery).orderByVariableRevision();
    inOrder.verify(mockedQuery).asc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("variableRevision", "desc", Status.OK);
    inOrder.verify(mockedQuery).orderByVariableRevision();
    inOrder.verify(mockedQuery).desc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("time", "asc", Status.OK);
    inOrder.verify(mockedQuery).orderByTime();
    inOrder.verify(mockedQuery).asc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("time", "desc", Status.OK);
    inOrder.verify(mockedQuery).orderByTime();
    inOrder.verify(mockedQuery).desc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("occurrence", "asc", Status.OK);
    inOrder.verify(mockedQuery).orderPartiallyByOccurrence();
    inOrder.verify(mockedQuery).asc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("occurrence", "desc", Status.OK);
    inOrder.verify(mockedQuery).orderPartiallyByOccurrence();
    inOrder.verify(mockedQuery).desc();
  }

  @Test
  public void testSuccessfulPagination() {
    int firstResult = 0;
    int maxResults = 10;

    given()
      .queryParam("firstResult", firstResult)
      .queryParam("maxResults", maxResults)
    .then()
      .expect()
        .statusCode(Status.OK.getStatusCode())
      .when()
        .get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).listPage(firstResult, maxResults);
  }

  @Test
  public void testMissingFirstResultParameter() {
    int maxResults = 10;

    given()
      .queryParam("maxResults", maxResults)
    .then()
      .expect()
        .statusCode(Status.OK.getStatusCode())
      .when()
        .get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).listPage(0, maxResults);
  }

  @Test
  public void testMissingMaxResultsParameter() {
    int firstResult = 10;

    given()
      .queryParam("firstResult", firstResult)
    .then()
      .expect()
        .statusCode(Status.OK.getStatusCode())
      .when()
        .get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE);
  }

  @Test
  public void testQueryCount() {
    expect()
      .statusCode(Status.OK.getStatusCode())
      .body("count", equalTo(2))
    .when()
      .get(HISTORIC_DETAIL_COUNT_RESOURCE_URL);

    verify(mockedQuery).count();
  }

  @Test
  public void testSimpleHistoricActivityQuery() {
    Response response = given()
      .then()
        .expect()
          .statusCode(Status.OK.getStatusCode())
        .and()
          .body("[0].id", equalTo(historicUpdateBuilder.getId()))
          .body("[0].variableName", equalTo(historicUpdateBuilder.getName()))
          .body("[0].variableInstanceId", equalTo(historicUpdateBuilder.getVariableInstanceId()))
          .body("[0].variableType", equalTo(VariableTypeHelper.toExpectedValueTypeName(
              historicUpdateBuilder.getTypedValue().getType())))
          .body("[0].value", equalTo(historicUpdateBuilder.getTypedValue().getValue()))
          .body("[0].processDefinitionKey", equalTo(historicUpdateBuilder.getProcessDefinitionKey()))
          .body("[0].processDefinitionId", equalTo(historicUpdateBuilder.getProcessDefinitionId()))
          .body("[0].processInstanceId", equalTo(historicUpdateBuilder.getProcessInstanceId()))
          .body("[0].errorMessage", equalTo(historicUpdateBuilder.getErrorMessage()))
          .body("[0].activityInstanceId", equalTo(historicUpdateBuilder.getActivityInstanceId()))
          .body("[0].revision", equalTo(historicUpdateBuilder.getRevision()))
          .body("[0].time", equalTo(historicUpdateBuilder.getTime()))
          .body("[0].taskId", equalTo(historicUpdateBuilder.getTaskId()))
          .body("[0].executionId", equalTo(historicUpdateBuilder.getExecutionId()))
          .body("[0].type", equalTo("variableUpdate"))
          .body("[0].caseDefinitionKey", equalTo(historicUpdateBuilder.getCaseDefinitionKey()))
          .body("[0].caseDefinitionId", equalTo(historicUpdateBuilder.getCaseDefinitionId()))
          .body("[0].caseInstanceId", equalTo(historicUpdateBuilder.getCaseInstanceId()))
          .body("[0].caseExecutionId", equalTo(historicUpdateBuilder.getCaseExecutionId()))
        .when()
          .get(HISTORIC_DETAIL_RESOURCE_URL);

    InOrder inOrder = inOrder(mockedQuery);
    inOrder.verify(mockedQuery).list();

    String content = response.asString();
    List<String> details = from(content).getList("");
    Assert.assertEquals("There should be two activity instance returned.", 2, details.size());
    Assert.assertNotNull("The returned details should not be null.", details.get(0));
    Assert.assertNotNull("The returned details should not be null.", details.get(1));

    // note: element [0] is asserted as part of the fluent rest-assured invocation

    String returnedId2 = from(content).getString("[1].id");
    String returnedProcessDefinitionKey2 = from(content).getString("[1].processDefinitionKey");
    String returnedProcessDefinitionId2 = from(content).getString("[1].processDefinitionId");
    String returnedProcessInstanceId2 = from(content).getString("[1].processInstanceId");
    String returnedActivityInstanceId2 = from(content).getString("[1].activityInstanceId");
    String returnedExecutionId2 = from(content).getString("[1].executionId");
    String returnedTaskId2 = from(content).getString("[1].taskId");
    Date returnedTime2 = DateTimeUtil.parseDate(from(content).getString("[1].time"));
    String returnedFieldId = from(content).getString("[1].fieldId");
    String returnedFieldValue = from(content).getString("[1].fieldValue");
    String returnedType = from(content).getString("[1].type");
    String returnedCaseDefinitionKey2 = from(content).getString("[1].caseDefinitionKey");
    String returnedCaseDefinitionId2 = from(content).getString("[1].caseDefinitionId");
    String returnedCaseInstanceId2 = from(content).getString("[1].caseInstanceId");
    String returnedCaseExecutionId2 = from(content).getString("[1].caseExecutionId");

    Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_ID, returnedId2);
    Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_PROC_DEF_KEY, returnedProcessDefinitionKey2);
    Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_PROC_DEF_ID, returnedProcessDefinitionId2);
    Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_PROC_INST_ID, returnedProcessInstanceId2);
    Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_ACT_INST_ID, returnedActivityInstanceId2);
    Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_EXEC_ID, returnedExecutionId2);
    Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_TASK_ID, returnedTaskId2);
    Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_TIME), returnedTime2);
    Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_FIELD_ID, returnedFieldId);
    Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_VALUE, returnedFieldValue);
    Assert.assertEquals("formField", returnedType);
    Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_CASE_DEF_ID, returnedCaseDefinitionId2);
    Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_CASE_DEF_KEY, returnedCaseDefinitionKey2);
    Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_CASE_INST_ID, returnedCaseInstanceId2);
    Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_CASE_EXEC_ID, returnedCaseExecutionId2);

  }

  @Test
  public void testSerializableVariableInstanceRetrieval() {
    ObjectValue serializedValue = Variables.serializedObjectValue("a serialized value").create();
    MockHistoricVariableUpdateBuilder builder = MockProvider.mockHistoricVariableUpdate()
        .typedValue(serializedValue);

    List<HistoricDetail> details = new ArrayList<HistoricDetail>();
    details.add(builder.build());

    mockedQuery = setUpMockedDetailsQuery(details);

    given()
        .then().expect().statusCode(Status.OK.getStatusCode())
        .and()
          .body("[0].value", equalTo("a serialized value"))
          .body("[0].variableType", equalTo(VariableTypeHelper.toExpectedValueTypeName(serializedValue.getType())))
          .body("[0].errorMessage", nullValue())
        .when().get(HISTORIC_DETAIL_RESOURCE_URL);

    // should not resolve custom objects but existing API requires it
//  verify(mockedQuery).disableCustomObjectDeserialization();
    verify(mockedQuery, never()).disableCustomObjectDeserialization();
  }

  @Test
  public void testSpinVariableInstanceRetrieval() {
    MockHistoricVariableUpdateBuilder builder = MockProvider.mockHistoricVariableUpdate()
        .typedValue(Variables
            .serializedObjectValue("aSerializedValue")
            .serializationDataFormat("aDataFormat")
            .objectTypeName("aRootType")
            .create());

    List<HistoricDetail> details = new ArrayList<HistoricDetail>();
    details.add(builder.build());

    mockedQuery = setUpMockedDetailsQuery(details);

    given()
        .then().expect().statusCode(Status.OK.getStatusCode())
        .and()
          .body("[0].variableType", equalTo(VariableTypeHelper.toExpectedValueTypeName(ValueType.OBJECT)))
          .body("[0].errorMessage", nullValue())
          .body("[0].value", equalTo("aSerializedValue"))
          .body("[0].valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME,
              equalTo("aRootType"))
          .body("[0].valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT,
              equalTo("aDataFormat"))
        .when().get(HISTORIC_DETAIL_RESOURCE_URL);
  }

  @Test
  public void testQueryByProcessInstanceId() {
    String processInstanceId = MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_PROC_INST_ID;
    given()
      .queryParam("processInstanceId", processInstanceId)
      .then().expect().statusCode(Status.OK.getStatusCode())
      .when().get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).processInstanceId(processInstanceId);
  }

  @Test
  public void testQueryByExecutionId() {
    String executionId = MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_EXEC_ID;
    given()
      .queryParam("executionId", executionId)
      .then().expect().statusCode(Status.OK.getStatusCode())
      .when().get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).executionId(executionId);
  }

  @Test
  public void testQueryByActivityInstanceId() {
    String activityInstanceId = MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_ACT_INST_ID;
    given()
      .queryParam("activityInstanceId", activityInstanceId)
      .then().expect().statusCode(Status.OK.getStatusCode())
      .when().get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).activityInstanceId(activityInstanceId);
  }

  @Test
  public void testQueryByTaskId() {
    String taskId = MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_TASK_ID;
    given()
      .queryParam("taskId", taskId)
      .then().expect().statusCode(Status.OK.getStatusCode())
      .when().get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).taskId(taskId);
  }

  @Test
  public void testQueryByVariableInstanceId() {
    String variableInstanceId = MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_ID;
    given()
      .queryParam("variableInstanceId", variableInstanceId)
      .then().expect().statusCode(Status.OK.getStatusCode())
      .when().get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).variableInstanceId(variableInstanceId);
  }

  @Test
  public void testQueryByFormFields() {
    given()
      .queryParam("formFields", "true")
      .then().expect().statusCode(Status.OK.getStatusCode())
      .when().get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).formFields();
  }

  @Test
  public void testQueryByVariableUpdates() {
    given()
      .queryParam("variableUpdates", "true")
      .then().expect().statusCode(Status.OK.getStatusCode())
      .when().get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).variableUpdates();
  }

  @Test
  public void testQueryByExcludeTaskDetails() {
    given()
      .queryParam("excludeTaskDetails", "true")
      .then().expect().statusCode(Status.OK.getStatusCode())
      .when().get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).excludeTaskDetails();
  }

  @Test
  public void testQueryByCaseInstanceId() {
    given()
      .queryParam("caseInstanceId", MockProvider.EXAMPLE_CASE_INSTANCE_ID)
    .then().expect()
      .statusCode(Status.OK.getStatusCode())
    .when()
      .get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).caseInstanceId(MockProvider.EXAMPLE_CASE_INSTANCE_ID);
  }

  @Test
  public void testQueryByCaseExecutionId() {
    given()
      .queryParam("caseExecutionId", MockProvider.EXAMPLE_CASE_EXECUTION_ID)
    .then().expect()
      .statusCode(Status.OK.getStatusCode())
    .when()
      .get(HISTORIC_DETAIL_RESOURCE_URL);

    verify(mockedQuery).caseExecutionId(MockProvider.EXAMPLE_CASE_EXECUTION_ID);
  }

}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

$lang['wysiwyg.meta.width'] = 'Breite';
$lang['wysiwyg.meta.height'] = 'Höhe';
$lang['wysiwyg.meta.size'] = 'Größe';
$lang['wysiwyg.label.insert_width'] = 'Bildbreite eintragen:';
$lang['wysiwyg.label.no_limit'] = 'Volle Grösse';
$lang['wysiwyg.label.float'] = 'Ausrichtung';
$lang['wysiwyg.label.left'] = 'Links';
$lang['wysiwyg.label.right'] = 'Rechts';
$lang['wysiwyg.label.none'] = 'Nichts';
$lang['wysiwyg.meta.mime'] = 'Mime Typ';


text:
require 'spec_helper'

class DummyShippingCalculator < Spree::ShippingCalculator
end

describe Spree::ShippingMethod do
  let(:shipping_method){ create(:shipping_method) }

  context 'calculators' do
    it "Should reject calculators that don't inherit from Spree::ShippingCalculator" do
      Spree::ShippingMethod.stub_chain(:spree_calculators, :shipping_methods).and_return([
        Spree::Calculator::Shipping::FlatPercentItemTotal,
        Spree::Calculator::Shipping::PriceSack,
        Spree::Calculator::DefaultTax,
        DummyShippingCalculator # included as regression test for https://github.com/spree/spree/issues/3109
      ])

      Spree::ShippingMethod.calculators.should == [Spree::Calculator::Shipping::FlatPercentItemTotal, Spree::Calculator::Shipping::PriceSack, DummyShippingCalculator ]
      Spree::ShippingMethod.calculators.should_not == [Spree::Calculator::DefaultTax]
    end
  end

  context "validations" do
    before { subject.valid? }

    it "validates presence of name" do
      subject.should have(1).error_on(:name)
    end

    context "shipping category" do
      it "validates presence of at least one" do
        subject.should have(1).error_on(:base)
      end

      context "one associated" do
        before { subject.shipping_categories.push create(:shipping_category) }
        it { subject.should have(0).error_on(:base) }
      end
    end
  end

  context 'factory' do
    it "should set calculable correctly" do
      shipping_method.calculator.calculable.should == shipping_method
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context="cn.hadcn.simplecalendar.MainActivity">
    <Button
        android:id="@+id/main_normal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Normal Calendar"/>
    <Button
        android:id="@+id/main_dialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Dialog Calendar"/>
</LinearLayout>


text:
require 'fpm/cookery/exceptions'

module FPM
  module Cookery
    module Package
      class Package
        attr_reader :recipe, :config, :fpm

        def initialize(recipe, config = {})
          @recipe = recipe
          @config = config
          @fpm = fpm_object

          @fpm.name = recipe.name
          @fpm.url = recipe.homepage
          @fpm.category = recipe.section || 'optional'
          @fpm.description = recipe.description.strip if recipe.description
          @fpm.architecture = recipe.arch.to_s if recipe.arch

          @fpm.dependencies += recipe.depends
          @fpm.conflicts += recipe.conflicts
          @fpm.provides += recipe.provides
          @fpm.replaces += recipe.replaces
          @fpm.config_files += recipe.config_files
          @fpm.directories += recipe.directories

          @fpm.attributes[:deb_compression] = 'gz'
          @fpm.attributes[:deb_user] = 'root'
          @fpm.attributes[:deb_group] = 'root'
          @fpm.attributes[:rpm_compression] = 'gzip'
          @fpm.attributes[:rpm_digest] = 'md5'
          @fpm.attributes[:rpm_user] = 'root'
          @fpm.attributes[:rpm_group] = 'root'
          @fpm.attributes[:rpm_defattrfile] = '-'
          @fpm.attributes[:rpm_defattrdir] = '-'
          @fpm.attributes[:excludes] = recipe.exclude

          # Package type specific code should be called in package_setup.
          package_setup

          # combine recipe specific fpm attributes. here allows to
          # overwrite the values from package_setup().
          @fpm.attributes.merge!(recipe.fpm_attributes)

          # The input for the FPM package will be set here.
          package_input

          # The call to input() overwrites the license and vendor attributes.
          # XXX Needs to be fixed in fpm/package/dir.rb.
          fpm.license = recipe.license if recipe.license
        end

        def fpm_object
          # Has to be overwritten in a subclass.
          raise Error::MethodNotImplemented, "The #fpm_object method has not been implemented in #{self.class}"
        end

        def package_setup
          # Can be overwritten in a subclass.
        end

        def package_input
          # Has to be overwritten in a subclass.
          raise Error::MethodNotImplemented, "The #package_input method has not been implemented in #{self.class}"
        end

        def convert(output_class)
          fpm.convert(output_class)
        end

        def cleanup
          fpm.cleanup
        end

        def add_script(type, content)
          case type.to_sym
          when :pre_install
            fpm.scripts[:before_install] = content
          when :post_install
            fpm.scripts[:after_install] = content
          when :pre_uninstall
            fpm.scripts[:before_remove] = content
          when :post_uninstall
            fpm.scripts[:after_remove] = content
          end
        end

        # XXX should go away and set in initializer
        def version=(version)
          fpm.version = version.version
          fpm.iteration = version.revision
          fpm.vendor = version.vendor
        end

        def maintainer=(value)
          fpm.maintainer = value
        end

        def vendor=(value)
          fpm.vendor = value
        end

        def epoch=(value)
          fpm.epoch = value
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Please enter language data in the fields below.  All data should be entered in English -->
<ldml xmlns:sil="urn://www.sil.org/ldml/0.1">
	<identity>
		<version number="0.0.1"/>
		<!-- name.en(mzp)="Movima" -->
		<language type="mzp"/>
		<special>
			<sil:identity defaultRegion="BO" script="Latn"/>
		</special>
	</identity>
	<localeDisplayNames>
		<languages>
			<language type="mzp">Chosineɬ diꞌ mowi:maj</language>
		</languages>
		<special>
			<sil:names>
				<sil:name xml:lang="en">Movima</sil:name>
			</sil:names>
		</special>
	</localeDisplayNames>
	<characters>
		<exemplarCharacters>[ꞌ a b c {ch} d e {hu} i j l ƚ m {m̍} n {n̍} o p {qu} r s t u v y]</exemplarCharacters>
		<exemplarCharacters type="auxiliary">[f g h k q w x z]</exemplarCharacters>
	</characters>
	<special>
		<sil:external-resources>
			<sil:font name="Charis SIL" types="default">
				<sil:url>https://wirl.api.sil.org/CharisSILReg&type=ttf</sil:url>
			</sil:font>
			<sil:font name="Noto Sans"><!--types="ui"-->
				<sil:url>https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSans/NotoSans-Regular.ttf</sil:url>
			</sil:font>
			<sil:font name="Noto Serif">
				<sil:url>https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Regular.ttf</sil:url>
			</sil:font>
		</sil:external-resources>
	</special>
</ldml>