text:
require 'openssl'

module Certs
  def cert(name)
    OpenSSL::X509::Certificate.new load "#{name}.crt"
  end

  def crl(name)
    OpenSSL::X509::CRL.new load "#{name}.crl"
  end

  private
  def load(filename)
    path = File.join(File.dirname(__FILE__), 'ca', filename)
    File.read path
  end
end

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function addMoreRegister(headerId, courseId) {
    var firtName = $("#moreFirstName_1").val();
    var lastName = $("#moreLastName_1").val();
    var email = $("#moreUserEmail_1").val();
    var phone = $("#phone_number_1").val();
    var addressForReceipt = $("#addressForReceipt").val();
    var addressForContact = $("#addressForContact").val();
    var isSameAddress = "";
    if ($("#isSameAddress").is(":checked")) {
        isSameAddress = "true";
    } else {
        isSameAddress = "false";
    }
    if (firtName == "" && lastName == "" && phone == "" && !validatePhone(phone) && email == "" && !validateEmail(email)) {
        showWarningNotficationDialog("
กรุณาระบุ ชื่อ สกุล ของผู้สมัครท่านอื่น

กรุณาระบุ เบอร์โทรศัพท์ ให้ถูกต้อง (กรุณาระบุเป็นตัวเลขเท่านั้น)

กรุณาระบุ อีเมล ให้ถูกต้อง
");
        $('html,body').animate({
            scrollTop: $("#loadMoreUser").offset().top
        });
    } else if (firtName == "") {
        showWarningNotficationDialog("กรุณาระบุ ชื่อ");
        $('html,body').animate({
            scrollTop: $("#loadMoreUser").offset().top
        });
    } else if (lastName == "") {
        showWarningNotficationDialog("กรุณาระบุ สกุล");
        $('html,body').animate({
            scrollTop: $("#moreFirstName_1").offset().top
        });
    } else if (phone == "" || !validatePhone(phone)) {
        showWarningNotficationDialog("กรุณาระบุ เบอร์โทรศัพท์ ให้ถูกต้อง (กรุณาระบุเป็นตัวเลขเท่านั้น)");
        $('html,body').animate({
            scrollTop: $("#moreLastName_1").offset().top
        });
    } else if (email == "" || !validateEmail(email)) {
        showWarningNotficationDialog("กรุณาระบุ อีเมล ให้ถูกต้อง");
        $('html,body').animate({
            scrollTop: $("#phone_number_1").offset().top
        });
    } else if (validateIsHotmail(email)) {
        showWarningNotficationDialog("กรุณาสมัครสมาชิกด้วย Email ที่ไม่ใช่ hotmail");
        $('html,body').animate({
            scrollTop: $("#phone_number_1").offset().top
        });
    } else {
        $.ajax({
            url: "../model/com.gogetrich.function/verifyUserExistingIntmpTbleByEmail.php?email=" + email,
            type: 'POST',
            beforeSend: function (xhr) {
                $(".preloader").show();
            },
            success: function (isDuplicate, textStatus, jqXHR) {
//                $(".preloader").fadeOut("slow");
                if (isDuplicate == 409) {
                    showWarningNotficationDialog("อีเมลนี้ได้ถูกใช้ในการลงทะเบียนเรียบร้อยแล้ว");
                } else if (isDuplicate == 505) {
                    showSuccessNotficationDialog("เกิดข้อผิดพลาดระหว่างการทำงาน
กรุณากดลงทะเบียนใหม่อีกครั้งค่ะ", "scheduleDetail?cname=" + courseId)
                } else {
                    $.ajax({
                        url: "../model/com.gogetrich.function/verifyEmailEnrollment.php?email=" + email + "&courseID=" + headerId,
                        type: 'POST',
                        beforeSend: function (xhr) {
                            $(".preloader").show();
                        },
                        success: function (dataCheckRegistered, textStatus, jqXHR) {
//                            $(".preloader").fadeOut("slow");
                            if (dataCheckRegistered == 200) {
                                $.ajax({
                                    url: "../model/com.gogetrich.function/SaveAdditionalUserToTmp.php?isSameAddress=" + isSameAddress + "&fName=" + firtName + "&lName=" + lastName + "&email=" + email + "&phone=" + phone + "&isOwner=false&addressForReceipt=" + addressForReceipt + "&addressForContact=" + addressForContact,
                                    type: 'POST',
                                    beforeSend: function (xhr) {
                                        $(".preloader").show();
                                    },
                                    success: function (data, textStatus, jqXHR) {
                                        $(".preloader").fadeOut("slow");
                                        if (data == 200) {
                                            $("#loadMoreUser").load("moreUserTbl.php?courseId=" + courseId, function () {
                                                $('html,body').animate({
                                                    scrollTop: $("#main").offset().top
                                                });
                                            });
                                            $("#addMoreRegisLab").toggle();
                                            $("#regisMoreThan1User").toggle();
                                            $("#moreFirstName_1").val("");
                                            $("#moreLastName_1").val("");
                                            $("#moreUserEmail_1").val("");
                                            $("#phone_number_1").val("");
                                            $("#addressForReceipt").val("");
                                            $("#addressForContact").val("");
                                            $("#isSameAddress").prop("checked", false);
                                            $("#addressForReceipt").removeClass("blockTextArea");
                                        } else {
                                            showWarningNotficationDialog(data);
                                        }

                                    }
                                });
                                $("body, html, #scheduleFormDiv").animate({scrollTop: 0}, "fast");
                            } else {
                                showWarningNotficationDialog(dataCheckRegistered);
                            }
                        }
                    });
                }
            }
        });
    }
}
function validateIsHotmail($email) {
    console.log($email);
    return $email.indexOf('@hotmail') != -1
}
function validateEmail($email) {
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    return emailReg.test($email);
}
function validatePhone($phone) {
    var phoneReg = /[0-9 -()+]+$/;
    return phoneReg.test($phone);
}
function initialPageRegisCourse(cid, fpage) {
    $("#addMoreRegisLab").hide();
    //Manage login
    runSetDefaultValidation();
    var form = $('.login-form');
    var errorHandler = $('.errorHandler', form);
    form.validate({
        rules: {
            username: {
                required: true
            },
            password: {
                required: true
            }
        },
        submitHandler: function (form) {
            errorHandler.hide();
            submitLogin(form, cid, fpage);
        },
        invalidHandler: function (event, validator) {//display error alert on form submit
            errorHandler.show();
        }
    });
    //Show login popup
    $('#login_menu').tooltipster({
        contentAsHTML: true,
        content: $('

 Logout

'),
        touchDevices: true,
        position: "bottom",
        interactive: true,
        autoClose: true,
        trigger: "click",
        minWidth: 150,
        arrow: false
    });
}

var runSetDefaultValidation = function () {
    $.validator.setDefaults({
        errorElement: "span", // contain the error msg in a small tag
        errorClass: 'help-block',
        errorPlacement: function (error, element) {// render error placement for each input type
            if (element.attr("type") == "radio" || element.attr("type") == "checkbox") {// for chosen elements, need to insert the error after the chosen container
                error.insertAfter($(element).closest('.form-group').children('div').children().last());
            } else if (element.attr("name") == "card_expiry_mm" || element.attr("name") == "card_expiry_yyyy") {
                error.appendTo($(element).closest('.form-group').children('div'));
            } else {
                error.insertAfter(element);
                // for other inputs, just perform default behavior
            }
        },
        ignore: ':hidden',
        success: function (label, element) {
            label.addClass('help-block valid');
            // mark the current input as valid and display OK icon
            $(element).closest('.form-group').removeClass('has-error');
        },
        highlight: function (element) {
            $(element).closest('.help-block').removeClass('valid');
            // display OK icon
            $(element).closest('.form-group').addClass('has-error');
            // add the Bootstrap error class to the control group
        },
        unhighlight: function (element) {// revert the change done by hightlight
            $(element).closest('.form-group').removeClass('has-error');
            // set error class to the control group
        }
    });
}
function toggleRegistrationForm() {
    $("#addMoreRegisLab").hide();
    $("#regisMoreThan1User").show();
}
function logoutFromApplication() {
    $.ajax({
        url: "../model/com.gogetrich.function/Logout.php",
        success: function (data, textStatus, jqXHR) {
            if (data == 200) {
                window.location.href = "main";
            }
        }
    });
}
function deleteMoreUserTmp(tmpID, courseId) {
    $.ajax({
        url: "../model/com.gogetrich.function/deleteTmpAddMoreUser.php?tmpID=" + tmpID,
        type: 'POST',
        beforeSend: function (xhr) {
            $(".preloader").show();
        },
        success: function (data2, textStatus, jqXHR) {
            $(".preloader").fadeOut("slow");
            if (data2 == 200) {
                $.ajax({
                    url: "../model/com.gogetrich.function/checkIsRegister.php",
                    type: 'POST',
                    beforeSend: function (xhr) {
                        $(".preloader").show();
                    },
                    success: function (data, textStatus, jqXHR) {
                        $(".preloader").fadeOut("slow");
                        resetForm();
                        if (data > 0) {
                            $("#loadMoreUser").load("moreUserTbl.php?courseId=" + courseId);
                            $('html,body').animate({
                                scrollTop: $("#main").offset().top
                            });
                            $("#regisMoreThan1User").hide();
                            $("#addMoreRegisLab").show();
                        } else {
                            $("#loadMoreUser").empty();
                            $("#regisMoreThan1User").show();
                            $("#addMoreRegisLab").hide();
                            $('html,body').animate({
                                scrollTop: $("#main").offset().top
                            });
                        }
                    }
                });

            } else {
                showWarningNotficationDialog(data2);
            }
        }
    });
}
function resetForm() {
    $("#moreFirstName_1").val("");
    $("#moreLastName_1").val("");
    $("#moreUserEmail_1").val("");
    $("#phone_number_1").val("");
    $("#addressForReceipt").val("");
    $("#addressForContact").val("");
    $("#isSameAddress").prop("checked", false);
    $("#addressForReceipt").removeClass("blockTextArea");

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../">
  <title data-ice="title">app/feedback.js | Zeeguu Exercises API Document</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

  Home

  Reference
  Source

    <input class="search-input">

CcookieHandler

CEnvironment

CFeedback

CLoader

CSession

CTDS

CValidator

FGenerator

Vevents

animations
CLoadingAnimation

CShakeAnimation

exercises
FEx1

FEx2

FEx3

FEx4

FExercise

pages
FEmptyPage

FHome

FNotFound

FStarter

test_example
CBear

app/feedback.js

/**
 * The class responsible for sending a feedback regarding exercise outcome
 */
import * as Mustache from "mustache";
import $ from "jquery";
import Settings from "./settings";

export default class Feedback {

    /**
     * Construct the feedback class
     * @param {number}, id of the current word
     * @param {String}, resultSubmitSource,
     * */
    constructor(resultSubmitSource, sessionId){
         /** Class parameters*/
        this.wordId = -1;//will be set whenever the feedback box is called
        this.resultSubmitSource = resultSubmitSource;
        this.sessionId = sessionId;
    }

    /**
     * Bind all the actions connected to this module
     * return {void}
     * */
    bindUIActions(){
        //Bind UI action of credits to the function
        $('.btn-feedback-option').click((event) => {this.feedbackAction($(event.target));});
    }

    /**
     * The action performed predefined option is clicked
     * @param {Object}, elem, the element that is clicked
     * */
    feedbackAction(elem){
        this.submitFeedback(this.wordId,elem.attr('value'),this.resultSubmitSource);
        this.successfulFeedback();
    }

    /**
     * @param {number}, session id
     * @param {String}, resultSubmitSource,
     * */
    exerciseFeedbackBox (wordId) {
        let _this = this;
        this.wordId = wordId;
        let feedbackOptions = this.exerciseFeedbackOptions();
        let inputBox = this.exerciseFeedbackInput();
        swal({
                title: "",
                text: feedbackOptions + inputBox,
                showCancelButton: true,
                closeOnConfirm: false,
                animation: "slide-from-top",
                imageUrl: "static/img/illustrations/zeeguu_balloon.png",
                imageSize: "110x110",
                allowOutsideClick: true,
                html: true
            },
            function () {
                let inputValue = $('#feedback-input-box').val().trim();
                if (inputValue != "") {
                    _this.submitFeedback(wordId,inputValue,_this.resultSubmitSource);
                    _this.successfulFeedback();
                    return;
                }
                swal.close();
            });
        this.bindUIActions();
    }

    /**
     * Success message when the feedback is being submitted
     * */
    successfulFeedback(){
        swal({
            title: "",
            text: "",
            timer: 1000,
            type:"success",
            showConfirmButton: false,
            showCancelButton: false,
            closeOnConfirm: false,
            confirmButtonText: "",
        });
    }

    /**
     * Feedback fields for the feedback box within the exercise
     * Using html template and Mustache to render the content
     * @return {String} rendered html
     * */
    exerciseFeedbackOptions(){
        let preDefinedOptions = {
            Options: [
                {name: "Too easy.", icon: 'static/img/emoji/bored.svg', val: 'too_easy'},
                {name: "I know it.", icon: 'static/img/emoji/nerd.svg',val: 'i_already_know_this'},
                {name: "Don't want to see it.", icon: 'static/img/emoji/confused.svg', val: 'dont_show_it_to_me_again'}]
        };
        let preOptionTemplate =
            '{{#Options}}' +
            '<div type = "button" value = {{val}} class = "btn btn-default btn-feedback-option">' +
                '<div class = "emoji-icon"  value = {{val}} style = "background-image: url({{icon}});" ></div>' +
                '<span value = {{val}}>{{name}}</span>' +
            '</div>' +
            '{{/Options}}';
        return (Mustache.render(preOptionTemplate,preDefinedOptions));
    }

    /**
     * Returns the input box for the feedback
     * @return {String}, the input box for the feedback
     * */
    exerciseFeedbackInput(){
        return  '<div class="input-group feedback-input">'+
                    '<input type="text" class="form-control" id = "feedback-input-box" placeholder="Something else ?">'+
                '</div>';
    }

    /**
     *	Request the submit for feedback to the Zeeguu API
     *  @param {number}, id, id of the word
     *  @param {String}, feedbackOption, the outcome of the feedback @example: too_easy
     *  @param {String}, resultSubmitSource, the source of submission @example: Recognize_L1W_in_L2T
     **/
    submitFeedback(wordID,feedbackOption,resultSubmitSource){
        //console.log(Settings.ZEEGUU_API + Settings.ZEEGUU_EX_OUTCOME_ENDPOINT + "/" + feedbackOption + resultSubmitSource + "/" + -1 + "/" + wordID + "?session="+this.sessionId);
		$.post(Settings.ZEEGUU_API + Settings.ZEEGUU_EX_OUTCOME_ENDPOINT + "/" + feedbackOption + resultSubmitSource + "/" + -1 + "/" + wordID + "?session="+this.sessionId);
    }
}

  Generated by ESDoc(0.5.2)


text:
#include <bcon.h>
#include <mongoc.h>
#include <mongoc-collection-private.h>
#include <mongoc-find-and-modify-private.h>
#include <mongoc-client-private.h>

#include "TestSuite.h"

#include "test-libmongoc.h"
#include "test-conveniences.h"
#include "mongoc-tests.h"
#include "mock_server/future-functions.h"
#include "mock_server/mock-server.h"

static void
auto_ismaster (mock_server_t *server,
               int32_t max_wire_version,
               int32_t max_message_size,
               int32_t max_bson_size,
               int32_t max_batch_size)
{
   char *response = bson_strdup_printf (
      "{'ismaster': true, "
      " 'maxWireVersion': %d,"
      " 'maxBsonObjectSize': %d,"
      " 'maxMessageSizeBytes': %d,"
      " 'maxWriteBatchSize': %d }",
      max_wire_version, max_bson_size, max_message_size, max_batch_size);

   mock_server_auto_ismaster (server, response);

   bson_free (response);
}

int
should_run_fam_wc (void)
{
   if (test_framework_is_replset()) {
      return test_framework_max_wire_version_at_least (WIRE_VERSION_FAM_WRITE_CONCERN);
   }
   return 0;
}

static mongoc_collection_t *
get_test_collection (mongoc_client_t *client,
                     const char      *prefix)
{
   mongoc_collection_t *ret;
   char *str;

   str = gen_collection_name (prefix);
   ret = mongoc_client_get_collection (client, "test", str);
   bson_free (str);

   return ret;
}

static void
test_find_and_modify_bypass (bool bypass)
{
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   mock_server_t *server;
   request_t *request;
   future_t *future;
   bson_error_t error;
   bson_t *update;
   bson_t doc = BSON_INITIALIZER;
   bson_t reply;
   mongoc_find_and_modify_opts_t *opts;

   server = mock_server_new ();
   mock_server_run (server);

   client = mongoc_client_new_from_uri (mock_server_get_uri (server));
   ASSERT (client);

   collection = mongoc_client_get_collection (client, "test", "test_find_and_modify");

   auto_ismaster (server,
                  WIRE_VERSION_FAM_WRITE_CONCERN, /* max_wire_version */
                  48000000,   /* max_message_size */
                  16777216,   /* max_bson_size */
                  1000);      /* max_write_batch_size */

   BSON_APPEND_INT32 (&doc, "superduper", 77889);

   update = BCON_NEW ("$set", "{",
                         "superduper", BCON_INT32 (1234),
                      "}");

   opts = mongoc_find_and_modify_opts_new ();
   mongoc_find_and_modify_opts_set_bypass_document_validation (opts, bypass);
   mongoc_find_and_modify_opts_set_update (opts, update);
   mongoc_find_and_modify_opts_set_flags (opts, MONGOC_FIND_AND_MODIFY_RETURN_NEW);

   future = future_collection_find_and_modify_with_opts (collection,
                                               &doc,
                                               opts,
                                               &reply,
                                               &error);

   if (bypass) {
      request = mock_server_receives_command (server, "test", MONGOC_QUERY_NONE,
       "{ 'findAndModify' : 'test_find_and_modify', "
         "'query' : { 'superduper' : 77889 },"
         "'update' : { '$set' : { 'superduper' : 1234 } },"
         "'new' : true,"
         "'bypassDocumentValidation' : true }");
   } else {
      request = mock_server_receives_command (server, "test", MONGOC_QUERY_NONE,
       "{ 'findAndModify' : 'test_find_and_modify', "
         "'query' : { 'superduper' : 77889 },"
         "'update' : { '$set' : { 'superduper' : 1234 } },"
         "'new' : true,"
         "'bypassDocumentValidation' : false }");
   }

   mock_server_replies_simple (request, "{ 'value' : null, 'ok' : 1 }");
   ASSERT_OR_PRINT (future_get_bool (future), error);

   future_destroy (future);

   mongoc_find_and_modify_opts_destroy (opts);
   bson_destroy (&reply);
   bson_destroy (update);

   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);
   mock_server_destroy (server);
   bson_destroy (&doc);
}

static void
test_find_and_modify_bypass_true (void)
{
   test_find_and_modify_bypass (true);
}

static void
test_find_and_modify_bypass_false (void)
{
   test_find_and_modify_bypass (false);
}

static void
test_find_and_modify_write_concern (int wire_version)
{
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   mock_server_t *server;
   request_t *request;
   future_t *future;
   bson_error_t error;
   bson_t *update;
   bson_t doc = BSON_INITIALIZER;
   bson_t reply;
   mongoc_find_and_modify_opts_t *opts;
   mongoc_write_concern_t *write_concern;

   server = mock_server_new ();
   mock_server_run (server);

   client = mongoc_client_new_from_uri (mock_server_get_uri (server));
   ASSERT (client);

   collection = mongoc_client_get_collection (client, "test", "test_find_and_modify");

   auto_ismaster (server,
                  wire_version,          /* max_wire_version */
                  48000000,   /* max_message_size */
                  16777216,   /* max_bson_size */
                  1000);      /* max_write_batch_size */

   BSON_APPEND_INT32 (&doc, "superduper", 77889);

   update = BCON_NEW ("$set", "{",
                         "superduper", BCON_INT32 (1234),
                      "}");

   write_concern = mongoc_write_concern_new ();
   mongoc_write_concern_set_w (write_concern, 42);
   opts = mongoc_find_and_modify_opts_new ();
   mongoc_collection_set_write_concern (collection, write_concern);
   mongoc_find_and_modify_opts_set_update (opts, update);
   mongoc_find_and_modify_opts_set_flags (opts, MONGOC_FIND_AND_MODIFY_RETURN_NEW);

   future = future_collection_find_and_modify_with_opts (collection,
                                               &doc,
                                               opts,
                                               &reply,
                                               &error);

   if (wire_version >= 4) {
      request = mock_server_receives_command (server, "test", MONGOC_QUERY_NONE,
       "{ 'findAndModify' : 'test_find_and_modify', "
         "'query' : { 'superduper' : 77889 },"
         "'update' : { '$set' : { 'superduper' : 1234 } },"
         "'new' : true,"
         "'writeConcern' : { 'w' : 42 } }");
   } else {
      request = mock_server_receives_command (server, "test", MONGOC_QUERY_NONE,
       "{ 'findAndModify' : 'test_find_and_modify', "
         "'query' : { 'superduper' : 77889 },"
         "'update' : { '$set' : { 'superduper' : 1234 } },"
         "'new' : true }");
   }

   mock_server_replies_simple (request, "{ 'value' : null, 'ok' : 1 }");
   ASSERT_OR_PRINT (future_get_bool (future), error);

   future_destroy (future);

   mongoc_find_and_modify_opts_destroy (opts);
   bson_destroy (&reply);
   bson_destroy (update);

   mongoc_write_concern_destroy (write_concern);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);
   bson_destroy (&doc);
   mock_server_destroy (server);
}

static void
test_find_and_modify_write_concern_wire_32_failure (void *context)
{
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   bson_error_t error;
   mongoc_find_and_modify_opts_t *opts;
   bson_t reply;
   bson_t query = BSON_INITIALIZER;
   bson_t *update;
   bool success;
   mongoc_write_concern_t *wc;

   client = test_framework_client_new ();
   collection = get_test_collection (client, "writeFailure");
   wc = mongoc_write_concern_new ();

   mongoc_write_concern_set_w (wc, 42);
   mongoc_collection_set_write_concern (collection, wc);

   /* Find Zlatan Ibrahimovic, the striker */
   BSON_APPEND_UTF8 (&query, "firstname", "Zlatan");
   BSON_APPEND_UTF8 (&query, "lastname", "Ibrahimovic");
   BSON_APPEND_UTF8 (&query, "profession", "Football player");
   BSON_APPEND_INT32 (&query, "age", 34);
   BSON_APPEND_INT32 (&query, "goals", (16+35+23+57+16+14+28+84)+(1+6+62));

   /* Add his football position */
   update = BCON_NEW ("$set", "{",
      "position", BCON_UTF8 ("striker"),
   "}");

   opts = mongoc_find_and_modify_opts_new ();

   mongoc_find_and_modify_opts_set_update (opts, update);

   /* Create the document if it didn't exist, and return the updated document */
   mongoc_find_and_modify_opts_set_flags (opts, MONGOC_FIND_AND_MODIFY_UPSERT|MONGOC_FIND_AND_MODIFY_RETURN_NEW);

   success = mongoc_collection_find_and_modify_with_opts (collection, &query, opts, &reply, &error);

   ASSERT (success);
   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_WRITE_CONCERN, 100, "Write Concern error:");

   bson_destroy (&reply);
   bson_destroy (update);
   bson_destroy (&query);
   mongoc_find_and_modify_opts_destroy (opts);
   mongoc_collection_drop (collection, NULL);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);
}

