text:
package scaleionodes

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
	"time"

	log "github.com/Sirupsen/logrus"
	xplatform "github.com/dvonthenen/goxplatform"
	xplatformsys "github.com/dvonthenen/goxplatform/sys"

	config "github.com/codedellemc/scaleio-framework/scaleio-executor/config"
	common "github.com/codedellemc/scaleio-framework/scaleio-executor/executor/common"
	ubuntu14 "github.com/codedellemc/scaleio-framework/scaleio-executor/executor/pkgmgr/deb/ubuntu14"
	mgr "github.com/codedellemc/scaleio-framework/scaleio-executor/executor/pkgmgr/mgr"
	rhel7 "github.com/codedellemc/scaleio-framework/scaleio-executor/executor/pkgmgr/rpm/rhel7"
	types "github.com/codedellemc/scaleio-framework/scaleio-scheduler/types"
)

//ScaleioPrimaryMdmNode implementation for ScaleIO Primary MDM Node
type ScaleioPrimaryMdmNode struct {
	common.ScaleioNode
	PkgMgr mgr.IMdmMgr
}

//NewPri generates a Primary MDM Node object
func NewPri(state *types.ScaleIOFramework, cfg *config.Config, getstate common.RetrieveState) *ScaleioPrimaryMdmNode {
	myNode := &ScaleioPrimaryMdmNode{}
	myNode.Config = cfg
	myNode.GetState = getstate
	myNode.RebootRequired = false

	var pkgmgr mgr.IMdmMgr
	switch xplatform.GetInstance().Sys.GetOsType() {
	case xplatformsys.OsRhel:
		log.Infoln("Is RHEL7")
		pkgmgr = rhel7.NewMdmRpmRhel7Mgr(state)
	case xplatformsys.OsUbuntu:
		log.Infoln("Is Ubuntu14")
		pkgmgr = ubuntu14.NewMdmDebUbuntu14Mgr(state)
	}
	myNode.PkgMgr = pkgmgr

	return myNode
}

//RunStateUnknown default action for StateUnknown
func (spmn *ScaleioPrimaryMdmNode) RunStateUnknown() {
	reboot, err := spmn.PkgMgr.EnvironmentSetup(spmn.State)
	if err != nil {
		log.Errorln("EnvironmentSetup Failed:", err)
		errState := spmn.UpdateNodeState(types.StateFatalInstall)
		if errState != nil {
			log.Errorln("Failed to signal state change:", errState)
		} else {
			log.Debugln("Signaled StateFatalInstall")
		}
		return
	}

	errState := spmn.UpdateNodeState(types.StateCleanPrereqsReboot)
	if errState != nil {
		log.Errorln("Failed to signal state change:", errState)
	} else {
		log.Debugln("Signaled StateCleanPrereqsReboot")
	}

	common.WaitForCleanPrereqsReboot(spmn)

	errState = spmn.UpdateNodeState(types.StatePrerequisitesInstalled)
	if errState != nil {
		log.Errorln("Failed to signal state change:", errState)
	} else {
		log.Debugln("Signaled StatePrerequisitesInstalled")
	}

	//requires a reboot?
	if reboot {
		log.Infoln("Reboot required before StatePrerequisitesInstalled!")

		if spmn.State.Debug {
			log.Infoln("Skipping the reboot since Debug is TRUE")
		} else {
			ip1, err1 := xplatform.GetInstance().Nw.AutoDiscoverIP()
			ip2, err2 := spmn.Config.ParseIPFromRestURI()

			if err1 == nil && err2 == nil && ip1 == ip2 {
				log.Infoln("Delay reboot host running the Scheduler")
				time.Sleep(time.Duration(common.DelayForRebootInSeconds) * time.Second)
			}

			rebootErr := xplatform.GetInstance().Run.Command(common.RebootCmdline, common.RebootCheck, "")
			if rebootErr != nil {
				log.Errorln("Install Kernel Failed:", rebootErr)
			}

			time.Sleep(time.Duration(common.WaitForRebootInSeconds) * time.Second)
		}
	} else {
		log.Infoln("No need to reboot while installing prerequisites")
	}
}

//RunStatePrerequisitesInstalled default action for StatePrerequisitesInstalled
func (spmn *ScaleioPrimaryMdmNode) RunStatePrerequisitesInstalled() {
	common.WaitForPrereqsFinish(spmn)
	err := spmn.PkgMgr.ManagementSetup(spmn.State, true)
	if err != nil {
		log.Errorln("ManagementSetup Failed:", err)
		errState := spmn.UpdateNodeState(types.StateFatalInstall)
		if errState != nil {
			log.Errorln("Failed to signal state change:", errState)
		} else {
			log.Debugln("Signaled StateFatalInstall")
		}
		return
	}

	err = spmn.PkgMgr.NodeSetup(spmn.State)
	if err != nil {
		log.Errorln("NodeSetup Failed:", err)
		errState := spmn.UpdateNodeState(types.StateFatalInstall)
		if errState != nil {
			log.Errorln("Failed to signal state change:", errState)
		} else {
			log.Debugln("Signaled StateFatalInstall")
		}
		return
	}

	err = spmn.UpdateDevices()
	if err != nil {
		log.Errorln("UpdateDevices Failed:", err)
		errState := spmn.UpdateNodeState(types.StateFatalInstall)
		if errState != nil {
			log.Errorln("Failed to signal state change:", errState)
		} else {
			log.Debugln("Signaled StateFatalInstall")
		}
		return
	}

	errState := spmn.UpdateNodeState(types.StateBasePackagedInstalled)
	if errState != nil {
		log.Errorln("Failed to signal state change:", errState)
	} else {
		log.Debugln("Signaled StateBasePackagedInstalled")
	}
}

//RunStateBasePackagedInstalled default action for StateBasePackagedInstalled
func (spmn *ScaleioPrimaryMdmNode) RunStateBasePackagedInstalled() {
	common.WaitForBaseFinish(spmn)
	err := spmn.PkgMgr.CreateCluster(spmn.State)
	if err != nil {
		log.Errorln("CreateCluster Failed:", err)
		errState := spmn.UpdateNodeState(types.StateFatalInstall)
		if errState != nil {
			log.Errorln("Failed to signal state change:", errState)
		} else {
			log.Debugln("Signaled StateFatalInstall")
		}
		return
	}

	err = spmn.UpdateCluster()
	if err != nil {
		log.Errorln("UpdateCluster Failed:", err)
		errState := spmn.UpdateNodeState(types.StateFatalInstall)
		if errState != nil {
			log.Errorln("Failed to signal state change:", errState)
		} else {
			log.Debugln("Signaled StateFatalInstall")
		}
		return
	}

	errState := spmn.UpdateNodeState(types.StateInitializeCluster)
	if errState != nil {
		log.Errorln("Failed to signal state change:", errState)
	} else {
		log.Debugln("Signaled StateInitializeCluster")
	}
}

//RunStateInitializeCluster default action for StateInitializeCluster
func (spmn *ScaleioPrimaryMdmNode) RunStateInitializeCluster() {
	common.WaitForClusterInstallFinish(spmn)
	reboot, err := spmn.PkgMgr.GatewaySetup(spmn.State)
	if err != nil {
		log.Errorln("GatewaySetup Failed:", err)
		errState := spmn.UpdateNodeState(types.StateFatalInstall)
		if errState != nil {
			log.Errorln("Failed to signal state change:", errState)
		} else {
			log.Debugln("Signaled StateFatalInstall")
		}
		return
	}
	spmn.RebootRequired = spmn.RebootRequired || reboot

	errState := spmn.UpdateNodeState(types.StateAddResourcesToScaleIO)
	if errState != nil {
		log.Errorln("Failed to signal state change:", errState)
	} else {
		log.Debugln("Signaled StateAddResourcesToScaleIO")
	}
}

//RunStateInstallRexRay default action for StateInstallRexRay
func (spmn *ScaleioPrimaryMdmNode) RunStateInstallRexRay() {
	reboot, err := spmn.PkgMgr.RexraySetup(spmn.State, spmn.Config.ExecutorID)
	if err != nil {
		log.Errorln("REX-Ray setup Failed:", err)
		errState := spmn.UpdateNodeState(types.StateFatalInstall)
		if errState != nil {
			log.Errorln("Failed to signal state change:", errState)
		} else {
			log.Debugln("Signaled StateFatalInstall")
		}
		return
	}
	spmn.RebootRequired = spmn.RebootRequired || reboot

	err = spmn.PkgMgr.SetupIsolator(spmn.State)
	if err != nil {
		log.Errorln("Mesos Isolator setup Failed:", err)
		errState := spmn.UpdateNodeState(types.StateFatalInstall)
		if errState != nil {
			log.Errorln("Failed to signal state change:", errState)
		} else {
			log.Debugln("Signaled StateFatalInstall")
		}
		return
	}

	errState := spmn.UpdateNodeState(types.StateCleanInstallReboot)
	if errState != nil {
		log.Errorln("Failed to signal state change:", errState)
	} else {
		log.Debugln("Signaled StateCleanInstallReboot")
	}

	common.WaitForCleanInstallReboot(spmn)

	//requires a reboot?
	if spmn.RebootRequired {
		log.Infoln("Reboot required before StateFinishInstall!")
		log.Debugln("rebootRequired:", spmn.RebootRequired)

		errState := spmn.UpdateNodeState(types.StateSystemReboot)
		if errState != nil {
			log.Errorln("Failed to signal state change:", errState)
		} else {
			log.Debugln("Signaled StateSystemReboot")
		}

		if spmn.State.Debug {
			log.Infoln("Skipping the reboot since Debug is TRUE")
		} else {
			ip1, err1 := xplatform.GetInstance().Nw.AutoDiscoverIP()
			ip2, err2 := spmn.Config.ParseIPFromRestURI()

			if err1 == nil && err2 == nil && ip1 == ip2 {
				log.Infoln("Delay reboot host running the Scheduler")
				time.Sleep(time.Duration(common.DelayForRebootInSeconds) * time.Second)
			}

			rebootErr := xplatform.GetInstance().Run.Command(common.RebootCmdline, common.RebootCheck, "")
			if rebootErr != nil {
				log.Errorln("Install Kernel Failed:", rebootErr)
			}

			time.Sleep(time.Duration(common.WaitForRebootInSeconds) * time.Second)
		}
	} else {
		log.Infoln("No need to reboot while installing REX-Ray")

		errState := spmn.UpdateNodeState(types.StateFinishInstall)
		if errState != nil {
			log.Errorln("Failed to signal state change:", errState)
		} else {
			log.Debugln("Signaled StateFinishInstall")
		}
	}
}

