<commit_before>/**
 * Created by ant4 on 30/10/15.
 */

var BoilerNotifications = (function($) {
    var notify = function(message){
        var tmpl = '
' + message + '

';

        $('*[data-role="notificatons"]')
            .removeClass('hidden')
            .find('#message_header_center')
            .append($(tmpl));
    };

    return {
        notity: notify
    }
})(jQuery);

(function(window, sessionStorage){
    var userDataAjaPromise = null;

    /**
     * Returns a promise that gets the user data. The first time it is called, it creates the promise making the ajax request.
     * The other times the created promise is returned
     * @param apiEndpoint
     * @param token
     * @param userId
     * @returns {*}
     */
    var getUserData = function(apiEndpoint, token, userId){
        var url = apiEndpoint + '/api/users/' + userId;

        if(userDataAjaPromise == null){

            userDataAjaPromise = $.ajax({
                url: url,
                headers: {Authorization: 'Bearer ' + token},
            });
        }

        return userDataAjaPromise;
    };

    /**
     * Checks from the sessionStorage or calculates from the userData if a given parameter is setted to true
     * @param userId
     * @param apiEndpoint
     * @param token
     * @param storageKey
     * @param message
     * @param remoteVerifyer
     */
    var checkFromStorageOrRemote = function(userId, apiEndpoint, token, storageKey, message, remoteVerifyer){
        var doNotify = function(mustNotify){ // this is executed when we know we have the key in the storage
            if(!mustNotify){
                BoilerNotifications.notity(message);
            }
        };

        // if we have not the key in the session storage, we fetch data from the server to search if the user has a profile photo
        if(sessionStorage == null || sessionStorage.getItem(storageKey) == null){
            getUserData(apiEndpoint, token, userId).then(function(data){
                var mustNotify = remoteVerifyer(data) ? 1 : 0;

                if(sessionStorage !== null){
                    sessionStorage.setItem(storageKey, mustNotify);
                }

                //now that we have the key in the storage we do the logic
                doNotify(mustNotify == 1);
            });
        }else{ // we allready have the key on the storage, we do the logic
            var mustNotify = sessionStorage.getItem(storageKey) == 1;
            doNotify(mustNotify);
        }
    };

    /**
     * Notifies if a user has no profile photo
     * @param userId
     * @param apiEndpoint
     * @param token
     * @param message
     */
    var notifyIfUserHasNoProfilePhoto = function(userId, apiEndpoint, token, message){
        var storageKey = 'has_profile_photo';
        var remoteVerifyer = function(data){
            return typeof(data['profile']) != 'undefined' && typeof(data['profile']['profile_photo']) != 'undefined' ? 1 : 0;
        };

        checkFromStorageOrRemote(userId, apiEndpoint, token, storageKey, message, remoteVerifyer);
    };

    /**
     * Notifies if a user has no city
     * @param userId
     * @param apiEndpoint
     * @param token
     * @param message
     */
    var notifyIfUserHasNoCity = function(userId, apiEndpoint, token, message){
        var storageKey = 'has_city';
        var remoteVerifyer = function(data){
            return typeof(data['city']) != 'undefined' ? 1 : 0;
        };

        checkFromStorageOrRemote(userId, apiEndpoint, token, storageKey, message, remoteVerifyer);
    };

    /**
     * Sets the user data promise to null
     */
    var clearUserData = function(){
        userDataAjaPromise = null;
    };

    window.notifyIfUserHasNoProfilePhoto = notifyIfUserHasNoProfilePhoto;
    window.notifyIfUserHasNoCity = notifyIfUserHasNoCity;
    window.clearUserData = clearUserData;
})(
    window,
    typeof(window.sessionStorage) !== "undefined" ? window.sessionStorage : null //this way we don't have to use allways typeof every time we want to check if the browser support session storage
);<commit_msg>Append user id to the sessionStorage key<commit_after>/**
 * Created by ant4 on 30/10/15.
 */

var BoilerNotifications = (function($) {
    var notify = function(message){
        var tmpl = '
' + message + '

';

        $('*[data-role="notificatons"]')
            .removeClass('hidden')
            .find('#message_header_center')
            .append($(tmpl));
    };

    return {
        notity: notify
    }
})(jQuery);

(function(window, sessionStorage){
    var userDataAjaPromise = null;

    /**
     * Returns a promise that gets the user data. The first time it is called, it creates the promise making the ajax request.
     * The other times the created promise is returned
     * @param apiEndpoint
     * @param token
     * @param userId
     * @returns {*}
     */
    var getUserData = function(apiEndpoint, token, userId){
        var url = apiEndpoint + '/api/users/' + userId;

        if(userDataAjaPromise == null){

            userDataAjaPromise = $.ajax({
                url: url,
                headers: {Authorization: 'Bearer ' + token},
            });
        }

        return userDataAjaPromise;
    };

    /**
     * Checks from the sessionStorage or calculates from the userData if a given parameter is setted to true
     * @param userId
     * @param apiEndpoint
     * @param token
     * @param storageKey
     * @param message
     * @param remoteVerifyer
     */
    var checkFromStorageOrRemote = function(userId, apiEndpoint, token, storageKey, message, remoteVerifyer){
        storageKey = storageKey + '_' + userId; // make sure the session belongs to the user

        var doNotify = function(mustNotify){ // this is executed when we know we have the key in the storage
            if(!mustNotify){
                BoilerNotifications.notity(message);
            }
        };

        // if we have not the key in the session storage, we fetch data from the server to search if the user has a profile photo
        if(sessionStorage == null || sessionStorage.getItem(storageKey) == null){
            getUserData(apiEndpoint, token, userId).then(function(data){
                var mustNotify = remoteVerifyer(data) ? 1 : 0;

                if(sessionStorage !== null){
                    sessionStorage.setItem(storageKey, mustNotify);
                }

                //now that we have the key in the storage we do the logic
                doNotify(mustNotify == 1);
            });
        }else{ // we allready have the key on the storage, we do the logic
            var mustNotify = sessionStorage.getItem(storageKey) == 1;
            doNotify(mustNotify);
        }
    };

    /**
     * Notifies if a user has no profile photo
     * @param userId
     * @param apiEndpoint
     * @param token
     * @param message
     */
    var notifyIfUserHasNoProfilePhoto = function(userId, apiEndpoint, token, message){
        var storageKey = 'has_profile_photo';
        var remoteVerifyer = function(data){
            return typeof(data['profile']) != 'undefined' && typeof(data['profile']['profile_photo']) != 'undefined' ? 1 : 0;
        };

        checkFromStorageOrRemote(userId, apiEndpoint, token, storageKey, message, remoteVerifyer);
    };

    /**
     * Notifies if a user has no city
     * @param userId
     * @param apiEndpoint
     * @param token
     * @param message
     */
    var notifyIfUserHasNoCity = function(userId, apiEndpoint, token, message){
        var storageKey = 'has_city';
        var remoteVerifyer = function(data){
            return typeof(data['city']) != 'undefined' ? 1 : 0;
        };

        checkFromStorageOrRemote(userId, apiEndpoint, token, storageKey, message, remoteVerifyer);
    };

    /**
     * Sets the user data promise to null
     */
    var clearUserData = function(){
        userDataAjaPromise = null;
    };

    window.notifyIfUserHasNoProfilePhoto = notifyIfUserHasNoProfilePhoto;
    window.notifyIfUserHasNoCity = notifyIfUserHasNoCity;
    window.clearUserData = clearUserData;
})(
    window,
    typeof(window.sessionStorage) !== "undefined" ? window.sessionStorage : null //this way we don't have to use allways typeof every time we want to check if the browser support session storage
);<|endoftext|>


<commit_before>// See Purple/license.txt for Google BSD license
// Copyright 2011 Google, Inc. johnjbarton@johnjbarton.com

define(['../lib/base.js', '../lib/domplate/lib/domplate','../resources/ResourceRep'], function (Base, domplate, ResourceRep) {

  var Resource = Base.extend({
    initialize: function(url) {
      this.url = url;
      this.rep = ResourceRep;
    }
  });

  return Resource;
});<commit_msg>missed one file in the rename<commit_after>// See Purple/license.txt for Google BSD license
// Copyright 2011 Google, Inc. johnjbarton@johnjbarton.com

define(['../lib/Base.js', '../lib/domplate/lib/domplate','../resources/ResourceRep'], function (Base, domplate, ResourceRep) {

  var Resource = Base.extend({
    initialize: function(url) {
      this.url = url;
      this.rep = ResourceRep;
    }
  });

  return Resource;
});<|endoftext|>


<commit_before>var app = require('app');
var BrowserWindow = require('browser-window');
var Menu = require('menu');
var MenuItem = require('menu-item');
var Tray = require('tray');
var ipc = require('ipc')
var globalShortcut = require('global-shortcut');
var shell = require('shell');
var path = require("path");
var fs = require("fs");
var initPath = path.join(app.getAppPath(), "init.json");
var data;
var dialog = require('dialog');
try {
data = JSON.parse(fs.readFileSync(initPath, 'utf8'));
}
catch(e) {
}

var menu = new Menu();
var minToTray;
minToTray = data.minTray;

var updateReady = false;

app.commandLine.appendSwitch('client-certificate', 'file://' + __dirname + '/assets/comodorsaaddtrustca.crt');
app.commandLine.appendSwitch('ignore-certificate-errors');

app.on('window-all-closed', function() {
  if (process.platform != 'darwin') {
    app.quit();
  }
});