static void
test_find_and_modify_write_concern_wire_32 (void)
{
   test_find_and_modify_write_concern (4);
}

static void
test_find_and_modify_write_concern_wire_pre_32 (void)
{
   test_find_and_modify_write_concern (2);
}

static void
test_find_and_modify (void)
{
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   bson_error_t error;
   bson_iter_t iter;
   bson_iter_t citer;
   bson_t *update;
   bson_t doc = BSON_INITIALIZER;
   bson_t reply;
   mongoc_find_and_modify_opts_t *opts;

   client = test_framework_client_new ();
   ASSERT (client);

   collection = get_test_collection (client, "test_find_and_modify");
   ASSERT (collection);

   BSON_APPEND_INT32 (&doc, "superduper", 77889);

   ASSERT_OR_PRINT (mongoc_collection_insert (
      collection, MONGOC_INSERT_NONE, &doc, NULL, &error), error);

   update = BCON_NEW ("$set", "{",
                         "superduper", BCON_INT32 (1234),
                      "}");

   opts = mongoc_find_and_modify_opts_new ();
   mongoc_find_and_modify_opts_set_update (opts, update);
   mongoc_find_and_modify_opts_set_fields (opts, tmp_bson ("{'superduper': 1}"));
   mongoc_find_and_modify_opts_set_sort (opts, tmp_bson ("{'superduper': 1}"));
   mongoc_find_and_modify_opts_set_flags (opts, MONGOC_FIND_AND_MODIFY_RETURN_NEW);

   ASSERT_OR_PRINT (mongoc_collection_find_and_modify_with_opts (collection,
                                                                 &doc,
                                                                 opts,
                                                                 &reply,
                                                                 &error), error);

   assert (bson_iter_init_find (&iter, &reply, "value"));
   assert (BSON_ITER_HOLDS_DOCUMENT (&iter));
   assert (bson_iter_recurse (&iter, &citer));
   assert (bson_iter_find (&citer, "superduper"));
   assert (BSON_ITER_HOLDS_INT32 (&citer));
   assert (bson_iter_int32 (&citer) == 1234);

   assert (bson_iter_init_find (&iter, &reply, "lastErrorObject"));
   assert (BSON_ITER_HOLDS_DOCUMENT (&iter));
   assert (bson_iter_recurse (&iter, &citer));
   assert (bson_iter_find (&citer, "updatedExisting"));
   assert (BSON_ITER_HOLDS_BOOL (&citer));
   assert (bson_iter_bool (&citer));

   bson_destroy (&reply);
   bson_destroy (update);

   ASSERT_OR_PRINT (mongoc_collection_drop (collection, &error), error);

   mongoc_find_and_modify_opts_destroy (opts);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);
   bson_destroy (&doc);
}