//RunStateSystemReboot default action for StateSystemReboot
func (spmn *ScaleioPrimaryMdmNode) RunStateSystemReboot() {
	errState := spmn.UpdateNodeState(types.StateFinishInstall)
	if errState != nil {
		log.Errorln("Failed to signal state change:", errState)
	} else {
		log.Debugln("Signaled StateFinishInstall")
	}
}

//RunStateFinishInstall default action for StateFinishInstall
func (spmn *ScaleioPrimaryMdmNode) RunStateFinishInstall() {
	node := spmn.GetSelfNode()
	if !node.Imperative && !node.Advertised {
		err := spmn.UpdateDevices()
		if err == nil {
			log.Infoln("UpdateDevices() Succcedeed. Devices advertised!")
		} else {
			log.Errorln("UpdateDevices() Failed. Err:", err)
		}
	}

	log.Debugln("In StateFinishInstall. Wait for", common.PollForChangesInSeconds,
		"seconds for changes in the cluster.")
	time.Sleep(time.Duration(common.PollForChangesInSeconds) * time.Second)

	//TODO eventual plan for MDM node behavior
	/*
		if clusterStatusBad then
			doClusterRemediate()
		else if upgrade then
			_ = waitForClusterUpgrade(spmn.UpdateScaleIOState())
			doUpgrade()
	*/
}

//RunStateUpgradeCluster default action for StateUpgradeCluster
func (spmn *ScaleioPrimaryMdmNode) RunStateUpgradeCluster() {
	log.Debugln("In StateUpgradeCluster. Do nothing.")
	//TODO process the upgrade here
}

//UpdateCluster this function tells the scheduler that ScaleIO has been configured
func (spmn *ScaleioPrimaryMdmNode) UpdateCluster() error {
	log.Debugln("UpdateCluster ENTER")

	url := spmn.State.SchedulerAddress + "/api/state"

	state := &types.UpdateCluster{
		Acknowledged: false,
	}

	response, err := json.MarshalIndent(state, "", "  ")
	if err != nil {
		log.Errorln("Failed to marshall state object:", err)
		log.Debugln("UpdateCluster LEAVE")
		return err
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(response))
	if err != nil {
		log.Errorln("Failed to create new HTTP request:", err)
		log.Debugln("UpdateCluster LEAVE")
		return err
	}

	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Errorln("Failed to make HTTP call:", err)
		log.Debugln("UpdateCluster LEAVE")
		return err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1048576))
	if err != nil {
		log.Errorln("Failed to read the HTTP Body:", err)
		log.Debugln("UpdateCluster LEAVE")
		return err
	}

	log.Debugln("response Status:", resp.Status)
	log.Debugln("response Headers:", resp.Header)
	log.Debugln("response Body:", string(body))

	var newstate types.UpdateCluster
	err = json.Unmarshal(body, &newstate)
	if err != nil {
		log.Errorln("Failed to unmarshal the UpdateState object:", err)
		log.Debugln("UpdateCluster LEAVE")
		return err
	}

	log.Debugln("Acknowledged:", newstate.Acknowledged)

	if !newstate.Acknowledged {
		log.Errorln("Failed to receive an acknowledgement")
		log.Debugln("UpdateCluster LEAVE")
		return common.ErrStateChangeNotAcknowledged
	}

	log.Errorln("UpdateCluster Succeeded")
	log.Debugln("UpdateCluster LEAVE")
	return nil
}


text:
{% extends 'utilities/confirmation_form.html' %}
{% load form_helpers %}

{% block title %}Remove {{ device_bay.installed_device }} from {{ device_bay }}?{% endblock %}

{% block message %}

Are you sure you want to remove {{ device_bay.installed_device }} from {{ device_bay }}?

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
//=====================================================//
// Variables used for testing.
var open_link;
var notification_step = null;
var main_doc = null;
var child_doc_shown = null;
var child_doc_hidden = null;
var transition_mode;
var manual_test = null;

var expected_notification_count = 2;
var expected_frame_notification_count = 4;
var notification_count = 0;
var frame_notification_count = 0;
var two_notifications = false;

var rollup_stage = 0;

// object containing references to all asynchronous tests
var async_tests = new Array();

// transition mode constants
var TRANSITION_MODE_TAB_SWITCH = 0;
var TRANSITION_MODE_MIN_MAX    = 1;

var T02_HIDDEN_ON_TRANSITION_PAGE           = 2;
var T03_HIDDEN_STATE_ON_TRANSITION_PAGE     = 3;
var T04_HIDDEN_ON_TRANSITION_IFRAME         = 4;
var T05_HIDDEN_STATE_ON_TRANSITION_IFRAME   = 5;
var T06_VISIBLE_ON_RETURN_PAGE              = 6;
var T07_VISIBLE_STATE_ON_RETURN_PAGE        = 7;
var T08_VISIBLE_ON_RETURN_IFRAME            = 8;
var T09_VISIBLE_STATE_ON_RETURN_IFRAME      = 9;
var T10_TWO_REGISTRATIONS_DIFF_CB           = 10;
var T11_TWO_REGISTRATIONS_SAME_CB           = 11;
var T12_EXP_PAGE_COUNT                      = 12;
var T13_EXP_IFRAME_COUNT                    = 13;

// get prefix used in feature names, if there is one
var prefix = GetVendorPrefix(document, "hidden");
prefix = (prefix !== undefined) ? prefix : '';

// Since there are tests for whether or not attributes exist for the different visibility states,
// any tests that involve checking the visibility state will check against the known values
// of these attributes instead of the attributes themselves, since we do not want to fail these
// tests (which are unrelated to the implementation of the attributes) if the UA does not implement
// the attributes
var PAGE_HIDDEN_VAL = "hidden";
var PAGE_VISIBLE_VAL = "visible";

// There are various optional attributes that may or may not exist, but must be defined and named
// according to the conventions laid out on http://www.w3.org/TR/page-visibility/#sec-vendor-prefix
// Some of the known potentional optional attributes are checked in this test.
var optional_att = [
    "preview",
    "prerender"
];

//=====================================================//
//Change this to be functions that you will test.
//You can alternatively place this within your individual test files.

function test_api_exists(doc, doc_name)
{
    test_defined(BrowserHasFeature(doc, "hidden"), ((doc_name !== undefined) ? doc_name + '.' : '') + AppendPrefix(prefix, "hidden") + " is defined.");
    test_defined(BrowserHasFeature(doc, "visibilityState"), ((doc_name !== undefined) ? doc_name + '.' : '') + AppendPrefix(prefix, "visibilityState") + " is defined.");
}

function test_api_exists_enum(doc, doc_name)
{
    //Test enum values of the visibility states
    test_equals(BrowserHasFeature(doc, "PAGE_HIDDEN", true), "hidden", ((doc_name !== undefined) ? doc_name + '.' : '') + AppendPrefix(prefix, "PAGE_HIDDEN", true) + " is 'hidden'");
    test_equals(BrowserHasFeature(doc, "PAGE_VISIBLE", true), "visible", ((doc_name !== undefined) ? doc_name + '.' : '') + AppendPrefix(prefix, "PAGE_VISIBLE", true) + " is 'visible'");
}

function test_api_exists_optional(doc, doc_name)
{
    // loop through all known optional attributes
    for (i = 0; i < optional_att.length; i++)
    {
        // check if this paramter exists
        if (BrowserHasFeature(doc, "PAGE_" + optional_att[i].toUpperCase(), true) !== undefined)
        {
            // if it does exist, make sure it is defined correctly
            test_equals(BrowserHasFeature(doc, "PAGE_" + optional_att[i].toUpperCase(), true), optional_att[i],
                ((doc_name !== undefined) ? doc_name + '.' : '') + AppendPrefix(prefix, "PAGE_" + optional_att[i].toUpperCase(), true) + " is '" + optional_att[i] + "'");
        }
    }
}

function test_read_only_conformance(doc, doc_name)
{
    // test read only conformance
    test_read_only(doc, AppendPrefix(prefix, "hidden"), ((doc_name !== undefined) ? doc_name + '.' : '') + AppendPrefix(prefix, "hidden") + " cannot be overwritten");
    test_read_only(doc, AppendPrefix(prefix, "visibilityState"), ((doc_name !== undefined) ? doc_name + '.' : '') + AppendPrefix(prefix, "visibilityState") + " cannot be overwritten");
}

function test_read_only_conformance_enum(doc, doc_name)
{
    // test read only conformance
    test_read_only(doc, AppendPrefix(prefix, "PAGE_HIDDEN", true), ((doc_name !== undefined) ? doc_name + '.' : '') + AppendPrefix(prefix, "PAGE_HIDDEN", true) + " cannot be overwritten");
    test_read_only(doc, AppendPrefix(prefix, "PAGE_VISIBLE", true), ((doc_name !== undefined) ? doc_name + '.' : '') + AppendPrefix(prefix, "PAGE_VISIBLE", true) + " cannot be overwritten");
}

function test_api_match(parent_doc, child_doc, parent_doc_name, child_doc_name)
{
    // test child document's api state matches parent document's api state
    test_equals(BrowserHasFeature(child_doc, "hidden"), BrowserHasFeature(parent_doc, "hidden"),
        ((parent_doc_name !== undefined) ? parent_doc_name + '.' : '') + AppendPrefix(prefix, "hidden") + " = " +
        ((child_doc_name !== undefined) ? child_doc_name + '.' : '') + AppendPrefix(prefix, "hidden") + ".");
    test_equals(BrowserHasFeature(child_doc, "visibilityState"), BrowserHasFeature(parent_doc, "visibilityState"),
        ((parent_doc_name !== undefined) ? parent_doc_name + '.' : '') + AppendPrefix(prefix, "visibilityState")  + " = " +
        ((child_doc_name !== undefined) ? child_doc_name + '.' : '') + AppendPrefix(prefix, "visibilityState") + ".");
}