app.on('ready', function() {

    updateWindow = new BrowserWindow({width: 300, height: 300, icon: __dirname + '/icon.png', title: "Discord", 'auto-hide-menu-bar': true, frame: false});
    updateWindow.setResizable(false);
    updateWindow.setAlwaysOnTop(true);
    updateWindow.setSkipTaskbar(true);
    updateWindow.loadUrl('file://' + __dirname + '/update.html');

    //When no updates

    //mainWindow = new BrowserWindow((data && data.bounds) ? data.bounds : {width: 1200, height: 900});
    mainWindow = new BrowserWindow({width: 900, height: 750, icon: __dirname + '/icon.png', title: "Discord", 'auto-hide-menu-bar': true});
    mainWindow.setBounds(data.bounds);
    webContents = mainWindow.webContents;
    updateWindow.close();
    mainWindow.setTitle("Discord");
    mainWindow.setMenuBarVisibility(false);
    mainWindow.loadUrl('file://' + __dirname + '/index.html');

    //Nullify any closed windows.
    mainWindow.on('closed', function() {
        //updateWindow.close();
        mainWindow = null;
    });
    updateWindow.on('closed', function(){
        updateWindow = null;
    });
    //Save settings when app is closed.
    mainWindow.on('close', function(){
        var data = {
            bounds: mainWindow.getBounds(),
            minTray: minToTray
        };
        fs.writeFileSync(initPath, JSON.stringify(data));
    });

    var showButton = new MenuItem({
        label: 'Show Discord',
        type: 'normal',
        click: function() {
            mainWindow.setBounds(data.bounds);
            mainWindow.restore(); mainWindow.setSkipTaskbar(false);
        }
    });

    //Minimize to tray. (Only works on some OSs)
    var disMinButton = new MenuItem({
      label: 'Disable Minimize to Tray',
      type: 'checkbox',
      checked: true,
      click: function() {
        if(disMinButton.checked == true){
          minToTray = false;
          console.log("Disabled MinToTray");
        } else if (disMinButton.checked == false) {
          minToTray = true;
          console.log("Enabled MinToTray");
        }

        if(minToTray == false){
          disMinButton.checked = true;
        }
        else if(minToTray == true){
          disMinButton.checked = false;
        }

      }
    });

    mainWindow.on('minimize', function() {
        //showButton.enabled = true;
        var data = {
            bounds: mainWindow.getBounds(),
            minTray: minToTray
        };
        if(minToTray == true){
        mainWindow.setSkipTaskbar(true);
        }
    });

    //Tray Menu
    //menu.append(new MenuItem({ label: 'Show Discord', type: 'normal', click: function() { mainWindow.restore(); mainWindow.setSkipTaskbar(false); } }));
    menu.append(showButton);
    menu.append(new MenuItem({ type: 'separator' }));
    menu.append(new MenuItem({ label: 'Refresh Discord', type: 'normal', click: function(){ mainWindow.reload(); } }));
    menu.append(new MenuItem({ type: 'separator' }));
    menu.append(disMinButton);
    menu.append(new MenuItem({ type: 'separator' }));
    menu.append(new MenuItem({ label: 'Quit Discord', type: 'normal', click: function() { app.quit(); } }));

    appIcon = new Tray(__dirname + '/tray.png');
    appIcon.setToolTip('Discord');
    appIcon.setContextMenu(menu);

    //Link fix
    webContents.on('new-window', function(event, urlToOpen) {
      event.preventDefault();
      shell.openExternal(urlToOpen);
    });

    //Allow refreshing and Show Window
    mainWindow.on('focus', function(){
        showButton.enabled = false;
        globalShortcut.register('ctrl+r', function () {
            mainWindow.reload();
        });
    });
    //Disable refresh when not in focus.
    mainWindow.on('blur', function(){
        showButton.enabled = true;
        globalShortcut.unregister('ctrl+r');
    });

});
<commit_msg>Fix minimize to tray bug with GNOME. Hides instead of minimizes when closing to tray. Does it on close instead of on minimize. 'Quit Discord' tray menu option always quits.<commit_after>var app = require('app');
var BrowserWindow = require('browser-window');
var Menu = require('menu');
var MenuItem = require('menu-item');
var Tray = require('tray');
var ipc = require('ipc')
var globalShortcut = require('global-shortcut');
var shell = require('shell');
var path = require("path");
var fs = require("fs");
var initPath = path.join(app.getAppPath(), "init.json");
var data;
var dialog = require('dialog');
try {
data = JSON.parse(fs.readFileSync(initPath, 'utf8'));
}
catch(e) {
}

var menu = new Menu();
var minToTray;
minToTray = data.minTray;

var updateReady = false;
var quitForReal = false; // Dirty

app.commandLine.appendSwitch('client-certificate', 'file://' + __dirname + '/assets/comodorsaaddtrustca.crt');
app.commandLine.appendSwitch('ignore-certificate-errors');

app.on('window-all-closed', function() {
  if (process.platform != 'darwin') {
    app.quit();
  }
});

app.on('ready', function() {

    updateWindow = new BrowserWindow({width: 300, height: 300, icon: __dirname + '/icon.png', title: "Discord", 'auto-hide-menu-bar': true, frame: false});
    updateWindow.setResizable(false);
    updateWindow.setAlwaysOnTop(true);
    updateWindow.setSkipTaskbar(true);
    updateWindow.loadUrl('file://' + __dirname + '/update.html');

    //When no updates

    //mainWindow = new BrowserWindow((data && data.bounds) ? data.bounds : {width: 1200, height: 900});
    mainWindow = new BrowserWindow({width: 900, height: 750, icon: __dirname + '/icon.png', title: "Discord", 'auto-hide-menu-bar': true});
    mainWindow.setBounds(data.bounds);
    webContents = mainWindow.webContents;
    updateWindow.close();
    mainWindow.setTitle("Discord");
    mainWindow.setMenuBarVisibility(false);
    mainWindow.loadUrl('file://' + __dirname + '/index.html');

    //Nullify any closed windows.
    mainWindow.on('closed', function() {
        //updateWindow.close();
        mainWindow = null;
    });
    updateWindow.on('closed', function(){
        updateWindow = null;
    });
    //Save settings when app is closed.
    mainWindow.on('close', function(){
        var data = {
            bounds: mainWindow.getBounds(),
            minTray: minToTray
        };
        fs.writeFileSync(initPath, JSON.stringify(data));
    });

    var showButton = new MenuItem({
        label: 'Show Discord',
        type: 'normal',
        click: function() {
			mainWindow.setSkipTaskbar(false);
            mainWindow.show();
        }
    });

    //Minimize to tray. (Only works on some OSs)
    var disMinButton = new MenuItem({
      label: 'Disable Minimize to Tray',
      type: 'checkbox',
      checked: !minToTray,
      click: function() {
        if(disMinButton.checked == true){
          minToTray = false;
          console.log("Disabled MinToTray");
        } else if (disMinButton.checked == false) {
          minToTray = true;
          console.log("Enabled MinToTray");
        }

		disMinButton.checked = !minToTray;

      }
    });

    mainWindow.on('close', function(event) {
        if(minToTray && !quitForReal){
			event.preventDefault();
			data.bounds = mainWindow.getBounds();
			mainWindow.hide();
        	mainWindow.setSkipTaskbar(true);
        }
    });

    //Tray Menu
    //menu.append(new MenuItem({ label: 'Show Discord', type: 'normal', click: function() { mainWindow.restore(); mainWindow.setSkipTaskbar(false); } }));
    menu.append(showButton);
    menu.append(new MenuItem({ type: 'separator' }));
    menu.append(new MenuItem({ label: 'Refresh Discord', type: 'normal', click: function(){ mainWindow.reload(); } }));
    menu.append(new MenuItem({ type: 'separator' }));
    menu.append(disMinButton);
    menu.append(new MenuItem({ type: 'separator' }));
    menu.append(new MenuItem({ label: 'Quit Discord', type: 'normal', click: function() { quitForReal = true; app.quit(); } }));

    appIcon = new Tray(__dirname + '/tray.png');
    appIcon.setToolTip('Discord');
    appIcon.setContextMenu(menu);

	appIcon.on('clicked', function(event){
		mainWindow.setSkipTaskbar(false);
		mainWindow.show();
	});

    //Link fix
    webContents.on('new-window', function(event, urlToOpen) {
      event.preventDefault();
      shell.openExternal(urlToOpen);
    });

    //Allow refreshing and Show Window
    mainWindow.on('focus', function(){
        showButton.enabled = false;
        globalShortcut.register('ctrl+r', function () {
            mainWindow.reload();
        });
    });
    //Disable refresh when not in focus.
    mainWindow.on('blur', function(){
        showButton.enabled = true;
        globalShortcut.unregister('ctrl+r');
    });

});
<|endoftext|>


<commit_before>/*
 *   Initializes the game.
 */
function init() {
    var game = new Game();
    game.start();
}

var CONFIG = (function() {
    var private = {
        'WIDTH': 800,
        'HEIGHT': 600
    };

    return {
        get: function(name) { return private[name]; }
    };
})();

/*
 *  On window load function.
 */
window.onload = init;<commit_msg>Moved constants to game.js<commit_after>/*
 *   Initializes the game.
 */
function init() {
    var game = new Game();
    game.start();
}

/*
 *  On window load function.
 */
window.onload = init;<|endoftext|>


<commit_before>const SIMILARITY_URL = 'https://tools.wmflabs.org/similarity/search';

let SuggestionsCache = new (function() {
  const MAX_CACHE_SIZE = 10;
  const ENTRY_TTL_S = 10 * 60;

  this._cache = [];

  this._expire = () => {
    this._cache = this._cache.filter((entry) => {
      return ((new Date() - entry.date) / 1000) < ENTRY_TTL_S;
    });
  }

  this.get = key => {
    this._expire();
    for (let i = 0; i < this._cache.length; i++) {
      let entry = this._cache[i];
      if (entry.key === key) {
        return entry.value;
      }
    }
    return undefined;
  };

  this.set = (key, value) => {
    this._expire();
    if (this._cache.length == MAX_CACHE_SIZE) {
      this._cache.shift();
    }
    this._cache = this._cache.filter(entry => entry.key !== key);
    this._cache.push({key: key, value: value, date: new Date()});
  };
});

function getDocumentContents() {
  return new Promise((resolve, reject) => {
    let script = 'document.documentElement.outerHTML';
    chrome.tabs.executeScript({
      code: script
    }, (result) => { resolve(result[0]); });
  });
}

function fetchSimilarArticles(html, url) {
  let formData = new FormData();
  formData.append('html', html);
  formData.append('url', url);
  let o = {method: 'POST', mode: 'cors', body: formData};
  return window.fetch(SIMILARITY_URL, o).then(
    (response) => { return response.json() }).then(
    (response) => {
      console.log(response['debug']);
      return response['results'];
    });
}

function getSuggestionsForTab(tab, options) {
  return new Promise((resolve, reject) => {
    if (!tab.url) {
      reject('No URL!');
      return;
    }

    let whitelist = loadURLsWhitelist();
    let match = whitelist.some((w) => {
      return tab.url.match(RegExp(w));
    });
    if (!match) {
      resolve([]);
      return;
    };

    if (!options || options.canUseCache) {
      let cached = SuggestionsCache.get(tab.url);
      if (cached) {
        resolve(cached);
        return;
      }
    }

    resolve(getDocumentContents().then((html) => {
      return fetchSimilarArticles(html, tab.url);
    }).then((suggestions) => {
      SuggestionsCache.set(tab.url, suggestions);
      return suggestions;
    }));
  });
}

function getSuggestionsAndUpdateUI(tab, options) {
  getSuggestionsForTab(tab, options).then((articles) => {
    if (articles.length) {
      chrome.pageAction.show(tab.id);
    } else {
      chrome.pageAction.hide(tab.id);
    }
  }).catch((e) => {
    console.log(e);
    chrome.pageAction.hide(tab.id);
  });
}