void
test_find_and_modify_install (TestSuite *suite)
{
   TestSuite_Add (suite, "/find_and_modify/find_and_modify", test_find_and_modify);
   TestSuite_Add (suite, "/find_and_modify/find_and_modify/bypass/true",
                  test_find_and_modify_bypass_true);
   TestSuite_Add (suite, "/find_and_modify/find_and_modify/bypass/false",
                  test_find_and_modify_bypass_false);
   TestSuite_Add (suite, "/find_and_modify/find_and_modify/write_concern",
                  test_find_and_modify_write_concern_wire_32);
   TestSuite_Add (suite, "/find_and_modify/find_and_modify/write_concern_pre_32",
                  test_find_and_modify_write_concern_wire_pre_32);
   TestSuite_AddFull (suite, "/find_and_modify/find_and_modify/write_concern_failure",
                  test_find_and_modify_write_concern_wire_32_failure, NULL, NULL,
                  should_run_fam_wc);
}


text:
import * as React from "react";
import ChatComponent from "../chat/ChatComponent";
import VideoInputComponent from "../video/VideoInputComponent";

export default class TabRootComponent extends React.Component<{}, {}> {
  render() {
      let tabs : Array<ITabProperties> = [
        {
          icon : "fa fa-comment",
          children : <ChatComponent/>
        },
        {
          icon : "fa fa-video-camera",
          children : <VideoInputComponent/>
        }
      ];

    return (

        <TabList selectedIndex={0} tabs={tabs} />

    );
  }
}

interface ITabListProperties {
  selectedIndex : number;
  tabs : Array<ITabProperties>;
}

interface ITabListState {
  selectedIndex : number;
}

interface ITabProperties {
  icon : string;
  children : React.ReactNode;
}

class TabList extends React.Component<ITabListProperties, ITabListState> {
  constructor(props : ITabListProperties) {
    super(props);
    this.state = {
      selectedIndex : props.selectedIndex
    };
  }

  onClick(index : number) {
    this.setState({
      selectedIndex : index
    });
  }

  render() {
    let self = this;
    return (

          {
            this.props.tabs.map(function(tab, index) {
              return

            })
          }

        {
          this.props.tabs.map(function(tabContent, index) {
            return (

                {tabContent.children}

            )
          })
        }

    );
  }
}//}


text:
HoptoadNotifier.configure do |config|
  config.api_key = 'c874bd32c27a83f0daf675ebe4d3112f'
  config.js_notifier = false
  config.ignore << "ActionController::UnknownHttpMethod"
  config.backtrace_filters << /RendererExtensionBindings/
  config.backtrace_filters << /d3lvr7yuk4uaui.cloudfront.net/
  config.ignore_user_agent << "Mozilla/5.0 (en-us) AppleWebKit/525.13 (KHTML, like Gecko; Google Web Preview) Version/3.1 Safari/525.13"
end


text:
<?php

namespace Intacct\Functions\Common\Query\Comparison\EqualTo;

/**
 * @coversDefaultClass \Intacct\Functions\Common\Query\Comparison\EqualTo\EqualToInteger
 */
class EqualToIntegerTest extends \PHPUnit\Framework\TestCase
{

    public function testToString(): void
    {
        $condition = new EqualToInteger();
        $condition->setField('RECORDNO');
        $condition->setValue(1234);

        $expected = "RECORDNO = 1234";

        $this->assertEquals($expected, (string)$condition);
    }

    public function testToStringNot(): void
    {
        $condition = new EqualToInteger();
        $condition->setField('RECORDNO');
        $condition->setValue(1234);
        $condition->setNegate(true);

        $expected = "NOT RECORDNO = 1234";

        $this->assertEquals($expected, (string)$condition);
    }
}


text:
using System.Reflection;
using slang.Compiler.Clr.Compilation.Core;

namespace slang.Compiler.Clr.Compilation.CSharp
{
    public class CSharpAssemblyGenerator : IAssemblyGenerator
    {
        public Assembly GenerateDynamicAssembly(AssemblyDefinition assemblyDefinition)
        {
            return CSharpCompiler.CompileToInMemoryAssembly(
                new CSharpCompilationParameters(
                    assemblyDefinition.Name,
                    OutputType.DynamicallyLinkedLibrary,
                    SlangToCSharpTranspiler.Transpile(assemblyDefinition)));
        }
    }
}


text:
modprobe bcm2835_wdt
echo "bcm2835_wdt" | sudo tee -a /etc/modules

update-rc.d watchdog defaults

echo "watchdog-timeout = 30" >> /etc/watchdog.conf


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="First Name"
        />
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Last Name"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


text:
class ApplicationHelper::Toolbar::SummaryCenterRestful < ApplicationHelper::Toolbar::Basic
  button_group('record_summary', [
    button(
      :show_summary,
      'fa fa-arrow-left fa-lg',
      proc do
        _('Show %{object_name} Summary') %
          {:object_name => @layout == "cim_base_storage_extent" ? @record.evm_display_name : @record.name}
      end,
      nil,
      :url       => "/",
      :url_parms => "?id=\#{@record.id}"),
  ])
end


text:
jQuery plugin to make element blinking and fadeout

##Download

