<commit_before>(function () {
  'use strict';

  // core
  function a (o) { return o instanceof Array; }
  function atoa (a) { return Array.prototype.slice.call(a); }
  function cb (fn, args) { if (!fn) { return; } tick(function run () { fn.apply(null, args || []); }); }
  function once (fn) {
    var disposed;
    function disposable () {
      if (disposed) { return; }
      disposed = true;
      fn.apply(null, arguments);
    }
    disposable.discard = function () { disposed = true; };
    return disposable;
  }
  function handle (args, done, disposable) {
    var err = args.shift();
    if (err) { if (disposable) { disposable.discard(); } cb(done, [err]); return true; }
  }

  var tick;

  // methods
  function _waterfall (steps, done) {
    function next () {
      var d = once(done);
      return once(function callback () {
        var args = atoa(arguments);
        var step = steps.shift();
        if (step) {
          if (handle(args, d)) { return; }
          args.push(next());
          cb(step, args);
        } else {
          cb(d, arguments);
        }
      });
    }
    next()();
  }

  function _series (tasks, done) {
    var d = once(done);
    var keys = Object.keys(tasks);
    var results = a(tasks) ? [] : {};
    var pk;
    function next () {
      return once(function callback () {
        var k = keys.shift();
        var args = atoa(arguments);
        var step = tasks[k];
        if (pk) {
          if (handle(args, d)) { return; }
          results[pk] = args.shift();
        }
        pk = k;
        if (step) {
          cb(step, [next()]);
        } else {
          cb(d, [null, results]);
        }
      });
    }
    next()();
  }

  function _concurrent (tasks, done) {
    var d = once(done);
    var keys = Object.keys(tasks);
    var results = a(tasks) ? [] : {};
    var completed = 0, all = keys.length;
    keys.forEach(function iterator (key) { cb(tasks[key], [next(key)]); });
    function next (k) {
      var fn = once(function callback () {
        var args = atoa(arguments);
        if (handle(args, d, fn)) { return; }
        results[k] = args.shift();
        if (++completed === all) {
          cb(d, [null, results]);
        }
      });
      return fn;
    }
  }

  function _map (flow) {
    return function map (collection, transformer, done) {
      var keys = Object.keys(collection);
      var tasks = a(collection) ? [] : {};
      keys.forEach(function iterator (key) {
        tasks[key] = function transform (cb) {
          transformer(collection[key], cb);
        };
      });
      flow(tasks, done);
    };
  }

  function emitter () {

  }

  var _queue = function (worker, concurrency) {
    var q = [], load = 0, max = concurrency || 1;
    function _add (task, top, done) {
      var m = top ? 'unshift' : 'push';
      var tasks = task instanceof Array ? task : [task];
      tasks.forEach(function insert (t) {q[m]({ t: t, done: done }); });
      cb(labor);
    }
    function labor () {
      if (load >= max || !q.length) { return; }
      load++;
      var job = q.pop();
      worker(job.t, once(complete.bind(null, job)));
    }
    function complete (job, err) {
      load--;
      cb(job.done, [err]);
      cb(labor);
    }
    return {
      push: function (task, done) { _add(task, false, done); },
      unshift: function (task, done) { _add(task, true, done); },
      get length () { return q.length; }
    };
  };

  // api
  var $ = {
    waterfall: _waterfall,
    series: _series,
    concurrent: _concurrent,
    map: _map(_concurrent),
    queue: _queue
  };

  $.map.series = _map(_series);

  // cross-platform ticks
  if (typeof process === 'undefined' || !process.nextTick) {
    if (typeof setImmediate === 'function') {
      tick = function tick (fn) { setImmediate(fn); };
    } else {
      tick = function tick (fn) { setTimeout(fn, 0); };
    }
  } else {
    tick = typeof setImmediate === 'function' ? setImmediate : process.nextTick;
  }

  // cross-platform export
  if (typeof module !== 'undefined' && module.exports) {
    module.exports = $;
  } else if (typeof define !== 'undefined' && define.amd) {
    define([], function amd () { return $; });
  } else {
    window.a = $;
  }
})();
<commit_msg>emitter wrapper thing. awesome thing.<commit_after>(function () {
  'use strict';

  // core
  function a (o) { return o instanceof Array; }
  function atoa (a) { return Array.prototype.slice.call(a); }
  function cb (fn, args) { if (!fn) { return; } tick(function run () { fn.apply(null, args || []); }); }
  function once (fn) {
    var disposed;
    function disposable () {
      if (disposed) { return; }
      disposed = true;
      fn.apply(null, arguments);
    }
    disposable.discard = function () { disposed = true; };
    return disposable;
  }
  function handle (args, done, disposable) {
    var err = args.shift();
    if (err) { if (disposable) { disposable.discard(); } cb(done, [err]); return true; }
  }

  var tick;

  // methods
  function _waterfall (steps, done) {
    function next () {
      var d = once(done);
      return once(function callback () {
        var args = atoa(arguments);
        var step = steps.shift();
        if (step) {
          if (handle(args, d)) { return; }
          args.push(next());
          cb(step, args);
        } else {
          cb(d, arguments);
        }
      });
    }
    next()();
  }

  function _series (tasks, done) {
    var d = once(done);
    var keys = Object.keys(tasks);
    var results = a(tasks) ? [] : {};
    var pk;
    function next () {
      return once(function callback () {
        var k = keys.shift();
        var args = atoa(arguments);
        var step = tasks[k];
        if (pk) {
          if (handle(args, d)) { return; }
          results[pk] = args.shift();
        }
        pk = k;
        if (step) {
          cb(step, [next()]);
        } else {
          cb(d, [null, results]);
        }
      });
    }
    next()();
  }

  function _concurrent (tasks, done) {
    var d = once(done);
    var keys = Object.keys(tasks);
    var results = a(tasks) ? [] : {};
    var completed = 0, all = keys.length;
    keys.forEach(function iterator (key) { cb(tasks[key], [next(key)]); });
    function next (k) {
      var fn = once(function callback () {
        var args = atoa(arguments);
        if (handle(args, d, fn)) { return; }
        results[k] = args.shift();
        if (++completed === all) {
          cb(d, [null, results]);
        }
      });
      return fn;
    }
  }

  function _map (flow) {
    return function map (collection, transformer, done) {
      var keys = Object.keys(collection);
      var tasks = a(collection) ? [] : {};
      keys.forEach(function iterator (key) {
        tasks[key] = function transform (cb) {
          transformer(collection[key], cb);
        };
      });
      flow(tasks, done);
    };
  }

  function _emitter (thing) {
    var me = this;
    var sub = {};
    thing.on = function (type, fn) {
      if (!sub[type]) {
        sub[type] = [fn];
      } else {
        sub[type].push(fn);
      }
    };
    thing.emit = function () {
      var args = atoa(arguments);
      var type = args.shift();
      var st = sub[type];
      if (type === 'error' && !st) { throw args.length === 1 ? args[0] : args; }
      if (!st) { return; }
      st.forEach(function (s) { s.call(me, args); });
    };
  }

  var _queue = function (worker, concurrency) {
    var q = [], load = 0, max = concurrency || 1;
    function _add (task, top, done) {
      var m = top ? 'unshift' : 'push';
      var tasks = task instanceof Array ? task : [task];
      tasks.forEach(function insert (t) {q[m]({ t: t, done: done }); });
      cb(labor);
    }
    function labor () {
      if (load >= max || !q.length) { return; }
      load++;
      var job = q.pop();
      worker(job.t, once(complete.bind(null, job)));
    }
    function complete (job, err) {
      load--;
      cb(job.done, [err]);
      cb(labor);
    }
    return {
      push: function (task, done) { _add(task, false, done); },
      unshift: function (task, done) { _add(task, true, done); },
      get length () { return q.length; }
    };
  };

  // api
  var $ = {
    waterfall: _waterfall,
    series: _series,
    concurrent: _concurrent,
    map: _map(_concurrent),
    queue: _queue,
    emitter: _emitter
  };

  $.map.series = _map(_series);

  // cross-platform ticks
  if (typeof process === 'undefined' || !process.nextTick) {
    if (typeof setImmediate === 'function') {
      tick = function tick (fn) { setImmediate(fn); };
    } else {
      tick = function tick (fn) { setTimeout(fn, 0); };
    }
  } else {
    tick = typeof setImmediate === 'function' ? setImmediate : process.nextTick;
  }

  // cross-platform export
  if (typeof module !== 'undefined' && module.exports) {
    module.exports = $;
  } else if (typeof define !== 'undefined' && define.amd) {
    define([], function amd () { return $; });
  } else {
    window.a = $;
  }
})();
<|endoftext|>


<commit_before>if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}

define(["require","../deep", "../deep-unit"], function (require, deep, Unit) {

    //_______________________________________________________________ GENERIC STORE TEST CASES

    var unit = {
        title:"Unit title",
        stopOnError:false,
        setup:function(){},
        tests : {

			base:function(){
				var sheet = {
					"dq.up::./!":{
						hello:"world",
						array:["from up"]
					},
					"dq.bottom::./!":{
						array:["from bottom"]
					},
					"dq.up::./a":{
						test:123,
						other:true
					}
				};

				var obj = {
					array:["base entry"],
					a:{
						test:1
					}
				};

				deep.utils.sheet(sheet, obj);
				return deep(obj).equal({"array":["from bottom","base entry","from up"],"a":{"test":123,"other":true},"hello":"world"});
			}
        }
    };

    return new Unit(unit);
});

<commit_msg>extracted sheets stuff + sheets one step beyond : welcome deep.sheeters<commit_after>if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}