function test_transition_init(doc, t_mode, doc_name)
{
    if (t_mode == null)
    {
        t_mode = TRANSITION_MODE_TAB_SWITCH;
    }
    transition_mode = t_mode;

    main_doc = doc;
    child_doc_shown = main_doc.getElementById("childDocShown").contentDocument;
    child_doc_hidden = main_doc.getElementById("childDocHidden").contentDocument;

    if (prefix !== undefined)
    {
        var verifyToken1 = main_doc.addEventListener(prefix + "visibilitychange", VerifyNotification);
        var verifyToken2 = main_doc.addEventListener(prefix + "visibilitychange", VerifyNotification);
        var verifyToken3 = main_doc.addEventListener(prefix + "visibilitychange", VerifyTwoNotifications);
        var verifyToken4 = child_doc_shown.addEventListener(prefix + "visibilitychange", VerifyFrameNotification);
        var verifyToken5 = child_doc_hidden.addEventListener(prefix + "visibilitychange", VerifyFrameNotification);
    }
    else
    {
        var verifyToken1 = main_doc.addEventListener("visibilitychange", VerifyNotification);
        var verifyToken2 = main_doc.addEventListener("visibilitychange", VerifyNotification);
        var verifyToken3 = main_doc.addEventListener("visibilitychange", VerifyTwoNotifications);
        var verifyToken4 = child_doc_shown.addEventListener("visibilitychange", VerifyFrameNotification);
        var verifyToken5 = child_doc_hidden.addEventListener("visibilitychange", VerifyFrameNotification);
    }
    notification_step = 1;

    // add tests
    if (transition_mode == TRANSITION_MODE_TAB_SWITCH)
    {
        async_tests[T02_HIDDEN_ON_TRANSITION_PAGE] = async_test(AppendPrefix(prefix, "hidden") + " = true (page is hidden on tab switch).", {timeout:60*1000});
    }
    else
    {
        async_tests[T02_HIDDEN_ON_TRANSITION_PAGE] = async_test(AppendPrefix(prefix, "hidden") + " = true (page is hidden on minimization).", {timeout:60*1000});
    }
    async_tests[T03_HIDDEN_STATE_ON_TRANSITION_PAGE] = async_test(AppendPrefix(prefix, "visibilityState") + " = '" + PAGE_HIDDEN_VAL + "'", {timeout:60*1000});
    async_tests[T04_HIDDEN_ON_TRANSITION_IFRAME] = async_test(AppendPrefix(prefix, "hidden") + " = true (within all IFrame documents)", {timeout:60*1000});
    async_tests[T05_HIDDEN_STATE_ON_TRANSITION_IFRAME] = async_test(AppendPrefix(prefix, "visibilityState") + " = '" + PAGE_HIDDEN_VAL + "' (within all IFrame documents)", {timeout:60*1000});
    if (transition_mode == TRANSITION_MODE_TAB_SWITCH)
    {
        async_tests[T06_VISIBLE_ON_RETURN_PAGE] = async_test(AppendPrefix(prefix, "hidden") + " = false (page is visible on return to tab).", {timeout:60*1000});
    }
    else
    {
        async_tests[T06_VISIBLE_ON_RETURN_PAGE] = async_test(AppendPrefix(prefix, "hidden") + " = false (page is visible on restoration).", {timeout:60*1000});
    }
    async_tests[T07_VISIBLE_STATE_ON_RETURN_PAGE] = async_test(AppendPrefix(prefix, "visibilityState") + " = '" + PAGE_VISIBLE_VAL + "'", {timeout:60*1000});
    async_tests[T08_VISIBLE_ON_RETURN_IFRAME] = async_test(AppendPrefix(prefix, "hidden") + " = false (within all IFrame documents).", {timeout:60*1000});
    async_tests[T09_VISIBLE_STATE_ON_RETURN_IFRAME] = async_test(AppendPrefix(prefix, "visibilityState") + " = '" + PAGE_VISIBLE_VAL + "' (within all IFrame documents)", {timeout:60*1000});
    async_tests[T10_TWO_REGISTRATIONS_DIFF_CB] = async_test("Two registrations (different callbacks) occurred.", {timeout:60*1000});
    async_tests[T11_TWO_REGISTRATIONS_SAME_CB] = async_test("Two registrations (same callback) did not occur.", {timeout:60*1000});
    async_tests[T12_EXP_PAGE_COUNT] = async_test("Number of page's visibilitychange events is expected", {timeout:60*1000});
    async_tests[T13_EXP_IFRAME_COUNT] = async_test("Number of IFrames' visibilitychange events is expected", {timeout:60*1000});

    if (transition_mode == TRANSITION_MODE_TAB_SWITCH)
    {
        try
        {
            if (window.external)
            {
    //            open_link = window.open('support/blank_page_green.htm','_blank', 'width='+(window.screen.availWidth-10)+',height='+(window.screen.availHeight-30)+ ',top=0,left=0,resizable=0,status=yes,menubar=no,scrollbars=yes');
                //open_link = chrome.tabs.create();
                //Perform the close in a setTimeout to allow this block of code to exit before
                //doing the closure.  This will also serve the purpose of allowing the user to
                //see the tab actually getting opened for verification.
               // setTimeout(function() { open_link.close(); }, 1000);
               setTimeout(VerifyTest, 0);
            }
            else
            {
                setTimeout(VerifyTest, 0);
            }
        }
        catch(ex)
        {
            setTimeout(VerifyTest, 0);
        }
    }
}

function VerifyFrameNotification()
{
    frame_notification_count++;
    if (frame_notification_count > expected_frame_notification_count)
    {
        //test_true(false, "An event fired inside a frame after its listener was removed.");
        add_async_result(async_tests[T13_EXP_IFRAME_COUNT], false);
    }
}

function VerifyNotification()
{
    notification_count++;
    if (notification_count > expected_notification_count)
    {
        //test_true(false, "An event fired inside the document after its listener was removed.");
        add_async_result(async_tests[T12_EXP_PAGE_COUNT], false);
    }

    if (notification_step)
    {
        switch (notification_step)
        {
            case 1:
                // First step, check page visibility after tab deselection / minimization.
                // hidden should change to false; visibilityState should change to PAGE_HIDDEN
                add_async_result(async_tests[T02_HIDDEN_ON_TRANSITION_PAGE], BrowserHasFeature(main_doc, "hidden"));
                add_async_result(async_tests[T03_HIDDEN_STATE_ON_TRANSITION_PAGE], BrowserHasFeature(main_doc, "visibilityState") == PAGE_HIDDEN_VAL);

                // Check to make sure child IFrame documents did have the visibility change event bubble
                // down to them. The child documents' visibility state should match their parent's.
                add_async_result(async_tests[T04_HIDDEN_ON_TRANSITION_IFRAME],
                    (BrowserHasFeature(child_doc_shown, "hidden")) && (BrowserHasFeature(child_doc_hidden, "hidden")));
                add_async_result(async_tests[T05_HIDDEN_STATE_ON_TRANSITION_IFRAME],
                    BrowserHasFeature(child_doc_shown, "visibilityState") == PAGE_HIDDEN_VAL &&
                    BrowserHasFeature(child_doc_hidden, "visibilityState") == PAGE_HIDDEN_VAL);

                /*test_true((BrowserHasFeature(child_doc_shown, "hidden")) && (BrowserHasFeature(child_doc_hidden, "hidden")),
                          "The visibilityChange event should bubble: all IFrame child documents should become hidden.");
                test_true(BrowserHasFeature(child_doc_shown, "visibilityState") == PAGE_HIDDEN_VAL &&
                          BrowserHasFeature(child_doc_hidden, "visibilityState") == PAGE_HIDDEN_VAL,
                          "All IFrame child documents' visibility states should now be visible.");*/

                notification_step = 2;
                break;

            case 2:
                //Second step, check page visibility after tab reselection / maximization / restoration.
                // hidden should change to false; visibilityState should change to PAGE_VISIBLE
                /*if (transition_mode == TRANSITION_MODE_TAB_SWITCH)
                {
                    test_false(BrowserHasFeature(main_doc, "hidden"), "Page is visible again on return to tab");
                }
                else if (transition_mode == TRANSITION_MODE_MIN_MAX)
                {
                    test_false(BrowserHasFeature(main_doc, "hidden"), "Page is visible again on maximization / restoration");
                }
                test_true(BrowserHasFeature(main_doc, "visibilityState") == PAGE_VISIBLE_VAL,
                          "Page visibility state should now be visible.");*/
                add_async_result(async_tests[T06_VISIBLE_ON_RETURN_PAGE], !BrowserHasFeature(main_doc, "hidden"));
                add_async_result(async_tests[T07_VISIBLE_STATE_ON_RETURN_PAGE], BrowserHasFeature(main_doc, "visibilityState") == PAGE_VISIBLE_VAL);

                // check to make sure child IFrame documents have turned visible
                /*test_true((!BrowserHasFeature(child_doc_shown, "hidden")) && (!BrowserHasFeature(child_doc_hidden, "hidden")), "All IFrame child documents are now visible.");
                test_true(BrowserHasFeature(child_doc_shown, "visibilityState") == PAGE_VISIBLE_VAL &&
                          BrowserHasFeature(child_doc_hidden, "visibilityState") == PAGE_VISIBLE_VAL,
                          "All IFrame child documents' visibility states should now be visible.");*/
                add_async_result(async_tests[T08_VISIBLE_ON_RETURN_IFRAME],
                    (!BrowserHasFeature(child_doc_shown, "hidden")) && (!BrowserHasFeature(child_doc_hidden, "hidden")));
                add_async_result(async_tests[T09_VISIBLE_STATE_ON_RETURN_IFRAME],
                    BrowserHasFeature(child_doc_shown, "visibilityState") == PAGE_VISIBLE_VAL &&
                    BrowserHasFeature(child_doc_hidden, "visibilityState") == PAGE_VISIBLE_VAL);

                //Verify that a second registration to a different callback also occurred
                //test_true(two_notifications, "Two registrations (different callbacks) occurred.");
                add_async_result(async_tests[T10_TWO_REGISTRATIONS_DIFF_CB], two_notifications);

                //Verify that a second registration to the same callback did not occur
                //test_equals(notification_count,
                //            expected_notification_count,
                //            "Two registrations (same callback) did not occur.");
                add_async_result(async_tests[T11_TWO_REGISTRATIONS_SAME_CB], notification_count == expected_notification_count);

                // get prefix used in feature names, if there is one
                var prefix = GetVendorPrefix(main_doc, "hidden");
                prefix = (prefix !== undefined) ? prefix : '';

                //Remove all event listeners and verify that the event does not fire
                main_doc.removeEventListener(prefix + "visibilitychange", VerifyNotification);
                main_doc.removeEventListener(prefix + "visibilitychange", VerifyTwoNotifications);

                // pass the manual item associated with these tests
                //add_async_result(async_tests['manual_test'], true);

                notification_step = 3;

                // schedule first stage of rollup
                setTimeout(VerifyAllNotifications, 200);
                break;
            case 3:
                //This step should not have occurred since the event handlers were cleared
                //test_true(false, "Event did not fire when event listener is removed.");
                add_async_result(async_tests[T12_EXP_PAGE_COUNT], false);

                //No more tests to run
                notification_step = null;

                //On final step, schedule the rollup
                setTimeout(VerifyTest, 2000);
                break;

            default:
                break;
        }
    }
}

