text:
import _ from 'lodash';
import 'ui/field_format_editor/pattern/pattern';
import 'ui/stringify/icons';
import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format';
import urlTemplate from 'ui/stringify/editors/url.html';
export default function UrlFormatProvider(Private, highlightFilter) {

  let FieldFormat = Private(IndexPatternsFieldFormatProvider);

  _.class(Url).inherits(FieldFormat);
  function Url(params) {
    Url.Super.call(this, params);
    this._compileTemplate = _.memoize(this._compileTemplate);
  }

  Url.id = 'url';
  Url.title = 'Url';
  Url.fieldType = [
    'number',
    'boolean',
    'date',
    'ip',
    'string',
    'murmur3',
    'unknown',
    'conflict'
  ];

  Url.editor = {
    template: urlTemplate,
    controllerAs: 'url',
    controller: function ($scope) {
      let iconPattern = '/bundles/src/ui/public/stringify/icons/{{value}}.png';

      this.samples = {
        a: [ 'john', '/some/pathname/asset.png', 1234 ],
        img: [ 'go', 'stop', ['de', 'ne', 'us', 'ni'], 'cv' ]
      };

      $scope.$watch('editor.formatParams.type', function (type, prev) {
        let params = $scope.editor.formatParams;
        if (type === 'img' && type !== prev && !params.urlTemplate) {
          params.urlTemplate = iconPattern;
        }
      });
    }
  };

  Url.templateMatchRE = /{{([\s\S]+?)}}/g;
  Url.paramDefaults = {
    type: 'a',
    urlTemplate: null,
    labelTemplate: null
  };

  Url.urlTypes = [
    { id: 'a', name: 'Link' },
    { id: 'img', name: 'Image' }
  ];

  Url.prototype._formatUrl = function (value) {
    let template = this.param('urlTemplate');
    if (!template) return value;

    return this._compileTemplate(template)({
      value: encodeURIComponent(value),
      rawValue: value
    });
  };

  Url.prototype._formatLabel = function (value, url) {
    let template = this.param('labelTemplate');
    if (url == null) url = this._formatUrl(value);
    if (!template) return url;

    return this._compileTemplate(template)({
      value: value,
      url: url
    });
  };

  Url.prototype._convert = {
    text: function (value) {
      return this._formatLabel(value);
    },

    html: function (rawValue, field, hit) {
      let url = _.escape(this._formatUrl(rawValue));
      let label = _.escape(this._formatLabel(rawValue, url));

      switch (this.param('type')) {
        case 'img':
          return '';
        default:
          if (hit && hit.highlight && hit.highlight[field.name]) {
            label = highlightFilter(label, hit.highlight[field.name]);
          }

          return '' + label + '';
      }
    }
  };

  Url.prototype._compileTemplate = function (template) {
    let parts = template.split(Url.templateMatchRE).map(function (part, i) {
      // trim all the odd bits, the variable names
      return (i % 2) ? part.trim() : part;
    });

    return function (locals) {
      // replace all the odd bits with their local var
      let output = '';
      let i = -1;
      while (++i < parts.length) {
        if (i % 2) {
          if (locals.hasOwnProperty(parts[i])) {
            let local = locals[parts[i]];
            output += local == null ? '' : local;
          }
        } else {
          output += parts[i];
        }
      }

      return output;
    };
  };

  return Url;
};


text:
@interface TestSFViewController : UIViewController {

	SFScene	*theScene;
	SFContext *theContext;

	GLfloat offset;

	SFLayer *layer;
	SFLayer *layer2;

}

@end

redpajama_set_name: RedPajamaGithub


text:
@interface PodsDummy_React_RCTBlob : NSObject
@end
@implementation PodsDummy_React_RCTBlob
@end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="com.amrdevelopment.xmlparser.MainActivity">

    <TextView
            android:text="Hello World!"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    <ProgressBar
            android:id="@+id/progressBar"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:maxHeight="5dip"
            android:minHeight="5dip"
            android:visibility="invisible" >
    </ProgressBar>

</RelativeLayout>


text:
using Assets.Scripts.Data.Interfaces;
using Assets.Scripts.Data.Model.Objects;
using Assets.Scripts.Data.Model.Telemetrics;
using System.Collections.Generic;
using UnityEngine;

namespace Assets.Scripts.Data.Providers
{
    public sealed class TestDataProvider : IDataProvider
    {
        public List<Building> LoadBuildings()
        {
            return new List<Building>(0);
        }

        public List<MoveableObject> LoadMoveableObjects()
        {
            var moveableObjects = new List<MoveableObject>
            {
                BuildEmployee(0, 43.586955, 39.716298, 5f, 139.119f, "Kristin Garcia", "Accountant", "Accounting"),
                BuildEmployee(1, 43.585888, 39.719431, 10f, 29.307f, "Diane Woods", "Manager", "Customer service"),
                BuildEmployee(2, 43.589140, 39.720010, 0f, 30.2f, "Clifton Ryan", "Director", "Leadership"),
                BuildVehicle(3, 43.599800, 39.730257, 90f, -13.167f, "Toyota Celica", "A 111 BC 23"),
                BuildVehicle(4, 43.592829, 39.737904, 60f, -48.449f, "Honda Civic", "D 222 EF 93"),
                BuildVehicle(5, 43.584737, 39.738638, 45f, 115.004f, "Opel Astra", "G 333 HI 123")
            };
            return moveableObjects;
        }

        public List<TrackPoint> UpdateMoveableObjectLocations()
        {
            var locations = new List<TrackPoint>
            {
                new TrackPoint(0, 43.581387, 39.722955, 5f, 139.119f),
                new TrackPoint(1, 43.593074, 39.725001, 10f, 29.307f),
                new TrackPoint(2, 43.593620, 39.723616, 0f, 30.2f),
                new TrackPoint(3, 43.601215, 39.729797, 90f, -13.167f),
                new TrackPoint(4, 43.593942, 39.736162, 60f, -48.449f),
                new TrackPoint(5, 43.583654, 39.741845, 45f, 115.004f)
            };
            return locations;
        }

        private static Employee BuildEmployee(int id, double lat, double lng, float speed, float course,
            string name, string job, string department)
        {
            var go = new GameObject(string.Format("{0} ({1})", name, job));
            var employee = go.AddComponent<Employee>();
            employee.Id = id;
            employee.Latitude = lat;
            employee.Longitude = lng;
            employee.Speed = speed;
            employee.Course = course;
            employee.Name = name;
            employee.JobPosition = job;
            employee.Department = department;
            return employee;
        }

        private static Vehicle BuildVehicle(int id, double lat, double lng, float speed, float course,
            string brandModel, string regNumber)
        {
            var go = new GameObject(string.Format("{0} {1}", brandModel, regNumber));
            var vehicle = go.AddComponent<Vehicle>();
            vehicle.Id = id;
            vehicle.Latitude = lat;
            vehicle.Longitude = lng;
            vehicle.Speed = speed;
            vehicle.Course = course;
            vehicle.BrandModel = brandModel;
            vehicle.RegNumber = regNumber;
            return vehicle;
        }
    }
}


text: JSNLog receiver middleware for ASP.NET Core


text:
package io.c12.bala.db.domain;

/**
 * @author b.palaniappan
 *
 */
public class InternetAddress {

	private String internetAddress;
	private InternetAddressType internetAddressType;

	public String getInternetAddress() {
		return internetAddress;
	}
	public void setInternetAddress(String internetAddress) {
		this.internetAddress = internetAddress;
	}
	public InternetAddressType getInternetAddressType() {
		return internetAddressType;
	}
	public void setInternetAddressType(InternetAddressType internetAddressType) {
		this.internetAddressType = internetAddressType;
	}

}


text:
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework.Internal;
using NUnit.TestUtilities.Collections;

namespace NUnit.Framework.Constraints
{
    [TestFixture]
    public class CollectionSupersetConstraintTests : ConstraintTestBase
    {
        [SetUp]
        public void SetUp()
        {
            TheConstraint = new CollectionSupersetConstraint(new int[] { 1, 2, 3, 4, 5 });
            StringRepresentation = "<supersetof System.Int32[]>";
            ExpectedDescription = "superset of < 1, 2, 3, 4, 5 >";
        }

        static object[] SuccessData = new object[]
        {
            new int[] { 1, 2, 3, 4, 5, 6 }
            , new int[] { 1, 2, 3, 4, 5 }
            , new int[] { 1, 2, 2, 2, 3, 4, 5, 3 }
            , new int[] { 1, 2, 2, 2, 3, 4, 5, 7 }
        };

        static object[] FailureData = new object[]
        {
            new object[] { new int[] { 1, 3, 7 }, "< 1, 3, 7 >" }
            , new object[] { new int[] { 1, 2, 2, 2, 5 }, "< 1, 2, 2, 2, 5 >" }
            , new object[] { new int[] { 1, 2, 3, 5 }, "< 1, 2, 3, 5 >" }
            , new object[] { new int[] { 1, 2, 3, 5, 7 }, "< 1, 2, 3, 5, 7 >" }
        };

        [Test]
        [TestCaseSource(typeof(IgnoreCaseDataProvider), nameof(IgnoreCaseDataProvider.TestCases))]
        public void HonorsIgnoreCase( IEnumerable expected, IEnumerable actual )
        {
            var constraint = new CollectionSupersetConstraint( expected ).IgnoreCase;
            var constraintResult = constraint.ApplyTo( actual );
            if ( !constraintResult.IsSuccess )
            {
                MessageWriter writer = new TextMessageWriter();
                constraintResult.WriteMessageTo( writer );
                Assert.Fail( writer.ToString() );
            }
        }

        public class IgnoreCaseDataProvider
        {
            public static IEnumerable TestCases
            {
                get
                {
                    yield return new TestCaseData(new SimpleObjectCollection("z", "Y", "X"), new SimpleObjectCollection("w", "x", "y", "z"));
                    yield return new TestCaseData(new object[] {'a', 'b', 'c'}, new[] {'A', 'B', 'C', 'D', 'E'});
                    yield return new TestCaseData(new object[] { "A", "C", "B" }, new[] { "a", "b", "c", "d", "e" });
                    yield return new TestCaseData(new Dictionary<int, string> { { 1, "A" } }, new Dictionary<int, string> { { 1, "a" }, { 2, "b" } });
                    yield return new TestCaseData(new Dictionary<int, char> { { 1, 'a' } }, new Dictionary<int, char> { { 1, 'A' }, { 2, 'B' } });
                    yield return new TestCaseData(new Dictionary<string, int> { { "b", 2 } }, new Dictionary<string, int> { { "b", 2 }, { "a", 1 } });
                    yield return new TestCaseData(new Dictionary<char, int> { { 'a', 1 } }, new Dictionary<char, int> { { 'A', 1 }, { 'B', 2 } });

#if !NETCOREAPP1_1
                    yield return new TestCaseData(new Hashtable { { 1, "A" } }, new Hashtable { { 1, "a" }, { 2, "b" } });
                    yield return new TestCaseData(new Hashtable { { 2, 'b' } }, new Hashtable { { 1, 'A' }, { 2, 'B' } });
                    yield return new TestCaseData(new Hashtable { { "A", 1 } }, new Hashtable { { "b", 2 }, { "a", 1 } });
                    yield return new TestCaseData(new Hashtable { { 'a', 1 } }, new Hashtable { { 'A', 1 }, { 'B', 2 } });
#endif
                }
            }
        }