define(["require","../deep", "../deep-unit"], function (require, deep, Unit) {

    //_______________________________________________________________ GENERIC STORE TEST CASES

    var unit = {
        title:"deepjs/units/sheets",
        stopOnError:false,
        setup:function(){},
        tests : {

			base:function(){
				var sheet = {
					"dq.up::./!":{
						hello:"world",
						array:["from up"]
					},
					"dq.bottom::./!":{
						array:["from bottom"]
					},
					"dq.up::./a":{
						test:123,
						other:true
					}
				};

				var obj = {
					array:["base entry"],
					a:{
						test:1
					}
				};

				deep.utils.sheet(sheet, obj);
				return deep(obj).equal({"array":["from bottom","base entry","from up"],"a":{"test":123,"other":true},"hello":"world"});
			},
			transform:function(){
				var sheet = {
					"dq.transform::./*":function(input){
						return "e"+input;
					}
				};
				var obj = [1,2,3,4,5];

				return deep(obj).sheet(sheet)
				.equal({
					"dq.transform::./*": [
						"e1",
						"e2",
						"e3",
						"e4",
						"e5"
					]
				})
				.valuesEqual(["e1", "e2", "e3", "e4", "e5"]);
			},
			through:function(){
				var sheet = {
					"dq.through::./*":function(input){
						return "e"+input;
					}
				};
				var obj = [1,2,3,4,5];

				return deep(obj).sheet(sheet)
				.equal({
					"dq.through::./*": [
						"e1",
						"e2",
						"e3",
						"e4",
						"e5"
					]
				})
				.valuesEqual([1,2,3,4,5]);
			},
			sheeter1:function(){
				var sheet = {
				"dq.sheeter::./*":  deep.sheeter
									.up({ fromUp:"tools" })
									.bottom({ fromBottom:"hello" })
				};

				var obj = {
					a:{
						base:"deepjs"
					}
				};

				return deep(obj)
				.sheet(sheet)
				.equal({
					"dq.sheeter::./*": [
						{
						"fromBottom": "hello",
						"base": "deepjs",
						"fromUp": "tools"
						}
					]
				})
				.valuesEqual( {
					"a": {
						"fromBottom": "hello",
						"base": "deepjs",
						"fromUp": "tools"
					}
				});
			}
        }
    };

    return new Unit(unit);
});

<|endoftext|>


<commit_before>// @flow
/**
 * All About Olaf
 * iOS Home page
 */

import React from 'react'
import {
  Navigator,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  StatusBar,
} from 'react-native'

import Icon from 'react-native-vector-icons/Entypo'
import * as c from './components/colors'

const Dimensions = require('Dimensions')
let Viewport = Dimensions.get('window')

type ViewType = {usable: boolean, view: string, title: string, icon: string, tint: string};
const views: ViewType[] = [
  {usable: true, view: 'MenusView', title: 'Menus', icon: 'bowl', tint: c.emerald},
  {usable: true, view: 'SISView', title: 'SIS', icon: 'fingerprint', tint: c.goldenrod},
  {usable: true, view: 'BuildingHoursView', title: 'Building Hours', icon: 'clock', tint: c.wave},
  {usable: true, view: 'CalendarView', title: 'Calendar', icon: 'calendar', tint: c.coolPurple},
  {usable: true, view: 'DirectoryView', title: 'Directory', icon: 'v-card', tint: c.indianRed},
  {usable: true, view: 'StreamingView', title: 'Streaming Media', icon: 'video', tint: c.denim},
  {usable: true, view: 'NewsView', title: 'News', icon: 'news', tint: c.eggplant},
  {usable: true, view: 'MapView', title: 'Campus Map', icon: 'map', tint: c.coffee},
  {usable: true, view: 'ContactsView', title: 'Important Contacts', icon: 'phone', tint: c.crimson},
  {usable: true, view: 'TransportationView', title: 'Transportation', icon: 'address', tint: c.cardTable},
  {usable: true, view: 'DictionaryView', title: 'Campus Dictionary', icon: 'open-book', tint: c.olive},
  {usable: true, view: 'OlevilleView', title: 'Oleville', icon: 'mouse-pointer', tint: c.grapefruit},
]

type ScenePropsType = {navigator: typeof Navigator, route: Object};
export default function HomePageScene({navigator, route}: ScenePropsType) {
  return (
    <ScrollView
      automaticallyAdjustContentInsets={false}
      overflow={'hidden'}
      alwaysBounceHorizontal={false}
      showsHorizontalScrollIndicator={false}
      showsVerticalScrollIndicator={false}
      style={styles.scrollView}
      contentContainerStyle={styles.container}
    >
      <StatusBar
        barStyle='light-content'
      />
      {views.map(view =>
        <TouchableOpacity
          key={view.view}
          onPress={() => navigator.push({id: view.view, index: route.index + 1, title: view.title, sceneConfig: Navigator.SceneConfigs.PushFromRight})}
          activeOpacity={0.5}
        >
          <View style={[styles.rectangle, {backgroundColor: view.tint}]}>
            <Icon name={view.icon} size={32} style={styles.rectangleButtonIcon} />
            <Text
              style={styles.rectangleButtonText}
              autoAdjustsFontSize={true}
            >
              {view.title}{view.usable ? '' : ' !'}
            </Text>
          </View>
        </TouchableOpacity>)}
    </ScrollView>
  )
}

HomePageScene.propTypes = {
  navigator: React.PropTypes.instanceOf(Navigator),
  route: React.PropTypes.object.isRequired,
}

let marginTop = 15

let cellMargin = 10
let cellSidePadding = 10
let cellEdgePadding = 8
let cellWidth = (Viewport.width / 2) - (cellMargin * 1.5)

let styles = StyleSheet.create({
  // Body container
  container: {
    marginLeft: cellMargin,
    marginTop: marginTop,

    alignItems: 'flex-start',
    justifyContent: 'center',
    flexDirection: 'row',
    flexWrap: 'wrap',
  },

  scrollView: {},
  navButton: {},

  // Main buttons for actions on home screen
  rectangle: {
    width: cellWidth,
    alignItems: 'center',
    paddingTop: cellSidePadding,
    paddingBottom: cellSidePadding,
    paddingRight: cellEdgePadding,
    paddingLeft: cellEdgePadding,
    borderRadius: 6,

    marginBottom: cellMargin,
    marginRight: cellMargin,
  },

  navigationButtonText: {
    color: c.mandarin,
  },
  navigationButtonIcon: {
    color: c.mandarin,
    fontSize: 20,
    marginTop: 8,
    marginLeft: 14,
  },

  // Text styling in buttons
  rectangleButtonIcon: {
    color: c.white,
  },
  rectangleButtonText: {
    color: c.white,
    textAlign: 'center',
    fontSize: 14,
  },
})
<commit_msg>remove extra layer of view from Home buttons<commit_after>// @flow
/**
 * All About Olaf
 * iOS Home page
 */

import React from 'react'
import {
  Navigator,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  StatusBar,
} from 'react-native'

import Icon from 'react-native-vector-icons/Entypo'
import * as c from './components/colors'

const Dimensions = require('Dimensions')
let Viewport = Dimensions.get('window')

type ViewType = {usable: boolean, view: string, title: string, icon: string, tint: string};
const views: ViewType[] = [
  {usable: true, view: 'MenusView', title: 'Menus', icon: 'bowl', tint: c.emerald},
  {usable: true, view: 'SISView', title: 'SIS', icon: 'fingerprint', tint: c.goldenrod},
  {usable: true, view: 'BuildingHoursView', title: 'Building Hours', icon: 'clock', tint: c.wave},
  {usable: true, view: 'CalendarView', title: 'Calendar', icon: 'calendar', tint: c.coolPurple},
  {usable: true, view: 'DirectoryView', title: 'Directory', icon: 'v-card', tint: c.indianRed},
  {usable: true, view: 'StreamingView', title: 'Streaming Media', icon: 'video', tint: c.denim},
  {usable: true, view: 'NewsView', title: 'News', icon: 'news', tint: c.eggplant},
  {usable: true, view: 'MapView', title: 'Campus Map', icon: 'map', tint: c.coffee},
  {usable: true, view: 'ContactsView', title: 'Important Contacts', icon: 'phone', tint: c.crimson},
  {usable: true, view: 'TransportationView', title: 'Transportation', icon: 'address', tint: c.cardTable},
  {usable: true, view: 'DictionaryView', title: 'Campus Dictionary', icon: 'open-book', tint: c.olive},
  {usable: true, view: 'OlevilleView', title: 'Oleville', icon: 'mouse-pointer', tint: c.grapefruit},
]

type ScenePropsType = {navigator: typeof Navigator, route: Object};
export default function HomePageScene({navigator, route}: ScenePropsType) {
  return (
    <ScrollView
      automaticallyAdjustContentInsets={false}
      overflow={'hidden'}
      alwaysBounceHorizontal={false}
      showsHorizontalScrollIndicator={false}
      showsVerticalScrollIndicator={false}
      style={styles.scrollView}
      contentContainerStyle={styles.container}
    >
      <StatusBar
        barStyle='light-content'
      />
      {views.map(view =>
        <TouchableOpacity
          key={view.view}
          onPress={() => navigator.push({
            id: view.view,
            index: route.index + 1,
            title: view.title,
            sceneConfig: Navigator.SceneConfigs.PushFromRight,
          })}
          activeOpacity={0.5}
          style={[styles.rectangle, {backgroundColor: view.tint}]}
        >
          <Icon name={view.icon} size={32} style={styles.rectangleButtonIcon} />
          <Text
            style={styles.rectangleButtonText}
            autoAdjustsFontSize={true}
          >
            {view.title}{view.usable ? '' : ' !'}
          </Text>
        </TouchableOpacity>)
      }
    </ScrollView>
  )
}