* [jquery.blinkout.js](https://raw.github.com/kssfilo/jquery.blinkout/master/dist/jquery.blinkout.js)
* [jquery.blinkout.min.js](https://raw.github.com/kssfilo/jquery.blinkout/master/dist/jquery.blinkout.min.js)

##Usage

```html
<html>
	<head>
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
		<script src='jquery.blinkout.js' ></script>

		<script>
			$(window).load(function(){
				$('.target').blinkout();
			});
		</script>
	</head>

	<body>
		<h1 class='target'>Blinkout</h1>
	</body>
</html>
```

##Optional Arguments

	$('.target').blinkout(5000,1000);

-> Blinking Time to 5000ms(Default:10000ms),Fade Time to 1000ms(Default:5000ms)

##History


text:
package org.zstack.sdk;

public class GetBareMetal2ChassisPowerStatusResult {
    public java.lang.String status;
    public void setStatus(java.lang.String status) {
        this.status = status;
    }
    public java.lang.String getStatus() {
        return this.status;
    }

}


text:
package org.docksidestage.mysql.dbflute.exbhv;

import org.docksidestage.mysql.dbflute.bsbhv.BsWhiteNonUniqueManyToOneToBhv;

/**
 * The behavior of WHITE_NON_UNIQUE_MANY_TO_ONE_TO.
 * <p>
 * You can implement your original methods here.
 * This class remains when re-generating.
 * </p>
 * @author DBFlute(AutoGenerator)
 */
public class WhiteNonUniqueManyToOneToBhv extends BsWhiteNonUniqueManyToOneToBhv {
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<TITLE
>Indirect References</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.7"><LINK
REL="HOME"
TITLE="Advanced Bash-Scripting Guide"
HREF="index.html"><LINK
REL="UP"
TITLE="Advanced Topics"
HREF="part5.html"><LINK
REL="PREVIOUS"
TITLE="Arrays"
HREF="arrays.html"><LINK
REL="NEXT"
TITLE="/dev and /proc"
HREF="devproc.html">

Advanced Bash-Scripting Guide:

Prev		Next

Chapter 28. Indirect References

We have seen that referencing
        a variable, <TT
CLASS="VARNAME"
>$var</TT
>, fetches its
        value. But,
        what about the value of a value? What
        about <TT
CLASS="VARNAME"
>$$var</TT
>?

The actual notation is
	<TT
CLASS="REPLACEABLE"
>\$$var</TT
>, usually preceded by
	an eval (and sometimes an
	echo). This is called an
	indirect reference.

Example 28-1. Indirect Variable References

#!/bin/bash
# ind-ref.sh: Indirect variable referencing.
# Accessing the contents of the contents of a variable.

# First, let's fool around a little.

var=23

echo "\$var   = $var"           # $var   = 23
# So far, everything as expected. But ...

echo "\$\$var  = $$var"         # $$var  = 4570var
#  Not useful ...
#  \$\$ expanded to PID of the script
#  -- refer to the entry on the $$ variable --
#+ and "var" is echoed as plain text.
#  (Thank you, Jakob Bohm, for pointing this out.)

echo "\\\$\$var = \$$var"       # \$$var = $23
#  As expected. The first $ is escaped and pasted on to
#+ the value of var ($var = 23 ).
#  Meaningful, but still not useful.

# Now, let's start over and do it the right way.

# ============================================== #

a=letter_of_alphabet   # Variable "a" holds the name of another variable.
letter_of_alphabet=z

echo

# Direct reference.
echo "a = $a"          # a = letter_of_alphabet

# Indirect reference.
  eval a=\$$a
# ^^^        Forcing an eval(uation), and ...
#        ^   Escaping the first $ ...
# ------------------------------------------------------------------------
# The 'eval' forces an update of $a, sets it to the updated value of \$$a.
# So, we see why 'eval' so often shows up in indirect reference notation.
# ------------------------------------------------------------------------
  echo "Now a = $a"    # Now a = z

echo

# Now, let's try changing the second-order reference.

t=table_cell_3
table_cell_3=24
echo "\"table_cell_3\" = $table_cell_3"            # "table_cell_3" = 24
echo -n "dereferenced \"t\" = "; eval echo \$$t    # dereferenced "t" = 24
# In this simple case, the following also works (why?).
#         eval t=\$$t; echo "\"t\" = $t"

echo

t=table_cell_3
NEW_VAL=387
table_cell_3=$NEW_VAL
echo "Changing value of \"table_cell_3\" to $NEW_VAL."
echo "\"table_cell_3\" now $table_cell_3"
echo -n "dereferenced \"t\" now "; eval echo \$$t
# "eval" takes the two arguments "echo" and "\$$t" (set equal to $table_cell_3)

echo

# (Thanks, Stephane Chazelas, for clearing up the above behavior.)

#   A more straightforward method is the ${!t} notation, discussed in the
#+ "Bash, version 2" section.
#   See also ex78.sh.

exit 0

Indirect referencing in Bash
        is a multi-step process. First, take the name of a variable:
	<TT
CLASS="VARNAME"
>varname</TT
>. Then, reference it:
	<TT
CLASS="VARNAME"
>$varname</TT
>. Then, reference the reference:
	<TT
CLASS="VARNAME"
>$$varname</TT
>. Then, escape
	the first $: <TT
CLASS="VARNAME"
>\$$varname</TT
>.
	Finally, force a reevaluation of the expression and assign it:
	eval newvar=\$$varname.

Of what practical use is indirect referencing of
	  variables? It gives Bash a little of the functionality
	  of pointers
	  in C, for instance, in table lookup.  And, it also has some
	  other very interesting applications. . . .

Nils Radtke shows how to build "dynamic"
	  variable names and evaluate their contents. This can be useful
	  when sourcing configuration
	  files.

#!/bin/bash

# ---------------------------------------------
# This could be "sourced" from a separate file.
isdnMyProviderRemoteNet=172.16.0.100
isdnYourProviderRemoteNet=10.0.0.10
isdnOnlineService="MyProvider"
# ---------------------------------------------

remoteNet=$(eval "echo \$$(echo isdn${isdnOnlineService}RemoteNet)")
remoteNet=$(eval "echo \$$(echo isdnMyProviderRemoteNet)")
remoteNet=$(eval "echo \$isdnMyProviderRemoteNet")
remoteNet=$(eval "echo $isdnMyProviderRemoteNet")

echo "$remoteNet"    # 172.16.0.100

# ================================================================

#  And, it gets even better.

#  Consider the following snippet given a variable named getSparc,
#+ but no such variable getIa64:

chkMirrorArchs () {
  arch="$1";
  if [ "$(eval "echo \${$(echo get$(echo -ne $arch |
       sed 's/^\(.\).*/\1/g' | tr 'a-z' 'A-Z'; echo $arch |
       sed 's/^.\(.*\)/\1/g')):-false}")" = true ]
  then
     return 0;
  else
     return 1;
  fi;
}

getSparc="true"
unset getIa64
chkMirrorArchs sparc
echo $?        # 0
               # True

chkMirrorArchs Ia64
echo $?        # 1
               # False

# Notes:
# -----
# Even the to-be-substituted variable name part is built explicitly.
# The parameters to the chkMirrorArchs calls are all lower case.
# The variable name is composed of two parts: "get" and "Sparc" . . .

Example 28-2. Passing an indirect reference to awk

#!/bin/bash

#  Another version of the "column totaler" script
#+ that adds up a specified column (of numbers) in the target file.
#  This one uses indirect references.

ARGS=2
E_WRONGARGS=85

if [ $# -ne "$ARGS" ] # Check for proper number of command-line args.
then
   echo "Usage: `basename $0` filename column-number"
   exit $E_WRONGARGS
fi

filename=$1         # Name of file to operate on.
column_number=$2    # Which column to total up.

#===== Same as original script, up to this point =====#

# A multi-line awk script is invoked by
#   awk "
#   ...
#   ...
#   ...
#   "

# Begin awk script.
# -------------------------------------------------
awk "

{ total += \$${column_number} # Indirect reference
}
END {
     print total
     }

     " "$filename"
# Note that awk doesn't need an eval preceding \$$.
# -------------------------------------------------
# End awk script.

#  Indirect variable reference avoids the hassles
#+ of referencing a shell variable within the embedded awk script.
#  Thanks, Stephane Chazelas.

exit $?

This method of indirect referencing is a bit tricky.
	If the second order variable changes its value, then the first
	order variable must be properly dereferenced (as in the above
	example). Fortunately, the
	<TT
CLASS="REPLACEABLE"
>${!variable}</TT
> notation introduced
	with version 2 of Bash
	(see Example 37-2 and Example A-22) makes
	indirect referencing more intuitive.

Bash does not support pointer arithmetic, and this severely
	 limits the usefulness of indirect referencing. In fact, indirect
	 referencing in a scripting language is, at best, something of
	 an afterthought.

Prev	Home	Next

Arrays	Up	<TT
CLASS="FILENAME"
>/dev</TT
> and <TT
CLASS="FILENAME"
>/proc</TT
>


text:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  Copyright (C) Inkton 2016 <thebird@nest.yt>#
## -*- python -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4

import errno, os, sys
import argparse, json
import re

from datetime import datetime, date, time
from subprocess import Popen, PIPE, STDOUT
import re
from thing import FailedValidation
from cloud import Cloud
from auth import Auth

class Deployment(Cloud):

    def __init__(self, auth):
        super(Deployment, self).__init__('deployment', auth)

    def new_copy(self, object):
        new_entity = Deployment(self.auth)
        new_entity.__dict__.update(object)
        return new_entity

    def parse_command(self, subparsers):
        cmd_parser = subparsers.add_parser(self.subject, help='Manage the deployment')
        app_cmd_parsers = cmd_parser.add_subparsers(dest='dep_command', help='Deployment commands')

        app_cmd_parsers.add_parser('pull', help='Download the deployment')
        app_cmd_parsers.add_parser('push', help='Push the source to the remote')
        app_cmd_parsers.add_parser('deploy', help='Remote build and deploy')
        app_cmd_parsers.add_parser('restore', help='Restore the project')
        app_cmd_parsers.add_parser('clear', help='Clear the project')
        app_cmd_parsers.add_parser('clean', help='Clean the project')
        app_cmd_parsers.add_parser('build', help='Build the project')
        app_cmd_parsers.add_parser('clean_build_tests', help='Clean build unit tests')
        app_cmd_parsers.add_parser('unit_test_debug_host', help='Spawn unit test debug')
        app_cmd_parsers.add_parser('restore_all', help='Restore all projects')
        app_cmd_parsers.add_parser('release_clean_all', help='Release clean all')
        app_cmd_parsers.add_parser('release_build_all', help='Release build all')
        app_cmd_parsers.add_parser('release_test_all', help='Release test all')
        app_cmd_parsers.add_parser('release_coverage_report', help='Release produce report')
        app_cmd_parsers.add_parser('release_upload_all', help='Release upload all')
        app_cmd_parsers.add_parser('uncache', help='Clear cache')

    def exec_command(self, args):
        self.set_log(args.log)
        cmd_handled = False
        if args.command == self.subject:
            self.log("handle deployment command")
            cmd_handled = True
            if (args.dep_command == 'pull'):
                self.pull()
            elif (args.dep_command == 'push'):
                self.push()
            elif (args.dep_command == 'deploy'):
                self.deploy()
            elif (args.dep_command == 'restore'):
                self.restore()
            elif (args.dep_command == 'build'):
                self.build()
            elif (args.dep_command == 'clear'):
                self.clear()
            elif (args.dep_command == 'clean_build_tests'):
                self.clean_build_debug_tests()
            elif (args.dep_command == 'unit_test_debug_host'):
                self.unit_test_debug_host()
            elif (args.dep_command == 'restore_all'):
                self.restore_all()
            elif (args.dep_command == 'release_clean_all'):
                self.release_clean_all()
            elif (args.dep_command == 'release_build_all'):
                self.release_build_all()
            elif (args.dep_command == 'release_test_all'):
                self.release_test_all()
            elif (args.dep_command == 'release_coverage_report'):
                self.release_coverage_report()
            elif (args.dep_command == 'release_upload_all'):
                self.release_upload_all()
            elif (args.dep_command == 'clean'):
                self.clean()
            elif (args.dep_command == 'uncache'):
                self.clear_cache()
            else:
                cmd_handled = False
            self.end_cmd()
        return cmd_handled

    def pull(self):
        try:
            self.os_exec("mkdir " + self.get_source_folder())

            self.os_exec(self.transfer_cmd() + "nest:" + self.get_source_target_folder() + "/ " + self.get_source_target_folder() + "/")
            self.os_exec(self.transfer_cmd() + "nest:" + self.get_source_shared_folder() + "/ " + self.get_source_shared_folder() + "/")

            self.os_exec(self.transfer_cmd() + "nest:/var/app/log /var/app", False)

            self.os_exec(self.transfer_cmd() + "nest:/var/app/source/" + self.get_app_tag_capitalized() + ".sln /var/app/source", False)
            self.os_exec(self.transfer_cmd() + "nest:/var/app/app.nest /var/app", False)
            self.os_exec(self.transfer_cmd() + "nest:/var/app/app.json /var/app", False)
            self.os_exec(self.transfer_cmd() + "nest:/var/app/nest /var/app", False)
            self.os_exec(self.transfer_cmd() + "nest:/var/app/downtime /var/app", False)

            self.setup_git()
        except Exception as e:
            print(e)

    def push(self):
        try:
            self.os_exec(self.transfer_cmd() + "/var/app/source/" + self.get_app_tag_capitalized() + ".sln nest:/var/app/source/" + self.get_app_tag_capitalized() + ".sln", False)
            self.os_exec(self.transfer_cmd() + "/var/app/app.nest nest:/var/app", False)
            self.os_exec(self.transfer_cmd() + "/var/app/app.json nest:/var/app", False)
            self.os_exec(self.transfer_cmd() + "/var/app/nest nest:/var/app", False)
            self.os_exec(self.transfer_cmd() + "/var/app/downtime nest:/var/app", False)

            self.os_exec(self.transfer_cmd() + self.get_source_shared_folder() + "/  nest:" + self.get_source_shared_folder() + "/", False)
            self.os_exec(self.transfer_cmd() + self.get_source_target_folder() + "/ nest:" + self.get_source_target_folder() + "/", False)
        except Exception as e:
            print(e)

    def deploy(self):
        try:
            self.os_exec("ssh nest 'deploy'", False)
        except Exception as e:
            print(e)

    def restore(self):
        self.log("test restore")
        self.os_exec("dotnet restore " + self.get_source_target_source_folder(), False)

    def build(self):
        self.log("build " + self.get_source_target_source_folder())
        self.os_exec("dotnet build " + self.get_source_target_source_folder() + " -c Debug ", False)

    def clean(self):
        self.log("clean")
        self.os_exec("dotnet clean " + self.get_source_target_source_folder(), False)

    def clear(self):
        self.log("remove build folders")
        self.os_exec_shell("rm -rf " + self.get_source_target_source_folder() + "/obj", False)
        self.os_exec_shell("rm -rf " + self.get_source_target_source_folder() + "/bin", False)

    def clean_build_debug_tests(self):
        self.log("build debug tests")
        self.os_exec_shell("rm -rf " + self.get_source_target_test_folder() + "/obj")
        self.os_exec_shell("rm -rf " + self.get_source_target_test_folder() + "/bin")
        self.os_exec("dotnet build " + self.get_source_target_test_folder() + " -c Debug ", False)

    def unit_test_debug_host(self):
        self.os_exec("pkill dotnet")
        # do the UNIX double-fork magic, see Stevens' "Advanced
        # Programming in the UNIX Environment" for details (ISBN 0201563177)
        # https://stackoverflow.com/questions/6011235/run-a-program-from-
        # python-and-have-it-continue-to-run-after-the-script-is-kille
        try:
            pid = os.fork()
            if pid > 0:
                # parent process, return and keep running
                return
        except OSError, e:
            print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
            sys.exit(1)
        os.setsid()
        # do stuff
        my_env = os.environ.copy()
        my_env["VSTEST_HOST_DEBUG"] = "1"
        devnull = open(os.devnull, 'wb')
        proc = Popen(["/usr/bin/dotnet", "exec", self.get_vtest_console_runtime_path(),
            self.get_source_target_test_runtime_path()], stdout=PIPE, env=my_env)
        bite_this = re.compile("Process Id:+\s+(\d*), Name:+\sdotnet")
        while proc.poll() is None:
            out = proc.stdout.readline()
            match = bite_this.search(out)
            if match:
                print match.group(1)
                break
        # all done
        os._exit(os.EX_OK)

    def setup_git_folder(self, folder):
        self.log("setup git folder " + folder)
        git_command = "git -C " + folder + " "
        self.os_exec(git_command + "init")
        self.os_exec(git_command + "config --file "+ folder + "/.git/config user.email "+os.environ['NEST_CONTACT_EMAIL'] )
        self.os_exec(git_command + "config --file "+ folder + "/.git/config user.name "+os.environ['NEST_CONTACT_ID'] )
        self.os_exec(git_command + "remote rm origin ")
        self.os_exec(git_command + "remote add origin nest:repository.git ")
        self.os_exec(git_command + "fetch origin --tags")

    def setup_git(self):
        self.log("setup git")
        self.os_exec("git config --global user.email "+os.environ['NEST_CONTACT_EMAIL'] )
        self.os_exec("git config --global user.name "+os.environ['NEST_CONTACT_ID'] )
        self.setup_git_folder(self.get_source_shared_folder())
        self.setup_git_folder(self.get_source_target_folder())

    def apply_all_projects(self, op, command, test_only):
        self.log("restore all with settings " + self.get_app_folder() + "/settings.json")
        with open(self.get_app_folder() + "/settings.json") as settings_file:
            settings = json.load(settings_file)
            machine = "app-" + settings["app"]["environment"]["NEST_TAG"]
            target_folder = settings["app"]["environment"]["NEST_FOLDER_SOURCE"] + '/' + settings["app"]["environment"]["NEST_TAG_CAP"]
            title = op + " the app " + settings["app"]["environment"]["NEST_TAG_CAP"]
            print title
            print '-' * len(title)
            if not test_only:
                self.os_exec(self.remote_shell_cmd() + machine + " " + command + " " + target_folder +"/src", False, True)
            self.os_exec(self.remote_shell_cmd() + machine + " " + command + " " + target_folder +"/test", False, True)
            i = 0
            while i < len(settings["workers"]):
                machine = "worker-" + settings["workers"][i]["environment"]["NEST_TAG"]
                target_folder = settings["workers"][i]["environment"]["NEST_FOLDER_SOURCE"] + '/' + settings["workers"][i]["environment"]["NEST_TAG_CAP"]
                title = "\n" + op + " the worker " +settings["workers"][i]["environment"]["NEST_TAG_CAP"]
                print title
                print '-' * len(title)
                if not test_only:
                    self.os_exec(self.remote_shell_cmd() + machine + " " + command + " " + target_folder +"/src", False, True)
                self.os_exec(self.remote_shell_cmd() + machine + " " + command + " " + target_folder +"/test", False, True)
                i += 1

    def restore_all(self):
        try:
            self.log("restore all")
            self.apply_all_projects("Restoring", "dotnet restore", False)
        except Exception as e:
            print '-- Ended --'
            sys.exit(-1)

    def release_build_all(self):
        try:
            self.log("release build all")
            self.apply_all_projects("Restoring", "dotnet build --configuration Release --output " + self.get_publish_folder(), False)
        except Exception as e:
            print '-- Ended --'
            sys.exit(-1)

    def release_clean_all(self):
        try:
            self.log("release clean all")
            self.apply_all_projects("Clean", "dotnet clean --configuration Release ", False)
        except Exception as e:
            print '-- Ended --'
            sys.exit(-1)

    def release_test_all(self):
        try:
            self.log("release test all")
            self.apply_all_projects("Testing", "dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura --configuration Release --output " + self.get_publish_folder(), True)
        except Exception as e:
            print '-- Ended --'
            sys.exit(-1)

    def release_coverage_report(self):
        try:
            with open(self.get_app_folder() + "/settings.json") as settings_file:
                settings = json.load(settings_file)
                machine = "app-" + settings["app"]["environment"]["NEST_TAG"]
                command = "/root/.dotnet/tools/reportgenerator -reports:$NEST_FOLDER_SOURCE/*/*/coverage.cobertura.xml -targetdir:$NEST_FOLDER_PUBLISH/reports"
                self.os_exec(self.remote_shell_cmd() + machine + " " + command, False)
        except Exception as e:
            print '-- Ended --'
            sys.exit(-1)

    def release_upload_all(self):
        try:
            self.log("release deploy all")
            print "Uploading app assets"
            print "--------------------"
            self.os_exec(self.transfer_cmd() + " /var/app/app.nest nest:/var/app", False, True)
            self.os_exec(self.transfer_cmd() + " /var/app/app.json nest:/var/app", False, True)
            self.os_exec(self.transfer_cmd() + " /var/app/nest nest:/var/app", False, True)
            self.os_exec(self.transfer_cmd() + " /var/app/downtime/ nest:/var/app/downtime/", False, True)
            print "\nUploading the app source code"
            print "------------------------------"
            self.os_exec(self.transfer_cmd() + " /var/app/source/ nest:/var/app/source/", False, True)
        except Exception as e:
            print '-- Ended --'
            sys.exit(-1)


text:
package watch

import (
	"context"
	"testing"

	"github.com/google/go-cmp/cmp"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/watch"
	"kpt.dev/configsync/pkg/core"
	"kpt.dev/configsync/pkg/declared"
	"kpt.dev/configsync/pkg/diff/difftest"
	"kpt.dev/configsync/pkg/remediator/queue"
	"kpt.dev/configsync/pkg/syncer/syncertest"
	"kpt.dev/configsync/pkg/testing/fake"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

type action struct {
	event watch.EventType
	obj   client.Object
}

func TestFilteredWatcher(t *testing.T) {
	scope := declared.Scope("test")
	syncName := "rs"

	deployment1 := fake.DeploymentObject(core.Name("hello"))
	deployment1Beta := fake.DeploymentObject(core.Name("hello"))
	deployment1Beta.GetObjectKind().SetGroupVersionKind(deployment1Beta.GroupVersionKind().GroupKind().WithVersion("beta1"))

	deployment2 := fake.DeploymentObject(core.Name("world"))
	deployment3 := fake.DeploymentObject(core.Name("nomes"))

	managedBySelfDeployment := fake.DeploymentObject(core.Name("not-declared"),
		syncertest.ManagementEnabled, difftest.ManagedBy(scope, syncName))
	managedByOtherDeployment := fake.DeploymentObject(core.Name("not-declared"),
		syncertest.ManagementEnabled, difftest.ManagedBy("other", "other-rs"))
	deploymentForRoot := fake.DeploymentObject(core.Name("managed-by-root"), difftest.ManagedBy(declared.RootReconciler, "any-rs"))

	testCases := []struct {
		name     string
		declared []client.Object
		actions  []action
		want     []core.ID
	}{
		{
			"Enqueue events for declared resources",
			[]client.Object{
				deployment1,
				deployment2,
				deployment3,
			},
			[]action{
				{
					watch.Added,
					deployment1,
				},
				{
					watch.Modified,
					deployment2,
				},
				{
					watch.Deleted,
					deployment3,
				},
			},
			[]core.ID{
				core.IDOf(deployment1),
				core.IDOf(deployment2),
				core.IDOf(deployment3),
			},
		},
		{
			"Filter events for undeclared-but-managed-by-other-reconciler resource",
			[]client.Object{
				deployment1,
			},
			[]action{
				{
					watch.Modified,
					managedByOtherDeployment,
				},
			},
			nil,
		},
		{
			"Enqueue events for undeclared-but-managed-by-this-reconciler resource",
			[]client.Object{
				deployment1,
			},
			[]action{
				{
					watch.Modified,
					managedBySelfDeployment,
				},
			},
			[]core.ID{
				core.IDOf(managedBySelfDeployment),
			},
		},
		{
			"Filter events for undeclared-and-unmanaged resources",
			[]client.Object{
				deployment1,
			},
			[]action{
				{
					watch.Added,
					deployment2,
				},
				{
					watch.Added,
					deployment3,
				},
			},
			nil,
		},
		{
			"Filter events for declared resource with different manager",
			[]client.Object{
				deployment1,
			},
			[]action{
				{
					watch.Modified,
					deploymentForRoot,
				},
			},
			nil,
		},
		{
			"Filter events for declared resource with different GVK",
			[]client.Object{
				deployment1,
			},
			[]action{
				{
					watch.Modified,
					deployment1Beta,
				},
			},
			nil,
		},
		{
			"Handle bookmark events",
			[]client.Object{
				deployment1,
			},
			[]action{
				{
					watch.Modified,
					deployment1,
				},
				{
					watch.Bookmark,
					deployment1,
				},
			},
			[]core.ID{
				core.IDOf(deployment1),
			},
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			dr := &declared.Resources{}
			ctx := context.Background()
			if _, err := dr.Update(ctx, tc.declared); err != nil {
				t.Fatalf("unexpected error %v", err)
			}

			base := watch.NewFake()
			q := queue.New("test")
			cfg := watcherConfig{
				scope:     scope,
				syncName:  syncName,
				resources: dr,
				queue:     q,
				startWatch: func(options metav1.ListOptions) (watch.Interface, error) {
					return base, nil
				},
			}
			w := NewFiltered(ctx, cfg)

			go func() {
				for _, a := range tc.actions {
					// Each base.Action() blocks until the code within w.Run() reads its
					// event from the queue.
					base.Action(a.event, a.obj)
				}
				// This is not reached until after w.Run() reads the last event from the
				// queue.
				w.Stop()
			}()
			// w.Run() blocks until w.Stop() is called.
			if err := w.Run(ctx); err != nil {
				t.Fatalf("got Run() = %v, want Run() = <nil>", err)
			}

			var got []core.ID
			for q.Len() > 0 {
				obj, shutdown := q.Get()
				if shutdown {
					t.Fatal("Object queue was shut down unexpectedly.")
				}
				got = append(got, core.IDOf(obj))
			}

			if diff := cmp.Diff(tc.want, got); diff != "" {
				t.Errorf("did not get desired object IDs: %v", diff)
			}
		})
	}
}


text:
const path = require('path');
const test = require('tap').test;
const makeTestStorage = require('../fixtures/make-test-storage');
const extract = require('../fixtures/extract');
const VirtualMachine = require('../../src/index');

const projectUri = path.resolve(__dirname, '../fixtures/stack-click.sb2');
const project = extract(projectUri);

/**
 * stack-click.sb2 contains a sprite at (0, 0) with a single stack
 *     when timer > 100000000
 *         move 100 steps
 * The intention is to make sure that the stack can be activated by a stack click
 * even when the hat predicate is false.
 */
test('stack click activates the stack', t => {
    const vm = new VirtualMachine();
    vm.attachStorage(makeTestStorage());

    // Evaluate playground data and exit
    vm.on('playgroundData', () => {
        // The sprite should have moved 100 to the right
        t.equal(vm.editingTarget.x, 100);
        t.end();
        process.nextTick(process.exit);
    });

    // Start VM, load project, and run
    t.doesNotThrow(() => {
        vm.start();
        vm.clear();
        vm.setCompatibilityMode(false);
        vm.setTurboMode(false);
        vm.loadProject(project).then(() => {
            const blockContainer = vm.runtime.targets[1].blocks;
            const allBlocks = blockContainer._blocks;

            // Confirm the editing target is initially at 0
            t.equal(vm.editingTarget.x, 0);

            // Find hat for greater than and click it
            for (const blockId in allBlocks) {
                if (allBlocks[blockId].opcode === 'event_whengreaterthan') {
                    blockContainer.blocklyListen({
                        blockId: blockId,
                        element: 'stackclick'
                    }, vm.runtime);
                }
            }

            // After two seconds, get playground data and stop
            setTimeout(() => {
                vm.getPlaygroundData();
                vm.stopAll();
            }, 2000);
        });
    });
});


text:
package org.keycloak.services.scheduled;

import org.jboss.logging.Logger;
import org.keycloak.cluster.ClusterProvider;
import org.keycloak.cluster.ExecutionResult;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.timer.ScheduledTask;

import java.util.concurrent.Callable;

/**
 * Ensures that there are not concurrent executions of same task (either on this host or any other cluster host)
 *
 * @author Marek Posolda
 */
public class ClusterAwareScheduledTaskRunner extends ScheduledTaskRunner {

    private static final Logger logger = Logger.getLogger(ClusterAwareScheduledTaskRunner.class);

    private final int intervalSecs;

    public ClusterAwareScheduledTaskRunner(KeycloakSessionFactory sessionFactory, ScheduledTask task, long intervalMillis) {
        super(sessionFactory, task);
        this.intervalSecs = (int) (intervalMillis / 1000);
    }

    @Override
    protected void runTask(final KeycloakSession session) {
        session.getTransactionManager().begin();

        ClusterProvider clusterProvider = session.getProvider(ClusterProvider.class);
        String taskKey = task.getClass().getSimpleName();

        ExecutionResult<Void> result = clusterProvider.executeIfNotExecuted(taskKey, intervalSecs, new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                task.run(session);
                return null;
            }

        });

        session.getTransactionManager().commit();

        if (result.isExecuted()) {
            logger.debugf("Executed scheduled task %s", taskKey);
        } else {
            logger.debugf("Skipped execution of task %s as other cluster node is executing it", taskKey);
        }
    }

}


text:
describe('MapContaining', function() {
  it('matches any actual map to an empty map', function() {
    const actualMap = new Map([['foo', 'bar']]);
    const containing = new jasmineUnderTest.MapContaining(new Map());

    expect(containing.asymmetricMatch(actualMap)).toBe(true);
  });

  it('matches when all the key/value pairs in sample have matches in actual', function() {
    const actualMap = new Map([
      ['foo', [1, 2, 3]],
      [{ foo: 'bar' }, 'baz'],
      ['other', 'any']
    ]);

    const containingMap = new Map([
      [{ foo: 'bar' }, 'baz'],
      ['foo', [1, 2, 3]]
    ]);
    const containing = new jasmineUnderTest.MapContaining(containingMap);
    const matchersUtil = new jasmineUnderTest.MatchersUtil();

    expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(true);
  });

  it('does not match when a key is not in actual', function() {
    const actualMap = new Map([
      ['foo', [1, 2, 3]],
      [{ foo: 'not a bar' }, 'baz']
    ]);

    const containingMap = new Map([
      [{ foo: 'bar' }, 'baz'],
      ['foo', [1, 2, 3]]
    ]);
    const containing = new jasmineUnderTest.MapContaining(containingMap);
    const matchersUtil = new jasmineUnderTest.MatchersUtil();

    expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false);
  });

  it('does not match when a value is not in actual', function() {
    const actualMap = new Map([['foo', [1, 2, 3]], [{ foo: 'bar' }, 'baz']]);

    const containingMap = new Map([[{ foo: 'bar' }, 'baz'], ['foo', [1, 2]]]);
    const containing = new jasmineUnderTest.MapContaining(containingMap);
    const matchersUtil = new jasmineUnderTest.MatchersUtil();

    expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false);
  });

  it('matches when all the key/value pairs in sample have asymmetric matches in actual', function() {
    const actualMap = new Map([
      ['foo1', 'not a bar'],
      ['foo2', 'bar'],
      ['baz', [1, 2, 3, 4]]
    ]);

    const containingMap = new Map([
      [jasmineUnderTest.stringMatching(/^foo\d/), 'bar'],
      ['baz', jasmineUnderTest.arrayContaining([2, 3])]
    ]);
    const containing = new jasmineUnderTest.MapContaining(containingMap);
    const matchersUtil = new jasmineUnderTest.MatchersUtil();

    expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(true);
  });

  it('does not match when a key in sample has no asymmetric matches in actual', function() {
    const actualMap = new Map([['a-foo1', 'bar'], ['baz', [1, 2, 3, 4]]]);

    const containingMap = new Map([
      [jasmineUnderTest.stringMatching(/^foo\d/), 'bar'],
      ['baz', jasmineUnderTest.arrayContaining([2, 3])]
    ]);
    const containing = new jasmineUnderTest.MapContaining(containingMap);
    const matchersUtil = new jasmineUnderTest.MatchersUtil();

    expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false);
  });

  it('does not match when a value in sample has no asymmetric matches in actual', function() {
    const actualMap = new Map([['foo1', 'bar'], ['baz', [1, 2, 3, 4]]]);

    const containingMap = new Map([
      [jasmineUnderTest.stringMatching(/^foo\d/), 'bar'],
      ['baz', jasmineUnderTest.arrayContaining([4, 5])]
    ]);
    const containing = new jasmineUnderTest.MapContaining(containingMap);
    const matchersUtil = new jasmineUnderTest.MatchersUtil();

    expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false);
  });

  it('matches recursively', function() {
    const actualMap = new Map([
      ['foo', new Map([['foo1', 1], ['foo2', 2]])],
      [new Map([[1, 'bar1'], [2, 'bar2']]), 'bar'],
      ['other', 'any']
    ]);

    const containingMap = new Map([
      ['foo', new jasmineUnderTest.MapContaining(new Map([['foo1', 1]]))],
      [new jasmineUnderTest.MapContaining(new Map([[2, 'bar2']])), 'bar']
    ]);
    const containing = new jasmineUnderTest.MapContaining(containingMap);
    const matchersUtil = new jasmineUnderTest.MatchersUtil();

    expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(true);
  });

  it('uses custom equality testers', function() {
    function tester(a, b) {
      // treat all negative numbers as equal
      return typeof a == 'number' && typeof b == 'number'
        ? a < 0 && b < 0
        : a === b;
    }
    const actualMap = new Map([['foo', -1]]);
    const containing = new jasmineUnderTest.MapContaining(
      new Map([['foo', -2]])
    );
    const matchersUtil = new jasmineUnderTest.MatchersUtil({
      customTesters: [tester]
    });

    expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(true);
  });

  it('does not match when actual is not a map', function() {
    const containingMap = new Map([['foo', 'bar']]);
    expect(
      new jasmineUnderTest.MapContaining(containingMap).asymmetricMatch('foo')
    ).toBe(false);
    expect(
      new jasmineUnderTest.MapContaining(containingMap).asymmetricMatch(-1)
    ).toBe(false);
    expect(
      new jasmineUnderTest.MapContaining(containingMap).asymmetricMatch({
        foo: 'bar'
      })
    ).toBe(false);
  });

  it('throws an error when sample is not a map', function() {
    expect(function() {
      new jasmineUnderTest.MapContaining({ foo: 'bar' }).asymmetricMatch(
        new Map()
      );
    }).toThrowError(/You must provide a map/);
  });

  it('defines a `jasmineToString` method', function() {
    const sample = new Map(),
      containing = new jasmineUnderTest.MapContaining(sample),
      pp = jasmine.createSpy('pp').and.returnValue('sample');

    expect(containing.jasmineToString(pp)).toEqual(
      '<jasmine.mapContaining(sample)>'
    );
    expect(pp).toHaveBeenCalledWith(sample);
  });
});


