<commit_before>/**
 * Created by Andrew D.Laptev<a.d.laptev@gmail.com> on 30.03.15.
 */

const spawn = require('child_process').spawn
	, EventEmitter = require('events').EventEmitter
	, util = require('util')
	;

/**
 * Stream constructor
 * @param {object} options
 * @param {string} options.input Stream uri, for example rtsp://r3---sn-5hn7su76.c.youtube.com/CiILENy73wIaGQnup-1SztVOYBMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
 * @param {number} [options.rate] Framerate
 * @param {string} [options.quality]
 * @constructor
 */
var FFMpeg = function(options) {
	if (options.input) {
		this.input = options.input;
	} else {
		throw new Error('no `input` parameter');
	}
	this.rate = options.rate || 4;
	this.quality = options.quality || 'qvga';

	this.on('newListener', newListener.bind(this));
	this.on('removeListener', removeListener.bind(this));
};

util.inherits(FFMpeg, EventEmitter);

function newListener(event) {
	if (event === 'data' && this.listeners(event).length === 0) {
		this.start();
	}
}

function removeListener(event) {
	if (event === 'data' && this.listeners(event).length === 1) {
		this.stop();
	}
}

FFMpeg.prototype._args = function() {
	return [
		'-loglevel', 'quiet'
		, '-y'
		, '-i', this.input
		, '-r', this.rate
		, '-s', this.quality
		, '-b:v', '32k'
		, '-f', 'image2'
		, '-updatefirst', '1'
		, '-'
	];
};

/**
 * Start ffmpeg spawn process
 */
FFMpeg.prototype.start = function() {
	this.child = spawn('ffmpeg', this._args());
	this.child.stdout.on('data', this.emit.bind(this, 'data'));
	this.child.stderr.on('data', function(data) {
		console.error(data);
	});
	this.child.on('close', function(code) {
		console.log('exited with code ' + code);
	})
};

/**
 * Stop ffmpeg spawn process
 */
FFMpeg.prototype.stop = function() {
	this.child.disconnect();
	this.child.kill();
};

module.exports.FFMpeg = FFMpeg;<commit_msg>Restart method, tests<commit_after>/**
 * Created by Andrew D.Laptev<a.d.laptev@gmail.com> on 30.03.15.
 */

const spawn = require('child_process').spawn
	, EventEmitter = require('events').EventEmitter
	, util = require('util')
	;

/**
 * Stream constructor
 * @param {object} options
 * @param {string} options.input Stream uri, for example rtsp://r3---sn-5hn7su76.c.youtube.com/CiILENy73wIaGQnup-1SztVOYBMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
 * @param {number} [options.rate] Framerate
 * @param {string} [options.quality]
 * @constructor
 */
var FFMpeg = function(options) {
	if (options.input) {
		this.input = options.input;
	} else {
		throw new Error('no `input` parameter');
	}
	this.rate = options.rate || 4;
	this.quality = options.quality || 'qvga';

	this.on('newListener', newListener.bind(this));
	this.on('removeListener', removeListener.bind(this));
};

util.inherits(FFMpeg, EventEmitter);

function newListener(event) {
	if (event === 'data' && this.listeners(event).length === 0) {
		this.start();
	}
}

function removeListener(event) {
	if (event === 'data' && this.listeners(event).length === 0) {
		this.stop();
	}
}

FFMpeg.prototype._args = function() {
	return [
		'-loglevel', 'quiet'
		, '-y'
		, '-i', this.input
		, '-r', this.rate
		, '-s', this.quality
		, '-b:v', '32k'
		, '-f', 'image2'
		, '-updatefirst', '1'
		, '-'
	];
};

/**
 * Start ffmpeg spawn process
 */
FFMpeg.prototype.start = function() {
	this.child = spawn('ffmpeg', this._args());
	this.child.stdout.on('data', this.emit.bind(this, 'data'));
	this.child.stderr.on('data', function(data) {
		console.error(data);
	});
	this.child.on('close', function(code) {
		console.log('exited with code ' + code);
	})
};

/**
 * Stop ffmpeg spawn process
 */
FFMpeg.prototype.stop = function() {
	this.child.kill();
};

/**
 * Restart ffmpeg spawn process
 */
FFMpeg.restart = function() {
	this.stop();
	this.start();
};

module.exports.FFMpeg = FFMpeg;<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
  didInsertElement: function() {
    this.$('input').focus();
  },

  actions: {
    createApp: function() {
      return this.get('app').save();
    },

    discardNewApp: function() {
      this.get('app').deleteRecord();
    }
  }
});
<commit_msg>discard new app on "esc"<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
  didInsertElement: function() {
    this.$('input')
      .focus()
      .on('keyup', (e) => {
        if (e.keyCode == 27) {
          this.send('discardNewApp');
        }
      });
  },

  actions: {
    createApp: function() {
      return this.get('app').save();
    },

    discardNewApp: function() {
      this.get('app').deleteRecord();
    }
  }
});
<|endoftext|>


<commit_before>/* RESTfull module */

(function(){
    "use strict";

    var main        = global.cloudcmd.main,
        Util        = main.util,
        fs          = main.fs,
        zlib        = main.zlib,
        APIURL      = '/api/v1',
        OK          = 200,
        Header      = main.generateHeaders('api.json', false);

    /**
     * rest interface
     * @pConnectionData {request, responce}
     */
    exports.api = function(pConnectionData){
        var lRet    = false,
            lReq    = pConnectionData.request,
            lRes    = pConnectionData.response,
            lUrl    = lReq.url,
            lMethod = lReq.method;

        if( Util.isContainStr(lUrl, APIURL) ){
            lRet = true;

            getBody(lReq, function(pBody){
                var lCommand = Util.removeStr(lUrl, APIURL),
                    lData = getData({
                        command     : lCommand,
                        method      : lMethod,
                        body        : pBody,
                        request     : lReq,
                        response    : lRes
                    });

                if(lData)
                    send({
                        response : lRes,
                        data     : lData
                    });
            });
        }

        return lRet;
    };

    /**
     * send data
     *
     * @param pRes
     * @param pData
     */
    function send(pParams){
        var lRes            = pParams.response,
            lData           = pParams.data,
            lEndListener    = pParams.endListener;

        lRes.writeHead(OK, Header);
        lRes.end( JSON.stringify(lData) );

        if(lEndListener)
            lRes.on('end', function(){
                Util.exec(lEndListener);
            });
    }

    /**
     * getting data on method and command
     *
     * @param pParams {command, method, body, requrest, response}
     */
    function getData(pParams){
        var lResult,
            lCmd    = pParams.command,
            lMethod = pParams.method;

        if(lCmd[0] === '/'){
            lCmd = Util.removeStr(lCmd, '/');
            pParams.command = lCmd;
        }

        switch(lMethod){
            case 'GET':
                lResult = onGET(pParams);
                break;

            case 'PUT':
                lResult = onPUT(pParams);
                break;
            }

        return lResult;
    }

    /**
     * process data on GET request
     *
     * @param pParams {command, method, body, requrest, response}
     */
    function onGET(pParams){
        var lResult = {error: 'command not found'},
            lCmd = pParams.command;

        switch(lCmd){
            case '':
                lResult = {info: 'Cloud Commander API v1'};
                break;

            case 'client_id':
                var lEnv    = process.env,
                    lConfig = main.config;

                lResult = lEnv.oauth_client_id || lConfig.oauth_client_id;
                break;

            case 'kill':
                pParams.data = {
                    mesage: 'Cloud Commander was killed'
                };

                pParams.endListener = Util.retExec(process.exit);

                send(pParams);
                break;
        }

        return lResult;
    }

    /**
     * process data on PUT request
     *
     * @param pParams {command, method, body, requrest, response}
     */
    function onPUT(pParams){
        var lResult = {error: 'command not found'},
            lCmd    = pParams.command,
            lBody   = pParams.body,
            lRes    = pParams.response;

        switch(lCmd){
            case 'auth':
                main.auth(lBody, function(pTocken){
                    send({
                        response: lRes,
                        data: pTocken
                    });
                });

                lResult = false;
                break;

            case 'read':
                console.log(lBody);
                var lFiles = lBody;

                if( Util.isString(lFiles) ){
                    pParams.name = lFiles;
                    main.sendFile(pParams);

                    lResult = null;
                }

                break;
        }

        return lResult;
    }

    /**
     * get body of url query
     *
     * @param pReq
     * @param pCallBack
     */
    function getBody(pReq, pCallBack){
        var lBody = '';
        pReq.on('data', function(chunk) {
            lBody += chunk.toString();
        });

        pReq.on('end', function() {
            Util.exec(pCallBack, lBody);
        });
    }

})();
<commit_msg>minor changes<commit_after>/* RESTfull module */

