<commit_before>
module.exports = function (conf) {

	var fs = require('fs');
	var Promise = require('bluebird');
	var _ = require("underscore");
	var spawn = require('child_process').spawn;
	var path = require('path');
	var Joi = require('joi');

	var executionmethods = require('./executionserver.methods')(conf);

	var handler = {};

	handler.submitJob = function(doc, cwd){

		Joi.assert(doc, executionmethods.Job);

		return new Promise(function(resolve, reject){
			var command = 'bsub';
			var parameters = doc.parameters;

			var params = [];

			if(doc.jobparameters){
				params = doc.jobparameters;
			}

			params.push("-cwd");
			params.push(cwd);
			params.push("-e");
			params.push(path.join(cwd, doc._id + ".err"));
			params.push("-o");
			params.push(path.join(cwd, doc._id + ".out"));
			params.push("-u");
			params.push(doc.userEmail);
			params.push("-J");
			params.push(doc.userEmail);

			params.push(doc.executable);
			if(parameters){
				for(var i = 0; i < parameters.length; i++){
					var param = parameters[i];
					if(param.flag){
						params.push(param.flag);
					}
					if(param.name){
						params.push(param.name);
					}
				}
			}

			try{
				const runcommand = spawn(command, params);

				var allerror = "";
				runcommand.stderr.on('data', function(data){
					allerror += data;
				});

				var alldata = "";
				runcommand.stdout.on('data', function(data){
					alldata += data;
				});

				//"sample: Job <898104> is submitted to default queue <day>"
				runcommand.on('close', function(code){
					if(code){
						resolve({
							status: 'FAIL',
							error: allerror + alldata
						});
					}

					var ind = alldata.indexOf('<') + 1;
                    var jobid = alldata.substr(ind, alldata.indexOf('>') - ind);

					resolve({
						jobid : Number.parseInt(jobid),
						status: 'RUN'
					});
				});

			}catch(e){
				reject({
					status: "FAIL",
					error: e
				});
			}

		});

	}

	handler.getJobStatus = function(doc){

		Joi.assert(doc.jobstatus, executionmethods.Joijobstatus);

		return new Promise(function(resolve, reject){

			try{

				var jobid = doc.jobstatus.jobid;
				var params = ["-J", doc.userEmail, jobid];

				const ps = spawn('bjobs', params);

				var allerror = "";
				ps.stderr.on('data', function(data){
					allerror += data;
				});

				var alldata = "";
				ps.stdout.on('data', function(data){
					alldata += data;
				});

				//"sample success: 898104  jprieto DONE  day        killdevil-l donor_pool2 *gmail.com Feb 14 11:16"
				//"sample fail: Job <8981> is not found"

				ps.on('close', function(code){

					if(alldata && (alldata.indexOf('DONE') || alldata.indexOf('is not found'))){
						resolve({
							status: 'DONE',
							stat: alldata
						});
					}else if(alldata && alldata.indexOf('EXIT')){
						resolve({
							status: 'EXIT',
							stat: alldata
						});
					}else if(code || allerror){
						resolve({
							status: 'FAIL',
							error: allerror
						});
					}else{
						resolve({
							status: 'RUN',
							stat: alldata
						});
					}

				});

			}catch(e){
				reject(e);
			}

		});
	}

	handler.killJob = function(doc){

		Joi.assert(doc.jobstatus, executionmethods.Joijobstatus);

		return new Promise(function(resolve, reject){

			try{

				var jobid = doc.jobstatus.jobid;
				var params = ["-J", doc.userEmail, jobid];

				const kill = spawn('bkill', params);

				var allerror = "";
				kill.stderr.on('data', function(data){
					allerror += data;
				});

				var alldata = "";
				kill.stdout.on('data', function(data){
					alldata += data;
				});

				kill.on('close', function(code){
					resolve({
						status: 'KILL',
						stat: allerror + alldata
					})
				});

			}catch(e){
				reject(e);
			}

		});

	}

	return handler;
}<commit_msg>BUG: If job is done and not found. The information appears in not found<commit_after>
module.exports = function (conf) {

	var fs = require('fs');
	var Promise = require('bluebird');
	var _ = require("underscore");
	var spawn = require('child_process').spawn;
	var path = require('path');
	var Joi = require('joi');

	var executionmethods = require('./executionserver.methods')(conf);

	var handler = {};

	handler.submitJob = function(doc, cwd){

		Joi.assert(doc, executionmethods.Job);

		return new Promise(function(resolve, reject){
			var command = 'bsub';
			var parameters = doc.parameters;

			var params = [];

			if(doc.jobparameters){
				params = doc.jobparameters;
			}

			params.push("-cwd");
			params.push(cwd);
			params.push("-e");
			params.push(path.join(cwd, doc._id + ".err"));
			params.push("-o");
			params.push(path.join(cwd, doc._id + ".out"));
			params.push("-u");
			params.push(doc.userEmail);
			params.push("-J");
			params.push(doc.userEmail);

			params.push(doc.executable);
			if(parameters){
				for(var i = 0; i < parameters.length; i++){
					var param = parameters[i];
					if(param.flag){
						params.push(param.flag);
					}
					if(param.name){
						params.push(param.name);
					}
				}
			}

			try{
				const runcommand = spawn(command, params);

				var allerror = "";
				runcommand.stderr.on('data', function(data){
					allerror += data;
				});

				var alldata = "";
				runcommand.stdout.on('data', function(data){
					alldata += data;
				});

				//"sample: Job <898104> is submitted to default queue <day>"
				runcommand.on('close', function(code){
					if(code){
						resolve({
							status: 'FAIL',
							error: allerror + alldata
						});
					}

					var ind = alldata.indexOf('<') + 1;
                    var jobid = alldata.substr(ind, alldata.indexOf('>') - ind);

					resolve({
						jobid : Number.parseInt(jobid),
						status: 'RUN'
					});
				});

			}catch(e){
				reject({
					status: "FAIL",
					error: e
				});
			}

		});

	}

	handler.getJobStatus = function(doc){

		Joi.assert(doc.jobstatus, executionmethods.Joijobstatus);

		return new Promise(function(resolve, reject){

			try{

				var jobid = doc.jobstatus.jobid;
				var params = ["-J", doc.userEmail, jobid];

				const ps = spawn('bjobs', params);

				var allerror = "";
				ps.stderr.on('data', function(data){
					allerror += data;
				});

				var alldata = "";
				ps.stdout.on('data', function(data){
					alldata += data;
				});

				//"sample success: 898104  jprieto DONE  day        killdevil-l donor_pool2 *gmail.com Feb 14 11:16"
				//"sample fail: Job <8981> is not found"

				ps.on('close', function(code){

					if(alldata && (alldata.indexOf('DONE') || allerror && allerror.indexOf('is not found'))){
						resolve({
							status: 'DONE',
							stat: alldata
						});
					}else if(alldata && alldata.indexOf('EXIT')){
						resolve({
							status: 'EXIT',
							stat: alldata
						});
					}else if(code || allerror){
						resolve({
							status: 'FAIL',
							error: allerror
						});
					}else{
						resolve({
							status: 'RUN',
							stat: alldata
						});
					}

				});

			}catch(e){
				reject(e);
			}

		});
	}

	handler.killJob = function(doc){

		Joi.assert(doc.jobstatus, executionmethods.Joijobstatus);

		return new Promise(function(resolve, reject){

			try{

				var jobid = doc.jobstatus.jobid;
				var params = ["-J", doc.userEmail, jobid];

				const kill = spawn('bkill', params);

				var allerror = "";
				kill.stderr.on('data', function(data){
					allerror += data;
				});

				var alldata = "";
				kill.stdout.on('data', function(data){
					alldata += data;
				});

				kill.on('close', function(code){
					resolve({
						status: 'KILL',
						stat: allerror + alldata
					})
				});

			}catch(e){
				reject(e);
			}

		});

	}

	return handler;
}<|endoftext|>


<commit_before>
var debug = require('debug');
var lg = debug('vash:codegen');

var gens = {}

gens.VashProgram = function(node, opts, generate) {
  return node.body.map(generate).join('');
}

gens.VashExplicitExpression = function(node, opts, generate) {
  var str = node.values.map(generate).join('');
  return '(' + maybeHTMLEscape(node, opts, str) + ')';
}

gens.VashExpression = function(node, opts, generate) {
  var str = node.values.map(generate).join('');
  if (parentIsContent(node)) {
    str = bewrap(maybeHTMLEscape(node, opts, str));
  }
  return str;
}

gens.VashMarkup = function(node, opts, generate) {
  var name = node.expression
    ? node.expression.values.map(generate).join('')
    : bcwrap(node.name);
  return ''
    + bcwrap('<')
    + name
    + bcwrap(node.attributes.length ? ' ' : '')
    + node.attributes.map(generate).join(' ')
    + (node.isVoid
      ? bcwrap(node.voidClosed ? ' />' : '>')
      : bcwrap('>')
        + node.values.map(generate).join('')
        + bcwrap('</')
        + name
        + bcwrap('>'))
}

gens.VashMarkupAttribute = function(node, opts, generate) {
  var quote = node.rightIsQuoted || '';
  quote = escapeMarkupContent(quote);
  return node.left.map(generate).join('')
    + (node.right.length
      ?   bcwrap('=' + quote)
        + node.right.map(generate).join('')
        + bcwrap(quote)
      : '');
}

gens.VashBlock = function(node, opts, generate) {
  return node.head.map(generate).join('')
    + '{'
    + node.values.map(generate).join('')
    + '}'
    + node.tail.map(generate).join('');
}

gens.VashIndexExpression = function(node, opts, generate) {
  var str = node.values.map(generate).join('');
  return '[' + str + ']';
}

gens.VashText = function(node, opts, generate) {
  return parentIsContent(node)
    ? bcwrap(escapeMarkupContent(node.value))
    : node.value;
}

