<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// 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.

'use strict';

var parallel = require('run-parallel');
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;

var errors = require('./errors');

var DEFAULT_RETRY_LIMIT = 5;

function TChannelRequest(channel, options) {
    options = options || {};
    if (options.streamed) {
        throw new Error('streaming request federation not supported');
    }
    var self = this;
    EventEmitter.call(self);
    self.channel = channel;
    self.logger = self.channel.logger;
    self.random = self.channel.random;
    self.timers = self.channel.timers;

    self.options = options;
    self.triedRemoteAddrs = {};
    self.outReqs = [];
    self.timeout = self.options.timeout;
    self.limit = self.options.retryLimit || DEFAULT_RETRY_LIMIT;
    self.start = 0;
    self.end = 0;
    self.elapsed = 0;

    self.service = options.service || '';
    self.headers = self.options.headers || {}; // so that as-foo can punch req.headers.X
    self.options.headers = self.headers; // for passing to peer.request(opts) later

    self.arg1 = null;
    self.arg2 = null;
    self.arg3 = null;

    self.err = null;
    self.res = null;
    self.on('error', self.onError);
    self.on('response', self.onResponse);
}

inherits(TChannelRequest, EventEmitter);

TChannelRequest.prototype.type = 'tchannel.request';

TChannelRequest.prototype.onError = function onError(err) {
    var self = this;
    if (!self.end) self.end = self.timers.now();
    self.err = err;
};

TChannelRequest.prototype.onResponse = function onResponse(res) {
    var self = this;
    if (!self.end) self.end = self.timers.now();
    self.res = res;
};

TChannelRequest.prototype.hookupStreamCallback = function hookupCallback(callback) {
    throw new Error('not implemented');
};

TChannelRequest.prototype.hookupCallback = function hookupCallback(callback) {
    var self = this;
    if (callback.canStream) {
        return self.hookupStreamCallback(callback);
    }
    var called = false;

    self.on('error', onError);
    self.on('response', onResponse);

    function onError(err) {
        if (called) return;
        called = true;
        callback(err, null, null, null);
    }

    function onResponse(res) {
        if (called) return;
        called = true;
        withArg23(res, callback);
    }

    return self;
};

TChannelRequest.prototype.choosePeer = function choosePeer() {
    var self = this;
    return self.channel.peers.choosePeer(self, self.options);
};

TChannelRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;
    self.arg1 = arg1;
    self.arg2 = arg2;
    self.arg3 = arg3;
    if (callback) {
        self.hookupCallback(callback);
    }
    self.start = self.timers.now();
    self.resend();
};

TChannelRequest.prototype.resend = function resend() {
    var self = this;

    var peer = self.choosePeer();
    if (!peer) {
        if (self.outReqs.length) {
            var lastReq = self.outReqs[self.outReqs.length - 1];
            if (lastReq.err) self.emit('error', lastReq.err);
            else self.emit('response', lastReq.res);
        } else {
            self.emit('error', errors.NoPeerAvailable());
        }
        return;
    }

    var outReq = peer.request(self.options);
    self.outReqs.push(outReq);

    self.triedRemoteAddrs[outReq.remoteAddr] = (self.triedRemoteAddrs[outReq.remoteAddr] || 0) + 1;
    outReq.on('response', onResponse);
    outReq.on('error', onError);
    outReq.send(self.arg1, self.arg2, self.arg3);

    function onError(err) {
        var now = self.timers.now();
        self.elapsed = now - self.start;
        if (self.elapsed < self.timeout && self.shouldRetry(err)) {
            process.nextTick(deferResend);
        } else {
            self.emit('error', err);
        }
    }

    function onResponse(res) {
        withArg23(res, function onArg23(err, res, arg2, arg3) {
            var now = self.timers.now();
            self.elapsed = now - self.start;
            if (self.elapsed < self.timeout &&
                self.shouldRetry(err, res, arg2, arg3)) {
                process.nextTick(deferResend);
            } else if (err) {
                self.emit('error', err);
            } else {
                self.emit('response', res);
            }
        });
    }

    function deferResend() {
        self.resend();
    }
};

TChannelRequest.prototype.shouldRetry = function shouldRetry(err, res, arg2, arg3) {
    var self = this;

    if (self.outReqs.length >= self.retryLimit) {
        return false;
    }

    if (err) {
        switch (err.type) {
            case 'tchannel.bad-request':
            case 'tchannel.canceled':
                return false;

            case 'tchannel.socket':
            case 'tchannel.timeout':
            case 'tchannel.busy':
            case 'tchannel.declined':
            case 'tchannel.unexpected':
            case 'tchannel.protocol':
                return true;

            default:
                self.logger.error('unknown error type in request retry', {
                    error: err
                });
                return true;
        }
    }

    if (!res.ok && self.options.shouldApplicationRetry) {
        return self.options.shouldApplicationRetry(self, res, arg2, arg3);
    }

    return false;
};

module.exports = TChannelRequest;

function withArg23(res, callback) {
    if (!res.streamed) {
        callback(null, res, res.arg2, res.arg3);
        return;
    }
    parallel({
        arg2: res.arg2.onValueReady,
        arg3: res.arg3.onValueReady
    }, compatCall);
    function compatCall(err, args) {
        callback(err, res, args.arg2, args.arg3);
    }
}
<commit_msg>TChannelRequest: add a resend sanity limit<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// 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.

'use strict';

var parallel = require('run-parallel');
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;

var errors = require('./errors');

var DEFAULT_RETRY_LIMIT = 5;

function TChannelRequest(channel, options) {
    options = options || {};
    if (options.streamed) {
        throw new Error('streaming request federation not supported');
    }
    var self = this;
    EventEmitter.call(self);
    self.channel = channel;
    self.logger = self.channel.logger;
    self.random = self.channel.random;
    self.timers = self.channel.timers;

    self.options = options;
    self.triedRemoteAddrs = {};
    self.outReqs = [];
    self.timeout = self.options.timeout;
    self.limit = self.options.retryLimit || DEFAULT_RETRY_LIMIT;
    self.start = 0;
    self.end = 0;
    self.elapsed = 0;
    self.resendSanity = 0;

    self.service = options.service || '';
    self.headers = self.options.headers || {}; // so that as-foo can punch req.headers.X
    self.options.headers = self.headers; // for passing to peer.request(opts) later

    self.arg1 = null;
    self.arg2 = null;
    self.arg3 = null;

    self.err = null;
    self.res = null;
    self.on('error', self.onError);
    self.on('response', self.onResponse);
}

inherits(TChannelRequest, EventEmitter);

TChannelRequest.prototype.type = 'tchannel.request';

TChannelRequest.prototype.onError = function onError(err) {
    var self = this;
    if (!self.end) self.end = self.timers.now();
    self.err = err;
};

TChannelRequest.prototype.onResponse = function onResponse(res) {
    var self = this;
    if (!self.end) self.end = self.timers.now();
    self.res = res;
};

TChannelRequest.prototype.hookupStreamCallback = function hookupCallback(callback) {
    throw new Error('not implemented');
};

TChannelRequest.prototype.hookupCallback = function hookupCallback(callback) {
    var self = this;
    if (callback.canStream) {
        return self.hookupStreamCallback(callback);
    }
    var called = false;

    self.on('error', onError);
    self.on('response', onResponse);

    function onError(err) {
        if (called) return;
        called = true;
        callback(err, null, null, null);
    }

    function onResponse(res) {
        if (called) return;
        called = true;
        withArg23(res, callback);
    }

    return self;
};

TChannelRequest.prototype.choosePeer = function choosePeer() {
    var self = this;
    return self.channel.peers.choosePeer(self, self.options);
};

TChannelRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;
    self.arg1 = arg1;
    self.arg2 = arg2;
    self.arg3 = arg3;
    if (callback) {
        self.hookupCallback(callback);
    }
    self.start = self.timers.now();
    self.resendSanity = self.limit + 1;
    self.resend();
};

TChannelRequest.prototype.resend = function resend() {
    var self = this;

    var peer = self.choosePeer();
    if (!peer) {
        if (self.outReqs.length) {
            var lastReq = self.outReqs[self.outReqs.length - 1];
            if (lastReq.err) self.emit('error', lastReq.err);
            else self.emit('response', lastReq.res);
        } else {
            self.emit('error', errors.NoPeerAvailable());
        }
        return;
    }

    var outReq = peer.request(self.options);
    self.outReqs.push(outReq);

    self.triedRemoteAddrs[outReq.remoteAddr] = (self.triedRemoteAddrs[outReq.remoteAddr] || 0) + 1;
    outReq.on('response', onResponse);
    outReq.on('error', onError);
    outReq.send(self.arg1, self.arg2, self.arg3);

    function onError(err) {
        var now = self.timers.now();
        self.elapsed = now - self.start;
        if (self.elapsed < self.timeout && self.shouldRetry(err)) {
            deferResend();
        } else {
            self.emit('error', err);
        }
    }

    function onResponse(res) {
        withArg23(res, function onArg23(err, res, arg2, arg3) {
            var now = self.timers.now();
            self.elapsed = now - self.start;
            if (self.elapsed < self.timeout &&
                self.shouldRetry(err, res, arg2, arg3)) {
                deferResend();
            } else if (err) {
                self.emit('error', err);
            } else {
                self.emit('response', res);
            }
        });
    }

    function deferResend() {
        if (--self.resendSanity <= 0) {
            throw new Error('TChannelRequest out of resend sanity');
        } else {
            process.nextTick(doResend);
        }
    }

    function doResend() {
        self.resend();
    }
};

TChannelRequest.prototype.shouldRetry = function shouldRetry(err, res, arg2, arg3) {
    var self = this;

    if (self.outReqs.length >= self.retryLimit) {
        return false;
    }

    if (err) {
        switch (err.type) {
            case 'tchannel.bad-request':
            case 'tchannel.canceled':
                return false;

            case 'tchannel.socket':
            case 'tchannel.timeout':
            case 'tchannel.busy':
            case 'tchannel.declined':
            case 'tchannel.unexpected':
            case 'tchannel.protocol':
                return true;

            default:
                self.logger.error('unknown error type in request retry', {
                    error: err
                });
                return true;
        }
    }

    if (!res.ok && self.options.shouldApplicationRetry) {
        return self.options.shouldApplicationRetry(self, res, arg2, arg3);
    }

    return false;
};

module.exports = TChannelRequest;

function withArg23(res, callback) {
    if (!res.streamed) {
        callback(null, res, res.arg2, res.arg3);
        return;
    }
    parallel({
        arg2: res.arg2.onValueReady,
        arg3: res.arg3.onValueReady
    }, compatCall);
    function compatCall(err, args) {
        callback(err, res, args.arg2, args.arg3);
    }
}
<|endoftext|>


<commit_before>function find(data, path) {
	/*
	Context: Given a JS object and a string, return as if string was an eval
	Example: find({"names": {"john":5, "stacy":34}}, ["names", "john"]) => 5}

	This is actually a cool little piece of code IMO. The recursion loops through each argument and applys them one by one to the data
	*/
	if (path.length === 0){
		return data;
	}

	return find(data[path.shift()], path);
}