chrome.tabs.onActivated.addListener((activeInfo) => {
  chrome.tabs.get(activeInfo.tabId, (tab) => {
    getSuggestionsAndUpdateUI(tab);
  });
});

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  // Note: this event can happen multiple times, even after the page loads,
  // and changeInfo.status can even be undefined (despite being documented
  // as only ever being either 'loading' or 'complete').
  if (changeInfo.status == 'complete') {
    getSuggestionsAndUpdateUI(tab, {canUseCache: false});
  }
});

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    getSuggestionsForTab(tabs[0]).then(sendResponse);
  });
  return true;
});
<commit_msg>Remove cached suggestions when the url changes/tab closes, not by time.<commit_after>const SIMILARITY_URL = 'https://tools.wmflabs.org/similarity/search';

let SuggestionsCache = new (function() {
  const MAX_CACHE_SIZE = 10;

  this._cache = [];

  this.get = key => {
    for (let i = 0; i < this._cache.length; i++) {
      let entry = this._cache[i];
      if (entry.key === key) {
        return entry.value;
      }
    }
    return undefined;
  };

  this.set = (key, value) => {
    if (this._cache.length == MAX_CACHE_SIZE) {
      this._cache.shift();
    }
    this.remove(key);
    this._cache.push({key: key, value: value});
  };

  this.remove = (key) => {
    this._cache = this._cache.filter(entry => entry.key !== key);
  };
});

function getDocumentContents() {
  return new Promise((resolve, reject) => {
    let script = 'document.documentElement.outerHTML';
    chrome.tabs.executeScript({
      code: script
    }, (result) => { resolve(result[0]); });
  });
}

function fetchSimilarArticles(html, url) {
  let formData = new FormData();
  formData.append('html', html);
  formData.append('url', url);
  let o = {method: 'POST', mode: 'cors', body: formData};
  return window.fetch(SIMILARITY_URL, o).then(
    (response) => { return response.json() }).then(
    (response) => {
      console.log(response['debug']);
      return response['results'];
    });
}

function getSuggestionsForTab(tab, options) {
  return new Promise((resolve, reject) => {
    if (!tab.url) {
      reject('No URL!');
      return;
    }

    let whitelist = loadURLsWhitelist();
    let match = whitelist.some((w) => {
      return tab.url.match(RegExp(w));
    });
    if (!match) {
      resolve([]);
      return;
    };

    if (!options || options.canUseCache) {
      let cached = SuggestionsCache.get(tab.id);
      if (cached) {
        resolve(cached);
        return;
      }
    }

    resolve(getDocumentContents().then((html) => {
      return fetchSimilarArticles(html, tab.url);
    }).then((suggestions) => {
      SuggestionsCache.set(tab.id, suggestions);
      return suggestions;
    }));
  });
}

function getSuggestionsAndUpdateUI(tab, options) {
  getSuggestionsForTab(tab, options).then((articles) => {
    if (articles.length) {
      chrome.pageAction.show(tab.id);
    } else {
      chrome.pageAction.hide(tab.id);
    }
  }).catch((e) => {
    console.log(e);
    chrome.pageAction.hide(tab.id);
  });
}

chrome.tabs.onActivated.addListener((activeInfo) => {
  chrome.tabs.get(activeInfo.tabId, (tab) => {
    getSuggestionsAndUpdateUI(tab);
  });
});