HomePageScene.propTypes = {
  navigator: React.PropTypes.instanceOf(Navigator),
  route: React.PropTypes.object.isRequired,
}

let marginTop = 15

let cellMargin = 10
let cellSidePadding = 10
let cellEdgePadding = 8
let cellWidth = (Viewport.width / 2) - (cellMargin * 1.5)

let styles = StyleSheet.create({
  // Body container
  container: {
    marginLeft: cellMargin,
    marginTop: marginTop,

    alignItems: 'flex-start',
    justifyContent: 'center',
    flexDirection: 'row',
    flexWrap: 'wrap',
  },

  scrollView: {},
  navButton: {},

  // Main buttons for actions on home screen
  rectangle: {
    width: cellWidth,
    alignItems: 'center',
    paddingTop: cellSidePadding,
    paddingBottom: cellSidePadding,
    paddingRight: cellEdgePadding,
    paddingLeft: cellEdgePadding,
    borderRadius: 6,

    marginBottom: cellMargin,
    marginRight: cellMargin,
  },

  navigationButtonText: {
    color: c.mandarin,
  },
  navigationButtonIcon: {
    color: c.mandarin,
    fontSize: 20,
    marginTop: 8,
    marginLeft: 14,
  },

  // Text styling in buttons
  rectangleButtonIcon: {
    color: c.white,
  },
  rectangleButtonText: {
    color: c.white,
    textAlign: 'center',
    fontSize: 14,
  },
})
<|endoftext|>


<commit_before>const querystring = require('querystring')
const Constants = require('../../frontend/constants/Constants')

function initCommonQuery () {
  return {
    size: 0,
    aggs: {
      facets: {
        global: {},
        aggs: {}
      },
      byWork: {
        terms: {
          field: 'workUri',
          size: Constants.maxSearchResults
        },
        aggs: {
          publications: {
            top_hits: {
              size: 1
            }
          }
        }
      },
      workCount: {
        cardinality: {
          field: 'workUri'
        }
      }
    }
  }
}

function initSimpleQuery (query) {
  return {
    filtered: {
      filter: {
        bool: {
          must: []
        }
      },
      query: {
        bool: {
          filter: [
            {
              simple_query_string: {
                query: query,
                default_operator: 'and',
                fields: ['mainTitle^2', 'partTitle', 'subject', 'agents^2']
              }
            }
          ],
          must: []
        }
      }
    }
  }
}

function initAdvancedQuery (query) {
  return {
    filtered: {
      filter: {
        bool: {
          must: []
        }
      },
      query: {
        query_string: {
          query: query,
          default_operator: 'and'
        }
      }
    }
  }
}

