<commit_before>
/**
 * First we will load all of this project's JavaScript dependencies which
 * include Vue and Vue Resource. This gives a great starting point for
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');
require('jquery-tags-input/dist/jquery.tagsinput.min');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

//Vue.component('example', require('./components/people/dashboard/kids.vue'));
const Vue = require('vue');

// Notifications
import Notifications from 'vue-notification';
Vue.use(Notifications);

// Tooltip
import Tooltip from 'vue-directive-tooltip';
import 'vue-directive-tooltip/css/index.css';
Vue.use(Tooltip);

// Toggle Buttons
import ToggleButton from 'vue-js-toggle-button';
Vue.use(ToggleButton);

// Radio buttons
import PrettyCheckbox from 'pretty-checkbox-vue';
Vue.use(PrettyCheckbox);

// Custom components
Vue.component(
    'passport-clients',
    require('./components/passport/Clients.vue')
);

Vue.component(
    'passport-authorized-clients',
    require('./components/passport/AuthorizedClients.vue')
);

Vue.component(
    'passport-personal-access-tokens',
    require('./components/passport/PersonalAccessTokens.vue')
);

// Partials
Vue.component(
    'avatar',
    require('./components/partials/Avatar.vue')
);

// Form elements
Vue.component(
    'form-input',
    require('./components/partials/form/Input.vue')
);
Vue.component(
    'form-select',
    require('./components/partials/form/Select.vue')
);
Vue.component(
    'form-specialdate',
    require('./components/partials/form/SpecialDate.vue')
);
Vue.component(
    'form-date',
    require('./components/partials/form/Date.vue')
);
Vue.component(
    'form-radio',
    require('./components/partials/form/Radio.vue')
);

// Dashboard
Vue.component(
    'dashboard-log',
    require('./components/dashboard/DashboardLog.vue')
);

// Contacts
Vue.component(
    'contact-address',
    require('./components/people/Addresses.vue')
);

Vue.component(
    'contact-information',
    require('./components/people/ContactInformation.vue')
);

Vue.component(
    'contact-task',
    require('./components/people/Tasks.vue')
);

Vue.component(
    'contact-note',
    require('./components/people/Notes.vue')
);

Vue.component(
    'contact-gift',
    require('./components/people/Gifts.vue')
);

Vue.component(
    'pet',
    require('./components/people/Pets.vue')
);

Vue.component(
    'stay-in-touch',
    require('./components/people/StayInTouch.vue')
);

// Journal
Vue.component(
    'journal-list',
    require('./components/journal/JournalList.vue')
);

Vue.component(
    'journal-calendar',
    require('./components/journal/partials/JournalCalendar.vue')
);

Vue.component(
    'journal-content-rate',
    require('./components/journal/partials/JournalContentRate.vue')
);

Vue.component(
    'journal-content-activity',
    require('./components/journal/partials/JournalContentActivity.vue')
);

Vue.component(
    'journal-content-entry',
    require('./components/journal/partials/JournalContentEntry.vue')
);

// Settings
Vue.component(
    'contact-field-types',
    require('./components/settings/ContactFieldTypes.vue')
);

Vue.component(
    'genders',
    require('./components/settings/Genders.vue')
);

Vue.component(
    'reminder-rules',
    require('./components/settings/ReminderRules.vue')
);

Vue.component(
    'modules',
    require('./components/settings/Modules.vue')
);

// axios
import axios from 'axios';

// i18n
import VueI18n from 'vue-i18n';
Vue.use(VueI18n);

// Moments
import moment from 'moment';
Vue.filter('formatDate', function(value) {
    if (value) {
        return moment(String(value)).format('LL')
    }
});

import messages from '../../../public/js/langs/en.json';

export const i18n = new VueI18n({
    locale: 'en', // set locale
    fallbackLocale: 'en',
    messages: {'en': messages}
});

const loadedLanguages = ['en']; // our default language that is prelaoded

function setI18nLanguage (lang) {
    i18n.locale = lang;
    axios.defaults.headers.common['Accept-Language'] = lang;
    document.querySelector('html').setAttribute('lang', lang);
    return lang;
}

export function loadLanguageAsync (lang, set) {
    if (i18n.locale !== lang) {
      if (!loadedLanguages.includes(lang)) {
        return axios.get(`/js/langs/${lang}.json`).then(msgs => {
          i18n.setLocaleMessage(lang, msgs.data);
          loadedLanguages.push(lang);
          return set ? setI18nLanguage(lang) : lang;
        });
      }
    }
    return Promise.resolve(set ? setI18nLanguage(lang) : lang);
}

const app = null;
const me = this;
loadLanguageAsync(window.Laravel.locale, true).then((lang) => {
    moment.locale(lang);

    // the Vue appplication
    me.app = new Vue({
      i18n,
      data: {
        activities_description_show: false,
        reminders_frequency: 'once',
        accept_invite_user: false,
        date_met_the_contact: 'known',
        global_relationship_form_new_contact: true,
      },
      methods: {
      },
      mounted: function() {

        // required modules
        require('./tags');
        require('./search');
        require('./contacts');

      }
    }).$mount('#app');

    return app;
});

// jQuery-Tags-Input for the tags on the contact
$(document).ready(function() {
});
<commit_msg>Set the default vue tooltip delay to 0 so the tooltip does not stay displayed for 200ms by default (#1470)<commit_after>
/**
 * First we will load all of this project's JavaScript dependencies which
 * include Vue and Vue Resource. This gives a great starting point for
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');
require('jquery-tags-input/dist/jquery.tagsinput.min');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

//Vue.component('example', require('./components/people/dashboard/kids.vue'));
const Vue = require('vue');

// Notifications
import Notifications from 'vue-notification';
Vue.use(Notifications);

// Tooltip
import Tooltip from 'vue-directive-tooltip';
import 'vue-directive-tooltip/css/index.css';
Vue.use(Tooltip, {
    delay: 0,
});

// Toggle Buttons
import ToggleButton from 'vue-js-toggle-button';
Vue.use(ToggleButton);

// Radio buttons
import PrettyCheckbox from 'pretty-checkbox-vue';
Vue.use(PrettyCheckbox);

// Custom components
Vue.component(
    'passport-clients',
    require('./components/passport/Clients.vue')
);

Vue.component(
    'passport-authorized-clients',
    require('./components/passport/AuthorizedClients.vue')
);

Vue.component(
    'passport-personal-access-tokens',
    require('./components/passport/PersonalAccessTokens.vue')
);

// Partials
Vue.component(
    'avatar',
    require('./components/partials/Avatar.vue')
);

// Form elements
Vue.component(
    'form-input',
    require('./components/partials/form/Input.vue')
);
Vue.component(
    'form-select',
    require('./components/partials/form/Select.vue')
);
Vue.component(
    'form-specialdate',
    require('./components/partials/form/SpecialDate.vue')
);
Vue.component(
    'form-date',
    require('./components/partials/form/Date.vue')
);
Vue.component(
    'form-radio',
    require('./components/partials/form/Radio.vue')
);

// Dashboard
Vue.component(
    'dashboard-log',
    require('./components/dashboard/DashboardLog.vue')
);

// Contacts
Vue.component(
    'contact-address',
    require('./components/people/Addresses.vue')
);

Vue.component(
    'contact-information',
    require('./components/people/ContactInformation.vue')
);

Vue.component(
    'contact-task',
    require('./components/people/Tasks.vue')
);

Vue.component(
    'contact-note',
    require('./components/people/Notes.vue')
);

Vue.component(
    'contact-gift',
    require('./components/people/Gifts.vue')
);

Vue.component(
    'pet',
    require('./components/people/Pets.vue')
);

Vue.component(
    'stay-in-touch',
    require('./components/people/StayInTouch.vue')
);

// Journal
Vue.component(
    'journal-list',
    require('./components/journal/JournalList.vue')
);

Vue.component(
    'journal-calendar',
    require('./components/journal/partials/JournalCalendar.vue')
);

Vue.component(
    'journal-content-rate',
    require('./components/journal/partials/JournalContentRate.vue')
);

Vue.component(
    'journal-content-activity',
    require('./components/journal/partials/JournalContentActivity.vue')
);

Vue.component(
    'journal-content-entry',
    require('./components/journal/partials/JournalContentEntry.vue')
);

// Settings
Vue.component(
    'contact-field-types',
    require('./components/settings/ContactFieldTypes.vue')
);

Vue.component(
    'genders',
    require('./components/settings/Genders.vue')
);

Vue.component(
    'reminder-rules',
    require('./components/settings/ReminderRules.vue')
);

Vue.component(
    'modules',
    require('./components/settings/Modules.vue')
);

// axios
import axios from 'axios';

// i18n
import VueI18n from 'vue-i18n';
Vue.use(VueI18n);

// Moments
import moment from 'moment';
Vue.filter('formatDate', function(value) {
    if (value) {
        return moment(String(value)).format('LL')
    }
});

import messages from '../../../public/js/langs/en.json';

export const i18n = new VueI18n({
    locale: 'en', // set locale
    fallbackLocale: 'en',
    messages: {'en': messages}
});

const loadedLanguages = ['en']; // our default language that is prelaoded

function setI18nLanguage (lang) {
    i18n.locale = lang;
    axios.defaults.headers.common['Accept-Language'] = lang;
    document.querySelector('html').setAttribute('lang', lang);
    return lang;
}

export function loadLanguageAsync (lang, set) {
    if (i18n.locale !== lang) {
      if (!loadedLanguages.includes(lang)) {
        return axios.get(`/js/langs/${lang}.json`).then(msgs => {
          i18n.setLocaleMessage(lang, msgs.data);
          loadedLanguages.push(lang);
          return set ? setI18nLanguage(lang) : lang;
        });
      }
    }
    return Promise.resolve(set ? setI18nLanguage(lang) : lang);
}

const app = null;
const me = this;
loadLanguageAsync(window.Laravel.locale, true).then((lang) => {
    moment.locale(lang);

    // the Vue appplication
    me.app = new Vue({
      i18n,
      data: {
        activities_description_show: false,
        reminders_frequency: 'once',
        accept_invite_user: false,
        date_met_the_contact: 'known',
        global_relationship_form_new_contact: true,
      },
      methods: {
      },
      mounted: function() {

        // required modules
        require('./tags');
        require('./search');
        require('./contacts');

      }
    }).$mount('#app');

    return app;
});

// jQuery-Tags-Input for the tags on the contact
$(document).ready(function() {
});
<|endoftext|>


<commit_before>var metas = document.getElementsByTagName('meta');
var i;
if (navigator.userAgent.match(/iPhone/i)) {
  for (i=0; i<metas.length; i++) {
    if (metas[i].name == "viewport") {
      metas[i].content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0";
    }
  }
  document.addEventListener("gesturestart", gestureStart, false);
}
function gestureStart() {
  for (i=0; i<metas.length; i++) {
    if (metas[i].name == "viewport") {
      metas[i].content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6";
    }
  }
}
<commit_msg>Delete scale.fix.js<commit_after><|endoftext|>


<commit_before>// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/* A little code to ease navigation of these documents.
 *
 * On window load we:
 *  + Bind search box hint placeholder show/hide events (bindSearchEvents)
 *  + Generate a table of contents (generateTOC)
 *  + Bind foldable sections (bindToggles)
 *  + Bind links to foldable sections (bindToggleLinks)
 */