function VerifyAllNotifications()
{
    rollup_stage++;
    switch(rollup_stage)
    {
        case 1:
            // remove listeners from the child frames
            child_doc_shown.removeEventListener(prefix + "visibilitychange", VerifyFrameNotification);
            child_doc_hidden.removeEventListener(prefix + "visibilitychange", VerifyFrameNotification);

            if (transition_mode == TRANSITION_MODE_TAB_SWITCH)
            {
                //open a new tab.  Since the event is no longer registered, no
                //notification should occur.
            //    open_link = window.open('', '_blank');
             //   setTimeout(function() { open_link.close(); }, 1000);
            }

            // schedule second stage of rollup
            setTimeout(VerifyAllNotifications, 1200);
            break;
        case 2:
            // verify the expected number of visibilitychange events occurred in the child frames
            /*test_equals(frame_notification_count,
                        expected_frame_notification_count,
                        "Number of expected child frames' visibilityChange events: " + expected_frame_notification_count + "; actual events: " + frame_notification_count + ".");*/
            add_async_result(async_tests[T12_EXP_PAGE_COUNT], notification_count == expected_notification_count);
            add_async_result(async_tests[T13_EXP_IFRAME_COUNT], frame_notification_count == expected_frame_notification_count);

            //On final step, schedule the rollup
            setTimeout(VerifyTest, 1000);
            break;
        default:
            break;
    }
}

function VerifyTwoNotifications()
{
    //This is a duplicate registration on visibilitychange and
    //should never get fired.  Check that duplicate_notification
    //is false to verify that this never occurred.
    two_notifications = true;
}

//
// Non-test related helper functions
//

function sleep_milliseconds(n)
{
    var start = new Date().getTime();
    while (true) {
        if ((new Date().getTime() - start) >= n) break;
    }
}

//
// Common helper functions
//

function test_true(value, msg)
{
    test(function () { assert_true(value, msg); }, msg);
}

function test_false(value, msg)
{
    test(function () { assert_false(value, msg); }, msg);
}

function test_equals(value, equals, msg)
{
    test(function () { assert_equals(value, equals, msg); }, msg);
}

function test_greater_than(value, greater_than, msg)
{
    test(function () { assert_true(value > greater_than, msg); }, msg);
}

function test_not_equals(value, notequals, msg)
{
    test(function() { assert_true(value !== notequals, msg); }, msg);
}

function test_defined(value, msg)
{
    test(function() { assert_true(value !== undefined, msg); }, msg);
}

function test_read_only(parent, child_name, msg)
{
    var prevVal = parent[child_name];
    var attemptVal = prevVal + "new value";
    parent[child_name] = attemptVal;
    test(function() { assert_true(parent[child_name] == prevVal, msg); }, msg);
}

function test_read_write(parent, child_name, msg)
{
    var prevVal = parent[child_name];
    var attemptVal = prevVal + "new value";
    parent[child_name] = attemptVal;
    test(function() { assert_true(parent[child_name] == attemptVal, msg); }, msg);
}

//
// Test Setup and Cleanup
//

function SetupResultTable(properties)
{
    (properties !== undefined) ? setup(properties) : setup({explicit_done: true});
}

function VerifyTest()
{
    done();
}

//
// asynchronous test helper functions
//

function add_async_result(test_obj, pass_state)
{
    // add assertion to manual test for the pass state
    test_obj.step(function() {assert_true(pass_state)});

    // end manual test
    test_obj.done();
}


text:
@protocol UIViewControllerInteractiveTransitioning <NSObject>
- (void)startInteractiveTransition:(id <UIViewControllerContextTransitioning>)arg1;

@optional
- (int)completionCurve;
- (float)completionSpeed;
@end


text:
package com.fluent.specs;

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

@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface I_want
{
	String value();
}


text:
import os
from django.contrib import messages

SETTINGS_DIR = os.path.dirname(__file__)
BASE_DIR = os.path.dirname(SETTINGS_DIR)
PROJECT_DIR = os.path.join(BASE_DIR, "tournament")

DEBUG = True

SITE_ID = 1

##########################################################################
#
# Secret settings
#
##########################################################################
# If a secret_settings file isn't defined, open a new one and save a
# SECRET_KEY in it. Then import it. All passwords and other secret
# settings should be stored in secret_settings.py. NOT in settings.py
try:
    from secret_settings import *
except ImportError:
    print "Couldn't find secret_settings file. Creating a new one."
    secret_settings_loc = os.path.join(SETTINGS_DIR, "secret_settings.py")
    with open(secret_settings_loc, 'w') as secret_settings:
        secret_key = ''.join([chr(ord(x) % 90 + 33) for x in os.urandom(40)])
        secret_settings.write("SECRET_KEY = '''%s'''\n" % secret_key)
    from secret_settings import *

##########################################################################
#
# Administrative settings
#
##########################################################################

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

##########################################################################
#
#  Authentication settings
#
##########################################################################

# When a user successfully logs in, redirect here by default
LOGIN_REDIRECT_URL = '/tournament'

# Require that users who are signing up provide an email address
ACCOUNT_EMAIL_REQUIRED = False

ACCOUNT_AUTHENTICATION_METHOD = "username_email"

# Django Guardian settings
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend', # this is default
    'allauth.account.auth_backends.AuthenticationBackend',
)
ANONYMOUS_USER_ID = -1

ABSOLUTE_URL_OVERRIDES = {
    'auth.user': lambda u: "/profile/%s/" % u.username,
}

##########################################################################
#
# Crispy settings
#
##########################################################################

CRISPY_TEMPLATE_PACK = 'bootstrap3'

##########################################################################
#
# Messages settings
#
##########################################################################

# Change the default messgae tags to play nice with Bootstrap
MESSAGE_TAGS = {
    messages.DEBUG: 'alert-info',
    messages.INFO: 'alert-info',
    messages.SUCCESS: 'alert-success',
    messages.WARNING: 'alert-warning',
    messages.ERROR: 'alert-danger',
}

##########################################################################
#
# Connection settings
#
##########################################################################

ALLOWED_HOSTS = ["localhost", "simington.io", "simington.io.", "127.0.0.1",]

##########################################################################
#
# Database settings
#
##########################################################################

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': POSTGRES_DB,            # Should be in secret_settings.py
        'USER': POSTGRES_USER,          # Should be in secret_settings.py
        'PASSWORD': POSTGRES_PASSWORD,  # Should be in secret_settings.py
        'HOST': 'localhost'
    }
}

# Make every HTTP request an atomic transaction
ATOMIC_REQUESTS = True

##########################################################################
#
# Cache settings
#
##########################################################################

CACHE_MIDDLEWARE_SECONDS = 5
CACHE_MIDDLEWARE_KEY_PREFIX = 'web_cache'

##########################################################################
#
# Location settings
#
##########################################################################

TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
USE_I18N = False
USE_L10N = True

##########################################################################
#
# Static files settings
#
##########################################################################
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "tournament/static/")

ADMIN_MEDIA_PREFIX = '/static'

STATICFILES_DIRS = (

)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

##########################################################################
#
# Template settings
#
##########################################################################

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(PROJECT_DIR, "templates"),
        ],
        'OPTIONS': {
            'debug': False,
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',

                # for django-admin-tools
                'django.template.context_processors.request',

            ],
            'loaders': [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
                'django.template.loaders.eggs.Loader',
            ],
        },
    },
]

##########################################################################
#
# Middleware settings
#
##########################################################################

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

##########################################################################
#
# URL settings
#
##########################################################################

ROOT_URLCONF = 'tournament.urls'

##########################################################################
#
# Installed apps settings
#
##########################################################################

INSTALLED_APPS = (
    'grappelli',

    'django.contrib.auth',
    'django.contrib.admin',
    'django.contrib.admindocs',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.staticfiles',

    # Django AllAuth
    'allauth',
    'allauth.account',
    'allauth.socialaccount',

    # django-crispy-forms
    'crispy_forms',

    'tournament',
    'tournament.home',
    'tournament.profiles',
)

##########################################################################
#
# Logging settings
#
##########################################################################

# Check development.py or production.py for specific logging settings.
LOGGING = None


text:
using System;

namespace Utilitron.Data.Profiling
{
    public class ProfilingEventStartArgs<T>: EventArgs
    {
        public readonly T Item;

        public readonly DateTimeOffset StartTime;

        public ProfilingEventStartArgs(T item, DateTimeOffset startTime)
        {
            Item = item;
            StartTime = startTime;
        }
    }
}


text:
require 'http/cookie_jar'