var reQuote = /(['"])/g;
var reEscapedQuote = /\\+(["'])/g;
var reLineBreak = /\n/g;
var reHelpersName = /HELPERSNAME/g;
var reModelName = /MODELNAME/g;
var reOriginalMarkup = /ORIGINALMARKUP/g;

function escapeMarkupContent(str) {
  return str
    .replace(/(')/, '\\$1')
    .replace(reLineBreak, '\\n');
}

var BUFFER_HEAD = '\n__vbuffer.push(';
var BUFFER_TAIL = ');\n';

// buffer content wrap
function bcwrap(str) {
  return BUFFER_HEAD + '\'' + str + '\'' + BUFFER_TAIL;
}

// buffer expression wrap
function bewrap(str) {
  return BUFFER_HEAD + str + BUFFER_TAIL;
}

function parentIsContent(node) {
  return node.parent.type === 'VashMarkup'
    || node.parent.type === 'VashMarkupAttribute'
    || node.parent.type === 'VashProgram';
}

function maybeHTMLEscape(node, opts, str) {
  if (parentIsContent(node) && opts.htmlEscape) {
    return opts.helpersName + '.escape(' + str + ').toHtmlString()';
  } else {
    return str;
  }
}

function replaceDevTokens(str, opts){
  return str
    .replace( reHelpersName, opts.helpersName )
    .replace( reModelName, opts.modelName );
}

function head(opts){
  var str = ''
    + (opts.debug ? 'try { \n' : '')
    + 'var __vbuffer = HELPERSNAME.buffer; \n'
    + 'HELPERSNAME.options = __vopts; \n'
    + 'MODELNAME = MODELNAME || {}; \n'
    + (opts.useWith ? 'with( MODELNAME ){ \n' : '');

  str = replaceDevTokens(str, opts);
  return str;
}

function helperHead(opts){
  var str = ''
    + (options.debug ? 'try { \n' : '')
    + 'var __vbuffer = this.buffer; \n'
    + 'var MODELNAME = this.model; \n'
    + 'var HELPERSNAME = this; \n';

  str = this.replaceDevTokens(str);
  return str;
}

function tail(opts){
  var str = ''
    + (opts.simple
      ? 'return HELPERSNAME.buffer.join(""); \n'
      : '(__vopts && __vopts.onRenderEnd && __vopts.onRenderEnd(null, HELPERSNAME)); \n'
        + 'return (__vopts && __vopts.asContext) \n'
        + '  ? HELPERSNAME \n'
        + '  : HELPERSNAME.toString(); \n' )
    + (opts.useWith ? '} \n' : '')
    + (opts.debug ? '} catch( e ){ \n'
      + '  HELPERSNAME.reportError( e, HELPERSNAME.vl, HELPERSNAME.vc, "ORIGINALMARKUP" ); \n'
      + '} \n' : '');

  str = replaceDevTokens(str, opts)
    .replace(reOriginalMarkup, escapeForDebug(opts.source));

  return str;
}

 function helperTail(opts){
  var str = ''
    + (options.debug ? '} catch( e ){ \n'
      + '  HELPERSNAME.reportError( e, HELPERSNAME.vl, HELPERSNAME.vc, "ORIGINALMARKUP" ); \n'
      + '} \n' : '');

  str = replaceDevTokens(str)
    .replace(reOriginalMarkup, escapeForDebug(opts.source));

  return str;
}

function escapeForDebug( str ){
  return str
    .replace(reLineBreak, '!LB!')
    .replace(reQuote, '\\$1')
    .replace(reEscapedQuote, '\\$1')
}

// Not necessary, but provides faster execution when not in debug mode
// and looks nicer.
function condenseContent(str) {
  return str
    .replace(/'\);\n+__vbuffer.push\('/g, '')
    .replace(/\n+/g, '\n');
}

function generate(node, opts) {

  function gen(opts, node) {
    lg('Entering ' + node.type);
    var str = gens[node.type](node, opts, genChild);
    lg('Leaving ' + node.type);
    return str;

    function genChild(child) {
      if (!child.parent) child.parent = node;
      return gen(opts, child);
    }
  }

  var generated = gen(opts, node);

  var body;
  if(!opts.asHelper){
    body = head(opts) + generated + tail(opts);
  } else {
    body = helperHead(opts) + generated + helperTail(opts);
  }

  return condenseContent(body);
}

module.exports = generate;<commit_msg>codegen: empty attribute value if quotes are found<commit_after>
var debug = require('debug');
var lg = debug('vash:codegen');

var gens = {}

gens.VashProgram = function(node, opts, generate) {
  return node.body.map(generate).join('');
}

gens.VashExplicitExpression = function(node, opts, generate) {
  var str = node.values.map(generate).join('');
  return '(' + maybeHTMLEscape(node, opts, str) + ')';
}

gens.VashExpression = function(node, opts, generate) {
  var str = node.values.map(generate).join('');
  if (parentIsContent(node)) {
    str = bewrap(maybeHTMLEscape(node, opts, str));
  }
  return str;
}

gens.VashMarkup = function(node, opts, generate) {
  var name = node.expression
    ? node.expression.values.map(generate).join('')
    : bcwrap(node.name);
  return ''
    + bcwrap('<')
    + name
    + bcwrap(node.attributes.length ? ' ' : '')
    + node.attributes.map(generate).join(bcwrap(' '))
    + (node.isVoid
      ? bcwrap(node.voidClosed ? ' />' : '>')
      : bcwrap('>')
        + node.values.map(generate).join('')
        + bcwrap('</')
        + name
        + bcwrap('>'))
}

gens.VashMarkupAttribute = function(node, opts, generate) {
  var quote = node.rightIsQuoted || '';
  quote = escapeMarkupContent(quote);
  return node.left.map(generate).join('')
    + (node.right.length || node.rightIsQuoted
      ?   bcwrap('=' + quote)
        + node.right.map(generate).join('')
        + bcwrap(quote)
      : '');
}

gens.VashBlock = function(node, opts, generate) {
  return node.head.map(generate).join('')
    + '{'
    + node.values.map(generate).join('')
    + '}'
    + node.tail.map(generate).join('');
}

gens.VashIndexExpression = function(node, opts, generate) {
  var str = node.values.map(generate).join('');
  return '[' + str + ']';
}

gens.VashText = function(node, opts, generate) {
  return parentIsContent(node)
    ? bcwrap(escapeMarkupContent(node.value))
    : node.value;
}

var reQuote = /(['"])/g;
var reEscapedQuote = /\\+(["'])/g;
var reLineBreak = /\n/g;
var reHelpersName = /HELPERSNAME/g;
var reModelName = /MODELNAME/g;
var reOriginalMarkup = /ORIGINALMARKUP/g;

function escapeMarkupContent(str) {
  return str
    .replace(/(')/, '\\$1')
    .replace(reLineBreak, '\\n');
}

var BUFFER_HEAD = '\n__vbuffer.push(';
var BUFFER_TAIL = ');\n';

// buffer content wrap
function bcwrap(str) {
  return BUFFER_HEAD + '\'' + str + '\'' + BUFFER_TAIL;
}

// buffer expression wrap
function bewrap(str) {
  return BUFFER_HEAD + str + BUFFER_TAIL;
}

function parentIsContent(node) {
  return node.parent.type === 'VashMarkup'
    || node.parent.type === 'VashMarkupAttribute'
    || node.parent.type === 'VashProgram';
}

function maybeHTMLEscape(node, opts, str) {
  if (parentIsContent(node) && opts.htmlEscape) {
    return opts.helpersName + '.escape(' + str + ').toHtmlString()';
  } else {
    return str;
  }
}

function replaceDevTokens(str, opts){
  return str
    .replace( reHelpersName, opts.helpersName )
    .replace( reModelName, opts.modelName );
}

function head(opts){
  var str = ''
    + (opts.debug ? 'try { \n' : '')
    + 'var __vbuffer = HELPERSNAME.buffer; \n'
    + 'HELPERSNAME.options = __vopts; \n'
    + 'MODELNAME = MODELNAME || {}; \n'
    + (opts.useWith ? 'with( MODELNAME ){ \n' : '');

  str = replaceDevTokens(str, opts);
  return str;
}

function helperHead(opts){
  var str = ''
    + (options.debug ? 'try { \n' : '')
    + 'var __vbuffer = this.buffer; \n'
    + 'var MODELNAME = this.model; \n'
    + 'var HELPERSNAME = this; \n';

  str = this.replaceDevTokens(str);
  return str;
}

function tail(opts){
  var str = ''
    + (opts.simple
      ? 'return HELPERSNAME.buffer.join(""); \n'
      : '(__vopts && __vopts.onRenderEnd && __vopts.onRenderEnd(null, HELPERSNAME)); \n'
        + 'return (__vopts && __vopts.asContext) \n'
        + '  ? HELPERSNAME \n'
        + '  : HELPERSNAME.toString(); \n' )
    + (opts.useWith ? '} \n' : '')
    + (opts.debug ? '} catch( e ){ \n'
      + '  HELPERSNAME.reportError( e, HELPERSNAME.vl, HELPERSNAME.vc, "ORIGINALMARKUP" ); \n'
      + '} \n' : '');

  str = replaceDevTokens(str, opts)
    .replace(reOriginalMarkup, escapeForDebug(opts.source));

  return str;
}

 function helperTail(opts){
  var str = ''
    + (options.debug ? '} catch( e ){ \n'
      + '  HELPERSNAME.reportError( e, HELPERSNAME.vl, HELPERSNAME.vc, "ORIGINALMARKUP" ); \n'
      + '} \n' : '');

  str = replaceDevTokens(str)
    .replace(reOriginalMarkup, escapeForDebug(opts.source));

  return str;
}

function escapeForDebug( str ){
  return str
    .replace(reLineBreak, '!LB!')
    .replace(reQuote, '\\$1')
    .replace(reEscapedQuote, '\\$1')
}

// Not necessary, but provides faster execution when not in debug mode
// and looks nicer.
function condenseContent(str) {
  return str
    .replace(/'\);\n+__vbuffer.push\('/g, '')
    .replace(/\n+/g, '\n');
}

function generate(node, opts) {

  function gen(opts, node) {
    lg('Entering ' + node.type);
    var str = gens[node.type](node, opts, genChild);
    lg('Leaving ' + node.type);
    return str;

    function genChild(child) {
      if (!child.parent) child.parent = node;
      return gen(opts, child);
    }
  }

  var generated = gen(opts, node);

  var body;
  if(!opts.asHelper){
    body = head(opts) + generated + tail(opts);
  } else {
    body = helperHead(opts) + generated + helperTail(opts);
  }

  return condenseContent(body);
}

module.exports = generate;<|endoftext|>


<commit_before>/**
 * @fileOverview jQuery.autosave
 *
 * @author Kyle Florence
 * @website https://github.com/kflorence/jquery-autosave
 * @version 1.0.0
 *
 * Inspired by the jQuery.autosave plugin written by Raymond Julin,
 * Mads Erik Forberg and Simen Graaten.
 *
 * Dual licensed under the MIT and BSD Licenses.
 */
(function(c,e){var d=function(i,g,k){var h=c(i),f=/^(checked|selectedIndex)$/,j=("onpropertychange" in document.body);if(!h.length||typeof g!=="string"){return h}if(g!=="change"){return h.bind(g,k)}h.each(function(){g=j&&(this.type==="checkbox"||this.tagName.toLowerCase()==="select"&&this.multiple)?"propertychange":"change";c(this).bind(g,function(l){if(l.type!=="propertychange"||f.test(window.event.propertyName)){k.call(this,l)}})})};var a=function(i,g){var f={},h=typeof i;if(h==="function"){f.method=i}else{if(h==="string"&&i in g){f=g[i]}else{if(h==="object"){h=typeof i.method;if(h==="function"){f=i}else{if(h==="string"&&i.method in g){f=g[i.method]}}if(typeof f.options==="object"){f.options=c.extend(true,{},f.options,i.options)}else{f.options={}}}}}return f};c.autosave={timer:0,$queues:c({}),options:{namespace:"autosave",callbacks:{trigger:"change",scope:null,data:null,condition:null,save:"ajax"},events:{save:"save",saved:"saved",changed:"changed"},classes:{changed:"changed",ignore:"ignore"}},initialize:function(j,g){var f=this;c.extend(this,{context:j.context||document,selector:j.selector||j,options:c.extend(true,{},this.options,g)});if(this.elements().length){var i,k=this.forms(),h=this.inputs();k.data("autosave",this);c.each(this.options.events,function(m,l){f.options.events[m]=[l,f.options.namespace].join(".")});c.each(this.options.classes,function(l,m){f.options.classes[l]=[f.options.namespace,m].join("-")});c.each(this.options.callbacks,function(l,m){i=[];if(m){c.each(c.isArray(m)?m:[m],function(n,o){o=a(o,f.callbacks[l]);if(c.isFunction(o.method)){i.push(o)}})}f.options.callbacks[l]=i});d(k,this.options.events.save,function(l){f.save(this,l.type)});d(h,"change",function(l){c(this).addClass(f.options.classes.changed);c(this.form).triggerHandler(f.options.events.changed,[this])});c.each(this.options.callbacks.trigger,function(m,l){l.method.call(f,l.options)})}return j},elements:function(f,g){f=f||this.selector;g=g||this.context;return c(f,g).filter(function(){return(this.elements||this.form)})},forms:function(f){return c(c.unique(this.elements(f).map(function(){return this.elements?this:this.form}).get()))},inputs:function(f){return this.elements(f).map(function(){return this.elements?c.makeArray(this.elements):this})},validInputs:function(f){var g=this;return this.inputs(f).filter(function(){return !c(this).hasClass(g.options.classes.ignore)})},changedInputs:function(f){var g=this;return this.inputs(f).filter(function(){return c(this).hasClass(g.options.classes.changed)})},startInterval:function(g){var f=this;g=g||this.interval;if(this.timer){this.stopInterval()}if(!isNaN(parseInt(g))){this.timer=setTimeout(function(){f.save(false,f.timer)},g)}},stopInterval:function(){clearTimeout(this.timer);this.timer=null},save:function(f,h){var g=this,k=false,i=this.validInputs(f);if(this.options.callbacks.save.length){c.each(this.options.callbacks.scope,function(m,n){i=n.method.call(g,n.options,i)});if(i.length){var j=true,l=i.serializeArray();c.each(this.options.callbacks.data,function(m,n){l=n.method.call(g,n.options,i,l)});c.each(this.options.callbacks.condition,function(m,n){return(j=n.method.call(g,n.options,i,l,h))!==false});if(j){c.each(this.options.callbacks.save,function(m,n){g.$queues.queue("save",function(){if(n.method.call(g,n.options,l)!==false){g.next("save")}})});k=true}}}this.next("save",k)},next:function(h,g){var f=this.$queues.queue(h);if(f&&f.length){this.$queues.dequeue(h)}else{this.finished(f,h,g)}},finished:function(f,h,g){if(h==="save"){if(f){this.forms().triggerHandler(this.options.events.saved)}if(g!==false){this.changedInputs().removeClass(this.options.classes.changed)}if(this.timer){this.startInterval()}}}};var b=c.autosave.callbacks={};c.each(c.autosave.options.callbacks,function(f){b[f]={}});c.extend(b.trigger,{change:{method:function(){var f=this;this.forms().bind(this.options.events.changed,function(h,g){f.save(g,h.type)})}},interval:{method:function(f){if(!isNaN(parseInt(f.interval))){this.startInterval(this.interval=f.interval)}},options:{interval:30000}}});c.extend(b.scope,{all:{method:function(){return this.validInputs()}},changed:{method:function(){return this.changedInputs()}}});c.extend(b.data,{serializeObject:{method:function(f,g){var h={};c.each(g.serializeArray(),function(k,l){var m=l.name,j=l.value;h[m]=h[m]===e?j:c.isArray(h[m])?h[m].concat(j):[h[m],j]});return h}}});c.extend(b.condition,{interval:{method:function(g,h,i,f){return(!this.timer||this.timer===f)}},changed:{method:function(){return this.changedInputs().length>0}}});c.extend(b.save,{ajax:{method:function(g,h){var f=this;c.ajax(c.extend(true,{data:h},g,{complete:function(j,i){if(c.isFunction(g.complete)){g.complete.apply(f,arguments)}f.next("save")}}));return false},options:{url:window.location.href,type:"POST"}}});c.fn.autosave=function(f){return c.extend({},c.autosave).initialize(this,f)}})(jQuery);
<commit_msg>Update to 1.0.20110421<commit_after>/**
 * @fileOverview jQuery.autosave
 *
 * @author Kyle Florence
 * @website https://github.com/kflorence/jquery-autosave
 * @version 1.0.20110421
 *
 * Inspired by the jQuery.autosave plugin written by Raymond Julin,
 * Mads Erik Forberg and Simen Graaten.
 *
 * Dual licensed under the MIT and BSD Licenses.
 */
(function(a,b,c,d){var e=function(d,e,f){var g=a(d),h=/^(checked|selectedIndex)$/,i="onpropertychange"in c.body;if(!g.length||typeof e!="string")return g;if(e!=="change")return g.bind(e,f);g.each(function(){e=i&&(this.type==="checkbox"||this.tagName.toLowerCase()==="select"&&this.multiple)?"propertychange":"change",a(this).bind(e,function(a){(a.type!=="propertychange"||h.test(b.event.propertyName))&&f.call(this,a)})})},f=function(b,c){var d={},e=typeof b;e==="function"?d.method=b:e==="string"&&b in c?d=c[b]:e==="object"&&(e=typeof b.method,e==="function"?d=b:e==="string"&&b.method in c&&(d=c[b.method]),typeof d.options=="object"?d.options=a.extend(!0,{},d.options,b.options):d.options={});return d};a.autosave={timer:0,$queues:a({}),options:{namespace:"autosave",callbacks:{trigger:"change",scope:null,data:null,condition:null,save:"ajax"},events:{save:"save",saved:"saved",changed:"changed"},classes:{changed:"changed",ignore:"ignore"}},initialize:function(b,d){var g=this;a.extend(this,{context:b.context||c,selector:b.selector||b,options:a.extend(!0,{},this.options,d)});if(this.elements().length){var h,i=this.forms(),j=this.inputs();i.data(this.options.namespace,this),a.each(this.options.events,function(a,b){g.options.events[a]=[b,g.options.namespace].join(".")}),a.each(this.options.classes,function(a,b){g.options.classes[a]=[g.options.namespace,b].join("-")}),a.each(this.options.callbacks,function(b,c){h=[],c&&a.each(a.isArray(c)?c:[c],function(c,d){d=f(d,g.callbacks[b]),a.isFunction(d.method)&&h.push(d)}),g.options.callbacks[b]=h}),e(i,this.options.events.save,function(a,b){g.save(b,a.type)}),e(j,"change",function(b){a(this).addClass(g.options.classes.changed),a(this.form).triggerHandler(g.options.events.changed,[this])}),a.each(this.options.callbacks.trigger,function(a,b){b.method.call(g,b.options)})}return b},elements:function(b,c){b=b||this.selector,c=c||this.context;return a(b,c).filter(function(){return this.elements||this.form})},forms:function(b){return a(a.unique(this.elements(b).map(function(){return this.elements?this:this.form}).get()))},inputs:function(b){return this.elements(b).map(function(){return this.elements?a.makeArray(this.elements):this})},validInputs:function(b){var c=this;return this.inputs(b).filter(function(){return!a(this).hasClass(c.options.classes.ignore)})},changedInputs:function(b){var c=this;return this.inputs(b).filter(function(){return a(this).hasClass(c.options.classes.changed)})},startInterval:function(a){var b=this;a=a||this.interval,this.timer&&this.stopInterval(),isNaN(parseInt(a))||(this.timer=setTimeout(function(){b.save(!1,b.timer)},a))},stopInterval:function(){clearTimeout(this.timer),this.timer=null},save:function(b,c){var d=this,e=!1,f=this.validInputs(b);if(this.options.callbacks.save.length){a.each(this.options.callbacks.scope,function(a,b){f=b.method.call(d,b.options,f)});if(f.length){var g=!0,h=f.serializeArray();a.each(this.options.callbacks.data,function(a,b){h=b.method.call(d,b.options,f,h)}),a.each(this.options.callbacks.condition,function(a,b){return(g=b.method.call(d,b.options,f,h,c))!==!1}),g&&(a.each(this.options.callbacks.save,function(a,b){d.$queues.queue("save",function(){b.method.call(d,b.options,h)!==!1&&d.next("save")})}),e=!0)}}this.next("save",e)},next:function(a,b){var c=this.$queues.queue(a);c&&c.length?this.$queues.dequeue(a):this.finished(c,a,b)},finished:function(a,b,c){b==="save"&&(a&&this.forms().triggerHandler(this.options.events.saved),c!==!1&&this.changedInputs().removeClass(this.options.classes.changed),this.timer&&this.startInterval())}};var g=a.autosave.callbacks={};a.each(a.autosave.options.callbacks,function(a){g[a]={}}),a.extend(g.trigger,{change:{method:function(){var a=this;this.forms().bind(this.options.events.changed,function(b,c){a.save(c,b.type)})}},interval:{method:function(a){isNaN(parseInt(a.interval))||this.startInterval(this.interval=a.interval)},options:{interval:3e4}}}),a.extend(g.scope,{all:{method:function(){return this.validInputs()}},changed:{method:function(){return this.changedInputs()}}}),a.extend(g.data,{serializeObject:{method:function(b,c){var e={};a.each(c.serializeArray(),function(b,c){var f=c.name,g=c.value;e[f]=e[f]===d?g:a.isArray(e[f])?e[f].concat(g):[e[f],g]});return e}}}),a.extend(g.condition,{interval:{method:function(a,b,c,d){return!this.timer||this.timer===d}},changed:{method:function(){return this.changedInputs().length>0}}}),a.extend(g.save,{ajax:{method:function(b,c){var d=this;a.ajax(a.extend(!0,{data:c},b,{complete:function(c,e){a.isFunction(b.complete)&&b.complete.apply(d,arguments),d.next("save")}}));return!1},options:{url:b.location.href,type:"POST"}}}),a.fn.autosave=function(b){return a.extend({},a.autosave).initialize(this,b)}})(jQuery,window,document);
<|endoftext|>


<commit_before>import firebase from "firebase/app";
import "firebase/auth";
import firebaseConfig from "./config/firebaseConfig";
import "regenerator-runtime/runtime";

firebase.initializeApp(firebaseConfig);
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.NONE);

const postIdTokenToAuth = (idToken) => {
  return fetch("/authentication", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: idToken,
  });
};

const googleProvider = new firebase.auth.GoogleAuthProvider();
const signIn = (callback) => {
  firebase
    .auth()
    .signInWithPopup(googleProvider)
    .then((result) => {
      let user = result.user;
      user.getIdToken().then((idToken) => {
        postIdTokenToAuth(idToken).then((res) => {
          callback(res.ok, {
            email: user.email,
            displayName: user.displayName,
            id: 1, // TEMPORARY
          });
        });
      });
    });
};

const signOut = () => {
  return firebase
    .auth()
    .currentUser.getIdToken(true)
    .then(() => {
      return fetch("/authentication", {
        method: "DELETE",
        headers: {
          "Content-Type": "application/json",
        },
      });
    });
};

const persistLoginStatus = (user) => {
  // save user details to localstorage
  localStorage.setItem("user", user);
};

const loadLoginStatus = () => {
  // read user details from localstorage
  return {
    isLoggedIn: false,
  };
};

const clearPersistedLoginStatus = () => {
  // clear user details from localstorage
};

export default {
  signIn: signIn,
  signOut: signOut,
  persistLoginStatus: persistLoginStatus,
  loadLoginStatus: loadLoginStatus,
  clearPersistedLoginStatus: clearPersistedLoginStatus,
};
<commit_msg>Remove user from local storage<commit_after>import firebase from "firebase/app";
import "firebase/auth";
import firebaseConfig from "./config/firebaseConfig";
import "regenerator-runtime/runtime";

firebase.initializeApp(firebaseConfig);
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.NONE);

const postIdTokenToAuth = (idToken) => {
  return fetch("/authentication", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: idToken,
  });
};

const googleProvider = new firebase.auth.GoogleAuthProvider();
const signIn = (callback) => {
  firebase
    .auth()
    .signInWithPopup(googleProvider)
    .then((result) => {
      let user = result.user;
      user.getIdToken().then((idToken) => {
        postIdTokenToAuth(idToken).then((res) => {
          callback(res.ok, {
            email: user.email,
            displayName: user.displayName,
            id: 1, // TEMPORARY
          });
        });
      });
    });
};

const signOut = () => {
  return firebase
    .auth()
    .currentUser.getIdToken(true)
    .then(() => {
      return fetch("/authentication", {
        method: "DELETE",
        headers: {
          "Content-Type": "application/json",
        },
      });
    });
};

const persistLoginStatus = (user) => {
  // save user details to localstorage
  localStorage.setItem("user", user);
};

const loadLoginStatus = () => {
  // read user details from localstorage
  return {
    isLoggedIn: false,
  };
};

const clearPersistedLoginStatus = () => {
  // clear user details from localstorage
  localStorage.removeItem("user");
};

export default {
  signIn: signIn,
  signOut: signOut,
  persistLoginStatus: persistLoginStatus,
  loadLoginStatus: loadLoginStatus,
  clearPersistedLoginStatus: clearPersistedLoginStatus,
};
<|endoftext|>


<commit_before>// This is a page script run in panel.html to handle the input and UIs.

'use strict';

var CandidatesDisplay = {
  candidatesElement: null,

  candidates: [],
  candidatePage: 0,

  init: function cd_init() {
    this.candidatesElement = document.getElementById('candidates');
    this.candidatesElement.addEventListener('click', this);
  },

  handleEvent: function cd_handleEvent(evt) {
    var item = evt.target;
    IMEDisplay.sendMessage('select', [item.textContent, item.dataset.type]);
  },

  updateCandidates: function cd_updateCandidates(candidates) {
    this.candidates = candidates;
    this.candidatePage = 0;

    this.showCurrentCandidates();
  },

  showCurrentCandidates: function cd_showCurrentCandidates() {
    var candidatesElement = this.candidatesElement;
    candidatesElement.innerHTML = '';

    this.candidates.slice(
      this.candidatePage * 9, this.candidatePage * 9 + 9
    ).forEach(function candidate_forEach(candidate) {
      var item = document.createElement('li');
      item.textContent = candidate[0];
      item.dataset.type = candidate[1];
      candidatesElement.appendChild(item);
    });
  },

  setSelectionMode: function cd_setSelectionMode(mode) {
    if (mode)
      this.candidatesElement.classList.add('expanded');
    else
      this.candidatesElement.classList.remove('expanded');
  },

  setCandidatePage: function cd_setCandidatePage(page) {
    this.candidatePage = page;
    this.showCurrentCandidates();
  }
};

var IMEDisplay = {
  candidateSelectionMode: false,

  pendingSymbolsElement: null,

  init: function id_init() {
    CandidatesDisplay.init();

    this.pendingSymbolsElement =
      document.getElementById('pending_symbols');

    // register message event
    window.addEventListener('message', this, true);

    this.sendMessage('init');
  },

  setCandidateSelectionMode: function id_setCandidateSelectionMode(mode) {
    if (mode) {
      document.body.classList.add('candidateselectionmode');
    } else {
      document.body.classList.remove('candidateselectionmode');
    }

    CandidatesDisplay.setSelectionMode(mode);
  },

  updateHeight: function id_updateHeight() {
    this.sendMessage(
      'dimensionchange', { height: document.documentElement.offsetHeight });
  },

  handleEvent: function id_handleEvent(evt) {
    switch (evt.type) {
      case 'message':
        this.handleMessage(evt.data);
        break;
    }
  },

  handleMessage: function id_handleMessage(msg) {
    if (!msg.to || msg.to !== 'page')
      return;

    switch (msg.name) {
      case 'reset':
        this.pendingSymbolsElement.textContent = '';
        CandidatesDisplay.updateCandidates([]);
        this.setCandidateSelectionMode(false);
        break;

      case 'pendingsymbols':
        this.pendingSymbolsElement.textContent = msg.data;
        break;

      case 'candidates':
        CandidatesDisplay.updateCandidates(msg.data);
        break;

      case 'candidateselectionmode':
        this.setCandidateSelectionMode(msg.data);
        break;

      case 'candidateselectionpage':
        CandidatesDisplay.setCandidatePage(msg.data);
        break;
    }

    this.updateHeight();
  },

  sendMessage: function id_sendMessage(name, data) {
    window.postMessage({
      name: name,
      data: data
    }, '*');
  }
};

IMEDisplay.init();
<commit_msg>Remove reference of pending_symbols in panel.js<commit_after>// This is a page script run in panel.html to handle the input and UIs.

'use strict';

var CandidatesDisplay = {
  candidatesElement: null,

  candidates: [],
  candidatePage: 0,

  init: function cd_init() {
    this.candidatesElement = document.getElementById('candidates');
    this.candidatesElement.addEventListener('click', this);
  },

  handleEvent: function cd_handleEvent(evt) {
    var item = evt.target;
    IMEDisplay.sendMessage('select', [item.textContent, item.dataset.type]);
  },

  updateCandidates: function cd_updateCandidates(candidates) {
    this.candidates = candidates;
    this.candidatePage = 0;

    this.showCurrentCandidates();
  },

  showCurrentCandidates: function cd_showCurrentCandidates() {
    var candidatesElement = this.candidatesElement;
    candidatesElement.innerHTML = '';

    this.candidates.slice(
      this.candidatePage * 9, this.candidatePage * 9 + 9
    ).forEach(function candidate_forEach(candidate) {
      var item = document.createElement('li');
      item.textContent = candidate[0];
      item.dataset.type = candidate[1];
      candidatesElement.appendChild(item);
    });
  },

  setSelectionMode: function cd_setSelectionMode(mode) {
    if (mode)
      this.candidatesElement.classList.add('expanded');
    else
      this.candidatesElement.classList.remove('expanded');
  },

  setCandidatePage: function cd_setCandidatePage(page) {
    this.candidatePage = page;
    this.showCurrentCandidates();
  }
};

var IMEDisplay = {
  candidateSelectionMode: false,

  init: function id_init() {
    CandidatesDisplay.init();

    // register message event
    window.addEventListener('message', this, true);

    this.sendMessage('init');
  },

  setCandidateSelectionMode: function id_setCandidateSelectionMode(mode) {
    if (mode) {
      document.body.classList.add('candidateselectionmode');
    } else {
      document.body.classList.remove('candidateselectionmode');
    }

    CandidatesDisplay.setSelectionMode(mode);
  },

  updateHeight: function id_updateHeight() {
    this.sendMessage(
      'dimensionchange', { height: document.documentElement.offsetHeight });
  },

  handleEvent: function id_handleEvent(evt) {
    switch (evt.type) {
      case 'message':
        this.handleMessage(evt.data);
        break;
    }
  },

  handleMessage: function id_handleMessage(msg) {
    if (!msg.to || msg.to !== 'page')
      return;

    switch (msg.name) {
      case 'reset':
        CandidatesDisplay.updateCandidates([]);
        this.setCandidateSelectionMode(false);
        break;

      case 'candidates':
        CandidatesDisplay.updateCandidates(msg.data);
        break;

      case 'candidateselectionmode':
        this.setCandidateSelectionMode(msg.data);
        break;

      case 'candidateselectionpage':
        CandidatesDisplay.setCandidatePage(msg.data);
        break;
    }

    this.updateHeight();
  },

  sendMessage: function id_sendMessage(name, data) {
    window.postMessage({
      name: name,
      data: data
    }, '*');
  }
};

IMEDisplay.init();
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// Let the parent know our dimensions so that
// the panel has the same size as the content.
addEventListener("load", function () {
  let {offsetWidth: width, offsetHeight: height} = document.body;
  self.port.emit("load", {width: width, height: height});
});

// Hide the panel after opening a new tab.
addEventListener("click", function (event) {
  if (event.target.nodeName == "A") {
    event.preventDefault();
    self.port.emit("navigate", event.target.getAttribute("href"));
  }
});

// Notify the parent when redirects have been enabled or disabled.
let chk = document.getElementById("redirects-chk");
chk.addEventListener("change", function () {
  self.port.emit("toggle", chk.checked);
});
<commit_msg>update the panel checkbox state when the add-on is loaded<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// Let the parent know our dimensions so that
// the panel has the same size as the content.
addEventListener("load", function () {
  let {offsetWidth: width, offsetHeight: height} = document.body;
  self.port.emit("load", {width: width, height: height});
});

// Hide the panel after opening a new tab.
addEventListener("click", function (event) {
  if (event.target.nodeName == "A") {
    event.preventDefault();
    self.port.emit("navigate", event.target.getAttribute("href"));
  }
});

let checkbox = document.getElementById("redirects-chk");

// Notify the parent when redirects have been enabled or disabled.
checkbox.addEventListener("change", function () {
  self.port.emit("toggle", checkbox.checked);
});

// Update the checkbox state when the add-on loads.
self.port.on("toggle", function (enabled) {
  if (checkbox.checked != enabled) {
    checkbox.checked = enabled;
  }
});
<|endoftext|>


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

    angular.module('djangularRestFramework', ['angularExtQ', 'jmdobry.angular-cache'])
        .factory('drf', ['$rootScope', '$http', '$angularCacheFactory', 'extQ', function ($rootScope, $http, $angularCacheFactory, extQ) {
            var equals = angular.equals;
            var forEach = angular.forEach;
            var isDefined = angular.isDefined;
            var isUndefined = angular.isUndefined;

            var cacheOptions = {
                maxAge: 86400000,
                storageMode: 'localStorage'
            };

            var defaultOptions = {
                cache: true
            };

            var api = {
                optionsCache: $angularCacheFactory('optionsCache', cacheOptions),
                urlCache: $angularCacheFactory('urlCache', cacheOptions),
                objectCache: $angularCacheFactory('objectCache', cacheOptions),

                getPage: function (url, options, deferred, items) {
                    $http({
                        method: 'GET',
                        url: url,
                        params: options.params
                    }).then(function (response) {
                        // If the response has pages it will be structured
                        // differently.
                        var data;
                        if (angular.isDefined(response.data.results)) {
                            data = response.data.results;
                        } else {
                            data = response.data;
                        }

                        if (angular.isDefined(response.data.count) && angular.isUndefined(options.limit)) {
                            options.limit = response.data.count;
                        }

                        deferred.update(data);
                        items = items.concat(data);

                        if (isDefined(response.data.next) && response.data.next !== null && items.length < options.limit) {
                            api.getPage(response.data.next, options, deferred, items);
                        } else {
                            if (isDefined(options.limit)) {
                                items = items.splice(0, options.limit);
                            }
                            deferred.resolve(items);
                        }

                    }, function (response, status) {
                        deferred.reject({response: response, status: status});
                    });
                },

                stream: function (url, options) {
                    var deferred = extQ.defer(['update']);
                    var items = [];

                    api.getPage(url, options, deferred, items);

                    return deferred.promise;
                },

                load: function (url, options) {
                    var deferred = extQ.defer();

                    $http({
                        method: 'GET',
                        url: url,
                        params: options.params
                    }).then(function (response) {
                        deferred.resolve(response);
                    }, function (response, status) {
                        deferred.reject({response: response, status: status});
                    });

                    return deferred.promise;
                },

                loadList: function (url, options, deferred) {
                    options = angular.extend({}, defaultOptions, options);
                    deferred = deferred || extQ.defer(['add', 'update', 'remove']);

                    if (options.cache) {
                        // Load list of item URLs from urlCache.
                        var cached = api.urlCache.get(url);
                        if (isDefined(options.limit) && isDefined(cached)) {
                            cached = cached.splice(0, options.limit);
                        }
                        forEach(cached, function (url) {
                            var obj = api.objectCache.get(url);
                            if (isDefined(obj)) {
                                deferred.add(obj);
                            }
                        });
                    }

                    var seen = {};
                    api.stream(url, options).update(function (list) {
                        // Stream the list
                        forEach(list, function (item) {
                            seen[item.url] = item;
                            if (options.cache) {
                                var cached = api.objectCache.get(item.url);
                                if (isUndefined(cached)) {
                                    api.objectCache.put(item.url, item);
                                    deferred.add(item);
                                } else if (!equals(cached, item)) {
                                    api.objectCache.put(item.url, item);
                                    deferred.update(item);
                                }
                            } else {
                                deferred.add(item);
                            }
                        });
                    }).then(function (list) {
                        if (options.cache) {
                            // Remove items from the cache if they were not returned
                            // in the list.
                            if (cached) {
                                forEach(cached, function (url) {
                                    if (isUndefined(seen[url])) {
                                        deferred.remove(url);
                                        api.objectCache.remove(url);
                                    }
                                });
                            }

                            // Update the urlCache with a list of URLs.
                            var urls = [];
                            forEach(list, function (item) {
                                if (isDefined(item.url)) {
                                    urls.push(item.url);
                                }
                            });
                            api.urlCache.put(url, urls);
                        }

                        deferred.resolve(list);
                    });

                    return deferred.promise;
                },

                loadItem: function (url, options, deferred) {
                    options = angular.extend({}, defaultOptions, options);
                    deferred = deferred || extQ.defer(['add', 'update', 'remove']);

                    if (options.cache) {
                        // Load the item from the cache.
                        var cached = api.objectCache.get(url);
                        if (isDefined(cached)) {
                            deferred.add(cached);
                        }
                    }

                    api.load(url, options).then(function (response) {
                        var item = response.data;
                        if (options.cache) {
                            if (isUndefined(cached)) {
                                api.objectCache.put(url, item);
                                deferred.add(item);
                            } else if (!equals(cached, item)) {
                                api.objectCache.put(url, item);
                                deferred.update(item);
                            }
                        }

                        deferred.resolve(item);
                    });

                    return deferred.promise;
                },

                loadOptions: function (url, options, deferred) {
                    options = angular.extend({}, defaultOptions, options);
                    deferred = deferred || extQ.defer();

                    if (options.cache) {
                        // Load the options from the cache.
                        var cached = api.optionsCache.get(url);
                        if (isDefined(cached)) {
                            deferred.resolve({data: cached, url: url});
                        }
                    }

                    $http({
                        method: 'OPTIONS',
                        url: url
                    }).then(function (response) {
                        if (options.cache) {
                            if (!equals(cached, response.data)) {
                                api.optionsCache.put(url, response.data);
                            }
                        }

                        deferred.resolve({data: response.data, url: url});
                    }, function (response, status) {
                        deferred.reject({response: response, status: status});
                    });

                    return deferred.promise;
                }
            };

            return api;
        }]);
}());
<commit_msg>Remove shortcuts to angular methods.<commit_after>(function () {
    'use strict';

    angular.module('djangularRestFramework', ['angularExtQ', 'jmdobry.angular-cache'])
        .factory('drf', ['$rootScope', '$http', '$angularCacheFactory', 'extQ', function ($rootScope, $http, $angularCacheFactory, extQ) {
            var cacheOptions = {
                maxAge: 86400000,
                storageMode: 'localStorage'
            };

            var defaultOptions = {
                cache: true
            };

            var api = {
                optionsCache: $angularCacheFactory('optionsCache', cacheOptions),
                urlCache: $angularCacheFactory('urlCache', cacheOptions),
                objectCache: $angularCacheFactory('objectCache', cacheOptions),

                getPage: function (url, options, deferred, items) {
                    $http({
                        method: 'GET',
                        url: url,
                        params: options.params
                    }).then(function (response) {
                        // If the response has pages it will be structured
                        // differently.
                        var data;
                        if (angular.isDefined(response.data.results)) {
                            data = response.data.results;
                        } else {
                            data = response.data;
                        }

                        if (angular.isDefined(response.data.count) && angular.isUndefined(options.limit)) {
                            options.limit = response.data.count;
                        }

                        deferred.update(data);
                        items = items.concat(data);

                        if (angular.isDefined(response.data.next) && response.data.next !== null && items.length < options.limit) {
                            api.getPage(response.data.next, options, deferred, items);
                        } else {
                            if (angular.isDefined(options.limit)) {
                                items = items.splice(0, options.limit);
                            }
                            deferred.resolve(items);
                        }

                    }, function (response, status) {
                        deferred.reject({response: response, status: status});
                    });
                },

                stream: function (url, options) {
                    var deferred = extQ.defer(['update']);
                    var items = [];

                    api.getPage(url, options, deferred, items);

                    return deferred.promise;
                },

                load: function (url, options) {
                    var deferred = extQ.defer();

                    $http({
                        method: 'GET',
                        url: url,
                        params: options.params
                    }).then(function (response) {
                        deferred.resolve(response);
                    }, function (response, status) {
                        deferred.reject({response: response, status: status});
                    });

                    return deferred.promise;
                },

                loadList: function (url, options, deferred) {
                    options = angular.extend({}, defaultOptions, options);
                    deferred = deferred || extQ.defer(['add', 'update', 'remove']);

                    if (options.cache) {
                        // Load list of item URLs from urlCache.
                        var cached = api.urlCache.get(url);
                        if (angular.isDefined(options.limit) && isDefined(cached)) {
                            cached = cached.splice(0, options.limit);
                        }
                        angular.forEach(cached, function (url) {
                            var obj = api.objectCache.get(url);
                            if (angular.isDefined(obj)) {
                                deferred.add(obj);
                            }
                        });
                    }

                    var seen = {};
                    api.stream(url, options).update(function (list) {
                        // Stream the list
                        angular.forEach(list, function (item) {
                            seen[item.url] = item;
                            if (options.cache) {
                                var cached = api.objectCache.get(item.url);
                                if (angular.isUndefined(cached)) {
                                    api.objectCache.put(item.url, item);
                                    deferred.add(item);
                                } else if (!angular.equals(cached, item)) {
                                    api.objectCache.put(item.url, item);
                                    deferred.update(item);
                                }
                            } else {
                                deferred.add(item);
                            }
                        });
                    }).then(function (list) {
                        if (options.cache) {
                            // Remove items from the cache if they were not returned
                            // in the list.
                            if (cached) {
                                angular.forEach(cached, function (url) {
                                    if (angular.isUndefined(seen[url])) {
                                        deferred.remove(url);
                                        api.objectCache.remove(url);
                                    }
                                });
                            }

                            // Update the urlCache with a list of URLs.
                            var urls = [];
                            angular.forEach(list, function (item) {
                                if (angular.isDefined(item.url)) {
                                    urls.push(item.url);
                                }
                            });
                            api.urlCache.put(url, urls);
                        }

                        deferred.resolve(list);
                    });

                    return deferred.promise;
                },

                loadItem: function (url, options, deferred) {
                    options = angular.extend({}, defaultOptions, options);
                    deferred = deferred || extQ.defer(['add', 'update', 'remove']);

                    if (options.cache) {
                        // Load the item from the cache.
                        var cached = api.objectCache.get(url);
                        if (angular.isDefined(cached)) {
                            deferred.add(cached);
                        }
                    }

                    api.load(url, options).then(function (response) {
                        var item = response.data;
                        if (options.cache) {
                            if (angular.isUndefined(cached)) {
                                api.objectCache.put(url, item);
                                deferred.add(item);
                            } else if (!angular.equals(cached, item)) {
                                api.objectCache.put(url, item);
                                deferred.update(item);
                            }
                        }

                        deferred.resolve(item);
                    });

                    return deferred.promise;
                },

                loadOptions: function (url, options, deferred) {
                    options = angular.extend({}, defaultOptions, options);
                    deferred = deferred || extQ.defer();

                    if (options.cache) {
                        // Load the options from the cache.
                        var cached = api.optionsCache.get(url);
                        if (angular.isDefined(cached)) {
                            deferred.resolve({data: cached, url: url});
                        }
                    }

                    $http({
                        method: 'OPTIONS',
                        url: url
                    }).then(function (response) {
                        if (options.cache) {
                            if (!angular.equals(cached, response.data)) {
                                api.optionsCache.put(url, response.data);
                            }
                        }

                        deferred.resolve({data: response.data, url: url});
                    }, function (response, status) {
                        deferred.reject({response: response, status: status});
                    });

                    return deferred.promise;
                }
            };

            return api;
        }]);
}());
<|endoftext|>


<commit_before>/*
References:
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Dragging_and_Dropping_Multiple_Items
https://www.sitepoint.com/html5-file-drag-and-drop/
https://www.sitepoint.com/html5-ajax-file-upload/
http://www.html5rocks.com/en/tutorials/file/dndfiles/
*/

// INITIALIZATION
//========================================================================================
var file_array = [];		// contains files uploaded for this submission
var previous_files = [];	// contains names of files selected from previous submission
var changed = false;		// if files from previous submission changed

// initializing file_array and prevous_files
function createArray(num_parts){
	if(file_array.length == 0){
		for(var i=0; i<num_parts; i++){
			file_array.push([]);
			previous_files.push([]);
		}
	}
}

// read in name of previously submitted file
function readPrevious(filename, part){
	changed = false;
	previous_files[part-1].push(filename);
}

// DRAG AND DROP EFFECT
//========================================================================================
// open a file browser if clicked on drop zone
function clicked_on_box(e){
  document.getElementById("input_file" + get_part_number(e)).click();
  e.stopPropagation();
}

// hover effect
function draghandle(e){
	e.preventDefault();
	e.stopPropagation();
	document.getElementById("upload" + get_part_number(e)).style.opacity = (e.type == "dragenter" || e.type == "dragover") ? .5 : "";
}

// ADD FILES FOR NEW SUBMISSION
//========================================================================================
// add files dragged
function drop(e){
	draghandle(e);
	var filestream= e.dataTransfer.files;
	var part = get_part_number(e);
	for(var i=0; i<filestream.length; i++){
		addFileWithCheck(filestream[i], part); // check for folders
	}
}

function get_part_number(e){
	if(e.target.id.substring(0, 6) == "upload"){
		return e.target.id.substring(6);
	}
	else{
		return e.target.parentNode.id.substring(6);
	}
}

// copy files selected from the file browser
function addFilesFromInput(part){
	var filestream = document.getElementById("input_file" + part).files;
	for(var i=0; i<filestream.length; i++){
		addFile(filestream[i], part); // folders will not be selected in file browser, no need for check
	}
	$('#input_file' + part).val(""); // clear the input type='file'
}

// Check for duplicate file names. This function returns an array.
// First element:
// 1 - a file with the same name found in previous submission
// 0 - a file with the same name already selected for this version
// -1 - does not exist files with the same name
// Second element: index of the file with the same name (if found)
function fileExists(file, part){
	for(var i=0; i<previous_files[part-1].length; i++){
		if(previous_files[part-1][i] == file.name){
			return [1, i];
		}
	}
	for(var i=0; i<file_array[part-1].length; i++){
		if(file_array[part-1][i].name == file.name){
			return [0, i];
		}
	}
	return [-1];
}

// add file with folder check
function addFileWithCheck(file, part){
	// try to open file if it looks suspicious:
	// no type, or with size of a typical folder size
	if(!file.type || file.size%4096 == 0){
		var reader = new FileReader();
		reader.onload = notFolder(file, part);
		reader.onerror = isFolder(file);
		reader.readAsBinaryString(file);
	}
	else{
		addFile(file, part);
	}
}

// add file if is not a folder
function notFolder(file, part){
	return function(e){ addFile(file, part); }
}

function isFolder(file){
	return function(e){ alert("Upload failed: " + file.name + " might be a folder."); }
}

function addFile(file, part){
	var i = fileExists(file, part);
	if( i[0] == -1 ){	// file does not exist
		file_array[part-1].push(file);
		addLabel(file.name, (file.size/1024).toFixed(2), part, false);
	}
	else if(i[0] == 0){	// file already selected
		if(confirm("Note: " + file_array[part-1][i[1]].name + " is already selected. Do you want to replace it?")){
			file_array[part-1].splice(i[1], 1, file);
			removeLabel(file.name, part);
			addLabel(file.name, (file.size/1024).toFixed(2), part, false);
		}
	}
	else{	// file in previous submission
		if(confirm("Note: " + previous_files[part-1][i[1]] + " was in your previous submission. Do you want to replace it?")){
			file_array[part-1].push(file);
			previous_files[part-1].splice(i[1], 1);
			removeLabel(file.name, part);
			addLabel(file.name, (file.size/1024).toFixed(2), part, false);
			changed = true;
		}
	}
}

// REMOVE FILES
//========================================================================================
// delete files selected for a part
function deleteFiles(part){
	if(file_array.length != 0){
		file_array[part-1] = [];
	}
	if(previous_files.length != 0){
		previous_files[part-1] = [];
	}
	var dropzone = document.getElementById("upload" + part);
	var labels = dropzone.getElementsByClassName("mylabel");
	while(labels[0]){
		dropzone.removeChild(labels[0]);
	}
	changed = true;
}

function deleteSingleFile(filename, part, previous){
	// Remove files from previous submission
	if(previous){
		for(var i=0; i<previous_files[part-1].length; i++){
			if(previous_files[part-1][i] == filename){
				previous_files[part-1].splice(i, 1);
				changed = true;
				break;
			}
		}
	}
	// Remove files uploaded for submission
	else{
		for(var i=0; i<file_array[part-1].length; i++){
			if(file_array[part-1][i].name == filename){
				file_array[part-1].splice(i, 1);
				break;
			}
		}
	}
}

// LABELS FOR SELECTED FILES
//========================================================================================
function removeLabel(filename, part){
	var dropzone = document.getElementById("upload" + part);
	var labels = dropzone.getElementsByClassName("mylabel");
	for(var i=0 ; i<labels.length; i++){
		if(labels[i].innerHTML.substring(0, filename.length) == filename){
			dropzone.removeChild(labels[i]);
			break;
		}
	}
}

function addLabel(filename, filesize, part, previous){
	// create element
	var tmp = document.createElement('label');
	tmp.setAttribute("class", "mylabel");
	tmp.innerHTML =  filename + " " + filesize + "kb" + "
";
	// styling
	tmp.onmouseover = function(e){
		e.stopPropagation();
		this.style.color = "#FF3933";
		this.style.background = "lightgrey";
	}
	tmp.onmouseout = function(e){
		e.stopPropagation();
		this.style.color = "black";
		this.style.background = "";
	}
	// remove file and label on click
	tmp.onclick = function(e){
		e.stopPropagation();
		this.parentNode.removeChild(this);
		deleteSingleFile(filename, part, previous);
	}
	// add to parent div
	var dropzone = document.getElementById("upload" + part);
	// Uncomment if want buttons for emptying single bucket
	// var deletebutton = document.getElementById("delete" + part);
	dropzone.appendChild(tmp);
	// dropzone.insertBefore(tmp, deletebutton);
}

// HANDLE SUBMISSION
//========================================================================================
function isValidSubmission(){
	// check if new files added
	for(var i=0; i < file_array.length; i++){
		if(file_array[i].length != 0){
			return true;
		}
	}
	// check if files from previous submission changed
	if(changed){
		// check if previous submission files are emptied
		for(var i=0; i < previous_files.length; i++){
			if(previous_files[i] != 0){
				return true;
			}
		}
	}
	return false;
}

function submit(url, csrf_token, svn_checkout, loc){
	// Check if new submission
	if(!isValidSubmission()){
		alert("Not a new submission.");
		window.location.reload();
		return;
	}
	var files_to_upload = new FormData();

	files_to_upload.append('csrf_token', csrf_token);
	files_to_upload.append('svn_checkout', svn_checkout);

	// Files selected
	for(var i=0; i<file_array.length; i++){
		for(var j=0; j<file_array[i].length; j++){
			files_to_upload.append('files' + (i+1) + '[]', file_array[i][j]);
		}
	}
	// Files from previous submission
	files_to_upload.append('previous_files', JSON.stringify(previous_files));
	$.ajax({
		url: submit_url,
		data: files_to_upload,
		processData: false,
		contentType: false,
		type: 'POST',
		success: function(data) {
			window.location.href = loc;
		}
	});
}
<commit_msg>Update drag_and_drop.js (#434)<commit_after>/*
References:
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Dragging_and_Dropping_Multiple_Items
https://www.sitepoint.com/html5-file-drag-and-drop/
https://www.sitepoint.com/html5-ajax-file-upload/
http://www.html5rocks.com/en/tutorials/file/dndfiles/
*/

// INITIALIZATION
//========================================================================================
var file_array = [];		// contains files uploaded for this submission
var previous_files = [];	// contains names of files selected from previous submission
var changed = false;		// if files from previous submission changed

// initializing file_array and prevous_files
function createArray(num_parts){
	if(file_array.length == 0){
		for(var i=0; i<num_parts; i++){
			file_array.push([]);
			previous_files.push([]);
		}
	}
}

// read in name of previously submitted file
function readPrevious(filename, part){
	changed = false;
	previous_files[part-1].push(filename);
}

// DRAG AND DROP EFFECT
//========================================================================================
// open a file browser if clicked on drop zone
function clicked_on_box(e){
  document.getElementById("input_file" + get_part_number(e)).click();
  e.stopPropagation();
}

// hover effect
function draghandle(e){
	e.preventDefault();
	e.stopPropagation();
	document.getElementById("upload" + get_part_number(e)).style.opacity = (e.type == "dragenter" || e.type == "dragover") ? .5 : "";
}

// ADD FILES FOR NEW SUBMISSION
//========================================================================================
// add files dragged
function drop(e){
	draghandle(e);
	var filestream= e.dataTransfer.files;
	var part = get_part_number(e);
	for(var i=0; i<filestream.length; i++){
		addFileWithCheck(filestream[i], part); // check for folders
	}
}

function get_part_number(e){
	if(e.target.id.substring(0, 6) == "upload"){
		return e.target.id.substring(6);
	}
	else{
		return e.target.parentNode.id.substring(6);
	}
}

// copy files selected from the file browser
function addFilesFromInput(part){
	var filestream = document.getElementById("input_file" + part).files;
	for(var i=0; i<filestream.length; i++){
		addFile(filestream[i], part); // folders will not be selected in file browser, no need for check
	}
	$('#input_file' + part).val(""); // clear the input type='file'
}

// Check for duplicate file names. This function returns an array.
// First element:
// 1 - a file with the same name found in previous submission
// 0 - a file with the same name already selected for this version
// -1 - does not exist files with the same name
// Second element: index of the file with the same name (if found)
function fileExists(file, part){
	for(var i=0; i<previous_files[part-1].length; i++){
		if(previous_files[part-1][i] == file.name){
			return [1, i];
		}
	}
	for(var i=0; i<file_array[part-1].length; i++){
		if(file_array[part-1][i].name == file.name){
			return [0, i];
		}
	}
	return [-1];
}

// add file with folder check
function addFileWithCheck(file, part){
	// try to open file if it looks suspicious:
	// no type, or with size of a typical folder size
	if(!file.type || file.size%4096 == 0){
		var reader = new FileReader();
		reader.onload = notFolder(file, part);
		reader.onerror = isFolder(file);
		reader.readAsBinaryString(file);
	}
	else{
		addFile(file, part);
	}
}

// add file if is not a folder
function notFolder(file, part){
	return function(e){ addFile(file, part); }
}

function isFolder(file){
	return function(e){ alert("Upload failed: " + file.name + " might be a folder."); }
}

function addFile(file, part){
	var i = fileExists(file, part);
	if( i[0] == -1 ){	// file does not exist
		file_array[part-1].push(file);
		addLabel(file.name, (file.size/1024).toFixed(2), part, false);
	}
	else if(i[0] == 0){	// file already selected
		if(confirm("Note: " + file_array[part-1][i[1]].name + " is already selected. Do you want to replace it?")){
			file_array[part-1].splice(i[1], 1, file);
			removeLabel(file.name, part);
			addLabel(file.name, (file.size/1024).toFixed(2), part, false);
		}
	}
	else{	// file in previous submission
		if(confirm("Note: " + previous_files[part-1][i[1]] + " was in your previous submission. Do you want to replace it?")){
			file_array[part-1].push(file);
			previous_files[part-1].splice(i[1], 1);
			removeLabel(file.name, part);
			addLabel(file.name, (file.size/1024).toFixed(2), part, false);
			changed = true;
		}
	}
}

// REMOVE FILES
//========================================================================================
// delete files selected for a part
function deleteFiles(part){
	if(file_array.length != 0){
		file_array[part-1] = [];
	}
	if(previous_files.length != 0){
		previous_files[part-1] = [];
	}
	var dropzone = document.getElementById("upload" + part);
	var labels = dropzone.getElementsByClassName("mylabel");
	while(labels[0]){
		dropzone.removeChild(labels[0]);
	}
	changed = true;
}

function deleteSingleFile(filename, part, previous){
	// Remove files from previous submission
	if(previous){
		for(var i=0; i<previous_files[part-1].length; i++){
			if(previous_files[part-1][i] == filename){
				previous_files[part-1].splice(i, 1);
				changed = true;
				break;
			}
		}
	}
	// Remove files uploaded for submission
	else{
		for(var i=0; i<file_array[part-1].length; i++){
			if(file_array[part-1][i].name == filename){
				file_array[part-1].splice(i, 1);
				break;
			}
		}
	}
}

// LABELS FOR SELECTED FILES
//========================================================================================
function removeLabel(filename, part){
	var dropzone = document.getElementById("upload" + part);
	var labels = dropzone.getElementsByClassName("mylabel");
	for(var i=0 ; i<labels.length; i++){
		if(labels[i].innerHTML.substring(0, filename.length) == filename){
			dropzone.removeChild(labels[i]);
			break;
		}
	}
}

function addLabel(filename, filesize, part, previous){
	// create element
	var tmp = document.createElement('label');
	tmp.setAttribute("class", "mylabel");
	tmp.innerHTML =  filename + " " + filesize + "kb" + "
";
	// styling
	tmp.onmouseover = function(e){
		e.stopPropagation();
		this.style.color = "#FF3933";
		this.style.background = "lightgrey";
	}
	tmp.onmouseout = function(e){
		e.stopPropagation();
		this.style.color = "black";
		this.style.background = "";
	}
	// remove file and label on click
	tmp.onclick = function(e){
		e.stopPropagation();
		this.parentNode.removeChild(this);
		deleteSingleFile(filename, part, previous);
	}
	// add to parent div
	var dropzone = document.getElementById("upload" + part);
	// Uncomment if want buttons for emptying single bucket
	// var deletebutton = document.getElementById("delete" + part);
	dropzone.appendChild(tmp);
	// dropzone.insertBefore(tmp, deletebutton);
}

// HANDLE SUBMISSION
//========================================================================================
function isValidSubmission(){
	// check if new files added
	for(var i=0; i < file_array.length; i++){
		if(file_array[i].length != 0){
			return true;
		}
	}
	// check if files from previous submission changed
	if(changed){
		// check if previous submission files are emptied
		for(var i=0; i < previous_files.length; i++){
			if(previous_files[i] != 0){
				return true;
			}
		}
	}
	return false;
}

function submit(url, csrf_token, svn_checkout, loc){
	// Check if new submission
	if(!isValidSubmission()){
		alert("Not a new submission.");
		window.location.reload();
		return;
	}
	var files_to_upload = new FormData();

	files_to_upload.append('csrf_token', csrf_token);
	files_to_upload.append('svn_checkout', svn_checkout);

	// Files selected
	for(var i=0; i<file_array.length; i++){
		for(var j=0; j<file_array[i].length; j++){
			files_to_upload.append('files' + (i+1) + '[]', file_array[i][j]);
		}
	}
	// Files from previous submission
	files_to_upload.append('previous_files', JSON.stringify(previous_files));
	$.ajax({
		url: url,
		data: files_to_upload,
		processData: false,
		contentType: false,
		type: 'POST',
		success: function(data) {
			window.location.href = loc;
		}
	});
}
<|endoftext|>


<commit_before>angular.module('courseReg', [])
    .controller('CoureRegController', ['$scope', '$http', function($scope, $http){
        $scope.courseRegList;

        var clickListener = function(e)
        {

           if(e.target.id == "sendEmail")
           {
               emailjs.send("gmail","gmail",{name:$("#username").html(), email:$("#email").html(), tel:$("#tel").html()}).then(
                   function(response) {
                       alert("success");
                   },
                   function(error) {
                       alert("failed");
                   }
               );
           }

        }

        $scope.loadCourseReg = function()
        {
            $http.get('/course')
                .success(function(res){
                    $scope.courseRegList = res;
                    $("#sendEmail").click(clickListener);
                })
                .catch(function(err) {
                    console.log('Get courses error.');
                });
        };
        $scope.loadCourseReg();
    }]);

<commit_msg>minor changes<commit_after>angular.module('courseReg', [])
    .controller('CoureRegController', ['$scope', '$http', function($scope, $http){
        $scope.courseRegList;

        var clickListener = function(e)
        {

           if(e.target.id == "sendEmail")
           {
               emailjs.send("gmail","gmail",{name:$("#username").html(), email:$("#email").html(), tel:$("#tel").html()}).then(
                   function(response) {
                       alert("המייל נשלח בהצלחה");
                   },
                   function(error) {
                       alert("נכשל");
                   }
               );
           }

        }

        $scope.loadCourseReg = function()
        {
            $http.get('/course')
                .success(function(res){
                    $scope.courseRegList = res;
                    $("#sendEmail").click(clickListener);
                })
                .catch(function(err) {
                    console.log('Get courses error.');
                });
        };
        $scope.loadCourseReg();
    }]);

<|endoftext|>


<commit_before>/**
 * Created by .
 * User: dan
 * Date: Jan 25, 2011
 * Time: 8:49:02 PM
 * To change this template use File | Settings | File Templates.
 */
Diaspora.widgets.add("timeago", function() {
  this.selector = "abbr.timeago";

  this.start = function() {
      if(Diaspora.widgets.i18n.language === "en") {
        return;
      }

      jQuery.timeago.settings.strings = {
        prefixAgo: Diaspora.widgets.i18n.t("timeago.prefixAgo"),
        prefixFromNow: Diaspora.widgets.i18n.t("timeago.prefixFromNow"),
        suffixAgo: Diaspora.widgets.i18n.t("timeago.suffixAgo"),
        suffixFromNow: Diaspora.widgets.i18n.t("timeago.suffixFromNow"),
        seconds: Diaspora.widgets.i18n.t("timeago.seconds"),
        minute: Diaspora.widgets.i18n.t("timeago.minute"),
        minutes: Diaspora.widgets.i18n.t("timeago.minutes"),
        hour: Diaspora.widgets.i18n.t("timeago.hour"),
        hours: Diaspora.widgets.i18n.t("timeago.hours"),
        day: Diaspora.widgets.i18n.t("timeago.day"),
        days: Diaspora.widgets.i18n.t("timeago.days"),
        month: Diaspora.widgets.i18n.t("timeago.month"),
        months: Diaspora.widgets.i18n.t("timeago.months"),
        year: Diaspora.widgets.i18n.t("timeago.year"),
        years: Diaspora.widgets.i18n.t("timeago.years")
      };

      Diaspora.widgets.timeago.updateTimeAgo("abbr");
  };

  this.updateTimeAgo = function(selector) {
    $(selector || this.selector).timeago();
  };
});

InfiniteScroll.postScrollCallback = function(){
      Diaspora.widgets.timeago.updateTimeAgo();
}
<commit_msg>Fix infinite scroll javascript in jammed js<commit_after>/**
 * Created by .
 * User: dan
 * Date: Jan 25, 2011
 * Time: 8:49:02 PM
 * To change this template use File | Settings | File Templates.
 */
Diaspora.widgets.add("timeago", function() {
  this.selector = "abbr.timeago";

  this.start = function() {
      InfiniteScroll.postScrollCallback = function(){
            Diaspora.widgets.timeago.updateTimeAgo();
      }
      if(Diaspora.widgets.i18n.language === "en") {
        return;
      }

      jQuery.timeago.settings.strings = {
        prefixAgo: Diaspora.widgets.i18n.t("timeago.prefixAgo"),
        prefixFromNow: Diaspora.widgets.i18n.t("timeago.prefixFromNow"),
        suffixAgo: Diaspora.widgets.i18n.t("timeago.suffixAgo"),
        suffixFromNow: Diaspora.widgets.i18n.t("timeago.suffixFromNow"),
        seconds: Diaspora.widgets.i18n.t("timeago.seconds"),
        minute: Diaspora.widgets.i18n.t("timeago.minute"),
        minutes: Diaspora.widgets.i18n.t("timeago.minutes"),
        hour: Diaspora.widgets.i18n.t("timeago.hour"),
        hours: Diaspora.widgets.i18n.t("timeago.hours"),
        day: Diaspora.widgets.i18n.t("timeago.day"),
        days: Diaspora.widgets.i18n.t("timeago.days"),
        month: Diaspora.widgets.i18n.t("timeago.month"),
        months: Diaspora.widgets.i18n.t("timeago.months"),
        year: Diaspora.widgets.i18n.t("timeago.year"),
        years: Diaspora.widgets.i18n.t("timeago.years")
      };

      Diaspora.widgets.timeago.updateTimeAgo("abbr");

  };

  this.updateTimeAgo = function(selector) {
    $(selector || this.selector).timeago();
  };
});
<|endoftext|>


<commit_before>'use strict';

angular.module('eMarketApp').directive('searchResults', function(Restangular) {
  return {
    templateUrl: 'views/searchResults.html',
    restrict: 'E',
    scope: true,
    replace: true,
    link: function(scope, elem) {
      var page = $(elem[0]);
      var resultList = page.find('#resultList');

      page.on('pagebeforeshow', function(event, searchQuery) {
        //            scope.results = Restangular.customGETLIST('search', {q: searchQuery});
        Restangular.all('products').getList().then(function(results) {
          scope.results = results;
          setTimeout(function() {
            resultList.listview('refresh');
          });
        });
      });
    }
  };
});
<commit_msg>Connected the search on the front end.<commit_after>'use strict';

angular.module('eMarketApp').directive('searchResults', function(Restangular, $http) {
  return {
    templateUrl: 'views/searchResults.html',
    restrict: 'E',
    scope: {
      searchQuery: '='
    },
    replace: true,
    link: function(scope, elem) {
      var page = $(elem[0]);
      var resultList = page.find('#resultList');

      page.on('pagebeforeshow', function(event, data) {
        var searchInput = data.prevPage.find("#search");
        var searchQuery = searchInput.val();
        $http.get('api/search', {params: {q: searchQuery}}).success(function(results) {
          scope.results = results;
          setTimeout(function() {
            resultList.listview('refresh');
          });
          searchInput.val("");
        });
      });
    }
  };
});
<|endoftext|>


<commit_before>
// pg - "Pot Game"
goog.provide('test.scroll')

goog.require('lime');
goog.require('lime.Director');
goog.require('lime.Scene');
goog.require('lime.Layer');
goog.require('lime.Sprite');
goog.require('lime.animation.MoveTo');
goog.require('lime.animation.MoveBy');
goog.require('lime.animation.ScaleBy');
goog.require('lime.animation.RotateBy');
goog.require('lime.animation.ScaleTo');
goog.require('lime.animation.Spawn')
goog.require('lime.animation.Sequence')
goog.require('lime.animation.Delay')
goog.require('lime.animation.FadeTo')

test.WIDTH = 800;
test.HEIGHT = 600;

test.start = function(){

	//director
	test.director = new lime.Director(document.body,test.WIDTH,test.HEIGHT);
	test.director.makeMobileWebAppCapable();

	var gamescene = new lime.Scene;

	var layer = new lime.Sprite().setAnchorPoint(0,0);
	layer.setPosition(200,100);
	gamescene.appendChild(layer);

	var back = new lime.Sprite().setFill('#ccc').setSize(500,130).setAnchorPoint(0,0.5);
	layer.appendChild(back);
	var mask = new lime.Sprite().setFill('#ccc').setSize(500,130).setAnchorPoint(0,0.5);
	layer.appendChild(mask);
	back.setMask(mask);

	var moving = new lime.Layer();
	back.appendChild(moving);

    var box = new lime.Sprite().setFill('#00c').setSize(120,100);
    moving.appendChild(box);

	goog.events.listen(moving,['mousedown','touchstart'],function(e){
	    var x = e.position.x,
            y =moving.getPosition().y;
            var p = moving.getPosition().clone();
            console.log('aa');
        var oldx = posx = moving.getPosition().x;
        var ismove = 1,vx = 0;
        var LOW = 60,HIGH = 440;
        lime.animation.actionManager.stopAll(moving);
            moving.setPosition(p);
        var step = function(){
            if(ismove){
                vx = (posx-oldx);
                oldx = posx;
            }
            vx*=.95;
            /*if(Math.abs(vx)>0.5){
                var pos = moving.getPosition();
                pos.x+=vx;
                moving.setPosition(pos);
            }
            else if(!ismove) lime.scheduleManager.unschedule(step,moving);    */
        };

        lime.scheduleManager.schedule(step,moving);

        e.swallow(['touchmove', 'mousemove'], function(e) {
            var pos = e.position.clone();
                pos.x -= x;
                pos.y = y;
                pos = moving.localToNode(pos, moving.getParent());
                if(pos.x<LOW){
                    var diff = LOW-pos.x;
                    if(diff>200) diff=200;
                    pos.x = LOW-diff/2;
                }
                if(pos.x>HIGH) {
                    var diff = pos.x-HIGH;
                    if(diff>200) diff=200;
                    pos.x = HIGH+diff/2;
                }
                posx = pos.x;
                moving.setPosition(pos);
        });

        e.swallow(['touchend','mouseup','touchend'],function(e){
            var pos = e.position.clone();
                pos.x -= x;
                pos.y = y;
                pos = moving.localToNode(pos, moving.getParent());

                var oldx = pos.x;
                lime.scheduleManager.unschedule(step,moving);

                var k = Math.log(0.5/Math.abs(vx))/Math.log(0.95);
                var duration = k/30;
                var endpos = (Math.abs(vx)*(Math.pow(0.95,k)-1))/(0.95-1)*(vx>0?1:-1);
                console.log(vx,duration,endpos,k);
                pos.x+=endpos;
                ismove = 0;
                if(vx!=0){

                var diff = endpos;

                if(pos.x<LOW){
                    diff = LOW-(pos.x-endpos);
                    pos.x = LOW;
                }
                if(pos.x>HIGH) {
                    diff = HIGH-(pos.x-endpos);
                    pos.x = HIGH;
                }
                //console.log(diff,endpos);
                duration*=(diff/endpos);
                }
                if(oldx<LOW){
                    pos.x = LOW;
                    duration=.3;
                }
                if(oldx>HIGH) {
                    pos.x = HIGH;
                    duration=.3;
                }
                if(Math.abs(duration)<10)
               moving.runAction(new lime.animation.MoveTo(pos.x,pos.y).setDuration(duration).setEasing(lime.animation.getEasingFunction(.19,.6,.35,.97)).enableOptimizations());

        });

	},false,this);

	test.director.replaceScene(gamescene);

}

goog.exportSymbol('test.start', test.start);
<commit_msg>Content measure in scroll test<commit_after>
// pg - "Pot Game"
goog.provide('test.scroll')

goog.require('lime');
goog.require('lime.Director');
goog.require('lime.Scene');
goog.require('lime.Layer');
goog.require('lime.Sprite');
goog.require('lime.animation.MoveTo');
goog.require('lime.animation.MoveBy');
goog.require('lime.animation.ScaleBy');
goog.require('lime.animation.RotateBy');
goog.require('lime.animation.ScaleTo');
goog.require('lime.animation.Spawn')
goog.require('lime.animation.Sequence')
goog.require('lime.animation.Delay')
goog.require('lime.animation.FadeTo')

test.WIDTH = 800;
test.HEIGHT = 600;

test.start = function(){

	//director
	test.director = new lime.Director(document.body,test.WIDTH,test.HEIGHT);
	test.director.makeMobileWebAppCapable();

	var gamescene = new lime.Scene;

	var layer = new lime.Sprite().setAnchorPoint(0,0);
	layer.setPosition(200,100);
	gamescene.appendChild(layer);

	var back = new lime.Sprite().setFill('#ccc').setSize(500,130).setAnchorPoint(0,0.5);
	layer.appendChild(back);
	var mask = new lime.Sprite().setFill('#ccc').setSize(500,130).setAnchorPoint(0,0.5);
	layer.appendChild(mask);
	back.setMask(mask);

	var moving = new lime.Layer();
	back.appendChild(moving);

    var box = new lime.Sprite().setFill('#00c').setSize(120,100);
    moving.appendChild(box);
    var box = new lime.Sprite().setFill('#0cc').setSize(130,100).setPosition(200,0);
    moving.appendChild(box);
    var box = new lime.Sprite().setFill('#0c9').setSize(160,100).setPosition(470,0);
    moving.appendChild(box);
    var box = new lime.Sprite().setFill('#c00').setSize(160,100).setPosition(650,0);
    moving.appendChild(box);

	goog.events.listen(moving,['mousedown','touchstart'],function(e){
	  //  e.position = back.localToNode(e.position,moving);
	    var x = e.position.x,
            y =moving.getPosition().y;
            var p = moving.getPosition().clone();
            var measure = moving.measureContents();
            console.log(measure.top,measure.right,measure.bottom,measure.left);
        var oldx = posx = moving.getPosition().x;
        var ismove = 1,vx = 0;
        var LOW = -measure.left,HIGH =Math.min(500-measure.right,-measure.left);
      var diff = (measure.right-measure.left)-500;
      if(diff>0){
      LOW-=diff;
      HIGH+=diff;
  }
        var OFFSET = 250;
        var OFFSET_LAG = 0.4;
        var FRICTION = 0.95;
        lime.animation.actionManager.stopAll(moving);
            moving.setPosition(p);
        var step = function(){
            if(ismove){
                vx = (posx-oldx);
                oldx = posx;
            }
            vx*=FRICTION;
            /*if(Math.abs(vx)>0.5){
                var pos = moving.getPosition();
                pos.x+=vx;
                moving.setPosition(pos);
            }
            else if(!ismove) lime.scheduleManager.unschedule(step,moving);    */
        };

        lime.scheduleManager.schedule(step,moving);

        e.swallow(['touchmove', 'mousemove'], function(e) {
            var pos = e.position.clone();
                pos.x -= x;
                pos.y = y;
                pos = moving.localToNode(pos, moving.getParent());

                if(pos.x<LOW){
                    var diff = LOW-pos.x;
                    if(diff>OFFSET) diff=OFFSET;
                    pos.x = LOW-diff*OFFSET_LAG;
                }
                if(pos.x>HIGH) {
                    var diff = pos.x-HIGH;
                    if(diff>OFFSET) diff=OFFSET;
                    pos.x = HIGH+diff*OFFSET_LAG;
                }
                posx = pos.x;
                moving.setPosition(pos);
        });

        e.swallow(['touchend','mouseup','touchend'],function(e){
            var pos = e.position.clone();
                pos.x -= x;
                pos.y = y;
                pos = moving.localToNode(pos, moving.getParent());

                var oldx = pos.x;
                lime.scheduleManager.unschedule(step,moving);

                var k = Math.log(0.5/Math.abs(vx))/Math.log(FRICTION);
                var duration = k/30;
                var endpos = (Math.abs(vx)*(Math.pow(FRICTION,k)-1))/(FRICTION-1)*(vx>0?1:-1);
                pos.x+=endpos;
                ismove = 0;
                if(vx!=0){

                var diff = endpos;

                if(pos.x<LOW){
                    diff = LOW-(pos.x-endpos);
                    pos.x = LOW;
                }
                if(pos.x>HIGH) {
                    diff = HIGH-(pos.x-endpos);
                    pos.x = HIGH;
                }
                //console.log(diff,endpos);
                duration*=(diff/endpos);
                }
                if(oldx<LOW){
                    pos.x = LOW;
                    duration=.3;
                }
                if(oldx>HIGH) {
                    pos.x = HIGH;
                    duration=.3;
                }
                if(Math.abs(duration)<10)
               moving.runAction(new lime.animation.MoveTo(pos.x,pos.y).setDuration(duration).setEasing(lime.animation.getEasingFunction(.19,.6,.35,.97)).enableOptimizations());

        });

	},false,this);

	test.director.replaceScene(gamescene);

}

goog.exportSymbol('test.start', test.start);
<|endoftext|>


<commit_before>// <nowiki>
(function() {

	if (mw.config.get('wgAction') !== 'edit') {
		return;
	}

	function main() {

		var zhwpapi = new mw.ForeignApi('//zh.wikipedia.org/w/api.php');

		let text = wpTextbox1.value;

		text = text.replace('#重定向', '#REDIRECT');
		text = text.replace(/[[\]{}<>|:*'_#&\s]/gim, function(s) {
			return "&#" + s.charCodeAt(0) + ";";
		});
		text = text.replace(/-{(.+?)}-/g, function(s) {
			return s
				.replace('-{', '-{')
				.replace('}-', '}-')
				.replace(/|/g, '|')
				.replace(/ /g, ' ')
				.replace(/=/g, '=')
				.replace(/>/g, '>')
				.replace(/:/g, ':')
		});

		zhwpapi.parse(
			'{{NoteTA|G1=IT|G2=MediaWiki}}
' + text + '
',
			{
				'uselang': 'zh-tw',
				'prop': 'text'
			}
		).then(function(data) {
			var newtext = $('
').html(data).find('#TVcontent').text();

			wpTextbox1.value = newtext;
			wpSummary.value = '本地化';
			wpMinoredit.checked = true;
			wpDiff.click();

		}, function(err) {
			mw.notify('解析時發生錯誤：' + err);
		});

	}

	var link = mw.util.addPortletLink('p-namespaces', '#', '本地化');
	$(link).on('click', main);

})();
// </nowiki>
<commit_msg>Add special case<commit_after>// <nowiki>
(function() {

	if (mw.config.get('wgAction') !== 'edit') {
		return;
	}

	function main() {

		var zhwpapi = new mw.ForeignApi('//zh.wikipedia.org/w/api.php');

		let text = wpTextbox1.value;

		// Special cases
		text = text.replace('#重定向', '#REDIRECT');
		if (mw.config.get('wgNamespaceNumber') === 828) { // Module
			text = text.replace(/(wrappers\s*=\s*['"])Template:/, '$1taazihan mitudung:');
		}

		text = text.replace(/[[\]{}<>|:*'_#&\s]/gim, function(s) {
			return "&#" + s.charCodeAt(0) + ";";
		});
		text = text.replace(/-{(.+?)}-/g, function(s) {
			return s
				.replace('-{', '-{')
				.replace('}-', '}-')
				.replace(/|/g, '|')
				.replace(/ /g, ' ')
				.replace(/=/g, '=')
				.replace(/>/g, '>')
				.replace(/:/g, ':')
		});

		zhwpapi.parse(
			'{{NoteTA|G1=IT|G2=MediaWiki}}
' + text + '
',
			{
				'uselang': 'zh-tw',
				'prop': 'text'
			}
		).then(function(data) {
			var newtext = $('
').html(data).find('#TVcontent').text();

			wpTextbox1.value = newtext;
			wpSummary.value = '本地化';
			wpMinoredit.checked = true;
			wpDiff.click();

		}, function(err) {
			mw.notify('解析時發生錯誤：' + err);
		});

	}

	var link = mw.util.addPortletLink('p-namespaces', '#', '本地化');
	$(link).on('click', main);

})();
// </nowiki>
<|endoftext|>