text:
package com.uzielasto.app.prot;

import javax.media.CaptureDeviceInfo;
import javax.media.cdm.CaptureDeviceManager;
import javax.media.format.VideoFormat;
import javax.sound.sampled.AudioFormat;
/**
 * Created with IntelliJ IDEA.
 * User: Aleksandr
 * Date: 10.11.12
 * Time: 18:32
 * All rights recieved.(c)
 */
public class GetDeviceList
{

    private static CaptureDeviceInfo captureVideoDevice = null;
    private static CaptureDeviceInfo    captureAudioDevice = null;
    private static VideoFormat captureVideoFormat = null;
    private static AudioFormat          captureAudioFormat = null;

    public static void devicelist()
{
    java.util.Vector deviceListVector = CaptureDeviceManager.getDeviceList();

    if (deviceListVector == null)
    {
        System.out.println("... error: media device list vector is null, program aborted");

    }
    if (deviceListVector.size() == 0)
    {
        System.out.println("... error: media device list vector size is 0, program aborted");

    }

    System.out.println("... list completed.");

}
}


text:
jxcore.utils.
  console.log('Extracting the binaries', 'yellow');

if (process.argv[2] == "EXTRACT") {
  var AdmZip = require('adm-zip');

  var zip = new AdmZip("./io.jxcore.node/bin/ios.zip");
  zip.extractAllTo("./io.jxcore.node/bin/", true);
} else {

  require("child_process").execFile(process.execPath, ["io.jxcore.node/index.js", "EXTRACT"],
    {cwd: process.cwd()}, function (error, stdout, stderr) {

      if (error) {
        console.error("Something bad happened with the extraction:\n", stdout, "\n", stderr);
        process.exit(1);
      }

      jxcore.utils.
        console.log('DONE\n\nJXcore Cordova Plugin is available under io.jxcore.node/ folder.', 'green');

      jxcore.utils.
        console.log('type: ', 'yellow');

      jxcore.utils.
        console.log('cordova plugins add io.jxcore.node/');

      jxcore.utils.
        console.log('to install the plugin', 'yellow');

      require('fs').unlinkSync("io.jxcore.node.jx");
      require('fs').unlinkSync("io.jxcore.node/bin/ios.zip");
    });
}