function isAdvancedQuery (queryString) {
  return /[:+-^()"*]/.test(queryString)
}

function simpleSearchBuilder (queryString) {
  let query = initCommonQuery()
  query.query = initSimpleQuery(queryString)
  return query
}

function advancedSearchBuilder (queryString) {
  let query = initCommonQuery()
  query.query = initAdvancedQuery(queryString)
  return query
}

function parseFilters (filtersFromLocationQuery) {
  const filterableFields = Constants.filterableFields
  let filterBuckets = {}
  if (!Array.isArray(filtersFromLocationQuery)) {
    filtersFromLocationQuery = [filtersFromLocationQuery]
  }
  filtersFromLocationQuery.forEach(filter => { // ex filter: 'audience_juvenile'
    const split = filter.split('_')
    const filterableField = filterableFields[ split[0] ]
    const aggregation = filterableField.name
    if (!filterBuckets[aggregation]) {
      filterBuckets[aggregation] = []
    }
    const val = filterableField.prefix + filter.substring(`${split[ 0 ]}_`.length)
    filterBuckets[aggregation].push(val)
  })

  let filters = []
  Object.keys(filterBuckets).forEach(aggregation => {
    filters.push({ aggregation: aggregation, bucket: filterBuckets[aggregation] })
  })

  return filters
}

function createMust (field, terms) {
  return {
    terms: {
      [field]: terms
    }
  }
}

module.exports.buildQuery = function (urlQueryString) {
  const params = querystring.parse(urlQueryString)
  const queryString = params.query
  let elasticSearchQuery = {}
  if (isAdvancedQuery(queryString)) {
    elasticSearchQuery = advancedSearchBuilder(queryString)
  } else {
    elasticSearchQuery = simpleSearchBuilder(queryString)
  }
  const filters = parseFilters(params.filter || [])
  let musts = {}
  filters.forEach(filter => {
    const aggregation = filter.aggregation
    const must = createMust(aggregation, filter.bucket)
    musts[ aggregation ] = must
  })

  Object.keys(musts).forEach(aggregation => {
    elasticSearchQuery.query.filtered.filter.bool.must.push(musts[ aggregation ])
  })

  Object.keys(Constants.filterableFields).forEach(key => {
    const field = Constants.filterableFields[ key ]
    const fieldName = field.name
    elasticSearchQuery.aggs.facets.aggs[ fieldName ] = {
      filter: {
        bool: Object.assign({}, elasticSearchQuery.query.filtered.query.bool)
      },
      aggs: {
        [fieldName]: {
          terms: {
            field: fieldName,
            size: 0
          }
        }
      }
    }

    let aggregationMusts = []
    Object.keys(musts).forEach(aggregation => {
      const must = musts[aggregation]
      if (aggregation !== fieldName) {
        aggregationMusts.push(must)
      }
    })
    elasticSearchQuery.aggs.facets.aggs[ fieldName ].filter.bool.must = aggregationMusts
  })

  return elasticSearchQuery
}
<commit_msg>patron-client: fix aggregations for advanced search<commit_after>const querystring = require('querystring')
const Constants = require('../../frontend/constants/Constants')

function initCommonQuery () {
  return {
    size: 0,
    aggs: {
      facets: {
        global: {},
        aggs: {}
      },
      byWork: {
        terms: {
          field: 'workUri',
          size: Constants.maxSearchResults
        },
        aggs: {
          publications: {
            top_hits: {
              size: 1
            }
          }
        }
      },
      workCount: {
        cardinality: {
          field: 'workUri'
        }
      }
    }
  }
}

function initSimpleQuery (query) {
  return {
    filtered: {
      filter: {
        bool: {
          must: []
        }
      },
      query: {
        bool: {
          filter: [
            {
              simple_query_string: {
                query: query,
                default_operator: 'and',
                fields: ['mainTitle^2', 'partTitle', 'subject', 'agents^2']
              }
            }
          ],
          must: []
        }
      }
    }
  }
}

function initAdvancedQuery (query) {
  return {
    filtered: {
      filter: {
        bool: {
          must: []
        }
      },
      query: {
        query_string: {
          query: query,
          default_operator: 'and'
        }
      }
    }
  }
}

function isAdvancedQuery (queryString) {
  return /[:+-^()"*]/.test(queryString)
}

function simpleSearchBuilder (queryString) {
  let query = initCommonQuery()
  query.query = initSimpleQuery(queryString)
  return query
}

function advancedSearchBuilder (queryString) {
  let query = initCommonQuery()
  query.query = initAdvancedQuery(queryString)
  return query
}

function parseFilters (filtersFromLocationQuery) {
  const filterableFields = Constants.filterableFields
  let filterBuckets = {}
  if (!Array.isArray(filtersFromLocationQuery)) {
    filtersFromLocationQuery = [filtersFromLocationQuery]
  }
  filtersFromLocationQuery.forEach(filter => { // ex filter: 'audience_juvenile'
    const split = filter.split('_')
    const filterableField = filterableFields[ split[0] ]
    const aggregation = filterableField.name
    if (!filterBuckets[aggregation]) {
      filterBuckets[aggregation] = []
    }
    const val = filterableField.prefix + filter.substring(`${split[ 0 ]}_`.length)
    filterBuckets[aggregation].push(val)
  })

  let filters = []
  Object.keys(filterBuckets).forEach(aggregation => {
    filters.push({ aggregation: aggregation, bucket: filterBuckets[aggregation] })
  })

  return filters
}

function createMust (field, terms) {
  return {
    terms: {
      [field]: terms
    }
  }
}

module.exports.buildQuery = function (urlQueryString) {
  const params = querystring.parse(urlQueryString)
  const queryString = params.query
  let elasticSearchQuery = {}
  if (isAdvancedQuery(queryString)) {
    elasticSearchQuery = advancedSearchBuilder(queryString)
  } else {
    elasticSearchQuery = simpleSearchBuilder(queryString)
  }
  const filters = parseFilters(params.filter || [])
  let musts = {}
  filters.forEach(filter => {
    const aggregation = filter.aggregation
    const must = createMust(aggregation, filter.bucket)
    musts[ aggregation ] = must
  })

  Object.keys(musts).forEach(aggregation => {
    elasticSearchQuery.query.filtered.filter.bool.must.push(musts[ aggregation ])
  })

  Object.keys(Constants.filterableFields).forEach(key => {
    const field = Constants.filterableFields[ key ]
    const fieldName = field.name
    elasticSearchQuery.aggs.facets.aggs[ fieldName ] = {
      filter: {
        bool: Object.assign({}, elasticSearchQuery.query.filtered.query.bool || {filter: [elasticSearchQuery.query.filtered.query]})
      },
      aggs: {
        [fieldName]: {
          terms: {
            field: fieldName,
            size: 0
          }
        }
      }
    }

    let aggregationMusts = []
    Object.keys(musts).forEach(aggregation => {
      const must = musts[aggregation]
      if (aggregation !== fieldName) {
        aggregationMusts.push(must)
      }
    })
    elasticSearchQuery.aggs.facets.aggs[ fieldName ].filter.bool.must = aggregationMusts
  })

  return elasticSearchQuery
}
<|endoftext|>


<commit_before>function showResourceVersion(form) {
    var url=$('resource_versions').value;
    location.href=url;
    form.submit;
}

// ***************  Resource Upload Validation  *****************

function validateResourceFields(is_new_file, resource_name, is_managed) {

    // only make this test if that's a new SOP
    if(is_new_file) {
        if($(resource_name + '_data').value.length == 0 && $(resource_name + '_data_url').value.length == 0) {
            alert("Please specify the file to upload, or provide a URL.");
            $(resource_name + '_data').focus();
            return(false);
        }
    }

    // other tests are applicable to both editing and creating new SOP
    if($(resource_name + '_title').value.length == 0) {
        alert("Please specify the title!");
        $(resource_name + '_title').focus();
        return(false);
    }
    if (is_managed){
        if (!checkProjectExists(resource_name)) {
            return (false);
        }

        // check if no tokens remain in the attributions autocompleter
        // (only do this if the fold with attributions is expanded)
        if($('attributions_fold_content').style.display == "block" &&
            autocompleters[attributions_autocompleter_id].getRecognizedSelectedIDs() != "")
            {
            alert('You didn\'t press "Add" link to add items in the attributions autocomplete field.');
            $('attributions_autocomplete_input').focus();
            return(false);
        }
        clickLink($('preview_permission'));
    }
    else{
        // filename and title set - can submit
        $(resource_name + '_submit_btn').disabled = true;
        $(resource_name + '_submit_btn').value = (is_new_file==true ? "Creating..." : "Updating...");
        $(resource_name + '_submit_btn').form.submit();
    }

}

function checkProjectExists(prefix) {
    el=prefix+"_project_ids";
    if ($F(el).length < 1) {
        alert("Please specify at least one project");
        return (false);
    }
    return(true);
}

function clickLink(link) {
    var cancelled = false;
    if (document.createEvent) {
        var event = document.createEvent("MouseEvents");
        event.initMouseEvent("click", true, true, window,
            0, 0, 0, 0, 0,
            false, false, false, false,
            0, null);
        cancelled = !link.dispatchEvent(event);
    }
    else if (link.fireEvent) {
        cancelled = !link.fireEvent("onclick");
    }

    if (!cancelled) {
        window.location = link.href;
    }
}

function createOrUpdateResource(is_new_file, resource_name){
    // filename and title set - can submit
    $(resource_name + '_submit_btn').disabled = true;
    $(resource_name + '_submit_btn').value = (is_new_file=='true' ? "Creating..." : "Updating...");
    $(resource_name + '_submit_btn').form.submit();

    RedBox.close();
}<commit_msg>VL: allow no projects<commit_after>function showResourceVersion(form) {
    var url=$('resource_versions').value;
    location.href=url;
    form.submit;
}

// ***************  Resource Upload Validation  *****************

function validateResourceFields(is_new_file, resource_name, is_managed) {

    // only make this test if that's a new SOP
    if(is_new_file) {
        if($(resource_name + '_data').value.length == 0 && $(resource_name + '_data_url').value.length == 0) {
            alert("Please specify the file to upload, or provide a URL.");
            $(resource_name + '_data').focus();
            return(false);
        }
    }

    // other tests are applicable to both editing and creating new SOP
    if($(resource_name + '_title').value.length == 0) {
        alert("Please specify the title!");
        $(resource_name + '_title').focus();
        return(false);
    }
    if (is_managed){

        // check if no tokens remain in the attributions autocompleter
        // (only do this if the fold with attributions is expanded)
        if($('attributions_fold_content').style.display == "block" &&
            autocompleters[attributions_autocompleter_id].getRecognizedSelectedIDs() != "")
            {
            alert('You didn\'t press "Add" link to add items in the attributions autocomplete field.');
            $('attributions_autocomplete_input').focus();
            return(false);
        }
        clickLink($('preview_permission'));
    }
    else{
        // filename and title set - can submit
        $(resource_name + '_submit_btn').disabled = true;
        $(resource_name + '_submit_btn').value = (is_new_file==true ? "Creating..." : "Updating...");
        $(resource_name + '_submit_btn').form.submit();
    }

}

function checkProjectExists(prefix) {
    el=prefix+"_project_ids";
    if ($F(el).length < 1) {
        alert("Please specify at least one project");
        return (false);
    }
    return(true);
}

function clickLink(link) {
    var cancelled = false;
    if (document.createEvent) {
        var event = document.createEvent("MouseEvents");
        event.initMouseEvent("click", true, true, window,
            0, 0, 0, 0, 0,
            false, false, false, false,
            0, null);
        cancelled = !link.dispatchEvent(event);
    }
    else if (link.fireEvent) {
        cancelled = !link.fireEvent("onclick");
    }

    if (!cancelled) {
        window.location = link.href;
    }
}

function createOrUpdateResource(is_new_file, resource_name){
    // filename and title set - can submit
    $(resource_name + '_submit_btn').disabled = true;
    $(resource_name + '_submit_btn').value = (is_new_file=='true' ? "Creating..." : "Updating...");
    $(resource_name + '_submit_btn').form.submit();

    RedBox.close();
}<|endoftext|>


<commit_before>//= require "../chrome/storage"

var libraries = [
    {
        "url": "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js",
        "label": "jQuery latest",
        "group": "jQuery"
    },
    {
        "url": "http://code.jquery.com/jquery-git.js",
        "label": "jQuery WIP (via git)",
        "group": "jQuery"
    },
    {
        "url": "http://code.jquery.com/jquery-1.8.0.min.js",
        "label": "jQuery 1.8.0",
        "group": "jQuery"
    },
    {
        "url": "http://code.jquery.com/jquery-1.7.2.min.js",
        "label": "jQuery 1.7.2",
        "group": "jQuery"
    },
    {
        "url": [
            "http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css",
            "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js",
            "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"
        ],
        "label": "jQuery UI 1.8.13",
        "group": "jQuery UI"
    },
    {
        "url": [
            "http://code.jquery.com/mobile/latest/jquery.mobile.css",
            "http://code.jquery.com/jquery-1.6.4.min.js",
            "http://code.jquery.com/mobile/latest/jquery.mobile.js"
        ],
        "label": "jQuery Mobile Latest",
        "group": "jQuery Mobile"
    },
    {
        "url": [
            "http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css",
            "http://code.jquery.com/jquery-1.6.4.min.js",
            "http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.js"
        ],
        "label": "jQuery Mobile 1.1.0",
        "group": "jQuery Mobile"
    },
    {
        "url": [
            "http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css",
            "http://code.jquery.com/jquery-1.6.4.min.js",
            "http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.1.min.js"
        ],
        "label": "jQuery Mobile 1.0.1",
        "group": "jQuery Mobile"
    },
    {
        "url": [
            "http://code.jquery.com/jquery.min.js",
            "http://twitter.github.com/bootstrap/assets/css/bootstrap.css",
            "http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css",
            "http://twitter.github.com/bootstrap/assets/js/bootstrap.js"
        ],
        "label": "Bootstrap latest",
        "group": "Bootstrap"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js",
        "label": "Prototype latest",
        "group": "Prototype"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/prototype/1.7.1/prototype.js",
        "label": "Prototype 1.7.1",
        "group": "Prototype"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js",
        "label": "Prototype 1.6.1.0",
        "group": "Prototype"
    },
    {
        "url": [
            "http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js",
            "http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js"
        ],
        "label": "script.aculo.us 1.8.3",
        "group": "Prototype"
    },
    {
        "url": "http://yui.yahooapis.com/3.6.0/build/yui/yui-min.js",
        "label": "YUI 3.6.0",
        "group": "YUI"
    },
    {
        "url": "http://yui.yahooapis.com/2.9.0/build/yuiloader/yuiloader-min.js",
        "label": "YUI 2.9.0",
        "group": "YUI"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/mootools/1.4.5/mootools-yui-compressed.js",
        "label": "MooTools 1.4.5",
        "group": "MooTools"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/mootools/1.3.2/mootools-yui-compressed.js",
        "label": "MooTools 1.3.2",
        "group": "MooTools"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js",
        "label": "Dojo 1.6.0",
        "group": "Dojo"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/dojo/1.4.1/dojo/dojo.xd.js",
        "label": "Dojo 1.4.1",
        "group": "Dojo"
    },
    {
        "url": [
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.common.min.css",
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.default.min.css",
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.dataviz.min.css",
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.mobile.all.min.css",
            "http://code.jquery.com/jquery-1.8.0.min.js",
            "http://cdn.kendostatic.com/2012.2.710/js/kendo.all.min.js"
        ],
        "label": "Kendo UI Q2 2012",
        "group": "Kendo UI"
    },
    {
        "url": [
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.common.min.css",
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.default.min.css",
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.dataviz.min.css",
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.mobile.all.min.css",
            "http://code.jquery.com/jquery-1.8.0.min.js",
            "http://cdn.kendostatic.com/2012.1.322/js/kendo.all.min.js"
        ],
        "label": "Kendo UI Q1 2012",
        "group": "Kendo UI"
    },
    {
        "url" : [
            "http://code.jquery.com/qunit/qunit-git.css",
            "http://code.jquery.com/qunit/qunit-git.js"
        ],
        "label": "QUnit",
        "group": "Testing"
    },
    {
        "url":"http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js",
        "label": "Angular 1.0.1"
    },
    {
        "url": [
            "http://documentcloud.github.com/underscore/underscore-min.js",
            "http://documentcloud.github.com/backbone/backbone-min.js"
        ],
        "label": "Backbone 0.9.2"
    },
    {
        "url": "http://jashkenas.github.com/coffee-script/extras/coffee-script.js",
        "label": "CoffeeScript"
    },
    {
        "url": "https://github.com/downloads/emberjs/ember.js/ember-0.9.8.1.min.js",
        "label": "Ember.js 0.9.8.1"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/es5-shim/1.2.4/es5-shim.min.js",
        "label": "ES5 shim 1.2.4"
    },
    {
        "url": [
            "http://extjs.cachefly.net/ext-3.1.0/resources/css/ext-all.css",
            "http://cdnjs.cloudflare.com/ajax/libs/ext-core/3.1.0/ext-core.js"
        ],
        "label": "ext-core 3.1.0"
    },
    {
        "url": "http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js",
        "label": "Knockout 2.1"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/less.js/1.1.3/less-1.1.3.min.js",
        "label": "Less 1.1.3"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.5.2/lodash.min.js",
        "label": "lodash 0.5.2"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.5.3/modernizr.min.js",
        "label": "Modernizr 2.5.3"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.6/prefixfree.min.js",
        "label": "Prefixfree 1.0.6"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/processing.js/1.3.6/processing-api.min.js",
        "label": "Processing 1.3.6"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/raphael/2.0.0/raphael-min.js",
        "label": "Raphaël 2.0.0"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/sammy.js/0.6.3/sammy.min.js",
        "label": "Sammy 0.6.3"
    },
    {
        "url": [
            "http://cdn.sencha.io/touch/1.1.0/resources/css/sencha-touch.css",
            "http://cdn.sencha.io/touch/1.1.0/sencha-touch.js"
        ],
        "label": "Sencha Touch"
    },
    {
        "url": [
            "http://traceur-compiler.googlecode.com/git/src/traceur.js",
            "http://traceur-compiler.googlecode.com/git/src/bootstrap.js"
        ],
        "label": "Traceur"
    },
    {
        "url": "http://remy.github.com/twitterlib/twitterlib.min.js",
        "label": "TwitterLib"
    },
    {
        "url": "http://documentcloud.github.com/underscore/underscore-min.js",
        "label": "underscore 1.3.1"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/zepto/0.7/zepto.min.js",
        "label": "Zepto 0.7"
    }
];

window.libraries = libraries; // expose a command line API

libraries.userSpecified = JSON.parse(localStorage.getItem('libraries') || "[]");
for (var i = 0; i < libraries.userSpecified.length; i++) {
  libraries.push(libraries.userSpecified[i]);
}

libraries.add = function (lib) {
  // save to localStorage
  lib.group = 'Custom';
  this.userSpecified.push(lib);
  try {
    localStorage.setItem('libraries', JSON.stringify(this.userSpecified));
  } catch (e) {} // just in case of DOM_22 error, makes me so sad to use this :(
  libraries.push(lib);
  $('#library').trigger('init');
};

libraries.clear = function () {
  libraries.userSpecified = [];
  localStorage.removeItem('libraries');
  var length = libraries.length;
  for (var i = 0; i < length; i++) {
    if (libraries[i].group === 'Custom') {
      libraries.splice(i, 1);
      length--;
    }
  }
  // force a refresh?
  $('#library').trigger('init');
};
<commit_msg>Updated jQuery UI to 1.8.23 and add latest and WIP versions.<commit_after>//= require "../chrome/storage"

var libraries = [
    {
        "url": "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js",
        "label": "jQuery latest",
        "group": "jQuery"
    },
    {
        "url": "http://code.jquery.com/jquery-git.js",
        "label": "jQuery WIP (via git)",
        "group": "jQuery"
    },
    {
        "url": "http://code.jquery.com/jquery-1.8.0.min.js",
        "label": "jQuery 1.8.0",
        "group": "jQuery"
    },
    {
        "url": "http://code.jquery.com/jquery-1.7.2.min.js",
        "label": "jQuery 1.7.2",
        "group": "jQuery"
    },
    {
        "url": [
            "http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css",
            "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js",
            "http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"
        ],
        "label": "jQuery UI latest",
        "group": "jQuery UI"
    },
    {
        "url": [
            "http://code.jquery.com/ui/jquery-ui-git.css",
            "http://code.jquery.com/jquery-git.js",
            "http://code.jquery.com/ui/jquery-ui-git.js"
        ],
        "label": "jQuery UI WIP (via git)",
        "group": "jQuery UI"
    },
    {
        "url": [
            "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/themes/base/jquery-ui.css",
            "http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js",
            "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"
        ],
        "label": "jQuery UI 1.8.23",
        "group": "jQuery UI"
    },
    {
        "url": [
            "http://code.jquery.com/mobile/latest/jquery.mobile.css",
            "http://code.jquery.com/jquery-1.6.4.min.js",
            "http://code.jquery.com/mobile/latest/jquery.mobile.js"
        ],
        "label": "jQuery Mobile Latest",
        "group": "jQuery Mobile"
    },
    {
        "url": [
            "http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css",
            "http://code.jquery.com/jquery-1.6.4.min.js",
            "http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.js"
        ],
        "label": "jQuery Mobile 1.1.0",
        "group": "jQuery Mobile"
    },
    {
        "url": [
            "http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css",
            "http://code.jquery.com/jquery-1.6.4.min.js",
            "http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.1.min.js"
        ],
        "label": "jQuery Mobile 1.0.1",
        "group": "jQuery Mobile"
    },
    {
        "url": [
            "http://code.jquery.com/jquery.min.js",
            "http://twitter.github.com/bootstrap/assets/css/bootstrap.css",
            "http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css",
            "http://twitter.github.com/bootstrap/assets/js/bootstrap.js"
        ],
        "label": "Bootstrap latest",
        "group": "Bootstrap"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js",
        "label": "Prototype latest",
        "group": "Prototype"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/prototype/1.7.1/prototype.js",
        "label": "Prototype 1.7.1",
        "group": "Prototype"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js",
        "label": "Prototype 1.6.1.0",
        "group": "Prototype"
    },
    {
        "url": [
            "http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js",
            "http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js"
        ],
        "label": "script.aculo.us 1.8.3",
        "group": "Prototype"
    },
    {
        "url": "http://yui.yahooapis.com/3.6.0/build/yui/yui-min.js",
        "label": "YUI 3.6.0",
        "group": "YUI"
    },
    {
        "url": "http://yui.yahooapis.com/2.9.0/build/yuiloader/yuiloader-min.js",
        "label": "YUI 2.9.0",
        "group": "YUI"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/mootools/1.4.5/mootools-yui-compressed.js",
        "label": "MooTools 1.4.5",
        "group": "MooTools"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/mootools/1.3.2/mootools-yui-compressed.js",
        "label": "MooTools 1.3.2",
        "group": "MooTools"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js",
        "label": "Dojo 1.6.0",
        "group": "Dojo"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/dojo/1.4.1/dojo/dojo.xd.js",
        "label": "Dojo 1.4.1",
        "group": "Dojo"
    },
    {
        "url": [
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.common.min.css",
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.default.min.css",
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.dataviz.min.css",
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.mobile.all.min.css",
            "http://code.jquery.com/jquery-1.8.0.min.js",
            "http://cdn.kendostatic.com/2012.2.710/js/kendo.all.min.js"
        ],
        "label": "Kendo UI Q2 2012",
        "group": "Kendo UI"
    },
    {
        "url": [
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.common.min.css",
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.default.min.css",
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.dataviz.min.css",
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.mobile.all.min.css",
            "http://code.jquery.com/jquery-1.8.0.min.js",
            "http://cdn.kendostatic.com/2012.1.322/js/kendo.all.min.js"
        ],
        "label": "Kendo UI Q1 2012",
        "group": "Kendo UI"
    },
    {
        "url" : [
            "http://code.jquery.com/qunit/qunit-git.css",
            "http://code.jquery.com/qunit/qunit-git.js"
        ],
        "label": "QUnit",
        "group": "Testing"
    },
    {
        "url":"http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js",
        "label": "Angular 1.0.1"
    },
    {
        "url": [
            "http://documentcloud.github.com/underscore/underscore-min.js",
            "http://documentcloud.github.com/backbone/backbone-min.js"
        ],
        "label": "Backbone 0.9.2"
    },
    {
        "url": "http://jashkenas.github.com/coffee-script/extras/coffee-script.js",
        "label": "CoffeeScript"
    },
    {
        "url": "https://github.com/downloads/emberjs/ember.js/ember-0.9.8.1.min.js",
        "label": "Ember.js 0.9.8.1"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/es5-shim/1.2.4/es5-shim.min.js",
        "label": "ES5 shim 1.2.4"
    },
    {
        "url": [
            "http://extjs.cachefly.net/ext-3.1.0/resources/css/ext-all.css",
            "http://cdnjs.cloudflare.com/ajax/libs/ext-core/3.1.0/ext-core.js"
        ],
        "label": "ext-core 3.1.0"
    },
    {
        "url": "http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js",
        "label": "Knockout 2.1"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/less.js/1.1.3/less-1.1.3.min.js",
        "label": "Less 1.1.3"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.5.2/lodash.min.js",
        "label": "lodash 0.5.2"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.5.3/modernizr.min.js",
        "label": "Modernizr 2.5.3"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.6/prefixfree.min.js",
        "label": "Prefixfree 1.0.6"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/processing.js/1.3.6/processing-api.min.js",
        "label": "Processing 1.3.6"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/raphael/2.0.0/raphael-min.js",
        "label": "Raphaël 2.0.0"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/sammy.js/0.6.3/sammy.min.js",
        "label": "Sammy 0.6.3"
    },
    {
        "url": [
            "http://cdn.sencha.io/touch/1.1.0/resources/css/sencha-touch.css",
            "http://cdn.sencha.io/touch/1.1.0/sencha-touch.js"
        ],
        "label": "Sencha Touch"
    },
    {
        "url": [
            "http://traceur-compiler.googlecode.com/git/src/traceur.js",
            "http://traceur-compiler.googlecode.com/git/src/bootstrap.js"
        ],
        "label": "Traceur"
    },
    {
        "url": "http://remy.github.com/twitterlib/twitterlib.min.js",
        "label": "TwitterLib"
    },
    {
        "url": "http://documentcloud.github.com/underscore/underscore-min.js",
        "label": "underscore 1.3.1"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/zepto/0.7/zepto.min.js",
        "label": "Zepto 0.7"
    }
];

window.libraries = libraries; // expose a command line API

libraries.userSpecified = JSON.parse(localStorage.getItem('libraries') || "[]");
for (var i = 0; i < libraries.userSpecified.length; i++) {
  libraries.push(libraries.userSpecified[i]);
}

libraries.add = function (lib) {
  // save to localStorage
  lib.group = 'Custom';
  this.userSpecified.push(lib);
  try {
    localStorage.setItem('libraries', JSON.stringify(this.userSpecified));
  } catch (e) {} // just in case of DOM_22 error, makes me so sad to use this :(
  libraries.push(lib);
  $('#library').trigger('init');
};

libraries.clear = function () {
  libraries.userSpecified = [];
  localStorage.removeItem('libraries');
  var length = libraries.length;
  for (var i = 0; i < length; i++) {
    if (libraries[i].group === 'Custom') {
      libraries.splice(i, 1);
      length--;
    }
  }
  // force a refresh?
  $('#library').trigger('init');
};
<|endoftext|>


<commit_before>const net = require('net');
const InventoryData = require('../shared/InventoryData');
const MapData = require('../shared/MapData');

/**
 * Used to make sure the server is working properly. Attempts to replicate
 * most of the function of the actual robot lua code.
 */
class testClient {

	/**
	 * Set the test client's initial state based on testing data.
	 * @param {object} testData
	 */
	constructor(testData) {

		this.testData = testData;
		this.inventory = new InventoryData(this.testData.internalInventory.meta);
		for (let slot of this.testData.internalInventory.slots) {
			this.inventory.setSlot(slot);
		}
		this.equipped;
		this.map = new MapData();
		this.map.setFromMapData(this.testData.map);
		this.position = this.testData.position;
		this.map.set(this.position.x, this.position.y, this.position.z, {"hardness": 2});
		this.components = this.testData.components;

		this.power = 1;
		this.writeBufferLength = 20;
		this.delimiter = '\r\n';

		this.socket = new net.Socket();
		this.socket.on('close', function() {
			console.log('Connection closed');
		});

		this.commandMap = {

			scanArea: (scanLevel)=>{

				// this.sendWithCost('map data', this.testData.geolyzerScan);
				// for i=-2,5 do sendScan.volume(-3, -3, i, 8, 8, 1) end;
				let scanX = -3;
				let scanY = -2;
				let scanZ = -3;
				let scanW = 8;
				let scanD = 8;
				let scanN = scanW * scanD * 8/* difference between -2 and 5 */;

				let newScan = {
					x: scanX + this.position.x,
					y: scanY + this.position.y,
					z: scanZ + this.position.z,
					w: scanW,
					d: scanD,
					data: {
						n: scanN,
					},
				};

				for (let x = 0; x < scanW; x++) {
					for (let z = 0; z < scanD; z++) {
						for (let y = 0; y < (scanN / (scanW * scanD)); y++) {

							let xWithOffset = x + scanX;
							let yWithOffset = y + scanY;
							let zWithOffset = z + scanZ;

							// this is how the geolyzer reports 3d data in a 1d array
							// also lua is indexed from 1
							let index = (x + 1) + z*scanW + y*scanW*scanD;

							let blockData = this.map.get(xWithOffset, yWithOffset, zWithOffset);
							newScan.data[index] = blockData && blockData.hardness ? blockData.hardness : 0;

						}
					}
				}

				this.sendWithCost('map data', newScan);

			},

			viewInventory: ()=>{
				this.sendWithCost('inventory data', this.serializeMeta());
				for (let slotNum in this.inventory.slots) {
					this.sendWithCost('slot data', this.serializeSlot(slotNum));
				}
			},

			equip: ()=>{
				let temporarySlot = this.equipped;
				this.equipped = this.inventory.slots[this.inventory.selected];
				this.inventory.slots[this.inventory.selected] = temporarySlot;
				this.sendWithCost('inventory data', this.serializeMeta());
				this.sendWithCost(
					'slot data',
					this.serializeSlot(this.inventory.selected)
				);
			},

			dig: (v1, v2, selectionIndex, scanLevel)=>{},

			place: (v1, v2, selectionIndex, scanLevel)=>{},

			move: (x, y, z, scanLevel)=>{},

			interact: (coord, scanLevel)=>{},

			inspect: (coord, scanLevel)=>{},

			select: (slotNum)=>{
				this.inventory.selected = slotNum;
			},

			transfer: (fromSlot, fromSide, toSlot, toSide, amount)=>{},

			craft: (itemName)=>{},

			raw: (commandString)=>{
				this.sendWithCost('command result', [true, 'received command: ' + commandString]);
			},

			sendPosition: ()=>{
				this.sendWithCost('robot position', this.position);
			},

			sendComponents: ()=>{
				this.sendWithCost('available components', this.components);
			},

		};
		this.socket.on('data', (rawMessages)=>{
			let messages = String(rawMessages).split('\r\n').filter(s=>s).map(JSON.parse);
			for (let data of messages) {
				if (data.command) {
					console.log('Received:', data.command.name, data.command.parameters);
					this.commandMap[data.command.name](...data.command.parameters);
				}
				else if (data.message) {
					console.log(data.message);
				}
			}
		});

	}

	/**
	 * Used to make sending the test client's inventory data to the
	 * server easier.
	 * @param {number} slotNum
	 */
	serializeMeta() {
		let inventoryMeta = {
			size: this.inventory.size,
			side: -1,
			selected: this.inventory.selected,
		};
		return inventoryMeta;
	}
	/**
	 * Used to make sending the test client's slot data to the
	 * server easier.
	 * @param {number} slotNum
	 */
	serializeSlot(slotNum) {
		let inventorySlot = {
			side: -1,
			slotNum: slotNum,
			contents: this.inventory.slots[slotNum],
		};
		return inventorySlot;
	}

	/**
	 * Used to send data to the server, such as power level or position.
	 * @param {string} key
	 * @param {object} value
	 */
	send(key, value) {

		const data = {
			[key]: value,
		};
		const serializedData = JSON.stringify(data) + this.delimiter;

		if (serializedData.length > this.writeBufferLength) {
			const chunkRegExp = new RegExp('[\\s\\S]{1,' + this.writeBufferLength + '}', 'g');
			const dataChunks = serializedData.match(chunkRegExp) || [];
			dataChunks.map(this.socket.write, this.socket);
		}
		else {
			this.socket.write(serializedData);
		}

	}

	/**
	 * Used to simulate power consumption.
	 * Sends a message and also a power level update.
	 * @param {string} key
	 * @param {object} value
	 */
	sendWithCost(key, value) {
		this.send(key, value);
		this.decreasePower();
	}

	/**
	 * Used to identify the test client to the server and open the socket connection.
	 */
	connect() {
		this.socket.connect(this.testData.port, this.testData.host, ()=>{
			this.sendWithCost('id', {robot: this.testData.robotName, account: this.testData.accountName});
			this.send('message', 'hi');
			console.log('Connected');
		});
	}

	/**
	 * Used to make the test map data a little more like real geolyzer scans.
	 * @param {object} geolyzerScan
	 */
	addNoise(geolyzerScan) {
		let mapData = this.testData.geolyzerScan.data;
		for (var key in mapData) {
			if (mapData[key] == 1) {
				mapData[key] = Math.random() * 6;
			}
		}
	}

	/**
	 * Used to tell the server the test client now has less power than it did before.
	 */
	decreasePower() {
		this.power -= .02 * Math.random();
		this.send('power level', this.power);
	}

}

module.exports = testClient;<commit_msg>fixed test client scan start location bug it's now properly centered around the test client's position<commit_after>const net = require('net');
const InventoryData = require('../shared/InventoryData');
const MapData = require('../shared/MapData');

/**
 * Used to make sure the server is working properly. Attempts to replicate
 * most of the function of the actual robot lua code.
 */
class testClient {

	/**
	 * Set the test client's initial state based on testing data.
	 * @param {object} testData
	 */
	constructor(testData) {

		this.testData = testData;
		this.inventory = new InventoryData(this.testData.internalInventory.meta);
		for (let slot of this.testData.internalInventory.slots) {
			this.inventory.setSlot(slot);
		}
		this.equipped;
		this.map = new MapData();
		this.map.setFromMapData(this.testData.map);
		this.position = this.testData.position;
		this.map.set(this.position.x, this.position.y, this.position.z, {"hardness": 2});
		this.components = this.testData.components;

		this.power = 1;
		this.writeBufferLength = 20;
		this.delimiter = '\r\n';

		this.socket = new net.Socket();
		this.socket.on('close', function() {
			console.log('Connection closed');
		});

		this.commandMap = {

			scanArea: (scanLevel)=>{

				// this.sendWithCost('map data', this.testData.geolyzerScan);
				// for i=-2,5 do sendScan.volume(-3, -3, i, 8, 8, 1) end;
				let scanX = -3;
				let scanY = -2;
				let scanZ = -3;
				let scanW = 8;
				let scanD = 8;
				let scanN = scanW * scanD * 8/* difference between -2 and 5 */;

				let newScan = {
					x: scanX + this.position.x,
					y: scanY + this.position.y,
					z: scanZ + this.position.z,
					w: scanW,
					d: scanD,
					data: {
						n: scanN,
					},
				};

				for (let x = 0; x < scanW; x++) {
					for (let z = 0; z < scanD; z++) {
						for (let y = 0; y < (scanN / (scanW * scanD)); y++) {

							let xWithOffset = x + newScan.x;
							let yWithOffset = y + newScan.y;
							let zWithOffset = z + newScan.z;

							// this is how the geolyzer reports 3d data in a 1d array
							// also lua is indexed from 1
							let index = (x + 1) + z*scanW + y*scanW*scanD;

							let blockData = this.map.get(xWithOffset, yWithOffset, zWithOffset);
							newScan.data[index] = blockData && blockData.hardness ? blockData.hardness : 0;

						}
					}
				}

				this.sendWithCost('map data', newScan);

			},

			viewInventory: ()=>{
				this.sendWithCost('inventory data', this.serializeMeta());
				for (let slotNum in this.inventory.slots) {
					this.sendWithCost('slot data', this.serializeSlot(slotNum));
				}
			},

			equip: ()=>{
				let temporarySlot = this.equipped;
				this.equipped = this.inventory.slots[this.inventory.selected];
				this.inventory.slots[this.inventory.selected] = temporarySlot;
				this.sendWithCost('inventory data', this.serializeMeta());
				this.sendWithCost(
					'slot data',
					this.serializeSlot(this.inventory.selected)
				);
			},

			dig: (v1, v2, selectionIndex, scanLevel)=>{},

			place: (v1, v2, selectionIndex, scanLevel)=>{},

			move: (x, y, z, scanLevel)=>{},

			interact: (coord, scanLevel)=>{},

			inspect: (coord, scanLevel)=>{},

			select: (slotNum)=>{
				this.inventory.selected = slotNum;
			},

			transfer: (fromSlot, fromSide, toSlot, toSide, amount)=>{},

			craft: (itemName)=>{},

			raw: (commandString)=>{
				this.sendWithCost('command result', [true, 'received command: ' + commandString]);
			},

			sendPosition: ()=>{
				this.sendWithCost('robot position', this.position);
			},

			sendComponents: ()=>{
				this.sendWithCost('available components', this.components);
			},

		};
		this.socket.on('data', (rawMessages)=>{
			let messages = String(rawMessages).split('\r\n').filter(s=>s).map(JSON.parse);
			for (let data of messages) {
				if (data.command) {
					console.log('Received:', data.command.name, data.command.parameters);
					this.commandMap[data.command.name](...data.command.parameters);
				}
				else if (data.message) {
					console.log(data.message);
				}
			}
		});

	}

	/**
	 * Used to make sending the test client's inventory data to the
	 * server easier.
	 * @param {number} slotNum
	 */
	serializeMeta() {
		let inventoryMeta = {
			size: this.inventory.size,
			side: -1,
			selected: this.inventory.selected,
		};
		return inventoryMeta;
	}
	/**
	 * Used to make sending the test client's slot data to the
	 * server easier.
	 * @param {number} slotNum
	 */
	serializeSlot(slotNum) {
		let inventorySlot = {
			side: -1,
			slotNum: slotNum,
			contents: this.inventory.slots[slotNum],
		};
		return inventorySlot;
	}

	/**
	 * Used to send data to the server, such as power level or position.
	 * @param {string} key
	 * @param {object} value
	 */
	send(key, value) {

		const data = {
			[key]: value,
		};
		const serializedData = JSON.stringify(data) + this.delimiter;

		if (serializedData.length > this.writeBufferLength) {
			const chunkRegExp = new RegExp('[\\s\\S]{1,' + this.writeBufferLength + '}', 'g');
			const dataChunks = serializedData.match(chunkRegExp) || [];
			dataChunks.map(this.socket.write, this.socket);
		}
		else {
			this.socket.write(serializedData);
		}

	}

	/**
	 * Used to simulate power consumption.
	 * Sends a message and also a power level update.
	 * @param {string} key
	 * @param {object} value
	 */
	sendWithCost(key, value) {
		this.send(key, value);
		this.decreasePower();
	}

	/**
	 * Used to identify the test client to the server and open the socket connection.
	 */
	connect() {
		this.socket.connect(this.testData.port, this.testData.host, ()=>{
			this.sendWithCost('id', {robot: this.testData.robotName, account: this.testData.accountName});
			this.send('message', 'hi');
			console.log('Connected');
		});
	}

	/**
	 * Used to make the test map data a little more like real geolyzer scans.
	 * @param {object} geolyzerScan
	 */
	addNoise(geolyzerScan) {
		let mapData = this.testData.geolyzerScan.data;
		for (var key in mapData) {
			if (mapData[key] == 1) {
				mapData[key] = Math.random() * 6;
			}
		}
	}

	/**
	 * Used to tell the server the test client now has less power than it did before.
	 */
	decreasePower() {
		this.power -= .02 * Math.random();
		this.send('power level', this.power);
	}

}

module.exports = testClient;<|endoftext|>


<commit_before>/*
 * Framework javascript startup function
 */

function javascript_init ()
	{
	setTimeout (function () { $('.fadeout').fadeOut (); }, 8000);
	setTimeout (function () { $('.slideup').slideUp (); }, 8000);

	if (typeof reload_popups == 'function') { reload_popups (); }

	/* Set the default focus */
	$('#focus,.focus').focus ();

	/* Manage the stripes for table listings */
	$('table.list tr:nth-child(odd)').addClass ('stripe');
	$('table.list tr:nth-child(even)').removeClass ('stripe');

	/* Make the popup-box movable */
	$('#popup-box').draggable ({handle: '#popup-title'});

	if (jQuery().tooltip)
		{
		$('.tooltip').tooltip ({position: {my: "left+5 top+5", at: "left bottom", collision: "flipfit"}});
		}

	if (jQuery().datetimepicker)
		{
		$('.datebox').datepicker({showAnim: 'fade', dateFormat: 'yy-mm-dd', duration: 'fast'});
		}

	if (jQuery().datetimepicker)
		{
		$('.datetimebox').datetimepicker({ampm: true});
		}

	if (jQuery().timepicker)
		{
		$('.timebox').timepicker({ampm: true, step: 15});
		}

	if (jQuery().pagination)
		{
		$.fn.pagination.settings['function_default'] = function ()
			{
			/* Reset any stripes in the popups */
			$('table.list tr:nth-child(odd)').addClass ('stripe');

			/* Try to reload any popup-links we sent to the page */
			if (typeof reload_popups == 'function')
				{
				reload_popups ();
				}
			};
		}

	$('#noticebox-close').click (function () {
		var line = $(this).parent ('div');

		$.ajax ({
			data:		'',
			type:		'get',
			url:		path + 'limbo-register?id=' + line.attr ('id'),
			dataType:	'json',

			success: function (results)
				{
				if (results == null)
					alert ('Could not save notice-box-close registration');
				else
					line.slideUp ('fast');
				}
			});
		});

	$('#popup-close').click (function () { disable_popup (); });
	$('#popup-background').click (function () { disable_popup (); });

	/* Look for the escape key to close the popup */
	$(document).keyup (function (e) {
		if (e.keyCode == 27 && popup_status == 1)
			{
			disable_popup ();
			}
		});

	// If any user movement is noticed, mark this heartbeat as active
	$(this).mousemove (function () { heartbeat_active = true; });
	$(this).keypress (function () { heartbeat_active = true; });

	// Allow for a custom init function
	if (typeof custom_init == 'function')
		{
		custom_init ();
		}

	reload_popups ();
	}
<commit_msg>Allow more than one notice box per page<commit_after>/*
 * Framework javascript startup function
 */

function javascript_init ()
	{
	setTimeout (function () { $('.fadeout').fadeOut (); }, 8000);
	setTimeout (function () { $('.slideup').slideUp (); }, 8000);

	if (typeof reload_popups == 'function') { reload_popups (); }

	/* Set the default focus */
	$('#focus,.focus').focus ();

	/* Manage the stripes for table listings */
	$('table.list tr:nth-child(odd)').addClass ('stripe');
	$('table.list tr:nth-child(even)').removeClass ('stripe');

	/* Make the popup-box movable */
	$('#popup-box').draggable ({handle: '#popup-title'});

	if (jQuery().tooltip)
		{
		$('.tooltip').tooltip ({position: {my: "left+5 top+5", at: "left bottom", collision: "flipfit"}});
		}

	if (jQuery().datetimepicker)
		{
		$('.datebox').datepicker({showAnim: 'fade', dateFormat: 'yy-mm-dd', duration: 'fast'});
		}

	if (jQuery().datetimepicker)
		{
		$('.datetimebox').datetimepicker({ampm: true});
		}

	if (jQuery().timepicker)
		{
		$('.timebox').timepicker({ampm: true, step: 15});
		}

	if (jQuery().pagination)
		{
		$.fn.pagination.settings['function_default'] = function ()
			{
			/* Reset any stripes in the popups */
			$('table.list tr:nth-child(odd)').addClass ('stripe');

			/* Try to reload any popup-links we sent to the page */
			if (typeof reload_popups == 'function')
				{
				reload_popups ();
				}
			};
		}

	$('.noticebox-close').click (function () {
		var line = $(this).parent ('div');

		$.ajax ({
			data:		'',
			type:		'get',
			url:		path + 'limbo-register?id=' + line.attr ('id'),
			dataType:	'json',

			success: function (results)
				{
				if (results == null)
					alert ('Could not save notice-box-close registration');
				else
					line.slideUp ('fast');
				}
			});
		});

	$('#popup-close').click (function () { disable_popup (); });
	$('#popup-background').click (function () { disable_popup (); });

	/* Look for the escape key to close the popup */
	$(document).keyup (function (e) {
		if (e.keyCode == 27 && popup_status == 1)
			{
			disable_popup ();
			}
		});

	// If any user movement is noticed, mark this heartbeat as active
	$(this).mousemove (function () { heartbeat_active = true; });
	$(this).keypress (function () { heartbeat_active = true; });

	// Allow for a custom init function
	if (typeof custom_init == 'function')
		{
		custom_init ();
		}

	reload_popups ();
	}
<|endoftext|>


<commit_before>//- JavaScript source code

//- custom.js ~~
//                                                      ~~ (c) SRW, 09 Dec 2013
//                                                  ~~ last updated 09 Dec 2013

(function () {
    'use strict';

 // Pragmas

    /*jslint indent: 4, maxlen: 80, node: true */

 // Module definitions

    exports.log = function (request) {
     // This is a custom logging function that executes once for every request
     // if logging is enabled. This function is optional, however, because
     // QMachine provides a default logging function; feel free to delete or
     // adapt it as needed :-)
        var data = {
            host: request.headers.host,
            method: request.method,
            timestamp: new Date(),
            url: request.url
        };
        if (request.headers.hasOwnProperty('cf-ipcountry')) {
         // This header is specific to CloudFlare (www.cloudflare.com), but
         // storing the header with a hyphen inside can cause problems in query
         // languages like Hive. Thus, we use a hyphen convention.
            data.cf_ipcountry = request.headers['cf-ipcountry'];
        }
        if (request.headers.hasOwnProperty('x-forwarded-for')) {
            data.ip = request.headers['x-forwarded-for'].split(',')[0];
        } else {
            data.ip = request.connection.remoteAddress;
        }
        return data;
    };

    exports.parse = function (x) {
     // This function needs documentation.
        return JSON.parse(x, function (key, val) {
         // This function needs documentation.
            /*jslint unparam: true */
            if (typeof val === 'string') {
                return val.replace(/[$][{]([A-Z0-9_]+)[}]/g, function ($0, $1) {
                 // This function needs documentation.
                    return process.env[$1];
                });
            }
            return val;
        });
    };

 // That's all, folks!

    return;

}());

//- vim:set syntax=javascript:
<commit_msg>Added other CloudFlare headers to "custom.js"<commit_after>//- JavaScript source code

//- custom.js ~~
//                                                      ~~ (c) SRW, 09 Dec 2013
//                                                  ~~ last updated 09 Dec 2013

(function () {
    'use strict';

 // Pragmas

    /*jslint indent: 4, maxlen: 80, node: true */

    /*properties
        cf_connecting_ip, 'cf-connecting-ip', cf_ipcountry, 'cf-ipcountry',
        cf_ray, 'cf-ray', cf_visitor, 'cf-visitor', connection, env,
        hasOwnProperty, headers, host, ip, log, method, parse, remoteAddress,
        replace, split, timestamp, url, 'x-forwarded-for'
    */

 // Module definitions

    exports.log = function (request) {
     // This is a custom logging function that executes once for every request
     // if logging is enabled. This function is optional, however, because
     // QMachine provides a default logging function; feel free to delete or
     // adapt it as needed :-)
        var data = {
            host: request.headers.host,
            method: request.method,
            timestamp: new Date(),
            url: request.url
        };
        if (request.headers.hasOwnProperty('cf-connecting-ip')) {
         // This header is specific to CloudFlare (www.cloudflare.com), but
         // storing the header with a hyphen inside can cause problems in query
         // languages like Hive. Thus, we use a hyphen convention.
            data.cf_connecting_ip = request.headers['cf-connecting-ip'];
        }
        if (request.headers.hasOwnProperty('cf-ipcountry')) {
         // This header is specific to CloudFlare (www.cloudflare.com), too.
            data.cf_ipcountry = request.headers['cf-ipcountry'];
        }
     /*
        if (request.headers.hasOwnProperty('cf-ray')) {
         // This header is specific to CloudFlare (www.cloudflare.com), too.
         // It has been commented out here because it's mainly intended for
         // debugging with CF Support. Read more at http://goo.gl/wMfrD8.
            data.cf_ray = request.headers['cf-ray'];
        }
     */
        if (request.headers.hasOwnProperty('cf-visitor')) {
         // This header is specific to CloudFlare (www.cloudflare.com), too.
            data.cf_visitor = request.headers['cf-visitor'];
        }
        if (request.headers.hasOwnProperty('x-forwarded-for')) {
            data.ip = request.headers['x-forwarded-for'].split(',')[0];
        } else {
            data.ip = request.connection.remoteAddress;
        }
        return data;
    };

    exports.parse = function (x) {
     // This function needs documentation.
        return JSON.parse(x, function (key, val) {
         // This function needs documentation.
            /*jslint unparam: true */
            if (typeof val === 'string') {
                return val.replace(/[$][{]([A-Z0-9_]+)[}]/g, function ($0, $1) {
                 // This function needs documentation.
                    return process.env[$1];
                });
            }
            return val;
        });
    };

 // That's all, folks!

    return;

}());

//- vim:set syntax=javascript:
<|endoftext|>


<commit_before>// http://webconverger.org/kiosk/

pref("devtools.errorconsole.enabled", false);

pref("devtools.gcli.hideIntro", true);
pref("accessibility.typeaheadfind.flashBar", 0);
pref("app.update.enabled", false);
pref("browser.download.dir", "/dev/null");
pref("browser.download.manager.useWindow", false);
pref("browser.download.show_plugins_in_list", false);
pref("browser.download.downloadDir", "/dev/null");
pref("browser.download.folderList", 2);
pref("browser.download.manager.quitBehavior", 2);
pref("browser.helperApps.deleteTempFileOnExit", true);
pref("browser.download.lastDir", "/dev/null");
pref("browser.preferences.advanced.selectedTabIndex", 2);
pref("browser.startup.homepage_override.mstone", "ignore");
pref("browser.tabs.autoHide", false);
pref("browser.tabs.tabMinWidth", 0);

pref("browser.tabs.warnOnClose", false);
pref("browser.tabs.warnOnOpen", false);
pref("browser.urlbar.hideGoButton", true);
pref("network.cookie.prefsMigrated", true);
pref("pref.advanced.javascript.disable_button.advanced", false);
pref("pref.privacy.disable_button.view_cookies", false);
pref("security.warn_viewing_mixed", false);
pref("security.warn_viewing_mixed.show_once", false);
pref("security.warn_entering_secure", false);
pref("security.warn_leaving_secure", false);
pref("security.warn_submit_insecure", false);
pref("signon.rememberSignons", false);

pref("extensions.update.enabled", false);

// Disable default browser checking.
pref("browser.shell.checkDefaultBrowser", false);

// Make sure new windows open in a tab
pref("browser.link.open_newwindow", 3);
pref("browser.link.open_external",3);
pref("browser.link.open_newwindow.restriction", 0);

// Block extension installs
pref("xpinstall.enabled", false);

// Prevent slow script dialogs
pref("dom.max_chrome_script_run_time", 0);
pref("dom.max_script_run_time", 0);

// Disable the popup window that shows up when F7 is pressed
pref("accessibility.browsewithcaret_shortcut.enabled", false);

pref("network.protocol-handler.external.mailto", false);
pref("network.protocol-handler.external.news", false);
pref("network.protocol-handler.external.nntp", false);
pref("network.protocol-handler.external.snews", false);
<commit_msg>Addressing https://github.com/Webconverger/webc/issues/163<commit_after>// http://webconverger.org/kiosk/

pref("devtools.errorconsole.enabled", false);

pref("devtools.gcli.hideIntro", true);
pref("accessibility.typeaheadfind.flashBar", 0);
pref("app.update.enabled", false);
pref("browser.download.dir", "/dev/null");
pref("browser.download.manager.useWindow", false);
pref("browser.download.show_plugins_in_list", false);
pref("browser.download.downloadDir", "/dev/null");
pref("browser.download.folderList", 2);
pref("browser.download.manager.quitBehavior", 2);
pref("browser.helperApps.deleteTempFileOnExit", true);
pref("browser.download.lastDir", "/dev/null");
pref("browser.preferences.advanced.selectedTabIndex", 2);
pref("browser.startup.homepage_override.mstone", "ignore");
pref("browser.tabs.autoHide", false);
pref("browser.tabs.tabMinWidth", 0);

pref("browser.tabs.warnOnClose", false);
pref("browser.tabs.warnOnOpen", false);
pref("browser.urlbar.hideGoButton", true);
pref("network.cookie.prefsMigrated", true);
pref("pref.advanced.javascript.disable_button.advanced", false);
pref("pref.privacy.disable_button.view_cookies", false);
pref("security.warn_viewing_mixed", false);
pref("security.warn_viewing_mixed.show_once", false);
pref("security.warn_entering_secure", false);
pref("security.warn_leaving_secure", false);
pref("security.warn_submit_insecure", false);
pref("signon.rememberSignons", false);

pref("extensions.update.enabled", false);

// Disable default browser checking.
pref("browser.shell.checkDefaultBrowser", false);

// Make sure new windows open in a tab
pref("browser.link.open_newwindow", 3);
pref("browser.link.open_external",3);
pref("browser.link.open_newwindow.restriction", 0);

// Block extension installs
pref("xpinstall.enabled", false);

// Prevent slow script dialogs
pref("dom.max_chrome_script_run_time", 0);
pref("dom.max_script_run_time", 0);

// Disable the popup window that shows up when F7 is pressed
pref("accessibility.browsewithcaret_shortcut.enabled", false);

pref("network.protocol-handler.external.mailto", false);
pref("network.protocol-handler.external.news", false);
pref("network.protocol-handler.external.nntp", false);
pref("network.protocol-handler.external.snews", false);

pref("plugin.default.state", 2);
<|endoftext|>