(function() {
'use strict';

function bindSearchEvents() {

  var search = $('#search');
  if (search.length === 0) {
    return; // no search box
  }

  function clearInactive() {
    if (search.is('.inactive')) {
      search.val('');
      search.removeClass('inactive');
    }
  }

  function restoreInactive() {
    if (search.val() !== '') {
      return;
    }
    search.val(search.attr('placeholder'));
    search.addClass('inactive');
  }

  search.on('focus', clearInactive);
  search.on('blur', restoreInactive);

  restoreInactive();
}

/* Generates a table of contents: looks for h2 and h3 elements and generates
 * links. "Decorates" the element with id=="nav" with this table of contents.
 */
function generateTOC() {
  if ($('#manual-nav').length > 0) {
    return;
  }

  var nav = $('#nav');
  if (nav.length === 0) {
    return;
  }

  var toc_items = [];
  $(nav).nextAll('h2, h3').each(function() {
    var node = this;
    var link = $('').attr('href', '#' + node.id).text($(node).text());
    var item;
    if ($(node).is('h2')) {
      item = $('
');
    } else { // h3
      item = $('
');
    }
    item.append(link);
    toc_items.push(item);
  });
  if (toc_items.length <= 1) {
    return;
  }

  var dl1 = $('
');
  var dl2 = $('
');

  var split_index = (toc_items.length / 2) + 1;
  if (split_index < 8) {
    split_index = toc_items.length;
  }
  for (var i = 0; i < split_index; i++) {
    dl1.append(toc_items[i]);
  }
  for (/* keep using i */; i < toc_items.length; i++) {
    dl2.append(toc_items[i]);
  }

  var tocTable = $('
').appendTo(nav);
  var tocBody = $('
').appendTo(tocTable);
  var tocRow = $('
').appendTo(tocBody);

  // 1st column
  $('').appendTo(tocRow).append(dl1);
  // 2nd column
  $('').appendTo(tocRow).append(dl2);
}

function bindToggle(el) {
  $('.toggleButton', el).click(function() {
    if ($(el).is('.toggle')) {
      $(el).addClass('toggleVisible').removeClass('toggle');
    } else {
      $(el).addClass('toggle').removeClass('toggleVisible');
    }
  });
}
function bindToggles(selector) {
  $(selector).each(function(i, el) {
    bindToggle(el);
  });
}

function bindToggleLink(el, prefix) {
  $(el).click(function() {
    var href = $(el).attr('href');
    var i = href.indexOf('#'+prefix);
    if (i < 0) {
      return;
    }
    var id = '#' + prefix + href.slice(i+1+prefix.length);
    if ($(id).is('.toggle')) {
      $(id).find('.toggleButton').first().click();
    }
  });
}
function bindToggleLinks(selector, prefix) {
  $(selector).each(function(i, el) {
    bindToggleLink(el, prefix);
  });
}

function setupDropdownPlayground() {
  if (!$('#page').is('.wide')) {
    return; // don't show on front page
  }
  var button = $('#playgroundButton');
  var div = $('#playground');
  var setup = false;
  button.toggle(function() {
    button.addClass('active');
    div.show();
    if (setup) {
      return;
    }
    setup = true;
    playground({
      'codeEl': $('.code', div),
      'outputEl': $('.output', div),
      'runEl': $('.run', div),
      'fmtEl': $('.fmt', div),
      'shareEl': $('.share', div),
      'shareRedirect': 'http://play.golang.org/p/'
    });
  },
  function() {
    button.removeClass('active');
    div.hide();
  });
  button.show();
  $('#menu').css('min-width', '+=60');
}

$(document).ready(function() {
  bindSearchEvents();
  generateTOC();
  bindToggles(".toggle");
  bindToggles(".toggleVisible");
  bindToggleLinks(".exampleLink", "example_");
  bindToggleLinks(".overviewLink", "");
  bindToggleLinks(".examplesLink", "");
  bindToggleLinks(".indexLink", "");
  setupDropdownPlayground();
});

})();
<commit_msg>doc/godoc.js: assign tmp. id to nodes without id in generateTOC()<commit_after>// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/* A little code to ease navigation of these documents.
 *
 * On window load we:
 *  + Bind search box hint placeholder show/hide events (bindSearchEvents)
 *  + Generate a table of contents (generateTOC)
 *  + Bind foldable sections (bindToggles)
 *  + Bind links to foldable sections (bindToggleLinks)
 */

(function() {
'use strict';

function bindSearchEvents() {

  var search = $('#search');
  if (search.length === 0) {
    return; // no search box
  }

  function clearInactive() {
    if (search.is('.inactive')) {
      search.val('');
      search.removeClass('inactive');
    }
  }

  function restoreInactive() {
    if (search.val() !== '') {
      return;
    }
    search.val(search.attr('placeholder'));
    search.addClass('inactive');
  }

  search.on('focus', clearInactive);
  search.on('blur', restoreInactive);

  restoreInactive();
}

/* Generates a table of contents: looks for h2 and h3 elements and generates
 * links. "Decorates" the element with id=="nav" with this table of contents.
 */
function generateTOC() {
  if ($('#manual-nav').length > 0) {
    return;
  }

  var nav = $('#nav');
  if (nav.length === 0) {
    return;
  }

  var toc_items = [];
  $(nav).nextAll('h2, h3').each(function() {
    var node = this;
    if (node.id == '')
      node.id = 'tmp_' + toc_items.length;
    var link = $('').attr('href', '#' + node.id).text($(node).text());
    var item;
    if ($(node).is('h2')) {
      item = $('
');
    } else { // h3
      item = $('
');
    }
    item.append(link);
    toc_items.push(item);
  });
  if (toc_items.length <= 1) {
    return;
  }

  var dl1 = $('
');
  var dl2 = $('
');

  var split_index = (toc_items.length / 2) + 1;
  if (split_index < 8) {
    split_index = toc_items.length;
  }
  for (var i = 0; i < split_index; i++) {
    dl1.append(toc_items[i]);
  }
  for (/* keep using i */; i < toc_items.length; i++) {
    dl2.append(toc_items[i]);
  }

  var tocTable = $('
').appendTo(nav);
  var tocBody = $('
').appendTo(tocTable);
  var tocRow = $('
').appendTo(tocBody);

  // 1st column
  $('').appendTo(tocRow).append(dl1);
  // 2nd column
  $('').appendTo(tocRow).append(dl2);
}

function bindToggle(el) {
  $('.toggleButton', el).click(function() {
    if ($(el).is('.toggle')) {
      $(el).addClass('toggleVisible').removeClass('toggle');
    } else {
      $(el).addClass('toggle').removeClass('toggleVisible');
    }
  });
}
function bindToggles(selector) {
  $(selector).each(function(i, el) {
    bindToggle(el);
  });
}

function bindToggleLink(el, prefix) {
  $(el).click(function() {
    var href = $(el).attr('href');
    var i = href.indexOf('#'+prefix);
    if (i < 0) {
      return;
    }
    var id = '#' + prefix + href.slice(i+1+prefix.length);
    if ($(id).is('.toggle')) {
      $(id).find('.toggleButton').first().click();
    }
  });
}
function bindToggleLinks(selector, prefix) {
  $(selector).each(function(i, el) {
    bindToggleLink(el, prefix);
  });
}

function setupDropdownPlayground() {
  if (!$('#page').is('.wide')) {
    return; // don't show on front page
  }
  var button = $('#playgroundButton');
  var div = $('#playground');
  var setup = false;
  button.toggle(function() {
    button.addClass('active');
    div.show();
    if (setup) {
      return;
    }
    setup = true;
    playground({
      'codeEl': $('.code', div),
      'outputEl': $('.output', div),
      'runEl': $('.run', div),
      'fmtEl': $('.fmt', div),
      'shareEl': $('.share', div),
      'shareRedirect': 'http://play.golang.org/p/'
    });
  },
  function() {
    button.removeClass('active');
    div.hide();
  });
  button.show();
  $('#menu').css('min-width', '+=60');
}

$(document).ready(function() {
  bindSearchEvents();
  generateTOC();
  bindToggles(".toggle");
  bindToggles(".toggleVisible");
  bindToggleLinks(".exampleLink", "example_");
  bindToggleLinks(".overviewLink", "");
  bindToggleLinks(".examplesLink", "");
  bindToggleLinks(".indexLink", "");
  setupDropdownPlayground();
});

})();
<|endoftext|>


<commit_before>define([
	"Ember",
	"EmberData",
	"config",
	"utils/node/platform"
], function(
	Ember,
	DS,
	config,
	platform
) {

	var get = Ember.get;
	var set = Ember.set;
	var attr = DS.attr;

	var langs = config.langs;
	var langCodes = Object.keys( langs );

	var isWin = platform.isWin;

	function defaultLangFilterValue() {
		return langCodes.reduce(function( obj, code ) {
			if ( !langs[ code ].disabled ) {
				obj[ code ] = true;
			}
			return obj;
		}, {} );
	}

	return DS.Model.extend({
		advanced            : attr( "boolean", { defaultValue: false } ),
		livestreamer        : attr( "string",  { defaultValue: "" } ),
		livestreamer_params : attr( "string",  { defaultValue: "" } ),
		quality             : attr( "number",  { defaultValue: 0 } ),
		player              : attr( "string",  { defaultValue: "" } ),
		player_params       : attr( "string",  { defaultValue: "" } ),
		player_passthrough  : attr( "string",  { defaultValue: "http" } ),
		player_reconnect    : attr( "boolean", { defaultValue: true } ),
		player_no_close     : attr( "boolean", { defaultValue: false } ),
		gui_theme           : attr( "string",  { defaultValue: "default" } ),
		gui_smoothscroll    : attr( "boolean", { defaultValue: true } ),
		gui_integration     : attr( "number",  { defaultValue: 3 } ),
		gui_minimizetotray  : attr( "number",  { defaultValue: false } ),
		gui_minimize        : attr( "number",  { defaultValue: 0 } ),
		gui_focusrefresh    : attr( "number",  { defaultValue: 0 } ),
		gui_hidestreampopup : attr( "boolean", { defaultValue: false } ),
		gui_openchat        : attr( "boolean", { defaultValue: false } ),
		gui_openchat_context: attr( "boolean", { defaultValue: false } ),
		gui_twitchemotes    : attr( "boolean", { defaultValue: false } ),
		gui_homepage        : attr( "string",  { defaultValue: "/featured" } ),
		gui_layout          : attr( "string",  { defaultValue: "tile" } ),
		gui_filterstreams   : attr( "boolean", { defaultValue: false } ),
		gui_langfilter      : attr( "",        { defaultValue: defaultLangFilterValue } ),
		stream_info         : attr( "number",  { defaultValue: 0 } ),
		stream_show_flag    : attr( "boolean", { defaultValue: false } ),
		stream_show_info    : attr( "boolean", { defaultValue: false } ),
		stream_click_middle : attr( "number",  { defaultValue: 2 } ),
		stream_click_modify : attr( "number",  { defaultValue: 4 } ),
		notify_enabled      : attr( "boolean", { defaultValue: true } ),
		notify_all          : attr( "boolean", { defaultValue: true } ),
		notify_grouping     : attr( "boolean", { defaultValue: true } ),
		notify_click        : attr( "number",  { defaultValue: 1 } ),
		notify_click_group  : attr( "number",  { defaultValue: 1 } ),
		notify_badgelabel   : attr( "boolean", { defaultValue: true } ),
		notify_shortcut     : attr( "boolean", { defaultValue: true } ),
		hls_live_edge       : attr( "string",  { defaultValue: "3", min: "1", max: "10" } ),
		hls_segment_threads : attr( "string",  { defaultValue: "1", min: "1", max: "10" } ),
		retry_open          : attr( "string",  { defaultValue: "1", min: "1", max: "10" } ),
		retry_streams       : attr( "string",  { defaultValue: "1", min: "0", max: "3" } ),
		chat_method         : attr( "string",  { defaultValue: "default" } ),
		chat_command        : attr( "string",  { defaultValue: "" } ),

		// correct old value
		gui_minimize_observer: function() {
			if ( isNaN( get( this, "gui_minimize" ) ) ) {
				set( this, "gui_minimize", 0 );
			}
		}.observes( "gui_minimize" ),

		isVisibleInTaskbar: function() {
			return ( get( this, "gui_integration" ) & 1 ) > 0;
		}.property( "gui_integration" ),

		isVisibleInTray: function() {
			return ( get( this, "gui_integration" ) & 2 ) > 0;
		}.property( "gui_integration" ),

		playerParamsCorrected: function() {
			var params = get( this, "player_params" );
			return params.length && params.indexOf( "{filename}" ) === -1
				? params + " {filename}"
				: params;
		}.property( "player_params" )

	}).reopenClass({

		toString: function() { return "Settings"; },

		qualities: [
			{ id: 0, label: "Source",     quality: "source,best" },
			{ id: 1, label: "High",       quality: "high,mobile_high,best" },
			{ id: 2, label: "Medium",     quality: "medium,mobile_medium,worst" },
			{ id: 3, label: "Low",        quality: "low,mobile_mobile,worst" },
			{ id: 4, label: "Audio only", quality: "audio" }
		],

		passthrough: [
			{ value: "http", label: "http" },
			{ value: "rtmp", label: "rtmp" },
			{ value: "hls",  label: "hls" }
		],

		// bitwise IDs: both & 1 && both & 2
		integration: [
			{ id: 3, label: "Both" },
			{ id: 1, label: "Taskbar" },
			{ id: 2, label: "Tray" }
		],

		minimize: [
			{ id: 0, label: "Do nothing" },
			{ id: 1, label: "Minimize" },
			{ id: 2, label: "Move to tray" }
		],

		gui_focusrefresh: [
			{ value:      0, label: "Don't refresh" },
			{ value:  60000, label: "After one minute" },
			{ value: 120000, label: "After two minutes" },
			{ value: 300000, label: "After five minutes" }
		],

		notify_all: [
			{ value: true,  label: "Show all except disabled ones" },
			{ value: false, label: "Ignore all except enabled ones" }
		],

		notify_click: [
			{ id: 0, label: "Do nothing" },
			{ id: 1, label: "Go to favorites" },
			{ id: 2, label: "Open stream" },
			{ id: 3, label: "Open stream+chat" }
		],

		notify_click_group: [
			{ id: 1, label: "Go to favorites" },
			{ id: 2, label: "Open all streams" },
			{ id: 3, label: "Open all streams+chats" }
		],

		chat_methods: [
			// TODO: change to "browser"
			{ id: "default",  label: "Default Browser" },
			// TODO: change to "default"
			{ id: "irc",      label: "Internal IRC Client", disabled: true },
			{ id: "chromium", label: "Chromium" },
			{ id: "chrome",   label: "Google Chrome" },
			{ id: "msie",     label: "Internet Explorer", disabled: !isWin },
			{ id: "chatty",   label: "Chatty" },
			{ id: "custom",   label: "Custom application" }
		],

		gui_filterstreams: [
			{ value: false, label: "Fade out streams" },
			{ value: true,  label: "Filter out streams" }
		],

		stream_info: [
			{ id: 0, label: "Game being played" },
			{ id: 1, label: "Stream title" }
		],

		stream_click: [
			{ id: 0, key: "disabled", label: "Do nothing" },
			{ id: 1, key: "launch",   label: "Launch stream" },
			{ id: 2, key: "chat",     label: "Open chat" },
			{ id: 3, key: "channel",  label: "Go to channel page" },
			{ id: 4, key: "settings", label: "Go to channel settings" }
		]

	});

});
<commit_msg>Update the list of avail. livestreamer qualities<commit_after>define([
	"Ember",
	"EmberData",
	"config",
	"utils/node/platform"
], function(
	Ember,
	DS,
	config,
	platform
) {

	var get = Ember.get;
	var set = Ember.set;
	var attr = DS.attr;

	var langs = config.langs;
	var langCodes = Object.keys( langs );

	var isWin = platform.isWin;

	function defaultLangFilterValue() {
		return langCodes.reduce(function( obj, code ) {
			if ( !langs[ code ].disabled ) {
				obj[ code ] = true;
			}
			return obj;
		}, {} );
	}

	return DS.Model.extend({
		advanced            : attr( "boolean", { defaultValue: false } ),
		livestreamer        : attr( "string",  { defaultValue: "" } ),
		livestreamer_params : attr( "string",  { defaultValue: "" } ),
		quality             : attr( "number",  { defaultValue: 0 } ),
		player              : attr( "string",  { defaultValue: "" } ),
		player_params       : attr( "string",  { defaultValue: "" } ),
		player_passthrough  : attr( "string",  { defaultValue: "http" } ),
		player_reconnect    : attr( "boolean", { defaultValue: true } ),
		player_no_close     : attr( "boolean", { defaultValue: false } ),
		gui_theme           : attr( "string",  { defaultValue: "default" } ),
		gui_smoothscroll    : attr( "boolean", { defaultValue: true } ),
		gui_integration     : attr( "number",  { defaultValue: 3 } ),
		gui_minimizetotray  : attr( "number",  { defaultValue: false } ),
		gui_minimize        : attr( "number",  { defaultValue: 0 } ),
		gui_focusrefresh    : attr( "number",  { defaultValue: 0 } ),
		gui_hidestreampopup : attr( "boolean", { defaultValue: false } ),
		gui_openchat        : attr( "boolean", { defaultValue: false } ),
		gui_openchat_context: attr( "boolean", { defaultValue: false } ),
		gui_twitchemotes    : attr( "boolean", { defaultValue: false } ),
		gui_homepage        : attr( "string",  { defaultValue: "/featured" } ),
		gui_layout          : attr( "string",  { defaultValue: "tile" } ),
		gui_filterstreams   : attr( "boolean", { defaultValue: false } ),
		gui_langfilter      : attr( "",        { defaultValue: defaultLangFilterValue } ),
		stream_info         : attr( "number",  { defaultValue: 0 } ),
		stream_show_flag    : attr( "boolean", { defaultValue: false } ),
		stream_show_info    : attr( "boolean", { defaultValue: false } ),
		stream_click_middle : attr( "number",  { defaultValue: 2 } ),
		stream_click_modify : attr( "number",  { defaultValue: 4 } ),
		notify_enabled      : attr( "boolean", { defaultValue: true } ),
		notify_all          : attr( "boolean", { defaultValue: true } ),
		notify_grouping     : attr( "boolean", { defaultValue: true } ),
		notify_click        : attr( "number",  { defaultValue: 1 } ),
		notify_click_group  : attr( "number",  { defaultValue: 1 } ),
		notify_badgelabel   : attr( "boolean", { defaultValue: true } ),
		notify_shortcut     : attr( "boolean", { defaultValue: true } ),
		hls_live_edge       : attr( "string",  { defaultValue: "3", min: "1", max: "10" } ),
		hls_segment_threads : attr( "string",  { defaultValue: "1", min: "1", max: "10" } ),
		retry_open          : attr( "string",  { defaultValue: "1", min: "1", max: "10" } ),
		retry_streams       : attr( "string",  { defaultValue: "1", min: "0", max: "3" } ),
		chat_method         : attr( "string",  { defaultValue: "default" } ),
		chat_command        : attr( "string",  { defaultValue: "" } ),

		// correct old value
		gui_minimize_observer: function() {
			if ( isNaN( get( this, "gui_minimize" ) ) ) {
				set( this, "gui_minimize", 0 );
			}
		}.observes( "gui_minimize" ),

		isVisibleInTaskbar: function() {
			return ( get( this, "gui_integration" ) & 1 ) > 0;
		}.property( "gui_integration" ),

		isVisibleInTray: function() {
			return ( get( this, "gui_integration" ) & 2 ) > 0;
		}.property( "gui_integration" ),

		playerParamsCorrected: function() {
			var params = get( this, "player_params" );
			return params.length && params.indexOf( "{filename}" ) === -1
				? params + " {filename}"
				: params;
		}.property( "player_params" )

	}).reopenClass({

		toString: function() { return "Settings"; },

		/**
		 * Use a static list of qualities on twitch recognized by livestreamer:
		 * source, high, medium, low, mobile
		 *
		 * Specific qualities are available for a couple of special channels:
		 * 144p30, 240p30, 360p30, 480p30, 540p30, 720p30, 720p60
		 * https://blog.twitch.tv/-705404e95cc2
		 *
		 * Always add an ultimate fallback quality to the end of the list. This is needed for
		 * watching unpartnered channels that are only available in source quality when a
		 * different default quality has been selected by the user.
		 */
		qualities: [
			// Source - input stream from the broadcaster
			{ id: 0, label: "Source",     quality: "source,best" },
			// High   - 720p30 @ ~1.25 Mbit/s (use the same framerate first)
			{ id: 1, label: "High",       quality: "high,720p30,720p60,best" },
			// Medium - 480p30 @ ~0.75 Mbit/s (use the same bitrate first)
			{ id: 2, label: "Medium",     quality: "medium,480p30,540p30,worst" },
			// Low    - 360p30 @ ~0.50 Mbit/s (use the same resolution first)
			{ id: 3, label: "Low",        quality: "low,360p30,240p30,144p30,mobile,worst" },
			// Audio (no fallback qualities)
			{ id: 4, label: "Audio only", quality: "audio" }
		],

		passthrough: [
			{ value: "http", label: "http" },
			{ value: "rtmp", label: "rtmp" },
			{ value: "hls",  label: "hls" }
		],

		// bitwise IDs: both & 1 && both & 2
		integration: [
			{ id: 3, label: "Both" },
			{ id: 1, label: "Taskbar" },
			{ id: 2, label: "Tray" }
		],

		minimize: [
			{ id: 0, label: "Do nothing" },
			{ id: 1, label: "Minimize" },
			{ id: 2, label: "Move to tray" }
		],

		gui_focusrefresh: [
			{ value:      0, label: "Don't refresh" },
			{ value:  60000, label: "After one minute" },
			{ value: 120000, label: "After two minutes" },
			{ value: 300000, label: "After five minutes" }
		],

		notify_all: [
			{ value: true,  label: "Show all except disabled ones" },
			{ value: false, label: "Ignore all except enabled ones" }
		],

		notify_click: [
			{ id: 0, label: "Do nothing" },
			{ id: 1, label: "Go to favorites" },
			{ id: 2, label: "Open stream" },
			{ id: 3, label: "Open stream+chat" }
		],

		notify_click_group: [
			{ id: 1, label: "Go to favorites" },
			{ id: 2, label: "Open all streams" },
			{ id: 3, label: "Open all streams+chats" }
		],

		chat_methods: [
			// TODO: change to "browser"
			{ id: "default",  label: "Default Browser" },
			// TODO: change to "default"
			{ id: "irc",      label: "Internal IRC Client", disabled: true },
			{ id: "chromium", label: "Chromium" },
			{ id: "chrome",   label: "Google Chrome" },
			{ id: "msie",     label: "Internet Explorer", disabled: !isWin },
			{ id: "chatty",   label: "Chatty" },
			{ id: "custom",   label: "Custom application" }
		],

		gui_filterstreams: [
			{ value: false, label: "Fade out streams" },
			{ value: true,  label: "Filter out streams" }
		],

		stream_info: [
			{ id: 0, label: "Game being played" },
			{ id: 1, label: "Stream title" }
		],

		stream_click: [
			{ id: 0, key: "disabled", label: "Do nothing" },
			{ id: 1, key: "launch",   label: "Launch stream" },
			{ id: 2, key: "chat",     label: "Open chat" },
			{ id: 3, key: "channel",  label: "Go to channel page" },
			{ id: 4, key: "settings", label: "Go to channel settings" }
		]

	});

});
<|endoftext|>


<commit_before>var Q = require('q'),
    _ = require('underscore'),
    shell = require('shelljs'),
    SQS = require('./sqs'),
    DynamoDB = require('./dynamoDB');

var argv = require('optimist')
    .usage('Usage: $0 -i [TIME_SEC]')
    //.demand(['i'])
    .alias('i', 'timesec')
    .describe('i', 'Idle Time in seconds')
    .default('i', '0')
    .argv;

var idleTime = argv.i;

var idleTimer,
    noTimer = false,
    QUEUE_NAME = 'CS553';

if (idleTime == 0) {
    noTimer = true;
    console.log("[WORKER] : worker running with default value of 0 for Idle Time");
} else {
    idleTimer = startIdleTimer(idleTime);
}

var canProceed = true;

// NOTE: Check for tasks on Master Q every 1 second
setInterval(function () {
    if (canProceed) {
        SQS.getQueueLength(QUEUE_NAME).then(function (length) {
            console.log("Queue Length:", length);
            // NOTE: if there are tasks in Q, fetch task, process and then return the response
            if (length > 0) {
                canProceed = false;

                SQS.receiveMessage(QUEUE_NAME, ['clientId']).then(function (data) {
                    if (data.Messages && data.Messages.length > 0) {
                        data.Messages.forEach(function (task, i) {
                            var resultQ = task.MessageAttributes.clientId.StringValue,
                                taskId = task.MessageId; // messageId in Master Q is the taskId which will be verified at client

                            if (!noTimer)
                                clearTimeout(idleTimer);

                            DynamoDB.addItem(undefined, taskId).then(function (data) {
                                // added task; continue to process it

                                // NOTE: Synchronously process the task
                                var result = processTask(task.Body);

                                console.log("Task '" + task.Body + "' completed. Result : " + result);

                                var messageAttributes = {
                                    taskId: {
                                        DataType: 'String',
                                        StringValue: taskId
                                    }
                                };

                                console.log("Sending message to resultQ : " + resultQ + ", taskId : " + taskId);

                                SQS.sendMessage(resultQ, messageAttributes, result).then(function (taskId) {
                                    console.log("Task Result Sent Back : ", taskId);
                                    canProceed = true;

                                    if (!noTimer)
                                        idleTimer = startIdleTimer(idleTime);
                                }, function (err) {
                                    console.error("Failed to send message to ResultQ. ", err);
                                    canProceed = true;
                                });
                            }, function (error) {
                                // task already being processed by another worker, so ignore
                                console.log("Task '" + task.Body + "' already being processed by other worker; so ignoring. ");

                                if (!noTimer)
                                    idleTimer = startIdleTimer(idleTime);

                                canProceed = true;
                            });
                        });
                    }
                }, function (err) {
                    console.error("Problem retrieving message from MASTER_QUEUE.", err);
                    canProceed = true;
                });
            }
        }, function (error) {
            console.error("Error retrieving MASTER_QUEUE length.", error);
            canProceed = true;
        });
    }
}, 1000);

// NOTE: Synchronous process of task
function processTask(task) {
    console.log("Performing Task : ", Date.now());

    var taskResult = shell.exec(task, {
        silent: true
    }).output;

    return task + taskResult + ' Completed !';
}

function startIdleTimer(timeInSeconds) {
    return setTimeout(function () {
        console.log('Idle Timeout Expired, Terminating myself !!');
        shell.exec('sudo shutdown -h now', function (code, output) {
            console.log('Exit Code: ', code);
            console.log('Program output: ', output);
        });
    }, timeInSeconds * 1000);
}

// Shutdown instance if worker crashes
process.on("SIGINT", function () {
    console.log('Exiting Worker !');

    if (!noTimer) {
        console.log('Shutting myself down !');

        shell.exec('sudo shutdown -h now', function (code, output) {
            console.log('Exit Code: ', code);
            console.log('Program output: ', output);
        });
    }
    process.exit();
});
<commit_msg>fix worker bug<commit_after>var Q = require('q'),
    _ = require('underscore'),
    shell = require('shelljs'),
    SQS = require('./sqs'),
    DynamoDB = require('./dynamoDB');

var argv = require('optimist')
    .usage('Usage: $0 -i [TIME_SEC]')
    //.demand(['i'])
    .alias('i', 'timesec')
    .describe('i', 'Idle Time in seconds')
    .default('i', '0')
    .argv;

var idleTime = argv.i;

var idleTimer,
    noTimer = false,
    QUEUE_NAME = 'CS553';

if (idleTime == 0) {
    noTimer = true;
    console.log("[WORKER] : worker running with default value of 0 for Idle Time");
} else {
    idleTimer = startIdleTimer(idleTime);
}

var canProceed = true;

// NOTE: Check for tasks on Master Q every 1 second
setInterval(function () {
    if (canProceed) {
        SQS.getQueueLength(QUEUE_NAME).then(function (length) {
            console.log("Queue Length:", length);
            // NOTE: if there are tasks in Q, fetch task, process and then return the response
            if (length > 0) {
                canProceed = false;

                SQS.receiveMessage(QUEUE_NAME, ['clientId']).then(function (data) {
                    if (data.Messages && data.Messages.length > 0) {
                        data.Messages.forEach(function (task, i) {
                            var resultQ = task.MessageAttributes.clientId.StringValue,
                                taskId = task.MessageId; // messageId in Master Q is the taskId which will be verified at client

                            if (!noTimer)
                                clearTimeout(idleTimer);

                            DynamoDB.addItem(undefined, taskId).then(function (data) {
                                // added task; continue to process it

                                // NOTE: Synchronously process the task
                                var result = processTask(task.Body);

                                console.log("Task '" + task.Body + "' completed. Result : " + result);

                                var messageAttributes = {
                                    taskId: {
                                        DataType: 'String',
                                        StringValue: taskId
                                    }
                                };

                                console.log("Sending message to resultQ : " + resultQ + ", taskId : " + taskId);

                                SQS.sendMessage(resultQ, messageAttributes, result).then(function (taskId) {
                                    console.log("Task Result Sent Back : ", taskId);
                                    canProceed = true;

                                    if (!noTimer)
                                        idleTimer = startIdleTimer(idleTime);
                                }, function (err) {
                                    console.error("Failed to send message to ResultQ. ", err);
                                    canProceed = true;
                                });
                            }, function (error) {
                                // task already being processed by another worker, so ignore
                                console.log("Task '" + task.Body + "' already being processed by other worker; so ignoring. ");

                                if (!noTimer)
                                    idleTimer = startIdleTimer(idleTime);

                                canProceed = true;
                            });
                        });
                    } else {
                        canProceed = true;
                    }
                }, function (err) {
                    console.error("Problem retrieving message from MASTER_QUEUE.", err);
                    canProceed = true;
                });
            }
        }, function (error) {
            console.error("Error retrieving MASTER_QUEUE length.", error);
            canProceed = true;
        });
    }
}, 1000);

// NOTE: Synchronous process of task
function processTask(task) {
    console.log("Performing Task : ", Date.now());

    var taskResult = shell.exec(task, {
        silent: true
    }).output;

    return task + taskResult + ' Completed !';
}

function startIdleTimer(timeInSeconds) {
    return setTimeout(function () {
        console.log('Idle Timeout Expired, Terminating myself !!');
        shell.exec('sudo shutdown -h now', function (code, output) {
            console.log('Exit Code: ', code);
            console.log('Program output: ', output);
        });
    }, timeInSeconds * 1000);
}

// Shutdown instance if worker crashes
process.on("SIGINT", function () {
    console.log('Exiting Worker !');

    if (!noTimer) {
        console.log('Shutting myself down !');

        shell.exec('sudo shutdown -h now', function (code, output) {
            console.log('Exit Code: ', code);
            console.log('Program output: ', output);
        });
    }
    process.exit();
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';

class UpdateTeamUserMutation extends Relay.Mutation {
  getMutation() {
    return Relay.QL`mutation updateTeamUser {
      updateTeamUser
    }`;
  }

  static fragments = {
    team_user: () => Relay.QL`fragment on TeamUser { id, team_id, user_id, status, role }`,
  };

  getVariables() {
    return { team_id: this.props.team_id, user_id: this.props.user_id, status: this.props.status, id: this.props.id, role: this.props.role.value };
  }

  getFatQuery() {
    return Relay.QL`
      fragment on UpdateTeamUserPayload {
        team_user
      }
    `;
  }

  getConfigs() {
    return [{
      type: 'REQUIRED_CHILDREN',
      children: [Relay.QL`
        fragment on UpdateTeamUserPayload {
          team_user {
            id, team_id, user_id, status, role
          }
        }`,
      ],
    }];
  }
}

export default UpdateTeamUserMutation;
<commit_msg>Ticket #5613<commit_after>import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';

class UpdateTeamUserMutation extends Relay.Mutation {
  getMutation() {
    return Relay.QL`mutation updateTeamUser {
      updateTeamUser
    }`;
  }

  static fragments = {
    team_user: () => Relay.QL`fragment on TeamUser { id, team_id, user_id, status, role }`,
  };

  getVariables() {
    let role = this.props.role
    if (typeof role !== 'undefined') {
      role = role.value
    }
    return { team_id: this.props.team_id, user_id: this.props.user_id, status: this.props.status, id: this.props.id, role: role };
  }

  getFatQuery() {
    return Relay.QL`
      fragment on UpdateTeamUserPayload {
        team_user
      }
    `;
  }

  getConfigs() {
    return [{
      type: 'REQUIRED_CHILDREN',
      children: [Relay.QL`
        fragment on UpdateTeamUserPayload {
          team_user {
            id, team_id, user_id, status, role
          }
        }`,
      ],
    }];
  }
}

export default UpdateTeamUserMutation;
<|endoftext|>


<commit_before>if(process.env.NEW_RELIC_LICENSE_KEY) require('newrelic')

var express  = require('express')
var session  = require('express-session')
var passport = require('passport')
var bparser  = require('body-parser')
var raven    = require('raven')

// global variables (and list of all used environment variables)
APP_VERSION       = require('./package').version
APP_STARTED       = new Date().toISOString()
APP_PORT          = process.env.PORT || 3000
APP_COOKIE_SECRET = process.env.COOKIE_SECRET
APP_SENTRY        = process.env.SENTRY_DSN

GOOGLE_ID = process.env.GOOGLE_ID
GOOGLE_SECRET = process.env.GOOGLE_SECRET

FACEBOOK_ID = process.env.FACEBOOK_ID
FACEBOOK_SECRET = process.env.FACEBOOK_SECRET

TWITTER_KEY = process.env.TWITTER_KEY
TWITTER_SECRET = process.env.TWITTER_SECRET

TAAT_ENTRYPOINT = process.env.TAAT_ENTRYPOINT
TAAT_ISSUER = process.env.TAAT_ISSUER
TAAT_CERT = process.env.TAAT_CERT
TAAT_PRIVATECERT = process.env.TAAT_PRIVATECERT

// passport (de)serialize
passport.serializeUser(function(user, done) {
    done(null, user)
})

passport.deserializeUser(function(user, done) {
    done(null, user)
})

var app = express()

// logs to getsentry.com
if(APP_SENTRY) app.use(raven.middleware.express(APP_SENTRY))

// Use cookies
app.use(session({ secret: APP_COOKIE_SECRET, key: 'sid', maxAge: 360 * 5 }))

// Initialize Passport
app.use(passport.initialize())

// parse POST requests
app.use(bparser.json())
app.use(bparser.urlencoded({extended: true}))

// routes mapping
.use('/user', require('./routes/user'))

// provider mapping (only if configured)
if(GOOGLE_ID && GOOGLE_SECRET) app.use('/google', require('./routes/google'))
if(FACEBOOK_ID && FACEBOOK_SECRET) app.use('/facebook', require('./routes/facebook'))
if(TWITTER_KEY && TWITTER_SECRET) app.use('/twitter', require('./routes/twitter'))
if(TAAT_ENTRYPOINT && TAAT_CERT && TAAT_PRIVATECERT) app.use('/taat', require('./routes/taat'))

// show error
app.use(function(err, req, res, next) {
        var status = parseInt(err.status) || 500

        res.status(status)
        res.send({
            error: err.message,
            version: APP_VERSION,
            started: APP_STARTED
        })

        if(err.status !== 404) console.log(err)
    })

// start server
app.listen(APP_PORT)

console.log(new Date().toString() + ' started listening port ' + APP_PORT)
<commit_msg>Last try<commit_after>if(process.env.NEW_RELIC_LICENSE_KEY) require('newrelic')

var express  = require('express')
var session  = require('express-session')
var passport = require('passport')
var bparser  = require('body-parser')
var raven    = require('raven')

// global variables (and list of all used environment variables)
APP_VERSION       = require('./package').version
APP_STARTED       = new Date().toISOString()
APP_PORT          = process.env.PORT || 3000
APP_COOKIE_SECRET = process.env.COOKIE_SECRET
APP_SENTRY        = process.env.SENTRY_DSN

GOOGLE_ID = process.env.GOOGLE_ID
GOOGLE_SECRET = process.env.GOOGLE_SECRET

FACEBOOK_ID = process.env.FACEBOOK_ID
FACEBOOK_SECRET = process.env.FACEBOOK_SECRET

TWITTER_KEY = process.env.TWITTER_KEY
TWITTER_SECRET = process.env.TWITTER_SECRET

TAAT_ENTRYPOINT = process.env.TAAT_ENTRYPOINT
TAAT_ISSUER = process.env.TAAT_ISSUER
TAAT_CERT = process.env.TAAT_CERT
TAAT_PRIVATECERT = process.env.TAAT_PRIVATECERT

// passport (de)serialize
passport.serializeUser(function(user, done) {
    done(null, user)
})

passport.deserializeUser(function(user, done) {
    done(null, user)
})

var app = express()

// logs to getsentry.com
if(APP_SENTRY) app.use(raven.middleware.express(APP_SENTRY))

// Use cookies
app.use(session({
    secret: APP_COOKIE_SECRET,
    key: 'sid',
    maxAge: 360 * 5,
    cookie: {
        secure: false
    }
}))

// Initialize Passport
app.use(passport.initialize())

// parse POST requests
app.use(bparser.json())
app.use(bparser.urlencoded({extended: true}))

// routes mapping
.use('/user', require('./routes/user'))

// provider mapping (only if configured)
if(GOOGLE_ID && GOOGLE_SECRET) app.use('/google', require('./routes/google'))
if(FACEBOOK_ID && FACEBOOK_SECRET) app.use('/facebook', require('./routes/facebook'))
if(TWITTER_KEY && TWITTER_SECRET) app.use('/twitter', require('./routes/twitter'))
if(TAAT_ENTRYPOINT && TAAT_CERT && TAAT_PRIVATECERT) app.use('/taat', require('./routes/taat'))

// show error
app.use(function(err, req, res, next) {
        var status = parseInt(err.status) || 500

        res.status(status)
        res.send({
            error: err.message,
            version: APP_VERSION,
            started: APP_STARTED
        })

        if(err.status !== 404) console.log(err)
    })

// start server
app.listen(APP_PORT)

console.log(new Date().toString() + ' started listening port ' + APP_PORT)
<|endoftext|>


<commit_before>/**
 * !!! This file can be found as worker.js in the quick_server folder !!!
 *
 * Provides worker oriented networking interface.
 *
 * Created by krause on 2016-06-22.
 */
"use strict";

window.quick_server = window.quick_server || {}; // init namespace

window.quick_server.Worker = function() {
  var that = this;
  var timeStart = 500;
  var timeCap = 1000*60; /* has to be below 2min so the server doesn't remove the result */
  var timeMinInc = 10;
  var timeMulInc = 1.1;

  var status = function(req) {};
  this.status = function(_) {
    if(!arguments.length) return status;
    status = _;
  };

  var active = true;
  this.active = function(_) {
    if(!arguments.length) return active;
    active = _;
  };

  var sendRequest = function(url, obj, cb) {
    if(d3) { // d3 compatibility
      d3.json(url).header("Content-Type", "application/json").post(obj, function(err, data) {
        cb(err, data);
      });
      return;
    }
    throw { "err": "unimplemented", };
  };
  this.sendRequest = function(_) {
    if(!arguments.length) return sendRequest;
    sendRequest = _;
  };

  var preDelay = 500;
  this.preDelay = function(_) {
    if(!arguments.length) return preDelay;
    preDelay = _;
  };

  var req = 0;
  function changeStatus(inc, error) {
    if(req < 0) return;
    if(error) {
      req = -1;
    } else if(inc) {
      req += 1;
    } else {
      req -= 1;
    }
    status(req);
  }

  var starts = {};
  var tokens = {};
  var urls = {};
  function postTask(ref) {
    setTimeout(function() {
      if(!starts[ref]) return;
      var s = starts[ref];
      var url = s["url"];
      var cb = s["cb"];
      starts[ref] = null;
      changeStatus(true, false);
      var obj = JSON.stringify({
        "action": "start",
        "payload": s["payload"],
      });
      sendRequest(url, obj, function(err, data) {
        if(err) {
          console.warn("Failed to start " + ref);
          changeStatus(false, true);
          return console.warn(err);
        }
        cancel(ref, function(err) {
          if(err) {
            console.warn("Failed to cancel " + ref);
            changeStatus(false, true);
            return console.warn(err);
          }
        });
        if(data["done"]) {
          execute(cb, data["result"]);
        } else {
          var token = +data["token"];
          urls[ref] = url;
          tokens[ref] = token;
          monitor(ref, token, cb, timeStart);
        }
      });
    }, preDelay);
  }

  function monitor(ref, token, cb, delay) {
    if(tokens[ref] !== token) {
      changeStatus(false, false);
      return;
    }
    var url = urls[ref];
    var obj = JSON.stringify({
      "action": "get",
      "token": token,
    });
    sendRequest(url, obj, function(err, data) {
      if(err) {
        console.warn("Error while retrieving " + ref + " token: " + token);
        changeStatus(false, true);
        return console.warn(err);
      }
      var cur_token = +data["token"];
      if(cur_token !== tokens[ref]) {
        // late response
        changeStatus(false, false);
        return;
      }
      if(cur_token !== token) {
        // wrong response
        console.warn("Error while retrieving " + ref);
        changeStatus(false, true);
        return console.warn({ "err": "token mismatch: " + cur_token + " instead of " + token, });
      }
      if(data["done"]) {
        tokens[ref] = -1;
        urls[ref] = null;
        execute(cb, data["result"]);
      } else if(data["continue"]) {
        setTimeout(function() {
          var newDelay = Math.min(Math.max(delay * timeMulInc, delay + timeMinInc), timeCap);
          monitor(ref, token, cb, newDelay);
        }, delay);
      } else {
        changeStatus(false, false);
      }
    });
  }

  function cancel(ref, cb) {
    if(!(ref in tokens && tokens[ref] >= 0)) return;
    var token = tokens[ref];
    var url = urls[ref];
    var obj = JSON.stringify({
      "action": "stop",
      "token": token,
    });
    tokens[ref] = -1;
    urls[ref] = null;
    sendRequest(url, obj, function(err, data) {
      if(err) {
        return cb(err);
      }
      return cb(+data["token"] !== token && { "err": "token mismatch: " + data["token"] + " instead of " + token, });
    });
  }

  function execute(cb, data) {
    var err = true;
    try {
      cb(data);
      err = false;
    } finally {
      if(err) {
        changeStatus(false, true);
      } else {
        changeStatus(false, false);
      }
    }
  }

  this.post = function(ref, url, payload, cb) {
    if(!active) return;
    starts[ref] = {
      "url": url,
      "cb": cb,
      "payload": payload,
    };
    postTask(ref);
  };
  this.cancel = function(ref) {
    cancel(ref, function(err) {
      changeStatus(false, !!err);
      if(err) {
        console.warn("Failed to cancel " + ref);
        return console.warn(err);
      }
    });
  };

  window.addEventListener("beforeunload", function() {
    Object.keys(tokens).forEach(function(ref) {
      // we probably won't read the results but the server still cancels properly
      that.cancel(ref);
    });
  });
} // quick_server.Worker
<commit_msg>even more frequent<commit_after>/**
 * !!! This file can be found as worker.js in the quick_server folder !!!
 *
 * Provides worker oriented networking interface.
 *
 * Created by krause on 2016-06-22.
 */
"use strict";

window.quick_server = window.quick_server || {}; // init namespace

window.quick_server.Worker = function() {
  var that = this;
  var timeStart = 500;
  var timeCap = 1000*60; /* has to be below 2min so the server doesn't remove the result */
  var timeMinInc = 10;
  var timeMulInc = 1.01;

  var status = function(req) {};
  this.status = function(_) {
    if(!arguments.length) return status;
    status = _;
  };

  var active = true;
  this.active = function(_) {
    if(!arguments.length) return active;
    active = _;
  };

  var sendRequest = function(url, obj, cb) {
    if(d3) { // d3 compatibility
      d3.json(url).header("Content-Type", "application/json").post(obj, function(err, data) {
        cb(err, data);
      });
      return;
    }
    throw { "err": "unimplemented", };
  };
  this.sendRequest = function(_) {
    if(!arguments.length) return sendRequest;
    sendRequest = _;
  };

  var preDelay = 500;
  this.preDelay = function(_) {
    if(!arguments.length) return preDelay;
    preDelay = _;
  };

  var req = 0;
  function changeStatus(inc, error) {
    if(req < 0) return;
    if(error) {
      req = -1;
    } else if(inc) {
      req += 1;
    } else {
      req -= 1;
    }
    status(req);
  }

  var starts = {};
  var tokens = {};
  var urls = {};
  function postTask(ref) {
    setTimeout(function() {
      if(!starts[ref]) return;
      var s = starts[ref];
      var url = s["url"];
      var cb = s["cb"];
      starts[ref] = null;
      changeStatus(true, false);
      var obj = JSON.stringify({
        "action": "start",
        "payload": s["payload"],
      });
      sendRequest(url, obj, function(err, data) {
        if(err) {
          console.warn("Failed to start " + ref);
          changeStatus(false, true);
          return console.warn(err);
        }
        cancel(ref, function(err) {
          if(err) {
            console.warn("Failed to cancel " + ref);
            changeStatus(false, true);
            return console.warn(err);
          }
        });
        if(data["done"]) {
          execute(cb, data["result"]);
        } else {
          var token = +data["token"];
          urls[ref] = url;
          tokens[ref] = token;
          monitor(ref, token, cb, timeStart);
        }
      });
    }, preDelay);
  }

  function monitor(ref, token, cb, delay) {
    if(tokens[ref] !== token) {
      changeStatus(false, false);
      return;
    }
    var url = urls[ref];
    var obj = JSON.stringify({
      "action": "get",
      "token": token,
    });
    sendRequest(url, obj, function(err, data) {
      if(err) {
        console.warn("Error while retrieving " + ref + " token: " + token);
        changeStatus(false, true);
        return console.warn(err);
      }
      var cur_token = +data["token"];
      if(cur_token !== tokens[ref]) {
        // late response
        changeStatus(false, false);
        return;
      }
      if(cur_token !== token) {
        // wrong response
        console.warn("Error while retrieving " + ref);
        changeStatus(false, true);
        return console.warn({ "err": "token mismatch: " + cur_token + " instead of " + token, });
      }
      if(data["done"]) {
        tokens[ref] = -1;
        urls[ref] = null;
        execute(cb, data["result"]);
      } else if(data["continue"]) {
        setTimeout(function() {
          var newDelay = Math.min(Math.max(delay * timeMulInc, delay + timeMinInc), timeCap);
          monitor(ref, token, cb, newDelay);
        }, delay);
      } else {
        changeStatus(false, false);
      }
    });
  }

  function cancel(ref, cb) {
    if(!(ref in tokens && tokens[ref] >= 0)) return;
    var token = tokens[ref];
    var url = urls[ref];
    var obj = JSON.stringify({
      "action": "stop",
      "token": token,
    });
    tokens[ref] = -1;
    urls[ref] = null;
    sendRequest(url, obj, function(err, data) {
      if(err) {
        return cb(err);
      }
      return cb(+data["token"] !== token && { "err": "token mismatch: " + data["token"] + " instead of " + token, });
    });
  }

  function execute(cb, data) {
    var err = true;
    try {
      cb(data);
      err = false;
    } finally {
      if(err) {
        changeStatus(false, true);
      } else {
        changeStatus(false, false);
      }
    }
  }

  this.post = function(ref, url, payload, cb) {
    if(!active) return;
    starts[ref] = {
      "url": url,
      "cb": cb,
      "payload": payload,
    };
    postTask(ref);
  };
  this.cancel = function(ref) {
    cancel(ref, function(err) {
      changeStatus(false, !!err);
      if(err) {
        console.warn("Failed to cancel " + ref);
        return console.warn(err);
      }
    });
  };

  window.addEventListener("beforeunload", function() {
    Object.keys(tokens).forEach(function(ref) {
      // we probably won't read the results but the server still cancels properly
      that.cancel(ref);
    });
  });
} // quick_server.Worker
<|endoftext|>


<commit_before>var assign = require("object-assign");
var createTexture = require("gl-texture2d");
var BezierEasing = require("bezier-easing");
var SegmentTimeline = require("../SegmentTimeline");

function SegmentTransition (renderChannel, data, segmentFrom, segmentTo) {
  SegmentTimeline.call(this, renderChannel, data);
  this.segmentFrom = segmentFrom;
  this.segmentTo = segmentTo;
}

SegmentTransition.prototype = assign({}, SegmentTimeline.prototype, {
  ready: function (ctx) {
    return this.segmentFrom.ready(ctx) &&
           this.segmentTo.ready(ctx) &&
           (!this.data.name || ctx.transitions.has(this.data.name));
  },

  enter: function (ctx) {
    var transitionNext = this.data;
    var transition = ctx.transitions.getOrFade(transitionNext.name);
    var gl = ctx.getChannelContext(this.channel);
    this.gl = gl;
    this.from = ctx.getChannel(this.segmentFrom.channel);
    this.to = ctx.getChannel(this.segmentTo.channel);
    this.fromTexture = createTexture(gl, this.from);
    this.toTexture = createTexture(gl, this.to);
    // ^ FIXME need to verify that channel has been rendered with latest frame?
    this.uniforms = assign({}, transition.uniforms, transitionNext.uniforms || {});
    this.duration = transitionNext.duration || 1000;
    this.easing = BezierEasing.apply(null, transitionNext.easing || [0, 0, 1, 1]);
    this.t = transition.t;
    return [ "transition", this.data, this.segmentFrom.data, this.segmentTo.data ];
  },

  resize: function () {
    if (this.fromTexture) this.fromTexture.dispose();
    if (this.toTexture) this.toTexture.dispose();
    this.fromTexture = createTexture(this.gl, this.from);
    this.toTexture = createTexture(this.gl, this.to);
    this.render(this._p||0);
  },

  leave: function () {
    if (this.fromTexture) this.fromTexture.dispose();
    if (this.toTexture) this.toTexture.dispose();
    this.fromTexture = null;
    this.toTexture = null;
    return [ "transitionEnd", this.data, this.segmentFrom.data, this.segmentTo.data ];
  },

  render: function (p) {
    this._p = p;
    this.fromTexture.setPixels(this.from);
    this.toTexture.setPixels(this.to);
    this.t.render(
      this.easing(p),
      this.fromTexture,
      this.toTexture,
      this.uniforms);
  }
});

module.exports = SegmentTransition;
<commit_msg>more efficient SegmentGlslTransition#resize<commit_after>var assign = require("object-assign");
var createTexture = require("gl-texture2d");
var BezierEasing = require("bezier-easing");
var SegmentTimeline = require("../SegmentTimeline");

function SegmentTransition (renderChannel, data, segmentFrom, segmentTo) {
  SegmentTimeline.call(this, renderChannel, data);
  this.segmentFrom = segmentFrom;
  this.segmentTo = segmentTo;
}

SegmentTransition.prototype = assign({}, SegmentTimeline.prototype, {
  ready: function (ctx) {
    return this.segmentFrom.ready(ctx) &&
           this.segmentTo.ready(ctx) &&
           (!this.data.name || ctx.transitions.has(this.data.name));
  },

  enter: function (ctx) {
    var transitionNext = this.data;
    var transition = ctx.transitions.getOrFade(transitionNext.name);
    var gl = ctx.getChannelContext(this.channel);
    this.gl = gl;
    this.from = ctx.getChannel(this.segmentFrom.channel);
    this.to = ctx.getChannel(this.segmentTo.channel);
    this.fromTexture = createTexture(gl, this.from);
    this.toTexture = createTexture(gl, this.to);
    // ^ FIXME need to verify that channel has been rendered with latest frame?
    this.uniforms = assign({}, transition.uniforms, transitionNext.uniforms || {});
    this.duration = transitionNext.duration || 1000;
    this.easing = BezierEasing.apply(null, transitionNext.easing || [0, 0, 1, 1]);
    this.t = transition.t;
    return [ "transition", this.data, this.segmentFrom.data, this.segmentTo.data ];
  },

  resize: function () {
    if (this.fromTexture) this.fromTexture.dispose();
    if (this.toTexture) this.toTexture.dispose();
    this.fromTexture = createTexture(this.gl, this.from);
    this.toTexture = createTexture(this.gl, this.to);
    this.t.render(
      this.easing(this._p||0),
      this.fromTexture,
      this.toTexture,
      this.uniforms);
  },

  leave: function () {
    if (this.fromTexture) this.fromTexture.dispose();
    if (this.toTexture) this.toTexture.dispose();
    this.fromTexture = null;
    this.toTexture = null;
    return [ "transitionEnd", this.data, this.segmentFrom.data, this.segmentTo.data ];
  },

  render: function (p) {
    this._p = p;
    this.fromTexture.setPixels(this.from);
    this.toTexture.setPixels(this.to);
    this.t.render(
      this.easing(p),
      this.fromTexture,
      this.toTexture,
      this.uniforms);
  }
});

module.exports = SegmentTransition;
<|endoftext|>


<commit_before>function resetFilters()
{
    document.getElementById("pkgFilter").value="";
    document.getElementById("itemFilter").value="";
    applyFilters();
}

function applyFilters()
{
    var pkg=document.getElementById("pkgFilter").value.toLowerCase();
    var item=document.getElementById("itemFilter").value.toLowerCase();
    var childs=document.getElementById("pkgNav").childNodes;
    for (i = 0; i < childs.length; i++)
        {
            var child=childs[i];
            var id=child.id;
            if(id!=null && id.indexOf("__")==0)
                {
                    if(id.toLowerCase().indexOf(pkg)==-1)
                        child.style.display='none';
                    else
                        {
                            var anyChild=false;
                            var items=child.childNodes;
                            for (j = 0; j < items.length; j++)
                                {
                                    var it=items[j];
                                    var iid=it.id;
                                    if(iid!=null && iid.indexOf(id+"__")==0)
                                        {
                                            iid=iid.substring(id.length);
                                            if(iid.toLowerCase().indexOf(item)==-1)
                                                it.style.display='none';
                                            else
                                                {
                                                    anyChild=true;
                                                    it.style.display='block';
                                                }
                                            }
                                        }
                                        if(anyChild)
                                            child.style.display='block';
                                        else
                                            child.style.display='none';
                                    }
                                }
                            }
                        }

                        <commit_msg>working package / item javascript filter<commit_after>function resetFilters()
{
    document.getElementById("pkgFilter").value="";
    document.getElementById("itemFilter").value="";
    applyFilters();
}

function applyFilters()
{
    var pkg=document.getElementById("pkgFilter").value.toLowerCase();
    var item=document.getElementById("itemFilter").value.toLowerCase();
    var childs=document.getElementById("pkgNav").childNodes;
    for (i = 0; i < childs.length; i++){
        var child=childs[i];
        var id=child.id;
        if(id!=null && id.indexOf("__")==0){
            if(id.toLowerCase().indexOf(pkg)==-1){
                child.style.display='none';
                }
            else{
                var anyChild=false;
                var items=child.childNodes;
                for (j = 0; j < items.length; j++){}
                var it=items[j];
                var iid=it.id;
                if(iid!=null && iid.indexOf(id+"__")==0){
                    iid=iid.substring(id.length);
                    if(iid.toLowerCase().indexOf(item)==-1)
                        it.style.display='none';
                    else{
                        anyChild=true;
                        it.style.display='block';
                    }
                }
            }
            if(anyChild)
                child.style.display='block';
            else
                child.style.display='none';
        }
    }
}

<|endoftext|>


<commit_before>var territoryBro = (function () {
  var MAX_ZOOM = 18;

  function initTerritoryMap(elementId, areaWkt) {
    var territoryArea = new ol.format.WKT().readFeature(areaWkt);
    territoryArea.getGeometry().transform('EPSG:4326', 'EPSG:3857');
    var territorySource = new ol.source.Vector({
      features: [territoryArea]
    });
    var territoryStyles = [
      new ol.style.Style({
        stroke: new ol.style.Stroke({
          color: 'rgba(255, 0, 0, 1.0)',
          width: 3
        }),
        fill: new ol.style.Fill({
          color: 'rgba(255, 0, 0, 0.1)'
        })
      })
    ];
    var territoryLayer = new ol.layer.Vector({
      source: territorySource,
      style: territoryStyles
    });

    var streetsLayer = new ol.layer.Tile({
      source: new ol.source.OSM()
    });

    var map = new ol.Map({
      target: elementId,
      layers: [streetsLayer, territoryLayer],
      view: new ol.View({
        center: ol.proj.fromLonLat([0.0, 0.0]),
        zoom: 1
      })
    });
    var view = map.getView();
    view.fit(territorySource.getExtent(), map.getSize());
    view.setZoom(Math.min(MAX_ZOOM, view.getZoom()));
  }

  return {
    initTerritoryMap: initTerritoryMap
  };
})();
<commit_msg>Render map at a higher dpi<commit_after>var territoryBro = (function () {
  function initTerritoryMap(elementId, areaWkt) {
    var territoryArea = new ol.format.WKT().readFeature(areaWkt);
    territoryArea.getGeometry().transform('EPSG:4326', 'EPSG:3857');
    var territorySource = new ol.source.Vector({
      features: [territoryArea]
    });
    var territoryStyles = [
      new ol.style.Style({
        stroke: new ol.style.Stroke({
          color: 'rgba(255, 0, 0, 1.0)',
          width: 3
        }),
        fill: new ol.style.Fill({
          color: 'rgba(255, 0, 0, 0.1)'
        })
      })
    ];
    var territoryLayer = new ol.layer.Vector({
      source: territorySource,
      style: territoryStyles
    });

    var streetsLayer = new ol.layer.Tile({
      source: new ol.source.OSM()
    });

    var map = new ol.Map({
      target: elementId,
      pixelRatio: 2, // render at high DPI for printing
      layers: [streetsLayer, territoryLayer],
      view: new ol.View({
        center: ol.proj.fromLonLat([0.0, 0.0]),
        zoom: 1,
        // show more surrounding area for small territories
        maxZoom: 18
      })
    });
    var view = map.getView();
    // render at a higher zoom level for high DPI
    // XXX: resets when window is resize or map.updateSize() is called
    map.setSize(map.getSize().map(function (x) { return x*2; }));
    // zoom and center on the territory
    view.fit(territorySource.getExtent(), map.getSize());
  }

  return {
    initTerritoryMap: initTerritoryMap
  };
})();
<|endoftext|>


<commit_before>oscar.Gui.LinkedLists = new oscar.BaseClass(oscar.Gui,{
	displayClass:"oscarGuiLinkedLists",
	availableText:"",
	selectedText:"",
	EVENT_TYPES:["sourceReceived","destinationReceived"],
	initialize:function(options) {
		this.EVENT_TYPES = this.EVENT_TYPES.concat(oscar.Gui.prototype.EVENT_TYPES);
		oscar.Gui.prototype.initialize.apply(this,[options]);
		this.connectionClass=OpenLayers.Util.createUniqueID("connection");
		this.events.register("sourceReceived", this, this.sourceReceived);
		this.events.register("destinationReceived", this, this.destinationReceived);

	},
	filter:function() {
		return true;
	},
	draw:function() {
		var sourceId = OpenLayers.Util.createUniqueID("source");
		var destinationId = OpenLayers.Util.createUniqueID("destination");

		oscar.Gui.prototype.draw.apply(this);
		var $this = $$(this.div);
		this.sourceDiv = $$("

");
		this.sourceDiv.addClass("sourceDiv");
		this.sourceTextDiv = $$("

").html(oscar.i18n(this.availableText));
		this.sourceTextDiv.addClass("sourceText");
		this.navTextDiv = $$("

").html(' ');
		this.navTextDiv.addClass("navText");
		this.selectedTextDiv = $$("

").html(oscar.i18n(this.selectedText));
		this.selectedTextDiv.addClass("selectedText");

		this.sourceList = $$("

");
		this.sourceList.addClass(this.connectionClass);
		this.sourceList.attr("id",sourceId);
		this.sourceDiv.append(this.sourceList);

		this.buttonsDiv = $$("

");
		this.buttonsDiv.addClass("buttonsDiv");

		this.destinationDiv = $$("

");
		this.destinationDiv.addClass("selectedDiv");

		this.destinationList = $$("

");
		this.destinationList.attr("id",destinationId);
		this.destinationList.addClass(this.connectionClass);

		this.destinationDiv.append(this.destinationList);

		$this.append(this.sourceTextDiv);
		$this.append(this.navTextDiv);
		$this.append(this.selectedTextDiv);
		$this.append("
");
		$this.append(this.sourceDiv);
		$this.append(this.sourceDiv);
		$this.append(this.sourceDiv);
		$this.append(this.buttonsDiv);
		$this.append(this.destinationDiv);

		$this.addClass(this.displayClass);
		this.buildButtons();
		$this.append("
");
		$this.disableSelection();

	},
	sourceReceived:function(li) {
		this.sourceList.append(li);
		if(this.sourceDecorator) {
			this.sourceDecorator(li);
		}
		this.filter(li);
	},
	destinationReceived:function(li){
		//check to see if this already exists
		var alreadyExists=false;
		this.destinationList.children().each(function() {
			var $this = $$(this);
			if(li.data("id") == $this.data("id")) {
				alreadyExists = true;
			}
		});
		if(!alreadyExists) {
			this.destinationList.append(li);
		}
		if(this.destinationDecorator) {
			this.destinationDecorator(li);
		}
		this.filter(li);
	},

	buildButtons:function() {
		var scope = this;
		this.toTheRight = $$("<button onclick='return false;'></button>").html(oscar.i18n("MoveAllToTheRight"));

		this.toTheRight.button({
			icons: {
				primary:"ui-icon-seek-next"
			},
			text:false
		});
		this.toTheRight.click(function() {
			var available = scope.sourceList.children();
			available.each(function() {
				scope.events.triggerEvent("destinationReceived",$$(this));
			});
			scope.destinationList.sortable('refresh');
			return false;
		});
		this.toTheRight.css("float","center");
		this.toTheLeft = $$("<button onclick='return false;'></button>").html(oscar.i18n("MoveAllToTheLeft"));
		this.toTheLeft.button({
			icons: {
				primary:"ui-icon-seek-prev"
			},
			text:false
		});
		this.toTheLeft.click(function() {
			var available = scope.destinationList.children();
			available.each(function() {
				scope.events.triggerEvent("sourceReceived",$$(this));
			});
			return false;
		});
		this.toTheLeft.css("float","center");
		this.buttonsDiv.append(this.toTheRight);
		this.buttonsDiv.append(this.toTheLeft);
	},
	addToSourceList:function(listItem) {
		var li = $$("

").html(listItem.text);
		li.attr("title",listItem.text);
		var data = listItem.getData();

		for(var p in data) {
			li.data(p,data[p]);
		}

		li.addClass("ui-state-default");
		if(!this.isSelected(li)) {
			this.events.triggerEvent("sourceReceived",li);
		}
		this.sortable();
		return li;
	},
	addToDestinationList:function(listItem) {
		var li = $$("

").html(listItem.text);
		li.attr("title",listItem.text);
		var data = listItem.getData();

		for(var p in data) {
			li.data(p,data[p]);
		}
		li.addClass("ui-state-default");
		this.events.triggerEvent("destinationReceived",li);
		this.sortable();

		return li;
	},
	sortable:function() {
		var scope=this;
		$$(this.sourceList).sortable({
		connectWith:"."+this.connectionClass,
		dropOnEmpty:true,
		cursor: "move",
		receive:function(event,ui) {
			scope.events.triggerEvent("sourceReceived",ui.item);
		}
	}).disableSelection();

	$$(this.destinationList).sortable({
		connectWith:"."+this.connectionClass,
		dropOnEmpty: true,
		cursor: "move",
		receive:function(event,ui) {
			scope.events.triggerEvent("destinationReceived",ui.item);
		}
	}).disableSelection();
	},
	getAvailable:function() {
		return this.sourceList.children();
	},
	getSelected:function() {
		return this.destinationList.children();
	},
	isSelected:function(li) {
		var isFound = false;
		var scope = this;
		this.destinationList.children().each(function() {
			if(scope.compare(li,$$(this))) {
				isFound = true;
			}
		});
		return isFound;
	},
	clearSourceList:function() {
		this.sourceList.empty();
	},
	compare:function(a,b) {
		if(a.html() == b.html())
			return true;
		else
			return false;
	},
	showHelp:function(str) {
		if(!this.helpDiv) {
			this.helpDiv = $$("

");
			this.helpDiv.addClass("help2");
			$$(this.div).after(this.helpDiv);
		}
		this.helpDiv.html("");
		this.helpDiv.html(oscar.i18n(str));

	},
	CLASS_NAME:"oscar.Gui.LinkedLists"

});
oscar.ListItem = new oscar.BaseClass({
	text:"",
	data:{},
	initialize:function(text,data) {
		this.text=text;
		if(data) {
			this.data = data;
		}
	},
	setData:function(data) {
		this.data = data;
	},
	getData:function(data) {
		return this.data;
	},
	CLASS_NAME:"oscar.ListItem"
});<commit_msg>SFS-2591<commit_after>oscar.Gui.LinkedLists = new oscar.BaseClass(oscar.Gui,{
	displayClass:"oscarGuiLinkedLists",
	availableText:"",
	selectedText:"",
	EVENT_TYPES:["sourceReceived","destinationReceived"],
	initialize:function(options) {
		this.EVENT_TYPES = this.EVENT_TYPES.concat(oscar.Gui.prototype.EVENT_TYPES);
		oscar.Gui.prototype.initialize.apply(this,[options]);
		this.connectionClass=OpenLayers.Util.createUniqueID("connection");
		this.events.register("sourceReceived", this, this.sourceReceived);
		this.events.register("destinationReceived", this, this.destinationReceived);

	},
	filter:function() {
		return true;
	},
	draw:function() {
		var sourceId = OpenLayers.Util.createUniqueID("source");
		var destinationId = OpenLayers.Util.createUniqueID("destination");

		oscar.Gui.prototype.draw.apply(this);
		var $this = $$(this.div);
		this.sourceDiv = $$("

");
		this.sourceDiv.addClass("sourceDiv");
		this.sourceTextDiv = $$("

").html(oscar.i18n(this.availableText));
		this.sourceTextDiv.addClass("sourceText");
		this.navTextDiv = $$("

").html(' ');
		this.navTextDiv.addClass("navText");
		this.selectedTextDiv = $$("

").html(oscar.i18n(this.selectedText));
		this.selectedTextDiv.addClass("selectedText");

		this.sourceList = $$("

");
		this.sourceList.addClass(this.connectionClass);
		this.sourceList.attr("id",sourceId);
		this.sourceDiv.append(this.sourceList);

		this.buttonsDiv = $$("

");
		this.buttonsDiv.addClass("buttonsDiv");

		this.destinationDiv = $$("

");
		this.destinationDiv.addClass("selectedDiv");

		this.destinationList = $$("

");
		this.destinationList.attr("id",destinationId);
		this.destinationList.addClass(this.connectionClass);

		this.destinationDiv.append(this.destinationList);

		$this.append(this.sourceTextDiv);
		$this.append(this.navTextDiv);
		$this.append(this.selectedTextDiv);
		$this.append("
");
		$this.append(this.sourceDiv);
		$this.append(this.sourceDiv);
		$this.append(this.sourceDiv);
		$this.append(this.buttonsDiv);
		$this.append(this.destinationDiv);

		$this.addClass(this.displayClass);
		this.buildButtons();
		$this.append("
");
		$this.disableSelection();

	},
	sourceReceived:function(li) {
		this.sourceList.append(li);
		if(this.sourceDecorator) {
			this.sourceDecorator(li);
		}
		this.filter(li);
	},
	destinationReceived:function(li){
		//check to see if this already exists
		var scope = this;
		var alreadyExists=false;
		this.destinationList.children().each(function() {
			var $this = $$(this);
			if(scope.compare(li,$$(this))) {
				alreadyExists = true;
			}
		});
		if(!alreadyExists) {
			this.destinationList.append(li);
		}
		if(this.destinationDecorator) {
			this.destinationDecorator(li);
		}
	},

	buildButtons:function() {
		var scope = this;
		this.toTheRight = $$("<button onclick='return false;'></button>").html(oscar.i18n("MoveAllToTheRight"));

		this.toTheRight.button({
			icons: {
				primary:"ui-icon-seek-next"
			},
			text:false
		});
		this.toTheRight.click(function() {
			var available = scope.sourceList.children();
			available.each(function() {
				scope.events.triggerEvent("destinationReceived",$$(this));
			});
			scope.destinationList.sortable('refresh');
			return false;
		});
		this.toTheRight.css("float","center");
		this.toTheLeft = $$("<button onclick='return false;'></button>").html(oscar.i18n("MoveAllToTheLeft"));
		this.toTheLeft.button({
			icons: {
				primary:"ui-icon-seek-prev"
			},
			text:false
		});
		this.toTheLeft.click(function() {
			var available = scope.destinationList.children();
			available.each(function() {
				scope.events.triggerEvent("sourceReceived",$$(this));
			});
			return false;
		});
		this.toTheLeft.css("float","center");
		this.buttonsDiv.append(this.toTheRight);
		this.buttonsDiv.append(this.toTheLeft);
	},
	addToSourceList:function(listItem) {
		var li = $$("

").html(listItem.text);
		li.attr("title",listItem.text);
		var data = listItem.getData();

		for(var p in data) {
			li.data(p,data[p]);
		}

		li.addClass("ui-state-default");
		if(!this.isSelected(li)) {
			this.events.triggerEvent("sourceReceived",li);
		}
		this.sortable();
		return li;
	},
	addToDestinationList:function(listItem) {
		var li = $$("

").html(listItem.text);
		li.attr("title",listItem.text);
		var data = listItem.getData();

		for(var p in data) {
			li.data(p,data[p]);
		}
		li.addClass("ui-state-default");
		this.events.triggerEvent("destinationReceived",li);
		this.sortable();

		return li;
	},
	sortable:function() {
		var scope=this;
		$$(this.sourceList).sortable({
		connectWith:"."+this.connectionClass,
		dropOnEmpty:true,
		cursor: "move",
		receive:function(event,ui) {
			scope.events.triggerEvent("sourceReceived",ui.item);
		}
	}).disableSelection();

	$$(this.destinationList).sortable({
		connectWith:"."+this.connectionClass,
		dropOnEmpty: true,
		cursor: "move",
		receive:function(event,ui) {
			scope.events.triggerEvent("destinationReceived",ui.item);
		}
	}).disableSelection();
	},
	getAvailable:function() {
		return this.sourceList.children();
	},
	getSelected:function() {
		return this.destinationList.children();
	},
	isSelected:function(li) {
		var isFound = false;
		var scope = this;
		this.destinationList.children().each(function() {
			if(scope.compare(li,$$(this))) {
				isFound = true;
			}
		});
		return isFound;
	},
	clearSourceList:function() {
		this.sourceList.empty();
	},
	compare:function(a,b) {
		if(a.html() == b.html())
			return true;
		else
			return false;
	},
	showHelp:function(str) {
		if(!this.helpDiv) {
			this.helpDiv = $$("

");
			this.helpDiv.addClass("help2");
			$$(this.div).after(this.helpDiv);
		}
		this.helpDiv.html("");
		this.helpDiv.html(oscar.i18n(str));

	},
	CLASS_NAME:"oscar.Gui.LinkedLists"

});
oscar.ListItem = new oscar.BaseClass({
	text:"",
	data:{},
	initialize:function(text,data) {
		this.text=text;
		if(data) {
			this.data = data;
		}
	},
	setData:function(data) {
		this.data = data;
	},
	getData:function(data) {
		return this.data;
	},
	CLASS_NAME:"oscar.ListItem"
});<|endoftext|>


<commit_before>/* ServiceAssistant
* This assistant is called before anything within the service.
* It sets up the keystore decipher.
*/
/*jslint node: true */
/*global log, debug, fs, crypto, Future, KeyStore */

var keystoreFolder = "/var/palm/keystore/";
var keyFile = keystoreFolder + "key";
var keyStoreFile = keystoreFolder + "store.sqlite";

var KeyManagerServiceAssistant = function () {
    "use strict";
};

KeyManagerServiceAssistant.prototype.setup = function () {
    "use strict";
    var future = new Future(), masterkey;

    fs.exists(keystoreFolder, function existsCB(exists) {
        if (!exists) {
            fs.mkdir(keystoreFolder, function (err) {
                if (err) {
                    future.result = { returnValue: false, error: err};
                } else {
                    future.result = { returnValue: true };
                }
            });
        } else {
            future.result = { returnValue: true };
        }
    });

    future.then(this, function dirCheckCB() {
        var result = future.result;
        if (result.returnValue) {
            future.nest(KeyStore.loadKey()); //let's try anyway.
        } else {
            future.result = result;
        }
    });

    future.then(this, function haveCiphersCB() {
        var result = future.result;
        if (result.returnValue) {
            future.nest(KeyStore.loadDatabase(keyStoreFile));
        } else {
            future.result = result;
        }
    });

    return future;
};
<commit_msg>better filename for db file<commit_after>/* ServiceAssistant
* This assistant is called before anything within the service.
* It sets up the keystore decipher.
*/
/*jslint node: true */
/*global log, debug, fs, crypto, Future, KeyStore */

var keystoreFolder = "/var/palm/keystore/";
var keyFile = keystoreFolder + "key";
var keyStoreFile = keystoreFolder + "store.db";

var KeyManagerServiceAssistant = function () {
    "use strict";
};

KeyManagerServiceAssistant.prototype.setup = function () {
    "use strict";
    var future = new Future(), masterkey;

    fs.exists(keystoreFolder, function existsCB(exists) {
        if (!exists) {
            fs.mkdir(keystoreFolder, function (err) {
                if (err) {
                    future.result = { returnValue: false, error: err};
                } else {
                    future.result = { returnValue: true };
                }
            });
        } else {
            future.result = { returnValue: true };
        }
    });

    future.then(this, function dirCheckCB() {
        var result = future.result;
        if (result.returnValue) {
            future.nest(KeyStore.loadKey()); //let's try anyway.
        } else {
            future.result = result;
        }
    });

    future.then(this, function haveCiphersCB() {
        var result = future.result;
        if (result.returnValue) {
            future.nest(KeyStore.loadDatabase(keyStoreFile));
        } else {
            future.result = result;
        }
    });

    return future;
};
<|endoftext|>


<commit_before>$(document).ready(function() {
    randomAnimation();
});

function randomAnimation() {
    x = (Math.random() * 4) - 2
    y = (Math.random() * 4) - 2

    $('#logo-r').animate({
        top: y,
        left: x
    }, 100, "swing" function() {
        randomAnimation();
    });

};
<commit_msg>Update animate.header.v2.js<commit_after>$(document).ready(function() {
    randomAnimation();
});

function randomAnimation() {
    x = (Math.random() * 4) - 2
    y = (Math.random() * 4) - 2

    $('#logo-r').animate({
        top: y,
        left: x
    }, 100, "swing", function() {
        randomAnimation();
    });

};
<|endoftext|>


<commit_before>var p;
var density = 0.05;
var type = 2; //'Squares or diamonds - it will alternate between them at the moment
var rate = 5; //Number of squares to draw for each animation frame
var loop = true;
var seed;
var $canv;

//The percolator object - give it any canvas element and it will percolate all over it
var percolator = function(initialdensity,element,type,rate,inseed){

  var width = element.width();
  var height = element.height();
  var square = 3;
  var gap = 1;
  var t = this;
  var nx = Math.round(width/(square+gap));
  var ny = Math.round(height/(square+gap));
  var paused = false;

  this.bgcol = 'rgba(255,255,255,1)';
  this.fgcol = 'rgba(0,0,0,0)';
  this.finished = false;
  this.history = false;
  this.s = [];
  this.donext = loop;
  var ctx = element[0].getContext('2d');

  this.seed = inseed;

  //if we dont' specify a seed, generate a new one for this object
  //Initialize the s, the initial condition
  this.initialize = function(nopush){

    while(t.s.length>0){
      t.s.pop();
    }

    Math.seedrandom(t.seed);
    if(!nopush){
      t.url();
    }
    t.finished = false;
    t.finalized = false;
    t.paused = false;
    t.history = false;
    t.donext = loop;
    console.log('Initialize seed: ' + t.seed);

    for(var ii=0;ii<nx;ii++){
      t.s[ii] = [];
      for(var jj=0;jj<ny;jj++){
        t.s[ii][jj] = Math.random()<initialdensity ? 1 : 0;
      }
    }
    ctx.fillStyle = t.bgcol;
    ctx.fillRect(0,0,width,height);
    t.render();
  };

  this.render = function(){
    arrayloop(function(ii,jj){
      if(t.s[ii][jj] === 1) drawSquare(ii,jj);
    });
  };

  this.update = function(cb){
    //cb is the callback when the pattern has finished
    if(paused){
      return;
    }
    if(t.finished){
      t.onfinish();
      return;
    }
    var changes = [];

    arrayloop(function(ii,jj){
      var change = updaterule[type](ii,jj,np);
      if(change){
        changes.push([ii,jj]);
      }
    });

    if(changes.length>0){

      var indices = [];
      for(var ll=0; ll<changes.length;ll++){
        indices.push(ll);
      }
      indices = shuffle(indices);

      var c;
      var mm = 0;

      var raf = function(step){

        for(var rateind = 0; rateind< rate; rateind++){
          if(mm < indices.length){
            c = indices[mm];
            drawSquare(changes[c][0],changes[c][1]);
            t.s[changes[c][0]][changes[c][1]] = 1;
            mm++;
          }
        }
        if (mm < indices.length && !t.finished){
          requestAnimationFrame(raf);
        } else {
          t.update();
        }
      };

      requestAnimationFrame(raf);
    } else {
      if(!t.finished){
      t.onfinish();
      }
    }

    };

  this.togglepause = function(){
    paused = !paused;
    if(!paused){
      t.update();
    }
  };

  this.onfinish = function(){
    if (t.donext){
    console.log('seed is now being set as ' + t.seed);
    Math.seedrandom(t.seed);
    if(!p.history){
      t.seed = randomstring(32);
    }
    t.initialize(p.history);
    t.update();
    } else {
    t.finalized = true;
    }
  };

  this.finish = function(){
    t.finished=true;
  };

  //Handle the url for the object
  this.url = function(){
    var res = document.location.href.split('?')[0];
    var state = {seed:t.seed,density:density,type:type,rate:rate,loop:loop};
    history.pushState(state,'Percolation',createURL(res,state));
  };

  //Private methods
  var arrayloop = function(f){
    for(var ii = 0; ii < nx; ii++){
      for(var jj = 0; jj< ny; jj++){
        f(ii,jj);
      }
    }
  };

  var np = function(ii,jj){
    return t.s[(ii+nx)%nx][(jj+ny)%ny];
  };

  var drawSquare = function(ii,jj){
    ctx.clearRect(ii*(square+gap),jj*(square+gap),square,square);
  };

  //Initialize the object!
  this.initialize();
};

function addCanvases(){

  //Sort out the DOM so other things aren't borked
  //var $bg = $('.bg');
  //var w = $bg.width();
  //var h = $bg.height();
  //$bg.css({'background-image':'none'});
  //$bg.children().css({'position':'relative'});
  //var $canv_wrap = $('<div>').attr('id','canv_wrap').css({position:'absolute',float:'left'});
  //$canv = $('<canvas>').attr('id','canvas').attr('width',w).attr('height',h);
  //$canv_wrap.append($canv);
  //$bg.prepend($canv_wrap);
$canv = $('.bg canvas');

}

function parseURL(){

  var urlobj = getUrlVars();
  if(urlobj.density){
    density = urlobj.density;
  }
  if(urlobj.type){
    type = urlobj.type;
  }
  if(urlobj.rate){
    rate = urlobj.rate;
  }
  if(urlobj.loop){
    loop = urlobj.loop ==='true' ;
  }
  if(urlobj.seed){
    seed = urlobj.seed;
  } else {
    seed = randomstring(32);
  }

}

function initpage(){

  addCanvases();

  p = new percolator(density,$canv,type,rate,seed);
  p.update();

//Space to toggle pause
  $(window).keypress(function(e) {
    if (e.keyCode == 32) {
        p.togglepause();
      }
      e.preventDefault();
    });

//Right arrow to go to the next pattern
  $(window).keydown(function(e){
    //This is the right arrow thing
    if (e.keyCode== 39){
      p.donext = true;
      p.finish();
      if (p.finalized){
          p.onfinish();
      }
    }
  });

  window.onpopstate = function(event){
    parseURL();
    p.seed = seed;
    p.history = true;
    p.finish();
  };

}

$(function(){
 parseURL();
 initpage();
});

<commit_msg>looping off by default<commit_after>var p;
var density = 0.05;
var type = 2; //'Squares or diamonds - it will alternate between them at the moment
var rate = 5; //Number of squares to draw for each animation frame
var loop = true;
var seed;
var $canv;

//The percolator object - give it any canvas element and it will percolate all over it
var percolator = function(initialdensity,element,type,rate,inseed){

  var width = element.width();
  var height = element.height();
  var square = 3;
  var gap = 1;
  var t = this;
  var nx = Math.round(width/(square+gap));
  var ny = Math.round(height/(square+gap));
  var paused = false;

  this.bgcol = 'rgba(255,255,255,1)';
  this.fgcol = 'rgba(0,0,0,0)';
  this.finished = false;
  this.history = false;
  this.s = [];
  this.donext = loop;
  var ctx = element[0].getContext('2d');

  this.seed = inseed;

  //if we dont' specify a seed, generate a new one for this object
  //Initialize the s, the initial condition
  this.initialize = function(nopush){

    while(t.s.length>0){
      t.s.pop();
    }

    Math.seedrandom(t.seed);
    if(!nopush){
      t.url();
    }
    t.finished = false;
    t.finalized = false;
    t.paused = false;
    t.history = false;
    t.donext = loop;
    console.log('Initialize seed: ' + t.seed);

    for(var ii=0;ii<nx;ii++){
      t.s[ii] = [];
      for(var jj=0;jj<ny;jj++){
        t.s[ii][jj] = Math.random()<initialdensity ? 1 : 0;
      }
    }
    ctx.fillStyle = t.bgcol;
    ctx.fillRect(0,0,width,height);
    t.render();
  };

  this.render = function(){
    arrayloop(function(ii,jj){
      if(t.s[ii][jj] === 1) drawSquare(ii,jj);
    });
  };

  this.update = function(cb){
    //cb is the callback when the pattern has finished
    if(paused){
      return;
    }
    if(t.finished){
      t.onfinish();
      return;
    }
    var changes = [];

    arrayloop(function(ii,jj){
      var change = updaterule[type](ii,jj,np);
      if(change){
        changes.push([ii,jj]);
      }
    });

    if(changes.length>0){

      var indices = [];
      for(var ll=0; ll<changes.length;ll++){
        indices.push(ll);
      }
      indices = shuffle(indices);

      var c;
      var mm = 0;

      var raf = function(step){

        for(var rateind = 0; rateind< rate; rateind++){
          if(mm < indices.length){
            c = indices[mm];
            drawSquare(changes[c][0],changes[c][1]);
            t.s[changes[c][0]][changes[c][1]] = 1;
            mm++;
          }
        }
        if (mm < indices.length && !t.finished){
          requestAnimationFrame(raf);
        } else {
          t.update();
        }
      };

      requestAnimationFrame(raf);
    } else {
      if(!t.finished){
      t.onfinish();
      }
    }

    };

  this.togglepause = function(){
    paused = !paused;
    if(!paused){
      t.update();
    }
  };

  this.onfinish = function(){
    if (t.donext){
    console.log('seed is now being set as ' + t.seed);
    Math.seedrandom(t.seed);
    if(!p.history){
      t.seed = randomstring(32);
    }
    t.initialize(p.history);
    t.update();
    } else {
    t.finalized = true;
    }
  };

  this.finish = function(){
    t.finished=true;
  };

  //Handle the url for the object
  this.url = function(){
    var res = document.location.href.split('?')[0];
    var state = {seed:t.seed,density:density,type:type,rate:rate,loop:loop};
    history.pushState(state,'Percolation',createURL(res,state));
  };

  //Private methods
  var arrayloop = function(f){
    for(var ii = 0; ii < nx; ii++){
      for(var jj = 0; jj< ny; jj++){
        f(ii,jj);
      }
    }
  };

  var np = function(ii,jj){
    return t.s[(ii+nx)%nx][(jj+ny)%ny];
  };

  var drawSquare = function(ii,jj){
    ctx.clearRect(ii*(square+gap),jj*(square+gap),square,square);
  };

  //Initialize the object!
  this.initialize();
};

function addCanvases(){

  //Sort out the DOM so other things aren't borked
  //var $bg = $('.bg');
  //var w = $bg.width();
  //var h = $bg.height();
  //$bg.css({'background-image':'none'});
  //$bg.children().css({'position':'relative'});
  //var $canv_wrap = $('<div>').attr('id','canv_wrap').css({position:'absolute',float:'left'});
  //$canv = $('<canvas>').attr('id','canvas').attr('width',w).attr('height',h);
  //$canv_wrap.append($canv);
  //$bg.prepend($canv_wrap);
$canv = $('.bg canvas');

}

function parseURL(){

  var urlobj = getUrlVars();
  if(urlobj.density){
    density = urlobj.density;
  }
  if(urlobj.type){
    type = urlobj.type;
  }
  if(urlobj.rate){
    rate = urlobj.rate;
  }
  if(urlobj.loop){
    loop = urlobj.loop ==='true' ;
  } else {
    loop = false;
  }
  if(urlobj.seed){
    seed = urlobj.seed;
  } else {
    seed = randomstring(32);
  }

}

function initpage(){

  addCanvases();

  p = new percolator(density,$canv,type,rate,seed);
  p.update();

//Space to toggle pause
  $(window).keypress(function(e) {
    if (e.keyCode == 32) {
        p.togglepause();
      }
      e.preventDefault();
    });

//Right arrow to go to the next pattern
  $(window).keydown(function(e){
    //This is the right arrow thing
    if (e.keyCode== 39){
      p.donext = true;
      p.finish();
      if (p.finalized){
          p.onfinish();
      }
    }
  });

  window.onpopstate = function(event){
    parseURL();
    p.seed = seed;
    p.history = true;
    p.finish();
  };

}

$(function(){
 parseURL();
 initpage();
});

<|endoftext|>