text:
package gwt.material.design.addins.client.fileuploader.js;

import com.google.gwt.dom.client.Element;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;

@JsType(isNative = true, name = "Blob", namespace = JsPackage.GLOBAL)
public class Blob {

    public Blob() {
    }

    public Blob(Object[] arr) {}

    public Blob(Object[] blob, String name) {
    }

    @JsProperty
    public String name;

    @JsProperty
    public String lastModifiedDate;

    @JsProperty
    public String size;

    @JsProperty
    public String type;

    @JsProperty
    public XHR xhr;

    @JsProperty
    public Element previewElement;
}


text:
#include "OgreVolumeHalfFloatGridSource.h"
#include "OgreRoot.h"
#include "OgreDeflate.h"
#include "OgreStreamSerialiser.h"
#include "OgreBitwise.h"
#include "OgreMemoryAllocatorConfig.h"
#include "OgreLogManager.h"
#include "OgreTimer.h"

namespace Ogre {
namespace Volume {

    float HalfFloatGridSource::getVolumeGridValue(size_t x, size_t y, size_t z) const
    {
        x = x >= mWidth ? mWidth - 1 : x;
        y = y >= mHeight ? mHeight - 1 : y;
        z = z >= mDepth ? mDepth - 1 : z;
        return Bitwise::halfToFloat(mData[(mDepth - z - 1) * mDepthTimesHeight + x * mHeight + y]);
    }