(function(){
    "use strict";

    var main        = global.cloudcmd.main,
        Util        = main.util,
        APIURL      = '/api/v1',
        OK          = 200,
        Header      = main.generateHeaders('api.json', false);

    /**
     * rest interface
     * @pConnectionData {request, responce}
     */
    exports.api = function(pConnectionData){
        var lRet    = false,
            lReq    = pConnectionData.request,
            lRes    = pConnectionData.response,
            lUrl    = lReq.url,
            lMethod = lReq.method;

        if( Util.isContainStr(lUrl, APIURL) ){
            lRet = true;

            getBody(lReq, function(pBody){
                var lCommand = Util.removeStr(lUrl, APIURL),
                    lData = getData({
                        command     : lCommand,
                        method      : lMethod,
                        body        : pBody,
                        request     : lReq,
                        response    : lRes
                    });

                if(lData)
                    send({
                        response : lRes,
                        data     : lData
                    });
            });
        }

        return lRet;
    };

    /**
     * send data
     *
     * @param pRes
     * @param pData
     */
    function send(pParams){
        var lRes            = pParams.response,
            lData           = pParams.data,
            lEndListener    = pParams.endListener;

        lRes.writeHead(OK, Header);
        lRes.end( JSON.stringify(lData) );

        if(lEndListener)
            lRes.on('end', function(){
                Util.exec(lEndListener);
            });
    }

    /**
     * getting data on method and command
     *
     * @param pParams {command, method, body, requrest, response}
     */
    function getData(pParams){
        var lResult,
            lCmd    = pParams.command,
            lMethod = pParams.method;

        if(lCmd[0] === '/'){
            lCmd = Util.removeStr(lCmd, '/');
            pParams.command = lCmd;
        }

        switch(lMethod){
            case 'GET':
                lResult = onGET(pParams);
                break;

            case 'PUT':
                lResult = onPUT(pParams);
                break;
            }

        return lResult;
    }

    /**
     * process data on GET request
     *
     * @param pParams {command, method, body, requrest, response}
     */
    function onGET(pParams){
        var lResult = {error: 'command not found'},
            lCmd = pParams.command;

        switch(lCmd){
            case '':
                lResult = {info: 'Cloud Commander API v1'};
                break;

            case 'client_id':
                var lEnv    = process.env,
                    lConfig = main.config;

                lResult = lEnv.oauth_client_id || lConfig.oauth_client_id;
                break;

            case 'kill':
                pParams.data = {
                    mesage: 'Cloud Commander was killed'
                };

                pParams.endListener = Util.retExec(process.exit);

                send(pParams);

                lResult = null;
                break;
        }

        return lResult;
    }

    /**
     * process data on PUT request
     *
     * @param pParams {command, method, body, requrest, response}
     */
    function onPUT(pParams){
        var lResult = {error: 'command not found'},
            lCmd    = pParams.command,
            lBody   = pParams.body,
            lRes    = pParams.response;

        switch(lCmd){
            case 'auth':
                main.auth(lBody, function(pTocken){
                    send({
                        response: lRes,
                        data: pTocken
                    });
                });

                lResult = false;
                break;

            case 'read':
                console.log(lBody);
                var lFiles = lBody;

                if( Util.isString(lFiles) ){
                    pParams.name = lFiles;
                    main.sendFile(pParams);

                    lResult = null;
                }

                break;
        }

        return lResult;
    }

    /**
     * get body of url query
     *
     * @param pReq
     * @param pCallBack
     */
    function getBody(pReq, pCallBack){
        var lBody = '';
        pReq.on('data', function(chunk) {
            lBody += chunk.toString();
        });

        pReq.on('end', function() {
            Util.exec(pCallBack, lBody);
        });
    }

})();
<|endoftext|>


<commit_before>"use strict";
var Server = {
    save: function(path, content, callback) {
        console.log("SAVING:", path);
        var postString =
            'path=' + encodeURIComponent(path) +
            '&data=' + encodeURIComponent(content);

        var req = $.ajax({
            url: 'lib/weltmeister/api/save.php',
            type: 'POST',
            dataType: 'json',
            async: false,
            data: postString,
            success: callback || function() { console.log("FILE SAVED"); }
        });

        return req;
    },

    browse: function(dirPath, type) {
        return new Promise(function (resolve, reject) {
            var query =
                'dir=' + encodeURIComponent(dirPath) +
                '&type=' + encodeURIComponent(type);

            return $.ajax({
                url: 'lib/weltmeister/api/browse.php',
                dataType: 'json',
                async: false,
                data: query,
                success: resolve
            });
        });
    },

    browseRecursive: function(dirPath, type) {
        return Server.browse(dirPath, type)
            .then(desc => {
                return Promise.all(desc.dirs.map(subDir =>
                        Server.browseRecursive(subDir, type)
                )).then(dirContents =>
                        desc.dirContents = dirContents
                ).then(() => desc);
            });
    },

    glob: function(pattern) {
        return new Promise((resolve, reject) => {
            var query =
                'glob=' + encodeURIComponent(pattern);

            return $.ajax({
                url: 'lib/weltmeister/api/glob.php',
                dataType: 'json',
                async: false,
                data: query,
                success: resolve
            });
        });
    },

    glob2: function(basedir, pattern) {
        return new Promise((resolve, reject) => {
            var query =
                'basedir=' + encodeURIComponent(basedir) +
                '&pattern=' + encodeURIComponent(pattern);

            return $.ajax({
                url: 'lib/weltmeister/api/glob2.php',
                dataType: 'json',
                async: false,
                data: query,
                success: resolve
            });
        });
    },

    types: {
        scripts: "scripts"
    }
};
<commit_msg>added todos<commit_after>// TODO: convert to esnext
// TODO: recursive glob/browse
// TODO: fetch instead of $
"use strict";
var Server = {
    save: function(path, content, callback) {
        console.log("SAVING:", path);
        var postString =
            'path=' + encodeURIComponent(path) +
            '&data=' + encodeURIComponent(content);

        var req = $.ajax({
            url: 'lib/weltmeister/api/save.php',
            type: 'POST',
            dataType: 'json',
            async: false,
            data: postString,
            success: callback || function() { console.log("FILE SAVED"); }
        });

        return req;
    },

    browse: function(dirPath, type) {
        return new Promise(function (resolve, reject) {
            var query =
                'dir=' + encodeURIComponent(dirPath) +
                '&type=' + encodeURIComponent(type);

            return $.ajax({
                url: 'lib/weltmeister/api/browse.php',
                dataType: 'json',
                async: false,
                data: query,
                success: resolve
            });
        });
    },

    browseRecursive: function(dirPath, type) {
        return Server.browse(dirPath, type)
            .then(desc => {
                return Promise.all(desc.dirs.map(subDir =>
                        Server.browseRecursive(subDir, type)
                )).then(dirContents =>
                        desc.dirContents = dirContents
                ).then(() => desc);
            });
    },

    glob: function(pattern) {
        return new Promise((resolve, reject) => {
            var query =
                'glob=' + encodeURIComponent(pattern);

            return $.ajax({
                url: 'lib/weltmeister/api/glob.php',
                dataType: 'json',
                async: false,
                data: query,
                success: resolve
            });
        });
    },

    glob2: function(basedir, pattern) {
        return new Promise((resolve, reject) => {
            var query =
                'basedir=' + encodeURIComponent(basedir) +
                '&pattern=' + encodeURIComponent(pattern);

            return $.ajax({
                url: 'lib/weltmeister/api/glob2.php',
                dataType: 'json',
                async: false,
                data: query,
                success: resolve
            });
        });
    },

    types: {
        scripts: "scripts"
    }
};
<|endoftext|>


<commit_before>exports.up = function(knex) {
  return knex.schema.createTable('${QUIZ_NAME}_responses', table => {
    table.increments('id').primary();
    table.integer('user_id').references('id').inTable('${QUIZ_NAME}_users');
    table.json('data_string');
    table.timestamp('created_at');
    table.timestamp('updated_at');
  });
};

exports.down = function(knex) {
  return knex.schema.dropTable('${QUIZ_NAME}_responses');
};
<commit_msg>changed name to metaResponses<commit_after><|endoftext|>


<commit_before>'use strict';

let me = {};

// always returns 7 characters
me.getDuration = function ({chalk: {bold}, core: {isEntryRunning, getDurationStr}}, duration, start) {
	const isCurrent = isEntryRunning(duration);

	let durStr = getDurationStr(isCurrent ?
		Math.floor((new Date() - Date.parse(start)) / 1e3) :
		duration
	);

	if (durStr.length <= 7) {
		durStr = Array(7 + 1 - durStr.length).join(' ') + durStr;
	}

	return isCurrent ? bold(durStr) : durStr;
};

me.getBrackets = function ({chalk: {bold}}, {name, client}) {
	const brackets = [name];

	if (client) {
		brackets.push(bold(client.name));
	}

	return `[${ brackets.join(' • ') }]`;
};

me.renderOne = function ({chalk: {white, blue, red, green}, core}, idx, {description, duration, start, project}) {
	return [
		blue(`${(idx < 10 ? ' ' : '') + idx})`),
		green(me.getDuration(duration, start)),
		white(description || '(no description)'),
		project ? red(me.getBrackets(project)) : ''
	];
};

me.printList = function ({console: {log}, core}) {
	return entries => {
		let idx = core.isEntryRunning(entries[0]) ? 0 : 1;
		for (const entry of entries) {
			log(...me.renderOne(idx++, entry));
		}
	};
};

me.show = function ({console: {error}, toggl}, token, amount) {
	toggl.getTimeEntries(token, {amount, deps: true})
		.then(me.printList())
		.catch(error);
};

me = require('mee')(module, me, {
	chalk: require('chalk'),

	toggl: require('../toggl.js'),
	core: require('./core.js'),

	console
});
<commit_msg>simple/list simplified…<commit_after>'use strict';

let me = {};

me.getBrackets = function ({chalk: {bold}}, {name, client}) {
	const brackets = [name];

	if (client) {
		brackets.push(bold(client.name));
	}

	return `[${ brackets.join(' • ') }]`;
};

me.getListElement = function ({chalk: {white, blue, red, green, bold}, core}, idx, {description, duration, start, project}) {
	const {durStr, isCurrent} = core.getDuration(duration, start);

	return [
		blue(`${(idx < 10 ? ' ' : '') + idx})`),
		green(isCurrent ? bold(durStr) : durStr),
		white(description || '(no description)'),
		project ? red(me.getBrackets(project)) : ''
	];
};

me.printList = function ({console: {log}, core}) {
	return entries => {
		let idx = core.isEntryRunning(entries[0]) ? 0 : 1;
		for (const entry of entries) {
			log(...me.getListElement(idx++, entry));
		}
	};
};

me.show = function ({console: {error}, toggl}, token, amount) {
	toggl.getTimeEntries(token, {amount, deps: true})
		.then(me.printList())
		.catch(error);
};

me = require('mee')(module, me, {
	chalk: require('chalk'),

	toggl: require('../toggl.js'),
	core: require('./core.js'),

	console
});
<|endoftext|>


<commit_before>"use strict";

var arrayProto = require("@sinonjs/commons").prototypes.array;
var extend = require("./util/core/extend");
var functionToString = require("./util/core/function-to-string");
var proxyCall = require("./proxy-call");
var proxyCallUtil = require("./proxy-call-util");
var proxyInvoke = require("./proxy-invoke");
var sinonFormat = require("./util/core/format");

var push = arrayProto.push;
var forEach = arrayProto.forEach;
var slice = arrayProto.slice;

var emptyFakes = Object.freeze([]);