chrome.tabs.onRemoved.addListener((tabId, removeInfo) => {
  SuggestionsCache.remove(tabId);
});

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  // Note: this event can happen multiple times, even after the page loads,
  // and changeInfo.status can even be undefined (despite being documented
  // as only ever being either 'loading' or 'complete').
  if (changeInfo.status == 'complete') {
    getSuggestionsAndUpdateUI(tab, {canUseCache: false});
  }
});

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    getSuggestionsForTab(tabs[0]).then(sendResponse);
  });
  return true;
});
<|endoftext|>


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

  // Initialize options
  chrome.runtime.onInstalled.addListener(function () {
    localStorage.game = 'bf4';
    localStorage.notifIsActivated = false;
    localStorage.notifFrequency = 1;
  });

  var HOME_URL = 'http://battlelog.battlefield.com/' + localStorage.game + '/';
  var UPDATES_URL = 'http://battlelog.battlefield.com/' + localStorage.game + '/updates/';
  var FRIENDS_URL_JSON  = 'http://battlelog.battlefield.com/' + localStorage.game + '/comcenter/sync/';
  var NOTIFICATIONS_URL_JSON  = 'http://battlelog.battlefield.com/' + localStorage.game + '/updates/loadNotifications/';

  var colorOffline = [63, 59, 61, 255];
  var colorOnline  = [120, 199, 83, 255];
  var colorPlaying = [96, 192, 246, 255];

  // XHR helper function
  var xhr = function () {
    var xhr = new XMLHttpRequest();
    return function(method, url, callback) {
      xhr.onreadystatechange = function () {
        // request finished and response is ready
        if (xhr.readyState === 4) {
          if (xhr.status !== 200) {
            callback(false);
          }
          callback(xhr.responseText);
        }
      };
      xhr.open(method, url);
      xhr.send();
    };
  }();

  // main function
  window.FriendsCount = function (callback) {
    xhr('GET', FRIENDS_URL_JSON, function (data) {
      var key;
      var friendsCount = 0;
      var friendsOnlineCount = 0;
      var friendsPlayingCount = 0;
      var count = '0';
      var status;

      // no data
      if (data === false) {
        callback(false);
      }

      try {
        var json = JSON.parse(data);
      } catch (e) {
        console.error("Parsing error:", e);
        callback(false);
      }

      if (json.type == 'success') {
        if (json.data.originavailable) {
          for(key in json.data.friendscomcenter) {
            if(json.data.friendscomcenter.hasOwnProperty(key)) {
              friendsCount++;
              if (json.data.friendscomcenter[key].presence.isOnline) {
                friendsOnlineCount++;
              }
              if (json.data.friendscomcenter[key].presence.isPlaying) {
                friendsPlayingCount++;
              }
            }
          }
          if (friendsPlayingCount > 0) {
            count = friendsPlayingCount.toString();
            status = 'playing';
          }
          else {
            if (friendsOnlineCount > 0) {
              count = friendsOnlineCount.toString();
              status = 'online';
            }
            else {
              count = friendsCount.toString();
              status = 'offline';
            }
          }
        }
        // origin not available
        else {
          count = '0';
          status = 'offline';
        }
        callback(count, status);
      }
      else {
        callback(false);
      }
    });
  };

  window.NotificationsCount = function (callback) {
    xhr('GET', NOTIFICATIONS_URL_JSON, function (data) {
      var count = '0';

      // no data
      if (data === false) {
        callback(false);
      }

      var json = JSON.parse(data);
      if (json.type == 'success') {
        count = json.data.numUnread.toString();
        callback(count);
      }
      else {
        callback(false);
      }
    });
  }

  // badge renderer
  function render(badge, color, title) {
    chrome.browserAction.setBadgeText({
      text: badge
    });
    chrome.browserAction.setBadgeBackgroundColor({
      color: color
    });
    chrome.browserAction.setTitle({
      title: title
    });
  }

  // update badge
  function updateBadge() {
    //console.log('updateBadge()'); // debug
    var color;
    FriendsCount(function (count, status) {
      //console.log('friends count: ' + count); // debug
      if (count !== false) {
        color = colorOffline;
        if (status == 'playing') {
          color = colorPlaying;
        }
        if (status == 'online') {
          color = colorOnline;
        }
        render((count !== '0' ? count : ''), color, chrome.i18n.getMessage('browserActionDefaultTitle', [count, status]));
      } else {
        render('?', [190, 190, 190, 230], chrome.i18n.getMessage('browserActionErrorTitle'));
      }
    });
  }

  function showNotification() {
    NotificationsCount(function (count) {
      //console.log('notifications count: ' + count); // debug
      if (count !== false && count > 0) {
        var opt = {
          type: "basic",
          title: chrome.i18n.getMessage('notificationTitle'),
          message: chrome.i18n.getMessage('notificationMessage', [count]),
          iconUrl: "icon-48.png",
          buttons: [
            { title: chrome.i18n.getMessage('notificationButton1Title'), iconUrl: "glyphicons_206_ok_2.png" },
            { title: chrome.i18n.getMessage('notificationButton2Title'), iconUrl: "glyphicons_266_flag.png" },
          ]
        };
        var notification = chrome.notifications.create('showNotification', opt, function() {
          // auto clear after 5s
          /*
          setTimeout(function() {
            chrome.notifications.clear('showNotification', function(){});
          }, 5000);
          */
        });
      }
    });
  }

  function isBattlelogUrl(url) {
    return url.indexOf(HOME_URL) == 0;
  }

  function isBattlelogUpdatesUrl(url) {
    return url.indexOf(UPDATES_URL) == 0;
  }

  function openBattlelogHomeInTab() {
    // check if Battle is already open
    chrome.tabs.getAllInWindow(undefined, function(tabs) {
      for (var i = 0, tab; tab = tabs[i]; i++) {
        if (tab.url && isBattlelogUrl(tab.url)) {
          chrome.tabs.update(tab.id, {selected: true});
          return;
        }
      }
      chrome.tabs.create({url: HOME_URL});
    });
  }

  function openBattlelogUpdatesInTab() {
    // check if Battlelog is already open
    chrome.tabs.getAllInWindow(undefined, function(tabs) {
      for (var i = 0, tab; tab = tabs[i]; i++) {
        if (tab.url && isBattlelogUpdatesUrl(tab.url)) {
          chrome.tabs.update(tab.id, {selected: true});
          return;
        }
      }
      chrome.tabs.create({url: UPDATES_URL});
    });
  }

  // alarms
  chrome.alarms.create('badge', {periodInMinutes: 1});
  if (chrome.notifications
    && localStorage.notifIsActivated === true
    && localStorage.notifFrequency)
  {
    chrome.alarms.create('notification', {periodInMinutes: parseInt(localStorage.notifFrequency)});
  }
  chrome.alarms.onAlarm.addListener(function (alarm) {
    if (alarm.name == 'badge') {
      updateBadge();
    }
    if (alarm.name == 'notification') {
      showNotification();
    }
  });

  // browser action
  chrome.browserAction.onClicked.addListener(function () {
    updateBadge();
    if (chrome.notifications
      && localStorage.notifIsActivated === true)
    {
      showNotification();
    }
    openBattlelogHomeInTab();
  });

  if (chrome.notifications) {
    // notification action
    chrome.notifications.onClicked.addListener(function () {
      openBattlelogHomeInTab();
      chrome.notifications.clear('showNotification', function(){});
    });
    // notification button(s) action
    chrome.notifications.onButtonClicked.addListener(function (notificationId, buttonIndex) {
      //console.log('button index: ' + buttonIndex); // debug
      if (buttonIndex == 1) {
        openBattlelogUpdatesInTab();
      }
      chrome.notifications.clear('showNotification', function(){});
    });
  }

  // message
  chrome.runtime.onMessage.addListener(function () {
    //console.log('onMessage event'); // debug
    updateBadge();
  });

  updateBadge();
})();<commit_msg>Revamping the loading method of base URLs<commit_after>(function () {
  'use strict';

  // Initialize options
  chrome.runtime.onInstalled.addListener(function () {
    localStorage.game = 'bf4';
    localStorage.notifIsActivated = false;
    localStorage.notifFrequency = 1;
  });

  // HOME_URL
  function getHomeUrl(game) {
    return 'http://battlelog.battlefield.com/' + game + '/';
  }
  // UPDATES_URL
  function getUpdateUrl(game) {
    return 'http://battlelog.battlefield.com/' + game + '/updates/';
  }
  // FRIENDS_URL_JSON
  function getFriendsUrlJson(game) {
    return 'http://battlelog.battlefield.com/' + game + '/comcenter/sync/';
  }
  // NOTIFICATIONS_URL_JSON
  function getNotificationsUrlJson(game) {
    return 'http://battlelog.battlefield.com/' + game + '/updates/loadNotifications/';
  }

  var colorOffline = [63, 59, 61, 255];
  var colorOnline  = [120, 199, 83, 255];
  var colorPlaying = [96, 192, 246, 255];

  // XHR helper function
  var xhr = function () {
    var xhr = new XMLHttpRequest();
    return function(method, url, callback) {
      xhr.onreadystatechange = function () {
        // request finished and response is ready
        if (xhr.readyState === 4) {
          if (xhr.status !== 200) {
            callback(false);
          }
          callback(xhr.responseText);
        }
      };
      xhr.open(method, url);
      xhr.send();
    };
  }();

  // main function
  window.FriendsCount = function (callback) {
    xhr('GET', getFriendsUrlJson(localStorage.game), function (data) {
      var key;
      var friendsCount = 0;
      var friendsOnlineCount = 0;
      var friendsPlayingCount = 0;
      var count = '0';
      var status;

      // no data
      if (data === false) {
        callback(false);
      }

      try {
        var json = JSON.parse(data);
      } catch (e) {
        console.error("Parsing error:", e);
        callback(false);
      }

      if (json.type == 'success') {
        if (json.data.originavailable) {
          for(key in json.data.friendscomcenter) {
            if(json.data.friendscomcenter.hasOwnProperty(key)) {
              friendsCount++;
              if (json.data.friendscomcenter[key].presence.isOnline) {
                friendsOnlineCount++;
              }
              if (json.data.friendscomcenter[key].presence.isPlaying) {
                friendsPlayingCount++;
              }
            }
          }
          if (friendsPlayingCount > 0) {
            count = friendsPlayingCount.toString();
            status = 'playing';
          }
          else {
            if (friendsOnlineCount > 0) {
              count = friendsOnlineCount.toString();
              status = 'online';
            }
            else {
              count = friendsCount.toString();
              status = 'offline';
            }
          }
        }
        // origin not available
        else {
          count = '0';
          status = 'offline';
        }
        callback(count, status);
      }
      else {
        callback(false);
      }
    });
  };

  window.NotificationsCount = function (callback) {
    xhr('GET', getNotificationsUrlJson(localStorage.game), function (data) {
      var count = '0';

      // no data
      if (data === false) {
        callback(false);
      }

      var json = JSON.parse(data);
      if (json.type == 'success') {
        count = json.data.numUnread.toString();
        callback(count);
      }
      else {
        callback(false);
      }
    });
  }

  // badge renderer
  function render(badge, color, title) {
    chrome.browserAction.setBadgeText({
      text: badge
    });
    chrome.browserAction.setBadgeBackgroundColor({
      color: color
    });
    chrome.browserAction.setTitle({
      title: title
    });
  }

  // update badge
  function updateBadge() {
    //console.log('updateBadge()'); // debug
    var color;
    FriendsCount(function (count, status) {
      //console.log('friends count: ' + count); // debug
      if (count !== false) {
        color = colorOffline;
        if (status == 'playing') {
          color = colorPlaying;
        }
        if (status == 'online') {
          color = colorOnline;
        }
        render((count !== '0' ? count : ''), color, chrome.i18n.getMessage('browserActionDefaultTitle', [count, status]));
      } else {
        render('?', [190, 190, 190, 230], chrome.i18n.getMessage('browserActionErrorTitle'));
      }
    });
  }

  function showNotification() {
    NotificationsCount(function (count) {
      //console.log('notifications count: ' + count); // debug
      if (count !== false && count > 0) {
        var opt = {
          type: "basic",
          title: chrome.i18n.getMessage('notificationTitle'),
          message: chrome.i18n.getMessage('notificationMessage', [count]),
          iconUrl: "icon-48.png",
          buttons: [
            { title: chrome.i18n.getMessage('notificationButton1Title'), iconUrl: "glyphicons_206_ok_2.png" },
            { title: chrome.i18n.getMessage('notificationButton2Title'), iconUrl: "glyphicons_266_flag.png" },
          ]
        };
        var notification = chrome.notifications.create('showNotification', opt, function() {
          // auto clear after 5s
          /*
          setTimeout(function() {
            chrome.notifications.clear('showNotification', function(){});
          }, 5000);
          */
        });
      }
    });
  }

  function isBattlelogUrl(url) {
    return url.indexOf(getHomeUrl(localStorage.game)) == 0;
  }

  function isBattlelogUpdatesUrl(url) {
    return url.indexOf(getUpdateUrl(localStorage.game)) == 0;
  }

  function openBattlelogHomeInTab() {
    // check if Battle is already open
    chrome.tabs.getAllInWindow(undefined, function(tabs) {
      for (var i = 0, tab; tab = tabs[i]; i++) {
        if (tab.url && isBattlelogUrl(tab.url)) {
          chrome.tabs.update(tab.id, {selected: true});
          return;
        }
      }
      chrome.tabs.create({url: getHomeUrl(localStorage.game)});
    });
  }

  function openBattlelogUpdatesInTab() {
    // check if Battlelog is already open
    chrome.tabs.getAllInWindow(undefined, function(tabs) {
      for (var i = 0, tab; tab = tabs[i]; i++) {
        if (tab.url && isBattlelogUpdatesUrl(tab.url)) {
          chrome.tabs.update(tab.id, {selected: true});
          return;
        }
      }
      chrome.tabs.create({url: getUpdateUrl(localStorage.game)});
    });
  }

  // alarms
  chrome.alarms.create('badge', {periodInMinutes: 1});
  if (chrome.notifications
    && localStorage.notifIsActivated === true
    && localStorage.notifFrequency)
  {
    chrome.alarms.create('notification', {periodInMinutes: parseInt(localStorage.notifFrequency)});
  }
  chrome.alarms.onAlarm.addListener(function (alarm) {
    if (alarm.name == 'badge') {
      updateBadge();
    }
    if (alarm.name == 'notification') {
      showNotification();
    }
  });

  // browser action
  chrome.browserAction.onClicked.addListener(function () {
    updateBadge();
    if (chrome.notifications
      && localStorage.notifIsActivated === true)
    {
      showNotification();
    }
    openBattlelogHomeInTab();
  });

  if (chrome.notifications) {
    // notification action
    chrome.notifications.onClicked.addListener(function () {
      openBattlelogHomeInTab();
      chrome.notifications.clear('showNotification', function(){});
    });
    // notification button(s) action
    chrome.notifications.onButtonClicked.addListener(function (notificationId, buttonIndex) {
      //console.log('button index: ' + buttonIndex); // debug
      if (buttonIndex == 1) {
        openBattlelogUpdatesInTab();
      }
      chrome.notifications.clear('showNotification', function(){});
    });
  }

  // message
  chrome.runtime.onMessage.addListener(function () {
    //console.log('onMessage event'); // debug
    updateBadge();
  });

  updateBadge();
})();<|endoftext|>


<commit_before>// ==UserScript==
// @name         Legend Agar.io Extension
// @namespace    Legend Agario Mod
// @version      3.1
// @description  Agario Mod - Legend,Ogario,Kitty,Old Skins,Animated Skins,Language Packs,Manual User Scripts,Chat,60++ Macros/Hotkeys(Tricksplit,Doublesplit,Quick Feeding,Popsplit,Auto Coins,Freeze Cell Macro,Auto respawn)
// @homepage     http://www.legendmod.ml
// @author       Jimboy3100
// @license      MIT
// @icon         https://jimboy3100.github.io/banners/CropedImage128.gif
// @match        http://agar.io/*
// @match        https://talky.io/*
// @match        https://play.google.com/*
// @match        http://ext.fzogar.xyz/ogs/*
// @downloadURL  jimboy3100.github.io/legendmod.user.js
// @updateURL    jimboy3100.github.io/legendmod.user.js
// @run-at       document-start
// @grant        GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant GM_registerMenuCommand
// ==/UserScript==
// Legend Mod by Jimboy3100

var cpickerCSS = '<link href="https://jimboy3100.github.io/bootstrap-colorpicker.min.css" rel="stylesheet"></link>';
var toastrCSS = '<link href="https://jimboy3100.github.io/toastr.min.css" rel="stylesheet"></link>';
var switchCSS = '<link href="https://jimboy3100.github.io/switchery.min.css" rel="stylesheet"></link>';
var rangeCSS = '<link href="https://jimboy3100.github.io/rangeslider.css" rel="stylesheet"></link>';
var perfectCSS = '<link href="https://jimboy3100.github.io/perfect-scrollbar.min.css" rel="stylesheet"></link>';
var faCSS = '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"></link>';
var legendarioCSS = '<link href="http://cdn.ogario.ovh/v3/ogario.v3.css?v=339" rel="stylesheet"></link>';

var keyJS = '';
var cpickerJS = '';
var toastrJS = '';
var switchJS = '';
var rangeJS = '';
var perfectJS = '';
var legendJS = '';
var legendJSniffJS = '';
var legendJSniff2JS = '';
var legendJSniff3JS = '';
var legendarioSniffJS = '';
var legendarioJS = '';

var modVersion = "3.2";