// List of tables that are checked out
var checkout = {};

request = {

	error: function (msg) {
		return {'status': 'error', "data": msg}
	},

	// Get request
	get: function(table, query, val) {
		// If it's just a table, they want a table.
		if (query === undefined) {
			return table;
		}

		// If they included a filer, find and apply
		if (val != undefined) {
			// Just converts String -> Function
			var fn_val = new Function("x", "return " + val);
			return find(table, query).filter(fn_val);
		}

		// Else, they have the want a query
		else {
			return find(table, query);
		}
	},

	// Put request
	put: function(table, query, val) {
		if (query === undefined) {
			return error("bad query");
		}

		else {
			//I have no idea how to do this. I'll try again tomorrow
		}
	},

	// Checkout request
	checkout: function(table, token) {
		//If it's not taken (false or undefined)
		if (!checkout[table]){
			// Set it to the user's token
			checkout[table] = token;
			return "sucess";
		}

		// Else, it's taken, so tell the user
		else {
			return "table checked out";
		}
	},

	// Checkin request
	checkin: function(table, token) {
		//If it's not taken (false or undefined)
		if (!checkout[table]){
			return "table not checked out";
		}

		// If the user's token works, let them know
		if (checkout[table] === token){
			checkout[table] = false;
			return "sucess";
		}

		// Else, tell user they failed
		else {
			return "token table mismatch";
		}
	}
}

module.exports = request;<commit_msg>Oh. My. God. Last night I was thinking about the problem and I was pretty sure I solved it. It's the same solution I've been trying, but in my head I actually implemented it. I wrote it down and *POOF* it actually worked. Good job me.<commit_after>function find(data, path) {
	/*
	Context: Given a JS object and a string, return as if string was an eval
	Example: find({"names": {"john":5, "stacy":34}}, ["names", "john"]) => 5}

	This is actually a cool little piece of code IMO. The recursion loops through each argument and applys them one by one to the data
	*/
	if (path.length === 0){
		return data;
	}

	return find(data[path.shift()], path);
}

function update(data, path, value) {
	if (path.length === 1){
		data[path[0]] = value;
		return data;
	}

	data[path[0]] = update(data[path.shift()], path, value);
	return data
}

// List of tables that are checked out
var checkout = {};

request = {

	error: function (msg) {
		return {'status': 'error', "data": msg}
	},

	// Get request
	get: function(table, query, val) {
		// If it's just a table, they want a table.
		if (query === undefined) {
			return table;
		}

		// If they included a filer, find and apply
		if (val != undefined) {
			// Just converts String -> Function
			var fn_val = new Function("x", "return " + val);
			return find(table, query).filter(fn_val);
		}

		// Else, they have the want a query
		else {
			return find(table, query);
		}
	},

	// Put request
	put: function(table, query, val) {
		if (query === undefined) {
			return error("bad query");
		}

		else {
			data = update(table, query, val);
		}
	},

	// Checkout request
	checkout: function(table, token) {
		//If it's not taken (false or undefined)
		if (!checkout[table]){
			// Set it to the user's token
			checkout[table] = token;
			return "sucess";
		}

		// Else, it's taken, so tell the user
		else {
			return "table checked out";
		}
	},

	// Checkin request
	checkin: function(table, token) {
		//If it's not taken (false or undefined)
		if (!checkout[table]){
			return "table not checked out";
		}

		// If the user's token works, let them know
		if (checkout[table] === token){
			checkout[table] = false;
			return "sucess";
		}

		// Else, tell user they failed
		else {
			return "token table mismatch";
		}
	}
}

module.exports = request;<|endoftext|>


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

  var globals = typeof window === 'undefined' ? global : window;
  if (typeof globals.require === 'function') return;

  var modules = {};
  var cache = {};
  var has = ({}).hasOwnProperty;

  var aliases = {};

  var endsWith = function(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
  };

  var unalias = function(alias, loaderPath) {
    var start = 0;
    if (loaderPath) {
      if (loaderPath.indexOf('components/' === 0)) {
        start = 'components/'.length;
      }
      if (loaderPath.indexOf('/', start) > 0) {
        loaderPath = loaderPath.substring(start, loaderPath.indexOf('/', start));
      }
    }
    var result = aliases[alias + '/index.js'] || aliases[loaderPath + '/deps/' + alias + '/index.js'];
    if (result) {
      return 'components/' + result.substring(0, result.length - '.js'.length);
    }
    return alias;
  };

  var expand = (function() {
    var reg = /^\.\.?(\/|$)/;
    return function(root, name) {
      var results = [], parts, part;
      parts = (reg.test(name) ? root + '/' + name : name).split('/');
      for (var i = 0, length = parts.length; i < length; i++) {
        part = parts[i];
        if (part === '..') {
          results.pop();
        } else if (part !== '.' && part !== '') {
          results.push(part);
        }
      }
      return results.join('/');
    };
  })();
  var dirname = function(path) {
    return path.split('/').slice(0, -1).join('/');
  };

  var localRequire = function(path) {
    return function(name) {
      var absolute = expand(dirname(path), name);
      return globals.require(absolute, path);
    };
  };

  var initModule = function(name, definition) {
    var module = {id: name, exports: {}};
    cache[name] = module;
    definition(module.exports, localRequire(name), module);
    return module.exports;
  };

  var require = function(name, loaderPath) {
    var path = expand(name, '.');
    if (loaderPath == null) loaderPath = '/';
    path = unalias(name, loaderPath);

    if (has.call(cache, path)) return cache[path].exports;
    if (has.call(modules, path)) return initModule(path, modules[path]);

    var dirIndex = expand(path, './index');
    if (has.call(cache, dirIndex)) return cache[dirIndex].exports;
    if (has.call(modules, dirIndex)) return initModule(dirIndex, modules[dirIndex]);

    throw new Error('Cannot find module "' + name + '" from '+ '"' + loaderPath + '"');
  };

  require.alias = function(from, to) {
    aliases[to] = from;
  };

  require.register = require.define = function(bundle, fn) {
    if (typeof bundle === 'object') {
      for (var key in bundle) {
        if (has.call(bundle, key)) {
          modules[key] = bundle[key];
        }
      }
    } else {
      modules[bundle] = fn;
    }
  };

  require.list = function() {
    var result = [];
    for (var item in modules) {
      if (has.call(modules, item)) {
        result.push(item);
      }
    }
    return result;
  };

  require.brunch = true;
  globals.require = require;
})();
<commit_msg>Support for npm modules<commit_after>(function() {
  'use strict';

  var globals = typeof window === 'undefined' ? global : window;
  if (typeof globals.require === 'function') return;

  var modules = {};
  var cache = {};
  var has = ({}).hasOwnProperty;

  var aliases = {};

  var unalias = function(alias, loaderPath) {
    var start = 0;
    if (loaderPath) {
      if (loaderPath.indexOf('components/') === 0) {
        start = 'components/'.length;
      }
      if (loaderPath.indexOf('/', start) > 0) {
        loaderPath = loaderPath.substring(start, loaderPath.indexOf('/', start));
      }
    }
    var result = aliases[alias + '/index.js'] || aliases[loaderPath + '/deps/' + alias + '/index.js'];
    if (result) {
      return 'components/' + result.substring(0, result.length - '.js'.length);
    }
    return alias;
  };

  var expand = function(name) {
    var results = [];
    var parts = name.split('/');
    for (var i = 0, length = parts.length; i < length; i++) {
      var part = parts[i];
      if (part === '..') {
        results.pop();
      } else if (part !== '.' && part !== '') {
        results.push(part);
      }
    }
    return results.join('/');
  };

  var localRequire = function(path) {
    return function(name) {
      return globals.require(name, path);
    };
  };

  var initModule = function(name, definition) {
    var module = {id: name, exports: {}};
    cache[name] = module;
    definition(module.exports, localRequire(name), module);
    return module.exports;
  };

  var isRelative = /^\.\.?(\/|$)/;

  var require = function(name, loaderPath) {
    if (loaderPath)
      loaderPath = expand(loaderPath);
    else
      loaderPath = '.';

    if (isRelative.test(name)) {
      var result = requirePath(loaderPath + '/' + name, loaderPath);
      if(result)
        return result;
    }
    else {
      var loaderPathSegments = loaderPath.split('/');
      while (loaderPathSegments.length) {
        loaderPathSegments.pop();
        var result = requirePath(loaderPathSegments.join('/') + '/node_modules/' + name);
        if(result)
          return result;
      }
    }

    throw new Error('Cannot find module "' + name + '" from "' + loaderPath + '"');
  };

  var requirePath = function(path, loaderPath) {
    path = expand(path);
    path = unalias(path, loaderPath);

    if (has.call(cache, path)) return cache[path].exports;
    if (has.call(modules, path)) return initModule(path, modules[path]);

    var dirIndex = path + '/index';
    if (has.call(cache, dirIndex)) return cache[dirIndex].exports;
    if (has.call(modules, dirIndex)) return initModule(dirIndex, modules[dirIndex]);

    return undefined;
  }

  require.alias = function(from, to) {
    aliases[to] = from;
  };

  require.register = require.define = function(bundle, fn) {
    if (typeof bundle === 'object') {
      for (var key in bundle) {
        if (has.call(bundle, key)) {
          modules[key] = bundle[key];
        }
      }
    } else {
      modules[bundle] = fn;
    }
  };

  require.list = function() {
    var result = [];
    for (var item in modules) {
      if (has.call(modules, item)) {
        result.push(item);
      }
    }
    return result;
  };

  require.brunch = true;
  globals.require = require;
})();
<|endoftext|>


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

  angular.module('WithinDownloader', []);

}());

(function() {
  'use strict';

  angular.module('WithinDownloader')
    .controller('WithinController', ['$window', 'WithinService', MainController]);

  function MainController($window, WithinService) {

    var vm = this;

    vm.videoData = [];

    vm.settings = {
      resolutions: ['640x320', '1280x640', '1920x960', '2880x1440', '4096x2048L', '4096x2048H'],
      projections: ['stereo', 'mono'],
      fileTypes: ['mp4', 'webm']
    };

    vm.selectedSettings = {
      resolution: "",
      projection: "",
      fileType: "",
      downloadAudio: "true"
    };

    vm.getImagePath = getImagePath;
    vm.getVideoPath = getVideoPath;
    vm.getAudioPaths = getAudioPaths;
    vm.downloadFiles = downloadFiles;

    init();

    function init() {
      WithinService.getWithinMetadata().then(function(_videoData) {
        vm.videoData = _videoData;
      });
    }

    function getVideoPath(video) {

      return "http://player.with.in/" + video.root + "video/" + video.cameras.default.webplayer.name + "-WEBPLAYER_PROGRESSIVE-" + vm.selectedSettings.projection + "-" + vm.selectedSettings.resolution + "." + vm.selectedSettings.fileType;
    }

    function getImagePath(video) {
      return "http://with.in/images/projects/" + video.root.slice(0, -1) + ".jpg";
    }

    function getAudioPaths(video) {

    }

    function downloadFiles(video) {

      if (vm.selectedSettings.fileType !== "" && vm.selectedSettings.resolution !== "" && vm.selectedSettings.projection !== "") {

        vm.error = "";
        var videoPath = getVideoPath(video);
        $window.open(videoPath, "Download");

        if (vm.selectedSettings.downloadAudio === "true") {

        }
      } else {
        vm.error = "Please select file type, resolution and projection";
      }

    }

  }
}());