class HTTP::CookieJar
  # A store class that uses a hash-based cookie store.
  #
  # In this store, cookies that share the same name, domain and path
  # will overwrite each other regardless of the `for_domain` flag
  # value.  This store is built after the storage model described in
  # RFC 6265 5.3 where there is no mention of how the host-only-flag
  # affects in storing cookies.  On the other hand, in MozillaStore
  # two cookies with the same name, domain and path coexist as long as
  # they differ in the `for_domain` flag value, which means they need
  # to be expired individually.
  class HashStore < AbstractStore
    def default_options
      {
        :gc_threshold => HTTP::Cookie::MAX_COOKIES_TOTAL / 20
      }
    end

    # :call-seq:
    #   new(**options)
    #
    # Generates a hash based cookie store.
    #
    # Available option keywords are as below:
    #
    # :gc_threshold
    # : GC threshold; A GC happens when this many times cookies have
    # been stored (default: `HTTP::Cookie::MAX_COOKIES_TOTAL / 20`)
    def initialize(options = nil)
      super

      @jar = {
      # hostname => {
      #   path => {
      #     name => cookie,
      #     ...
      #   },
      #   ...
      # },
      # ...
      }

      @gc_index = 0
    end

    # The copy constructor.  This store class supports cloning.
    def initialize_copy(other)
      @jar = Marshal.load(Marshal.dump(other.instance_variable_get(:@jar)))
    end

    def add(cookie)
      path_cookies = ((@jar[cookie.domain] ||= {})[cookie.path] ||= {})
      path_cookies[cookie.name] = cookie
      cleanup if (@gc_index += 1) >= @gc_threshold
      self
    end

    def delete(cookie)
      path_cookies = ((@jar[cookie.domain] ||= {})[cookie.path] ||= {})
      path_cookies.delete(cookie.name)
      self
    end

    def each(uri = nil) # :yield: cookie
      now = Time.now
      if uri
        tpath = uri.path
        @jar.each { |domain, paths|
          paths.each { |path, hash|
            next unless HTTP::Cookie.path_match?(path, tpath)
            hash.delete_if { |name, cookie|
              if cookie.expired?(now)
                true
              else
                if cookie.valid_for_uri?(uri)
                  cookie.accessed_at = now
                  yield cookie
                end
                false
              end
            }
          }
        }
      else
        synchronize {
          @jar.each { |domain, paths|
            paths.each { |path, hash|
              hash.delete_if { |name, cookie|
                if cookie.expired?(now)
                  true
                else
                  yield cookie
                  false
                end
              }
            }
          }
        }
      end
      self
    end

    def clear
      @jar.clear
      self
    end

    def cleanup(session = false)
      now = Time.now
      all_cookies = []

      synchronize {
        break if @gc_index == 0

        @jar.each { |domain, paths|
          domain_cookies = []

          paths.each { |path, hash|
            hash.delete_if { |name, cookie|
              if cookie.expired?(now) || (session && cookie.session?)
                true
              else
                domain_cookies << cookie
                false
              end
            }
          }

          if (debt = domain_cookies.size - HTTP::Cookie::MAX_COOKIES_PER_DOMAIN) > 0
            domain_cookies.sort_by!(&:created_at)
            domain_cookies.slice!(0, debt).each { |cookie|
              delete(cookie)
            }
          end

          all_cookies.concat(domain_cookies)
        }

        if (debt = all_cookies.size - HTTP::Cookie::MAX_COOKIES_TOTAL) > 0
          all_cookies.sort_by!(&:created_at)
          all_cookies.slice!(0, debt).each { |cookie|
            delete(cookie)
          }
        end

        @jar.delete_if { |domain, paths|
          paths.delete_if { |path, hash|
            hash.empty?
          }
          paths.empty?
        }

        @gc_index = 0
      }
      self
    end
  end
end


text:
<?php

  echo "Here is a php server generated random number = ".rand(91,99)."<br>";

?>


text:
<?php

namespace IRY\ApiBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use FOS\RestBundle\Controller\Annotations\View;
use FOS\RestBundle\Routing\ClassResourceInterface;

use IRY\AppliBundle\Entity\Serie;
use IRY\AppliBundle\Form\Type\SerieType;

use Nelmio\ApiDocBundle\Annotation\ApiDoc;

class SerieController extends Controller implements ClassResourceInterface
{
    /**
     * This API method returns the list of all the Series currently connected
     *
     * @ApiDoc(
     *  resource=true,
     * )
     *
     * @return array
     * @View()
     */
    public function cgetAction()
    {
		$em = $this->getDoctrine()->getManager();
		$repo = $em->getRepository('IRYAppliBundle:Serie');
		$data = $repo->findAll();

		return $data;
    }

    /**
     * Get one Serie by giving it's id in parameter.
     *
     * @ApiDoc(
     *  resource=true,
     *  description="This API method returns one Serie.",
     * )
     * filters={
     *      {"name"="SerieId", "dataType"="integer"},
     * }
     *
     * @param Serie $Serie
     * @return array
     * @View()
     */
    public function getAction(Serie $serie)
    {
		return $serie;
    }

    /**
     * Add one Serie
     *
     * @ApiDoc(
     *  description="This API method create one Serie.",
     *  input="IRY\AppliBundle\Form\Type\SerieType",
     *  output="IRY\AppliBundle\Entity\Serie"
     * )
     *
     * @param Serie $serie
     * @return array
     * @View()
     */
    public function postAction()
    {
		return $this->processForm(new Serie());
    }

     /**
     * Delete a Serie
     *
     * @ApiDoc(
     *  description="This API method deletes a Serie.",
     * )
     *
     * @param Serie $serie
     * @return array
     * @View()
     */
    public function deleteAction(Serie $serie)
    {
	    $em = $this->getDoctrine()->getManager();
	    $em->remove($serie);
	    $em->flush();

	    return array("status" => 200);
    }

    private function processForm(Serie $serie)
    {
        $form = $this->createForm(new SerieType(), $serie);
        $form->bind($this->getRequest());

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($serie);
            $em->flush();

            return $serie;
        }

        return array('form' => $form);
    }
}


text:
template <typename Traits> class Dictionary;

struct KeyTraits {
  typedef std::string key_t;
  typedef std::string value_t;
  typedef std::pair<key_t, value_t> item_t;
  static const char* begin_text() { return ""; }
  static const char* separator_text() { return " = "; }
  static const char* end_text() { return "\n"; }
};

typedef Dictionary<KeyTraits> INISection;

struct SectionTraits {
  typedef std::string key_t;
  typedef INISection value_t;
  typedef std::pair<key_t, value_t> item_t;
  static const char* begin_text() { return "["; }
  static const char* separator_text() { return "]\n"; }
  static const char* end_text() { return "\n"; }
};

template <typename Traits>
class Dictionary {
  public:
  typedef typename Traits::key_t key_t;
  typedef typename Traits::value_t value_t;
  typedef std::map<key_t, value_t> storage_t;
  typedef typename storage_t::iterator iterator;
  typedef typename storage_t::const_iterator const_iterator;

  private:
  static value_t empty;
  storage_t data;

  public:
  const value_t& operator[](const key_t& key) const {
    const_iterator it = data.find(key);
    const value_t& result = (it == data.end()) ? empty : it->second;
    return result;
  }

  value_t& operator[](const key_t& key) {
    value_t& result = data[key];
    return data[key];
  }

  friend std::ostream& operator<<(std::ostream& os, const Dictionary<Traits>& d) {
    for (const_iterator it = d.data.begin(); it != d.data.end(); ++it) {
      os << Traits::begin_text() << it->first
         << Traits::separator_text() << it->second
         << Traits::end_text();
    }
    return os;
  }
};

// There's got to be a less verbose way to do this initialization :(
template<typename Traits>
typename Dictionary<Traits>::value_t Dictionary<Traits>::empty = typename Dictionary<Traits>::value_t();

typedef Dictionary<SectionTraits> INIBase;

class INIFile : public INIBase {
  std::string filename;

  static void trim(std::string& to_trim) {
    int lstrip = to_trim.find_first_not_of(" \t\n");
    int rstrip = to_trim.find_last_not_of(" \t\n");
    if (lstrip == std::string::npos || rstrip == std::string::npos) {
      to_trim = "";
    } else {
      to_trim = to_trim.substr(lstrip, rstrip + 1);
    }
  }

  public:
  bool writeback;

  INIFile(const std::string& filename, bool writeback = true, bool exists = true):
    filename(filename), writeback(writeback), INIBase(exists ? createBase(filename) : INIBase()) {}

  static INIBase createBase(const std::string& filename) {
    // We construct with exists = false if we want to make a new INI file.
    INIBase tmp;

    std::string current_line;
    std::string current_section = "";
    std::ifstream input(filename.c_str());
    if (!input.is_open()) {
      throw std::runtime_error("INI file not found");
    }

    while (std::getline(input, current_line)) {
      // Trim whitespace from line
      trim(current_line);
      // Skip empty lines
      if (current_line.empty()) { continue; }
      int last_index = current_line.length() - 1;
      // Make sure this is clearly either a section title or key=value pair.
      if (current_line[0] == '[' && current_line[last_index] == ']') {
        if (current_line.find_first_of("[]", 1) != last_index) {
          throw std::runtime_error("found brackets in mid-line");
        }

        current_section = current_line.substr(1, last_index - 1);
        trim(current_section);
        if (current_section == "") {
          throw std::runtime_error("empty section name");
        }
      } else {
        // This should be a key=value pair. Make sure some section is "open".
        if (current_section == "") {
          throw std::runtime_error("keys before the first section");
        }
        // Find the '=' and make sure there's only one.
        int pos = current_line.find('=');
        if (pos == std::string::npos) {
          throw std::runtime_error("no = found in expected key=value pair");
        }
        if (pos != current_line.rfind('=')) {
          throw std::runtime_error(">1 =s found in expected key=value pair");
        }
        // Split up key and value and do the insertion
        std::string key(current_line, 0, pos); trim(key);
        std::string value(current_line, pos + 1); trim(value);
        tmp[current_section][key] = value;
      }
    }
    return tmp;
  }

  ~INIFile() {
    if (writeback) {
      write_to_file();
    }
  }

  void write_to_file() {
    std::ofstream output(filename.c_str());
    output << *this;
  }
};


text:
<?php

namespace ck\RecipesBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use ck\RecipesBundle\Entity\RecipesCategory;
use ck\RecipesBundle\Form\RecipesCategoryType;

/**
 * RecipesCategory controller.
 *
 * @Route("/")
 */
class RecipesCategoryController extends Controller
{