        [Test]
        public void IsSuperSetHonorsUsingWhenCollectionsAreOfDifferentTypes()
        {
            ICollection set = new SimpleObjectCollection("2", "3");
            ICollection superSet = new SimpleObjectCollection(1, 2, 3, 4, 5);

            Assert.That(superSet, Is.SupersetOf(set).Using<int, string>((i, s) => i.ToString() == s));
        }
    }
}


text:
import webob.exc

from nova.api.ec2 import cloud
from nova.api.ec2 import ec2utils
from nova.api.ec2 import inst_state
from nova.compute import power_state
from nova.compute import utils as compute_utils
from nova.compute import vm_states
from nova import context
from nova import db
from nova import exception
from nova import flags
from nova.image import fake
from nova import log as logging
from nova.openstack.common import importutils
from nova import rpc
from nova import test

LOG = logging.getLogger(__name__)
FLAGS = flags.FLAGS

class EC2ValidateTestCase(test.TestCase):
    def setUp(self):
        super(EC2ValidateTestCase, self).setUp()
        self.flags(connection_type='fake',
                   stub_network=True)

        def dumb(*args, **kwargs):
            pass

        self.stubs.Set(compute_utils, 'notify_about_instance_usage', dumb)
        # set up our cloud
        self.cloud = cloud.CloudController()

        # set up services
        self.compute = self.start_service('compute')
        self.scheduter = self.start_service('scheduler')
        self.network = self.start_service('network')
        self.volume = self.start_service('volume')
        self.image_service = importutils.import_object(FLAGS.image_service)

        self.user_id = 'fake'
        self.project_id = 'fake'
        self.context = context.RequestContext(self.user_id,
                                              self.project_id,
                                              is_admin=True)

        self.EC2_MALFORMED_IDS = ['foobar', '', 123]
        self.EC2_VALID__IDS = ['i-284f3a41', 'i-001', 'i-deadbeef']

        self.ec2_id_exception_map = [(x, exception.InvalidInstanceIDMalformed)
                for x in self.EC2_MALFORMED_IDS]
        self.ec2_id_exception_map.extend([(x, exception.InstanceNotFound)
                for x in self.EC2_VALID__IDS])
        self.volume_id_exception_map = [(x,
                exception.InvalidInstanceIDMalformed)
                for x in self.EC2_MALFORMED_IDS]
        self.volume_id_exception_map.extend([(x, exception.VolumeNotFound)
                for x in self.EC2_VALID__IDS])

        def fake_show(meh, context, id):
            return {'id': id,
                    'container_format': 'ami',
                    'properties': {
                        'kernel_id': 'cedef40a-ed67-4d10-800e-17455edce175',
                        'ramdisk_id': 'cedef40a-ed67-4d10-800e-17455edce175',
                        'type': 'machine',
                        'image_state': 'available'}}

        self.stubs.Set(fake._FakeImageService, 'show', fake_show)
        self.stubs.Set(fake._FakeImageService, 'show_by_name', fake_show)

        # NOTE(comstud): Make 'cast' behave like a 'call' which will
        # ensure that operations complete
        self.stubs.Set(rpc, 'cast', rpc.call)

        # make sure we can map ami-00000001/2 to a uuid in FakeImageService
        db.api.s3_image_create(self.context,
                               'cedef40a-ed67-4d10-800e-17455edce175')
        db.api.s3_image_create(self.context,
                               '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6')

    #EC2_API tests (InvalidInstanceID.Malformed)
    def test_console_output(self):
        for ec2_id, e in self.ec2_id_exception_map:
            self.assertRaises(e,
                              self.cloud.get_console_output,
                              context=self.context,
                              instance_id=[ec2_id])

    def test_describe_instance_attribute(self):
        for ec2_id, e in self.ec2_id_exception_map:
            self.assertRaises(e,
                              self.cloud.describe_instance_attribute,
                              context=self.context,
                              instance_id=ec2_id,
                              attribute='kernel')

    def test_instance_lifecycle(self):
        lifecycle = [self.cloud.terminate_instances,
                            self.cloud.reboot_instances,
                            self.cloud.stop_instances,
                            self.cloud.start_instances,
                    ]
        for cmd in lifecycle:
            for ec2_id, e in self.ec2_id_exception_map:
                self.assertRaises(e,
                                  cmd,
                                  context=self.context,
                                  instance_id=[ec2_id])

    def test_create_image(self):
        for ec2_id, e in self.ec2_id_exception_map:
            self.assertRaises(e,
                              self.cloud.create_image,
                              context=self.context,
                              instance_id=ec2_id)

    def test_create_snapshot(self):
        for ec2_id, e in self.volume_id_exception_map:
            self.assertRaises(e,
                              self.cloud.create_snapshot,
                              context=self.context,
                              volume_id=ec2_id)

    def test_describe_volumes(self):
        for ec2_id, e in self.volume_id_exception_map:
            self.assertRaises(e,
                              self.cloud.describe_volumes,
                              context=self.context,
                              volume_id=[ec2_id])

    def test_delete_volume(self):
        for ec2_id, e in self.volume_id_exception_map:
            self.assertRaises(e,
                              self.cloud.delete_volume,
                              context=self.context,
                              volume_id=ec2_id)

    def test_detach_volume(self):
        for ec2_id, e in self.volume_id_exception_map:
            self.assertRaises(e,
                              self.cloud.detach_volume,
                              context=self.context,
                              volume_id=ec2_id)


text:
CREATE OR REPLACE TYPE CUR_TwoValues AS OBJECT
       (Assay   VARCHAR(255),
        Value1  VARCHAR2(255),
        Value2  VARCHAR2(255),
        SampleID INTEGER);
/
CREATE OR REPLACE TYPE CUR_TwoValues_Table AS TABLE OF CUR_TwoValues;
/
exit;


text:
"""
This module runs tests on the ROACH1 in baseband mode using mock hardware.
"""
from kid_readout.roach.baseband import RoachBaseband
from kid_readout.roach.tests.mock_roach import MockRoach
from kid_readout.roach.tests.mock_valon import MockValon
from kid_readout.roach.tests.mixin import RoachMixin, Roach1Mixin, BasebandSoftwareMixin, MockMixin

class TestRoach1BasebandMock(RoachMixin, Roach1Mixin, BasebandSoftwareMixin, MockMixin):

    @classmethod
    def setup_class(cls):
        cls.ri = RoachBaseband(roach=MockRoach('roach'), adc_valon=MockValon(), initialize=False)


text:
/* ************************************ */
/*       Define Helper Functions        */
/* ************************************ */