(function() {
  'use strict';

  angular.module('WithinDownloader')
    .service('WithinService', ['$http', WithinService]);

  function WithinService($http) {

    var self = this;

    self.getWithinMetadata = getWithinMetadata;

    return self;

    function getWithinMetadata() {

      return $http.get("./res/unified.json").then(function(data) {

        var content = data.data.content;
        var videoData = [];

        for (var key in content) {
          if (content.hasOwnProperty(key)) {

            var video = content[key];

            if (video.visible_on.webplayer === true) {
              videoData.push(video);
            }
          }
        }

        return videoData;
      });
    }
  }
}());

// (function() {
//   'use strict';
//
//   function WithinDownloader() {
//
//   }
//
//   WithinDownloader.prototype.getWithinMetadata = function(cb) {
//     this.getHTTP("http://with.in/unified.json", cb);
//   };
//
// WithinDownloader.prototype.getVideoPath = function(name, display, resolution, format) {
//     return "http://player.with.in/6-EVOL/video/" + name + "-WEBPLAYER_PROGRESSIVE-" + display + "-" + resolution + "." + format;
//   };
//
//   WithinDownloader.prototype.getAudioPaths = function(name) {
//
//   };
//
//   WithinDownloader.prototype.getImagePath = function(name){
//
//   };
//
//   WithinDownloader.prototype.getHTTP = function(path, onSuccess, onFailure) {
//
//     var request = new XMLHttpRequest();
//     request.open("GET", path, true);
//
//     request.onreadystatechange = function() {
//       if (this.readyState === 4) {
//         if (this.status >= 200 && this.status < 400) {
//           var data = JSON.parse(this.responseText);
//           onSuccess(data);
//         } else {
//           onFailure(this);
//         }
//       }
//     };
//     request.send();
//   };
//
//   var wd = new WithinDownloader();
//   wd.getWithinMetadata(onMetaDataLoaded);
//
//   function onMetaDataLoaded(data){
//     var metaData = data.content;
//     for(var key in metaData){
//       if(metaData.hasOwnProperty(key)){
//         addVideoPanel(metaData[key]);
//       }
//     }
//   }
//
//
// }());
<commit_msg>Remove commented code block.<commit_after>(function() {
  'use strict';

  angular.module('WithinDownloader', []);

}());

(function() {
  'use strict';

  angular.module('WithinDownloader')
    .controller('WithinController', ['$window', 'WithinService', MainController]);

  function MainController($window, WithinService) {

    var vm = this;

    vm.videoData = [];

    vm.settings = {
      resolutions: ['640x320', '1280x640', '1920x960', '2880x1440', '4096x2048L', '4096x2048H'],
      projections: ['stereo', 'mono'],
      fileTypes: ['mp4', 'webm']
    };

    vm.selectedSettings = {
      resolution: "",
      projection: "",
      fileType: "",
      downloadAudio: "true"
    };

    vm.getImagePath = getImagePath;
    vm.getVideoPath = getVideoPath;
    vm.getAudioPaths = getAudioPaths;
    vm.downloadFiles = downloadFiles;

    init();

    function init() {
      WithinService.getWithinMetadata().then(function(_videoData) {
        vm.videoData = _videoData;
      });
    }

    function getVideoPath(video) {

      return "http://player.with.in/" + video.root + "video/" + video.cameras.default.webplayer.name + "-WEBPLAYER_PROGRESSIVE-" + vm.selectedSettings.projection + "-" + vm.selectedSettings.resolution + "." + vm.selectedSettings.fileType;
    }

    function getImagePath(video) {
      return "http://with.in/images/projects/" + video.root.slice(0, -1) + ".jpg";
    }

    function getAudioPaths(video) {

    }

    function downloadFiles(video) {

      if (vm.selectedSettings.fileType !== "" && vm.selectedSettings.resolution !== "" && vm.selectedSettings.projection !== "") {

        vm.error = "";
        var videoPath = getVideoPath(video);
        $window.open(videoPath, "Download");

        if (vm.selectedSettings.downloadAudio === "true") {

        }
      } else {
        vm.error = "Please select file type, resolution and projection";
      }

    }

  }
}());

(function() {
  'use strict';

  angular.module('WithinDownloader')
    .service('WithinService', ['$http', WithinService]);

  function WithinService($http) {

    var self = this;

    self.getWithinMetadata = getWithinMetadata;

    return self;

    function getWithinMetadata() {

      return $http.get("./res/unified.json").then(function(data) {

        var content = data.data.content;
        var videoData = [];

        for (var key in content) {
          if (content.hasOwnProperty(key)) {

            var video = content[key];

            if (video.visible_on.webplayer === true) {
              videoData.push(video);
            }
          }
        }

        return videoData;
      });
    }
  }
}());

<|endoftext|>


<commit_before>var grade1, grade2, finalGrade, semesterGrade, calculatedGrade;

// This will listen for a device shake and call the clear function
window.addEventListener('shake', shakeEventDidOccur, false);
function shakeEventDidOccur () {
    reset();
}

    //hide clear button until grade is calculated
    $("#clearButton").hide();

    function calcGrade() {
      grade1 = $('#box1').val();
      grade2 = $('#box2').val();
      finalGrade = $('#box3').val();
      semesterGrade = $('#box4').val();

      if($("#finGr").is(':checked')) {
        calcFinalGrade();
      }

      else if($("#semGr").is(':checked')) {
        calcSemesterGrade();
      }

      else {
        alert("Please select the type of grade you want to check.");
      }
    }

      function calcSemesterGrade() {
          $("clearButton").show();
          calculatedGrade = 0.4*(grade1) + 0.4*(grade2) + 0.2*(finalGrade);
          $('#box4').val(calculatedGrade);
      }

      function calcFinalGrade() {
          $("clearButton").show();
          calculatedGrade = 5*(semesterGrade - 0.4*(grade1) - 0.4*(grade2));

          if(calculatedGrade<0 || calculatedGrade > 100) {
            alert("The situation is not possible. Please try again.");
            reset();
          }
          else {
            $('#box3').val(calculatedGrade);
          }
      }

//reset all variables when user clears
function reset() {
    grade1 = 0;
    grade2 = 0;
    finalGrade = 0;
    semesterGrade = 0;
    calculatedGrade = 0;

    $('#box1').val("");
    $('#box2').val("");
    $('#box3').val("");
    $('#box4').val("");
    $("#clearButton").hide();
}
<commit_msg>Update app.js<commit_after>var grade1, grade2, finalGrade, semesterGrade, calculatedGrade;

// This will listen for a device shake and call the clear function
window.addEventListener('shake', shakeEventDidOccur, false);
function shakeEventDidOccur () {
    reset();
}
    //hide clear button until grade is calculated
    $("#clearButton").hide();

    function calcGrade() {
      grade1 = $('#box1').val();
      grade2 = $('#box2').val();
      finalGrade = $('#box3').val();
      semesterGrade = $('#box4').val();

      if($("#finGr").is(':checked')) {
        calcFinalGrade();
      }

      else if($("#semGr").is(':checked')) {
        calcSemesterGrade();
      }

      else {
        alert("Please select the type of grade you want to check.");
      }
    }

      function calcSemesterGrade() {
          $("clearButton").show();
          calculatedGrade = 0.4*(grade1) + 0.4*(grade2) + 0.2*(finalGrade);
          $('#box4').val(calculatedGrade);
      }

      function calcFinalGrade() {
          $("clearButton").show();
          calculatedGrade = 5*(semesterGrade - 0.4*(grade1) - 0.4*(grade2));

          if(calculatedGrade<0 || calculatedGrade > 100) {
            alert("The situation is not possible. Please try again.");
            reset();
          }
          else {
            $('#box3').val(calculatedGrade);
          }
      }

//reset all variables when user clears
function reset() {
    grade1 = 0;
    grade2 = 0;
    finalGrade = 0;
    semesterGrade = 0;
    calculatedGrade = 0;

    $('#box1').val("");
    $('#box2').val("");
    $('#box3').val("");
    $('#box4').val("");
    $("#clearButton").hide();
}
<|endoftext|>


<commit_before>'use strict';

var Shrinkwrap = require('shrinkwrap')
  , readme = require('renderme')
  , Registry = require('npmjs')
  , async = require('async');

/**
* Gather all the required data to correctly render a package page.
*
* @param {String} name The name of the package.
* @param {String} registry The optional registry we should use.
* @param {Function} next The callback.
* @api private
*/
function resolve(name, registry, next) {
  if ('function' === typeof registry) {
    next = registry;
    registry = Registry.mirrors.nodejitsu;
  }

  var shrinkwrap = new Shrinkwrap({ registry: registry })
    , npm = new Registry({ registry: registry });

  npm.packages.details(name, function details(err, data) {
    if (err) return next(err);

    data = Array.isArray(data) ? data.pop() : data;

    //
    // Retrieve some additional information and pre-parse some information.
    //
    async.parallel({
      dependent: function render(next) {
        shrinkwrap.resolve(data, function resolved(err, data, dependent) {
          next(err, dependent);
        });
      },
      readme: function render(next) {
        readme(data, next);
      }
    }, function parallel(err, additional) {
      if (err) return next(err);

      reduce({
        package: data,
        readme: additional.readme,
        dependent: additional.dependent
      }, next);
    });
  });
}

/**
 * Reduce the massive data structure to something useful.
 *
 * @param {Object} data The received data structure.
 * @param {Function} fn The callback.
 * @api private
 */
function reduce(data, fn) {

  delete data.package.readmeFilename;
  delete data.package.versions;
  delete data.package.readme;

  //
  // Remove circular references as it would prevent us from caching in Redis or
  // what ever because there's a circular reference.
  //
  if ('object' === typeof data.dependent) {
    Object.keys(data.dependent).forEach(function each(id) {
      delete data.dependent[id].dependent;
      delete data.dependent[id].parent;
    });
  }

  //
  // Make sure we default to something so we don't get template errors
  //
  data.readme = data.readme || data.package.description || '';

  fn(undefined, data);
}

//
// Expose the methods.
//
resolve.reduce = reduce;
module.exports = resolve;
<commit_msg>[fix] Dependencies still caused an recursive data structure.<commit_after>'use strict';

var Shrinkwrap = require('shrinkwrap')
  , readme = require('renderme')
  , Registry = require('npmjs')
  , async = require('async');