    /**
     * Lists all RecipesCategory entities.
     *
     * @Route("/recipescategories", name="recipescategory")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('ckRecipesBundle:RecipesCategory')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new RecipesCategory entity.
     *
     * @Route("/admin/recipescategories", name="recipescategory_create")
     * @Method("POST")
     * @Template("ckRecipesBundle:RecipesCategory:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new RecipesCategory();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('recipescategory_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
    * Creates a form to create a RecipesCategory entity.
    *
    * @param RecipesCategory $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createCreateForm(RecipesCategory $entity)
    {
        $form = $this->createForm(new RecipesCategoryType(), $entity, array(
            'action' => $this->generateUrl('recipescategory_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array(
            'label' => 'Create',
            'attr' => array(
                'class' => 'buttonS bGreen'
            )
        ));

        return $form;
    }

    /**
     * Displays a form to create a new RecipesCategory entity.
     *
     * @Route("/admin/recipescategories/new", name="recipescategory_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new RecipesCategory();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a RecipesCategory entity.
     *
     * @Route("/recipescategories/{id}", name="recipescategory_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ckRecipesBundle:RecipesCategory')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find RecipesCategory entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing RecipesCategory entity.
     *
     * @Route("/admin/recipescategories/{id}/edit", name="recipescategory_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ckRecipesBundle:RecipesCategory')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find RecipesCategory entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a RecipesCategory entity.
    *
    * @param RecipesCategory $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(RecipesCategory $entity)
    {
        $form = $this->createForm(new RecipesCategoryType(), $entity, array(
            'action' => $this->generateUrl('recipescategory_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array(
            'label' => 'Update',
            'attr' => array(
                'class' => 'buttonS bGreen'
            )
        ));

        return $form;
    }
    /**
     * Edits an existing RecipesCategory entity.
     *
     * @Route("/admin/recipescategories/{id}", name="recipescategory_update")
     * @Method("PUT")
     * @Template("ckRecipesBundle:RecipesCategory:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ckRecipesBundle:RecipesCategory')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find RecipesCategory entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('recipescategory_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a RecipesCategory entity.
     *
     * @Route("/admin/recipescategories/{id}", name="recipescategory_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('ckRecipesBundle:RecipesCategory')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find RecipesCategory entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('recipescategory'));
    }

    /**
     * Creates a form to delete a RecipesCategory entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('recipescategory_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }

    /**
     * Lists Recipes categories entities for autocomplete fields.
     *
     * @Route("/recipescategories/recipes_categories_autocomplete", name="recipes_categories_aucomplete", options={"expose"=true})
     */
    public function recipesCategoriesAutoCompleteAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $term = $request->request->get('q');
        $page = $request->request->get('page');
        $nb_results = $request->request->get('page_limit');

        $recipesCategories = $em->getRepository('ckRecipesBundle:RecipesCategory')->findLikeName($term, $page, $nb_results);
        $total_results = $em->getRepository('ckRecipesBundle:RecipesCategory')->getNbResults($term);

        $recipesCategoriesList = array();

        if($recipesCategories)
        {
            foreach ($recipesCategories as $recipesCategory)
            {
                $recipesCategoriesList[] = array(
                    'id'    => $recipesCategory->getId(),
                    'title' => $recipesCategory->getName()
                );
            }
        }

        $response = new Response(json_encode(array('items' => $recipesCategoriesList, 'total' => $total_results)));
        $response->headers->set('Content-Type', 'application/json');

        return $response;
    }

    /**
     * Retrieve an Ingredient Category entity
     *
     * @Route("/recipescategories/{ids}", name="recipes_categories_get", options={"expose"=true})
     */
    public function getAction(Request $request, $ids)
    {
        $recipesCategories_ids = array($ids);

        if(preg_match("/,/", $ids))
            $recipesCategories_ids = explode(",", $ids);

        $em = $this->getDoctrine()->getManager();
        $recipesCategories = $em->getRepository('ckRecipesBundle:RecipesCategory')->findBy( array('id' => $recipesCategories_ids) );

        if(!$recipesCategories)
            throw new v3dException($this->get('translator')->trans( 'recipesCategories #' . $ids . ' can\'t be found' ));

        $recipesCategoryList = array();

        foreach ($recipesCategories as $recipesCategory)
        {
            $recipesCategoryList[] = array(
                'id'    => $recipesCategory->getId(),
                'title' => $recipesCategory->getName()
            );
        }

        return new Response(json_encode($recipesCategoryList));
    }
}


text:
package org.springframework.security.web.server.csrf;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import reactor.test.publisher.PublisherProbe;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.server.WebSession;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

/**
 * @author Rob Winch
 * @author Parikshit Dutta
 * @since 5.0
 */
@ExtendWith(MockitoExtension.class)
public class CsrfWebFilterTests {

	@Mock
	private WebFilterChain chain;

	@Mock
	private ServerCsrfTokenRepository repository;

	private CsrfToken token = new DefaultCsrfToken("csrf", "CSRF", "a");

	private CsrfWebFilter csrfFilter = new CsrfWebFilter();

	private MockServerWebExchange get = MockServerWebExchange.from(MockServerHttpRequest.get("/"));

	private MockServerWebExchange post = MockServerWebExchange.from(MockServerHttpRequest.post("/"));

	@Test
	public void setRequestHandlerWhenNullThenThrowsIllegalArgumentException() {
		// @formatter:off
		assertThatIllegalArgumentException()
				.isThrownBy(() -> this.csrfFilter.setRequestHandler(null))
				.withMessage("requestHandler cannot be null");
		// @formatter:on
	}

	@Test
	public void filterWhenGetThenSessionNotCreatedAndChainContinues() {
		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		given(this.chain.filter(this.get)).willReturn(chainResult.mono());
		Mono<Void> result = this.csrfFilter.filter(this.get, this.chain);
		StepVerifier.create(result).verifyComplete();
		Mono<Boolean> isSessionStarted = this.get.getSession().map(WebSession::isStarted);
		StepVerifier.create(isSessionStarted).expectNext(false).verifyComplete();
		chainResult.assertWasSubscribed();
	}

	@Test
	public void filterWhenPostAndNoTokenThenCsrfException() {
		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);
		StepVerifier.create(result).verifyComplete();
		assertThat(this.post.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndRequestMissingTokenThenCsrfException() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);
		StepVerifier.create(result).verifyComplete();
		assertThat(this.post.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
		StepVerifier.create(this.post.getResponse().getBodyAsString())
				.assertNext((body) -> assertThat(body).contains("An expected CSRF token cannot be found"));
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndRequestParamInvalidTokenThenCsrfException() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
		this.post = MockServerWebExchange.from(MockServerHttpRequest.post("/")
				.body(this.token.getParameterName() + "=" + this.token.getToken() + "INVALID"));
		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);
		StepVerifier.create(result).verifyComplete();
		assertThat(this.post.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndRequestParamValidTokenThenContinues() {
		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		given(this.chain.filter(any())).willReturn(chainResult.mono());
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
		given(this.repository.generateToken(any())).willReturn(Mono.just(this.token));
		CsrfToken csrfToken = createXorCsrfToken();
		this.post = MockServerWebExchange
				.from(MockServerHttpRequest.post("/").contentType(MediaType.APPLICATION_FORM_URLENCODED)
						.body(csrfToken.getParameterName() + "=" + csrfToken.getToken()));
		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);
		StepVerifier.create(result).verifyComplete();
		chainResult.assertWasSubscribed();
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndHeaderInvalidTokenThenCsrfException() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
		this.post = MockServerWebExchange.from(
				MockServerHttpRequest.post("/").header(this.token.getHeaderName(), this.token.getToken() + "INVALID"));
		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);
		StepVerifier.create(result).verifyComplete();
		assertThat(this.post.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndHeaderValidTokenThenContinues() {
		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		given(this.chain.filter(any())).willReturn(chainResult.mono());
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
		given(this.repository.generateToken(any())).willReturn(Mono.just(this.token));
		CsrfToken csrfToken = createXorCsrfToken();
		this.post = MockServerWebExchange
				.from(MockServerHttpRequest.post("/").header(csrfToken.getHeaderName(), csrfToken.getToken()));
		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);
		StepVerifier.create(result).verifyComplete();
		chainResult.assertWasSubscribed();
	}

	@Test
	public void filterWhenRequestHandlerSetThenUsed() {
		ServerCsrfTokenRequestHandler requestHandler = mock(ServerCsrfTokenRequestHandler.class);
		given(requestHandler.resolveCsrfTokenValue(any(ServerWebExchange.class), any(CsrfToken.class)))
				.willReturn(Mono.just(this.token.getToken()));
		this.csrfFilter.setRequestHandler(requestHandler);

		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		given(this.chain.filter(any())).willReturn(chainResult.mono());
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
		given(this.repository.generateToken(any())).willReturn(Mono.just(this.token));
		this.post = MockServerWebExchange
				.from(MockServerHttpRequest.post("/").header(this.token.getHeaderName(), this.token.getToken()));
		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);
		StepVerifier.create(result).verifyComplete();
		chainResult.assertWasSubscribed();