// Public API
var proxyApi = {
    toString: functionToString,

    named: function named(name) {
        this.displayName = name;
        var nameDescriptor = Object.getOwnPropertyDescriptor(this, "name");
        if (nameDescriptor && nameDescriptor.configurable) {
            // IE 11 functions don't have a name.
            // Safari 9 has names that are not configurable.
            nameDescriptor.value = name;
            Object.defineProperty(this, "name", nameDescriptor);
        }
        return this;
    },

    invoke: proxyInvoke,

    /*
     * Hook for derived implementation to return fake instances matching the
     * given arguments.
     */
    matchingFakes: function(/*args, strict*/) {
        return emptyFakes;
    },

    getCall: function getCall(index) {
        var i = index;
        if (i < 0) {
            i += this.callCount;
        }
        if (i < 0 || i >= this.callCount) {
            return null;
        }

        return proxyCall(
            this,
            this.thisValues[i],
            this.args[i],
            this.returnValues[i],
            this.exceptions[i],
            this.callIds[i],
            this.errorsWithCallStack[i]
        );
    },

    getCalls: function() {
        var calls = [];
        var i;

        for (i = 0; i < this.callCount; i++) {
            push(calls, this.getCall(i));
        }

        return calls;
    },

    calledBefore: function calledBefore(proxy) {
        if (!this.called) {
            return false;
        }

        if (!proxy.called) {
            return true;
        }

        return this.callIds[0] < proxy.callIds[proxy.callIds.length - 1];
    },

    calledAfter: function calledAfter(proxy) {
        if (!this.called || !proxy.called) {
            return false;
        }

        return this.callIds[this.callCount - 1] > proxy.callIds[0];
    },

    calledImmediatelyBefore: function calledImmediatelyBefore(proxy) {
        if (!this.called || !proxy.called) {
            return false;
        }

        return this.callIds[this.callCount - 1] === proxy.callIds[proxy.callCount - 1] - 1;
    },

    calledImmediatelyAfter: function calledImmediatelyAfter(proxy) {
        if (!this.called || !proxy.called) {
            return false;
        }

        return this.callIds[this.callCount - 1] === proxy.callIds[proxy.callCount - 1] + 1;
    },

    formatters: require("./spy-formatters"),
    printf: function(format) {
        var spyInstance = this;
        var args = slice(arguments, 1);
        var formatter;

        return (format || "").replace(/%(.)/g, function(match, specifyer) {
            formatter = proxyApi.formatters[specifyer];

            if (typeof formatter === "function") {
                return String(formatter(spyInstance, args));
            } else if (!isNaN(parseInt(specifyer, 10))) {
                return sinonFormat(args[specifyer - 1]);
            }

            return "%" + specifyer;
        });
    },

    resetHistory: function() {
        if (this.invoking) {
            var err = new Error(
                "Cannot reset Sinon function while invoking it. " +
                    "Move the call to .resetHistory outside of the callback."
            );
            err.name = "InvalidResetException";
            throw err;
        }

        this.called = false;
        this.notCalled = true;
        this.calledOnce = false;
        this.calledTwice = false;
        this.calledThrice = false;
        this.callCount = 0;
        this.firstCall = null;
        this.secondCall = null;
        this.thirdCall = null;
        this.lastCall = null;
        this.args = [];
        this.lastArg = null;
        this.returnValues = [];
        this.thisValues = [];
        this.exceptions = [];
        this.callIds = [];
        this.errorsWithCallStack = [];

        if (this.fakes) {
            forEach(this.fakes, function(fake) {
                fake.resetHistory();
            });
        }

        return this;
    }
};

var delegateToCalls = proxyCallUtil.delegateToCalls;
delegateToCalls(proxyApi, "calledOn", true);
delegateToCalls(proxyApi, "alwaysCalledOn", false, "calledOn");
delegateToCalls(proxyApi, "calledWith", true);
delegateToCalls(proxyApi, "calledOnceWith", true, "calledWith", false, undefined, 1);
delegateToCalls(proxyApi, "calledWithMatch", true);
delegateToCalls(proxyApi, "alwaysCalledWith", false, "calledWith");
delegateToCalls(proxyApi, "alwaysCalledWithMatch", false, "calledWithMatch");
delegateToCalls(proxyApi, "calledWithExactly", true);
delegateToCalls(proxyApi, "calledOnceWithExactly", true, "calledWithExactly", false, undefined, 1);
delegateToCalls(proxyApi, "alwaysCalledWithExactly", false, "calledWithExactly");
delegateToCalls(proxyApi, "neverCalledWith", false, "notCalledWith", false, function() {
    return true;
});
delegateToCalls(proxyApi, "neverCalledWithMatch", false, "notCalledWithMatch", false, function() {
    return true;
});
delegateToCalls(proxyApi, "threw", true);
delegateToCalls(proxyApi, "alwaysThrew", false, "threw");
delegateToCalls(proxyApi, "returned", true);
delegateToCalls(proxyApi, "alwaysReturned", false, "returned");
delegateToCalls(proxyApi, "calledWithNew", true);
delegateToCalls(proxyApi, "alwaysCalledWithNew", false, "calledWithNew");

function createProxy(func, originalFunc) {
    var proxy = wrapFunction(func, originalFunc);

    // Inherit function properties:
    extend(proxy, func);

    proxy.prototype = func.prototype;

    extend.nonEnum(proxy, proxyApi);

    return proxy;
}