/**
* Gather all the required data to correctly render a package page.
*
* @param {String} name The name of the package.
* @param {String} registry The optional registry we should use.
* @param {Function} next The callback.
* @api private
*/
function resolve(name, registry, next) {
  if ('function' === typeof registry) {
    next = registry;
    registry = Registry.mirrors.nodejitsu;
  }

  var shrinkwrap = new Shrinkwrap({ registry: registry })
    , npm = new Registry({ registry: registry });

  npm.packages.details(name, function details(err, data) {
    if (err) return next(err);

    data = Array.isArray(data) ? data.pop() : data;

    //
    // Retrieve some additional information and pre-parse some information.
    //
    async.parallel({
      dependent: function render(next) {
        shrinkwrap.resolve(data, function resolved(err, data, dependent) {
          next(err, dependent);
        });
      },
      readme: function render(next) {
        readme(data, next);
      }
    }, function parallel(err, additional) {
      if (err) return next(err);

      reduce({
        package: data,
        readme: additional.readme,
        dependent: additional.dependent
      }, next);
    });
  });
}

/**
 * Reduce the massive data structure to something useful.
 *
 * @param {Object} data The received data structure.
 * @param {Function} fn The callback.
 * @api private
 */
function reduce(data, fn) {

  delete data.package.readmeFilename;
  delete data.package.versions;
  delete data.package.readme;

  //
  // Remove circular references as it would prevent us from caching in Redis or
  // what ever because there's a circular reference.
  //
  if ('object' === typeof data.dependent) {
    Object.keys(data.dependent).forEach(function each(id) {
      delete data.dependent[id].dependencies;
      delete data.dependent[id].dependent;
      delete data.dependent[id].parent;
    });
  }

  //
  // Make sure we default to something so we don't get template errors
  //
  data.readme = data.readme || data.package.description || '';

  fn(undefined, data);
}

//
// Expose the methods.
//
resolve.reduce = reduce;
module.exports = resolve;
<|endoftext|>


<commit_before>// This file is concerned with altering the Firefox 4+ Add-ons Manager window,
// for those sorts of functionality we want that the API does not handle.  (As
// opposed to addons4.jsm which is responsible for what the API does handle.)
(function private_scope() {
Components.utils.import("resource://gre/modules/AddonManager.jsm");
Components.utils.import("resource://greasemonkey/addons4.js");
Components.utils.import('resource://greasemonkey/third-party/droppedUrls.js');
Components.utils.import('resource://greasemonkey/util.js');

var userScriptViewId = 'addons://list/greasemonkey-user-script';

window.addEventListener('focus', focus, false);
window.addEventListener('load', init, false);
window.addEventListener('unload', unload, false);

var stringBundle = Components
    .classes["@mozilla.org/intl/stringbundle;1"]
    .getService(Components.interfaces.nsIStringBundleService)
    .createBundle("chrome://greasemonkey/locale/gm-addons.properties");

// Patch the default createItem() to add our custom property.
var _createItemOrig = createItem;
createItem = function GM_createItem(aObj, aIsInstall, aIsRemote) {
  var item = _createItemOrig(aObj, aIsInstall, aIsRemote);
  if (SCRIPT_ADDON_TYPE == aObj.type) {
   // Save a reference to this richlistitem on the Addon object, so we can
   // fix the 'executionIndex' attribute if/when it changes.
   aObj.richlistitem = item;
   setRichlistitemExecutionIndex(aObj);
  }
  return item;
};

// Patch the default onDrop() to make user script installation work.
var _gDragDrop_onDrop_Orig = gDragDrop.onDrop;
gDragDrop.onDrop = function GM_onDrop(aEvent) {
  var urls = droppedUrls(aEvent);

  var droppedNonUserScript = false;
  for (var i = urls.length - 1, url = null; url = urls[i]; i--) {
    if (url.match(/\.user\.js$/)) {
      GM_util.showInstallDialog(
          url, GM_util.getBrowserWindow().gBrowser, GM_util.getService());
    } else {
      droppedNonUserScript = true;
    }
  }

  // Pass call through to the original handler, if any non-user-script
  // was part of this drop action.
  if (droppedNonUserScript) {
    _gDragDrop_onDrop_Orig(aEvent);
  }
  else {
    aEvent.preventDefault();
  }
};

// Set up an "observer" on the config, to keep the displayed items up to date
// with their actual state.
var observer = {
  notifyEvent: function observer_notifyEvent(script, event, data) {
    if (!isScriptView()) return;

    var addon = ScriptAddonFactoryByScript(script);
    switch (event) {
      case 'install':
        gListView.addItem(addon);
        setEmptyWarningVisible();
        break;
      case 'edit-enabled':
        var item = gListView.getListItemForID(addon.id);
        var callback = data? item.onEnabled : item.onDisabled;
        if (!callback) {
          // This observer triggers in the case of an uninstall undo.  But
          // does not need to -- and can not -- run.  Ignore this case.
          break;
        }
        item.userDisabled = !data;
        callback.call(item);
        break;
      case 'modified':
        if (!data) break;
        var oldAddon = ScriptAddonFactoryByScript({'id': data});
        if (!oldAddon) break;
        addon = ScriptAddonFactoryByScript(script, true);

        // Use old and new the addon references to update the view.
        var item = createItem(addon);
        var oldItem = gListView.getListItemForID(oldAddon.id);
        oldItem.parentNode.replaceChild(item, oldItem);
        break;
    }
  }
};

// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ //

function addonIsInstalledScript(aAddon) {
  if (!aAddon) return false;
  if (SCRIPT_ADDON_TYPE != aAddon.type) return false;
  if (aAddon._script.needsUninstall) return false;
  return true;
};

function isScriptView() {
  return userScriptViewId == gViewController.currentViewId;
}

function addonExecutesNonFirst(aAddon) {
  if (!aAddon) return false;
  if (SCRIPT_ADDON_TYPE != aAddon.type) return false;
  return 0 != aAddon.executionIndex;
}

function addonExecutesNonLast(aAddon) {
  if (!aAddon) return false;
  if (SCRIPT_ADDON_TYPE != aAddon.type) return false;
  return (GM_util.getService().config.scripts.length - 1)
      != aAddon.executionIndex;
}

function addonUpdateCanBeForced(aAddon) {
  if (!aAddon) return false;
  if (SCRIPT_ADDON_TYPE != aAddon.type) return false;
  var script = aAddon._script;
  // Can be forced if non-forced isn't allowed, but forced is.
  return !script.isRemoteUpdateAllowed(false)
      && script.isRemoteUpdateAllowed(true);
}

function sortedByExecOrder() {
  return document.getElementById('greasemonkey-sort-bar')
    .getElementsByAttribute('sortBy', 'executionIndex')[0]
    .hasAttribute('checkState');
};

function focus() {
  // When the window gains focus, it might be from switching to an editor
  // and back, so scan for updated scripts.
  var config = GM_util.getService().config;
  config.updateModifiedScripts('document-start', null);
  config.updateModifiedScripts('document-end', null);
}

function init() {
  GM_util.getService().config.addObserver(observer);

  gViewController.commands.cmd_userscript_edit = {
      isEnabled: addonIsInstalledScript,
      doCommand: function(aAddon) { GM_util.openInEditor(aAddon._script); }
    };
  gViewController.commands.cmd_userscript_show = {
      isEnabled: addonIsInstalledScript,
      doCommand: function(aAddon) { GM_openFolder(aAddon._script.file); }
    };

  gViewController.commands.cmd_userscript_execute_first = {
      isEnabled: addonExecutesNonFirst,
      doCommand: function(aAddon) { reorderScriptExecution(aAddon, -9999); }
    };
  gViewController.commands.cmd_userscript_execute_sooner = {
      isEnabled: addonExecutesNonFirst,
      doCommand: function(aAddon) { reorderScriptExecution(aAddon, -1); }
    };
  gViewController.commands.cmd_userscript_execute_later = {
      isEnabled: addonExecutesNonLast,
      doCommand: function(aAddon) { reorderScriptExecution(aAddon, 1); }
    };
  gViewController.commands.cmd_userscript_execute_last = {
      isEnabled: addonExecutesNonLast,
      doCommand: function(aAddon) { reorderScriptExecution(aAddon, 9999); }
    };

  gViewController.commands.cmd_userscript_forcedFindItemUpdates = {
      isEnabled: addonUpdateCanBeForced,
      doCommand: function(aAddon) {
        var result = confirm(
            stringBundle.GetStringFromName('confirmForceUpdate'));
        if (result) {
          aAddon.forceUpdate = true;
          gViewController.commands.cmd_findItemUpdates.doCommand(aAddon);
          aAddon.forceUpdate = false;
        }
      }
  };

  window.addEventListener('ViewChanged', onViewChanged, false);
  onViewChanged(); // initialize on load as well as when it changes later

  document.getElementById('greasemonkey-sort-bar').addEventListener(
      'command', onSortersClicked, false);
  applySort();
};

function onSortersClicked(aEvent) {
  if ('button' != aEvent.target.tagName) return;
  var button = aEvent.target;

  var checkState = button.getAttribute('checkState');

  // Remove checkState from all buttons.
  var buttons = document.getElementById('greasemonkey-sort-bar')
      .getElementsByTagName('button');
  for (var i = 0, el = null; el = buttons[i]; i++) {
    el.removeAttribute('checkState');
  }

  // Toggle state of this button.
  if ('2' == checkState) {
    button.setAttribute('checkState', '1');
  } else {
    button.setAttribute('checkState', '2');
  }

  applySort();
};

function applySort() {
  // Find checked button.
  var buttons = document.getElementById('greasemonkey-sort-bar')
    .getElementsByTagName('button');
  for (var i = 0, button = null; button = buttons[i]; i++) {
    if (button.hasAttribute('checkState')) break;
  }

  var ascending = '1' != button.getAttribute('checkState');
  var sortBy = button.getAttribute('sortBy').split(',');

  var list = document.getElementById('addon-list');
  var elements = Array.slice(list.childNodes, 0);
  sortElements(elements, sortBy, ascending);
  while (list.lastChild) list.removeChild(list.lastChild);
  elements.forEach(function(el) { list.appendChild(el); });
};

function onViewChanged(aEvent) {
  if (userScriptViewId == gViewController.currentViewId) {
    document.documentElement.classList.add('greasemonkey');
    setEmptyWarningVisible();
    applySort();
  } else {
    document.documentElement.classList.remove('greasemonkey');
  }
};

function setEmptyWarningVisible() {
  var emptyWarning = document.getElementById('user-script-list-empty');
  emptyWarning.collapsed = !!GM_util.getService().config.scripts.length;
}

function selectScriptExecOrder() {
  if (sortedByExecOrder()) return;

  var button = document.getElementById('greasemonkey-sort-bar')
    .getElementsByAttribute('sortBy', 'executionIndex')[0];
  // Sort the script list by execution order
  onSortersClicked({'target': button});
};

function reorderScriptExecution(aAddon, moveBy) {
  selectScriptExecOrder();
  GM_util.getService().config.move(aAddon._script, moveBy);
  AddonManager.getAddonsByTypes([SCRIPT_ADDON_TYPE], function(aAddons) {
      // Fix all the 'executionOrder' attributes.
      for (var i = 0, addon = null; addon = aAddons[i]; i++) {
        setRichlistitemExecutionIndex(addon);
      }
      // Re-sort the list, with these fixed attributes.
      applySort();
      // Ensure the selected element is still visible.
      var richlistbox = document.getElementById('addon-list');
      richlistbox.ensureElementIsVisible(richlistbox.currentItem);
    });
};

function setRichlistitemExecutionIndex(aAddon) {
  aAddon.richlistitem.setAttribute('executionIndex',
      // String format with leading zeros, so it will sort properly.
      ('0000' + aAddon.executionIndex).substr(-5));
};

function unload() {
  var GM_config = GM_util.getService().config;
  // Since .getAddonsByTypes() is asynchronous, AddonManager gets destroyed
  // by the time the callback runs.  Cache this value we need from it.
  var pending_uninstall = AddonManager.PENDING_UNINSTALL;

  AddonManager.getAddonsByTypes([SCRIPT_ADDON_TYPE], function(aAddons) {
      var didUninstall = false;
      for (var i = 0, addon = null; addon = aAddons[i]; i++) {
        if (addon.pendingOperations & pending_uninstall) {
          addon.performUninstall();
          didUninstall = true;
        }
      }
      // Guarantee that the config.xml is saved to disk.
      // Todo: This without dipping into private members.
      if (didUninstall) GM_config._save(true);
    });

  GM_config.removeObserver(observer);
};
})();