    //-----------------------------------------------------------------------

    void HalfFloatGridSource::setVolumeGridValue(int x, int y, int z, float value)
    {

        // Clamp if wanted.
        if (mMaxClampedAbsoluteDensity != (Real)0.0 && Math::Abs(value) > mMaxClampedAbsoluteDensity)
        {
            value = mMaxClampedAbsoluteDensity;
        }

        mData[(mDepth - z - 1) * mDepthTimesHeight + x * mHeight + y] = Bitwise::floatToHalf(value);
    }

    //-----------------------------------------------------------------------

    HalfFloatGridSource::HalfFloatGridSource(const String &serializedVolumeFile, const bool trilinearValue, const bool trilinearGradient, const bool sobelGradient) :
        GridSource(trilinearValue, trilinearGradient, sobelGradient)
    {

        Timer t;
        DataStreamPtr streamRead = Root::getSingleton().openFileStream(serializedVolumeFile);
#if OGRE_NO_ZIP_ARCHIVE == 0
        DataStreamPtr uncompressStream(OGRE_NEW DeflateStream(serializedVolumeFile, streamRead));
        StreamSerialiser ser(uncompressStream);
#else
        StreamSerialiser ser(streamRead);
#endif
        if (!ser.readChunkBegin(VOLUME_CHUNK_ID, VOLUME_CHUNK_VERSION))
        {
            OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                "Invalid volume file given!",
                __FUNCTION__);
        }

        // Read header
        Vector3 readFrom, readTo;
        ser.read(&readFrom);
        ser.read(&readTo);
        float voxelWidth;
        ser.read<float>(&voxelWidth);
        size_t width, height, depth;
        ser.read<size_t>(&width);
        ser.read<size_t>(&height);
        ser.read<size_t>(&depth);
        mWidth = static_cast<int>(width);
        mHeight = static_cast<int>(height);
        mDepth = static_cast<int>(depth);
        mDepthTimesHeight = static_cast<int>(mDepth * mHeight);

        Vector3 worldDimension = readTo - readFrom;
        mPosXScale = (Real)1.0 / (Real)worldDimension.x * (Real)mWidth;
        mPosYScale = (Real)1.0 / (Real)worldDimension.y * (Real)mHeight;
        mPosZScale = (Real)1.0 / (Real)worldDimension.z * (Real)mDepth;

        mVolumeSpaceToWorldSpaceFactor = (Real)worldDimension.x * (Real)mWidth;
        mMaxClampedAbsoluteDensity = 0;

        // Read data
        size_t elementCount = mWidth * mHeight * mDepth;
        mData = OGRE_ALLOC_T(uint16, elementCount, MEMCATEGORY_GENERAL);
        ser.read(mData, elementCount);

        ser.readChunkEnd(VOLUME_CHUNK_ID);

        LogManager::getSingleton().stream() << "Processed serialization in " << t.getMilliseconds() << "ms.";
    }

    //-----------------------------------------------------------------------

    void HalfFloatGridSource::setMaxClampedAbsoluteDensity(Real maxClampedAbsoluteDensity)
    {
        mMaxClampedAbsoluteDensity = maxClampedAbsoluteDensity;
    }

    //-----------------------------------------------------------------------

    Real HalfFloatGridSource::getMaxClampedAbsoluteDensity(void) const
    {
        return mMaxClampedAbsoluteDensity;
    }

    //-----------------------------------------------------------------------

    HalfFloatGridSource::~HalfFloatGridSource(void)
    {
        OGRE_FREE(mData, MEMCATEGORY_GENERAL);
    }
}
}


text:
package com.zhihu.matisse.internal.entity;

public class CaptureStrategy {

    public final boolean isPublic;
    public final String authority;

    public CaptureStrategy(boolean isPublic, String authority) {
        this.isPublic = isPublic;
        this.authority = authority;
    }
}


text:
require 'vines/services'
require 'minitest/autorun'

describe Vines::Services::Config do
  def teardown
    FileUtils.rm(Dir.glob('localhost-*.db'))
    %w[data uploads].each do |dir|
      FileUtils.remove_dir(dir) if File.exist?(dir)
    end
  end

  def test_missing_host_raises
    assert_raises(RuntimeError) do
      Vines::Services::Config.new do
        # missing domain
      end
    end
  end

  def test_multiple_domains_raises
    assert_raises(RuntimeError) do
      Vines::Services::Config.new do
        host 'vines.wonderland.lit', 'vines.wonderland.lit' do
          upstream 'localhost', 5347, 'secr3t'
          storage 'couchdb' do
            host 'localhost'
            port 5984
            database 'wonderland_lit'
            tls false
            username ''
            password ''
            index_dir '.'
          end
        end
      end
    end
  end

  def test_configure
    config = Vines::Services::Config.configure do
      host 'vines.wonderland.lit' do
        upstream 'localhost', 5347, 'secr3t'
        storage 'couchdb' do
          host 'localhost'
          port 5984
          database 'wonderland_lit'
          tls false
          username ''
          password ''
          index_dir '.'
        end
      end
    end
    refute_nil config
    assert_same config, Vines::Services::Config.instance
  end

  def test_default_upload_directory
    config = Vines::Services::Config.configure do
      host 'vines.wonderland.lit' do
        upstream 'localhost', 5347, 'secr3t'
        storage 'couchdb' do
          host 'localhost'
          port 5984
          database 'wonderland_lit'
          tls false
          username ''
          password ''
          index_dir '.'
        end
      end
    end
    assert File.exist?('data/upload')
  end

  def test_custom_upload_directory
    config = Vines::Services::Config.configure do
      host 'vines.wonderland.lit' do
        upstream 'localhost', 5347, 'secr3t'
        uploads 'uploads'
        storage 'couchdb' do
          host 'localhost'
          port 5984
          database 'wonderland_lit'
          tls false
          username ''
          password ''
          index_dir '.'
        end
      end
    end
    assert File.exist?('uploads')
  end

  def test_missing_upstream_raises
    assert_raises(RuntimeError) do
      Vines::Services::Config.new do
        host 'vines.wonderland.lit' do
          storage 'couchdb' do
            host 'localhost'
            port 5984
            database 'wonderland_lit'
            tls false
            username ''
            password ''
            index_dir '.'
          end
        end
      end
    end
  end

  def test_invalid_upstream_raises
    assert_raises(RuntimeError) do
      Vines::Services::Config.new do
        host 'vines.wonderland.lit' do
          upstream 'localhost', 5347, nil
          storage 'couchdb' do
            host 'localhost'
            port 5984
            database 'wonderland_lit'
            tls false
            username ''
            password ''
            index_dir '.'
          end
        end
      end
    end
  end

  def test_missing_storage_raises
    assert_raises(RuntimeError) do
      Vines::Services::Config.new do
        host 'vines.wonderland.lit' do
          upstream 'localhost', 5347, 'secr3t'
        end
      end
    end
  end

  def test_duplicate_storage_raises
    assert_raises(RuntimeError) do
      Vines::Services::Config.new do
        host 'vines.wonderland.lit' do
          upstream 'localhost', 5347, 'secr3t'
          storage 'couchdb' do
            host 'localhost'
            port 5984
            database 'wonderland_lit'
            tls false
            username ''
            password ''
            index_dir '.'
          end
          storage 'couchdb' do
            host 'localhost'
            port 5984
            database 'wonderland_lit'
            tls false
            username ''
            password ''
            index_dir '.'
          end
        end
      end
    end
  end

  def test_multiple_domains
    config = Vines::Services::Config.new do
      host 'vines.wonderland.lit' do
        upstream 'localhost', 5347, 'secr3t'
        storage 'couchdb' do
          host 'localhost'
          port 5984
          database 'wonderland_lit'
          tls false
          username ''
          password ''
          index_dir '.'
        end
      end
      host 'vines.verona.lit' do
        upstream 'localhost', 5347, 'secr3t'
        storage 'couchdb' do
          host 'localhost'
          port 5984
          database 'verona_lit'
          tls false
          username ''
          password ''
          index_dir '.'
        end
      end
    end
    assert_equal 2, config.vhosts.size
    assert_equal 'vines.wonderland.lit', config.vhosts['vines.wonderland.lit'].name
    assert_equal 'vines.verona.lit', config.vhosts['vines.verona.lit'].name
  end

  def test_invalid_log_level
    assert_raises(RuntimeError) do
      config = Vines::Services::Config.new do
        log 'bogus'
        host 'vines.wonderland.lit' do
          upstream 'localhost', 5347, 'secr3t'
          storage 'couchdb' do
            host 'localhost'
            port 5984
            database 'wonderland_lit'
            tls false
            username ''
            password ''
            index_dir '.'
          end
        end
      end
    end
  end

  def test_valid_log_level
    config = Vines::Services::Config.new do
      log :error
      host 'vines.wonderland.lit' do
        upstream 'localhost', 5347, 'secr3t'
        storage 'couchdb' do
          host 'localhost'
          port 5984
          database 'wonderland_lit'
          tls false
          username ''
          password ''
          index_dir '.'
        end
      end
    end
    assert_equal Logger::ERROR, Class.new.extend(Vines::Log).log.level
  end