function getDisplayElement() {
    $('

').appendTo('body')
    return $('

').appendTo('body')
}

function addID() {
	jsPsych.data.addDataToLastTrial({exp_id: 'spatial_task_switching_with_cued_task_switching'})
}

function evalAttentionChecks() {
  var check_percent = 1
  if (run_attention_checks) {
    var attention_check_trials = jsPsych.data.getTrialsOfType('attention-check')
    var checks_passed = 0
    for (var i = 0; i < attention_check_trials.length; i++) {
      if (attention_check_trials[i].correct === true) {
        checks_passed += 1
      }
    }
    check_percent = checks_passed / attention_check_trials.length
  }
  return check_percent
}

function assessPerformance() {
	var experiment_data = jsPsych.data.getTrialsOfType('poldrack-single-stim')
	var missed_count = 0
	var trial_count = 0
	var rt_array = []
	var rt = 0
	var correct = 0
		//record choices participants made
	var choice_counts = {}
	choice_counts[-1] = 0
	choice_counts[77] = 0
	choice_counts[90] = 0

	for (var i = 0; i < experiment_data.length; i++) {
		if (experiment_data[i].trial_id == 'test_trial') {
			trial_count += 1
			rt = experiment_data[i].rt
			key = experiment_data[i].key_press
			choice_counts[key] += 1
			if (rt == -1) {
				missed_count += 1
			} else {
				rt_array.push(rt)
			}

			if (key == experiment_data[i].correct_response) {
				correct += 1
			}

		}
	}

	//calculate average rt
	var avg_rt = -1
	if (rt_array.length !== 0) {
		avg_rt = math.median(rt_array)
	}
	//calculate whether response distribution is okay
	var responses_ok = true
	Object.keys(choice_counts).forEach(function(key, index) {
		if (choice_counts[key] > trial_count * 0.85) {
			responses_ok = false
		}
	})
	var missed_percent = missed_count/trial_count
	var accuracy = correct / trial_count
	credit_var = (missed_percent < 0.25 && avg_rt > 200 && responses_ok && accuracy > 0.60)
	jsPsych.data.addDataToLastTrial({final_credit_var: credit_var,
									 final_missed_percent: missed_percent,
									 final_avg_rt: avg_rt,
									 final_responses_ok: responses_ok,
									 final_accuracy: accuracy})
}

var randomDraw = function(lst) {
  var index = Math.floor(Math.random() * (lst.length))
  return lst[index]
}

function getAllIndexes(arr, val) {
    var indexes = [], i = -1;
    while ((i = arr.indexOf(val, i+1)) != -1){
        indexes.push(i);
    }
    return indexes;
}

function getAllIndexesList(arr,val){
	all_indexes = []
	for(var i = 0; i < arr.length; i++){
		indexes = getAllIndexes(arr[i],val)
		if (indexes.length !== 0){
			indexes.push(i)
			all_indexes.push(indexes)
		}
	}
	//this function will return an array, temp, containing indexes for the item, val, in the list of lists, arr.
	//Temp, will have as many lists, as how many list in lists that we can find at least 1 match for the item, val.  The values in each list in temp, are the indexes for that val in that list from the list of lists
	//The LAST value in each of the lists in, temp, shows which of the lists in arr, the indexes were found from.

	// this function searches a list of list containing strings, for a value.  Will itterively search each list in lists, for a str.
	return all_indexes
}

var getResponse = function() {
	return correct_response
}

var getInstructFeedback = function() {
	return '

' + feedback_instruct_text +
		'

'
}

var getFeedback = function() {
	return '

' + feedback_text + '

'
}

var getCue = function(){
	var cue_html = task_boards[whichQuadrant - 1][0] +
				   	'

' + curr_cue + '

' +
				   task_boards[whichQuadrant - 1][1]

  	return cue_html
}

var getFixation = function(){
	stim = stims.shift()
	left_number = stim.left_number
	left_magnitude = stim.left_magnitude
	left_parity = stim.left_parity
	right_number = stim.right_number
	right_magnitude = stim.right_magnitude
	right_parity = stim.right_parity
	correct_response = stim.correct_response
	whichQuadrant = stim.whichQuadrant

	cued_condition = stim.cued_condition
	cued_switch_condition = stim.cued_switch_condition
	curr_task = stim.curr_task
	curr_cue = stim.curr_cue
	predictable_condition = stim.predictable_condition
	predictable_dimension = stim.predictable_dimension

	var fixation_html = '

+

'

  	return fixation_html
}

var getStim = function(){

	return task_boards[whichQuadrant - 1][0] +
		   	'

' + curr_cue + '

' +
		   	'
' +
				'

' + preFileType + left_number + fileTypePNG + '

'+
				'

'+ preFileType + right_number + fileTypePNG + '

'+
		    '
'+
		   task_boards[whichQuadrant - 1][1]
}

var getCorrectResponse = function(number, predictable_dimension){
	if (number > 5){
		magnitude = 'high'
	} else if (number < 5){
		magnitude = 'low'
	}

	if (number%2 === 0){
		parity = 'even'
	} else if (number%2 !== 0) {
		parity = 'odd'
	}

	par_ind = predictable_dimensions_list[0].values.indexOf(parity)
	if (par_ind == -1){
		par_ind = predictable_dimensions_list[1].values.indexOf(parity)
		mag_ind = predictable_dimensions_list[0].values.indexOf(magnitude)
	} else {
		mag_ind = predictable_dimensions_list[1].values.indexOf(magnitude)
	}

	if (predictable_dimension == 'magnitude'){
		correct_response = possible_responses[mag_ind][1]
	} else if (predictable_dimension == 'parity'){
		correct_response = possible_responses[par_ind][1]
	}

	return [correct_response,magnitude,parity]

}

//added for spatial task
var makeTaskSwitches = function(numTrials) {
	task_switch_arr = ["tstay_cstay", "tstay_cswitch", "tswitch_cswitch", "tswitch_cswitch"]

	out = jsPsych.randomization.repeat(task_switch_arr, numTrials / 4)
	return out
}

//added for spatial task
var getQuad = function(oldQuad, curr_switch) {
	var out;
	switch(curr_switch){
		case "tstay_cstay":
			out = oldQuad
			break
		case "tstay_cswitch":
			if (oldQuad%2==0) { // if even (2,4), subtract 1
				out = oldQuad - 1
			} else {
				out = oldQuad + 1 //if odd (1,3), add 1
			}
			break
		case "tswitch_cswitch":
			if (oldQuad < 3) { //if in top quadrants (1,2)
				out = Math.ceil(Math.random() * 2) + 2 // should return 3 or 4
			} else  { //if in bottom quadrants (3,4)
				out = Math.ceil(Math.random() * 2)  // should return 1 or 2
			}
			break
	}
	return out;
}

var createTrialTypes = function(task_switches, numTrialsPerBlock){
	var whichQuadStart = jsPsych.randomization.repeat([1,2,3,4],1).pop()
	var predictable_cond_array = predictable_conditions[whichQuadStart%2]
	var predictable_dimensions = [predictable_dimensions_list[0].dim,
								 predictable_dimensions_list[0].dim,
								 predictable_dimensions_list[1].dim,
								 predictable_dimensions_list[1].dim]

	numbers_list = [[6,8],[7,9],[2,4],[1,3]]
	numbers = [1,2,3,4,6,7,8,9]

	/*
	var cued_condition_type_list = []
	var cued_switch_condition_type_list = []
	for(var i = 0; i < 4; i++){
		cued_condition_type_list.push(jsPsych.randomization.repeat(['switch','stay'], numTrialsPerBlock/8))
		cued_switch_condition_type_list.push(jsPsych.randomization.repeat(['switch','stay'], numTrialsPerBlock/8))
	}
	*/
	var all_two_by_two_conditions = []
	var numbers_list = [[6,8],[7,9],[2,4],[1,3]]
	var task_conds = ['switch','stay']
	var cue_conds = ['switch','stay']

	for (var z = 0; z < numbers_list.length; z++){
		var task_cue_conditions = []
		for(var i = 0; i < numTrialsPerBlock / (numbers_list.length*task_conds.length*cue_conds.length); i++){
			for (var x = 0; x < task_conds.length; x++){
				for (var y = 0; y < cue_conds.length; y++){

					task_cue_cond = {
						task_cond: task_conds[x],
						cue_cond: cue_conds[y]

					}

					task_cue_conditions.push(task_cue_cond)
				}
			}
		}
		task_cue_conditions = jsPsych.randomization.repeat(task_cue_conditions, 1)
		all_two_by_two_conditions.push(task_cue_conditions)
	}

	predictable_dimension = predictable_dimensions[whichQuadStart - 1]
	curr_task = jsPsych.randomization.repeat(['left','right'],1).pop()
	curr_cue = tasks[curr_task].cues[Math.floor((Math.random() * 2))]

	if (curr_task == 'left'){
		left_number = numbers[Math.floor((Math.random() * 8))]
		right_number = randomDraw(numbers.filter(function(y) {return y != left_number}))

		left_response_arr = getCorrectResponse(left_number,predictable_dimension)
		right_response_arr = getCorrectResponse(left_number,predictable_dimension)

		correct_response = left_response_arr[0]

		left_magnitude = left_response_arr[1]
		left_parity = left_response_arr[2]
		right_magnitude = right_response_arr[1]
		right_parity = right_response_arr[2]
	} else if (curr_task == 'right'){
		right_number = numbers[Math.floor((Math.random() * 8))]
		left_number = randomDraw(numbers.filter(function(y) {return y != right_number}))

		left_response_arr = getCorrectResponse(left_number,predictable_dimension)
		right_response_arr = getCorrectResponse(right_number,predictable_dimension)

		correct_response = right_response_arr[0]

		left_magnitude = left_response_arr[1]
		left_parity = left_response_arr[2]
		right_magnitude = right_response_arr[1]
		right_parity = right_response_arr[2]
	}

	var stims = []

	var first_stim = {
		whichQuadrant: whichQuadStart,
		predictable_condition: 'N/A',
		predictable_dimension: predictable_dimension,
		cued_condition: 'N/A',
		cued_switch_condition: 'N/A',
		curr_task: curr_task,
		curr_cue: curr_cue,
		left_number: left_number,
		left_magnitude: left_magnitude,
		left_parity: left_parity,
		right_number: right_number,
		right_magnitude: right_magnitude,
		right_parity: right_parity,
		correct_response: correct_response
		}
	stims.push(first_stim)

	oldQuad = whichQuadStart
	for (var ii = 0; ii < task_switches.length; ii++){
		whichQuadStart += 1
		quadIndex = whichQuadStart%4
		if (quadIndex === 0){
			quadIndex = 4
		}

		quadIdx = getQuad(oldQuad, task_switches[ii]) //changed for spatial task

		var temp_2_cond = all_two_by_two_conditions[quadIndex - 1].pop()
		cued_condition = temp_2_cond.task_cond
		cued_switch_condition = temp_2_cond.cue_cond
		predictable_dimension = predictable_dimensions[quadIdx - 1]
		predictable_condition = predictable_cond_array[ii%2]

		last_task = curr_task
		if (cued_condition == "switch"){ // if switch tasks, pick a random cue and switch to other task
			cued_switch_condition = 'switch'
			curr_task = randomDraw(['left','right'].filter(function(y) {return $.inArray(y, [last_task]) == -1}))
			curr_cue = tasks[curr_task].cues[Math.floor(Math.random() * 2)]
		} else if (cued_condition == "stay"){ // if stay tasks, if cued_switch condition is switch, then switch to other cue, stay if not.
			if (cued_switch_condition == 'switch'){
			last_cue = curr_cue
			curr_cue = randomDraw(tasks[curr_task].cues.filter(function(y) {return $.inArray(y, [last_cue]) == -1}))
			}

		}

		if (curr_task == 'left'){
			left_number = numbers[Math.floor((Math.random() * 8))]
			right_number = randomDraw(numbers.filter(function(y) {return y != left_number}))

			left_response_arr = getCorrectResponse(left_number,predictable_dimension)
			right_response_arr = getCorrectResponse(right_number,predictable_dimension)

			correct_response = left_response_arr[0]

			left_magnitude = left_response_arr[1]
			left_parity = left_response_arr[2]

			right_magnitude = right_response_arr[1]
			right_parity = right_response_arr[2]
		} else if (curr_task == 'right'){
			right_number = numbers[Math.floor((Math.random() * 8))]
			left_number = randomDraw(numbers.filter(function(y) {return y != right_number}))

			left_response_arr = getCorrectResponse(left_number,predictable_dimension)
			right_response_arr = getCorrectResponse(right_number,predictable_dimension)

			correct_response = right_response_arr[0]

			left_magnitude = left_response_arr[1]
			left_parity = left_response_arr[2]
			right_magnitude = right_response_arr[1]
			right_parity = right_response_arr[2]
		}

		stim = {
			whichQuadrant: quadIdx,
			predictable_condition: predictable_condition,
			predictable_dimension: predictable_dimension,
			cued_condition: cued_condition,
			cued_switch_condition: cued_switch_condition,
			curr_task: curr_task,
			curr_cue: curr_cue,
			left_number: left_number,
			left_magnitude: left_magnitude,
			left_parity: left_parity,
			right_number: right_number,
			right_magnitude: right_magnitude,
			right_parity: right_parity,
			correct_response: correct_response
			}

		stims.push(stim)

		oldQuad = quadIdx //changed for sptial task
	}
	return stims
}

var getCTI = function(){
	return CTI
}

var appendData = function(){
	curr_trial = jsPsych.progress().current_trial_global
	trial_id = jsPsych.data.getDataByTrialIndex(curr_trial).trial_id
	current_trial+=1
	task_switch = 'na'
	if (current_trial > 1) {
		task_switch = task_switches[current_trial - 2] //this might be off
	}

	if (trial_id == 'practice_trial'){
		current_block = practiceCount
	} else if (trial_id == 'test_trial'){
		current_block = testCount
	}

	jsPsych.data.addDataToLastTrial({
		whichQuadrant: whichQuadrant,
		predictable_condition: predictable_condition,
		predictable_dimension: predictable_dimension,
		task_switch: task_switch,
		task_condition: cued_condition,
		cue_condition: cued_switch_condition,
		curr_task: curr_task,
		curr_cue: curr_cue,
		left_number: left_number,
		left_magnitude: left_magnitude,
		left_parity: left_parity,
		right_number: right_number,
		right_magnitude: right_magnitude,
		right_parity: right_parity,
		correct_response: correct_response,
		current_trial: current_trial,
		current_block: current_block,
		CTI: CTI

	})

	if (jsPsych.data.getDataByTrialIndex(curr_trial).key_press == correct_response){
		jsPsych.data.addDataToLastTrial({
			correct_trial: 1,
		})

	} else if (jsPsych.data.getDataByTrialIndex(curr_trial).key_press != correct_response){
		jsPsych.data.addDataToLastTrial({
			correct_trial: 0,
		})

	}
}

/* ************************************ */
/*    Define Experimental Variables     */
/* ************************************ */
// generic task variables
var sumInstructTime = 0 //ms
var instructTimeThresh = 0 ///in seconds
var credit_var = 0
var run_attention_checks = true

var practice_len = 16 // must be divisible by 16
var exp_len = 240 //320 must be divisible by 16
var numTrialsPerBlock = 48 // 64 must be divisible by 16
var numTestBlocks = exp_len / numTrialsPerBlock
var CTI = 150

var accuracy_thresh = 0.75
var rt_thresh = 1000
var missed_thresh = 0.10
var practice_thresh = 3  // 3 blocks of 16 trials

var pathSource = "/static/experiments/spatial_task_switching_with_cued_task_switching/images/"
var fileTypePNG = ".png'>"
var preFileType = "<img class = center src='/static/experiments/spatial_task_switching_with_cued_task_switching/images/"

var numbers_list = [[6,8],[7,9],[2,4],[1,3]]

var predictable_conditions = [['switch','stay'],
							 ['stay','switch']]

var predictable_dimensions_list = [stim = {dim:'magnitude', values: ['high','low']},
								  stim = {dim:'parity', values: ['even','odd']}]

var possible_responses = [['M Key', 77],['Z Key', 90]]

var cued_conditions = jsPsych.randomization.repeat(['stay','switch'],1)
var curr_tasks = jsPsych.randomization.repeat(['right','left'],1)

var tasks = {
  left: {
    task: 'Left',
    cues: ['left', 'first']
  },
  right: {
    task: 'Right',
    cues: ['right', 'second']
  }
}

var current_trial = 0

var prompt_text_list = '
'+
						'
Top 2 quadrants: Judge cued number on '+predictable_dimensions_list[0].dim+'
' +
						'
'+predictable_dimensions_list[0].values[0]+': ' + possible_responses[0][0] + '
' +
						'
'+predictable_dimensions_list[0].values[1]+': ' + possible_responses[1][0] + '
' +
						'
Bottom 2 quadrants: Judge cued number on '+predictable_dimensions_list[1].dim+'
' +
						'
'+predictable_dimensions_list[1].values[0]+': ' + possible_responses[0][0] + '
' +
						'
'+predictable_dimensions_list[1].values[1]+': ' + possible_responses[1][0] + '
' +
						'
Cue was left or first, judge left number
' +
						'
Cue was right or second, judge right number
' +
					  '
'

var prompt_text = '
'+
					  '
Top 2 quadrants: Judge cued number on '+predictable_dimensions_list[0].dim+'
' +
					  '
'+predictable_dimensions_list[0].values[0]+': ' + possible_responses[0][0] + ' | ' + predictable_dimensions_list[0].values[1]+': ' + possible_responses[1][0] + '
' +
					  '
&nbsp
' +
					  '
Bottom 2 quadrants: Judge cued number on '+predictable_dimensions_list[1].dim+'
' +
					  '
'+predictable_dimensions_list[1].values[0]+': ' + possible_responses[0][0] + ' | ' + predictable_dimensions_list[1].values[1]+': ' + possible_responses[1][0] + '
' +
					  '
Cue was left or first, judge left number
' +
					  '
Cue was right or second, judge right number
' +
				  '
'

//PRE LOAD IMAGES HERE
var pathSource = "/static/experiments/spatial_task_switching_with_cued_task_switching/images/"
var numbersPreload = ['1','2','3','4','6','7','8','9']
var images = []

for(i=0;i<numbersPreload.length;i++){
	images.push(pathSource + numbersPreload[i] + '.png')
}

jsPsych.pluginAPI.preloadImages(images);

/* ************************************ */
/*          Define Game Boards          */
/* ************************************ */

var task_boards = [[['

'],['

']],
				   [['

'],['

']],
				   [['

'],['

']],
				   [['

'],['

']]]

var task_switches = makeTaskSwitches(practice_len)
var stims = createTrialTypes(task_switches, practice_len)

/* ************************************ */
/*        Set up jsPsych blocks         */
/* ************************************ */
// Set up attention check node
var attention_check_block = {
  type: 'attention-check',
  data: {
    trial_id: "attention_check"
  },
  timing_response:  180000,
  response_ends_trial: true,
  timing_post_trial: 200
}

var attention_node = {
  timeline: [attention_check_block],
  conditional_function: function() {
    return run_attention_checks
  }
}

//Set up post task questionnaire
var post_task_block = {
   type: 'survey-text',
   data: {
       exp_id: "spatial_task_switching_with_cued_task_switching",
       trial_id: "post task questions"
   },
   questions: ['
Please summarize what you were asked to do in this task.
',
              '
Do you have any comments about this task?
'],
   rows: [15, 15],
   timing_response:  360000,
   columns: [60,60]
};

var end_block = {
	type: 'poldrack-text',
	data: {
		trial_id: "end",
	},
	timing_response:  180000,
	text: '

Thanks for completing this task!

Press enter to continue.

',
	cont_key: [13],
	timing_post_trial: 0,
	on_finish: function(){
		assessPerformance()
		evalAttentionChecks()
    }
};

var feedback_instruct_text =
	'Welcome to the experiment. This experiment will take around 15 minutes. Press enter to begin.'
var feedback_instruct_block = {
	type: 'poldrack-text',
	data: {
		trial_id: "instruction"
	},
	cont_key: [13],
	text: getInstructFeedback,
	timing_post_trial: 0,
	timing_response:  180000
};

/// This ensures that the subject does not read through the instructions too quickly.  If they do it too quickly, then we will go over the loop again.
var instructions_block = {
	type: 'poldrack-instructions',
	data: {
		trial_id: "instruction"
	},
	pages: [
		'
'+
			'
In this experiment, across trials you will see a cue, either left, first, right, or second, followed by 2 numbers moving clockwise on the screen in 4 quadrants.  '+
			'On any trial, one quadrant will have a cue, followed by 2 numbers.
 '+

			'
The cue will instruct you which of the following 2 numbers, you must make a judgement on.
'+

			'
If you see the cue, left or first, please judge the upcoming left number.
'+

			'
If you saw the cue, right or second, please judge the upcoming right number.
'+

		'
',

		'
'+
			'
You will be asked to judge the cued number on magnitude (higher or lower than 5) or parity (odd or even), depending on which quadrant '+
			'the cue and numbers are in.
'+

			'
In the top two quadrants, please judge the cued number based on '+predictable_dimensions_list[0].dim+'. Press the '+possible_responses[0][0]+
			'  if '+predictable_dimensions_list[0].values[0]+', and the '+possible_responses[1][0]+'  if '+predictable_dimensions_list[0].values[1]+'.
'+
			/*In the top two quadrants, please judge the cued number based on magnitude. Press the M Key if high, and the Z Key if low.*/

			'
In the bottom two quadrants, please judge the cued number based on '+predictable_dimensions_list[1].dim+'.'+
			' Press the '+possible_responses[0][0]+' if '+predictable_dimensions_list[1].values[0]+', and the '+possible_responses[1][0]+
			' if '+predictable_dimensions_list[1].values[1]+'.
'+
			/*In the bottom two quadrants, please judge the cued number based on parity. Press the M Key if even, and the Z Key if odd.*/

			'
Please judge only the cued number for that trial!
'+
		'
',

		'
'+
			'
We will start practice after you finish instructions. Please make sure you understand the instructions before moving on. During practice, you will receive a reminder of the rules.  This reminder will not be available for test.
'+
			'
To avoid technical issues, please keep the experiment tab (on Chrome or Firefox) active and in full-screen mode for the whole duration of each task.
'+
		'
'
	],
	allow_keys: false,
	show_clickable_nav: true,
	timing_post_trial: 1000
};

/* This function defines stopping criteria */

var instruction_node = {
	timeline: [feedback_instruct_block, instructions_block],

	loop_function: function(data) {
		for (i = 0; i < data.length; i++) {
			if ((data[i].trial_type == 'poldrack-instructions') && (data[i].rt != -1)) {
				rt = data[i].rt
				sumInstructTime = sumInstructTime + rt
			}
		}
		if (sumInstructTime <= instructTimeThresh * 1000) {
			feedback_instruct_text =
				'Read through instructions too quickly.  Please take your time and make sure you understand the instructions.  Press enter to continue.'
			return true
		} else if (sumInstructTime > instructTimeThresh * 1000) {
			feedback_instruct_text = 'Done with instructions. Press enter to continue.'
			return false
		}
	}
}

var start_test_block = {
	type: 'poldrack-text',
	data: {
		trial_id: "instruction"
	},
	timing_response:  180000,
	text: '
'+
			'
We will now start the test portion
'+

			'
You will see a cue, either left, first, right, or second, which will instruct you to judge the upcoming right or left number.
'+

			'
Please judge the cued number on magnitude (higher or lower than 5) or parity (odd or even), depending on which quadrant '+
			'the cues and numbers are in.
'+

			'
In the top two quadrants, please judge the cued number based on '+predictable_dimensions_list[0].dim+'. Press the '+possible_responses[0][0]+
			'  if '+predictable_dimensions_list[0].values[0]+', and the '+possible_responses[1][0]+'  if '+predictable_dimensions_list[0].values[1]+'.
'+

			'
In the bottom two quadrants, please judge the cued number based on '+predictable_dimensions_list[1].dim+'.'+
			' Press the '+possible_responses[0][0]+' if '+predictable_dimensions_list[1].values[0]+', and the '+possible_responses[1][0]+
			' if '+predictable_dimensions_list[1].values[1]+'.
'+

			'
Please judge only the cued number for that trial!
'+

			'
You will no longer receive the rule prompt, so remember the instructions before you continue. Press Enter to begin.
'+
		 '
',
	cont_key: [13],
	timing_post_trial: 1000,
	on_finish: function(){
		feedback_text = "We will now start the test portion. Press enter to begin."
	}
};

var fixation_block = {
	type: 'poldrack-single-stim',
	stimulus: '

+

',
	is_html: true,
	choices: 'none',
	data: {
		trial_id: "practice_fixation"
	},
	timing_response:  500, //500
	timing_post_trial: 0,
}

var feedback_text =
'Welcome to the experiment. This experiment will take around 15 minutes. Press enter to begin.'
var feedback_block = {
	type: 'poldrack-single-stim',
	data: {
		exp_id: "spatial_task_switching_with_cued_task_switching",
		trial_id: "practice-no-stop-feedback"
	},
	choices: [13],
	stimulus: getFeedback,
	timing_post_trial: 0,
	is_html: true,
	timing_response:  180000,
	response_ends_trial: true,

};

/* ************************************ */
/*        Set up timeline blocks        */
/* ************************************ */

var practiceTrials = []
practiceTrials.push(feedback_block)
practiceTrials.push(instructions_block)
for (i = 0; i < practice_len + 1; i++) {
	var fixation_block = {
	  type: 'poldrack-single-stim',
	  stimulus: getFixation,
	  is_html: true,
	  choices: 'none',
	  data: {
		trial_id: "fixation"
	  },
	  timing_post_trial: 0,
	  timing_stim: 500, //500
	  timing_response:  500, //500
	  prompt: prompt_text
	}

	var cue_block = {
		type: 'poldrack-single-stim',
		stimulus: getCue,
		is_html: true,
		data: {
			"trial_id": "practice_cue_block",
		},
		choices: 'none',
		timing_stim: getCTI, //getCTI
		timing_response:  getCTI, //getCTI
		timing_post_trial: 0,
		response_ends_trial: false,
		prompt: prompt_text
	}

	var practice_block = {
		type: 'poldrack-categorize',
		stimulus: getStim,
		is_html: true,
		choices: [possible_responses[0][1],possible_responses[1][1]],
		key_answer: getResponse,
		data: {
			trial_id: "practice_trial"
			},
		correct_text: '

Correct!

' + prompt_text,
		incorrect_text: '

Incorrect

' + prompt_text,
		timeout_message: '

Respond Faster!

' + prompt_text,
		timing_stim: 1000, //1000
		timing_response:  2000, //2000
		timing_feedback_duration: 500,
		show_stim_with_feedback: false,
		timing_post_trial: 0,
		on_finish: appendData,
		prompt: prompt_text
	}
	practiceTrials.push(fixation_block)
	practiceTrials.push(cue_block)
	practiceTrials.push(practice_block)
}

var practiceCount = 0
var practiceNode = {
	timeline: practiceTrials,
	loop_function: function(data) {
		practiceCount += 1
		task_switches = makeTaskSwitches(practice_len)
		stims = createTrialTypes(task_switches, practice_len)
		current_trial = 0

		var sum_rt = 0
		var sum_responses = 0
		var correct = 0
		var total_trials = 0

		for (var i = 0; i < data.length; i++){
			if (data[i].trial_id == "practice_trial"){
				total_trials+=1
				if (data[i].rt != -1){
					sum_rt += data[i].rt
					sum_responses += 1
					if (data[i].key_press == data[i].correct_response){
						correct += 1

					}
				}

			}

		}

		var accuracy = correct / total_trials
		var missed_responses = (total_trials - sum_responses) / total_trials
		var ave_rt = sum_rt / sum_responses

		feedback_text = "
Please take this time to read your feedback and to take a short break! Press enter to continue"

		if (accuracy > accuracy_thresh){
			feedback_text +=
					'

Done with this practice. Press Enter to continue.'
			task_switches = makeTaskSwitches(numTrialsPerBlock)
			stims = createTrialTypes(task_switches, numTrialsPerBlock)
			return false

		} else if (accuracy < accuracy_thresh){
			feedback_text +=
					'

We are going to try practice again to see if you can achieve higher accuracy.  Remember:
' + prompt_text_list
			if (missed_responses > missed_thresh){
				feedback_text +=
						'

You have not been responding to some trials.  Please respond on every trial that requires a response.'
			}

	      	if (ave_rt > rt_thresh) {
	        	feedback_text +=
	            	'

You have been responding too slowly.'
	      	}

			if (practiceCount == practice_thresh){
				feedback_text +=
					'

Done with this practice.'
					task_switches = makeTaskSwitches(numTrialsPerBlock)
					stims = createTrialTypes(task_switches, numTrialsPerBlock)
					return false
			}

			feedback_text +=
				'

Redoing this practice. Press Enter to continue.'

			return true

		}

	}
}

var testTrials = []
testTrials.push(feedback_block)
testTrials.push(attention_node)
for (i = 0; i < numTrialsPerBlock + 1; i++) {
	var fixation_block = {
	  type: 'poldrack-single-stim',
	  stimulus: getFixation,
	  is_html: true,
	  choices: 'none',
	  data: {
		trial_id: "fixation"
	  },
	  timing_post_trial: 0,
	  timing_stim: 500, //500
	  timing_response:  500 //500
	}

	var cue_block = {
		type: 'poldrack-single-stim',
		stimulus: getCue,
		is_html: true,
		data: {
			"trial_id": "test_cue_block",
		},
		choices: 'none',
		timing_stim: getCTI, //getCTI
		timing_response:  getCTI, //getCTI
		timing_post_trial: 0,
		response_ends_trial: false,
	}

	var test_block = {
		type: 'poldrack-single-stim',
		stimulus: getStim,
		is_html: true,
		data: {
			"trial_id": "test_trial",
		},
		choices: [possible_responses[0][1],possible_responses[1][1]],
		timing_stim: 1000, //1000
		timing_response:  2000, //2000
		timing_post_trial: 0,
		response_ends_trial: false,
		on_finish: appendData
	}
	testTrials.push(fixation_block)
	testTrials.push(cue_block)
	testTrials.push(test_block)
}

var testCount = 0
var testNode = {
	timeline: testTrials,
	loop_function: function(data) {
	testCount += 1
	task_switches = makeTaskSwitches(numTrialsPerBlock)
	stims = createTrialTypes(task_switches, numTrialsPerBlock)
	current_trial = 0

	var sum_rt = 0
		var sum_responses = 0
		var correct = 0
		var total_trials = 0

		for (var i = 0; i < data.length; i++){
			if (data[i].trial_id == "test_trial"){
				total_trials+=1
				if (data[i].rt != -1){
					sum_rt += data[i].rt
					sum_responses += 1
					if (data[i].key_press == data[i].correct_response){
						correct += 1

					}
				}

			}

		}

		var accuracy = correct / total_trials
		var missed_responses = (total_trials - sum_responses) / total_trials
		var ave_rt = sum_rt / sum_responses

		feedback_text = "
Please take this time to read your feedback and to take a short break! Press enter to continue"
		feedback_text += "

You have completed: "+testCount+" out of "+numTestBlocks+" blocks of trials."

		if (accuracy < accuracy_thresh){
			feedback_text +=
					'

Your accuracy is too low.  Remember:
' + prompt_text_list
		}
		if (missed_responses > missed_thresh){
			feedback_text +=
					'

You have not been responding to some trials.  Please respond on every trial that requires a response.'
		}

      	if (ave_rt > rt_thresh) {
        	feedback_text +=
            	'

You have been responding too slowly.'
      	}

		if (testCount == numTestBlocks){
			feedback_text +=
					'

Done with this test. Press Enter to continue.
 If you have been completing tasks continuously for an hour or more, please take a 15-minute break before starting again.'
			return false
		} else {

			return true
		}

	}
}

/* ************************************ */
/*          Set up Experiment           */
/* ************************************ */

var spatial_task_switching_with_cued_task_switching_experiment = []

spatial_task_switching_with_cued_task_switching_experiment.push(practiceNode);
spatial_task_switching_with_cued_task_switching_experiment.push(feedback_block);

spatial_task_switching_with_cued_task_switching_experiment.push(start_test_block);
spatial_task_switching_with_cued_task_switching_experiment.push(testNode);
spatial_task_switching_with_cued_task_switching_experiment.push(feedback_block);

spatial_task_switching_with_cued_task_switching_experiment.push(post_task_block);
spatial_task_switching_with_cued_task_switching_experiment.push(end_block);


text:
<?php

/**
*       TECHMOB - Empresa Júnior da Faculdade de Computação - UFU
*
*       Controlador da Area de Suporte
*
*       @author: Jean Fabrício <jeanufu21@gmail.com>
*       @since 12/02/2016
*
*/
class SuporteController extends BaseController{

	public function getIndex()
	{

		return View::make("suporte.suporte");
	}

}


text:
import pickle

from django import forms
from django.db import models
from django.test import SimpleTestCase, TestCase
from django.utils.functional import lazy

from .models import (
    Foo, RenamedField, VerboseNameField, Whiz, WhizIter, WhizIterEmpty,
)

class Nested:
    class Field(models.Field):
        pass

class BasicFieldTests(TestCase):

    def test_show_hidden_initial(self):
        """
        Fields with choices respect show_hidden_initial as a kwarg to
        formfield().
        """
        choices = [(0, 0), (1, 1)]
        model_field = models.Field(choices=choices)
        form_field = model_field.formfield(show_hidden_initial=True)
        self.assertTrue(form_field.show_hidden_initial)

        form_field = model_field.formfield(show_hidden_initial=False)
        self.assertFalse(form_field.show_hidden_initial)

    def test_field_repr(self):
        """
        __repr__() of a field displays its name.
        """
        f = Foo._meta.get_field('a')
        self.assertEqual(repr(f), '<django.db.models.fields.CharField: a>')
        f = models.fields.CharField()
        self.assertEqual(repr(f), '<django.db.models.fields.CharField>')

    def test_field_repr_nested(self):
        """__repr__() uses __qualname__ for nested class support."""
        self.assertEqual(repr(Nested.Field()), '<model_fields.tests.Nested.Field>')

    def test_field_name(self):
        """
        A defined field name (name="fieldname") is used instead of the model
        model's attribute name (modelname).
        """
        instance = RenamedField()
        self.assertTrue(hasattr(instance, 'get_fieldname_display'))
        self.assertFalse(hasattr(instance, 'get_modelname_display'))

    def test_field_verbose_name(self):
        m = VerboseNameField
        for i in range(1, 23):
            self.assertEqual(m._meta.get_field('field%d' % i).verbose_name, 'verbose field%d' % i)

        self.assertEqual(m._meta.get_field('id').verbose_name, 'verbose pk')

    def test_choices_form_class(self):
        """Can supply a custom choices form class to Field.formfield()"""
        choices = [('a', 'a')]
        field = models.CharField(choices=choices)
        klass = forms.TypedMultipleChoiceField
        self.assertIsInstance(field.formfield(choices_form_class=klass), klass)

    def test_formfield_disabled(self):
        """Field.formfield() sets disabled for fields with choices."""
        field = models.CharField(choices=[('a', 'b')])
        form_field = field.formfield(disabled=True)
        self.assertIs(form_field.disabled, True)

    def test_field_str(self):
        f = models.Field()
        self.assertEqual(str(f), '<django.db.models.fields.Field>')
        f = Foo._meta.get_field('a')
        self.assertEqual(str(f), 'model_fields.Foo.a')

    def test_field_ordering(self):
        """Fields are ordered based on their creation."""
        f1 = models.Field()
        f2 = models.Field(auto_created=True)
        f3 = models.Field()
        self.assertLess(f2, f1)
        self.assertGreater(f3, f1)
        self.assertIsNotNone(f1)
        self.assertNotIn(f2, (None, 1, ''))

    def test_field_instance_is_picklable(self):
        """Field instances can be pickled."""
        field = models.Field(max_length=100, default='a string')
        # Must be picklable with this cached property populated (#28188).
        field._get_default
        pickle.dumps(field)

    def test_deconstruct_nested_field(self):
        """deconstruct() uses __qualname__ for nested class support."""
        name, path, args, kwargs = Nested.Field().deconstruct()
        self.assertEqual(path, 'model_fields.tests.Nested.Field')

class ChoicesTests(SimpleTestCase):

    def test_choices_and_field_display(self):
        """
        get_choices() interacts with get_FIELD_display() to return the expected
        values.
        """
        self.assertEqual(Whiz(c=1).get_c_display(), 'First')    # A nested value
        self.assertEqual(Whiz(c=0).get_c_display(), 'Other')    # A top level value
        self.assertEqual(Whiz(c=9).get_c_display(), 9)          # Invalid value
        self.assertIsNone(Whiz(c=None).get_c_display())         # Blank value
        self.assertEqual(Whiz(c='').get_c_display(), '')        # Empty value

    def test_iterator_choices(self):
        """
        get_choices() works with Iterators.
        """
        self.assertEqual(WhizIter(c=1).c, 1)          # A nested value
        self.assertEqual(WhizIter(c=9).c, 9)          # Invalid value
        self.assertIsNone(WhizIter(c=None).c)         # Blank value
        self.assertEqual(WhizIter(c='').c, '')        # Empty value

    def test_empty_iterator_choices(self):
        """
        get_choices() works with empty iterators.
        """
        self.assertEqual(WhizIterEmpty(c="a").c, "a")      # A nested value
        self.assertEqual(WhizIterEmpty(c="b").c, "b")      # Invalid value
        self.assertIsNone(WhizIterEmpty(c=None).c)         # Blank value
        self.assertEqual(WhizIterEmpty(c='').c, '')        # Empty value

class GetChoicesTests(SimpleTestCase):

    def test_blank_in_choices(self):
        choices = [('', '<><>'), ('a', 'A')]
        f = models.CharField(choices=choices)
        self.assertEqual(f.get_choices(include_blank=True), choices)

    def test_blank_in_grouped_choices(self):
        choices = [
            ('f', 'Foo'),
            ('b', 'Bar'),
            ('Group', (
                ('', 'No Preference'),
                ('fg', 'Foo'),
                ('bg', 'Bar'),
            )),
        ]
        f = models.CharField(choices=choices)
        self.assertEqual(f.get_choices(include_blank=True), choices)

    def test_lazy_strings_not_evaluated(self):
        lazy_func = lazy(lambda x: 0 / 0, int)  # raises ZeroDivisionError if evaluated.
        f = models.CharField(choices=[(lazy_func('group'), (('a', 'A'), ('b', 'B')))])
        self.assertEqual(f.get_choices(include_blank=True)[0], ('', '---------'))


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

<TITLE>
AFPStreamer (Apache FOP 1.1 API)
</TITLE>

<META NAME="date" CONTENT="2012-10-16">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 1.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.fop.afp

Class AFPStreamer

java.lang.Object
  org.apache.fop.afp.AFPStreamer

All Implemented Interfaces:
Streamable

public class AFPStreamer
extends java.lang.Object
implements Streamable

Manages the streaming of the AFP output

Constructor Summary

AFPStreamer(Factory factory)

          Main constructor

Method Summary

 void
close()

          Closes off the AFP stream writing the document stream

 DataStream
createDataStream(AFPPaintingState paintingState)

          Creates a new DataStream

 ResourceGroup
getResourceGroup(AFPResourceLevel level)

          Returns the resource group for a given resource info

 void
setDefaultResourceGroupFilePath(java.lang.String filePath)

          Sets the default resource group file path

 void
setOutputStream(java.io.OutputStream outputStream)

          Sets the final outputstream

 void
writeToStream(java.io.OutputStream os)

          DataStream objects must implement the writeToStream()
 method to write its data to the given OutputStream

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AFPStreamer

public AFPStreamer(Factory factory)

Main constructor

Parameters:
factory - a factory

Method Detail

createDataStream

public DataStream createDataStream(AFPPaintingState paintingState)
                            throws java.io.IOException

Creates a new DataStream

Parameters:
paintingState - the AFP painting state

Returns:
a new DataStream

Throws:

java.io.IOException - thrown if an I/O exception of some sort has occurred

setDefaultResourceGroupFilePath

public void setDefaultResourceGroupFilePath(java.lang.String filePath)

Sets the default resource group file path

Parameters:
filePath - the default resource group file path

getResourceGroup

public ResourceGroup getResourceGroup(AFPResourceLevel level)

Returns the resource group for a given resource info

Parameters:
level - a resource level

Returns:
a resource group for the given resource info

close

public void close()
           throws java.io.IOException

Closes off the AFP stream writing the document stream

Throws:

java.io.IOException - if an an I/O exception of some sort has occurred

setOutputStream

public void setOutputStream(java.io.OutputStream outputStream)

Sets the final outputstream

Parameters:
outputStream - an outputstream

writeToStream

public void writeToStream(java.io.OutputStream os)
                   throws java.io.IOException

DataStream objects must implement the writeToStream()
 method to write its data to the given OutputStream

Specified by:
writeToStream in interface Streamable

Parameters:
os - the outputsteam stream

Throws:

java.io.IOException - an I/O exception of some sort has occurred.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 1.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright 1999-2012 The Apache Software Foundation. All Rights Reserved.


text:
//
//  KPHGetAllLoginsHandler.m
//  KeePassHttp-ObjC
//
//  Created by James Hurst on 2014-09-25.
//  Copyright (c) 2014 James Hurst. All rights reserved.
//

#import "KPHGetAllLoginsHandler.h"

@implementation KPHGetAllLoginsHandler

- (void)handle:(KPHRequest *)request response:(KPHResponse *)response server:(KPHServer *)server {
  [super handle:request response:response server:server];

  if (![self verifyRequest:request]) {
    return;
  }

  NSString *key = [self delegateKeyForLabel:request.Id];
  if (!key) {
    return;
  }

  KPHAESConfig *aes = [KPHAESConfig aesWithKey:key base64key:YES IV:request.Nonce base64IV:YES];
  NSURL *url = [NSURL URLWithString:[KPHUtils decryptString:request.Url withAES:aes]];
  if (!url) {
    return;
  }

  NSArray *entries = [self delegateAllEntries];

  response.Id = request.Id;
  [self setResponseVerifier:response];

  if (entries) {
    entries = [self copyEntries:entries];

    /* these should not be provided in get-all-logins */
    for (KPHResponseEntry *entry in entries) {
      entry.Password = nil;
      entry.StringFields = nil;
    }

    aes = [KPHAESConfig aesWithKey:key base64key:YES IV:response.Nonce base64IV:YES];
    response.Entries = [KPHUtils encryptEntries:entries withAES:aes];

    response.Count = response.Entries.count;
    response.Success = YES;
  }

  return;
}

@end


text:
/* Theme Name:iDea - Clean & Powerful Bootstrap Theme
 * Author:HtmlCoder
 * Author URI:http://www.htmlcoder.me
 * Author e-mail:htmlcoder.me@gmail.com
 * Version: 1.3
 * Created:October 2014
 * License URI:http://support.wrapbootstrap.com/
 * File Description: Place here your custom scripts
 */


text:
package com.hazelcast.cache.jsr;

import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class CachingTest extends org.jsr107.tck.CachingTest {

    @BeforeClass
    public static void init() {
        JsrTestUtil.setup();
    }

    @AfterClass
    public static void cleanup() {
        JsrTestUtil.cleanup();
    }

    @Test
    @Override
    public void dummyTest() {
    }
}


text:
/* input field */
.form-phone-number .form-item,
.form-phone-number .form-item label {
  display: inline;
}
.form-phone-number .form-item label {
  margin-left: 1em;
  margin-right: .5em;
}

/* admin settings */
.cck-phone-settings .form-checkboxes .form-item {
  float: left;
  width: 33%;
}

.cck-phone-settings .cck-phone-default-country {
  background: #eee;
  font-weight: bold;
}


text:
[CmdletBinding (DefaultParameterSetName="Set 2")]
param (
    [Parameter(Parametersetname = "Set 1")][String]$Inputfile
)
# Check_forwarding Johns Fork
# Version 2.0.0 20170914

Function CloseGracefully()
{
    # Close all file streams, files and sessions.
    $Stream.writeline( $Date +  " PSSession and log file closed.")
    Write-Host $Date  +  " PSSession and log file closed."
    $Stream.Close()
    $fs.Close()

    # Close PS Sessions
    Get-PSSession | Remove-PSSession
    $error.clear()
    Exit
}

Function ConnectToO365 ()
{
    $usercredential = Get-Credential # -UserName "jkontoni.admin@allegisgroup.com" -Message "Please enter:"
    $PSsessions = Get-PSSession
    foreach ($PsSession in $PSsessions)
    {
        If ($PsSession.computername -eq  "outlook.office365.com")
        {
            $O365SessionExists = $True
        }
    }
    If ( -not ($O365SessionExists))
    {
        $ProxyAddress = [System.Net.WebProxy]::GetDefaultProxy() |select-object address
        if ($ProxyAddress.address)
        {
            $proxyOptions = New-PSSessionOption -ProxyAccessType IEConfig
            $session = new-pssession -configurationname Microsoft.exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection  -SessionOption $proxyOptions
        }
        Else
        {

        } $session = new-pssession -configurationname Microsoft.exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
        Import-PSSession $session
        If (!$session)
        {
            CloseGracefully
        }
    }
}

$mode       = [System.IO.FileMode]::Create
$access     = [System.IO.FileAccess]::Write
$sharing    = [IO.FileShare]::Read
$LogPath    = [System.IO.Path]::Combine("C:\temp\ForwardingResults.csv")

# create the FileStream and StreamWriter objects
$fs = New-Object IO.FileStream($LogPath, $mode, $access, $sharing)
$Stream = New-Object System.IO.StreamWriter($fs)
$Line = "TargetUser,ForwardingSmtpAddress,ForwardingAddress"
$Stream.writeline( $line )
ConnectToO365

$Inputfile = "C:\temp\checkforwarding.csv"
$SMigratedUsersT2 = import-csv -Path $Inputfile
foreach ($MigratedUser in $SMigratedUsersT2)
{
    $TargetUser = $MigratedUser.Allegisemail
    $TMailBox = get-mailbox $TargetUser -errorAction silentlycontinue
    if ( $TMailBox)
    {
        $Line = $TargetUser + "," + $TMailBox.ForwardingSmtpAddress + "," +  $TMailBox.ForwardingAddress
        $Stream.writeline( $line )
        Write-Host $Line
    }
    else
    {
        $Line = $TargetUser + " Mailbox could not be found"
        $Stream.writeline( $line )
        Write-Host $Line -ForegroundColor Red
    }
    $TMailBox = $null
}
CloseGracefully


text:
Carrierwave plugin to mount image uploader to postgresql json & hstore fields.

## Installation

Add this line to your application's Gemfile:

`gem 'carrierwave_accessors'`

And then execute:

`$ bundle`

Or install it yourself as:

`$ gem install carrierwave_accessors`

## Usage
You don't need to add anything special

    class User < ActiveRecord::Base
      store_accessor :data, :cover_image
      store_accessor :settings, :profile_image

      mount_uploader :cover_image, CoverUploader
      mount_uploader :profile_image, ProfileUploader
    end

## Contributing

1. Fork it ( https://bitbucket.org/antonovga/carrierwave_accessors )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
'use strict';

exports.FullyConnectedLayer = require('./fully_connected_layer');
exports.SoftmaxLayer = require('./softmax_layer');


text:
<!DOCTYPE html>

        <meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>

        <link rel="stylesheet" type="text/css" href="bower_components/font-awesome/css/font-awesome.min.css"/>
        <link rel="stylesheet" type="text/css" href="css/fonts.css"/>
        <link rel="stylesheet" type="text/css" href="css/storyquest.css"/>

Charactersheet


text:
<?php

namespace LoginBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Session\Session;

use TinkerSoft\FuncionesSitioBundle\Entity\RegistroGustos;
use TinkerSoft\FuncionesSitioBundle\Entity\Usuarios;

class LoginController extends Controller
{

    public function loginOutAction(Request $request){
        $request->getSession()->invalidate(1);
        return $this->redirectToRoute('login');
    }

     public function loginAction(Request $request){

        if($request->getMethod()=="POST"){
            $em = $this->getDoctrine()->getManager();

            $usuario = $em->getRepository('TinkerSoftUsuariosBundle:Usuarios')->
            findOneBy(array('correoElectronico'=>$request->request->get('email'), 'password'=>$request->request->get('password')));

            if($usuario){
                 if($usuario->getEstado()){

                $session = $request->getSession();
                $session->set('name', $usuario->getNombres());
                $session->set('nickname', $usuario->getNickname());
                $session->set('id', $usuario->getId());
                $session->set('rol', $usuario->getRol());
               /*Rol 1 = auditor*/
               if ($usuario->getRol() == 1){
                   return $this->redirectToRoute('auditor');
               }
               /*Rol 2 = administrador*/
               if ($usuario->getRol() == 2){
                   return $this->redirectToRoute('administrador');
               }
                $gustos = $em->getRepository('FuncionesSitioBundle:RegistroGustos')->
                findOneBy(array('idUsuario'=>$usuario->getId()));

                if($gustos){
                    return $this->redirectToRoute('vista_homepage');
                }else{
                    return $this->redirectToRoute('generos_barra');
                }

            }
            else{
                      return $this->render('VistaBundle:Default:login.html.twig', array('error'=>4));

            }
            }

            else{

                 return $this->render('VistaBundle:Default:login.html.twig', array('error'=>1));

            }
        }

    }

    public function registrarGustosAction(Request $request){

        if($request->getMethod()=="POST"){

            if($request->getSession()->get('id')){

                $generos = $this->get('app.api_controller')->listaGenerosAction("en");

                $contadorGenerosSeleccionados = 0;
                $em = $this->getDoctrine()->getManager();
                $usuario = $em->getRepository('FuncionesSitioBundle:Usuarios')->findOneBy(array('id'=>$request->getSession()->get('id')));

                for($i = 0; $i < count($generos['genres']) ; $i++){

                    if($request->request->get('genero_' . $i) != ""){
                        $contadorGenerosSeleccionados++;

                        $gusto = $em->getRepository('FuncionesSitioBundle:RegistroGustos')->
                        findOneBy(array('idUsuario'=>$usuario->getId(),'generoid'=>$request->request->get('genero_' . $i)));

                        if(!$gusto){
                            $gusto = new RegistroGustos();
                            $gusto->setIdUsuario($usuario);
                            $gusto->setGeneroid($request->request->get('genero_' . $i));
                            $em = $this->getDoctrine()->getManager();
                            $em->persist($gusto);
                            $em->flush();
                        }

                    }
                }
                if($contadorGenerosSeleccionados == 0){
                    return $this->render('VistaBundle:Default:elegirGenero.html.twig', array('error'=>1,'params' => $generos));
                }else{
                    if($request->request->get('origen')=="0"){
                    return $this->redirectToRoute('vista_homepage');
                    }
                    if($request->request->get('origen')=="1"){
                    return $this->redirectToRoute('usuario');
                    }
                }
            }else{
                 return $this->render('VistaBundle:Default:login.html.twig', array('error'=>2));
            }

        }else{
                return $this->render('VistaBundle:Default:login.html.twig', array('error'=>3));
        }
    }

}


text:
package org.crazyit.intentProject5_2_1;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ComponentAttr extends Activity
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button bn = (Button) findViewById(R.id.bn);
		// Ϊbn°´Å¥°ó¶¨Ê¼þ¼àÌýÆ÷
		bn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				// ´´½¨Ò»¸öComponentName¶ÔÏó
				ComponentName comp = new ComponentName(ComponentAttr.this,
						SecondActivity.class);
				Intent intent = new Intent();
				// ΪIntentÉèÖÃComponentÊôÐÔ
				intent.setComponent(comp);
//				Intent intent = new Intent(ComponentAttr.this,
//					SecondActivity.class);
				startActivity(intent);
			}
		});
	}
}


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

<title>S-Index</title>
<meta name="date" content="2014-12-06">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E F G H I J L P R S T U V

S

setDatacenterDescription(String) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update parent datacenter's description

setDatacenterId(int) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update parent datacenter's ID

setDatacenterId(int) - Method in class eu.virtuenergy.papillon.Floor

setDatacenterId(int) - Method in interface eu.virtuenergy.papillon.I_Floor

Update the ID of the parent Datacenter of current Floor

setDatacenterName(String) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update parent datacenter's name

setDescription(String) - Method in interface eu.virtuenergy.papillon.I_Resource

Set a new description for the resource

setDescription(String) - Method in class eu.virtuenergy.papillon.Resource

setFirstName(String) - Method in interface eu.virtuenergy.users.I_UserBean

Update user's first name

setFirstName(String) - Method in class eu.virtuenergy.users.UserBean

setFloorDescription(String) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update parent Floor's description

setFloorId(int) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update parent Floor's ID

setFloorId(int) - Method in interface eu.virtuenergy.papillon.I_Rack

Update ID of the parent Floor resource

setFloorId(int) - Method in class eu.virtuenergy.papillon.Rack

setFloorName(String) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update parent Floor's Name

setHostDescription(String) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update host Description

setHostId(int) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update Host ID

setHostName(String) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update host's Name

setHostType(HostType) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update Host type

setHostType(String) - Method in class eu.virtuenergy.papillon.Host

setHostType(String) - Method in interface eu.virtuenergy.papillon.I_Host

Update the host type to one of the Enumerated types

setId(int) - Method in interface eu.virtuenergy.papillon.I_Resource

Set a new ID for the resource

setId(int) - Method in class eu.virtuenergy.papillon.Resource

setId(int) - Method in interface eu.virtuenergy.users.I_UserBean

Update user's ID

 User's ID is the primary key for users and should not be changeable.

setId(int) - Method in class eu.virtuenergy.users.UserBean

setIPAddress(String) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update IP Address

setIPaddress(String) - Method in class eu.virtuenergy.papillon.Host

setIPaddress(String) - Method in interface eu.virtuenergy.papillon.I_Host

Update the IP address of the current Host object

setLastName(String) - Method in interface eu.virtuenergy.users.I_UserBean

Update user's surname

setLastName(String) - Method in class eu.virtuenergy.users.UserBean

setLatitude(double) - Method in class eu.virtuenergy.papillon.Datacenter

setLatitude(double) - Method in interface eu.virtuenergy.papillon.I_Datacenter

Set a new latitude value for current Datacenter object

setLongitude(double) - Method in class eu.virtuenergy.papillon.Datacenter

setLongitude(double) - Method in interface eu.virtuenergy.papillon.I_Datacenter

Set a new longitude value for current Datacenter object

setModelGroupId(int) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update Power Model Group ID

setModelGroupName(String) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update Power Model Group Name

setName(String) - Method in interface eu.virtuenergy.papillon.I_Resource

Set a new name for the resource

setName(String) - Method in class eu.virtuenergy.papillon.Resource

setParentRackId(int) - Method in class eu.virtuenergy.papillon.Host

setParentRackId(int) - Method in interface eu.virtuenergy.papillon.I_Host

Update the ID of the parent Rack for the current Host object

setPassword(String) - Method in interface eu.virtuenergy.users.I_UserBean

Update user's password

 TODO: Password should not be stored in plain text.

setPassword(String) - Method in class eu.virtuenergy.users.UserBean

setPowerModelGroupId(int) - Method in class eu.virtuenergy.papillon.Host

setPowerModelGroupId(int) - Method in interface eu.virtuenergy.papillon.I_Host

Update the ID of the relevant Power Model group for the current Host object

setProcessorCount(int) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update number of processors

setRackDescription(String) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update parent Rack's Description

setRackId(int) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update parent Rack's ID

setRackName(String) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update parent Rack's Name

setUserName(String) - Method in interface eu.virtuenergy.users.I_UserBean

Update user's username

 This should be unique and not recommended to be changeable

setUserName(String) - Method in class eu.virtuenergy.users.UserBean

setValid(boolean) - Method in interface eu.virtuenergy.users.I_UserBean

Update user's validation status

setValid(boolean) - Method in class eu.virtuenergy.users.UserBean

setVMCount(int) - Method in class eu.virtuenergy.papillon.ExtendedHost

Update number of parallel VMs

setXAxis(double) - Method in class eu.virtuenergy.papillon.Floor

setXAxis(double) - Method in interface eu.virtuenergy.papillon.I_Floor

Update the X Axis grid reference for current Floor object

setXAxis(double) - Method in interface eu.virtuenergy.papillon.I_Rack

Update X Axis grid reference

setXAxis(double) - Method in class eu.virtuenergy.papillon.Rack

setYAxis(double) - Method in class eu.virtuenergy.papillon.Floor

setYAxis(double) - Method in interface eu.virtuenergy.papillon.I_Floor

Update the Y Axis grid reference for current Floor object

setYAxis(double) - Method in interface eu.virtuenergy.papillon.I_Rack

Update Y Axis grid reference

setYAxis(double) - Method in class eu.virtuenergy.papillon.Rack

A C D E F G H I J L P R S T U V

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
#import <DVTFoundation/DVTPointerFunctions.h>

// Not exported
@interface DVTConcretePointerFunctions : DVTPointerFunctions
{
    struct DVTSlice slice;
}

+ (_Bool)initializeSlice:(struct DVTSlice *)arg1 withOptions:(int)arg2;
+ (void)initializeBackingStore:(struct DVTSlice *)arg1 sentinel:(BOOL)arg2 compactable:(BOOL)arg3;
- (BOOL)usesWeakReadAndWriteBarriers;
- (BOOL)usesStrongWriteBarrier;
- (void *)relinquishFunction;
- (void *)acquireFunction;
- (void *)descriptionFunction;
- (void *)isEqualFunction;
- (void *)hashFunction;
- (void *)sizeFunction;
- (void)setUsesWeakReadAndWriteBarriers:(BOOL)arg1;
- (void)setUsesStrongWriteBarrier:(BOOL)arg1;
- (void)setRelinquishFunction:(void *)arg1;
- (void)setAcquireFunction:(void *)arg1;
- (void)setDescriptionFunction:(void *)arg1;
- (void)setIsEqualFunction:(void *)arg1;
- (void)setHashFunction:(void *)arg1;
- (void)setSizeFunction:(void *)arg1;
- (BOOL)isEqual:(id)arg1;
- (unsigned long long)hash;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (id)initWithOptions:(int)arg1;

@end


text:
{% set page="index" %}
{% extends 'allura:templates/site_admin.html' %}
{% block content %}

Neighborhood Stats

Name	Projects	Configured

  {% for name, count, count_configured in neighborhoods %}

{{name}}	{{count}}	{{count_configured}}

  {% endfor %}

{% endblock %}


text:
<?php

/**
 * Check index0h\phar\iterators\***.
 *
 * @author Roman Levishchenko <index.0h@gmail.com>
 */
class IteratorCest
{
    public function testAllFilesFound(CodeGuy $I)
    {
        $module = $I->createModuleForIterator();
        $actual = $I->getAllFilesFromIteratorByModule($module);
        $I->seeAllFilesFoundByIterator($actual);
    }
}


text:
using System;
using System.Collections.Generic;
using Contract;
using NUnit.Framework;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;

namespace API.Repository.Test
{
    public class AudioJobRepositoryTest
    {
        [Test]
        public void AddThrowsForNullRequestParameter()
        {
            // Arrange
            var fixture = new Fixture().Customize(new AutoMoqCustomization());

            IAudioJobRepository sut = fixture.Create<AudioJobRepository>();

            // Act
            var exception = Assert.Throws<ArgumentNullException>(() => sut.Add(null, new List<AudioTranscodingJob>()));

            // Assert
        }

        [Test]
        public void AddThrowsForEmptyJobsParameter()
        {
            // Arrange
            var fixture = new Fixture().Customize(new AutoMoqCustomization());

            IAudioJobRepository sut = fixture.Create<AudioJobRepository>();

            // Act
            var exception = Assert.Throws<ArgumentException>(() => sut.Add(new AudioJobRequest(), new List<AudioTranscodingJob>()));

            // Assert

        }

    }
}


text:
require 'commons/listener'

module Middlewares

  class Stream < Commons::Middleware
    include StreamAPI
  end
end


text:
#pragma once
#include <aws/iotanalytics/IoTAnalytics_EXPORTS.h>
#include <aws/iotanalytics/model/ComputeType.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace IoTAnalytics
{
namespace Model
{

  /**
   *
The configuration of the resource used to execute the
   * containerAction.

See Also:
   AWS
   * API Reference

   */
  class AWS_IOTANALYTICS_API ResourceConfiguration
  {
  public:
    ResourceConfiguration();
    ResourceConfiguration(Aws::Utils::Json::JsonView jsonValue);
    ResourceConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The type of the compute resource used to execute the
     * containerAction. Possible values are: ACU_1 (vCPU=4,
     * memory=16 GiB) or ACU_2 (vCPU=8, memory=32 GiB).

     */
    inline const ComputeType& GetComputeType() const{ return m_computeType; }

    /**
     *
The type of the compute resource used to execute the
     * containerAction. Possible values are: ACU_1 (vCPU=4,
     * memory=16 GiB) or ACU_2 (vCPU=8, memory=32 GiB).

     */
    inline bool ComputeTypeHasBeenSet() const { return m_computeTypeHasBeenSet; }

    /**
     *
The type of the compute resource used to execute the
     * containerAction. Possible values are: ACU_1 (vCPU=4,
     * memory=16 GiB) or ACU_2 (vCPU=8, memory=32 GiB).

     */
    inline void SetComputeType(const ComputeType& value) { m_computeTypeHasBeenSet = true; m_computeType = value; }

    /**
     *
The type of the compute resource used to execute the
     * containerAction. Possible values are: ACU_1 (vCPU=4,
     * memory=16 GiB) or ACU_2 (vCPU=8, memory=32 GiB).

     */
    inline void SetComputeType(ComputeType&& value) { m_computeTypeHasBeenSet = true; m_computeType = std::move(value); }

    /**
     *
The type of the compute resource used to execute the
     * containerAction. Possible values are: ACU_1 (vCPU=4,
     * memory=16 GiB) or ACU_2 (vCPU=8, memory=32 GiB).

     */
    inline ResourceConfiguration& WithComputeType(const ComputeType& value) { SetComputeType(value); return *this;}

    /**
     *
The type of the compute resource used to execute the
     * containerAction. Possible values are: ACU_1 (vCPU=4,
     * memory=16 GiB) or ACU_2 (vCPU=8, memory=32 GiB).

     */
    inline ResourceConfiguration& WithComputeType(ComputeType&& value) { SetComputeType(std::move(value)); return *this;}

    /**
     *
The size, in GB, of the persistent storage available to the resource instance
     * used to execute the containerAction (min: 1, max: 50).

     */
    inline int GetVolumeSizeInGB() const{ return m_volumeSizeInGB; }

    /**
     *
The size, in GB, of the persistent storage available to the resource instance
     * used to execute the containerAction (min: 1, max: 50).

     */
    inline bool VolumeSizeInGBHasBeenSet() const { return m_volumeSizeInGBHasBeenSet; }

    /**
     *
The size, in GB, of the persistent storage available to the resource instance
     * used to execute the containerAction (min: 1, max: 50).

     */
    inline void SetVolumeSizeInGB(int value) { m_volumeSizeInGBHasBeenSet = true; m_volumeSizeInGB = value; }

    /**
     *
The size, in GB, of the persistent storage available to the resource instance
     * used to execute the containerAction (min: 1, max: 50).

     */
    inline ResourceConfiguration& WithVolumeSizeInGB(int value) { SetVolumeSizeInGB(value); return *this;}

  private:

    ComputeType m_computeType;
    bool m_computeTypeHasBeenSet;

    int m_volumeSizeInGB;
    bool m_volumeSizeInGBHasBeenSet;
  };

} // namespace Model
} // namespace IoTAnalytics
} // namespace Aws


text:
from oslo_serialization import jsonutils as json
from six.moves.urllib import parse as urllib

from tempest.lib.api_schema.response.compute.v2_1 import volumes as schema
from tempest.lib.common import rest_client
from tempest.lib import exceptions as lib_exc
from tempest.lib.services.compute import base_compute_client

class VolumesClient(base_compute_client.BaseComputeClient):

    def list_volumes(self, detail=False, **params):
        """List all the volumes created.

        For a full list of available parameters, please refer to the official
        API reference:
        http://developer.openstack.org/api-ref-compute-v2.1.html#listVolumes
        """
        url = 'os-volumes'

        if detail:
            url += '/detail'
        if params:
            url += '?%s' % urllib.urlencode(params)

        resp, body = self.get(url)
        body = json.loads(body)
        self.validate_response(schema.list_volumes, resp, body)
        return rest_client.ResponseBody(resp, body)

    def show_volume(self, volume_id):
        """Return the details of a single volume.

        For a full list of available parameters, please refer to the official
        API reference:
        http://developer.openstack.org/api-ref-compute-v2.1.html#showVolume
        """
        url = "os-volumes/%s" % volume_id
        resp, body = self.get(url)
        body = json.loads(body)
        self.validate_response(schema.create_get_volume, resp, body)
        return rest_client.ResponseBody(resp, body)

    def create_volume(self, **kwargs):
        """Create a new Volume.

        For a full list of available parameters, please refer to the official
        API reference:
        http://developer.openstack.org/api-ref-compute-v2.1.html#createVolume
        """
        post_body = json.dumps({'volume': kwargs})
        resp, body = self.post('os-volumes', post_body)
        body = json.loads(body)
        self.validate_response(schema.create_get_volume, resp, body)
        return rest_client.ResponseBody(resp, body)

    def delete_volume(self, volume_id):
        """Delete the Specified Volume.

        For a full list of available parameters, please refer to the official
        API reference:
        http://developer.openstack.org/api-ref-compute-v2.1.html#deleteVolume
        """
        resp, body = self.delete("os-volumes/%s" % volume_id)
        self.validate_response(schema.delete_volume, resp, body)
        return rest_client.ResponseBody(resp, body)

    def is_resource_deleted(self, id):
        try:
            self.show_volume(id)
        except lib_exc.NotFound:
            return True
        return False

    @property
    def resource_type(self):
        """Return the primary type of resource this client works with."""
        return 'volume'


text:
<?php

class Zhangguoping_Commercebug_Model_Layoutviewer_Observer extends Varien_Object{
    const FLAG_SHOW_LAYOUT 			= 'showLayout';
    const FLAG_SHOW_LAYOUT_FORMAT 	= 'showLayoutFormat';
    const FLAG_SHOW_LAYOUT_FILES 	= 'showLayoutFiles';
    const HTTP_HEADER_TEXT			= 'Content-Type: text/plain';
    const HTTP_HEADER_HTML			= 'Content-Type: text/html';
    const HTTP_HEADER_XML			= 'Content-Type: application/xml';

    private $request;

    private function init() {
        $this->setLayout(Mage::app()->getFrontController()->getAction()->getLayout());
        $this->setUpdate($this->getLayout()->getUpdate());
    }

    //entry point
    public function checkForLayoutDisplayRequest($observer) {
        $shim= $this->getShim();
        if(!$shim->helper('commercebug')->isModuleOutputEnabled())
        {
            return;
        }
        $this->init();
        $is_set = array_key_exists(self::FLAG_SHOW_LAYOUT, $_GET);
        if(		$is_set && 'package' == $_GET[self::FLAG_SHOW_LAYOUT]) {
            $this->outputPackageLayout();
        }
        else if($is_set && 'page'    == $_GET[self::FLAG_SHOW_LAYOUT]) {
            $this->outputPageLayout();
        }
        else if($is_set && 'handles' == $_GET[self::FLAG_SHOW_LAYOUT]) {
            $this->outputHandles();
        }

        if(array_key_exists(self::FLAG_SHOW_LAYOUT_FILES, $_GET))
        {
            header('Content-Type: text/plain');
            foreach($this->getXmlFiles() as $file)
            {
                echo $file, "\n";
            }
            exit;
        }
    }

    private function outputHandles() {
        $update = $this->getUpdate();
        $handles = $update->getHandles();
        echo '
','Handles For This Request','
'."\n";
        echo '
' . "\n";
        foreach($handles as $handle) {
            echo '
',$handle,'
';
        }
        echo '
' . "\n";
        die();
    }

    private function outputHeaders() {
        $is_set = array_key_exists(self::FLAG_SHOW_LAYOUT_FORMAT,$_GET);
        $header		= self::HTTP_HEADER_XML;
        if($is_set && 'text' == $_GET[self::FLAG_SHOW_LAYOUT_FORMAT]) {
            $header = self::HTTP_HEADER_TEXT;
        }
        header($header);
    }

    private function outputPageLayout() {
        $layout = $this->getLayout();
        $this->outputHeaders();
        die($layout->getNode()->asXML());
    }

    private function outputPackageLayout() {
        $update = $this->getUpdate();
        $this->outputHeaders();
        die($update->getPackageLayout()->asXML());
    }

    public function getShim()
    {
        $shim = Zhangguoping_Commercebug_Model_Shim::getInstance();
        return $shim;
    }

    protected function _findFilePath($file,$base)
    {
        $file = Mage::getDesign()->getLayoutFilename($file);
        $file = trim(str_replace($base, '',$file),'/');
        return $file;
    }

    public function getXmlFiles()
    {
        $files = array();
        $nodes = Mage::app()->getConfig()->getNode('frontend/layout/updates');
        // var_dump($nodes);
        $base = Mage::getBaseDir('design');
        foreach($nodes->children() as $node)
        {
            $files[] = $this->_findFilePath((string)$node->file,$base);
        }
        $files[] = $this->_findFilePath('local.xml',$base);
        return $files;
    }
}


text:
package org.hawkular.metrics.api.jaxrs.model;

import java.util.Collections;
import java.util.Map;
import java.util.Objects;

import org.hawkular.metrics.core.api.DataPoint;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableMap;
import com.wordnik.swagger.annotations.ApiModel;

/**
 * @author jsanda
 */
@ApiModel(description = "A timestamp and a value where the value is interpreted as a floating point number")
public class GaugeDataPoint {

    @JsonProperty
    private long timestamp;

    @JsonProperty
    private Double value;

    @JsonProperty
    private Map<String, String> tags = Collections.emptyMap();

    /**
     * Used by JAX-RS/Jackson to deserialize HTTP request data
     */
    private GaugeDataPoint() {
    }

    /**
     * Used to prepared data for serialization into the HTTP response
     *
     * @param dataPoint
     */
    public GaugeDataPoint(DataPoint<Double> dataPoint) {
        timestamp = dataPoint.getTimestamp();
        value = dataPoint.getValue();
        tags = dataPoint.getTags();
    }

    public Double getValue() {
        return value;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public Map<String, String> getTags() {
        return ImmutableMap.copyOf(tags);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        GaugeDataPoint that = (GaugeDataPoint) o;
        // TODO should tags be included in equals?
        return Objects.equals(timestamp, that.timestamp) &&
                Objects.equals(value, that.value);
    }

    @Override
    public int hashCode() {
        // TODO should tags be included?
        return Objects.hash(timestamp, value);
    }

    @Override
    public String toString() {
        return com.google.common.base.Objects.toStringHelper("GaugeDataPoint")
                .add("timestamp", timestamp)
                .add("value", value)
                .add("tags", tags)
                .toString();
    }
}


text:
FROM baseboxorg/jdk6-oracle
MAINTAINER Anthony Lai <anthony.lai@hostname.io>

ENV JAVA_HEAP_SIZE 512
ENV JAVA_HOME /usr/lib/jvm/java-6-oracle

RUN apt-get -qqy install tomcat7
RUN sed -i "s|#JAVA_HOME=.*|JAVA_HOME=$JAVA_HOME|g" /etc/default/tomcat7
RUN sed -i "s|-Xmx128m|-Xmx${JAVA_HEAP_SIZE}m|g" /etc/default/tomcat7


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Win32.SafeHandles;
using System.IO;
using System.Runtime.InteropServices;

internal partial class Interop
{
    internal partial class mincore
    {
        /// <summary>
        /// WARNING: This method does not implicitly handle long paths. Use DeleteVolumeMountPoint.
        /// </summary>
        [DllImport(Libraries.CoreFile_L1, EntryPoint = "DeleteVolumeMountPointW", SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)]
        internal static extern bool DeleteVolumeMountPointPrivate(string mountPoint);

        internal static bool DeleteVolumeMountPoint(string mountPoint)
        {
            mountPoint = PathInternal.EnsureExtendedPrefixOverMaxPath(mountPoint);
            return DeleteVolumeMountPointPrivate(mountPoint);
        }
    }
}