function GM_openUserscriptsOrg() {
  var chromeWin = GM_util.getBrowserWindow();
  chromeWin.gBrowser.selectedTab = chromeWin.gBrowser.addTab(
      'http://wiki.greasespot.net/User_Script_Hosting');
}
<commit_msg>Add-ons Manager: only force sort User Scripts.<commit_after>// This file is concerned with altering the Firefox 4+ Add-ons Manager window,
// for those sorts of functionality we want that the API does not handle.  (As
// opposed to addons4.jsm which is responsible for what the API does handle.)
(function private_scope() {
Components.utils.import("resource://gre/modules/AddonManager.jsm");
Components.utils.import("resource://greasemonkey/addons4.js");
Components.utils.import('resource://greasemonkey/third-party/droppedUrls.js');
Components.utils.import('resource://greasemonkey/util.js');

var userScriptViewId = 'addons://list/greasemonkey-user-script';

window.addEventListener('focus', focus, false);
window.addEventListener('load', init, false);
window.addEventListener('unload', unload, false);

var stringBundle = Components
    .classes["@mozilla.org/intl/stringbundle;1"]
    .getService(Components.interfaces.nsIStringBundleService)
    .createBundle("chrome://greasemonkey/locale/gm-addons.properties");

// Patch the default createItem() to add our custom property.
var _createItemOrig = createItem;
createItem = function GM_createItem(aObj, aIsInstall, aIsRemote) {
  var item = _createItemOrig(aObj, aIsInstall, aIsRemote);
  if (SCRIPT_ADDON_TYPE == aObj.type) {
   // Save a reference to this richlistitem on the Addon object, so we can
   // fix the 'executionIndex' attribute if/when it changes.
   aObj.richlistitem = item;
   setRichlistitemExecutionIndex(aObj);
  }
  return item;
};

// Patch the default onDrop() to make user script installation work.
var _gDragDrop_onDrop_Orig = gDragDrop.onDrop;
gDragDrop.onDrop = function GM_onDrop(aEvent) {
  var urls = droppedUrls(aEvent);

  var droppedNonUserScript = false;
  for (var i = urls.length - 1, url = null; url = urls[i]; i--) {
    if (url.match(/\.user\.js$/)) {
      GM_util.showInstallDialog(
          url, GM_util.getBrowserWindow().gBrowser, GM_util.getService());
    } else {
      droppedNonUserScript = true;
    }
  }

  // Pass call through to the original handler, if any non-user-script
  // was part of this drop action.
  if (droppedNonUserScript) {
    _gDragDrop_onDrop_Orig(aEvent);
  }
  else {
    aEvent.preventDefault();
  }
};

// Set up an "observer" on the config, to keep the displayed items up to date
// with their actual state.
var observer = {
  notifyEvent: function observer_notifyEvent(script, event, data) {
    if (!isScriptView()) return;

    var addon = ScriptAddonFactoryByScript(script);
    switch (event) {
      case 'install':
        gListView.addItem(addon);
        setEmptyWarningVisible();
        break;
      case 'edit-enabled':
        var item = gListView.getListItemForID(addon.id);
        var callback = data? item.onEnabled : item.onDisabled;
        if (!callback) {
          // This observer triggers in the case of an uninstall undo.  But
          // does not need to -- and can not -- run.  Ignore this case.
          break;
        }
        item.userDisabled = !data;
        callback.call(item);
        break;
      case 'modified':
        if (!data) break;
        var oldAddon = ScriptAddonFactoryByScript({'id': data});
        if (!oldAddon) break;
        addon = ScriptAddonFactoryByScript(script, true);

        // Use old and new the addon references to update the view.
        var item = createItem(addon);
        var oldItem = gListView.getListItemForID(oldAddon.id);
        oldItem.parentNode.replaceChild(item, oldItem);
        break;
    }
  }
};

// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ //

function addonIsInstalledScript(aAddon) {
  if (!aAddon) return false;
  if (SCRIPT_ADDON_TYPE != aAddon.type) return false;
  if (aAddon._script.needsUninstall) return false;
  return true;
};

function isScriptView() {
  return userScriptViewId == gViewController.currentViewId;
}

function addonExecutesNonFirst(aAddon) {
  if (!aAddon) return false;
  if (SCRIPT_ADDON_TYPE != aAddon.type) return false;
  return 0 != aAddon.executionIndex;
}

function addonExecutesNonLast(aAddon) {
  if (!aAddon) return false;
  if (SCRIPT_ADDON_TYPE != aAddon.type) return false;
  return (GM_util.getService().config.scripts.length - 1)
      != aAddon.executionIndex;
}

function addonUpdateCanBeForced(aAddon) {
  if (!aAddon) return false;
  if (SCRIPT_ADDON_TYPE != aAddon.type) return false;
  var script = aAddon._script;
  // Can be forced if non-forced isn't allowed, but forced is.
  return !script.isRemoteUpdateAllowed(false)
      && script.isRemoteUpdateAllowed(true);
}

function sortedByExecOrder() {
  return document.getElementById('greasemonkey-sort-bar')
    .getElementsByAttribute('sortBy', 'executionIndex')[0]
    .hasAttribute('checkState');
};

function focus() {
  // When the window gains focus, it might be from switching to an editor
  // and back, so scan for updated scripts.
  var config = GM_util.getService().config;
  config.updateModifiedScripts('document-start', null);
  config.updateModifiedScripts('document-end', null);
}

function init() {
  GM_util.getService().config.addObserver(observer);

  gViewController.commands.cmd_userscript_edit = {
      isEnabled: addonIsInstalledScript,
      doCommand: function(aAddon) { GM_util.openInEditor(aAddon._script); }
    };
  gViewController.commands.cmd_userscript_show = {
      isEnabled: addonIsInstalledScript,
      doCommand: function(aAddon) { GM_openFolder(aAddon._script.file); }
    };

  gViewController.commands.cmd_userscript_execute_first = {
      isEnabled: addonExecutesNonFirst,
      doCommand: function(aAddon) { reorderScriptExecution(aAddon, -9999); }
    };
  gViewController.commands.cmd_userscript_execute_sooner = {
      isEnabled: addonExecutesNonFirst,
      doCommand: function(aAddon) { reorderScriptExecution(aAddon, -1); }
    };
  gViewController.commands.cmd_userscript_execute_later = {
      isEnabled: addonExecutesNonLast,
      doCommand: function(aAddon) { reorderScriptExecution(aAddon, 1); }
    };
  gViewController.commands.cmd_userscript_execute_last = {
      isEnabled: addonExecutesNonLast,
      doCommand: function(aAddon) { reorderScriptExecution(aAddon, 9999); }
    };

  gViewController.commands.cmd_userscript_forcedFindItemUpdates = {
      isEnabled: addonUpdateCanBeForced,
      doCommand: function(aAddon) {
        var result = confirm(
            stringBundle.GetStringFromName('confirmForceUpdate'));
        if (result) {
          aAddon.forceUpdate = true;
          gViewController.commands.cmd_findItemUpdates.doCommand(aAddon);
          aAddon.forceUpdate = false;
        }
      }
  };

  window.addEventListener('ViewChanged', onViewChanged, false);
  onViewChanged(); // initialize on load as well as when it changes later

  document.getElementById('greasemonkey-sort-bar').addEventListener(
      'command', onSortersClicked, false);
  applySort();
};

function onSortersClicked(aEvent) {
  if ('button' != aEvent.target.tagName) return;
  var button = aEvent.target;

  var checkState = button.getAttribute('checkState');

  // Remove checkState from all buttons.
  var buttons = document.getElementById('greasemonkey-sort-bar')
      .getElementsByTagName('button');
  for (var i = 0, el = null; el = buttons[i]; i++) {
    el.removeAttribute('checkState');
  }

  // Toggle state of this button.
  if ('2' == checkState) {
    button.setAttribute('checkState', '1');
  } else {
    button.setAttribute('checkState', '2');
  }

  applySort();
};

function applySort() {
  if (userScriptViewId != gViewController.currentViewId) return;

  // Find checked button.
  var buttons = document.getElementById('greasemonkey-sort-bar')
    .getElementsByTagName('button');
  for (var i = 0, button = null; button = buttons[i]; i++) {
    if (button.hasAttribute('checkState')) break;
  }

  var ascending = '1' != button.getAttribute('checkState');
  var sortBy = button.getAttribute('sortBy').split(',');

  var list = document.getElementById('addon-list');
  var elements = Array.slice(list.childNodes, 0);
  sortElements(elements, sortBy, ascending);
  while (list.lastChild) list.removeChild(list.lastChild);
  elements.forEach(function(el) { list.appendChild(el); });
};

function onViewChanged(aEvent) {
  if (userScriptViewId == gViewController.currentViewId) {
    document.documentElement.classList.add('greasemonkey');
    setEmptyWarningVisible();
    applySort();
  } else {
    document.documentElement.classList.remove('greasemonkey');
  }
};

function setEmptyWarningVisible() {
  var emptyWarning = document.getElementById('user-script-list-empty');
  emptyWarning.collapsed = !!GM_util.getService().config.scripts.length;
}

function selectScriptExecOrder() {
  if (sortedByExecOrder()) return;

  var button = document.getElementById('greasemonkey-sort-bar')
    .getElementsByAttribute('sortBy', 'executionIndex')[0];
  // Sort the script list by execution order
  onSortersClicked({'target': button});
};

function reorderScriptExecution(aAddon, moveBy) {
  selectScriptExecOrder();
  GM_util.getService().config.move(aAddon._script, moveBy);
  AddonManager.getAddonsByTypes([SCRIPT_ADDON_TYPE], function(aAddons) {
      // Fix all the 'executionOrder' attributes.
      for (var i = 0, addon = null; addon = aAddons[i]; i++) {
        setRichlistitemExecutionIndex(addon);
      }
      // Re-sort the list, with these fixed attributes.
      applySort();
      // Ensure the selected element is still visible.
      var richlistbox = document.getElementById('addon-list');
      richlistbox.ensureElementIsVisible(richlistbox.currentItem);
    });
};

function setRichlistitemExecutionIndex(aAddon) {
  aAddon.richlistitem.setAttribute('executionIndex',
      // String format with leading zeros, so it will sort properly.
      ('0000' + aAddon.executionIndex).substr(-5));
};

function unload() {
  var GM_config = GM_util.getService().config;
  // Since .getAddonsByTypes() is asynchronous, AddonManager gets destroyed
  // by the time the callback runs.  Cache this value we need from it.
  var pending_uninstall = AddonManager.PENDING_UNINSTALL;

  AddonManager.getAddonsByTypes([SCRIPT_ADDON_TYPE], function(aAddons) {
      var didUninstall = false;
      for (var i = 0, addon = null; addon = aAddons[i]; i++) {
        if (addon.pendingOperations & pending_uninstall) {
          addon.performUninstall();
          didUninstall = true;
        }
      }
      // Guarantee that the config.xml is saved to disk.
      // Todo: This without dipping into private members.
      if (didUninstall) GM_config._save(true);
    });

  GM_config.removeObserver(observer);
};
})();