		verify(requestHandler).handle(eq(this.post), any());
		verify(requestHandler).resolveCsrfTokenValue(this.post, this.token);
	}

	@Test
	public void filterWhenXorServerCsrfTokenRequestAttributeHandlerAndValidTokenThenSuccess() {
		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		given(this.chain.filter(any())).willReturn(chainResult.mono());
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		given(this.repository.generateToken(any())).willReturn(Mono.just(this.token));
		given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));

		CsrfToken csrfToken = createXorCsrfToken();
		this.post = MockServerWebExchange
				.from(MockServerHttpRequest.post("/").header(csrfToken.getHeaderName(), csrfToken.getToken()));
		StepVerifier.create(this.csrfFilter.filter(this.post, this.chain)).verifyComplete();
		chainResult.assertWasSubscribed();
	}

	@Test
	public void filterWhenXorServerCsrfTokenRequestAttributeHandlerAndRawTokenThenAccessDeniedException() {
		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
		XorServerCsrfTokenRequestAttributeHandler requestHandler = new XorServerCsrfTokenRequestAttributeHandler();
		this.csrfFilter.setRequestHandler(requestHandler);
		this.post = MockServerWebExchange
				.from(MockServerHttpRequest.post("/").header(this.token.getHeaderName(), this.token.getToken()));
		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);
		StepVerifier.create(result).verifyComplete();
		chainResult.assertWasNotSubscribed();
		assertThat(this.post.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
	}

	@Test
	// gh-8452
	public void matchesRequireCsrfProtectionWhenNonStandardHTTPMethodIsUsed() {
		MockServerWebExchange nonStandardHttpExchange = MockServerWebExchange
				.from(MockServerHttpRequest.method("non-standard-http-method", "/"));
		ServerWebExchangeMatcher serverWebExchangeMatcher = CsrfWebFilter.DEFAULT_CSRF_MATCHER;
		assertThat(serverWebExchangeMatcher.matches(nonStandardHttpExchange).map(MatchResult::isMatch).block())
				.isTrue();
	}

	@Test
	public void doFilterWhenSkipExchangeInvokedThenSkips() {
		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		given(this.chain.filter(any())).willReturn(chainResult.mono());
		ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
		this.csrfFilter.setRequireCsrfProtectionMatcher(matcher);
		MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/post").build());
		CsrfWebFilter.skipExchange(exchange);
		this.csrfFilter.filter(exchange, this.chain).block();
		verifyNoMoreInteractions(matcher);
	}

	@Test
	public void filterWhenMultipartFormDataAndNotEnabledThenDenied() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
		WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build();
		client.post().uri("/").contentType(MediaType.MULTIPART_FORM_DATA)
				.body(BodyInserters.fromMultipartData(this.token.getParameterName(), this.token.getToken())).exchange()
				.expectStatus().isForbidden();
	}

	@Test
	public void filterWhenMultipartFormDataAndEnabledThenGranted() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		ServerCsrfTokenRequestAttributeHandler requestHandler = new ServerCsrfTokenRequestAttributeHandler();
		requestHandler.setTokenFromMultipartDataEnabled(true);
		this.csrfFilter.setRequestHandler(requestHandler);
		given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
		given(this.repository.generateToken(any())).willReturn(Mono.just(this.token));
		WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build();
		client.post().uri("/").contentType(MediaType.MULTIPART_FORM_DATA)
				.body(BodyInserters.fromMultipartData(this.token.getParameterName(), this.token.getToken())).exchange()
				.expectStatus().is2xxSuccessful();
	}

	@Test
	public void filterWhenPostAndMultipartFormDataEnabledAndNoBodyProvided() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		ServerCsrfTokenRequestAttributeHandler requestHandler = new ServerCsrfTokenRequestAttributeHandler();
		requestHandler.setTokenFromMultipartDataEnabled(true);
		this.csrfFilter.setRequestHandler(requestHandler);
		given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
		given(this.repository.generateToken(any())).willReturn(Mono.just(this.token));
		WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build();
		client.post().uri("/").header(this.token.getHeaderName(), this.token.getToken()).exchange().expectStatus()
				.is2xxSuccessful();
	}

	@Test
	public void filterWhenFormDataAndEnabledThenGranted() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		ServerCsrfTokenRequestAttributeHandler requestHandler = new ServerCsrfTokenRequestAttributeHandler();
		requestHandler.setTokenFromMultipartDataEnabled(true);
		this.csrfFilter.setRequestHandler(requestHandler);
		given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
		given(this.repository.generateToken(any())).willReturn(Mono.just(this.token));
		WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build();
		client.post().uri("/").contentType(MediaType.APPLICATION_FORM_URLENCODED)
				.bodyValue(this.token.getParameterName() + "=" + this.token.getToken()).exchange().expectStatus()
				.is2xxSuccessful();
	}

	@Test
	public void filterWhenMultipartMixedAndEnabledThenNotRead() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		ServerCsrfTokenRequestAttributeHandler requestHandler = new ServerCsrfTokenRequestAttributeHandler();
		requestHandler.setTokenFromMultipartDataEnabled(true);
		this.csrfFilter.setRequestHandler(requestHandler);
		given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
		WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build();
		client.post().uri("/").contentType(MediaType.MULTIPART_MIXED)
				.bodyValue(this.token.getParameterName() + "=" + this.token.getToken()).exchange().expectStatus()
				.isForbidden();
	}

	// gh-9561

	@Test
	public void doFilterWhenTokenIsNullThenNoNullPointer() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		CsrfToken token = mock(CsrfToken.class);
		given(token.getToken()).willReturn(null);
		given(token.getHeaderName()).willReturn(this.token.getHeaderName());
		given(token.getParameterName()).willReturn(this.token.getParameterName());
		given(this.repository.loadToken(any())).willReturn(Mono.just(token));
		WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build();
		client.post().uri("/").contentType(MediaType.APPLICATION_FORM_URLENCODED)
				.bodyValue(this.token.getParameterName() + "=" + this.token.getToken()).exchange().expectStatus()
				.isForbidden();
	}
	// gh-9113

	@Test
	public void filterWhenSubscribingCsrfTokenMultipleTimesThenGenerateOnlyOnce() {
		PublisherProbe<CsrfToken> chainResult = PublisherProbe.empty();
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		given(this.repository.loadToken(any())).willReturn(Mono.empty());
		given(this.repository.generateToken(any())).willReturn(chainResult.mono());
		given(this.chain.filter(any())).willReturn(Mono.empty());
		this.csrfFilter.filter(this.get, this.chain).block();
		Mono<CsrfToken> result = this.get.getAttribute(CsrfToken.class.getName());
		result.block();
		result.block();
		assertThat(chainResult.subscribeCount()).isEqualTo(1);
	}

	private CsrfToken createXorCsrfToken() {
		ServerCsrfTokenRequestHandler handler = new XorServerCsrfTokenRequestAttributeHandler();
		MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
		handler.handle(exchange, Mono.just(this.token));
		Mono<CsrfToken> csrfToken = exchange.getAttribute(CsrfToken.class.getName());
		return csrfToken.block();
	}

	@RestController
	static class OkController {

		@RequestMapping("/**")
		String ok() {
			return "ok";
		}

	}

}


text:
/*
 * Author: John Hsu, Nate Koenig, Dave Coleman
 * Desc: External interfaces for Gazebo
 */

#include <gazebo/common/SystemPaths.hh>
#include <gazebo/common/Plugin.hh>

#include <ros/ros.h>
#include <ros/package.h>

#include <map>

namespace gazebo
{

typedef std::vector<std::string> V_string;
typedef std::map<std::string, std::string> M_string;

class GazeboRosPathsPlugin : public SystemPlugin
{
public:
  GazeboRosPathsPlugin()
  {
    this->LoadPaths();
  }

  ~GazeboRosPathsPlugin()
  {
  };

  void Init()
  {
  }

  void Load(int argc, char** argv)
  {
  }

  /**
   * @brief Set Gazebo Path/Resources Configurations GAZEBO_MODEL_PATH, PLUGIN_PATH and
            GAZEBO_MEDIA_PATH by adding paths to GazeboConfig based on ros::package
   */
  void LoadPaths()
  {
    // set gazebo media paths by adding all packages that exports "gazebo_media_path" for gazebo
    gazebo::common::SystemPaths::Instance()->gazeboPathsFromEnv = false;
    std::vector<std::string> gazebo_media_paths;
    ros::package::getPlugins("gazebo_ros","gazebo_media_path",gazebo_media_paths);
    for (std::vector<std::string>::iterator iter=gazebo_media_paths.begin(); iter != gazebo_media_paths.end(); iter++)
    {
      ROS_DEBUG("med path %s",iter->c_str());
      gazebo::common::SystemPaths::Instance()->AddGazeboPaths(iter->c_str());
    }

    // set gazebo plugins paths by adding all packages that exports "plugin_path" for gazebo
    gazebo::common::SystemPaths::Instance()->pluginPathsFromEnv = false;
    std::vector<std::string> plugin_paths;
    ros::package::getPlugins("gazebo_ros","plugin_path",plugin_paths);
    for (std::vector<std::string>::iterator iter=plugin_paths.begin(); iter != plugin_paths.end(); iter++)
    {
      ROS_DEBUG("plugin path %s",(*iter).c_str());
      gazebo::common::SystemPaths::Instance()->AddPluginPaths(iter->c_str());
    }

    // set model paths by adding all packages that exports "gazebo_model_path" for gazebo
    gazebo::common::SystemPaths::Instance()->modelPathsFromEnv = false;
    std::vector<std::string> model_paths;
    ros::package::getPlugins("gazebo_ros","gazebo_model_path",model_paths);
    for (std::vector<std::string>::iterator iter=model_paths.begin(); iter != model_paths.end(); iter++)
    {
      ROS_DEBUG("model path %s",(*iter).c_str());
      gazebo::common::SystemPaths::Instance()->AddModelPaths(iter->c_str());
    }

    // set .gazeborc path to something else, so we don't pick up default ~/.gazeborc
    std::string gazeborc = ros::package::getPath("gazebo_ros")+"/.do_not_use_gazeborc";
    setenv("GAZEBORC",gazeborc.c_str(),1);
  }

};

// Register this plugin with the simulator
GZ_REGISTER_SYSTEM_PLUGIN(GazeboRosPathsPlugin)

}


text:
package com.msi.tough.cf;

import com.msi.tough.engine.resource.Resource;
import com.msi.tough.security.AESSecurity;

public class AccountType implements Resource {

    private long id;
    private String name;
    private String accessKey;
    private String secretKey;
    private String tenant;
    private String defSecurityGroups;
    private String defKeyName;
    private String defZone;

    public String getAccessKey() {
        return accessKey;
    }

    @Override
    public Object getAtt(final String key) {
        if (key.equals("Id")) {
            return id;
        }
        if (key.equals("Name")) {
            return name;
        }
        if (key.equals("AccessKey")) {
            return accessKey;
        }
        if (key.equals("SecretKey")) {
            return secretKey;
        }
        if (key.equals("DefSecurityGroups")) {
            return defSecurityGroups;
        }
        if (key.equals("DefKeyName")) {
            return defKeyName;
        }
        throw new RuntimeException("invalid key " + key);
    }

    public String getDefKeyName() {
        return defKeyName;
    }

    public String getDefSecurityGroups() {
        return defSecurityGroups;
    }

    public String getDefZone() {
        return defZone;
    }

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getSecretKey() {
        return AESSecurity.decrypt(secretKey);
    }

    public String getTenant() {
        return tenant;
    }

    @Override
    public Object ref() {
        return this;
    }

    public void setAccessKey(final String accessKey) {
        this.accessKey = accessKey;
    }

    public void setDefKeyName(final String defKeyName) {
        this.defKeyName = defKeyName;
    }