function wrapFunction(func, originalFunc) {
    var arity = originalFunc.length;
    var p;
    // Do not change this to use an eval. Projects that depend on sinon block the use of eval.
    // ref: https://github.com/sinonjs/sinon/issues/710
    switch (arity) {
        /*eslint-disable no-unused-vars, max-len*/
        case 0:
            p = function proxy() {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 1:
            p = function proxy(a) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 2:
            p = function proxy(a, b) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 3:
            p = function proxy(a, b, c) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 4:
            p = function proxy(a, b, c, d) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 5:
            p = function proxy(a, b, c, d, e) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 6:
            p = function proxy(a, b, c, d, e, f) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 7:
            p = function proxy(a, b, c, d, e, f, g) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 8:
            p = function proxy(a, b, c, d, e, f, g, h) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 9:
            p = function proxy(a, b, c, d, e, f, g, h, i) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 10:
            p = function proxy(a, b, c, d, e, f, g, h, i, j) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 11:
            p = function proxy(a, b, c, d, e, f, g, h, i, j, k) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 12:
            p = function proxy(a, b, c, d, e, f, g, h, i, j, k, l) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        default:
            p = function proxy() {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        /*eslint-enable*/
    }
    var nameDescriptor = Object.getOwnPropertyDescriptor(originalFunc, "name");
    if (nameDescriptor && nameDescriptor.configurable) {
        // IE 11 functions don't have a name.
        // Safari 9 has names that are not configurable.
        Object.defineProperty(p, "name", nameDescriptor);
    }
    extend.nonEnum(p, {
        isSinonProxy: true,

        called: false,
        notCalled: true,
        calledOnce: false,
        calledTwice: false,
        calledThrice: false,
        callCount: 0,
        firstCall: null,
        secondCall: null,
        thirdCall: null,
        lastCall: null,
        lastArg: null,
        args: [],
        returnValues: [],
        thisValues: [],
        exceptions: [],
        callIds: [],
        errorsWithCallStack: []
    });
    return p;
}

module.exports = createProxy;
<commit_msg>Add clarifying comment for negative indices<commit_after>"use strict";

var arrayProto = require("@sinonjs/commons").prototypes.array;
var extend = require("./util/core/extend");
var functionToString = require("./util/core/function-to-string");
var proxyCall = require("./proxy-call");
var proxyCallUtil = require("./proxy-call-util");
var proxyInvoke = require("./proxy-invoke");
var sinonFormat = require("./util/core/format");

var push = arrayProto.push;
var forEach = arrayProto.forEach;
var slice = arrayProto.slice;

var emptyFakes = Object.freeze([]);

// Public API
var proxyApi = {
    toString: functionToString,

    named: function named(name) {
        this.displayName = name;
        var nameDescriptor = Object.getOwnPropertyDescriptor(this, "name");
        if (nameDescriptor && nameDescriptor.configurable) {
            // IE 11 functions don't have a name.
            // Safari 9 has names that are not configurable.
            nameDescriptor.value = name;
            Object.defineProperty(this, "name", nameDescriptor);
        }
        return this;
    },

    invoke: proxyInvoke,

    /*
     * Hook for derived implementation to return fake instances matching the
     * given arguments.
     */
    matchingFakes: function(/*args, strict*/) {
        return emptyFakes;
    },

    getCall: function getCall(index) {
        var i = index;
        if (i < 0) {
            // Negative indices means counting backwards from the last call
            i += this.callCount;
        }
        if (i < 0 || i >= this.callCount) {
            return null;
        }

        return proxyCall(
            this,
            this.thisValues[i],
            this.args[i],
            this.returnValues[i],
            this.exceptions[i],
            this.callIds[i],
            this.errorsWithCallStack[i]
        );
    },

    getCalls: function() {
        var calls = [];
        var i;

        for (i = 0; i < this.callCount; i++) {
            push(calls, this.getCall(i));
        }

        return calls;
    },

    calledBefore: function calledBefore(proxy) {
        if (!this.called) {
            return false;
        }

        if (!proxy.called) {
            return true;
        }

        return this.callIds[0] < proxy.callIds[proxy.callIds.length - 1];
    },

    calledAfter: function calledAfter(proxy) {
        if (!this.called || !proxy.called) {
            return false;
        }

        return this.callIds[this.callCount - 1] > proxy.callIds[0];
    },

    calledImmediatelyBefore: function calledImmediatelyBefore(proxy) {
        if (!this.called || !proxy.called) {
            return false;
        }

        return this.callIds[this.callCount - 1] === proxy.callIds[proxy.callCount - 1] - 1;
    },

    calledImmediatelyAfter: function calledImmediatelyAfter(proxy) {
        if (!this.called || !proxy.called) {
            return false;
        }

        return this.callIds[this.callCount - 1] === proxy.callIds[proxy.callCount - 1] + 1;
    },

    formatters: require("./spy-formatters"),
    printf: function(format) {
        var spyInstance = this;
        var args = slice(arguments, 1);
        var formatter;

        return (format || "").replace(/%(.)/g, function(match, specifyer) {
            formatter = proxyApi.formatters[specifyer];

            if (typeof formatter === "function") {
                return String(formatter(spyInstance, args));
            } else if (!isNaN(parseInt(specifyer, 10))) {
                return sinonFormat(args[specifyer - 1]);
            }

            return "%" + specifyer;
        });
    },

    resetHistory: function() {
        if (this.invoking) {
            var err = new Error(
                "Cannot reset Sinon function while invoking it. " +
                    "Move the call to .resetHistory outside of the callback."
            );
            err.name = "InvalidResetException";
            throw err;
        }

        this.called = false;
        this.notCalled = true;
        this.calledOnce = false;
        this.calledTwice = false;
        this.calledThrice = false;
        this.callCount = 0;
        this.firstCall = null;
        this.secondCall = null;
        this.thirdCall = null;
        this.lastCall = null;
        this.args = [];
        this.lastArg = null;
        this.returnValues = [];
        this.thisValues = [];
        this.exceptions = [];
        this.callIds = [];
        this.errorsWithCallStack = [];

        if (this.fakes) {
            forEach(this.fakes, function(fake) {
                fake.resetHistory();
            });
        }

        return this;
    }
};

var delegateToCalls = proxyCallUtil.delegateToCalls;
delegateToCalls(proxyApi, "calledOn", true);
delegateToCalls(proxyApi, "alwaysCalledOn", false, "calledOn");
delegateToCalls(proxyApi, "calledWith", true);
delegateToCalls(proxyApi, "calledOnceWith", true, "calledWith", false, undefined, 1);
delegateToCalls(proxyApi, "calledWithMatch", true);
delegateToCalls(proxyApi, "alwaysCalledWith", false, "calledWith");
delegateToCalls(proxyApi, "alwaysCalledWithMatch", false, "calledWithMatch");
delegateToCalls(proxyApi, "calledWithExactly", true);
delegateToCalls(proxyApi, "calledOnceWithExactly", true, "calledWithExactly", false, undefined, 1);
delegateToCalls(proxyApi, "alwaysCalledWithExactly", false, "calledWithExactly");
delegateToCalls(proxyApi, "neverCalledWith", false, "notCalledWith", false, function() {
    return true;
});
delegateToCalls(proxyApi, "neverCalledWithMatch", false, "notCalledWithMatch", false, function() {
    return true;
});
delegateToCalls(proxyApi, "threw", true);
delegateToCalls(proxyApi, "alwaysThrew", false, "threw");
delegateToCalls(proxyApi, "returned", true);
delegateToCalls(proxyApi, "alwaysReturned", false, "returned");
delegateToCalls(proxyApi, "calledWithNew", true);
delegateToCalls(proxyApi, "alwaysCalledWithNew", false, "calledWithNew");

function createProxy(func, originalFunc) {
    var proxy = wrapFunction(func, originalFunc);

    // Inherit function properties:
    extend(proxy, func);

    proxy.prototype = func.prototype;

    extend.nonEnum(proxy, proxyApi);

    return proxy;
}

function wrapFunction(func, originalFunc) {
    var arity = originalFunc.length;
    var p;
    // Do not change this to use an eval. Projects that depend on sinon block the use of eval.
    // ref: https://github.com/sinonjs/sinon/issues/710
    switch (arity) {
        /*eslint-disable no-unused-vars, max-len*/
        case 0:
            p = function proxy() {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 1:
            p = function proxy(a) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 2:
            p = function proxy(a, b) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 3:
            p = function proxy(a, b, c) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 4:
            p = function proxy(a, b, c, d) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 5:
            p = function proxy(a, b, c, d, e) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 6:
            p = function proxy(a, b, c, d, e, f) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 7:
            p = function proxy(a, b, c, d, e, f, g) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 8:
            p = function proxy(a, b, c, d, e, f, g, h) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 9:
            p = function proxy(a, b, c, d, e, f, g, h, i) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 10:
            p = function proxy(a, b, c, d, e, f, g, h, i, j) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 11:
            p = function proxy(a, b, c, d, e, f, g, h, i, j, k) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        case 12:
            p = function proxy(a, b, c, d, e, f, g, h, i, j, k, l) {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        default:
            p = function proxy() {
                return p.invoke(func, this, slice(arguments));
            };
            break;
        /*eslint-enable*/
    }
    var nameDescriptor = Object.getOwnPropertyDescriptor(originalFunc, "name");
    if (nameDescriptor && nameDescriptor.configurable) {
        // IE 11 functions don't have a name.
        // Safari 9 has names that are not configurable.
        Object.defineProperty(p, "name", nameDescriptor);
    }
    extend.nonEnum(p, {
        isSinonProxy: true,

        called: false,
        notCalled: true,
        calledOnce: false,
        calledTwice: false,
        calledThrice: false,
        callCount: 0,
        firstCall: null,
        secondCall: null,
        thirdCall: null,
        lastCall: null,
        lastArg: null,
        args: [],
        returnValues: [],
        thisValues: [],
        exceptions: [],
        callIds: [],
        errorsWithCallStack: []
    });
    return p;
}

module.exports = createProxy;
<|endoftext|>


<commit_before>// https://jsfiddle.net/b4ycbo4p/7/

function t (x, y) {
	return `translate(${x},${y})`;
}

function genSmithChart ($) {
  return function SmithChart(props) {
    const r = props.r;
    return $('div', {},
      $('div', {}, 'Smith Chart'),
      $('div', {},
        $('svg', { viewBox: [0, 0, 2 * r + 2, 2 * r + 2] },
          $('defs', {},
            $('style', {},
            `.l1 {
            	stroke: black;
              fill: none;
              stroke-linecap: round;
              stroke-opacity: 0.1;
            }`)
          ),
          $('g', {transform: t(.5, .5)},
            $('line', {
              x1: 0, y1: r,
              x2: 2 * r, y2: r,
              className: 'l1'
            }),
            [0,1,2,3,4,5]
            .map(e => Math.pow(2, -e) * r)
            .map((e, i) => $('circle', {
              key: i,
              cx: 2 * r - e,
              cy: r,
              r: e,
              className: 'l1'
            })),
            [1]
            .map((e, i) => $('path', {
              className: 'l1',
              d: `M ${2 * r},${r} A ${r} ${r} 0 0 1 ${r},0`
            }))
          )
        )
      )
    );
  };
}

module.exports = genSmithChart;

// ReactDOM.render(
//   genSmithChart(React.createElement)({ r: 256 }),
//   document.getElementById('container')
// );
<commit_msg>Update smith-chart.js<commit_after>// https://jsfiddle.net/b4ycbo4p/7/

function t (x, y) {
	return `translate(${x},${y})`;
}

function genSmithChart ($) {
  return function SmithChart(props) {
    const r = props.r;
    return $('div', {},
      $('div', {}, 'Smith Chart'),
      $('div', {},
        $('svg', { viewBox: [0, 0, 2 * r + 2, 2 * r + 2] },
          $('defs', {},
            $('style', {},
            `.l1 {
            	stroke: black;
              fill: none;
              stroke-linecap: round;
              stroke-opacity: 0.1;
            }`)
          ),
          $('g', {transform: t(.5, .5)},
            $('line', {
              x1: 0, y1: r,
              x2: 2 * r, y2: r,
              className: 'l1'
            }),
            [0,1,2,3,4,5]
            .map(e => Math.pow(2, -e) * r)
            .map((e, i) => $('circle', {
              key: i,
              cx: 2 * r - e,
              cy: r,
              r: e,
              className: 'l1'
            })),
            [1]
            .map((e, i) => [
            	$('path', {
              	className: 'l1',
              	d: `M ${2 * r},${r} A ${r} ${r} 0 0 1 ${r},0`
            	}),
            	$('path', {
              	className: 'l1',
              	d: `M ${2 * r},${r} A ${r} ${r} 0 0 0 ${r},${2 * r}`
            	})
            ])
          )
        )
      )
    );
  };
}

module.exports = genSmithChart;

// ReactDOM.render(
//   genSmithChart(React.createElement)({ r: 256 }),
//   document.getElementById('container')
// );
<|endoftext|>


<commit_before>// https://jsfiddle.net/b4ycbo4p/10/

function t (x, y) {
	return `translate(${x},${y})`;
}

function genSmithChart ($) {

  function Re (props) {
    const r = props.r;
    return $('g', {},
    	props.lines
      .map(x => r / (1 + x))
      .map((e, i) => $('circle', {
        key: i,
        cx: 2 * r - e,
        cy: r,
        r: e,
        className: 'l1'
      }))
    );
  }

  function Im (props) {
    const r = props.r;
    return $('g', {},
      props.lines
      .map(x => [
      	$('circle', {
        	key: 0,
          cx: 2 * r,
          cy: r - (r / x),
          r: (r / x),
          className: 'l1'
        }),
        $('circle', {
        	key: 1,
          cx: 2 * r,
          cy: r + (r / x),
          r: (r / x),
          className: 'l1'
        })
/* 			$('path', {
          className: 'l1',
          d: `M ${2 * r},${r} A ${r} ${r} 0 0 1 ${r},0`
        }),
        $('path', {
          className: 'l1',
          d: `M ${2 * r},${r} A ${r} ${r} 0 0 0 ${r},${2 * r}`
        }) */
      ]
      ),
      $('line', {
        x1: 0, y1: r,
        x2: 2 * r, y2: r,
        className: 'l1'
      })
    );
  }

  return function SmithChart(props) {
    const r = props.r;
    return $('div', {},
      $('div', {}, 'Smith Chart'),
      $('div', {},
        $('svg', { viewBox: [0, 0, 2 * r + 2, 2 * r + 2] },
          $('defs', {},
            $('style', {},
            `.l1 {
            	stroke: black;
              fill: none;
              stroke-linecap: square; /* butt */
              stroke-opacity: 0.1;
            }`)
          ),
          $('g', {transform: t(.5, .5)},
            $(Re, {r: r, lines: [0, .2, .5, 1, 2, 5]}),
            $(Im, {r: r, lines: [.5, 1, 2, 5]})
          )
        )
      )
    );
  };
}

module.exports = genSmithChart;

// ReactDOM.render(
//   genSmithChart(React.createElement)({ r: 256 }),
//   document.getElementById('container')
// );
<commit_msg>Update smith-chart.js<commit_after>// https://jsfiddle.net/b4ycbo4p/12/

function t (x, y) {
  return `translate(${x},${y})`;
}

function genSmithChart ($) {

  function Re (props) {
    const r = props.r;
    return $('g', {transform: t(2 * r, r)},
    	props.lines
      .map(x => r / (1 + x))
      .map((e, i) => $('circle', {
        key: i,
        cx: -e,
        cy: 0,
        r: e,
        className: 'l1'
      }))
    );
  }

  function Im (props) {
    const r = props.r;
    return $('g', {transform: t(2 * r, r)},
      props.lines
      .map(x => [
      	$('circle', {
        	key: 0,
          cx: 0,
          cy: -(r / x),
          r: (r / x),
          className: 'l1'
        }),
        $('circle', {
        	key: 1,
          cx: 0,
          cy: r / x,
          r: r / x,
          className: 'l1'
        })
/* 			$('path', {
          className: 'l1',
          d: `M ${2 * r},${r} A ${r} ${r} 0 0 1 ${r},0`
        }),
        $('path', {
          className: 'l1',
          d: `M ${2 * r},${r} A ${r} ${r} 0 0 0 ${r},${2 * r}`
        }) */
      ]
      ),
      $('line', {
        x1: 0, y1: 0,
        x2: -2 * r, y2: 0,
        className: 'l1'
      })
    );
  }

  return function SmithChart(props) {
    const r = props.r;
    return $('div', {},
      $('div', {}, 'Smith Chart'),
      $('div', {},
        $('svg', { viewBox: [0, 0, 2 * r + 2, 2 * r + 2] },
          $('defs', {},
            $('style', {},
            `.l1 {
            	stroke: black;
              fill: none;
              stroke-linecap: square; /* butt */
              stroke-opacity: 0.1;
            }`)
          ),
          $('g', {transform: t(.5, .5)},
            $(Re, {r: r, lines: [0, .2, .5, 1, 2, 5]}),
            $(Im, {r: r, lines: [.2, .5, 1, 1.4, 2, 3, 5]})
          )
        )
      )
    );
  };
}

module.exports = genSmithChart;

// ReactDOM.render(
//   genSmithChart(React.createElement)({ r: 256 }),
//   document.getElementById('container')
// );
<|endoftext|>


<commit_before>"use strict";
/*jshint eqnull:true */
/*jshint globalstrict:true */
/*jshint node:true */

var sqlPromise = {};

var Promises = require('promise-plus');

sqlPromise.register = function register(motorName, motor){
    this.motors = this.motors || {};
    this.motors[motorName] = motor;
}

sqlPromise.Query = function Query(sqlLib, internal, motor) {
    this.fetchRowByRow = function fetchRowByRow(consumerFunction){
        return Promises.make(function(resolve, reject){
            motor.fetchRowByRow(internal, {
                onRow:consumerFunction,
                onEnd:resolve,
                onError:reject
            });
        });
    }
    this.fetchAll = function fetchAll(){
        return Promises.start(function(){
            return motor.fetchAll(internal);
        }).then(function(result){
            return result;
        });
    }
    this.fetchUniqueRow = function fetchUniqueRow() {
        var cont=0;
        function failWithError(reject) {
            var er = new Error("ERROR sql-promise.fetchUniqueRow");
            er.notUnique = true;
            reject(er);
        }
        return Promises.make(function(resolve, reject){
            motor.fetchRowByRow(internal, {
                onRow:function(res) {
                    ++cont;
                    if(cont>1) { failWithError(reject); }
                    return res;
                },
                onEnd:function() {
                    if(cont<1) { failWithError(reject); }
                    resolve();
                },
                onError:reject
            });
        });
    }
};
sqlPromise.Query.exposes={};
sqlPromise.Query.exposes.fetchAll={returns:Object};
sqlPromise.Query.exposes.fetchRowByRow={returns:Object};
sqlPromise.Query.exposes.fetchUniqueRow={returns:Object};

sqlPromise.PreparedQuery = function PreparedQuery(sqlLib, internal, motor) {
    this.query = function query(data){
        return Promises.plus(
            sqlLib.Query,
            Promises.start(function(){
                return motor.query(internal, data);
            }).then(function(internalQuery){
                return new sqlLib.Query(sqlLib, internalQuery, motor);
            })
        );
    }
};
sqlPromise.PreparedQuery.exposes={};
sqlPromise.PreparedQuery.exposes.query={returns:sqlPromise.Query};

sqlPromise.Connection = function Connection(sqlLib, internal, motor) {
    this.prepare = function prepare(sqlSentence){
        return Promises.plus(
            sqlLib.PreparedQuery,
            Promises.start(function(){
                return motor.prepare(internal, sqlSentence);
            }).then(function(internalPreparedQuery){
                return new sqlLib.PreparedQuery(sqlLib, internalPreparedQuery, motor);
            })
        );
    }
    this.done = function done(){
        return motor.done(internal);
    }
    // shortcuts:
    this.query = function query(sqlSentence, data){
        return Promises.plus(
            sqlLib.Query,
            this.prepare(sqlSentence).then(function(preparedQuery){
                return preparedQuery.query(data);
            })
        );
    }
    this.placeHolder = function placeHolder(n){
        return motor.placeHolder(n);
    }
};
sqlPromise.Connection.exposes={};
sqlPromise.Connection.exposes.prepare={returns:sqlPromise.PreparedQuery};
sqlPromise.Connection.exposes.done={};
sqlPromise.Connection.exposes.query={returns:sqlPromise.Query};

sqlPromise.connect = function connect(connOpts){
    var sqlLib = this;
    var motor = this.motors[connOpts.motor];
    return Promises.plus(
        sqlLib.Query,
        Promises.start(function(){
            return motor.connect(connOpts);
        }).then(function(internal){
            return new sqlLib.Connection(sqlLib, internal, motor);
        })
    );
}
sqlPromise.connect.returns = sqlPromise.Connection;

module.exports = sqlPromise;<commit_msg>Arreglo fetchUniqueRow<commit_after>"use strict";
/*jshint eqnull:true */
/*jshint globalstrict:true */
/*jshint node:true */

var sqlPromise = {};

var Promises = require('promise-plus');

sqlPromise.register = function register(motorName, motor){
    this.motors = this.motors || {};
    this.motors[motorName] = motor;
}

sqlPromise.Query = function Query(sqlLib, internal, motor) {
    this.fetchRowByRow = function fetchRowByRow(consumerFunction){
        return Promises.make(function(resolve, reject){
            motor.fetchRowByRow(internal, {
                onRow:consumerFunction,
                onEnd:resolve,
                onError:reject
            });
        });
    }
    this.fetchAll = function fetchAll(){
        return Promises.start(function(){
            return motor.fetchAll(internal);
        }).then(function(result){
            return result;
        });
    }
    this.fetchUniqueRow = function fetchUniqueRow() {
        var cont=0;
        function failWithError(reject) {
            var er = new Error("ERROR sql-promise.fetchUniqueRow");
            er.notUnique = true;
            reject(er);
        }
        var row=null;
        return Promises.make(function(resolve, reject){
            motor.fetchRowByRow(internal, {
                onRow:function(res) {
                    ++cont;
                    if(cont>1) { failWithError(reject); }
                    row = res;
                },
                onEnd:function() {
                    if(cont<1) { failWithError(reject); }
                    else resolve(row);
                },
                onError:reject
            });
        });
    }
};
sqlPromise.Query.exposes={};
sqlPromise.Query.exposes.fetchAll={returns:Object};
sqlPromise.Query.exposes.fetchRowByRow={returns:Object};
sqlPromise.Query.exposes.fetchUniqueRow={returns:Object};

sqlPromise.PreparedQuery = function PreparedQuery(sqlLib, internal, motor) {
    this.query = function query(data){
        return Promises.plus(
            sqlLib.Query,
            Promises.start(function(){
                return motor.query(internal, data);
            }).then(function(internalQuery){
                return new sqlLib.Query(sqlLib, internalQuery, motor);
            })
        );
    }
};
sqlPromise.PreparedQuery.exposes={};
sqlPromise.PreparedQuery.exposes.query={returns:sqlPromise.Query};

sqlPromise.Connection = function Connection(sqlLib, internal, motor) {
    this.prepare = function prepare(sqlSentence){
        return Promises.plus(
            sqlLib.PreparedQuery,
            Promises.start(function(){
                return motor.prepare(internal, sqlSentence);
            }).then(function(internalPreparedQuery){
                return new sqlLib.PreparedQuery(sqlLib, internalPreparedQuery, motor);
            })
        );
    }
    this.done = function done(){
        return motor.done(internal);
    }
    // shortcuts:
    this.query = function query(sqlSentence, data){
        return Promises.plus(
            sqlLib.Query,
            this.prepare(sqlSentence).then(function(preparedQuery){
                return preparedQuery.query(data);
            })
        );
    }
    this.placeHolder = function placeHolder(n){
        return motor.placeHolder(n);
    }
};
sqlPromise.Connection.exposes={};
sqlPromise.Connection.exposes.prepare={returns:sqlPromise.PreparedQuery};
sqlPromise.Connection.exposes.done={};
sqlPromise.Connection.exposes.query={returns:sqlPromise.Query};

sqlPromise.connect = function connect(connOpts){
    var sqlLib = this;
    var motor = this.motors[connOpts.motor];
    return Promises.plus(
        sqlLib.Query,
        Promises.start(function(){
            return motor.connect(connOpts);
        }).then(function(internal){
            return new sqlLib.Connection(sqlLib, internal, motor);
        })
    );
}
sqlPromise.connect.returns = sqlPromise.Connection;

module.exports = sqlPromise;<|endoftext|>


<commit_before><commit_msg>strReplace<commit_after>define(function (require) {
    return function (str, data) {
        var reg = /\#\{([a-zA-Z\_\-0-9]+)\}/g;
        var result = str.replace(reg, function (){
            var ar = (typeof data[arguments[1]] == 'undefined' ) ? '' : data[arguments[1]];
            return ar;
        });
        return result;
    };
});<|endoftext|>


<commit_before>var concurrency = Math.ceil(require('os').cpus().length * 16);
var util = require('util');

module.exports = {};
module.exports.Tile = Tile;
module.exports.Info = Info;
module.exports.DeserializationError = DeserializationError;
module.exports.Stats = Stats;
module.exports.addChildren = addChildren;
module.exports.sumChildren = sumChildren;
module.exports.isEmpty = isEmpty;
module.exports.multiread = multiread;
module.exports.multiwrite = multiwrite;
module.exports.setConcurrency = setConcurrency;
module.exports.serialize = serialize;
module.exports.deserialize = deserialize;
module.exports.serialHeader = 'BREAKFASTTIME';

function DeserializationError(msg) {
    this.message = msg;
    this.name = 'DeserializationError';
}
util.inherits(DeserializationError, Error);

function Tile(z,x,y,buffer) {
    this.z = isNaN(z) ? undefined : Number(z);
    this.x = isNaN(x) ? undefined : Number(x);
    this.y = isNaN(y) ? undefined : Number(y);
    this.buffer = buffer instanceof Buffer ? buffer : undefined;
    return this;
}

function Info(info) {
    for (var k in info) this[k] = info[k];
    return this;
}

function serialize(obj) {
    if (obj instanceof Tile) return serializeTile(obj);
    if (obj instanceof Info) return serializeInfo(obj);
    return '';
}

function deserialize(data) {
    if (data.indexOf('{"z":') === 0) return deserializeTile(data);
    if (data.indexOf('{') === 0) return deserializeInfo(data);
    throw new DeserializationError('Invalid data');
}

function serializeTile(tile) {
    var obj = {
        z: isNaN(tile.z) ? null : Number(tile.z),
        x: isNaN(tile.x) ? null : Number(tile.x),
        y: isNaN(tile.y) ? null : Number(tile.y),
        buffer: tile.buffer instanceof Buffer ? tile.buffer.toString('base64') : null
    };

    return JSON.stringify(obj);
}

function serializeInfo(info) {
    return JSON.stringify(info);
}

function deserializeTile(data) {
    var obj, buf;

    try { obj = JSON.parse(data); }
    catch(err) { throw new DeserializationError('Could not parse data'); }

    if (!obj.hasOwnProperty('z') ||
        !obj.hasOwnProperty('x') ||
        !obj.hasOwnProperty('y') ||
        !obj.hasOwnProperty('buffer')) {
        throw new DeserializationError('Invalid data');
    }

    if (typeof obj.buffer === 'string' || typeof obj.buffer === 'number') {
        buf = new Buffer(obj.buffer, 'base64');
    } else {
        throw new DeserializationError('Invalid buffer');
    }

    return new Tile(obj.z, obj.x, obj.y, buf);
}

function deserializeInfo(data) {
    try { obj = JSON.parse(data); }
    catch(err) { throw new DeserializationError('Could not parse data'); }

    return new Info(obj);
}

function Stats() {
    this.ops = 0;
    this.total = 0;
    this.done = 0;
    this.skipped = 0;
}

function addChildren(tile, bboxes, array) {
    var z = tile.z + 1;
    var x = tile.x * 2;
    var y = tile.y * 2;
    var b = tile.buffer && isSolid(tile.buffer) ? tile.buffer : null;

    var bbox = bboxes[z];
    if (!bbox) return;
    if (y >= bbox.minY) {
        if (x >= bbox.minX) array.unshift(new Tile(z, x, y, b));
        if (x + 1 <= bbox.maxX) array.unshift(new Tile(z, x + 1, y, b));
    }
    if (y + 1 <= bbox.maxY) {
        if (x >= bbox.minX) array.unshift(new Tile(z, x, y + 1, b));
        if (x + 1 <= bbox.maxX) array.unshift(new Tile(z, x + 1, y + 1, b));
    }
}

function sumChildren(tile, bboxes) {
    var sum = 0;
    var size = 1;
    for (var x = tile.x, y = tile.y, z = tile.z + 1; bboxes[z]; z++) {
        x *= 2; y *= 2; size *= 2;
        var width = Math.min(bboxes[z].maxX, x + size - 1) - Math.max(bboxes[z].minX, x) + 1;
        var height = Math.min(bboxes[z].maxY, y + size - 1) - Math.max(bboxes[z].minY, y) + 1;
        sum += width * height;
    }
    return sum;
}

function isEmpty(buffer) {
    return buffer.solid && buffer.solid.split(',')[3] === '0';
}

function isSolid(buffer) {
    return buffer.solid && buffer.solid.split(',')[3] !== '0';
}

// Helper utility for _read functions. Pass your stream object and a
// getter that can be called concurrently and it will concurrently
// call your getter behind the scenes and manage the endstate of the
// stream.
function multiread(stream, get) {
    if (stream._multiread === undefined) {
        stream._multiread = stream._multiread || [];
        stream._multireading = stream._multireading || 0;
        stream._multireadmax = stream._multireadmax || concurrency;
    }
    if (stream._multiread.length) {
        push();
    } else {
        stream.once('_push', push);
    }
    while ((stream._multiread.length + stream._multireading) < stream._multireadmax) {
        stream._multireading++;
        if (!get(done)) break;
    }

    function done(item) {
        stream._multireading--;
        if (item === null && !stream._multireading) {
            stream.emit('_push');
        } else if (item) {
            stream._multiread.push(item);
            stream.emit('_push');
        }
    }

    function push() {
        if (stream._multiread.length) {
            stream.push(stream._multiread.shift());
        } else {
            stream.push(null);
        }
    }
}

function multiwrite(stream, callback, put) {
    if (stream._multiwrite === undefined) {
        stream._multiwrite = stream._multiwrite || [];
        stream._multiwriting = stream._multiwriting || 0;
        stream._multiwritemax = stream._multiwritemax || concurrency;
    }
    stream._multiwriting++;
    if (stream._multiwriting < stream._multiwritemax) {
        callback();
    } else {
        stream.once('_write', callback);
    }

    put(function(err) {
        stream._multiwriting--;
        if (err) stream.emit('error', err);
        stream.emit('_write');
        if (!stream._multiwriting) stream.emit('_writeEmpty');
    });
}

function setConcurrency(c) {
    concurrency = c;
}
<commit_msg>adjust header name to reflect serialization format<commit_after>var concurrency = Math.ceil(require('os').cpus().length * 16);
var util = require('util');

module.exports = {};
module.exports.Tile = Tile;
module.exports.Info = Info;
module.exports.DeserializationError = DeserializationError;
module.exports.Stats = Stats;
module.exports.addChildren = addChildren;
module.exports.sumChildren = sumChildren;
module.exports.isEmpty = isEmpty;
module.exports.multiread = multiread;
module.exports.multiwrite = multiwrite;
module.exports.setConcurrency = setConcurrency;
module.exports.serialize = serialize;
module.exports.deserialize = deserialize;
module.exports.serialHeader = 'JSONBREAKFASTTIME';

function DeserializationError(msg) {
    this.message = msg;
    this.name = 'DeserializationError';
}
util.inherits(DeserializationError, Error);

function Tile(z,x,y,buffer) {
    this.z = isNaN(z) ? undefined : Number(z);
    this.x = isNaN(x) ? undefined : Number(x);
    this.y = isNaN(y) ? undefined : Number(y);
    this.buffer = buffer instanceof Buffer ? buffer : undefined;
    return this;
}

function Info(info) {
    for (var k in info) this[k] = info[k];
    return this;
}

function serialize(obj) {
    if (obj instanceof Tile) return serializeTile(obj);
    if (obj instanceof Info) return serializeInfo(obj);
    return '';
}

function deserialize(data) {
    if (data.indexOf('{"z":') === 0) return deserializeTile(data);
    if (data.indexOf('{') === 0) return deserializeInfo(data);
    throw new DeserializationError('Invalid data');
}

function serializeTile(tile) {
    var obj = {
        z: isNaN(tile.z) ? null : Number(tile.z),
        x: isNaN(tile.x) ? null : Number(tile.x),
        y: isNaN(tile.y) ? null : Number(tile.y),
        buffer: tile.buffer instanceof Buffer ? tile.buffer.toString('base64') : null
    };

    return JSON.stringify(obj);
}

function serializeInfo(info) {
    return JSON.stringify(info);
}

function deserializeTile(data) {
    var obj, buf;

    try { obj = JSON.parse(data); }
    catch(err) { throw new DeserializationError('Could not parse data'); }

    if (!obj.hasOwnProperty('z') ||
        !obj.hasOwnProperty('x') ||
        !obj.hasOwnProperty('y') ||
        !obj.hasOwnProperty('buffer')) {
        throw new DeserializationError('Invalid data');
    }

    if (typeof obj.buffer === 'string' || typeof obj.buffer === 'number') {
        buf = new Buffer(obj.buffer, 'base64');
    } else {
        throw new DeserializationError('Invalid buffer');
    }

    return new Tile(obj.z, obj.x, obj.y, buf);
}

function deserializeInfo(data) {
    try { obj = JSON.parse(data); }
    catch(err) { throw new DeserializationError('Could not parse data'); }

    return new Info(obj);
}

function Stats() {
    this.ops = 0;
    this.total = 0;
    this.done = 0;
    this.skipped = 0;
}

function addChildren(tile, bboxes, array) {
    var z = tile.z + 1;
    var x = tile.x * 2;
    var y = tile.y * 2;
    var b = tile.buffer && isSolid(tile.buffer) ? tile.buffer : null;

    var bbox = bboxes[z];
    if (!bbox) return;
    if (y >= bbox.minY) {
        if (x >= bbox.minX) array.unshift(new Tile(z, x, y, b));
        if (x + 1 <= bbox.maxX) array.unshift(new Tile(z, x + 1, y, b));
    }
    if (y + 1 <= bbox.maxY) {
        if (x >= bbox.minX) array.unshift(new Tile(z, x, y + 1, b));
        if (x + 1 <= bbox.maxX) array.unshift(new Tile(z, x + 1, y + 1, b));
    }
}

function sumChildren(tile, bboxes) {
    var sum = 0;
    var size = 1;
    for (var x = tile.x, y = tile.y, z = tile.z + 1; bboxes[z]; z++) {
        x *= 2; y *= 2; size *= 2;
        var width = Math.min(bboxes[z].maxX, x + size - 1) - Math.max(bboxes[z].minX, x) + 1;
        var height = Math.min(bboxes[z].maxY, y + size - 1) - Math.max(bboxes[z].minY, y) + 1;
        sum += width * height;
    }
    return sum;
}

function isEmpty(buffer) {
    return buffer.solid && buffer.solid.split(',')[3] === '0';
}

function isSolid(buffer) {
    return buffer.solid && buffer.solid.split(',')[3] !== '0';
}

// Helper utility for _read functions. Pass your stream object and a
// getter that can be called concurrently and it will concurrently
// call your getter behind the scenes and manage the endstate of the
// stream.
function multiread(stream, get) {
    if (stream._multiread === undefined) {
        stream._multiread = stream._multiread || [];
        stream._multireading = stream._multireading || 0;
        stream._multireadmax = stream._multireadmax || concurrency;
    }
    if (stream._multiread.length) {
        push();
    } else {
        stream.once('_push', push);
    }
    while ((stream._multiread.length + stream._multireading) < stream._multireadmax) {
        stream._multireading++;
        if (!get(done)) break;
    }

    function done(item) {
        stream._multireading--;
        if (item === null && !stream._multireading) {
            stream.emit('_push');
        } else if (item) {
            stream._multiread.push(item);
            stream.emit('_push');
        }
    }

    function push() {
        if (stream._multiread.length) {
            stream.push(stream._multiread.shift());
        } else {
            stream.push(null);
        }
    }
}

function multiwrite(stream, callback, put) {
    if (stream._multiwrite === undefined) {
        stream._multiwrite = stream._multiwrite || [];
        stream._multiwriting = stream._multiwriting || 0;
        stream._multiwritemax = stream._multiwritemax || concurrency;
    }
    stream._multiwriting++;
    if (stream._multiwriting < stream._multiwritemax) {
        callback();
    } else {
        stream.once('_write', callback);
    }

    put(function(err) {
        stream._multiwriting--;
        if (err) stream.emit('error', err);
        stream.emit('_write');
        if (!stream._multiwriting) stream.emit('_writeEmpty');
    });
}

function setConcurrency(c) {
    concurrency = c;
}
<|endoftext|>


<commit_before>"use strict";

var VALID_HOSTNAME_VALUE = 0;

function minIndex(a, b) {
  if (a === null) return b;
  if (b === null) return a;
  return a < b ? a : b;
}

function insertInTrie(rule, trie) {
  var parts = rule.parts;
  var node = trie;

  for (var i = 0; i < parts.length; i++) {
    var part = parts[i];
    var nextNode = node[part];
    if (nextNode === undefined) {
      nextNode = Object.create(null);
      node[part] = nextNode;
    }

    node = nextNode;
  }

  node.$ = VALID_HOSTNAME_VALUE;

  return trie;
}

function lookupInTrie(parts, trie, index) {
  var part;
  var nextNode;
  var publicSuffixIndex = null;

  if (trie === undefined) {
    return null;
  }

  // We have a match
  if (trie.$ !== undefined) {
    publicSuffixIndex = index + 1;
  }

  if (index === -1) {
    return publicSuffixIndex;
  }

  // Check branch corresponding to next part of hostname
  part = parts[index];
  nextNode = trie[part];
  if (nextNode !== undefined) {
    publicSuffixIndex = minIndex(
      publicSuffixIndex,
      lookupInTrie(parts, nextNode, index - 1)
    );
  }

  // Check wildcard
  nextNode = trie['*'];
  if (nextNode !== undefined) {
    publicSuffixIndex = minIndex(
      publicSuffixIndex,
      lookupInTrie(parts, nextNode, index - 1)
    );
  }

  return publicSuffixIndex;
}

function SuffixTrie(rules) {
  this.exceptions = Object.create(null);
  this.rules = Object.create(null);

  (rules || []).forEach(function (rule) {
    if (rule.exception) {
      insertInTrie(rule, this.exceptions);
    } else {
      insertInTrie(rule, this.rules);
    }
  }.bind(this));
}

SuffixTrie.fromJson = function (json) {
  var trie = new SuffixTrie();

  trie.exceptions = json.exceptions;
  trie.rules = json.rules;

  return trie;
};

SuffixTrie.prototype.hasTld = function (value) {
  return this.rules[value] !== undefined;
};

SuffixTrie.prototype.suffixLookup = function (hostname) {
  var publicSuffix = null;
  var parts = hostname.split('.');
  var publicSuffixIndex = lookupInTrie(parts, this.exceptions, parts.length - 1);

  if (publicSuffixIndex !== null) {
    // TODO - could be done from `hostname` directly with a substring.
    publicSuffix = parts.slice(publicSuffixIndex + 1).join('.');
  } else {
    publicSuffixIndex = lookupInTrie(parts, this.rules, parts.length - 1);
    if (publicSuffixIndex === null) {
      return null;
    }

    publicSuffix = parts.slice(publicSuffixIndex).join('.');
  }

  return publicSuffix;
};

SuffixTrie.prototype.lookup = function (hostname) {
  var candidate = this.suffixLookup(hostname);

  if (candidate !== hostname) {
    return null;
  }

  return candidate;
};

SuffixTrie.prototype.has = function (hostname) {
  return this.lookup(hostname) !== null;
};

module.exports = SuffixTrie;
<commit_msg>trie lookup: check exceptions only if we have a normal match<commit_after>"use strict";

var VALID_HOSTNAME_VALUE = 0;

function minIndex(a, b) {
  if (a === null) return b;
  if (b === null) return a;
  return a < b ? a : b;
}

function insertInTrie(rule, trie) {
  var parts = rule.parts;
  var node = trie;

  for (var i = 0; i < parts.length; i++) {
    var part = parts[i];
    var nextNode = node[part];
    if (nextNode === undefined) {
      nextNode = Object.create(null);
      node[part] = nextNode;
    }

    node = nextNode;
  }

  node.$ = VALID_HOSTNAME_VALUE;

  return trie;
}

function lookupInTrie(parts, trie, index) {
  var part;
  var nextNode;
  var publicSuffixIndex = null;

  if (trie === undefined) {
    return null;
  }

  // We have a match
  if (trie.$ !== undefined) {
    publicSuffixIndex = index + 1;
  }

  if (index === -1) {
    return publicSuffixIndex;
  }

  // Check branch corresponding to next part of hostname
  part = parts[index];
  nextNode = trie[part];
  if (nextNode !== undefined) {
    publicSuffixIndex = minIndex(
      publicSuffixIndex,
      lookupInTrie(parts, nextNode, index - 1)
    );
  }

  // Check wildcard
  nextNode = trie['*'];
  if (nextNode !== undefined) {
    publicSuffixIndex = minIndex(
      publicSuffixIndex,
      lookupInTrie(parts, nextNode, index - 1)
    );
  }

  return publicSuffixIndex;
}

function SuffixTrie(rules) {
  this.exceptions = Object.create(null);
  this.rules = Object.create(null);

  (rules || []).forEach(function (rule) {
    if (rule.exception) {
      insertInTrie(rule, this.exceptions);
    } else {
      insertInTrie(rule, this.rules);
    }
  }.bind(this));
}

SuffixTrie.fromJson = function (json) {
  var trie = new SuffixTrie();

  trie.exceptions = json.exceptions;
  trie.rules = json.rules;

  return trie;
};

SuffixTrie.prototype.hasTld = function (value) {
  return this.rules[value] !== undefined;
};

SuffixTrie.prototype.suffixLookup = function (hostname) {
  var publicSuffix = null;
  var parts = hostname.split('.');

  // Look for a match in rules
  publicSuffixIndex = lookupInTrie(
    parts,
    this.rules,
    parts.length - 1
  );

  if (publicSuffixIndex === null) {
    return null;
  }

  publicSuffix = parts.slice(publicSuffixIndex).join('.');

  // Look for exceptions
  var publicSuffixIndex = lookupInTrie(
    parts,
    this.exceptions,
    parts.length - 1
  );

  if (publicSuffixIndex !== null) {
    publicSuffix = parts.slice(publicSuffixIndex + 1).join('.');
  }

  return publicSuffix;
};

SuffixTrie.prototype.lookup = function (hostname) {
  var candidate = this.suffixLookup(hostname);

  if (candidate !== hostname) {
    return null;
  }

  return candidate;
};

SuffixTrie.prototype.has = function (hostname) {
  return this.lookup(hostname) !== null;
};

module.exports = SuffixTrie;
<|endoftext|>


<commit_before>/*
*   editorPlain
*   author: ronglin
*   create date: 2012.3.2
*/

(function (ctx, $) {

    var editorPlain = function (config) {
        editorPlain.superclass.constructor.call(this, config);
    };

    ctx.extend(editorPlain, ctx.editor, {

        richText: false, _plainBlur: null, _plainPaste: null, _plainKeydown: null, _timeoutId: null,

        initialize: function () {
            var self = this;
            editorPlain.superclass.initialize.call(this);
            this.el.addClass("kb-editor-hl");
            //this.Sniffer.destroy();
            //// events
            this.el.blur(this._plainBlur = function () { self.stripHtml(false); });
            if (this.el.get(0).onpaste === null) { // test if support paste event
                this.el.bind('paste', self._plainPaste = function () {
                    self.stripHtml();
                });
            }
            this.el.keydown(self._plainKeydown = function (ev) {
                var keyCode = ev.keyCode;
                if (ev.ctrlKey) {
                    if (keyCode === 65 || // ctrl+a
                        keyCode === 67 || // ctrl+c
                        keyCode === 88 || // ctrl+x
                        keyCode === 89 || // ctrl+y
                        keyCode === 90) { // ctrl+z
                        // do default
                    } else if (keyCode === 86) { // ctrl+v
                        if (self._plainPaste === null) {
                            self.stripHtml();
                        }
                    } else {
                        // prevent some browser default comments.
                        // for example: prevent ctrl+b to set bold style to text.
                        ev.preventDefault();
                    }
                }
                if (ev.shiftKey) {
                    if (keyCode === 45) { // shift+insert
                        if (self._plainPaste === null) {
                            self.stripHtml();
                        }
                    }
                }
            });
        },
        getSelector: function () {
            return this.el.get(0).tagName + '.kb-editor-on';
        },
        buildEditor: function (selector) {
            var self = this;
            tinymce.init({
                selector: selector,
                plugins: [
                    "exit"
                ],
                inline: true,
                menubar: false,
                force_p_newlines: false,
                forced_root_block: false,
		verify_html: false,
                toolbar_items_size: 'small',
                toolbar: "save exit | undo redo |",
		setup:function(ed){
		     tinymce.ui.FloatPanel.zIndex=0x7FFFFFFF;
		},
                init_instance_callback: function (ed) {
                    self.editorInstance = ed;
                    setTimeout(function () {
                        ed.focus();
                        ed.off('blur');
                    }, 500);
                },
                exit_onsavecallback: function (ed) {
		    self.onSave && self.onSave();
        	    self.stripHtml(false);
                },
                exit_onbeforeexit: function (ed) {
		    setTimeout(function(){
                       self.onCancel && self.onCancel();
                       self._onBeforeExit();
		    },100);
                }
            });
        },

        stripHtml: function (timeout) {
            clearTimeout(this._timeoutId);
            if (timeout === false) {
                this.el.text(this.el.text());
            } else {
                var self = this;
                this._timeoutId = setTimeout(function () {
                    self.el.text(self.el.text());
                }, 0);
            }
        },

        //_firstFocus: function () {
        //    // override with a empty implement
        //},

        //_unifyInputs: function (ev) {
        //    // enter
        //    if (ev.which == 13) {
        //        return false;
        //    }
        //    // tab
        //    if (ev.which == 9) {
        //        this.pasteHtml('    ');
        //        return false;
        //    }
        //},

        getHtml: function () {
            return this.el.text();
        },

        setHtml: function (str) {
            this.el.text(str);
        },

        remove: function () {
            editorPlain.superclass.remove.call(this);
            if (this._plainBlur) { this.el.unbind('blur', this._plainBlur); }
            if (this._plainPaste) { this.el.unbind('paste', this._plainPaste); }
            if (this._plainKeydown) { this.el.unbind('keydown', this._plainKeydown); }
        }

    });

    // register
    ctx.editorPlain = editorPlain;

})(yardi, jQuery);
<commit_msg>Edit html code in label.<commit_after>/*
*   editorPlain
*   author: ronglin
*   create date: 2012.3.2
*/

(function (ctx, $) {

    var editorPlain = function (config) {
        editorPlain.superclass.constructor.call(this, config);
    };

    ctx.extend(editorPlain, ctx.editor, {

        richText: false, _plainBlur: null, _plainPaste: null, _plainKeydown: null, _timeoutId: null,

        initialize: function () {
            var self = this;
            editorPlain.superclass.initialize.call(this);
            this.el.addClass("kb-editor-hl");
            //this.Sniffer.destroy();
            //// events
            /*this.el.blur(this._plainBlur = function () { self.stripHtml(false); });
            if (this.el.get(0).onpaste === null) { // test if support paste event
                this.el.bind('paste', self._plainPaste = function () {
                    self.stripHtml();
                });
            }*/
            this.el.keydown(self._plainKeydown = function (ev) {
                var keyCode = ev.keyCode;
                if (ev.ctrlKey) {
                    if (keyCode === 65 || // ctrl+a
                        keyCode === 67 || // ctrl+c
                        keyCode === 88 || // ctrl+x
                        keyCode === 89 || // ctrl+y
                        keyCode === 90) { // ctrl+z
                        // do default
                    } else if (keyCode === 86) { // ctrl+v
                        /*if (self._plainPaste === null) {
                            self.stripHtml();
                        }*/
                    } else {
                        // prevent some browser default comments.
                        // for example: prevent ctrl+b to set bold style to text.
                        ev.preventDefault();
                    }
                }
                if (ev.shiftKey) {
                    if (keyCode === 45) { // shift+insert
                        /*if (self._plainPaste === null) {
                            self.stripHtml();
                        }*/
                    }
                }
            });
        },
        getSelector: function () {
            return this.el.get(0).tagName + '.kb-editor-on';
        },
        buildEditor: function (selector) {
            var self = this;
            tinymce.init({
                selector: selector,
                plugins: [
                    "exit"
                ],
                inline: true,
                menubar: false,
                force_p_newlines: false,
                forced_root_block: false,
                toolbar_items_size: 'small',
                toolbar: "save exit | undo redo |",
                init_instance_callback: function (ed) {
                    self.editorInstance = ed;
                    setTimeout(function () {
                        ed.focus();
                        ed.off('blur');
                    }, 500);
                },
                exit_onsavecallback: function (ed) {
                    self.onSave && self.onSave();
                    //self.stripHtml(false);
                },
                exit_onbeforeexit: function (ed) {
                    setTimeout(function () {
                        self.onCancel && self.onCancel();
                        self._onBeforeExit();
                    }, 100);
                }
            });
        },

        stripHtml: function (timeout) {
            clearTimeout(this._timeoutId);
            if (timeout === false) {
                this.el.text(this.el.text());
            } else {
                var self = this;
                this._timeoutId = setTimeout(function () {
                    self.el.text(self.el.text());
                }, 0);
            }
        },

        //_firstFocus: function () {
        //    // override with a empty implement
        //},

        //_unifyInputs: function (ev) {
        //    // enter
        //    if (ev.which == 13) {
        //        return false;
        //    }
        //    // tab
        //    if (ev.which == 9) {
        //        this.pasteHtml('    ');
        //        return false;
        //    }
        //},

        getHtml: function () {
            return this.el.html();//text();
        },

        setHtml: function (str) {
            this.el.html(str);//text(str);
        },

        remove: function () {
            editorPlain.superclass.remove.call(this);
            if (this._plainBlur) { this.el.unbind('blur', this._plainBlur); }
            if (this._plainPaste) { this.el.unbind('paste', this._plainPaste); }
            if (this._plainKeydown) { this.el.unbind('keydown', this._plainKeydown); }
        }

    });

    // register
    ctx.editorPlain = editorPlain;

})(yardi, jQuery);
<|endoftext|>


<commit_before>/*
 * cookie.js
 * by Garrett Smith
 * Loosely based on:
 * Cookie API v1.0
 * http://www.dithered.com/javascript/cookies/index.html
 * maintained by Chris Nott (chris@NOSPAMdithered.com - remove NOSPAM)
 */

function setPageCookie(name, value) {
	document.cookie = name + "=" + escape(value) + "; path=" + getPath();
}

function getCookie(name) {
	var dc = document.cookie;

	var prefix = name + "=";
	var begin = dc.lastIndexOf(prefix);

	if (begin == -1)
		return null;

	var end = dc.indexOf(";", begin);

	if (end == -1)
		end = dc.length;

	return unescape(dc.substring(begin + prefix.length, end));
}

function deletePageCookie(name, path) {
	var value = getCookie(name);

	if (value != null)
		document.cookie = name + "=" + "; path=" + getPath() + "; expires=Thu, 01-Jan-70 00:00:01 GMT";

	return value;
}

function getFilename() {
	var href = window.location.href;

	var file = href.substring(href.lastIndexOf("/") + 1);
	return file;
}

function getPath() {
	var href = window.location.href;

	var path = href.substring(href.indexOf("//") + 2);
	path = path.substring(path.indexOf("/"));
	path = path.substring(0, path.lastIndexOf("/") + 1);
	return path;
}<commit_msg>updated cookie.js to 1.0.1 from http://www.dithered.com/javascript/cookies/index.html<commit_after>// Cookie API  v1.0.1
// documentation: http://www.dithered.com/javascript/cookies/index.html
// license: http://creativecommons.org/licenses/by/1.0/
// code (mostly) by Chris Nott (chris[at]dithered[dot]com)

// Write a cookie value
function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + '=' + escape(value) + ((expires) ? '; expires=' + expires.toGMTString() : '') + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '') + ((secure) ? '; secure' : '');
	document.cookie = curCookie;
}

// Retrieve a named cookie value
function getCookie(name) {
	var dc = document.cookie;

	// find beginning of cookie value in document.cookie
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	}
	else begin += 2;

	// find end of cookie value
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) end = dc.length;

	// return cookie value
	return unescape(dc.substring(begin + prefix.length, end));
}