function GM_openUserscriptsOrg() {
  var chromeWin = GM_util.getBrowserWindow();
  chromeWin.gBrowser.selectedTab = chromeWin.gBrowser.addTab(
      'http://wiki.greasespot.net/User_Script_Hosting');
}
<|endoftext|>


<commit_before>
var store_icon = static_url + 'img/map_icons/home-2.png'
var online_icon = static_url + 'img/map_icons/wifi.png'
var geolocation_icon = static_url + '/img/map_icons/home-2-green.png'

function lookup_marker(id) {
    if (id == null || id == 1) {
        return store_icon
    } else if (id == 2) {
        return online_icon
    } else if (id == 999) {
        return geolocation_icon
    }  else {
        return store_icon
    }
}

function initialize_map(markers, element) {
    var mapOptions = {
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(element, mapOptions);
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < markers.length; i++) {
        marker = markers[i];
        if (marker[1] != null && marker[2] != null) {
            var latlng = new google.maps.LatLng(marker[1], marker[2]);
            bounds.extend(latlng);
            var marker_obj = new google.maps.Marker({
                position: latlng,
                map: map,
                title: marker[0],
                icon: lookup_marker(marker[3])
            });
            if (marker[4] != '') {
                google.maps.event.addListener(marker_obj, 'click', (function(marker) {
                    return function() {
                        window.location = marker[4];
                    }
                })(marker));
            }
        }
    }
    map.fitBounds(bounds)
}<commit_msg>Fix icon path.<commit_after>
var store_icon = static_url + 'img/map_icons/home-2.png'
var online_icon = static_url + 'img/map_icons/wifi.png'
var geolocation_icon = static_url + 'img/map_icons/home-2-green.png'

function lookup_marker(id) {
    if (id == null || id == 1) {
        return store_icon
    } else if (id == 2) {
        return online_icon
    } else if (id == 999) {
        return geolocation_icon
    }  else {
        return store_icon
    }
}

function initialize_map(markers, element) {
    var mapOptions = {
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(element, mapOptions);
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < markers.length; i++) {
        marker = markers[i];
        if (marker[1] != null && marker[2] != null) {
            var latlng = new google.maps.LatLng(marker[1], marker[2]);
            bounds.extend(latlng);
            var marker_obj = new google.maps.Marker({
                position: latlng,
                map: map,
                title: marker[0],
                icon: lookup_marker(marker[3])
            });
            if (marker[4] != '') {
                google.maps.event.addListener(marker_obj, 'click', (function(marker) {
                    return function() {
                        window.location = marker[4];
                    }
                })(marker));
            }
        }
    }
    map.fitBounds(bounds)
}<|endoftext|>


<commit_before>
var global_analysisResult = {};

function backendComm(jsObject){
	/**
	* Print the input to the console.
	*/
	console.log(JSON.stringify(jsObject));

	//backend script called
	var pathToCGI = "./cgi-bin/backendCom.cgi";

 	$.ajax({
		url: pathToCGI,
		type: "post",
		contentType: "json",
		data:JSON.stringify(jsObject),
		success: function(response){
			setTimeout(function(){
				if(jsObject.analysis.action=="allNextStates"){
					executeJava(true);
				}else{
					executeJava(false);
				}
		    }, 500);
		}
	})	.fail(function(){
		msg = "Ops! Something went wrong.";
		alert(msg);
	});

}

function executeJava(isGetNextSteps){
	var pathToCGI = "./cgi-bin/executeJava.cgi";
	$.ajax({
		url: pathToCGI,
		type: "get",
		success: function(response){
		    setTimeout(function(){
				getFileResults(isGetNextSteps);
		    }, 500);
		}
	})
	.fail(function(){
		msg = "Ops! Something went wrong. Executing java.";
		alert(msg);
	});
}

function getFileResults(isGetNextSteps){
	var pathToCGI = "./cgi-bin/fileRead.cgi";

	//Executing action to send backend
	$.ajax({
		url: pathToCGI,
		type: "get",
		success: function(response){
			analysisResults = JSON.parse(response['data']);

			if (constraintErrorExists(analysisResults)) {
				var msg = getErrorMessage(analysisResults.errorMessage);
				alert(msg);
			} else {
				/**
					* Print the response data to the console.
				*/
					console.log(JSON.stringify(JSON.parse(response['data'])));

				global_analysisResult = analysisResults;
				if (analysisResults == ""){
					alert("Error while reading the resonse file from server. This can be due an error in executing java application.")
					return
				}
				if(isGetNextSteps){
					open_analysis_viewer();
				}else{
					displayAnalysis(analysisResults);
				}
			}
		}
	})
	.fail(function(){
		msg = "Error while executing CGI file: fileRead. Please contact the system Admin.";
		alert(msg);
	});
}

function open_analysis_viewer(){
	var urlBase = document.URL.substring(0, document.URL.lastIndexOf('/')+1);
	var url = urlBase+"analysis.html";

	var w = window.open(url, "Analysis View", "status=0,title=0,height=600,width=1200,scrollbars=1");

	if (!w) {
	    alert('You must allow popups for this map to work.');
	}
}

/*
 * Returns true iff analysisResults indicates that there is
 * an error message.
 *
 * @param {Object} analysisResults
 *   results from backend java code
 * @returns {boolean}
 */
function constraintErrorExists(analysisResults) {
	return analysisResults.errorMessage != null;
}

/*
 * Returns a user-readable error message, containing
 * user-defined node names instead of node ids.
 *
 * Example message:
 * The model is not solvable because of conflicting constraints
 * involving nodes: mouse, keyboard, and pizza.
 *
 * @param {String} backendErrorMsg
 *   error message from backend
 * @returns {boolean}
 */
function getErrorMessage(backendErrorMsg) {

	var ids = getIDs(backendErrorMsg);
	var names = [];
	var actorNames = [];
	for (var i = 0; i < ids.length; i++) {
		names.push(getNodeName(ids[i]));
		actorNames.push(getParentActorNameById(ids[i]));
	}

	var s = 'The model is not solvable because of conflicting constraints involving nodes (with associated actors): ';
	var numOfNames = names.length;

	for (var i = 0; i < numOfNames - 1; i++) {
		s += names[i] + ' (' + actorNames[i] + ')';
		if (i < numOfNames - 2) {
			s += ', ';
		} else {
			s += ' ';
		}
	}

	s += 'and ' + names[numOfNames - 1] + ' (' + actorNames[numOfNames - 1] + ').';
	s += '\n\nOriginal Error: ' + backendErrorMsg;
	return s;
}

/*
 * Returns the actor name for an actor
 * that embeds an element with element id id.
 * If element with element id id is not embedded within an actor
 * returns 'no actor'.
 *
 * @param {String} id
 *   element id for the element of interest
 * @returns {String}
 */
function getParentActorNameById(id) {
	var actor = getParentActor(getElementById(id));
	if (actor) {
		return actor.attributes.attrs['.name'].text;
	}
	return 'no actor';
}

/*
 * Returns the actor which embeds the element of interest.
 * Returns null if there is no actor that embeds the element.
 * (If an actor embeds an element, the actor is the element's parent)
 *
 * @param {dia.Element} element
 * @returns {dia.Element | null}
 */
function getParentActor(element) {
	// get call the ancestors for the element
	var ancestors = element.getAncestors();
	if (ancestors.length == 0) {
		return null;
	}
	// if there is an ancestor, there would only be one
	return ancestors[0];
}

/*
 * Returns the element with element id id.
 * Returns null if no element with that element id exists.
 *
 * @param {String} id
 *   element id of the element of interest
 * @returns {dia.Element | null}
 */
function getElementById(id) {
	var elements = graph.getElements();
	for (var i = 0; i < elements.length; i++) {
		if (id == elements[i].attributes.elementid) {
			return elements[i];
		}
	}
}

/*
 * Returns an array of all node ids that are mentioned in
 * the backendErrorMsg, in the order they appear.
 *
 * @param {String} backendErrorMsg
 *   error message from backend
 * @returns {Array of String}
 */
function getIDs(backendErrorMsg) {
	// this regex matches for an N, followed by 4 digits
	var pattern = /N\d{4}/g;
	var arr = backendErrorMsg.match(pattern);

	// remove the preceding N's to get each id
	for (var i = 0; i < arr.length; i++) {
		arr[i] = arr[i].substring(1);
	}

	return arr;
}
<commit_msg>Fix simulate single path error message bug<commit_after>
var global_analysisResult = {};

function backendComm(jsObject){
	/**
	* Print the input to the console.
	*/
	console.log(JSON.stringify(jsObject));

	//backend script called
	var pathToCGI = "./cgi-bin/backendCom.cgi";

 	$.ajax({
		url: pathToCGI,
		type: "post",
		contentType: "json",
		data:JSON.stringify(jsObject),
		success: function(response){
			setTimeout(function(){
				if(jsObject.analysis.action=="allNextStates"){
					executeJava(true);
				}else{
					executeJava(false);
				}
		    }, 500);
		}
	})	.fail(function(){
		msg = "Ops! Something went wrong.";
		alert(msg);
	});

}

function executeJava(isGetNextSteps){
	var pathToCGI = "./cgi-bin/executeJava.cgi";
	$.ajax({
		url: pathToCGI,
		type: "get",
		success: function(response){
		    setTimeout(function(){
				getFileResults(isGetNextSteps);
		    }, 500);
		}
	})
	.fail(function(){
		msg = "Ops! Something went wrong. Executing java.";
		alert(msg);
	});
}