    public void setDefSecurityGroups(final String defSecurityGroups) {
        this.defSecurityGroups = defSecurityGroups;
    }

    public void setDefZone(final String defZone) {
        this.defZone = defZone;
    }

    public void setId(final long id) {
        this.id = id;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public void setSecretKey(final String secretKey) {
        this.secretKey = AESSecurity.encrypt(secretKey);
    }

    public void setTenant(final String tenant) {
        this.tenant = tenant;
    }

}


text:
EditorEnemyDummyTrigger = EditorEnemyDummyTrigger or class(MissionScriptEditor)
function EditorEnemyDummyTrigger:create_element()
	self.super.create_element(self)
	self._element.class = "ElementEnemyDummyTrigger"
	self._element.values.event = "death"
	self._element.values.elements = {}
end

function EditorEnemyDummyTrigger:_build_panel()
	self:_create_panel()
	self:BuildElementsManage("elements", nil, {"ElementSpawnEnemyDummy", "ElementSpawnEnemyGroup", "ElementSpawnCivilian", "ElementSpawnCivilianGroup"})
	self:ComboCtrl("event", {
		"alerted",
		"death",
		"killshot",
		"fled",
		"spawn",
		"panic",
		"weapons_hot",
		"tied",
		"anim_act_01",
		"anim_act_02",
		"anim_act_03",
		"anim_act_04",
		"anim_act_05",
		"anim_act_06",
		"anim_act_07",
		"anim_act_08",
		"anim_act_09",
		"anim_act_10"
	})
end


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

<title>org.java_websocket.exceptions Class Hierarchy</title>
<meta name="date" content="2014-07-23">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.java_websocket.exceptions

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

java.lang.Throwable (implements java.io.Serializable)

java.lang.Exception

org.java_websocket.exceptions.InvalidDataException

org.java_websocket.exceptions.InvalidFrameException

org.java_websocket.exceptions.InvalidHandshakeException

org.java_websocket.exceptions.LimitExedeedException

java.lang.RuntimeException

org.java_websocket.exceptions.IncompleteHandshakeException

org.java_websocket.exceptions.NotSendableException

org.java_websocket.exceptions.WebsocketNotConnectedException

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
"""Predicting poker hand's strength with artificial neural networks in Python"""

from __future__ import absolute_import, print_function
from argparse import ArgumentParser as Parser
import os

from numpy import copy
from pybrain.structure.modules import LinearLayer, SoftmaxLayer, TanhLayer
from pybrain.supervised.trainers import BackpropTrainer, RPropMinusTrainer
from pybrain.tools.shortcuts import buildNetwork
from pybrain.tools.validation import Validator

from load import load_data

TRAIN_METHODS = {'gdm': BackpropTrainer,
                 'rp': RPropMinusTrainer}

ACTIVATION_FNS = {'purelin': LinearLayer,
                  'tansig': TanhLayer}

def get_parser():
    """Parse command-line arguments"""
    parser = Parser(description='Train neural network to classify poker hands')
    parser.add_argument('-a', '--activation', type=str,
                        nargs='?', default='tansig',
                        help='hidden layer activation fn (default: tansig)')
    parser.add_argument('-me', '--max_epochs', type=int, nargs='?', default=1000,
                        help='# of training iterations (default: 1000)')
    parser.add_argument('-hn', '--hidden-neurons', type=int, nargs='?', default=10,
                        help='# of hidden neuron units (default: 10)')
    parser.add_argument('-lr', '--learning-rate', type=float,
                        nargs='?', default=0.01,
                        help='controls size of weight changes (default: 0.01)')
    parser.add_argument('-m', '--method', type=str, nargs='?', default='rp',
                        help='training method (default: rp)')
    parser.add_argument('-nt', '--num-testing', type=int,
                        nargs='?', default='25000',
                        help='# of testing inputs (default: 25000)')
    parser.add_argument('-wtr', '--write-training-results', action='store_true',
                        help='write training results as well as testing')
    parser.add_argument('-v', '--verbose', help='print status messages',
                        action='store_true')
    return parser

def train(args, training_ds):
    """Build and train feed-forward neural network

       Keyword arguments:
       args -- program arguments (dict)
       training_ds -- suit, ranks, and target hands (list)
    """
    # Build a feed-forward network with x hidden units
    if args['verbose']:
        print('\nBuilding network:')
        print('\tinput neurons: {}'.format(training_ds.indim))
        print('\thidden neurons: {}'.format(args['hidden_neurons']))
        print('\toutput neurons: {}'.format(training_ds.outdim))
        print('\thidden layer activation fn: {}'.format(args['activation']))
        print('\toutput layer activation fn: softmax')

    ff_network = buildNetwork(training_ds.indim,
                              args['hidden_neurons'],
                              training_ds.outdim,
                              hiddenclass=ACTIVATION_FNS[args['activation']],
                              outclass=SoftmaxLayer)

    if args['verbose']:
        print('Network built.')

    # Train using user-specified method and training data for n epochs
    momentum = 0.0
    if args['method'] == 'gdm':
        momentum = 0.7
    if args['verbose']:
        print('\nTraining network:')
        print('\tmax epochs: {}'.format(args['max_epochs']))
        print('\ttraining method: {}'.format(args['method']))
        print('\tmomentum: {}'.format(momentum))
        print('\tlearning rate: {}'.format(args['learning_rate']))

    trainer = TRAIN_METHODS[args['method']](ff_network, dataset=training_ds,
                                            verbose=args['verbose'],
                                            momentum=momentum,
                                            learningrate=args['learning_rate'])

    try:
        trainer.trainEpochs(args['max_epochs'])
    except (KeyboardInterrupt, EOFError):
        pass

    return trainer, ff_network

def bit_array_transform(output):
    """Transforms activated outputs into a bit array representation"""
    def bit_transform(arr):
        # Largest weight becomes 1 in the bit array
        bit_arr = copy(arr)
        greatest = bit_arr.argmax()
        bit_arr[:] = 0
        bit_arr[greatest] = 1
        return bit_arr

    return [bit_transform(x) for x in output]

def evaluate(args, trainer, ff_network, training_ds, testing_ds, sim_num, header):
    """Evaluate the networks hit rate and MSE on training and testing"""
    if args['verbose']:
        print('\nEvaluating the networks hit rate and MSE:')
    print('\tTotal epochs: %4d' % trainer.totalepochs)

    def dataset_eval(dataset):
        """Return dataset hit rate and MSE"""
        # Transform output values to bit vectors, similar to the targets
        predicted = bit_array_transform(ff_network.activate(x)
                                        for x in dataset['input'])
        target = dataset['target']

        # Lists of positions holding predicted and target classes to compare
        predicted_pos = [list(x).index(1) for x in predicted]
        target_pos = [list(x).index(1) for x in target]

        hits = Validator.classificationPerformance(predicted_pos, target_pos)
        mse = Validator.MSE(predicted, target)
        return hits, mse

    def write_eval_results():
        """Write simulation results to a pipe-delimited text file"""
        with open('results/simulation{}.txt'.format(sim_num), 'a') as sim_file:
            sim_file.write('{}\n'.format('|'.join(str(args[x]) for x in header)))

    print('\n\tTraining set:')
    tr_hits, tr_mse = dataset_eval(training_ds)
    print('\t\tHit rate: {}'.format(tr_hits))
    print('\t\tMSE: {}'.format(tr_mse))

    print('\n\tTesting set:')
    te_hits, te_mse = dataset_eval(testing_ds)
    print('\t\tHit rate: {}'.format(te_hits))
    print('\t\tMSE: {}'.format(te_mse))

    # Write simulation results for testing set only (unless specified)
    if args['write_training_results']:
        args['hits'] = tr_hits
        args['mse'] = tr_mse

        write_eval_results()
        args['write_training_results'] = False

    args['hits'] = te_hits
    args['mse'] = te_mse
    write_eval_results()

def run_simulation(args, sim_num=0, header=None):
    """Run ANN simulation"""
    # Always run verbosely (for now)
    args['verbose'] = True

    # Load training and test data
    training_ds, testing_ds = load_data(args)

    # Build and train feed-forward neural network
    trainer, ff_network = train(args, training_ds)

    # Initialize results output file with given or default header
    if header is None:
        header = ['hidden_neurons', 'learning_rate', 'max_epochs',
                  'activation', 'hits', 'mse']

    # Create results directory to hold simulation files if not existing
    if not os.path.exists('results'):
        os.makedirs('results')

    # Write table header to simulation file
    with open('results/simulation{}.txt'.format(sim_num), 'a') as sim_file:
        sim_file.write('{}\n'.format('|'.join(header)))

    # Use the trainer to evaluate the network on the training and test data
    evaluate(args, trainer, ff_network, training_ds, testing_ds, sim_num, header)

def command_line_runner():
    """Handle command-line interaction"""
    parser = get_parser()
    args = vars(parser.parse_args())

    run_simulation(args)

if __name__ == '__main__':
    command_line_runner()


text:
package org.owasp.esapi.waf.internal;

/**
 * A simple object to represent a name=value HTTP parameter.
 *
 * @author Arshan Dabirsiaghi
 * @deprecated
 */
public class Parameter {

	private String name;
	private String value;
	private boolean fromMultipart;

	public Parameter(String name, String value, boolean fromMultipart) {
		this.name = name;
		this.value = value;
		this.fromMultipart = fromMultipart;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}

}


text:
package io.cozmic.usher.plugins.core;

import io.cozmic.usher.core.EncoderPlugin;
import io.cozmic.usher.message.PipelinePack;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;

/**
 * Created by chuck on 7/9/15.
 */
public class JsonEncoder implements EncoderPlugin {
    private JsonObject configObj;
    private Vertx vertx;

    @Override
    public void encode(PipelinePack pipelinePack, Handler<Buffer> bufferHandler) {
        final JsonObject message = pipelinePack.getMessage();
        final Buffer buffer = Buffer.buffer(message.toString());

        bufferHandler.handle(buffer);
    }

    @Override
    public EncoderPlugin createNew() {
        final JsonEncoder jsonEncoder = new JsonEncoder();
        jsonEncoder.init(configObj, vertx);
        return jsonEncoder;
    }

    @Override
    public void init(JsonObject configObj, Vertx vertx) {

        this.configObj = configObj;
        this.vertx = vertx;
    }
}