// Delete a named cookie value
function deleteCookie(name, path, domain) {
	var value = getCookie(name);
	if (value != null) document.cookie = name + '=' + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '') + '; expires=Thu, 01-Jan-70 00:00:01 GMT';
	return value;
}

// Fix Netscape 2.x Date bug
function fixDate(date) {
	var workingDate = date;
	var base = new Date(0);
	var skew = base.getTime();
	if (skew > 0) workingDate.setTime(workingDate.getTime() - skew);
	return workingDate;
}

// Test for cookie support
function supportsCookies(rootPath) {
	setCookie('checking_for_cookie_support', 'testing123', '', (rootPath != null ? rootPath : ''));
	if (getCookie('checking_for_cookie_support')) return true;
	else return false;
}<|endoftext|>


<commit_before>'use strict'

const
  Task = require('../Task'),
  Make = require('./Make'),
  chalk = require('chalk'),
  helpers = require('../helpers'),
  path = require('path'),
  cluster = require('cluster'),
  chokidar = require('chokidar')

/**
 * Watch the source file to run a Make command anytime there's a change
 */
class Watch extends Task {
  run(opt) {

    // main process
    if (cluster.isMaster && opt.isCli) {
      // from here we will spawn subprocesses
      // being sure that calls to process.exit coming from the js or css parsers
      // will not kill watch
      cluster.on('exit', () => cluster.fork({ isFirstFork: false }))
      cluster.fork({ isFirstFork: true  })
    } else {

      // subprocess that will be managed via the main process

      var
        glob = opt.flow[0] === 'f' ?
          opt.from :
          path.join(opt.from, '**/*.'+opt.ext),
        // the first subprocess must be detected
        isFirstFork = process.env.isFirstFork === 'true',
        watcher = chokidar.watch(glob, { ignoreInitial: !isFirstFork })

      watcher
        .on('ready', () => {
          helpers.log(
            chalk.cyan(
              isFirstFork ?
                `Watching: ${helpers.toRelative(glob)}` :
                `Process resumed! Watching: ${helpers.toRelative(glob)}`
            )
          )
        })
        .on('all', helpers.debounce(() => new Make(opt), 100))

      return watcher

    }

  }
}