function getFileResults(isGetNextSteps){
	var pathToCGI = "./cgi-bin/fileRead.cgi";

	//Executing action to send backend
	$.ajax({
		url: pathToCGI,
		type: "get",
		success: function(response){
			analysisResults = JSON.parse(response['data']);

			if (errorExists(analysisResults)) {
				var msg = getErrorMessage(analysisResults.errorMessage);
				alert(msg);
			} else {
				/**
					* Print the response data to the console.
				*/
					console.log(JSON.stringify(JSON.parse(response['data'])));

				global_analysisResult = analysisResults;
				if (analysisResults == ""){
					alert("Error while reading the resonse file from server. This can be due an error in executing java application.")
					return
				}
				if(isGetNextSteps){
					open_analysis_viewer();
				}else{
					displayAnalysis(analysisResults);
				}
			}
		}
	})
	.fail(function(){
		msg = "Error while executing CGI file: fileRead. Please contact the system Admin.";
		alert(msg);
	});
}

function open_analysis_viewer(){
	var urlBase = document.URL.substring(0, document.URL.lastIndexOf('/')+1);
	var url = urlBase+"analysis.html";

	var w = window.open(url, "Analysis View", "status=0,title=0,height=600,width=1200,scrollbars=1");

	if (!w) {
	    alert('You must allow popups for this map to work.');
	}
}

/*
 * Returns true iff analysisResults indicates that there is
 * an error message.
 *
 * @param {Object} analysisResults
 *   results from backend java code
 * @returns {boolean}
 */
function errorExists(analysisResults) {
	return analysisResults.errorMessage != null;
}

/*
 * Returns a user-readable error message, containing
 * user-defined node names instead of node ids.
 *
 * Example message:
 * The model is not solvable because of conflicting constraints
 * involving nodes: mouse, keyboard, and pizza.
 *
 * @param {String} backendErrorMsg
 *   error message from backend
 * @returns {boolean}
 */
function getErrorMessage(backendErrorMsg) {

	// If node ids does not exist, just return the original error message for now
	if (!nodeIDsExists(backendErrorMsg)) {
		return backendErrorMsg;
	}

	var ids = getIDs(backendErrorMsg);
	var names = [];
	var actorNames = [];
	for (var i = 0; i < ids.length; i++) {
		names.push(getNodeName(ids[i]));
		actorNames.push(getParentActorNameById(ids[i]));
	}

	var s = 'The model is not solvable because of conflicting constraints involving nodes (with associated actors): ';
	var numOfNames = names.length;

	for (var i = 0; i < numOfNames - 1; i++) {
		s += names[i] + ' (' + actorNames[i] + ')';
		if (i < numOfNames - 2) {
			s += ', ';
		} else {
			s += ' ';
		}
	}

	s += 'and ' + names[numOfNames - 1] + ' (' + actorNames[numOfNames - 1] + ').';
	s += '\n\nOriginal Error: ' + backendErrorMsg;
	return s;
}

/*
 * Returns the actor name for an actor
 * that embeds an element with element id id.
 * If element with element id id is not embedded within an actor
 * returns 'no actor'.
 *
 * @param {String} id
 *   element id for the element of interest
 * @returns {String}
 */
function getParentActorNameById(id) {
	var actor = getParentActor(getElementById(id));
	if (actor) {
		return actor.attributes.attrs['.name'].text;
	}
	return 'no actor';
}

/*
 * Returns the actor which embeds the element of interest.
 * Returns null if there is no actor that embeds the element.
 * (If an actor embeds an element, the actor is the element's parent)
 *
 * @param {dia.Element} element
 * @returns {dia.Element | null}
 */
function getParentActor(element) {
	// get call the ancestors for the element
	var ancestors = element.getAncestors();
	if (ancestors.length == 0) {
		return null;
	}
	// if there is an ancestor, there would only be one
	return ancestors[0];
}

/*
 * Returns the element with element id id.
 * Returns null if no element with that element id exists.
 *
 * @param {String} id
 *   element id of the element of interest
 * @returns {dia.Element | null}
 */
function getElementById(id) {
	var elements = graph.getElements();
	for (var i = 0; i < elements.length; i++) {
		if (id == elements[i].attributes.elementid) {
			return elements[i];
		}
	}
}

/**
 * Returns true iff node ids exists in msg
 *
 * @param {String} msg
 * @returns {Boolean}
 */
function nodeIDsExists(msg) {
	var pattern = /N\d{4}/g;
	return backendErrorMsg.match(pattern) != null;
}

/*
 * Returns an array of all node ids that are mentioned in
 * the backendErrorMsg, in the order they appear.
 *
 * @param {String} backendErrorMsg
 *   error message from backend
 * @returns {Array of String}
 */
function getIDs(backendErrorMsg) {
	// this regex matches for an N, followed by 4 digits
	var pattern = /N\d{4}/g;
	var arr = backendErrorMsg.match(pattern);

	// remove the preceding N's to get each id
	for (var i = 0; i < arr.length; i++) {
		arr[i] = arr[i].substring(1);
	}

	return arr;
}
<|endoftext|>