end


text:
import { createElement } from 'react';
import { renderToString } from 'react-dom/server';
import {
  ApolloClient,
  getDataFromTree,
  ApolloProvider,
} from 'react-apollo';
import { createExpressRouter } from 'laosdirg-router';

import createStore from '../shared/createStore.js';
import createApolloClient from '../shared/createApolloClient.js';
import Root from '../shared/containers/Root.js';
import routes from '../shared/routes.js';

export default async (req, res) => {
  console.log("=====REQEUSET====")
  const apolloClient = createApolloClient();
  const router = createExpressRouter(routes, req, { apolloClient });

  // create new redux store instance for each request
  const store = createStore({
    apollo: {
      reducer: apolloClient.reducer(),
      middleware: apolloClient.middleware(),
    },
    router,
  });

  // create root element
  const element = createElement(
    ApolloProvider,
    { client: apolloClient, store },
    createElement(Root),
  );

  // route initial and handle redirects
  /*await router.route();
  const routerState = store.getState().router;
  if (routerState.locationChanged) {
    return res.redirect(routerState.location);
  }*/

  // let apollo fetch all its data
  await getDataFromTree(element);

  // render the element to a string
  const body = renderToString(element);

  // grab initial state from our Redux store
  const state = store.getState();
  const dehydrated = JSON.stringify(state).replace(/</g, '\\u003c');

  // send the rendered page back to the client
  return res.render('react', { body, state: dehydrated });
};


text:
<!DOCTYPE html>

    <title>WhoPaysWhat</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/people.css">

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

            </button>
            WhoPaysWhat

Home

Configuration

People

Name the people

Please put a name to everbody!

    <form method="post" onsubmit="return false;" id="form" role="form">
        <input type="submit" value="Go!" id="go" class="btn btn-primary">
    </form>


text:
package io.wcm.caravan.commons.httpasyncclient.impl;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.nio.client.HttpAsyncClient;
import org.apache.sling.commons.osgi.Order;
import org.apache.sling.commons.osgi.ServiceUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;

import io.wcm.caravan.commons.httpasyncclient.HttpAsyncClientFactory;
import io.wcm.caravan.commons.httpclient.HttpClientConfig;
import io.wcm.caravan.commons.httpclient.impl.helpers.DefaultHttpClientConfig;

/**
 * Default implementation of {@link HttpAsyncClientFactory}.
 */
@Component(service = HttpAsyncClientFactory.class, immediate = true, reference = {
    @Reference(name = "httpClientConfig", service = HttpClientConfig.class,
        cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC,
        bind = "bindHttpClientConfig", unbind = "unbindHttpClientConfig")
})
public class HttpAsyncClientFactoryImpl implements HttpAsyncClientFactory {

  private final ConcurrentMap<Comparable<Object>, HttpAsyncClientItem> factoryItems = new ConcurrentSkipListMap<>();

  private HttpAsyncClientItem defaultFactoryItem;

  @Activate
  private void activate() {
    defaultFactoryItem = new HttpAsyncClientItem(DefaultHttpClientConfig.INSTANCE);
  }

  @Deactivate
  private void deactivate() {
    for (HttpAsyncClientItem item : factoryItems.values()) {
      item.close();
    }
    factoryItems.clear();
    defaultFactoryItem.close();
    defaultFactoryItem = null;
  }

  protected void bindHttpClientConfig(HttpClientConfig httpClientConfig, Map<String, Object> config) {
    factoryItems.put(ServiceUtil.getComparableForServiceRanking(config, Order.ASCENDING), new HttpAsyncClientItem(httpClientConfig));
  }

  @SuppressWarnings("unused")
  protected void unbindHttpClientConfig(HttpClientConfig httpClientConfig, Map<String, Object> config) {
    HttpAsyncClientItem removed = factoryItems.remove(ServiceUtil.getComparableForServiceRanking(config, Order.ASCENDING));
    if (removed != null) {
      removed.close();
    }
  }

  @Override
  public @NotNull HttpAsyncClient get(@Nullable String targetUrl) {
    return getCloseable(targetUrl);
  }

  @Override
  public @NotNull CloseableHttpAsyncClient getCloseable(@Nullable String targetUrl) {
    final URI uri = toUri(targetUrl);
    final String path = uri != null ? uri.getPath() : null;
    return getFactoryItem(uri, null, path, false).getHttpAsyncClient();
  }

  @Override
  public @NotNull HttpAsyncClient get(@Nullable URI targetUrl) {
    return getCloseable(targetUrl);
  }

  @Override
  public @NotNull CloseableHttpAsyncClient getCloseable(@Nullable URI targetUrl) {
    final String path = targetUrl != null ? targetUrl.getPath() : null;
    return getFactoryItem(targetUrl, null, path, false).getHttpAsyncClient();
  }

  @Override
  public @NotNull HttpAsyncClient getWs(@Nullable String targetUrl, @Nullable String wsAddressingToUri) {
    return getCloseableWs(targetUrl, wsAddressingToUri);
  }

  @Override
  public @NotNull CloseableHttpAsyncClient getCloseableWs(@Nullable String targetUrl, @Nullable String wsAddressingToUri) {
    final URI uri = toUri(targetUrl);
    final String path = uri != null ? uri.getPath() : null;
    return getFactoryItem(uri, wsAddressingToUri, path, true).getHttpAsyncClient();
  }

  @Override
  public @NotNull HttpAsyncClient getWs(@Nullable URI targetUrl, @Nullable URI wsAddressingToUri) {
    return getCloseableWs(targetUrl, wsAddressingToUri);
  }

  @Override
  public @NotNull CloseableHttpAsyncClient getCloseableWs(@Nullable URI targetUrl, @Nullable URI wsAddressingToUri) {
    String wsAddressingToUriString = wsAddressingToUri != null ? wsAddressingToUri.toString() : null;
    String path = targetUrl != null ? targetUrl.getPath() : null;
    return getFactoryItem(targetUrl, wsAddressingToUriString, path, true).getHttpAsyncClient();
  }

  @Override
  public @NotNull RequestConfig getDefaultRequestConfig(@Nullable String targetUrl) {
    final URI uri = toUri(targetUrl);
    return getDefaultRequestConfig(uri);
  }

  @Override
  public @NotNull RequestConfig getDefaultRequestConfig(@Nullable URI targetUrl) {
    String path = targetUrl != null ? targetUrl.getPath() : null;
    return getFactoryItem(targetUrl, null, path, false).getDefaultRequestConfig();
  }

  private @NotNull HttpAsyncClientItem getFactoryItem(@Nullable URI targetUrl, @Nullable String wsAddressingToUri, @Nullable String path, boolean isWsCall) {
    for (HttpAsyncClientItem item : factoryItems.values()) {
      String host = targetUrl != null ? targetUrl.getHost() : null;
      if (item.matches(host, wsAddressingToUri, path, isWsCall)) {
        return item;
      }
    }
    return defaultFactoryItem;
  }

  private @Nullable URI toUri(@Nullable String uri) {
    if (StringUtils.isEmpty(uri)) {
      return null;
    }
    else {
      try {
        return new URI(uri);
      }
      catch (URISyntaxException ex) {
        throw new IllegalArgumentException("Invalid URI: " + ex.getMessage(), ex);
      }
    }
  }

}


text:
inline float
RAND_01_f() {
  return float(rand())/float(RAND_MAX);
}

namespace GAME {

ParticlesSystem::
ParticlesSystem() noexcept
  : batches_used {0}
{}

void
ParticlesSystem::
add_batch(const ParticlesBatchSetup& setup) noexcept {
  if (batches_used == PARTICLE_BATCHES_MAX) {
    return;
  }

  auto& batch = batches[batches_used];
  batch.img = setup.img;
  batch.ms_duration = setup.ms_duration;
  batch.ms_start = setup.ms_start;
  batch.color = setup.color;
  batch.start_position = setup.start_position;

  const float base_angle = setup.center_out_angle - setup.spread_angle*0.5f;
  const float d_vel = setup.ms_max_vel - setup.ms_min_vel;

  for (auto& particle : batch.particles) {
    const float angle = base_angle + RAND_01_f()*setup.spread_angle;
    const float vel = setup.ms_min_vel + RAND_01_f()*d_vel;
    particle = {
      xMATH::Float2 {std::cos(angle)*vel, std::sin(angle)*vel},
      float {RAND_01_f()*2.0f*xMATH::PI<float>()}
    };
  }

  batches_used++;
}

void
ParticlesSystem::
update_and_render(GRAL::Screen *screen, uint32_t ms_now) {
  int i = 0;

  while (i < batches_used) {
    ParticlesBatch &batch = batches[i];
    float dt = ms_now - batch.ms_start;

    if (dt > batch.ms_duration) {
      batch = batches[batches_used-1];
      batches_used--;
      continue;
    }

    float t = dt / batch.ms_duration;

    // -4t(t-1) goes from (0,0), (0.5, 1), (1, 0) in a quadratic fashion;
    // 0.5 being where it's at its max.
    float fact = -t*(t-1.0f)*4.0f;

    GRAL::AlphaModGuard alpha_mod_guard(batch.img, fact*255);
    GRAL::ColorModGuard color_mod_guard(batch.img, batch.color);
    GRAL::BlendModeGuard blend_mode_guard(batch.img, SDL_BLENDMODE_ADD);

    for (const auto& particle : batch.particles) {
      xMATH::Float2 d_pos = dt*particle.vel;
      xMATH::Float2 pos = batch.start_position + d_pos;
      screen->draw_image(batch.img, pos, particle.angle);
    }

    i++;
  }
}

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE321_Hard_Coded_Cryptographic_Key__w32_char_62b.cpp
Label Definition File: CWE321_Hard_Coded_Cryptographic_Key__w32.label.xml
Template File: sources-sink-62b.tmpl.cpp
*/
/*
 * @description
 * CWE: 321 Use of Hard-coded Cryptographic Key
 * BadSource:  Copy a hardcoded value into cryptoKey
 * GoodSource: Read cryptoKey from the console
 * Sinks:
 *    BadSink : Hash cryptoKey and use the value to encrypt a string
 * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#define CRYPTO_KEY "Hardcoded"

namespace CWE321_Hard_Coded_Cryptographic_Key__w32_char_62
{

#ifndef OMITBAD

void badSource(char * &cryptoKey)
{
    /* FLAW: Use a hardcoded value for the hash input causing a hardcoded crypto key in the sink */
    strcpy(cryptoKey, CRYPTO_KEY);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
void goodG2BSource(char * &cryptoKey)
{
    {
        size_t cryptoKeyLen = strlen(cryptoKey);
        /* if there is room in cryptoKey, read into it from the console */
        if(100-cryptoKeyLen > 1)
        {
            /* FIX: Obtain the hash input from the console */
            if (fgets(cryptoKey+cryptoKeyLen, (int)(100-cryptoKeyLen), stdin) == NULL)
            {
                printLine("fgets() failed");
                /* Restore NUL terminator if fgets fails */
                cryptoKey[cryptoKeyLen] = '\0';
            }
            /* The next 3 lines remove the carriage return from the string that is
             * inserted by fgets() */
            cryptoKeyLen = strlen(cryptoKey);
            if (cryptoKeyLen > 0)
            {
                cryptoKey[cryptoKeyLen-1] = '\0';
            }
        }
    }
}

#endif /* OMITGOOD */

} /* close namespace */