function reqListener () {
    var doc=this.responseText;
    window.stop();
    document.documentElement.innerHTML = "";
    document.open();
    document.write(doc);
  //console.log(this.responseText);
            document.write("", legendarioSniffJS + cpickerCSS + toastrCSS + switchCSS + rangeCSS + perfectCSS + legendarioCSS + faCSS + cpickerJS + toastrJS + switchJS + rangeJS + perfectJS + keyJS + legendJSniff2JS + "");
            document.write("", legendJSniffJS + "</body");
            setTimeout(function() {
            document.write("", legendarioJS + legendJS + legendJSniff3JS +  "" + "");

            document.close();
                }, 1500);
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://agar.io");
oReq.send();

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
<commit_msg>Update codeneeded.js<commit_after>// ==UserScript==
// @name         Legend Agar.io Extension
// @namespace    Legend Agario Mod
// @version      3.2
// @description  Agario Mod - Legend,Ogario,Kitty,Old Skins,Animated Skins,Language Packs,Manual User Scripts,Chat,60++ Macros/Hotkeys(Tricksplit,Doublesplit,Quick Feeding,Popsplit,Auto Coins,Freeze Cell Macro,Auto respawn)
// @homepage     http://www.legendmod.ml
// @author       Jimboy3100
// @license      MIT
// @icon         https://jimboy3100.github.io/banners/CropedImage128.gif
// @match        http://agar.io/*
// @match        https://talky.io/*
// @match        https://play.google.com/*
// @match        http://ext.fzogar.xyz/ogs/*
// @downloadURL  jimboy3100.github.io/legendmod.user.js
// @updateURL    jimboy3100.github.io/legendmod.user.js
// @run-at       document-start
// @grant        GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant GM_registerMenuCommand
// ==/UserScript==
// Legend Mod by Jimboy3100

var cpickerCSS = '<link href="https://jimboy3100.github.io/bootstrap-colorpicker.min.css" rel="stylesheet"></link>';
var toastrCSS = '<link href="https://jimboy3100.github.io/toastr.min.css" rel="stylesheet"></link>';
var switchCSS = '<link href="https://jimboy3100.github.io/switchery.min.css" rel="stylesheet"></link>';
var rangeCSS = '<link href="https://jimboy3100.github.io/rangeslider.css" rel="stylesheet"></link>';
var perfectCSS = '<link href="https://jimboy3100.github.io/perfect-scrollbar.min.css" rel="stylesheet"></link>';
var faCSS = '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"></link>';
var legendarioCSS = '<link href="http://cdn.ogario.ovh/v3/ogario.v3.css?v=339" rel="stylesheet"></link>';

var keyJS = '';
var cpickerJS = '';
var toastrJS = '';
var switchJS = '';
var rangeJS = '';
var perfectJS = '';
var legendJS = '';
var legendJSniffJS = '';
var legendJSniff2JS = '';
var legendJSniff3JS = '';
var legendarioSniffJS = '';
var legendarioJS = '';

var modVersion = "3.2";

function reqListener () {
    var doc=this.responseText;
    window.stop();
    document.documentElement.innerHTML = "";
    document.open();
    document.write(doc);
  //console.log(this.responseText);
            document.write("", legendarioSniffJS + cpickerCSS + toastrCSS + switchCSS + rangeCSS + perfectCSS + legendarioCSS + faCSS + cpickerJS + toastrJS + switchJS + rangeJS + perfectJS + keyJS + legendJSniff2JS + "");
            document.write("", legendJSniffJS + "</body");
            setTimeout(function() {
            document.write("", legendarioJS + legendJS + legendJSniff3JS +  "" + "");

            document.close();
                }, 1500);
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://agar.io");
oReq.send();

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
<|endoftext|>


<commit_before>/*
 *  Large join() needs a valstack check.  Even larger joins run
 *  out of valstack unless the join is done in stages.
 *
 *  These were broken at some point.
 */

/*===
100
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
===*/

/* 100 elements */
tmp = [
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9
];

print(tmp.length);

print(tmp.join(''));

/*===
building
joining
1000000
===*/

/* This was broken at some point: joining happened naively through the
 * valstack whose size topped out for large joins.
 */

tmp = [];

/* The 'tmp' array build becomes sparse (array part abandoned) so this is
 * very memory and CPU intensive now.  It shouldn't affect the join test
 * though.
 */

print('building');
for (i = 1000000; i; i -= 1) {  // funny syntax; current version does not support comparisons yet
	tmp[tmp.length] = 'x';
}

print('joining');
print(tmp.join('').length);

<commit_msg>testcase trivia<commit_after>/*
 *  Large join() needs a valstack check.  Even larger joins run
 *  out of valstack unless the join is done in stages.
 *
 *  These were broken at some point.
 */

/*===
100
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
===*/

/* 100 elements */
tmp = [
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9
];

print(tmp.length);

print(tmp.join(''));

/*===
building
joining
1000000
===*/

/* This was broken at some point: joining happened naively through the
 * valstack whose size topped out for large joins.
 */

tmp = [];
var i;

print('building');
for (i = 1000000; i; i -= 1) {  // funny syntax; current version does not support comparisons yet
	tmp[tmp.length] = 'x';
}

print('joining');
print(tmp.join('').length);

<|endoftext|>


<commit_before>/*
 * jQuery Pines Notify (pnotify) Plugin 1.0
 *
 * Copyright (c) 2009 Hunter Perrin
 *
 * Licensed (along with all of Pines) under the GNU Affero GPL:
 *	  http://www.gnu.org/licenses/agpl.html
 */

(function($) {
	var first_top;
	var history_handle_top;
	var timer;
	$.extend({
		pnotify_remove_all: function () {
			var body = $("body");
			var body_data = body.data("pnotify");
			$.each(body_data, function(){
				if (this.pnotify_remove)
					this.pnotify_remove();
			});
		},
		pnotify_position_all: function () {
			timer = null;
			var body = $("body");
			var next = first_top;
			var body_data = body.data("pnotify");
			$.each(body_data, function(){
				var postop;
				var display = this.css("display");
				if (display != "none") {
					// Calculate the top value, disregarding the scroll, since position=fixed.
					postop = this.offset().top - $(window).scrollTop();
					if (!first_top) {
						first_top = postop;
						next = first_top;
					}
				}
				if (next) {
					if (postop > next) {
						this.animate({top: next+"px"}, {duration: 500, queue: false});
					} else {
						this.css("top", next+"px");
					}
				}
				if (display != "none") {
					next += this.height() + 10;
				}
			});
		},
		pnotify: function(options) {
			var body = $("body");
			var closer;

			// Build main options.
			var opts;
			if (typeof options == "string") {
				opts = $.extend({}, $.pnotify.defaults);
				opts.pnotify_text = options;
			} else {
				opts = $.extend({}, $.pnotify.defaults, options);
			}

			var pnotify = $("
").addClass("ui-widget ui-helper-clearfix ui-pnotify");
			pnotify.container = $("
").addClass("ui-corner-all ui-pnotify-container");
			pnotify.append(pnotify.container);

			pnotify.pnotify_version = "1.0.0";

			pnotify.pnotify_init = function() {
				body.append(pnotify);

				// Add events to stop fading when the user mouses over.
				if (opts.pnotify_hide) {
					pnotify.mouseenter(function(){
						pnotify.stop();
						pnotify.fadeTo("fast", opts.pnotify_opacity);
						pnotify.pnotify_cancel_remove();
					}).mouseleave(function(){
						pnotify.pnotify_queue_remove();
						$.pnotify_position_all();
					});
				}

				if (opts.pnotify_closer) {
					if (closer) closer.remove();
					closer = $("
").addClass("ui-pnotify-closer").css("cursor", "pointer");
					closer.append($("").addClass("ui-icon ui-icon-circle-close"));
					closer.click(function(){
						pnotify.pnotify_remove();
					});
					closer.hide();
					pnotify.container.prepend(closer);
					pnotify.hover(function(){
						closer.show();
					}, function(){
						closer.hide();
					});
				}
			};

			pnotify.pnotify_queue_position = function() {
				if (timer) {
					clearTimeout(timer);
				}
				timer = setTimeout($.pnotify_position_all, 10);
			};

			pnotify.pnotify_display = function() {
				if (pnotify.parent().get()) {
					pnotify.pnotify_init();
				}
				pnotify.pnotify_queue_position();
				// First show it, then set its opacity to 0, then fade into the set opacity.
				pnotify.show().fadeTo(0, 0).fadeTo(opts.pnotify_fade_speed, opts.pnotify_opacity);

				// Now set it to hide.
				if (opts.pnotify_hide) {
					pnotify.pnotify_queue_remove();
				}
			};

			pnotify.pnotify_remove = function() {
				if (pnotify.timer) {
					window.clearTimeout(pnotify.timer);
					pnotify.timer = null;
				}
				pnotify.fadeOut(opts.pnotify_fade_speed, function(){
					pnotify.pnotify_queue_position();
					if (opts.pnotify_remove)
						pnotify.remove();
				});
			};

			pnotify.pnotify_cancel_remove = function() {
				if (pnotify.timer) {
					window.clearTimeout(pnotify.timer);
				}
			};

			pnotify.pnotify_queue_remove = function() {
				pnotify.pnotify_cancel_remove();
				pnotify.timer = window.setTimeout(function(){
					pnotify.pnotify_remove();
				}, (isNaN(opts.pnotify_delay) ? 0 : opts.pnotify_delay));
			};

			if (opts.pnotify_type == "error") {
				pnotify.container.addClass("ui-state-error");
			} else if (opts.pnotify_type == "notice") {
				pnotify.container.addClass("ui-state-highlight");
			}

			if ((opts.pnotify_notice_icon && opts.pnotify_type == "notice") || (opts.pnotify_error_icon && opts.pnotify_type == "error")) {
				var icon = $("
").addClass("ui-pnotify-icon");
				icon.append($("").addClass(opts.pnotify_type == "notice" ? opts.pnotify_notice_icon : opts.pnotify_error_icon));
				pnotify.container.append(icon);
			}

			if (typeof opts.pnotify_title == "string") {
				var title = $("").addClass("ui-pnotify-title");
				title.html(opts.pnotify_title);
				pnotify.container.append(title);
			}

			if (typeof opts.pnotify_text == "string") {
				var text = $("").addClass("ui-pnotify-text");
				text.html(opts.pnotify_text);
				pnotify.container.append(text);
			}

			if (typeof opts.pnotify_width == "string") {
				pnotify.css("width", opts.pnotify_width);
			}

			if (typeof opts.pnotify_min_height == "string") {
				pnotify.container.css("min-height", opts.pnotify_min_height);
			}

			pnotify.hide();

			var body_data = body.data("pnotify");
			if (typeof body_data != "object")
				body_data = Array();
			body_data = $.merge(body_data, [pnotify]);
			body.data("pnotify", body_data);

			pnotify.pnotify_display();

			if (opts.pnotify_history) {
				var body_history = body.data("pnotify_history");
				if (typeof body_history == "undefined") {
					body_history = $("
").addClass("ui-pnotify-history-container ui-state-default ui-corner-bottom");
					body.append(body_history);

					body_history.append($("
Redisplay
").addClass("ui-pnotify-history-header"));
					body_history.append($("<button>All</button>").addClass("ui-pnotify-history-all ui-state-default ui-corner-all").hover(function(){
						$(this).addClass("ui-state-hover");
					}, function(){
						$(this).removeClass("ui-state-hover");
					}).click(function(){
						$.each(body_data, function(){
							if (this.pnotify_display)
								this.pnotify_display();
						});
					}));
					body_history.append($("<button>Last</button>").addClass("ui-pnotify-history-last ui-state-default ui-corner-all").hover(function(){
						$(this).addClass("ui-state-hover");
					}, function(){
						$(this).removeClass("ui-state-hover");
					}).click(function(){
						if (body_data[body_data.length - 1] && body_data[body_data.length - 1].pnotify_display)
							body_data[body_data.length - 1].pnotify_display();
					}));

					var handle = $("").addClass("ui-pnotify-history-pulldown ui-icon ui-icon-grip-dotted-horizontal").mouseenter(function(){
						body_history.animate({top: "0"}, {duration: 100, queue: false})
					});
					body_history.append(handle);
					history_handle_top = handle.offset().top;

					body_history.mouseleave(function(){
						body_history.animate({top: "-"+history_handle_top+"px"}, {duration: 100, queue: false});
					});
					body_history.css({top: "-"+history_handle_top+"px"});

					body.data("pnotify_history", body_history);
				}
			}

			return pnotify;
		}
	});

	$.pnotify.defaults = {
		// Display a pull down menu to redisplay previous notices.
		pnotify_history: true,
		// Width of the notice.
		pnotify_width: "300px",
		// Minimum height of the notice. It will expand to fit content.
		pnotify_min_height: "16px",
		// Type of the notice. "notice" or "error".
		pnotify_type: "notice",
		// The icon class to use if type is notice.
		pnotify_notice_icon: "ui-icon ui-icon-info",
		// The icon class to use if type is error.
		pnotify_error_icon: "ui-icon ui-icon-alert",
		// Speed at which the notice fades in and out. "slow", "def", "fast" or number of milliseconds.
		pnotify_fade_speed: "slow",
		// Opacity to fade to.
		pnotify_opacity: 1,
		// Provide a button for the user to manually close a notice.
		pnotify_closer: true,
		// After a delay, make the notice disappear.
		pnotify_hide: true,
		// Delay in milliseconds before the notice disappears.
		pnotify_delay: 8000,
		// Remove the notice from the DOM after it disappears.
		pnotify_remove: true
	};
})(jQuery);<commit_msg>Moved history handle up.<commit_after>/*
 * jQuery Pines Notify (pnotify) Plugin 1.0
 *
 * Copyright (c) 2009 Hunter Perrin
 *
 * Licensed (along with all of Pines) under the GNU Affero GPL:
 *	  http://www.gnu.org/licenses/agpl.html
 */

(function($) {
	var first_top;
	var history_handle_top;
	var timer;
	$.extend({
		pnotify_remove_all: function () {
			var body = $("body");
			var body_data = body.data("pnotify");
			$.each(body_data, function(){
				if (this.pnotify_remove)
					this.pnotify_remove();
			});
		},
		pnotify_position_all: function () {
			timer = null;
			var body = $("body");
			var next = first_top;
			var body_data = body.data("pnotify");
			$.each(body_data, function(){
				var postop;
				var display = this.css("display");
				if (display != "none") {
					// Calculate the top value, disregarding the scroll, since position=fixed.
					postop = this.offset().top - $(window).scrollTop();
					if (!first_top) {
						first_top = postop;
						next = first_top;
					}
				}
				if (next) {
					if (postop > next) {
						this.animate({top: next+"px"}, {duration: 500, queue: false});
					} else {
						this.css("top", next+"px");
					}
				}
				if (display != "none") {
					next += this.height() + 10;
				}
			});
		},
		pnotify: function(options) {
			var body = $("body");
			var closer;

			// Build main options.
			var opts;
			if (typeof options == "string") {
				opts = $.extend({}, $.pnotify.defaults);
				opts.pnotify_text = options;
			} else {
				opts = $.extend({}, $.pnotify.defaults, options);
			}

			var pnotify = $("
").addClass("ui-widget ui-helper-clearfix ui-pnotify");
			pnotify.container = $("
").addClass("ui-corner-all ui-pnotify-container");
			pnotify.append(pnotify.container);

			pnotify.pnotify_version = "1.0.0";

			pnotify.pnotify_init = function() {
				body.append(pnotify);

				// Add events to stop fading when the user mouses over.
				if (opts.pnotify_hide) {
					pnotify.mouseenter(function(){
						pnotify.stop();
						pnotify.fadeTo("fast", opts.pnotify_opacity);
						pnotify.pnotify_cancel_remove();
					}).mouseleave(function(){
						pnotify.pnotify_queue_remove();
						$.pnotify_position_all();
					});
				}

				if (opts.pnotify_closer) {
					if (closer) closer.remove();
					closer = $("
").addClass("ui-pnotify-closer").css("cursor", "pointer");
					closer.append($("").addClass("ui-icon ui-icon-circle-close"));
					closer.click(function(){
						pnotify.pnotify_remove();
					});
					closer.hide();
					pnotify.container.prepend(closer);
					pnotify.hover(function(){
						closer.show();
					}, function(){
						closer.hide();
					});
				}
			};

			pnotify.pnotify_queue_position = function() {
				if (timer) {
					clearTimeout(timer);
				}
				timer = setTimeout($.pnotify_position_all, 10);
			};

			pnotify.pnotify_display = function() {
				if (pnotify.parent().get()) {
					pnotify.pnotify_init();
				}
				pnotify.pnotify_queue_position();
				// First show it, then set its opacity to 0, then fade into the set opacity.
				pnotify.show().fadeTo(0, 0).fadeTo(opts.pnotify_fade_speed, opts.pnotify_opacity);

				// Now set it to hide.
				if (opts.pnotify_hide) {
					pnotify.pnotify_queue_remove();
				}
			};

			pnotify.pnotify_remove = function() {
				if (pnotify.timer) {
					window.clearTimeout(pnotify.timer);
					pnotify.timer = null;
				}
				pnotify.fadeOut(opts.pnotify_fade_speed, function(){
					pnotify.pnotify_queue_position();
					if (opts.pnotify_remove)
						pnotify.remove();
				});
			};

			pnotify.pnotify_cancel_remove = function() {
				if (pnotify.timer) {
					window.clearTimeout(pnotify.timer);
				}
			};

			pnotify.pnotify_queue_remove = function() {
				pnotify.pnotify_cancel_remove();
				pnotify.timer = window.setTimeout(function(){
					pnotify.pnotify_remove();
				}, (isNaN(opts.pnotify_delay) ? 0 : opts.pnotify_delay));
			};

			if (opts.pnotify_type == "error") {
				pnotify.container.addClass("ui-state-error");
			} else if (opts.pnotify_type == "notice") {
				pnotify.container.addClass("ui-state-highlight");
			}

			if ((opts.pnotify_notice_icon && opts.pnotify_type == "notice") || (opts.pnotify_error_icon && opts.pnotify_type == "error")) {
				var icon = $("
").addClass("ui-pnotify-icon");
				icon.append($("").addClass(opts.pnotify_type == "notice" ? opts.pnotify_notice_icon : opts.pnotify_error_icon));
				pnotify.container.append(icon);
			}

			if (typeof opts.pnotify_title == "string") {
				var title = $("").addClass("ui-pnotify-title");
				title.html(opts.pnotify_title);
				pnotify.container.append(title);
			}

			if (typeof opts.pnotify_text == "string") {
				var text = $("").addClass("ui-pnotify-text");
				text.html(opts.pnotify_text);
				pnotify.container.append(text);
			}

			if (typeof opts.pnotify_width == "string") {
				pnotify.css("width", opts.pnotify_width);
			}

			if (typeof opts.pnotify_min_height == "string") {
				pnotify.container.css("min-height", opts.pnotify_min_height);
			}

			pnotify.hide();

			var body_data = body.data("pnotify");
			if (typeof body_data != "object")
				body_data = Array();
			body_data = $.merge(body_data, [pnotify]);
			body.data("pnotify", body_data);

			pnotify.pnotify_display();

			if (opts.pnotify_history) {
				var body_history = body.data("pnotify_history");
				if (typeof body_history == "undefined") {
					body_history = $("
").addClass("ui-pnotify-history-container ui-state-default ui-corner-bottom");
					body.append(body_history);

					body_history.append($("
Redisplay
").addClass("ui-pnotify-history-header"));
					body_history.append($("<button>All</button>").addClass("ui-pnotify-history-all ui-state-default ui-corner-all").hover(function(){
						$(this).addClass("ui-state-hover");
					}, function(){
						$(this).removeClass("ui-state-hover");
					}).click(function(){
						$.each(body_data, function(){
							if (this.pnotify_display)
								this.pnotify_display();
						});
					}));
					body_history.append($("<button>Last</button>").addClass("ui-pnotify-history-last ui-state-default ui-corner-all").hover(function(){
						$(this).addClass("ui-state-hover");
					}, function(){
						$(this).removeClass("ui-state-hover");
					}).click(function(){
						if (body_data[body_data.length - 1] && body_data[body_data.length - 1].pnotify_display)
							body_data[body_data.length - 1].pnotify_display();
					}));

					var handle = $("").addClass("ui-pnotify-history-pulldown ui-icon ui-icon-grip-dotted-horizontal").mouseenter(function(){
						body_history.animate({top: "0"}, {duration: 100, queue: false})
					});
					body_history.append(handle);
					history_handle_top = handle.offset().top + 2;

					body_history.mouseleave(function(){
						body_history.animate({top: "-"+history_handle_top+"px"}, {duration: 100, queue: false});
					});
					body_history.css({top: "-"+history_handle_top+"px"});

					body.data("pnotify_history", body_history);
				}
			}

			return pnotify;
		}
	});

	$.pnotify.defaults = {
		// Display a pull down menu to redisplay previous notices.
		pnotify_history: true,
		// Width of the notice.
		pnotify_width: "300px",
		// Minimum height of the notice. It will expand to fit content.
		pnotify_min_height: "16px",
		// Type of the notice. "notice" or "error".
		pnotify_type: "notice",
		// The icon class to use if type is notice.
		pnotify_notice_icon: "ui-icon ui-icon-info",
		// The icon class to use if type is error.
		pnotify_error_icon: "ui-icon ui-icon-alert",
		// Speed at which the notice fades in and out. "slow", "def", "fast" or number of milliseconds.
		pnotify_fade_speed: "slow",
		// Opacity to fade to.
		pnotify_opacity: 1,
		// Provide a button for the user to manually close a notice.
		pnotify_closer: true,
		// After a delay, make the notice disappear.
		pnotify_hide: true,
		// Delay in milliseconds before the notice disappears.
		pnotify_delay: 8000,
		// Remove the notice from the DOM after it disappears.
		pnotify_remove: true
	};
})(jQuery);<|endoftext|>


<commit_before>/**
 * Copyright (c) 2008
 * Zhen Peng
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **/

if(!ORYX.Plugins)
	ORYX.Plugins = new Object();

ORYX.Plugins.BPELLayouting = Clazz.extend({

	/**
	 *	Constructor
	 *	@param {Object} Facade: The Facade of the Editor
	 */
	construct: function(facade) {
		this.facade = facade;

		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LAYOUT_BPEL, this.handleLayoutEvent.bind(this));
		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LAYOUT_BPEL_VERTICAL, this.handleLayoutVerticalEvent.bind(this));
		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LAYOUT_BPEL_HORIZONTAL, this.handleLayoutHorizontalEvent.bind(this));
		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LAYOUT_BPEL_SINGLECHILD, this.handleSingleChildLayoutEvent.bind(this));
		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LAYOUT_BPEL_AUTORESIZE, this.handleAutoResizeLayoutEvent.bind(this));
	},

	/**************************** Layout ****************************/

	/**
	 *  realize special BPEL layouting:
	 *  main activity: placed left,
	 *  Handler: placed right.
	 */
	handleLayoutEvent: function(event) {

     	var elements = event.shape.getChildShapes(false);

		// If there are no elements
		if(!elements || elements.length == 0) {
			return;
		};

		var activity = elements.find(function(node) {
				return (Array.indexOf(node.getStencil().roles(), node.getStencil().namespace() + "activity")>= 0);
		    });

     	var eventHandlers = elements.find(function(node) {
				return (node.getStencil().id() == node.getStencil().namespace() + "eventHandlers");
			});

		var faultHandlers = elements.find(function(node) {
				return (node.getStencil().id() == node.getStencil().namespace() + "faultHandlers");
			});

		var compensationHandler = elements.find(function(node) {
				return (node.getStencil().id() == node.getStencil().namespace() + "compensationHandler");
			});

		var terminationHandler = elements.find(function(node) {
				return (node.getStencil().id() == node.getStencil().namespace() + "terminationHandler");
			});

		var nextLeftBound = 30;
		var nextUpperBound = 30;

		// handle Activity
		if (activity){
			activity.bounds.moveTo(nextLeftBound, nextUpperBound);
			nextLeftBound = activity.bounds.lowerRight().x + 30;
		}
		// handle EventHanlders
		if (eventHandlers){
			eventHandlers.bounds.moveTo(nextLeftBound, nextUpperBound);
			nextUpperBound = eventHandlers.bounds.lowerRight().y + 10;
		}
		// handle FaultHandlers
		if (faultHandlers){
			faultHandlers.bounds.moveTo(nextLeftBound, nextUpperBound);
			nextUpperBound = faultHandlers.bounds.lowerRight().y + 10;
		}
		// handle CompensationHandler
		if (compensationHandler){
			compensationHandler.bounds.moveTo(nextLeftBound, nextUpperBound);
			nextUpperBound = compensationHandler.bounds.lowerRight().y + 10;
		}
		// handle TerminationHandler
     	if (terminationHandler){
			terminationHandler.bounds.moveTo(nextLeftBound, nextUpperBound);
		}

		this.autoResizeLayout(event);

		return;

	},

	handleLayoutVerticalEvent: function(event) {

		var elements = event.shape.getChildShapes(false);

		// If there are no elements
		if(!elements || elements.length == 0) {
			return;
		};

		// remove all shapes into a column
		elements.each(function(element){
			var ul = element.bounds.upperLeft();
			element.bounds.moveTo(30, ul.y);
		});

		// Sort top-down
		elements = elements.sortBy(function(element){
			return element.bounds.upperLeft().y;
		});

		var lastUpperYPosition = 0;
		// Arrange shapes
		elements.each(function(element){

			var ul = element.bounds.upperLeft();
			var oldUlY = ul.y;

			ul.y = lastUpperYPosition + 30;
			lastUpperYPosition = ul.y + element.bounds.height();

			if ((ul.y != oldUlY)) {
				element.bounds.moveTo(30, ul.y);
			}
		});

		this.autoResizeLayout(event);

		return;
	},

	handleLayoutHorizontalEvent: function(event) {

		var elements = event.shape.getChildShapes(false);

		// If there are no elements
		if(!elements || elements.length == 0) {
			return;
		};

		// remove all shapes in a row
		elements.each(function(element){
			var ul = element.bounds.upperLeft();
			element.bounds.moveTo(ul.x, 30);
		});

		// Sort left-right
		elements = elements.sortBy(function(element){
			return element.bounds.upperLeft().x;
		});

		var lastLeftXPosition = 0;

		// Arrange shapes on rows (align left)
		elements.each(function(element){

			var ul = element.bounds.upperLeft();
			var oldUlX = ul.x;

			ul.x = lastLeftXPosition + 30;
			lastLeftXPosition = ul.x + element.bounds.width();

			if ((ul.x != oldUlX)) {
				element.bounds.moveTo(ul.x, 30);
			}
		});

		this.autoResizeLayout(event);

		return;
	},

	handleSingleChildLayoutEvent: function(event) {

		var elements = event.shape.getChildShapes(false);

		// If there are no elements
		if(!elements || elements.length == 0) {
			return;
		};

		elements.first().bounds.moveTo(30, 30);

		this.autoResizeLayout(event);

		return;
	},

	handleAutoResizeLayoutEvent: function(event) {

		this.autoResizeLayout(event);
	},

	/**
	 * Resizes the shape to the bounds of the child shapes
	 */
	autoResizeLayout: function(event) {

		var elements = event.shape.getChildShapes(false);

		if (elements.length > 0) {

		    elements = elements.sortBy(function(element){
				return element.bounds.lowerRight().x;
		    });

			var rightBound = elements.last().bounds.lowerRight().x;

		    elements = elements.sortBy(function(element){
				return element.bounds.lowerRight().y;
		    });

			var lowerBound = elements.last().bounds.lowerRight().y;

			var ul = event.shape.bounds.upperLeft();

			event.shape.bounds.set(ul.x, ul.y, ul.x + rightBound + 30, ul.y + lowerBound + 30);
		};

		return;
	}

});<commit_msg>modified bpelLayout: the width of handlers will be checked and changed, so that all the handlers have the same width; in flow, there must be at least 30 space between children nodes and flow's left and upper bounds   <commit_after>/**
 * Copyright (c) 2008
 * Zhen Peng
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **/

if(!ORYX.Plugins)
	ORYX.Plugins = new Object();

ORYX.Plugins.BPELLayouting = Clazz.extend({

	/**
	 *	Constructor
	 *	@param {Object} Facade: The Facade of the Editor
	 */
	construct: function(facade) {
		this.facade = facade;

		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LAYOUT_BPEL, this.handleLayoutEvent.bind(this));
		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LAYOUT_BPEL_VERTICAL, this.handleLayoutVerticalEvent.bind(this));
		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LAYOUT_BPEL_HORIZONTAL, this.handleLayoutHorizontalEvent.bind(this));
		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LAYOUT_BPEL_SINGLECHILD, this.handleSingleChildLayoutEvent.bind(this));
		this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LAYOUT_BPEL_AUTORESIZE, this.handleAutoResizeLayoutEvent.bind(this));
	},

	/**************************** Layout ****************************/

	/**
	 *  realize special BPEL layouting:
	 *  main activity: placed left,
	 *  Handler: placed right.
	 */
	handleLayoutEvent: function(event) {

     	var elements = event.shape.getChildShapes(false);

		// If there are no elements
		if(!elements || elements.length == 0) {
			return;
		};

		var activity = elements.find(function(node) {
				return (Array.indexOf(node.getStencil().roles(), node.getStencil().namespace() + "activity")>= 0);
				        //& !(node.getStencil().id() == node.getStencil().namespace() + "scope"));
		    });

     	var eventHandlers = elements.find(function(node) {
				return (node.getStencil().id() == node.getStencil().namespace() + "eventHandlers");
			});

		var faultHandlers = elements.find(function(node) {
				return (node.getStencil().id() == node.getStencil().namespace() + "faultHandlers");
			});

		var compensationHandler = elements.find(function(node) {
				return (node.getStencil().id() == node.getStencil().namespace() + "compensationHandler");
			});

		var terminationHandler = elements.find(function(node) {
				return (node.getStencil().id() == node.getStencil().namespace() + "terminationHandler");
			});

		var nextLeftBound = 30;
		var nextUpperBound = 30;
		var width;
		var maxWidth = 0;

		// handle Activity
		if (activity){
			activity.bounds.moveTo(nextLeftBound, nextUpperBound);
			nextLeftBound = activity.bounds.lowerRight().x + 30;
		}
		// handle EventHanlders
		if (eventHandlers){
			eventHandlers.bounds.moveTo(nextLeftBound, nextUpperBound);
			nextUpperBound = eventHandlers.bounds.lowerRight().y + 10;

			// record maximal width
			width = eventHandlers.bounds.width();
			if (width > maxWidth){
				maxWidth = width;
			}
		}
		// handle FaultHandlers
		if (faultHandlers){
			faultHandlers.bounds.moveTo(nextLeftBound, nextUpperBound);
			nextUpperBound = faultHandlers.bounds.lowerRight().y + 10;

			// record maximal width
			width = faultHandlers.bounds.width();
			if (width > maxWidth){
				maxWidth = width;
			}
		}
		// handle CompensationHandler
		if (compensationHandler){
			compensationHandler.bounds.moveTo(nextLeftBound, nextUpperBound);
			nextUpperBound = compensationHandler.bounds.lowerRight().y + 10;

			// record maximal width
			width = compensationHandler.bounds.width();
			if (width > maxWidth){
				maxWidth = width;
			}
		}

		// handle TerminationHandler
     	if (terminationHandler){
			terminationHandler.bounds.moveTo(nextLeftBound, nextUpperBound);

			// record maximal width
			width = terminationHandler.bounds.width();
			if (width > maxWidth){
				maxWidth = width;
			}
		}

		// resize all the handlers with the same width
		if (width > 0){
			var ul;
			var lr;

			if (eventHandlers){
				width = eventHandlers.bounds.width();
				if (width < maxWidth){
					ul = eventHandlers.bounds.upperLeft();
					lr = eventHandlers.bounds.lowerRight();
					eventHandlers.bounds.set(ul.x, ul.y, ul.x + maxWidth, lr.y);
				}
			}

			if (faultHandlers){
				width = faultHandlers.bounds.width();
				if (width < maxWidth){
					ul = faultHandlers.bounds.upperLeft();
					lr = faultHandlers.bounds.lowerRight();
					faultHandlers.bounds.set(ul.x, ul.y, ul.x + maxWidth, lr.y);
				}
			}

			if (compensationHandler){
				width = compensationHandler.bounds.width();
				if (width < maxWidth){
					ul = compensationHandler.bounds.upperLeft();
					lr = compensationHandler.bounds.lowerRight();
					compensationHandler.bounds.set(ul.x, ul.y, ul.x + maxWidth, lr.y);
				}
			}

	     	if (terminationHandler){
				width = terminationHandler.bounds.width();
				if (width < maxWidth){
					ul = terminationHandler.bounds.upperLeft();
					lr = terminationHandler.bounds.lowerRight();
					terminationHandler.bounds.set(ul.x, ul.y, ul.x + maxWidth, lr.y);
				}
			}
		}

		this.autoResizeLayout(event);

		return;

	},

	handleLayoutVerticalEvent: function(event) {

		var elements = event.shape.getChildShapes(false);

		// If there are no elements
		if(!elements || elements.length == 0) {
			return;
		};

		// remove all shapes into a column
		elements.each(function(element){
			var ul = element.bounds.upperLeft();
			element.bounds.moveTo(30, ul.y);
		});

		// Sort top-down
		elements = elements.sortBy(function(element){
			return element.bounds.upperLeft().y;
		});

		var lastUpperYPosition = 0;
		// Arrange shapes
		elements.each(function(element){

			var ul = element.bounds.upperLeft();
			var oldUlY = ul.y;

			ul.y = lastUpperYPosition + 30;
			lastUpperYPosition = ul.y + element.bounds.height();

			if ((ul.y != oldUlY)) {
				element.bounds.moveTo(30, ul.y);
			}
		});

		this.autoResizeLayout(event);

		return;
	},

	handleLayoutHorizontalEvent: function(event) {

		var elements = event.shape.getChildShapes(false);

		// If there are no elements
		if(!elements || elements.length == 0) {
			return;
		};

		// remove all shapes in a row
		elements.each(function(element){
			var ul = element.bounds.upperLeft();
			element.bounds.moveTo(ul.x, 30);
		});

		// Sort left-right
		elements = elements.sortBy(function(element){
			return element.bounds.upperLeft().x;
		});

		var lastLeftXPosition = 0;

		// Arrange shapes on rows (align left)
		elements.each(function(element){

			var ul = element.bounds.upperLeft();
			var oldUlX = ul.x;

			ul.x = lastLeftXPosition + 30;
			lastLeftXPosition = ul.x + element.bounds.width();

			if ((ul.x != oldUlX)) {
				element.bounds.moveTo(ul.x, 30);
			}
		});

		this.autoResizeLayout(event);

		return;
	},

	handleSingleChildLayoutEvent: function(event) {

		var elements = event.shape.getChildShapes(false);

		// If there are no elements
		if(!elements || elements.length == 0) {
			return;
		};

		elements.first().bounds.moveTo(30, 30);

		this.autoResizeLayout(event);

		return;
	},

	handleAutoResizeLayoutEvent: function(event) {

		var elements = event.shape.getChildShapes(false);

		// If there are no elements
		if(!elements || elements.length == 0) {
			return;
		};

		elements.each(function(element){

			var ul = element.bounds.upperLeft();

			if ((ul.x < 30)) {
				element.bounds.moveTo(30, ul.y);
				ul = element.bounds.upperLeft();
			}

			if ((ul.y < 30)) {
				element.bounds.moveTo(ul.x, 30);
			}
		});

		this.autoResizeLayout(event);
	},

	/**
	 * Resizes the shape to the bounds of the child shapes
	 */
	autoResizeLayout: function(event) {

		var elements = event.shape.getChildShapes(false);

		if (elements.length > 0) {

		    elements = elements.sortBy(function(element){
				return element.bounds.lowerRight().x;
		    });

			var rightBound = elements.last().bounds.lowerRight().x;

		    elements = elements.sortBy(function(element){
				return element.bounds.lowerRight().y;
		    });

			var lowerBound = elements.last().bounds.lowerRight().y;

			var ul = event.shape.bounds.upperLeft();

			event.shape.bounds.set(ul.x, ul.y, ul.x + rightBound + 30, ul.y + lowerBound + 30);
		};

		return;
	}

});<|endoftext|>


<commit_before>module.exports = SessionSockets;

function SessionSockets(io, sessionStore, cookieParser, key) {
  key = typeof key === 'undefined' ? 'connect.sid' : key;
  var sessionSockets = this;

  this.on = function(event, callback) {
    return bind(event, callback, io.sockets);
  };

  this.of = function(namespace) {
    return {
      on: function(event, callback) {
        return bind(event, callback, io.of(namespace));
      }
    };
  };

  this.getSession = function(socket, callback) {
    cookieParser(socket.handshake, {}, function (parseErr) {
      sessionStore.load(findCookie(socket.handshake), function (storeErr, session) {
        var err = resolveErr(parseErr, storeErr, session);
        callback(err, session);
      });
    });
  };

  function bind(event, callback, namespace) {
    namespace.on(event, function (socket) {
      sessionSockets.getSession(socket, function (err, session) {
        callback(err, socket, session);
      });
    });
  }

  function findCookie(handshake) {
    if (handshake)
      return (handshake.secureCookies && handshake.secureCookies[key]) ||
             (handshake.signedCookies && handshake.signedCookies[key]) ||
             (handshake.cookies && handshake.cookies[key]);
  }

  function resolveErr(parseErr, storeErr, session) {
    var err = parseErr || storeErr || null;
    if (!err && !session) err = new Error('Could not lookup session by key: ' + key);
    return err;
  }
}<commit_msg>Delete session.socket.io.js<commit_after><|endoftext|>


<commit_before>var React = require("react");
var Router = require('react-router');
var Actions = require("./ActionsCreator");
var Store = require("./Store");
var ReactIntl = require("react-intl")
var FormattedRelative = ReactIntl.FormattedRelative;
var { Route, DefaultRoute, RouteHandler, Link } = Router;

   var DeploymentRow = React.createClass({
    mixins:[Router.Navigation],

    navigate:function(){
      this.transitionTo("deployment",{Id:this.props.Deployment.Id});
    },

    render:function(){
      if(this.props.Deployment.Status==0){
        return(

             Queued
            {this.props.Deployment.Name} - {this.props.Deployment.Configuration}
            {this.props.Deployment.Version}
            {this.props.Deployment.UserName}

);
      } else if(this.props.Deployment.Status==1){
        return(

             Running
            {this.props.Deployment.Name} - {this.props.Deployment.Configuration}
            {this.props.Deployment.Version}
            {this.props.Deployment.UserName}
            <FormattedRelative value={this.props.Deployment.StartDate} />

);
      } else if(this.props.Deployment.Status==2){
        return(

              Succeeded
            {this.props.Deployment.Name} - {this.props.Deployment.Configuration}
            {this.props.Deployment.Version}
            {this.props.Deployment.UserName}
            <FormattedRelative value={this.props.Deployment.StartDate} />

);
      } else{
        return(

             Failed
            {this.props.Deployment.Name} - {this.props.Deployment.Configuration}
            {this.props.Deployment.Version}
            {this.props.Deployment.UserName}
            <FormattedRelative value={this.props.Deployment.StartDate} />

);
      }
    }
  });

  var DeploymentsPage = React.createClass({

    getInitialState: function() {
      return {
        deployments : Store.getAll()
      };
    },

    componentDidMount: function() {
      Store.addChangeListener(this._onChange);
      Actions.updateDeployments();
    },

    componentWillUnmount: function() {
      Store.removeChangeListener(this._onChange);
    },

    render: function () {

      return(

Deployments:

Status	Application	Version	Started by

          {this.state.deployments.map(x => (
              <DeploymentRow Deployment={x} />
            ))}

)
      },

      _onChange: function(){
        this.setState({
          deployments : Store.getAll()
        })
      }
    });

    module.exports = DeploymentsPage;
<commit_msg>Removedd wording from deployments page<commit_after>var React = require("react");
var Router = require('react-router');
var Actions = require("./ActionsCreator");
var Store = require("./Store");
var ReactIntl = require("react-intl")
var FormattedRelative = ReactIntl.FormattedRelative;
var { Route, DefaultRoute, RouteHandler, Link } = Router;

   var DeploymentRow = React.createClass({
    mixins:[Router.Navigation],

    navigate:function(){
      this.transitionTo("deployment",{Id:this.props.Deployment.Id});
    },

    render:function(){
      if(this.props.Deployment.Status==0){
        return(

            {this.props.Deployment.Name} - {this.props.Deployment.Configuration}
            {this.props.Deployment.Version}
            {this.props.Deployment.UserName}

);
      } else if(this.props.Deployment.Status==1){
        return(

            {this.props.Deployment.Name} - {this.props.Deployment.Configuration}
            {this.props.Deployment.Version}
            {this.props.Deployment.UserName}
            <FormattedRelative value={this.props.Deployment.StartDate} />

);
      } else if(this.props.Deployment.Status==2){
        return(

            {this.props.Deployment.Name} - {this.props.Deployment.Configuration}
            {this.props.Deployment.Version}
            {this.props.Deployment.UserName}
            <FormattedRelative value={this.props.Deployment.StartDate} />

);
      } else{
        return(

            {this.props.Deployment.Name} - {this.props.Deployment.Configuration}
            {this.props.Deployment.Version}
            {this.props.Deployment.UserName}
            <FormattedRelative value={this.props.Deployment.StartDate} />

);
      }
    }
  });

  var DeploymentsPage = React.createClass({

    getInitialState: function() {
      return {
        deployments : Store.getAll()
      };
    },

    componentDidMount: function() {
      Store.addChangeListener(this._onChange);
      Actions.updateDeployments();
    },

    componentWillUnmount: function() {
      Store.removeChangeListener(this._onChange);
    },

    render: function () {

      return(

Deployments:

Status	Application	Version	Started by

          {this.state.deployments.map(x => (
              <DeploymentRow Deployment={x} />
            ))}

)
      },

      _onChange: function(){
        this.setState({
          deployments : Store.getAll()
        })
      }
    });

    module.exports = DeploymentsPage;
<|endoftext|>