module.exports = Watch<commit_msg>fixes #34<commit_after>'use strict'

const
  Task = require('../Task'),
  Make = require('./Make'),
  chalk = require('chalk'),
  helpers = require('../helpers'),
  path = require('path'),
  cluster = require('cluster'),
  chokidar = require('chokidar')

/**
 * Watch the source file to run a Make command anytime there's a change
 */
class Watch extends Task {
  run(opt) {

    // main process
    if (cluster.isMaster && opt.isCli) {
      // from here we will spawn subprocesses
      // being sure that calls to process.exit coming from the js or css parsers
      // will not kill watch
      cluster.on('exit', () => cluster.fork({ isFirstFork: false }))
      cluster.fork({ isFirstFork: true  })
    } else {

      // subprocess that will be managed via the main process

      var
        glob = opt.flow[0] === 'f' ?
          opt.from :
          path.join(opt.from, '**/*.'+opt.ext),
        // the first subprocess must be detected
        isFirstFork = process.env.isFirstFork === 'true',
        watcher = chokidar.watch(glob, {
          ignoreInitial: !isFirstFork,
          cwd: process.cwd()
        })

      watcher
        .on('ready', () => {
          helpers.log(
            chalk.cyan(
              isFirstFork ?
                `Watching: ${helpers.toRelative(glob)}` :
                `Process resumed! Watching: ${helpers.toRelative(glob)}`
            )
          )
        })
        .on('all', helpers.debounce(() => new Make(opt), 100))

      return watcher

    }

  }
}

module.exports = Watch<|endoftext|>