<commit_before>(function ($) {
    $.fn.extend({
        expandoControl: function (getControllees, options) {
            if (typeof getControllees !== "function")
                return this;

            var _this = $(this);
            var __cookieName = "Exp";
            var settings = $.extend({
                path: "/",
                key: _this.selector,
                collapse: false,
                remember: true
            }, options);
            _this.each(function (index, element) {
                var controller = $(element);
                var glyph = $("");

                glyph.data("controllees", getControllees(controller));

                if (glyph.data("controllees").length === 0 || glyph.data("controllees").height() < 1) {
                    return;
                }

                if ((settings.remember && "closed" === $.orchard.setting(__cookieName, { key: settings.key + "-" + controller.text(), path: settings.path }))
                    || settings.collapse
                    || (controller.closest("li").hasClass("collapsed") && !(settings.remember && "open" === $.orchard.setting(__cookieName, { key: settings.key + "-" + controller.text(), path: settings.path })))) {
                    glyph.addClass("closed").data("controllees").hide();
                }
                else if (settings.collapse) {

                }

                glyph.click(function () {
                    var __this = $(this);

                    if (settings.remember && !settings.collapse) { // remembering closed state as true because that's not the default - doesn't make sense to remember if the controllees are always to be collapsed by default
                        // need to allow specified keys since these selectors could get *really* long
                        $.orchard.setting(__cookieName, !__this.hasClass("closed") ? "closed" : "open", { key: settings.key + "-" + controller.text(), path: settings.path });
                    }

                    if (__this.hasClass("closed") || __this.hasClass("closing")) {
                        __this.data("controllees").slideDown(300, function () { __this.removeClass("opening").removeClass("closed").addClass("open"); });
                        __this.addClass("opening");
                    }
                    else {
                        __this.data("controllees").slideUp(300, function () { __this.removeClass("closing").removeClass("open").addClass("closed"); });
                        __this.addClass("closing");
                    }

                    return false;
                });

                controller.prepend(glyph);
            });

            return this;
        }
    });

    $(".bulk-actions-auto select").change(function () {
        $(this).closest("form").find(".apply-bulk-actions-auto:first").click();
    });

    $("body").on("click", "[itemprop~='RemoveUrl']", function () {
        // don't show the confirm dialog if the link is also UnsafeUrl, as it will already be handled in base.js
        if ($(this).filter("[itemprop~='UnsafeUrl']").length == 1) {
            return false;
        }

    	// use a custom message if its set in data-message
        var dataMessage = $(this).data('message');
        if (dataMessage === undefined) {
        	dataMessage = confirmRemoveMessage;
        }

        return confirm(dataMessage);
    });

    $(".check-all").change(function () {
        $("input[type=checkbox]:not(:disabled)").prop('checked', $(this).prop("checked"))
    });

    // Handle keypress events in bulk action fieldsets that are part of a single form.
    // This will make sure the expected action executes when pressing "enter" on a text field.
    $("form .bulk-actions").on("keypress", "input[type='text']", function (e) {
        if (e.which != 13)
            return;

        var sender = $(this);
        var fieldset = sender.closest("fieldset.bulk-actions");
        var submitButton = fieldset.find("button[type='submit']");

        if (submitButton.length == 0)
            return;

        e.preventDefault();
        submitButton.click();
    });

    var generateMenuFilter = function () {
        var adminMenu = $("ul.menu-admin");
        var filterText = adminMenu.data("filter-watermark");
        var filterMenuItem = $('

<input id="adminfilter" type="text" class="text-box" placeholder=' + filterText + '>

');

        $("ul.menu-admin").prepend(filterMenuItem);

        var allListItems = $("ul.menu-admin li ul li").not("#NavFilter");
        var itemHeading = $("ul.menu-admin li h3");

        $("#adminfilter").on("keyup", function (e) {
            var a = $(this).val().toLowerCase();

            var filteredItemHeading = itemHeading.filter(function (b, c) {
                return $(c).text().toLowerCase().indexOf(a) !== -1;
            });

            itemHeading.show();
            itemHeading.parent().hide();
            filteredItemHeading.parent().show();
            if (filteredItemHeading.length == 0) {
                itemHeading.parent().hide();
                var childListItem = allListItems.filter(function (b, c) {
                    return $(c).text().toLowerCase().indexOf(a) !== -1;
                });

                allListItems.hide();
                childListItem.parent().parent().show();
                childListItem.show();
            } else {
                allListItems.show();
            }

            if (e.keyCode == 13) {
                var visibleItems = adminMenu.find("li a").filter(":visible");

                if (visibleItems.length > 0) {
                    var hit = visibleItems.filter(function(b, c) {
                        return $(c).text().toLowerCase().indexOf(a) !== -1;
                    });
                    location.href = hit.attr("href");
                }
            }
        });

        // Bind global hotkey 'CTRL+M' and 'ESC.
        $(document).on("keyup", function (e) {
            if ((e.which == 77 && e.ctrlKey) || e.which == 27) {
                var filterWrapper = $(".admin-menu-filter");

                var hideFilter = function() {
                    $("#adminfilter").val("");
                    filterWrapper.slideUp(75);
                };

                switch(e.keyCode) {
                    case 77: // 'm'
                        if (filterWrapper.is(":visible")) {
                            hideFilter();
                        } else {
                            filterWrapper.slideDown(75);
                            $("#adminfilter").focus();
                        }
                        break;
                    case 27: // 'esc'
                        hideFilter();
                        break;
                }
            }
        });
    };

    generateMenuFilter();
})(jQuery);

/*
 console-shim 1.0.2
 https://github.com/kayahr/console-shim
 Copyright (C) 2011 Klaus Reimer <k@ailis.de>
 Licensed under the MIT license
 (See http://www.opensource.org/licenses/mit-license)
*/
function f() { return function () { } }
(function () {
    function c(a, l, b) { var c = Array.prototype.slice.call(arguments, 2); return function () { var b = c.concat(Array.prototype.slice.call(arguments, 0)); a.apply(l, b) } } window.console || (window.console = {}); var a = window.console; if (!a.log) if (window.log4javascript) { var b = log4javascript.getDefaultLogger(); a.log = c(b.info, b); a.debug = c(b.debug, b); a.info = c(b.info, b); a.warn = c(b.warn, b); a.error = c(b.error, b) } else a.log = f(); a.debug || (a.debug = a.log); a.info || (a.info = a.log); a.warn || (a.warn = a.log); a.error || (a.error = a.log);
    if (null != window.__consoleShimTest__ || eval("/*@cc_on @_jscript_version \x3c\x3d 9@*/")) b = function (d) { var b, e, c; d = Array.prototype.slice.call(arguments, 0); c = d.shift(); e = d.length; if (1 < e && !1 !== window.__consoleShimTest__) { "string" != typeof d[0] && (d.unshift("%o"), e += 1); for (b = (b = d[0].match(/%[a-z]/g)) ? b.length + 1 : 1; b < e; b += 1) d[0] += " %o" } Function.apply.call(c, a, d) }, a.log = c(b, window, a.log), a.debug = c(b, window, a.debug), a.info = c(b, window, a.info), a.warn = c(b, window, a.warn), a.error = c(b, window, a.error); a.assert || (a.assert =
    function () { var d = Array.prototype.slice.call(arguments, 0); d.shift() || (d[0] = "Assertion failed: " + d[0], a.error.apply(a, d)) }); a.dir || (a.dir = a.log); a.dirxml || (a.dirxml = a.log); a.exception || (a.exception = a.error); if (!a.time || !a.timeEnd) { var g = {}; a.time = function (a) { g[a] = (new Date).getTime() }; a.timeEnd = function (b) { var c = g[b]; c && (a.log(b + ": " + ((new Date).getTime() - c) + "ms"), delete g[b]) } } a.table || (a.table = function (b, c) {
        var e, g, j, h, k; if (b && b instanceof Array && b.length) {
            if (!c || !(c instanceof Array)) for (e in c =
            [], b[0]) b[0].hasOwnProperty(e) && c.push(e); e = 0; for (g = b.length; e < g; e += 1) { j = []; h = 0; for (k = c.length; h < k; h += 1) j.push(b[e][c[h]]); Function.apply.call(a.log, a, j) }
        }
    }); a.clear || (a.clear = f()); a.trace || (a.trace = f()); a.group || (a.group = f()); a.groupCollapsed || (a.groupCollapsed = f()); a.groupEnd || (a.groupEnd = f()); a.timeStamp || (a.timeStamp = f()); a.profile || (a.profile = f()); a.profileEnd || (a.profileEnd = f()); a.count || (a.count = f())
})();<commit_msg>Prevent double-click on Publish/Save<commit_after>(function ($) {
    $.fn.extend({
        expandoControl: function (getControllees, options) {
            if (typeof getControllees !== "function")
                return this;

            var _this = $(this);
            var __cookieName = "Exp";
            var settings = $.extend({
                path: "/",
                key: _this.selector,
                collapse: false,
                remember: true
            }, options);
            _this.each(function (index, element) {
                var controller = $(element);
                var glyph = $("");

                glyph.data("controllees", getControllees(controller));

                if (glyph.data("controllees").length === 0 || glyph.data("controllees").height() < 1) {
                    return;
                }

                if ((settings.remember && "closed" === $.orchard.setting(__cookieName, { key: settings.key + "-" + controller.text(), path: settings.path }))
                    || settings.collapse
                    || (controller.closest("li").hasClass("collapsed") && !(settings.remember && "open" === $.orchard.setting(__cookieName, { key: settings.key + "-" + controller.text(), path: settings.path })))) {
                    glyph.addClass("closed").data("controllees").hide();
                }
                else if (settings.collapse) {

                }

                glyph.click(function () {
                    var __this = $(this);

                    if (settings.remember && !settings.collapse) { // remembering closed state as true because that's not the default - doesn't make sense to remember if the controllees are always to be collapsed by default
                        // need to allow specified keys since these selectors could get *really* long
                        $.orchard.setting(__cookieName, !__this.hasClass("closed") ? "closed" : "open", { key: settings.key + "-" + controller.text(), path: settings.path });
                    }

                    if (__this.hasClass("closed") || __this.hasClass("closing")) {
                        __this.data("controllees").slideDown(300, function () { __this.removeClass("opening").removeClass("closed").addClass("open"); });
                        __this.addClass("opening");
                    }
                    else {
                        __this.data("controllees").slideUp(300, function () { __this.removeClass("closing").removeClass("open").addClass("closed"); });
                        __this.addClass("closing");
                    }

                    return false;
                });

                controller.prepend(glyph);
            });

            return this;
        }
    });

    $(".bulk-actions-auto select").change(function () {
        $(this).closest("form").find(".apply-bulk-actions-auto:first").click();
    });

    $("body").on("click", "[itemprop~='RemoveUrl']", function () {
        // don't show the confirm dialog if the link is also UnsafeUrl, as it will already be handled in base.js
        if ($(this).filter("[itemprop~='UnsafeUrl']").length == 1) {
            return false;
        }

    	// use a custom message if its set in data-message
        var dataMessage = $(this).data('message');
        if (dataMessage === undefined) {
        	dataMessage = confirmRemoveMessage;
        }

        return confirm(dataMessage);
    });

    $(".check-all").change(function () {
        $("input[type=checkbox]:not(:disabled)").prop('checked', $(this).prop("checked"))
    });

    //Prevent double-click on buttons of type "submit"
    $("form button[type='submit'], form input[type='submit']").click(function (e) {
        var form = $(this).closest("form")[0];
        if (typeof(form.formSubmitted) != "undefined") {
            e.preventDefault();
            return;
        }
        form.formSubmitted = true;
    });

    // Handle keypress events in bulk action fieldsets that are part of a single form.
    // This will make sure the expected action executes when pressing "enter" on a text field.
    $("form .bulk-actions").on("keypress", "input[type='text']", function (e) {
        if (e.which != 13)
            return;

        var sender = $(this);
        var fieldset = sender.closest("fieldset.bulk-actions");
        var submitButton = fieldset.find("button[type='submit']");

        if (submitButton.length == 0)
            return;

        e.preventDefault();
        submitButton.click();
    });

    var generateMenuFilter = function () {
        var adminMenu = $("ul.menu-admin");
        var filterText = adminMenu.data("filter-watermark");
        var filterMenuItem = $('

<input id="adminfilter" type="text" class="text-box" placeholder=' + filterText + '>

');

        $("ul.menu-admin").prepend(filterMenuItem);

        var allListItems = $("ul.menu-admin li ul li").not("#NavFilter");
        var itemHeading = $("ul.menu-admin li h3");

        $("#adminfilter").on("keyup", function (e) {
            var a = $(this).val().toLowerCase();

            var filteredItemHeading = itemHeading.filter(function (b, c) {
                return $(c).text().toLowerCase().indexOf(a) !== -1;
            });

            itemHeading.show();
            itemHeading.parent().hide();
            filteredItemHeading.parent().show();
            if (filteredItemHeading.length == 0) {
                itemHeading.parent().hide();
                var childListItem = allListItems.filter(function (b, c) {
                    return $(c).text().toLowerCase().indexOf(a) !== -1;
                });

                allListItems.hide();
                childListItem.parent().parent().show();
                childListItem.show();
            } else {
                allListItems.show();
            }

            if (e.keyCode == 13) {
                var visibleItems = adminMenu.find("li a").filter(":visible");

                if (visibleItems.length > 0) {
                    var hit = visibleItems.filter(function(b, c) {
                        return $(c).text().toLowerCase().indexOf(a) !== -1;
                    });
                    location.href = hit.attr("href");
                }
            }
        });

        // Bind global hotkey 'CTRL+M' and 'ESC.
        $(document).on("keyup", function (e) {
            if ((e.which == 77 && e.ctrlKey) || e.which == 27) {
                var filterWrapper = $(".admin-menu-filter");

                var hideFilter = function() {
                    $("#adminfilter").val("");
                    filterWrapper.slideUp(75);
                };

                switch(e.keyCode) {
                    case 77: // 'm'
                        if (filterWrapper.is(":visible")) {
                            hideFilter();
                        } else {
                            filterWrapper.slideDown(75);
                            $("#adminfilter").focus();
                        }
                        break;
                    case 27: // 'esc'
                        hideFilter();
                        break;
                }
            }
        });
    };

    generateMenuFilter();
})(jQuery);

/*
 console-shim 1.0.2
 https://github.com/kayahr/console-shim
 Copyright (C) 2011 Klaus Reimer <k@ailis.de>
 Licensed under the MIT license
 (See http://www.opensource.org/licenses/mit-license)
*/
function f() { return function () { } }
(function () {
    function c(a, l, b) { var c = Array.prototype.slice.call(arguments, 2); return function () { var b = c.concat(Array.prototype.slice.call(arguments, 0)); a.apply(l, b) } } window.console || (window.console = {}); var a = window.console; if (!a.log) if (window.log4javascript) { var b = log4javascript.getDefaultLogger(); a.log = c(b.info, b); a.debug = c(b.debug, b); a.info = c(b.info, b); a.warn = c(b.warn, b); a.error = c(b.error, b) } else a.log = f(); a.debug || (a.debug = a.log); a.info || (a.info = a.log); a.warn || (a.warn = a.log); a.error || (a.error = a.log);
    if (null != window.__consoleShimTest__ || eval("/*@cc_on @_jscript_version \x3c\x3d 9@*/")) b = function (d) { var b, e, c; d = Array.prototype.slice.call(arguments, 0); c = d.shift(); e = d.length; if (1 < e && !1 !== window.__consoleShimTest__) { "string" != typeof d[0] && (d.unshift("%o"), e += 1); for (b = (b = d[0].match(/%[a-z]/g)) ? b.length + 1 : 1; b < e; b += 1) d[0] += " %o" } Function.apply.call(c, a, d) }, a.log = c(b, window, a.log), a.debug = c(b, window, a.debug), a.info = c(b, window, a.info), a.warn = c(b, window, a.warn), a.error = c(b, window, a.error); a.assert || (a.assert =
    function () { var d = Array.prototype.slice.call(arguments, 0); d.shift() || (d[0] = "Assertion failed: " + d[0], a.error.apply(a, d)) }); a.dir || (a.dir = a.log); a.dirxml || (a.dirxml = a.log); a.exception || (a.exception = a.error); if (!a.time || !a.timeEnd) { var g = {}; a.time = function (a) { g[a] = (new Date).getTime() }; a.timeEnd = function (b) { var c = g[b]; c && (a.log(b + ": " + ((new Date).getTime() - c) + "ms"), delete g[b]) } } a.table || (a.table = function (b, c) {
        var e, g, j, h, k; if (b && b instanceof Array && b.length) {
            if (!c || !(c instanceof Array)) for (e in c =
            [], b[0]) b[0].hasOwnProperty(e) && c.push(e); e = 0; for (g = b.length; e < g; e += 1) { j = []; h = 0; for (k = c.length; h < k; h += 1) j.push(b[e][c[h]]); Function.apply.call(a.log, a, j) }
        }
    }); a.clear || (a.clear = f()); a.trace || (a.trace = f()); a.group || (a.group = f()); a.groupCollapsed || (a.groupCollapsed = f()); a.groupEnd || (a.groupEnd = f()); a.timeStamp || (a.timeStamp = f()); a.profile || (a.profile = f()); a.profileEnd || (a.profileEnd = f()); a.count || (a.count = f())
})();<|endoftext|>