<commit_before>#!/usr/bin/env node

'use strict';

// stdlib
var fs    = require('fs');
var path  = require('path');

// 3rd-party
var ArgumentParser = require('argparse').ArgumentParser;

// internal
var Mincer      = require('..');
var shellwords  = require('../lib/mincer/common').shellwords;

////////////////////////////////////////////////////////////////////////////////

var cli = new ArgumentParser({
  prog:     'mincer',
  version:  require('../package.json').version,
  addHelp:  true
});

cli.addArgument(['--noenv'], {
  help:         'Disables .mincerrc file',
  action:       'storeTrue'
});

cli.addArgument(['-I', '--include'], {
  help:         'Adds the directory to the Mincer load path',
  metavar:      'DIRECTORY',
  action:       'append',
  required:     true
});

cli.addArgument(['-o', '--output'], {
  help:         'Copy provided assets into DIRECTORY',
  metavar:      'DIRECTORY'
});

cli.addArgument(['filenames'], {
  help:         'File(s) to process',
  metavar:      'FILE',
  nargs:        '+'
});

////////////////////////////////////////////////////////////////////////////////

if (-1 === process.argv.indexOf('--noenv')) {
  if (path.existsSync('./.mincerrc')) {
    var rcflags = shellwords(fs.readFileSync('./.mincerrc', 'utf8'));
    [].splice.apply(process.argv, [2, 0].concat(rcflags));
  }
}

var args        = cli.parseArgs();
var environment = new Mincer.Environment(process.cwd());
var filenames   = [];

(process.env.MINCER_PATH || '').split(':').forEach(function (path) {
  if (path) {
    environment.appendPath(path);
  }
});

args.include.forEach(function (path) {
  environment.appendPath(path);
});

args.filenames.forEach(function (file) {
  filenames.push(path.normalize(file));
});

////////////////////////////////////////////////////////////////////////////////

//
// Configure Mincer logger
//

Mincer.logger.use(console);

//
// Compiling manifest with bunch of files
//

if (args.output) {
  var manifest = new Mincer.Manifest(environment, args.output);
  manifest.compile(filenames, function (err) {
    if (err) {
      console.error(err);
      process.exit(1);
    }
  });
  return;
}

if (1 === filenames.length) {
  var asset = environment.findAsset(filenames[0]);

  if (!asset) {
    console.error("Cannot find logical path: " + filenames[0]);
    process.exit(1);
  }

  asset.compile(function (err) {
    if (err) {
      console.error(err);
      process.exit(1);
    }

    process.stdout.write(asset.toString());
  });
  return;
}

console.error("Only one file can be compiled to stdout at a time");
process.exit(1);
<commit_msg>[fix] path.existsSync was moved to fs.existsSync<commit_after>#!/usr/bin/env node

'use strict';

// stdlib
var fs    = require('fs');
var path  = require('path');

// 3rd-party
var ArgumentParser = require('argparse').ArgumentParser;

// internal
var Mincer      = require('..');
var shellwords  = require('../lib/mincer/common').shellwords;

////////////////////////////////////////////////////////////////////////////////

var cli = new ArgumentParser({
  prog:     'mincer',
  version:  require('../package.json').version,
  addHelp:  true
});

cli.addArgument(['--noenv'], {
  help:         'Disables .mincerrc file',
  action:       'storeTrue'
});

cli.addArgument(['-I', '--include'], {
  help:         'Adds the directory to the Mincer load path',
  metavar:      'DIRECTORY',
  action:       'append',
  required:     true
});

cli.addArgument(['-o', '--output'], {
  help:         'Copy provided assets into DIRECTORY',
  metavar:      'DIRECTORY'
});

cli.addArgument(['filenames'], {
  help:         'File(s) to process',
  metavar:      'FILE',
  nargs:        '+'
});

////////////////////////////////////////////////////////////////////////////////

if (-1 === process.argv.indexOf('--noenv')) {
  if (fs.existsSync('./.mincerrc')) {
    var rcflags = shellwords(fs.readFileSync('./.mincerrc', 'utf8'));
    [].splice.apply(process.argv, [2, 0].concat(rcflags));
  }
}

var args        = cli.parseArgs();
var environment = new Mincer.Environment(process.cwd());
var filenames   = [];

(process.env.MINCER_PATH || '').split(':').forEach(function (path) {
  if (path) {
    environment.appendPath(path);
  }
});

args.include.forEach(function (path) {
  environment.appendPath(path);
});

args.filenames.forEach(function (file) {
  filenames.push(path.normalize(file));
});

////////////////////////////////////////////////////////////////////////////////

//
// Configure Mincer logger
//

Mincer.logger.use(console);

//
// Compiling manifest with bunch of files
//

if (args.output) {
  var manifest = new Mincer.Manifest(environment, args.output);
  manifest.compile(filenames, function (err) {
    if (err) {
      console.error(err);
      process.exit(1);
    }
  });
  return;
}

if (1 === filenames.length) {
  var asset = environment.findAsset(filenames[0]);

  if (!asset) {
    console.error("Cannot find logical path: " + filenames[0]);
    process.exit(1);
  }

  asset.compile(function (err) {
    if (err) {
      console.error(err);
      process.exit(1);
    }

    process.stdout.write(asset.toString());
  });
  return;
}

console.error("Only one file can be compiled to stdout at a time");
process.exit(1);
<|endoftext|>


<commit_before>// Sample app
var express = require('express');
var expressValidator = require('../../index');

var app = null;

function App(port, validation) {
  this.app = null;
  this.port = port;
  this.validation = validation;
}
module.exports = App;

App.prototype.start = function() {
  var self = this;
  self.app = express.createServer();

  self.app.use(express.bodyParser());
  self.app.use(expressValidator);

  function testAction(req, res) {
    var errors = [];
    req.onValidationError(function(msg) {
      errors.push(msg);
      return this;
    });

    self.validation(req, res, errors);
  }
  self.app.get('/:testparam?', testAction);
  self.app.post('/:testparam?', testAction);

  self.app.listen(this.port);
};

App.prototype.stop = function() {
  this.app.close();
};
<commit_msg>Remove unused variable<commit_after>// Sample app
var express = require('express');
var expressValidator = require('../../index');

function App(port, validation) {
  this.app = null;
  this.port = port;
  this.validation = validation;
}
module.exports = App;

App.prototype.start = function() {
  var self = this;
  self.app = express.createServer();

  self.app.use(express.bodyParser());
  self.app.use(expressValidator);

  function testAction(req, res) {
    var errors = [];
    req.onValidationError(function(msg) {
      errors.push(msg);
      return this;
    });

    self.validation(req, res, errors);
  }
  self.app.get('/:testparam?', testAction);
  self.app.post('/:testparam?', testAction);

  self.app.listen(this.port);
};

App.prototype.stop = function() {
  this.app.close();
};
<|endoftext|>


<commit_before><commit_msg>global.IE implementation.<commit_after>/*jshint camelcase:true, curly:true, eqeqeq:true, immed:true, indent:2, latedef:true, newcap:true, noarg:true, noempty:true, nonew:true, quotmark:single, undef:true, unused:true, strict:true, trailing:true */

(function (global, undefined) {
  'use strict';

  var IE;
  var IEInfo = (/(msie) ([\w.]+)/i).exec(global.navigator.userAgent);

  if (IEInfo) {
    IE = {
      valueOf : function () {
        return parseInt(IEInfo && IEInfo[2], 10) || undefined;
      }
    };
  }

  global.IE = IE;

}(this));<|endoftext|>


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

    angular
        .module('dpShared')
        .component('dpLink', {
            templateUrl: 'modules/shared/components/link/link.html',
            transclude: true,
            bindings: {
                className: '@',
                inline: '@',
                hoverText: '@',
                type: '@',
                payload: '<'
            },
            controller: DpLinkController,
            controllerAs: 'vm'
        });

    DpLinkController.$inject = ['$scope', 'store', 'ACTIONS', 'applicationState'];

    function DpLinkController ($scope, store, ACTIONS, applicationState) {
        const vm = this;

        const BUTTON = 'button',
            LINK = 'a';

        vm.className = vm.className || 'o-btn o-btn--link';
        vm.inline = vm.inline || false;

        $scope.$watch('vm.payload', function () {
            vm.tagName = getTagName(vm.type, vm.payload);
        });

        vm.dispatch = function () {
            store.dispatch(getAction(vm.type, vm.payload));
        };

        function getAction (type, payload) {
            const action = {
                type: ACTIONS[type] || type
            };
            if (angular.isDefined(payload)) {
                action.payload = payload;
            }
            return action;
        }

        function getTagName (type, payload) {
            if (ACTIONS[type] && ACTIONS[type].isButton) {
                return BUTTON;
            } else {
                vm.href = getHref(type, payload);
                // Do not catch a click event and handle the state change
                // internally, this prevents users from CTRL/CMD clicking!
                return LINK;
            }
        }

        function getHref (type, payload) {
            // Remove state properties that do not relate to the url
            // by converting the state to a url and back
            // This prevents deep copying of large state objects in the reducer (eg dataSelection.markers)
            const reducer = applicationState.getReducer(),
                state = applicationState.getStore().getState(),
                params = applicationState.getStateUrlConverter().state2params(state),
                sourceState = applicationState.getStateUrlConverter().params2state({}, params),
                targetState = reducer(sourceState, getAction(type, payload));

            return applicationState.getStateUrlConverter().state2url(targetState);
        }
    }
})();
<commit_msg>Add fix for url's in dp-link not updating<commit_after>(function () {
    'use strict';

    angular
        .module('dpShared')
        .component('dpLink', {
            templateUrl: 'modules/shared/components/link/link.html',
            transclude: true,
            bindings: {
                className: '@',
                inline: '@',
                hoverText: '@',
                type: '@',
                payload: '<'
            },
            controller: DpLinkController,
            controllerAs: 'vm'
        });

    DpLinkController.$inject = ['$scope', 'store', 'ACTIONS', 'applicationState', '$location'];

    function DpLinkController ($scope, store, ACTIONS, applicationState, $location) {
        const vm = this;
        vm.activeUrl = $location.url();

        const BUTTON = 'button',
            LINK = 'a';

        vm.className = vm.className || 'o-btn o-btn--link';
        vm.inline = vm.inline || false;

        $scope.$watch('vm.payload', function () {
            vm.tagName = getTagName(vm.type, vm.payload);
        });

        vm.dispatch = function () {
            store.dispatch(getAction(vm.type, vm.payload));
        };

        applicationState.getStore().subscribe(() => {
            const currentUrl = $location.url();
            if (currentUrl !== vm.activeUrl) {
                vm.href = getHref(vm.type, vm.payload);
                vm.activeUrl = currentUrl;
            }
        });

        function getAction (type, payload) {
            const action = {
                type: ACTIONS[type] || type
            };
            if (angular.isDefined(payload)) {
                action.payload = payload;
            }
            return action;
        }

        function getTagName (type, payload) {
            if (ACTIONS[type] && ACTIONS[type].isButton) {
                return BUTTON;
            } else {
                vm.href = getHref(type, payload);
                // Do not catch a click event and handle the state change
                // internally, this prevents users from CTRL/CMD clicking!
                return LINK;
            }
        }

        function getHref (type, payload) {
            // Remove state properties that do not relate to the url
            // by converting the state to a url and back
            // This prevents deep copying of large state objects in the reducer (eg dataSelection.markers)
            const reducer = applicationState.getReducer(),
                state = applicationState.getStore().getState(),
                params = applicationState.getStateUrlConverter().state2params(state),
                sourceState = applicationState.getStateUrlConverter().params2state({}, params),
                targetState = reducer(sourceState, getAction(type, payload));

            return applicationState.getStateUrlConverter().state2url(targetState);
        }
    }
})();
<|endoftext|>


<commit_before>#!/usr/bin/env node

/* global Config, Log */
'use strict';

const args = require('yargs')
  .usage('Usage: $0 [args]')
  .option('c', {
    alias: 'config',
    describe: 'Load configuration from file',
    type: 'string'
  })
  .help('help')
  .argv;

const express = require('express');
const http = require('http');
const Path = require('path');

// Load nconf into the global namespace
global.Config = require('nconf')
    .env()
    .argv();
if (args.c) {
  global.Config.file(Path.resolve(process.cwd(), args.c));
}
global.Config.defaults(require('../config/defaults.json'));

global.Log = require('../lib/logger').attach(global.Config);
const PluginManager = require('../lib/plugin-manager');

const host = Config.get('service:hostname');
const port = Config.get('service:port');
const app = express();
const server = http.createServer(app);
const storage = new (require('../lib/storage'))();
const manager = new PluginManager(storage);

manager.on('error', (err) => {
  Log.error(err);
});

server.on('error', (err) => {
  Log.error(err);
});

manager.initialize();

require('../lib/control/v1/core').attach(app, storage, manager);
require('../lib/control/v1/conqueso').attach(app, storage);

server.listen(port, host, () => {
  Log.info(`Listening on ${host}:${port}`);
});
<commit_msg>Registered middleware with express app. Restructured server.js slightly so that it's easier to visually parse. Resolves #98.<commit_after>#!/usr/bin/env node

/* global Config, Log */
'use strict';

const args = require('yargs')
  .usage('Usage: $0 [args]')
  .option('c', {
    alias: 'config',
    describe: 'Load configuration from file',
    type: 'string'
  })
  .help('help')
  .argv;

const express = require('express');
const http = require('http');
const Path = require('path');
const Logger = require('../lib/logger');
const app = express();

// Load nconf into the global namespace
global.Config = require('nconf')
    .env()
    .argv();

if (args.c) {
  global.Config.file(Path.resolve(process.cwd(), args.c));
}
global.Config.defaults(require('../config/defaults.json'));

// Set up logging
global.Log = Logger.attach(global.Config);

// Add request logging middleware
app.use(Logger.logRequests({write: (message) => global.Log.info(message)}));

// Initialize the Plugin Manager and storage layer
const PluginManager = require('../lib/plugin-manager');
const storage = new (require('../lib/storage'))();
const manager = new PluginManager(storage, {});

manager.on('error', (err) => global.Log.error(err));
manager.initialize();

// Register endpoints
require('../lib/control/v1/core').attach(app, storage, manager);
require('../lib/control/v1/conqueso').attach(app, storage);

// Instantiate server and start it
const host = Config.get('service:hostname');
const port = Config.get('service:port');
const server = http.createServer(app);

server.on('error', (err) => global.Log.error(err));

server.listen(port, host, () => {
  Log.info(`Listening on ${host}:${port}`);
});
<|endoftext|>


<commit_before>var test = require('tape');
var sync = require('../');
var modelStub = require('./helpers/modelStub');
var Model = require('ampersand-model');

var ImInBrowser = (typeof window !== 'undefined');

test('should get a response for read', function (t) {
    t.plan(2);
    var Me = Model.extend({
        url: 'http://www.mocky.io/v2/54f1d2b932d8370a036e5b21',
        ajaxConfig: {
            useXDR: true
        },
        props: {
            foo: 'string'
        },
        sync: sync //override with this sync, so fetch doesn't use the stable one from dependencies
    });
    var m = new Me();
    m.on('change', function () {
        //TODO: assert more arguments
        t.equal(m.foo, 'bar');
    });
    m.fetch({
        success: function (data) {
            //TODO: assert more arguments
            t.equal(data.foo, 'bar');
            t.end();
        },
        error: function () {
            t.fail('error while fetching (are you offline?)');
            t.end();
        }
    });
});

if (ImInBrowser && (typeof XDomainRequest !== 'undefined')) {
    test('should not parse body when not expecting JSON', function (t) {
        t.plan(1);
        var Me = Model.extend({
            url: 'http://www.mocky.io/v2/54f1d2b932d8370a036e5b21',
            ajaxConfig: {
                useXDR: true,
                headers: {
                    accept: 'application/xml'
                }
            }
        });
        var m = new Me();
        //not calling fetch, as model also gives parsing JSON a try apparently
        sync('read', m, {
            success: function (data) {
                t.equal(typeof data, 'string');
                t.end();
            },
            error: function () {
                t.fail('error while fetching (are you offline?)');
                t.end();
            }
        });
    });
}

test('should call error when read results in 404', function (t) {
    t.plan(1);
    var Me = Model.extend({
        url: '/nothing',
        sync: sync
    });
    var m = new Me();
    m.fetch({
        success: function () {
            t.fail('unexpected success call');
            t.end();
        },
        error: function () {
            t.pass('received an expected error');
            t.end();
        }
    });
});

if (ImInBrowser) {
    test('should call user provided beforeSend function. (when in the browser)', function (t) {
        t.plan(1);
        var xhr = sync('delete', modelStub(), {
            beforeSend: function (_xhr) {
                t.pass();
            },
            emulateHTTP: true
        });
        t.end();
    });
    test('should call user provided beforeSend function from model\'s ajaxConfig when no custom xhrFields are passed.  (when in the browser)', function (t) {
        t.plan(1);

        var Me = Model.extend({
            url: '/hi',
            ajaxConfig: {
                beforeSend: function (xhr) {
                    t.pass();
                }
            }
        });

        var m = new Me();
        var xhr = sync('create', m);

        t.end();
    });
} else {
    var concatStream = require('concat-stream');

    test('should alow piping from request', function (t) {
        t.plan(1);
        var Me = Model.extend({
            url: 'http://www.mocky.io/v2/54f1d2b932d8370a036e5b21',
            ajaxConfig: {
                useXDR: true
            },
            props: {
                foo: 'string'
            },
            sync: sync //override with this sync, so fetch doesn't use the stable one from dependencies
        });
        var m = new Me();
        var requestStream = m.fetch({});
        var writable = concatStream({
            encoding: 'string'
        }, function (data) {
            t.equal(JSON.parse(data).foo, 'bar');
            t.end();
        });
        requestStream.pipe(writable);
    });

}<commit_msg>switch response parsing test to work in the right set of browsers<commit_after>var test = require('tape');
var sync = require('../');
var modelStub = require('./helpers/modelStub');
var Model = require('ampersand-model');

var ImInBrowser = (typeof window !== 'undefined');

test('should get a response for read', function (t) {
    t.plan(2);
    var Me = Model.extend({
        url: 'http://www.mocky.io/v2/54f1d2b932d8370a036e5b21',
        ajaxConfig: {
            useXDR: true
        },
        props: {
            foo: 'string'
        },
        sync: sync //override with this sync, so fetch doesn't use the stable one from dependencies
    });
    var m = new Me();
    m.on('change', function () {
        //TODO: assert more arguments
        t.equal(m.foo, 'bar');
    });
    m.fetch({
        success: function (data) {
            //TODO: assert more arguments
            t.equal(data.foo, 'bar');
            t.end();
        },
        error: function () {
            t.fail('error while fetching (are you offline?)');
            t.end();
        }
    });
});

if (ImInBrowser && (typeof XDomainRequest === 'undefined')) {
    test('should not parse body when not expecting JSON', function (t) {
        t.plan(1);
        var Me = Model.extend({
            url: 'http://www.mocky.io/v2/54f1d2b932d8370a036e5b21',
            ajaxConfig: {
                useXDR: true,
                headers: {
                    accept: 'application/xml'
                }
            }
        });
        var m = new Me();
        //not calling fetch, as model also gives parsing JSON a try apparently
        sync('read', m, {
            success: function (data) {
                t.equal(typeof data, 'string');
                t.end();
            },
            error: function () {
                t.fail('error while fetching (are you offline?)');
                t.end();
            }
        });
    });
}

test('should call error when read results in 404', function (t) {
    t.plan(1);
    var Me = Model.extend({
        url: '/nothing',
        sync: sync
    });
    var m = new Me();
    m.fetch({
        success: function () {
            t.fail('unexpected success call');
            t.end();
        },
        error: function () {
            t.pass('received an expected error');
            t.end();
        }
    });
});

if (ImInBrowser) {
    test('should call user provided beforeSend function. (when in the browser)', function (t) {
        t.plan(1);
        var xhr = sync('delete', modelStub(), {
            beforeSend: function (_xhr) {
                t.pass();
            },
            emulateHTTP: true
        });
        t.end();
    });
    test('should call user provided beforeSend function from model\'s ajaxConfig when no custom xhrFields are passed.  (when in the browser)', function (t) {
        t.plan(1);

        var Me = Model.extend({
            url: '/hi',
            ajaxConfig: {
                beforeSend: function (xhr) {
                    t.pass();
                }
            }
        });

        var m = new Me();
        var xhr = sync('create', m);

        t.end();
    });
} else {
    var concatStream = require('concat-stream');

    test('should alow piping from request', function (t) {
        t.plan(1);
        var Me = Model.extend({
            url: 'http://www.mocky.io/v2/54f1d2b932d8370a036e5b21',
            ajaxConfig: {
                useXDR: true
            },
            props: {
                foo: 'string'
            },
            sync: sync //override with this sync, so fetch doesn't use the stable one from dependencies
        });
        var m = new Me();
        var requestStream = m.fetch({});
        var writable = concatStream({
            encoding: 'string'
        }, function (data) {
            t.equal(JSON.parse(data).foo, 'bar');
            t.end();
        });
        requestStream.pipe(writable);
    });

}<|endoftext|>


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

define(function (require, exports, module) {
    "use strict";

    var AppInit = brackets.getModule("utils/AppInit"),
        ViewCommandHandlers = brackets.getModule("view/ViewCommandHandlers"),
        DropdownButton = brackets.getModule("widgets/DropdownButton").DropdownButton,
        PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
        zoomSelect = new DropdownButton("", [], function (item, index) {
            return item;
        });

    function initialization() {
        zoomSelect.$button.text(getTitleTextFromCurrentFontSize());
        zoomSelect.items = ["20 %", "50 %", "70 %", "100 %", "150 %", "200 %", "400 %"];
        zoomSelect.dropdownExtraClasses = "dropdown-status-bar";
        zoomSelect.$button.css("width", "auto");
        zoomSelect.$button.addClass("btn-status-bar");

        $(zoomSelect).on("select", function (e, value, index) {
            zoomSelect.$button.text(value);

            try {
                if (index == 0) {
                    saveFontSize("2.4px");
                } else if (index == 1) {
                    saveFontSize("6px");
                } else if (index == 2) {
                    saveFontSize("8.4px");
                } else if (index == 3) {
                    saveFontSize("12px");
                } else if (index == 4) {
                    saveFontSize("18px");
                } else if (index == 5) {
                    saveFontSize("24px");
                } else if (index == 6) {
                    saveFontSize("48px");
                }

                ViewCommandHandlers.restoreFontSize();
            } catch (error) {
                alert(error);
            }
        });

        $(ViewCommandHandlers).on("fontSizeChange", function () {
            zoomSelect.$button.text(getTitleTextFromCurrentFontSize());
        });
    }

    function getTitleTextFromCurrentFontSize() {
        var fontSize = PreferencesManager.getViewState("fontSizeStyle");

        if(fontSize){
            fontSize = fontSize.replace("px", "");
        } else {
            return "100 %";
        }

        return Math.round(100 / 12 * fontSize) + " %";
    }

    function saveFontSize(fontSizeStyle) {
        PreferencesManager.setViewState("fontSizeStyle", fontSizeStyle);
    }

    AppInit.htmlReady(function () {
        initialization();

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

define(function (require, exports, module) {
    "use strict";

    var AppInit = brackets.getModule("utils/AppInit"),
        ViewCommandHandlers = brackets.getModule("view/ViewCommandHandlers"),
        DropdownButton = brackets.getModule("widgets/DropdownButton").DropdownButton,
        PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
        zoomSelect = new DropdownButton("", [], function (item, index) {
            return item;
        });

    zoomSelect.$button.text(getTitleTextFromCurrentFontSize());
    zoomSelect.items = ["20 %", "50 %", "70 %", "100 %", "150 %", "200 %", "400 %"];
    zoomSelect.dropdownExtraClasses = "dropdown-status-bar";
    zoomSelect.$button.css("width", "auto");
    zoomSelect.$button.addClass("btn-status-bar");

    $(zoomSelect).on("select", function (e, value, index) {
        zoomSelect.$button.text(value);

        try {
            if (index == 0) {
                saveFontSize("2.4px");
            } else if (index == 1) {
                saveFontSize("6px");
            } else if (index == 2) {
                saveFontSize("8.4px");
            } else if (index == 3) {
                saveFontSize("12px");
            } else if (index == 4) {
                saveFontSize("18px");
            } else if (index == 5) {
                saveFontSize("24px");
            } else if (index == 6) {
                saveFontSize("48px");
            }

            ViewCommandHandlers.restoreFontSize();
        } catch (error) {
            alert(error);
        }
    });

    $(ViewCommandHandlers).on("fontSizeChange", function () {
        zoomSelect.$button.text(getTitleTextFromCurrentFontSize());
    });

    function getTitleTextFromCurrentFontSize() {
        var fontSize = PreferencesManager.getViewState("fontSizeStyle");

        if (fontSize) {
            fontSize = fontSize.replace("px", "");
        } else {
            return "100 %";
        }

        return Math.round(100 / 12 * fontSize) + " %";
    }

    function saveFontSize(fontSizeStyle) {
        PreferencesManager.setViewState("fontSizeStyle", fontSizeStyle);
    }

    AppInit.htmlReady(function () {
        $("#status-info").prepend(zoomSelect.$button);
    });
});
<|endoftext|>


<commit_before>// 请将 AppId 改为你自己的 AppId，否则无法本地测试
var appId = '9p6hyhh60av3ukkni3i9z53q1l8yy3cijj6sie3cewft18vm';

// 请换成你自己的一个房间的 conversation id
var roomId = '551a2847e4b04d688d73dc54';

// 每个客户端自定义的 id
var clientId = 'LeanCloud';

var rt;
var room;

// 监听是否服务器连接成功
var firstFlag = true;

var openBtn = document.getElementById('open-btn');
var sendBtn = document.getElementById('send-btn');
var inputName = document.getElementById('input-name');
var inputSend = document.getElementById('input-send');
var printWall = document.getElementById('print-wall');

bindEvent(openBtn, 'click', main);
bindEvent(sendBtn, 'click', sendMsg);

bindEvent(document.body, 'keydown', function(e) {
    if (e.keyCode === 13) {
        if (firstFlag) {
            main();
        } else {
            sendMsg();
        }
    }
});

function main() {
    showLog('正在链接服务器，请等待。。。');
    var val = inputName.value;
    if (val) {
        clientId = val;
    }
    if (!firstFlag) {
        rt.close();
    }

    // 创建实时通信实例
    rt = AV.realtime({
        appId: appId,
        clientId: clientId
    });

    // 监听连接成功事件
    rt.on('open', function() {
        firstFlag = false;
        showLog('服务器连接成功！');

        // 获得已有房间的实例
        rt.room(roomId, function(object) {

            // 判断服务器端是否存在这个 room，如果存在
            if (object) {
                room = object;

                // 当前用户加入这个房间
                room.join(function() {
                    room.list(function(data) {
                        showLog('当前 Conversation 的成员列表：', data);
                    });
                });

                // 房间接受消息
                room.receive(function(data) {
                    // console.log(data);
                    var text = '';
                    if (data.msg.type) {
                        text = data.msg.text;
                    } else {
                        text = data.msg;
                    }
                    showLog(data.fromPeerId + '： ', text);
                });
            }
        });
    });

    // 监听服务情况
    rt.on('resue', function() {
        showLog('服务器正在重连，请耐心等待。。。');
    });
}

function sendMsg() {

    // 如果没有连接过服务器
    if (firstFlag) {
        alert('请先连接服务器！');
        return;
    }
    var val = inputSend.value;

    // 向这个房间发送消息，这段代码是兼容多终端格式的，包括 iOS、Android、Window Phone
    room.send({
        text: val
    }, {
        type: 'text'
    }, function(data) {

        // 发送成功之后的回调
        inputSend.value = '';
        showLog('自己： ' , val);
        printWall.scrollTop = printWall.scrollHeight;
    });

    // 发送多媒体消息，如果想测试图片发送，可以打开注释
    // room.send({
    //     text: '图片测试',
    //     // 自定义的属性
    //     attr: {
    //         a:123
    //     },
    //     url: 'https://leancloud.cn/images/static/press/Logo%20-%20Blue%20Padding.png',
    //     metaData: {
    //         name:'logo',
    //         format:'png',
    //         height: 123,
    //         width: 123,
    //         size: 888
    //     }
    // }, {
    //    type: 'image'
    // }, function(data) {
    //     console.log('图片数据发送成功！');
    // });
}

// demo 中输出代码
function showLog(msg, data) {
    if (data) {
        // console.log(msg, data);
        msg = msg + '' + encodeHTML(JSON.stringify(data)) + '';
    } else {
        // console.log(msg);
    }
    var p = document.createElement('p');
    p.innerHTML = msg;
    printWall.appendChild(p);
}

function encodeHTML(source) {
    return String(source)
        .replace(/&/g,'&')
        .replace(/</g,'<')
        .replace(/>/g,'>');
        // .replace(/\\/g,'\')
        // .replace(/"/g,'"')
        // .replace(/'/g,''');
}

function bindEvent(dom, eventName, fun) {
    if (window.addEventListener) {
        dom.addEventListener(eventName, fun);
    } else {
        dom.attachEvent('on' + eventName, fun);
    }
}
<commit_msg>[bugfix] Demo2 重连的事件名修正。<commit_after>// 请将 AppId 改为你自己的 AppId，否则无法本地测试
var appId = '9p6hyhh60av3ukkni3i9z53q1l8yy3cijj6sie3cewft18vm';

// 请换成你自己的一个房间的 conversation id
var roomId = '551a2847e4b04d688d73dc54';

// 每个客户端自定义的 id
var clientId = 'LeanCloud';

var rt;
var room;

// 监听是否服务器连接成功
var firstFlag = true;

var openBtn = document.getElementById('open-btn');
var sendBtn = document.getElementById('send-btn');
var inputName = document.getElementById('input-name');
var inputSend = document.getElementById('input-send');
var printWall = document.getElementById('print-wall');

bindEvent(openBtn, 'click', main);
bindEvent(sendBtn, 'click', sendMsg);

bindEvent(document.body, 'keydown', function(e) {
    if (e.keyCode === 13) {
        if (firstFlag) {
            main();
        } else {
            sendMsg();
        }
    }
});

function main() {
    showLog('正在链接服务器，请等待。。。');
    var val = inputName.value;
    if (val) {
        clientId = val;
    }
    if (!firstFlag) {
        rt.close();
    }

    // 创建实时通信实例
    rt = AV.realtime({
        appId: appId,
        clientId: clientId
    });

    // 监听连接成功事件
    rt.on('open', function() {
        firstFlag = false;
        showLog('服务器连接成功！');

        // 获得已有房间的实例
        rt.room(roomId, function(object) {

            // 判断服务器端是否存在这个 room，如果存在
            if (object) {
                room = object;

                // 当前用户加入这个房间
                room.join(function() {
                    room.list(function(data) {
                        showLog('当前 Conversation 的成员列表：', data);
                    });
                });

                // 房间接受消息
                room.receive(function(data) {
                    // console.log(data);
                    var text = '';
                    if (data.msg.type) {
                        text = data.msg.text;
                    } else {
                        text = data.msg;
                    }
                    showLog(data.fromPeerId + '： ', text);
                });
            }
        });
    });

    // 监听服务情况
    rt.on('reuse', function() {
        showLog('服务器正在重连，请耐心等待。。。');
    });
}

function sendMsg() {

    // 如果没有连接过服务器
    if (firstFlag) {
        alert('请先连接服务器！');
        return;
    }
    var val = inputSend.value;

    // 向这个房间发送消息，这段代码是兼容多终端格式的，包括 iOS、Android、Window Phone
    room.send({
        text: val
    }, {
        type: 'text'
    }, function(data) {

        // 发送成功之后的回调
        inputSend.value = '';
        showLog('自己： ' , val);
        printWall.scrollTop = printWall.scrollHeight;
    });

    // 发送多媒体消息，如果想测试图片发送，可以打开注释
    // room.send({
    //     text: '图片测试',
    //     // 自定义的属性
    //     attr: {
    //         a:123
    //     },
    //     url: 'https://leancloud.cn/images/static/press/Logo%20-%20Blue%20Padding.png',
    //     metaData: {
    //         name:'logo',
    //         format:'png',
    //         height: 123,
    //         width: 123,
    //         size: 888
    //     }
    // }, {
    //    type: 'image'
    // }, function(data) {
    //     console.log('图片数据发送成功！');
    // });
}

// demo 中输出代码
function showLog(msg, data) {
    if (data) {
        // console.log(msg, data);
        msg = msg + '' + encodeHTML(JSON.stringify(data)) + '';
    } else {
        // console.log(msg);
    }
    var p = document.createElement('p');
    p.innerHTML = msg;
    printWall.appendChild(p);
}

function encodeHTML(source) {
    return String(source)
        .replace(/&/g,'&')
        .replace(/</g,'<')
        .replace(/>/g,'>');
        // .replace(/\\/g,'\')
        // .replace(/"/g,'"')
        // .replace(/'/g,''');
}

function bindEvent(dom, eventName, fun) {
    if (window.addEventListener) {
        dom.addEventListener(eventName, fun);
    } else {
        dom.attachEvent('on' + eventName, fun);
    }
}
<|endoftext|>


<commit_before>function sendJointResult (result, sort, skip, limit, callback) {

    // build the final items
    var items = [];

    // each result object
    for (var i = 0; i < result.length; ++i) {

        // get the current result object
        var cResult = result[i];

        // if it's null, just continue
        if (cResult === null) { continue; }

        // if it is NOT null, push it
        items.push(cResult);
    }

    // get the count
    var count = items.length;

    // take the part of array that must be sent on the client
    items = items.slice(skip, skip + limit);

    // callback
    callback(null, items, count);
}

function jointRequest (dbReq, jointDbReq, result, callback) {

    jointDbReq.template._modm.collection.find(jointDbReq.query, jointDbReq.options, function (err, cursor) {

        // ignore query when no items in result
        if (err) {
            return callback(err);
        }

        cursor.toArray(function (err, jointResult) {

            if (err || jointResult.length === 0) {
                return callback(err);
            }

            // create joint object
            var jointData = {};
            for (var i = 0, l = jointResult.length; i < l; ++i) {

                // get the current joint result object
                var cJointResult = jointResult[i];

                // set it in joint data
                jointData[cJointResult._id] = cJointResult;
            }

            // merge linked data
            for (var i = 0, l = result.length; i < l; ++i) {

                // get the current result object
                var cResult = result[i];
                if (
                    cResult &&
                    cResult[jointDbReq.merge] &&
                    jointData[cResult[jointDbReq.merge]] &&
                    jointData[cResult[jointDbReq.merge]]._id.toString() === cResult[jointDbReq.merge].toString()
                ) {
                    // merge linked data in result field
                    cResult[jointDbReq.merge] = jointData[result[i][jointDbReq.merge]];
                } else {
                    result[i] = null;
                }
            }

            callback();
        });
    });
}

function jointResponse (dbReq, cursor, skip, limit, callback) {

    // skip not provided, set it 0
    skip = skip || 0;

    // convert cursor to array
    cursor.toArray(function (err, result) {

        if (err) {
            return callback(err);
        }

        // don't merge if no documents are found
        if (result.length === 0) {
            return callback(null, []);
        }

        var current = 0;
        for (var joint in dbReq.joints) {

            // get the current joint object
            var cJoint = dbReq.joints[joint];

            // set limit to length of result
            cJoint.options.limit = result.length;
            delete cJoint.options.limit;
            delete cJoint.options.skip;

            // get ids from linked fields
            var uniqueId = {};
            cJoint.query._id = {$in: []};
            for (var i = 0, l = result.length; i < l; ++i) {

                // get the current result object
                var cResult = result[i];

                if (!uniqueId[cResult[cJoint.merge]] && cResult[cJoint.merge]) {
                    uniqueId[cResult[cJoint.merge]] = 1;
                    cJoint.query._id.$in.push(cResult[cJoint.merge]);
                }
            }

            // get linked data
            jointRequest(dbReq, cJoint, result, function (err) {

                if (err) {
                    return callback(err);
                }

                if (++current === dbReq.jointsLength) {
                    sendJointResult(result, dbReq.options.sort, skip, limit, callback);
                }
            });
        }
    });
}

// CRUD interface

exports.create = function (dbReq, callback) {
    dbReq.template._modm.collection.insert(dbReq.data, dbReq.options, callback);
};

exports.read = function (dbReq, callback) {

    // delete limit
    if (dbReq.joints) {

        // get skip and limit
        var limit = dbReq.options.limit
          , skip  = dbReq.options.skip
          ;

        // then delete them
        delete dbReq.options.limit;
        delete dbReq.options.skip;
    }

    // get data and count
    dbReq.template._modm.collection.find(dbReq.query, dbReq.options, function (err, cursor) {

        if (err) {
            return callback(err);
        }

        dbReq.template._modm.collection.count(dbReq.query, function (countErr, count) {

            if (countErr) {
                count = -1;
            }

            // merge linked data in result data
            if (dbReq.joints) {
                return jointResponse(dbReq, cursor, skip, limit, function (err, result, count) {
                    callback(err, result, count);
                });
            }

            callback(null, cursor, count);
        });
    });
};

exports.update = function (dbReq, callback) {
    dbReq.template._modm.collection.update(dbReq.query, dbReq.data, dbReq.options, callback);
};

exports['delete'] = function (dbReq, callback) {
    dbReq.template._modm.collection.remove(dbReq.query, dbReq.options, callback);
};
<commit_msg>Don't check the length of the join result data<commit_after>function sendJointResult (result, sort, skip, limit, callback) {

    // build the final items
    var items = [];

    // each result object
    for (var i = 0; i < result.length; ++i) {

        // get the current result object
        var cResult = result[i];

        // if it's null, just continue
        if (cResult === null) { continue; }

        // if it is NOT null, push it
        items.push(cResult);
    }

    // get the count
    var count = items.length;

    // take the part of array that must be sent on the client
    items = items.slice(skip, skip + limit);

    // callback
    callback(null, items, count);
}

function jointRequest (dbReq, jointDbReq, result, callback) {

    jointDbReq.template._modm.collection.find(jointDbReq.query, jointDbReq.options, function (err, cursor) {

        // ignore query when no items in result
        if (err) {
            return callback(err);
        }

        cursor.toArray(function (err, jointResult) {

            if (err) {
                return callback(err);
            }

            // create joint object
            var jointData = {};
            for (var i = 0, l = jointResult.length; i < l; ++i) {

                // get the current joint result object
                var cJointResult = jointResult[i];

                // set it in joint data
                jointData[cJointResult._id] = cJointResult;
            }

            // merge linked data
            for (var i = 0, l = result.length; i < l; ++i) {

                // get the current result object
                var cResult = result[i];
                if (
                    cResult &&
                    cResult[jointDbReq.merge] &&
                    jointData[cResult[jointDbReq.merge]] &&
                    jointData[cResult[jointDbReq.merge]]._id.toString() === cResult[jointDbReq.merge].toString()
                ) {
                    // merge linked data in result field
                    cResult[jointDbReq.merge] = jointData[result[i][jointDbReq.merge]];
                } else {
                    result[i] = null;
                }
            }

            callback();
        });
    });
}

function jointResponse (dbReq, cursor, skip, limit, callback) {

    // skip not provided, set it 0
    skip = skip || 0;

    // convert cursor to array
    cursor.toArray(function (err, result) {

        if (err) {
            return callback(err);
        }

        // don't merge if no documents are found
        if (result.length === 0) {
            return callback(null, []);
        }

        var current = 0;
        for (var joint in dbReq.joints) {

            // get the current joint object
            var cJoint = dbReq.joints[joint];

            // set limit to length of result
            cJoint.options.limit = result.length;
            delete cJoint.options.limit;
            delete cJoint.options.skip;

            // get ids from linked fields
            var uniqueId = {};
            cJoint.query._id = {$in: []};
            for (var i = 0, l = result.length; i < l; ++i) {

                // get the current result object
                var cResult = result[i];

                if (!uniqueId[cResult[cJoint.merge]] && cResult[cJoint.merge]) {
                    uniqueId[cResult[cJoint.merge]] = 1;
                    cJoint.query._id.$in.push(cResult[cJoint.merge]);
                }
            }

            // get linked data
            jointRequest(dbReq, cJoint, result, function (err) {

                if (err) {
                    return callback(err);
                }

                if (++current === dbReq.jointsLength) {
                    sendJointResult(result, dbReq.options.sort, skip, limit, callback);
                }
            });
        }
    });
}

// CRUD interface

exports.create = function (dbReq, callback) {
    dbReq.template._modm.collection.insert(dbReq.data, dbReq.options, callback);
};

exports.read = function (dbReq, callback) {

    // delete limit
    if (dbReq.joints) {

        // get skip and limit
        var limit = dbReq.options.limit
          , skip  = dbReq.options.skip
          ;

        // then delete them
        delete dbReq.options.limit;
        delete dbReq.options.skip;
    }

    // get data and count
    dbReq.template._modm.collection.find(dbReq.query, dbReq.options, function (err, cursor) {

        if (err) {
            return callback(err);
        }

        dbReq.template._modm.collection.count(dbReq.query, function (countErr, count) {

            if (countErr) {
                count = -1;
            }

            // merge linked data in result data
            if (dbReq.joints) {
                return jointResponse(dbReq, cursor, skip, limit, function (err, result, count) {
                    callback(err, result, count);
                });
            }

            callback(null, cursor, count);
        });
    });
};

exports.update = function (dbReq, callback) {
    dbReq.template._modm.collection.update(dbReq.query, dbReq.data, dbReq.options, callback);
};

exports['delete'] = function (dbReq, callback) {
    dbReq.template._modm.collection.remove(dbReq.query, dbReq.options, callback);
};
<|endoftext|>


<commit_before>var _; //globals

/* This section uses a functional extension known as Underscore.js - http://documentcloud.github.com/underscore/
     "Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support
      that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects.
      It's the tie to go along with jQuery's tux."
 */
describe("About Higher Order Functions", function () {

  it("should use filter to return array items that meet a criteria", function () {
    var numbers = [1,2,3];
    var odd = _(numbers).filter(function (x) { return x % 2 !== 0 });

    expect(odd).toEqual(FILL_ME_IN);
    expect(odd.length).toBe(FILL_ME_IN);
    expect(numbers.length).toBe(FILL_ME_IN);
  });

  it("should use 'map' to transform each element", function () {
    var numbers = [1, 2, 3];
    var numbersPlus1 = _(numbers).map(function(x) { return x + 1 });

    expect(numbersPlus1).toEqual(FILL_ME_IN);
    expect(numbers).toEqual(FILL_ME_IN);
  });

  it("should use 'reduce' to update the same result on each iteration", function () {
    var numbers = [1, 2, 3];
    var reduction = _(numbers).reduce(
      function(memo, x) {
        //note: memo is the result from last call, and x is the current number
        return memo + x;
      },
      /* initial */ 0
    );

    expect(reduction).toBe(FILL_ME_IN);
    expect(numbers).toEqual(FILL_ME_IN);
  });

  it("should use 'forEach' for simple iteration", function () {
    var numbers = [1,2,3];
    var msg = "";
    var isEven = function (item) {
      msg += (item % 2) === 0;
    };

    _(numbers).forEach(isEven);

    expect(msg).toEqual(FILL_ME_IN);
    expect(numbers).toEqual(FILL_ME_IN);
  });

  it("should use 'all' to test whether all items pass condition", function () {
    var onlyEven = [2,4,6];
    var mixedBag = [2,4,5,6];

    var isEven = function(x) { return x % 2 === 0 };

    expect(_(onlyEven).all(isEven)).toBe(FILL_ME_IN);
    expect(_(mixedBag).all(isEven)).toBe(FILL_ME_IN);
  });

  it("should use 'any' to test if any items passes condition" , function () {
    var onlyEven = [2,4,6];
    var mixedBag = [2,4,5,6];

    var isEven = function(x) { return x % 2 === 0 };

    expect(_(onlyEven).any(isEven)).toBe(FILL_ME_IN);
    expect(_(mixedBag).any(isEven)).toBe(FILL_ME_IN);
  });

  it("should use range to generate an array", function() {
    expect(_.range(3)).toEqual(FILL_ME_IN);
    expect(_.range(1, 4)).toEqual(FILL_ME_IN);
    expect(_.range(0, -4, -1)).toEqual(FILL_ME_IN);
  });

  it("should use flatten to make nested arrays easy to work with", function() {
    expect(_([ [1, 2], [3, 4] ]).flatten()).toEqual(FILL_ME_IN);
  });

  it("should use chain() ... .value() to use multiple higher order functions", function() {
    var result = _([ [0, 1], 2 ]).chain()
                     .flatten()
                     .map(function(x) { return x+1 } )
                     .reduce(function (sum, x) { return sum + x })
                     .value();

    expect(result).toEqual(FILL_ME_IN);
  });

});

<commit_msg>Finished AboutHigherOrderFunctions koan.<commit_after>var _; //globals

/* This section uses a functional extension known as Underscore.js - http://documentcloud.github.com/underscore/
     "Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support
      that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects.
      It's the tie to go along with jQuery's tux."
 */
describe("About Higher Order Functions", function () {

  it("should use filter to return array items that meet a criteria", function () {
    var numbers = [1,2,3];
    var odd = _(numbers).filter(function (x) { return x % 2 !== 0 });

    expect(odd).toEqual([1,3]);
    expect(odd.length).toBe(2);
    expect(numbers.length).toBe(3);
  });

  it("should use 'map' to transform each element", function () {
    var numbers = [1, 2, 3];
    var numbersPlus1 = _(numbers).map(function(x) { return x + 1 });

    expect(numbersPlus1).toEqual([2, 3, 4]);
    expect(numbers).toEqual([1, 2, 3]);
  });

  it("should use 'reduce' to update the same result on each iteration", function () {
    var numbers = [1, 2, 3];
    var reduction = _(numbers).reduce(
      function(memo, x) {
        //note: memo is the result from last call, and x is the current number
        return memo + x;
      },
      /* initial */ 0
    );

    expect(reduction).toBe(6);
    expect(numbers).toEqual([1, 2, 3]);
  });

  it("should use 'forEach' for simple iteration", function () {
    var numbers = [1,2,3];
    var msg = "";
    var isEven = function (item) {
      msg += (item % 2) === 0;
    };

    _(numbers).forEach(isEven);

    expect(msg).toEqual('falsetruefalse');
    expect(numbers).toEqual([1, 2, 3]);
  });

  it("should use 'all' to test whether all items pass condition", function () {
    var onlyEven = [2,4,6];
    var mixedBag = [2,4,5,6];

    var isEven = function(x) { return x % 2 === 0 };

    expect(_(onlyEven).all(isEven)).toBe(true);
    expect(_(mixedBag).all(isEven)).toBe(false);
  });

  it("should use 'any' to test if any items passes condition" , function () {
    var onlyEven = [2,4,6];
    var mixedBag = [2,4,5,6];

    var isEven = function(x) { return x % 2 === 0 };

    expect(_(onlyEven).any(isEven)).toBe(true);
    expect(_(mixedBag).any(isEven)).toBe(true);
  });

  it("should use range to generate an array", function() {
    expect(_.range(3)).toEqual([0, 1, 2]);
    expect(_.range(1, 4)).toEqual([1, 2, 3]);
    expect(_.range(0, -4, -1)).toEqual([0, -1, -2, -3]);
  });

  it("should use flatten to make nested arrays easy to work with", function() {
    expect(_([ [1, 2], [3, 4] ]).flatten()).toEqual([1, 2, 3, 4]);
  });

  it("should use chain() ... .value() to use multiple higher order functions", function() {
    var result = _([ [0, 1], 2 ]).chain()
                     .flatten()
                     .map(function(x) { return x+1 } )
                     .reduce(function (sum, x) { return sum + x })
                     .value();

    expect(result).toEqual(6);
  });

});

<|endoftext|>


<commit_before>var _ = {};

_.modulo = function(a, b) {
    var c = a % b;
    return c >= 0 ? c : c + b;
};

_.enumerate = function(list) {
    if (!Array.isArray(list) && typeof list !== 'string')
        list = Object.keys(list);

    return {
        get: function(i) { return list[i] },
        length: list.length
    };
};

_.enumerateKeys = function(list) {
    if (!Array.isArray(list) && typeof list !== 'string')
        return this.enumerate(list);

    return {
        get: function(i) { return i },
        length: list.length
    };
};
<commit_msg>Add 'in' operator<commit_after>var _ = {};

_.modulo = function(a, b) {
    var c = a % b;
    return c >= 0 ? c : c + b;
};

_.enumerate = function(list) {
    if (!Array.isArray(list) && typeof list !== 'string')
        list = Object.keys(list);

    return {
        get: function(i) { return list[i] },
        length: list.length
    };
};

_.enumerateKeys = function(list) {
    if (!Array.isArray(list) && typeof list !== 'string')
        return this.enumerate(list);

    return {
        get: function(i) { return i },
        length: list.length
    };
};

_.inOp = function(el, list) {
    if (!Array.isArray(list) && typeof list !== 'string')
        return el in list

    return list.indexOf(el) != -1
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

var load_config = require('../lib/config')
  , backend = require('unpm-fs-backend')
  , path = require('path')
  , nopt = require('nopt')
  , unpm = require('../')

var noptions = {
    'port': Number
  , 'verbose': Boolean
  , 'log': Boolean
  , 'logdir': String
  , 'datadir': String
}

var shorts = {
    'p': ['--port']
  , 'v': ['--verbose']
  , 'l': ['--log']
  , 'L': ['--logdir']
  , 'd': ['--datadir']
}

var config = nopt(noptions, shorts)

var CWD = process.cwd()

var unpm_service
  , tarballs_dir
  , user_dir
  , meta_dir
  , data_dir

config = load_config(config || {})

data_dir = config.datadir || path.join(CWD, 'data')

if(!config.backend) {
  tarballs_dir = path.join(data_dir, 'tarballs')
  user_dir = path.join(data_dir, 'users')
  meta_dir = path.join(data_dir, 'meta')

  config.backend = backend(meta_dir, user_dir, tarballs_dir)
}

unpm_service = unpm(config)
unpm_service.server.listen(unpm_service.config.port)

unpm_service.log.info('Started unpm on port %s', unpm_service.config.port)
<commit_msg>normalize dir input<commit_after>#!/usr/bin/env node

var load_config = require('../lib/config')
  , backend = require('unpm-fs-backend')
  , path = require('path')
  , nopt = require('nopt')
  , unpm = require('../')

var noptions = {
    'port': Number
  , 'verbose': Boolean
  , 'log': Boolean
  , 'logdir': String
  , 'datadir': String
}

var shorts = {
    'p': ['--port']
  , 'v': ['--verbose']
  , 'l': ['--log']
  , 'L': ['--logdir']
  , 'd': ['--datadir']
}

var config = nopt(noptions, shorts)

var CWD = process.cwd()

var unpm_service
  , tarballs_dir
  , user_dir
  , meta_dir
  , data_dir

config = load_config(config || {})

data_dir = path.normalize(config.datadir) || path.join(CWD, 'data')

if(!config.backend) {
  tarballs_dir = path.join(data_dir, 'tarballs')
  user_dir = path.join(data_dir, 'users')
  meta_dir = path.join(data_dir, 'meta')

  config.backend = backend(meta_dir, user_dir, tarballs_dir)
}

unpm_service = unpm(config)
unpm_service.server.listen(unpm_service.config.port)

unpm_service.log.info('Started unpm on port %s', unpm_service.config.port)
<|endoftext|>


<commit_before>const ArgumentType = require('./base');

/** A type for command arguments that handles multiple other types */
class ArgumentUnionType extends ArgumentType {
	constructor(client, id) {
		super(client, id);

		/**
		 * Types to handle, in order of priority
		 * @type {ArgumentType[]}
		 */
		this.types = [];
		const typeIDs = id.split('|');
		for(const typeID of typeIDs) {
			const type = client.registry.types.get(typeID);
			if(!type) throw new Error(`Argument type "${typeID}" is not registered.`);
			this.types.push(type);
		}
	}

	async validate(value, msg, arg) {
		let results = this.types.map(type => type.validate(value, msg, arg));
		results = await Promise.all(results);
		if(results.some(valid => valid && typeof valid !== 'string')) return true;
		return false;
	}

	async parse(value, msg, arg) {
		let results = this.types.map(type => type.validate(value, msg, arg));
		results = await Promise.all(results);
		for(let i = 0; i < results.length; i++) {
			if(results[i] && typeof results[i] !== 'string') return this.types[i].parse(value, msg, arg);
		}
		throw new Error(`Couldn't parse value "${value}" with union type ${this.id}.`);
	}
}

module.exports = ArgumentUnionType;
<commit_msg>Add ArgumentUnionType#isEmpty<commit_after>const ArgumentType = require('./base');

/** A type for command arguments that handles multiple other types */
class ArgumentUnionType extends ArgumentType {
	constructor(client, id) {
		super(client, id);

		/**
		 * Types to handle, in order of priority
		 * @type {ArgumentType[]}
		 */
		this.types = [];
		const typeIDs = id.split('|');
		for(const typeID of typeIDs) {
			const type = client.registry.types.get(typeID);
			if(!type) throw new Error(`Argument type "${typeID}" is not registered.`);
			this.types.push(type);
		}
	}

	async validate(value, msg, arg) {
		let results = this.types.map(type => type.validate(value, msg, arg));
		results = await Promise.all(results);
		if(results.some(valid => valid && typeof valid !== 'string')) return true;
		return false;
	}

	async parse(value, msg, arg) {
		let results = this.types.map(type => type.validate(value, msg, arg));
		results = await Promise.all(results);
		for(let i = 0; i < results.length; i++) {
			if(results[i] && typeof results[i] !== 'string') return this.types[i].parse(value, msg, arg);
		}
		throw new Error(`Couldn't parse value "${value}" with union type ${this.id}.`);
	}

	isEmpty(value, msg, arg) {
		return !this.types.some(type => !type.isEmpty(value, msg, arg));
	}
}

module.exports = ArgumentUnionType;
<|endoftext|>


<commit_before>/* Copyright (c) 2017 Richard Rodger, MIT License */
'use strict'

var Assert = require('assert')

var Lab = require('lab')
var Code = require('code')
var Seneca = require('..')

var lab = (exports.lab = Lab.script())
var describe = lab.describe
var it = lab.it
var expect = Code.expect

var intern = Seneca.intern

describe('intern', function() {
  it('make_actmsg', function(fin) {
    /*

    var om0 = {a:1, b$: 2}
    om0.__proto__ = {c:3}
    var am0 = intern.make_actmsg(om0)
    expect(am0.a).equal(1)
    expect(am0.c).equal(3)
    expect(am0.b$).to.not.exist()
    expect(Object.keys(am0)).equal(['a'])
    expect(om0.__proto__ === am0.__proto__)

    var se = Seneca().use('entity')
    var om1 = se.make$('foo',{a:1})
    expect('-/-/foo').equal(om1.canon$())

    var am1 = intern.make_actmsg(om1)
    expect(om1.__proto__ === am1.__proto__)
    expect('-/-/foo').equal(am1.entity$)
    expect('-/-/foo').equal(am1.canon$())
*/

    fin()
  })
})
<commit_msg>removed intern.test.js as empty<commit_after><|endoftext|>


<commit_before>if (typeof(lowpoly) === 'undefined')
{
	var lowpoly = {
	linesWithAnchor: {},
	anchorsForLine: {},
	currentLayer: undefined,
	layers: {},
	lastAnchors: [],
	trianglesForAnchor: {},
	anchorsForTriangle: {}
	};
}

lowpoly.init = function()
{
	var width = window.innerWidth-2;
	var height = window.innerHeight/2;

	lowpoly.stage = new Konva.Stage({
		container: 'container',
		width: width,
		height: height
	});

	var bg_image_obj = new Image();
	bg_image_obj.src = 'test.jpg';
	bg_image_obj.onload = function()
	{
		lowpoly.image_layer = new Konva.Layer();
		var image = new Konva.Image({
			image: bg_image_obj,
			x: 0,
			y: 0
		});
		lowpoly.image_layer.add(image);
		lowpoly.stage.width(bg_image_obj.width);
		lowpoly.stage.height(bg_image_obj.height);
		lowpoly.stage.add(lowpoly.image_layer);
		lowpoly.image_layer.moveToBottom();
		image.on('click', lowpoly.stageClick);
	}

	var anchor_layer = new Konva.Layer();
	var line_layer = new Konva.Layer();
	var poly_layer = new Konva.Layer();
	lowpoly.layers["main"] = {
		anchors: anchor_layer,
		lines: line_layer,
		polys: poly_layer
	}
	lowpoly.currentLayer = "main";

	lowpoly.stage.add(line_layer);
	lowpoly.stage.add(poly_layer);
	lowpoly.stage.add(anchor_layer);
}

lowpoly.stageClick = function(event)
{
	if (!event.evt.shiftKey && !event.evt.altKey)
	{
		for (a in lowpoly.lastAnchors)
			lowpoly.markAnchorAsUnselected(lowpoly.lastAnchors[a])
		lowpoly.lastAnchors = [];
	}
	if (event.evt.shiftKey && lowpoly.lastAnchors.length == 2)
	{
		a = lowpoly.lastAnchors.shift();
		lowpoly.markAnchorAsUnselected(a);
	}
	var x = event.evt.x;
	var y = event.evt.y;
	// draw new anchor
	var anchor = new Konva.Circle({
		radius: 5,
		x: x,
		y: y,
		fill: 'white',
		stroke: 'black',
		strokeWidth: 1,
		draggable: 'true'
	});
	anchor.on("click", lowpoly.anchorClick);
	anchor.on("dragstart", lowpoly.anchorClick);
	anchor.on("dragstart dragmove dragend", lowpoly.anchorDrag);
	var layer = lowpoly.layers[lowpoly.currentLayer];
	layer.anchors.add(anchor);
	anchor.draw();

	lowpoly.linesWithAnchor[anchor._id] = [];
	lowpoly.trianglesForAnchor[anchor._id] = [];

	// draw lines
	if (lowpoly.lastAnchors.length > 0)
	{
		var prev = lowpoly.lastAnchors[0];
		lowpoly.connectAnchors(prev, anchor);
	}
	if (lowpoly.lastAnchors.length == 2)
	{
		var prev = lowpoly.lastAnchors[1];
		lowpoly.connectAnchors(prev, anchor);
		a = lowpoly.lastAnchors.shift();
		lowpoly.markAnchorAsUnselected(a);
	}
	lowpoly.lastAnchors.push(anchor);
	lowpoly.markAnchorsAsSelected(lowpoly.lastAnchors);
	lowpoly.stage.draw();
}

lowpoly.connectAnchors = function(a1, a2)
{
	var line = new Konva.Line({
		points: [a1.x(), a1.y(), a2.x(), a2.y()],
		stroke: 'black'
	});
	var layer = lowpoly.layers[lowpoly.currentLayer];
	layer.lines.add(line);
	lowpoly.linesWithAnchor[a1._id].push(line);
	lowpoly.linesWithAnchor[a2._id].push(line);
	lowpoly.anchorsForLine[line._id] = [a1, a2];
	// detect new triangles
	a1neighbours = {};
	lines = lowpoly.linesWithAnchor[a1._id];
	for (line in lines)
	{
		lineId = lines[line]._id;
		lineAnchors = lowpoly.anchorsForLine[lineId];
		if (a1 != lineAnchors[0] && a2 != lineAnchors[0])
			a1neighbours[lineAnchors[0]._id] = lineAnchors[0];
		else if (a1 != lineAnchors[1] && a2 != lineAnchors[1])
			a1neighbours[lineAnchors[1]._id] = lineAnchors[1];
	}
	a2neighbours = {};
	lines = lowpoly.linesWithAnchor[a2._id];
	for (line in lines)
	{
		lineId = lines[line]._id;
		lineAnchors = lowpoly.anchorsForLine[lineId];
		if (a2 != lineAnchors[0] && a1 != lineAnchors[0])
			a2neighbours[lineAnchors[0]._id] = lineAnchors[0];
		else if (a2 != lineAnchors[1] && a1 != lineAnchors[1])
			a2neighbours[lineAnchors[1]._id] = lineAnchors[1];
	}

	if (a1neighbours.size < a2neighbours.size)
	{
		n1 = a1neighbours;
		n2 = a2neighbours;
	}
	else
	{
		n1 = a2neighbours;
		n2 = a1neighbours;
	}

	for (n in n1)
	{
		if (n in n2)
		{
			fill_colour = lowpoly.getColourForTriangle(a1, a2, n1[n]);
			tri = new Konva.Line({
				points: [a1.x(), a1.y(), a2.x(), a2.y(), n1[n].x(), n1[n].y()],
				strokeWidth: 0,
				closed: true,
				fill: fill_colour
			})
			lowpoly.trianglesForAnchor[a1._id].push(tri);
			lowpoly.trianglesForAnchor[a2._id].push(tri);
			lowpoly.trianglesForAnchor[n1[n]._id].push(tri);
			lowpoly.anchorsForTriangle[tri._id] = [a1, a2, n1[n]];
			lowpoly.layers[lowpoly.currentLayer].polys.add(tri);
			tri.draw();
		}
	}
}

lowpoly.anchorClick = function(event)
{
	if (lowpoly.lastAnchors.length == 0)
	{
		lowpoly.lastAnchors.push(event.target);
		lowpoly.markAnchorsAsSelected(lowpoly.lastAnchors);
		return;
	}
	if (lowpoly.lastAnchors[lowpoly.lastAnchors.length - 1] == event.target)
		return;
	if (lowpoly.lastAnchors.length == 2)
	{
		a = lowpoly.lastAnchors.shift();
		lowpoly.markAnchorAsUnselected(a);
	}
	if (event.evt.shiftKey)
	{
		lowpoly.connectAnchors(lowpoly.lastAnchors[0], event.target);
	}
	lowpoly.lastAnchors.push(event.target);
	lowpoly.markAnchorsAsSelected(lowpoly.lastAnchors);
	lowpoly.stage.draw();
}

lowpoly.redrawLine = function(line)
{
	a1 = lowpoly.anchorsForLine[line._id][0];
	a2 = lowpoly.anchorsForLine[line._id][1];
	line.setPoints([a1.x(), a1.y(), a2.x(), a2.y()]);
}

lowpoly.redrawTriangle = function(triangle)
{
	a1 = lowpoly.anchorsForTriangle[triangle._id][0];
	a2 = lowpoly.anchorsForTriangle[triangle._id][1];
	a3 = lowpoly.anchorsForTriangle[triangle._id][2];
	triangle.setPoints([a1.x(), a1.y(), a2.x(), a2.y(), a3.x(), a3.y()]);
	triangle.fill(lowpoly.getColourForTriangle(a1, a2, a3));
}

lowpoly.anchorDrag = function(event)
{
	anchor = event.target;
	lines = lowpoly.linesWithAnchor[anchor._id];
	for (line in lines)
	{
		lowpoly.redrawLine(lines[line]);
	}
	triangles = lowpoly.trianglesForAnchor[anchor._id];
	for (tri in triangles)
	{
		lowpoly.redrawTriangle(triangles[tri]);
	}
	lowpoly.stage.draw();
}

lowpoly.getColourForTriangle = function(a1, a2, a3)
{
	var x = (a1.x() + a2.x() + a3.x()) / 3;
	var y = (a1.y() + a2.y() + a3.y()) / 3;
	var l = lowpoly.image_layer;
	var vis = l.visible();
	l.visible(true);
	l.draw();
	var colour = l.canvas._canvas.getContext('2d').getImageData(x, y, 1, 1).data;
	l.visible(vis);
	l.draw();
	var ret = 'rgb(' + colour[0] + ', ' + colour[1] + ', ' + colour[2] + ')';
	return ret;
}

lowpoly.markAnchorsAsSelected = function(anchors)
{
	if (anchors.length == 2)
	{
		lowpoly.markAnchorAsFirstSelection(anchors[1]);
		lowpoly.markAnchorAsSecondSelection(anchors[0]);
	}
	if (anchors.length == 1)
	{
		lowpoly.markAnchorAsFirstSelection(anchors[0]);
	}
}

lowpoly.markAnchorAsFirstSelection = function(anchor)
{
	anchor.fill("#00ff00");
}

lowpoly.markAnchorAsSecondSelection = function(anchor)
{
	anchor.fill("#ff0000");
}

lowpoly.markAnchorAsUnselected = function(anchor)
{
	anchor.fill("#ffffff");
}

lowpoly.toggleVisibility = function(event)
{
	if (event.target.id == "image")
	{
		lowpoly.image_layer.visible(event.target.checked);
		lowpoly.image_layer.draw();
		return;
	}
	layer = lowpoly.layers[lowpoly.currentLayer][event.target.id];
	layer.visible(event.target.checked);
	layer.draw();
}
<commit_msg>Add (library) ability to delete anchors and lines.<commit_after>if (typeof(lowpoly) === 'undefined')
{
	var lowpoly = {
	linesWithAnchor: {},
	anchorsForLine: {},
	currentLayer: undefined,
	layers: {},
	lastAnchors: [],
	trianglesForAnchor: {},
	anchorsForTriangle: {}
	};
}

lowpoly.init = function()
{
	var width = window.innerWidth-2;
	var height = window.innerHeight/2;

	lowpoly.stage = new Konva.Stage({
		container: 'container',
		width: width,
		height: height
	});

	var bg_image_obj = new Image();
	bg_image_obj.src = 'test.jpg';
	bg_image_obj.onload = function()
	{
		lowpoly.image_layer = new Konva.Layer();
		var image = new Konva.Image({
			image: bg_image_obj,
			x: 0,
			y: 0
		});
		lowpoly.image_layer.add(image);
		lowpoly.stage.width(bg_image_obj.width);
		lowpoly.stage.height(bg_image_obj.height);
		lowpoly.stage.add(lowpoly.image_layer);
		lowpoly.image_layer.moveToBottom();
		image.on('click', lowpoly.stageClick);
	}

	var anchor_layer = new Konva.Layer();
	var line_layer = new Konva.Layer();
	var poly_layer = new Konva.Layer();
	lowpoly.layers["main"] = {
		anchors: anchor_layer,
		lines: line_layer,
		polys: poly_layer
	}
	lowpoly.currentLayer = "main";

	lowpoly.stage.add(line_layer);
	lowpoly.stage.add(poly_layer);
	lowpoly.stage.add(anchor_layer);
}

lowpoly.stageClick = function(event)
{
	if (!event.evt.shiftKey && !event.evt.altKey)
	{
		for (a in lowpoly.lastAnchors)
			lowpoly.markAnchorAsUnselected(lowpoly.lastAnchors[a])
		lowpoly.lastAnchors = [];
	}
	if (event.evt.shiftKey && lowpoly.lastAnchors.length == 2)
	{
		a = lowpoly.lastAnchors.shift();
		lowpoly.markAnchorAsUnselected(a);
	}
	var x = event.evt.x;
	var y = event.evt.y;
	// draw new anchor
	var anchor = new Konva.Circle({
		radius: 5,
		x: x,
		y: y,
		fill: 'white',
		stroke: 'black',
		strokeWidth: 1,
		draggable: 'true'
	});
	anchor.on("click", lowpoly.anchorClick);
	anchor.on("dragstart", lowpoly.anchorClick);
	anchor.on("dragstart dragmove dragend", lowpoly.anchorDrag);
	var layer = lowpoly.layers[lowpoly.currentLayer];
	layer.anchors.add(anchor);
	anchor.draw();

	lowpoly.linesWithAnchor[anchor._id] = [];
	lowpoly.trianglesForAnchor[anchor._id] = [];

	// draw lines
	if (lowpoly.lastAnchors.length > 0)
	{
		var prev = lowpoly.lastAnchors[0];
		lowpoly.connectAnchors(prev, anchor);
	}
	if (lowpoly.lastAnchors.length == 2)
	{
		var prev = lowpoly.lastAnchors[1];
		lowpoly.connectAnchors(prev, anchor);
		a = lowpoly.lastAnchors.shift();
		lowpoly.markAnchorAsUnselected(a);
	}
	lowpoly.lastAnchors.push(anchor);
	lowpoly.markAnchorsAsSelected(lowpoly.lastAnchors);
	lowpoly.stage.draw();
}

lowpoly.connectAnchors = function(a1, a2)
{
	var line = new Konva.Line({
		points: [a1.x(), a1.y(), a2.x(), a2.y()],
		stroke: 'black'
	});
	var layer = lowpoly.layers[lowpoly.currentLayer];
	layer.lines.add(line);
	lowpoly.linesWithAnchor[a1._id].push(line);
	lowpoly.linesWithAnchor[a2._id].push(line);
	lowpoly.anchorsForLine[line._id] = [a1, a2];
	// detect new triangles
	a1neighbours = {};
	lines = lowpoly.linesWithAnchor[a1._id];
	for (line in lines)
	{
		lineId = lines[line]._id;
		lineAnchors = lowpoly.anchorsForLine[lineId];
		if (a1 != lineAnchors[0] && a2 != lineAnchors[0])
			a1neighbours[lineAnchors[0]._id] = lineAnchors[0];
		else if (a1 != lineAnchors[1] && a2 != lineAnchors[1])
			a1neighbours[lineAnchors[1]._id] = lineAnchors[1];
	}
	a2neighbours = {};
	lines = lowpoly.linesWithAnchor[a2._id];
	for (line in lines)
	{
		lineId = lines[line]._id;
		lineAnchors = lowpoly.anchorsForLine[lineId];
		if (a2 != lineAnchors[0] && a1 != lineAnchors[0])
			a2neighbours[lineAnchors[0]._id] = lineAnchors[0];
		else if (a2 != lineAnchors[1] && a1 != lineAnchors[1])
			a2neighbours[lineAnchors[1]._id] = lineAnchors[1];
	}

	if (a1neighbours.size < a2neighbours.size)
	{
		n1 = a1neighbours;
		n2 = a2neighbours;
	}
	else
	{
		n1 = a2neighbours;
		n2 = a1neighbours;
	}

	for (n in n1)
	{
		if (n in n2)
		{
			fill_colour = lowpoly.getColourForTriangle(a1, a2, n1[n]);
			tri = new Konva.Line({
				points: [a1.x(), a1.y(), a2.x(), a2.y(), n1[n].x(), n1[n].y()],
				strokeWidth: 0,
				closed: true,
				fill: fill_colour
			})
			lowpoly.trianglesForAnchor[a1._id].push(tri);
			lowpoly.trianglesForAnchor[a2._id].push(tri);
			lowpoly.trianglesForAnchor[n1[n]._id].push(tri);
			lowpoly.anchorsForTriangle[tri._id] = [a1, a2, n1[n]];
			lowpoly.layers[lowpoly.currentLayer].polys.add(tri);
			tri.draw();
		}
	}
}

lowpoly.anchorClick = function(event)
{
	if (lowpoly.lastAnchors.length == 0)
	{
		lowpoly.lastAnchors.push(event.target);
		lowpoly.markAnchorsAsSelected(lowpoly.lastAnchors);
		return;
	}
	if (lowpoly.lastAnchors[lowpoly.lastAnchors.length - 1] == event.target)
		return;
	if (lowpoly.lastAnchors.length == 2)
	{
		a = lowpoly.lastAnchors.shift();
		lowpoly.markAnchorAsUnselected(a);
	}
	if (event.evt.shiftKey)
	{
		lowpoly.connectAnchors(lowpoly.lastAnchors[0], event.target);
	}
	lowpoly.lastAnchors.push(event.target);
	lowpoly.markAnchorsAsSelected(lowpoly.lastAnchors);
	lowpoly.stage.draw();
}

lowpoly.redrawLine = function(line)
{
	a1 = lowpoly.anchorsForLine[line._id][0];
	a2 = lowpoly.anchorsForLine[line._id][1];
	line.setPoints([a1.x(), a1.y(), a2.x(), a2.y()]);
}

lowpoly.redrawTriangle = function(triangle)
{
	a1 = lowpoly.anchorsForTriangle[triangle._id][0];
	a2 = lowpoly.anchorsForTriangle[triangle._id][1];
	a3 = lowpoly.anchorsForTriangle[triangle._id][2];
	triangle.setPoints([a1.x(), a1.y(), a2.x(), a2.y(), a3.x(), a3.y()]);
	triangle.fill(lowpoly.getColourForTriangle(a1, a2, a3));
}

lowpoly.anchorDrag = function(event)
{
	anchor = event.target;
	lines = lowpoly.linesWithAnchor[anchor._id];
	for (line in lines)
	{
		lowpoly.redrawLine(lines[line]);
	}
	triangles = lowpoly.trianglesForAnchor[anchor._id];
	for (tri in triangles)
	{
		lowpoly.redrawTriangle(triangles[tri]);
	}
	lowpoly.stage.draw();
}

lowpoly.getColourForTriangle = function(a1, a2, a3)
{
	var x = (a1.x() + a2.x() + a3.x()) / 3;
	var y = (a1.y() + a2.y() + a3.y()) / 3;
	var l = lowpoly.image_layer;
	var vis = l.visible();
	l.visible(true);
	l.draw();
	var colour = l.canvas._canvas.getContext('2d').getImageData(x, y, 1, 1).data;
	l.visible(vis);
	l.draw();
	var ret = 'rgb(' + colour[0] + ', ' + colour[1] + ', ' + colour[2] + ')';
	return ret;
}

lowpoly.markAnchorsAsSelected = function(anchors)
{
	if (anchors.length == 2)
	{
		lowpoly.markAnchorAsFirstSelection(anchors[1]);
		lowpoly.markAnchorAsSecondSelection(anchors[0]);
	}
	if (anchors.length == 1)
	{
		lowpoly.markAnchorAsFirstSelection(anchors[0]);
	}
}

lowpoly.markAnchorAsFirstSelection = function(anchor)
{
	anchor.fill("#00ff00");
}

lowpoly.markAnchorAsSecondSelection = function(anchor)
{
	anchor.fill("#ff0000");
}

lowpoly.markAnchorAsUnselected = function(anchor)
{
	anchor.fill("#ffffff");
}

lowpoly.toggleVisibility = function(event)
{
	if (event.target.id == "image")
	{
		lowpoly.image_layer.visible(event.target.checked);
		lowpoly.image_layer.draw();
		return;
	}
	layer = lowpoly.layers[lowpoly.currentLayer][event.target.id];
	layer.visible(event.target.checked);
	layer.draw();
}

lowpoly.deleteTriangle = function(triangle)
{
	for (a in lowpoly.anchorsForTriangle[triangle._id])
	{
		var anchor = lowpoly.anchorsForTriangle[triangle._id][a];
		var triangles = lowpoly.trianglesForAnchor[anchor._id];
		$.each(triangles, function(i) {
			if (triangles[i] === triangle) {
				triangles.splice(i, 1);
				return false;
			}
		});
	}
	delete lowpoly.anchorsForTriangle[triangle._id];
	var layer = triangle.getLayer();
	triangle.destroy();
	layer.draw();
}

lowpoly.deleteLine = function(line)
{
	for (a in lowpoly.anchorsForLine[line._id])
	{
		var anchor = lowpoly.anchorsForLine[line._id][a];
		var lines = lowpoly.linesWithAnchor[anchor._id];
		$.each(lines, function(i) {
		    if (lines[i] === line) {
		        lines.splice(i,1);
		        return false;
		    }
		});
	}
	var triangles0 = lowpoly.trianglesForAnchor[lowpoly.anchorsForLine[line._id][0]._id];
	var triangles1 = lowpoly.trianglesForAnchor[lowpoly.anchorsForLine[line._id][1]._id];
	// for (t in triangles0)
	var t = 0;
	while (t < triangles0.length)
	{
		if ($.inArray(triangles0[t], triangles1) != -1)
			lowpoly.deleteTriangle(triangles0[t]);
		else
			++t;
	}
	delete lowpoly.anchorsForLine[line._id];
	var layer = line.getLayer();
	line.destroy();
	layer.draw();
}

lowpoly.deleteAnchor = function(anchor)
{
	var connections = [];
	// for (l in lowpoly.linesWithAnchor[anchor._id])
	while(lowpoly.linesWithAnchor[anchor._id].length != 0)
	{
		var line = lowpoly.linesWithAnchor[anchor._id][0];
		var anchors = lowpoly.anchorsForLine[line._id];
		if (anchors[0] === anchor)
			connections.push(anchors[1]);
		else
			connections.push(anchors[0]);
		lowpoly.deleteLine(line);
	}
	delete lowpoly.linesWithAnchor[anchor._id];
	var layer = anchor.getLayer();
	anchor.destroy();
	layer.draw();
	return connections;
}
<|endoftext|>


<commit_before>'use strict';

const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600});

  // and load the index.html of the app.
  mainWindow.loadURL('http://devdocs.io');

  // Open the DevTools.
  // mainWindow.webContents.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
});
<commit_msg>Switch to HTTPS<commit_after>'use strict';

const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600});

  // and load the index.html of the app.
  mainWindow.loadURL('https://devdocs.io');

  // Open the DevTools.
  // mainWindow.webContents.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
require('../server.babel'); // babel registration (runtime transpilation for node)
var path = require('path');
var rootDir = path.resolve(__dirname, '..');

process.env.PORT = 3000;

/**
 * Define isomorphic constants.
 */
global.__CLIENT__ = false;
global.__SERVER__ = true;
global.__DISABLE_SSR__ = false;  // <----- DISABLES SERVER SIDE RENDERING FOR ERROR DEBUGGING
global.__DEVELOPMENT__ = process.env.NODE_ENV !== 'production';

if (__DEVELOPMENT__) {
  if (!require('piping')({
      hook: true,
      ignore: /(\/\.|~$|\.json|\.scss$)/i
    })) {
    return;
  }
}

// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
var WebpackIsomorphicTools = require('webpack-isomorphic-tools');
global.webpackIsomorphicTools = new WebpackIsomorphicTools(require('../webpack/webpack-isomorphic-tools'))
  .development(__DEVELOPMENT__)
  .server(rootDir, function() {
    require('../src/server');
  });
<commit_msg>Port 6001<commit_after>#!/usr/bin/env node
require('../server.babel'); // babel registration (runtime transpilation for node)
var path = require('path');
var rootDir = path.resolve(__dirname, '..');

process.env.PORT = 6001;

/**
 * Define isomorphic constants.
 */
global.__CLIENT__ = false;
global.__SERVER__ = true;
global.__DISABLE_SSR__ = false;  // <----- DISABLES SERVER SIDE RENDERING FOR ERROR DEBUGGING
global.__DEVELOPMENT__ = process.env.NODE_ENV !== 'production';

if (__DEVELOPMENT__) {
  if (!require('piping')({
      hook: true,
      ignore: /(\/\.|~$|\.json|\.scss$)/i
    })) {
    return;
  }
}

// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
var WebpackIsomorphicTools = require('webpack-isomorphic-tools');
global.webpackIsomorphicTools = new WebpackIsomorphicTools(require('../webpack/webpack-isomorphic-tools'))
  .development(__DEVELOPMENT__)
  .server(rootDir, function() {
    require('../src/server');
  });
<|endoftext|>


<commit_before>'use strict'
const context = canvas.getContext('2d')

// Lets not hamper any further keypresses shall we?
window.onkeydown = e => e.keyCode===32?start():e

/* TODO:
 * - unit testing.
 * - something more fun, sync it up with a node server somehow?
 * - multiple particle types:
 *   -  default (atoms?)
 *   -  mist????
 * - more shiny good stuff.
 * - GUI
 * - actual particle behaviour:
 *   - point gravity.
 *   - motion.
 *   - containment.
 *   - collicions.
 *   - steering behaviour:
 *     - AI in a particle engine? yes, go fuck yourself if you don't know about steering behaviour.
 *     - seriously go feel a wicked degree of shame mate.
 * - mouse / pointer modes:
 *   - create / emit.
 *   - gravitate.
 *   - contain.
 *   - grab.
 */

const rand = i => {
    i = i || 1
    return i * Math.random()
}

// Particle constructor.
const particle = _ => { return {
    coords: {
        x: rand(canvas.width),
        y: rand(canvas.height)
    },
    acc: {
        x: rand(2)-1,
        y: rand(2)-1
    },
    color: `hsla(${rand(360)},100%,58%,1)`,
    mass: 20 + rand(20),
    type: 'particle',
    // It might be a wise move to let the behaviour be independent of the looks.
    shape: 'round',
}}

// A place to store all these particles... I need to sanitize the naming conventions.
let particleArr = []

// Overly big render object, might be smarter to do this as a function instead.
const render = {
    particle : (particle, fill) => {
        context.fillStyle = particle.color
        context.beginPath()
        context.arc(particle.coords.x,particle.coords.y,particle.mass,0,Math.PI*2)

        // Take a second look at below.
        fill || context.fill()
        context.closePath()
    },
    square : particle => {
        context.fillStyle = particle.color
        context.fillRect(particle.coords.x,particle.coords.y, particle.mass,  particle.mass)
        context.fill()
    },

}

// Moving stuff here.

const gravity = (particle, entity) => {
    const force = 9.81
    const distance = {
        x: particle.coords.x - entity.coords.x,
        y: particle.coords.y - entity.coords.y,
    }
    // logic here :p.
}

const move = particle => {
    particle.coords.x += particle.acc.x
    particle.coords.y += particle.acc.y
}

// Saving stuff below.

const save = _ => localStorage.setItem('particles', JSON.stringify(particleArr))

const load = _ => particleArr = JSON.parse(localStorage.getItem('particles'))

// Stuff for running the darn thing.

const start = _ => {
    let i = 100

    particleArr = []

    while (i--)
        particleArr.push(particle())
    console.log(particleArr)
}

const main = _ => {
    // Rate at which it runs doesn't matter.
    requestAnimationFrame(main)
    context.fillStyle='#FFF'
    context.fillRect(0,0,canvas.width,canvas.height)
    particleArr.forEach( particle => {
        move(particle)
        render.square(particle)
    })
}

start()
main()<commit_msg>PEWPEWPEW<commit_after>'use strict'
const context = canvas.getContext('2d')

// Lets not hamper any further keypresses shall we?
window.onkeydown = e => e.keyCode===32?start():e

/* TODO:
 * - unit testing.
 * - something more fun, sync it up with a node server somehow?
 * - multiple particle types:
 *   -  default (atoms?)
 *   -  mist????
 * - more shiny good stuff.
 * - GUI
 * - actual particle behaviour:
 *   - point gravity.
 *   - motion.
 *   - containment.
 *   - collicions.
 *   - steering behaviour:
 *     - AI in a particle engine? yes, go fuck yourself if you don't know about steering behaviour.
 *     - seriously go feel a wicked degree of shame mate.
 * - mouse / pointer modes:
 *   - create / emit.
 *   - gravitate.
 *   - contain.
 *   - grab.
 */

const mouse = {
    emit : ev => particleArr.push(particle(ev.clientX,ev.clientY)),
    pew : ev => {
        let i = 10
        while (i--){
            particleArr.push(particle(ev.clientX,ev.clientY))
        }
    },
}

window.onclick = mouse.pew

const rand = i => {
    i = i || 1
    return i * Math.random()
}

// Particle constructor.
const particle = (x,y) => { return {
    coords: {
        x: x || rand(canvas.width),
        y: y || rand(canvas.height)
    },
    acc: {
        x: rand(2)-1,
        y: rand(2)-1
    },
    color: `hsla(${rand(360)},100%,58%,1)`,
    mass: 20 + rand(20),
    type: 'particle',
    // It might be a wise move to let the behaviour be independent of the looks.
    shape: 'round',
}}

// A place to store all these particles... I need to sanitize the naming conventions.
let particleArr = []

// Overly big render object, might be smarter to do this as a function instead.
const render = {
    particle : (particle, fill) => {
        context.fillStyle = particle.color
        context.beginPath()
        context.arc(particle.coords.x,particle.coords.y,particle.mass,0,Math.PI*2)

        // Take a second look at below.
        fill || context.fill()
        context.closePath()
    },
    square : particle => {
        context.fillStyle = particle.color
        context.fillRect(particle.coords.x,particle.coords.y, particle.mass,  particle.mass)
        context.fill()
    },

}

// Moving stuff here.

const gravity = (particle, entity) => {
    const force = 9.81
    const distance = {
        x: particle.coords.x - entity.coords.x,
        y: particle.coords.y - entity.coords.y,
    }
    // logic here :p.
}

const move = particle => {
    particle.coords.x += particle.acc.x
    particle.coords.y += particle.acc.y
}

const collide = entity => {
    particleArr.forEach(particle => entity.coords == particle.coords ? particle.color = "": "" )
}

// Saving stuff below.

const save = _ => localStorage.setItem('particles', JSON.stringify(particleArr))

const load = _ => particleArr = JSON.parse(localStorage.getItem('particles'))

// Stuff for running the darn thing.

const start = _ => {
    let i = 100

    particleArr = []

    while (i--)
        particleArr.push(particle())
    console.log(particleArr)
}

const main = _ => {
    // Rate at which it runs doesn't matter.
    requestAnimationFrame(main)
    context.fillStyle='#FFF'
    context.fillRect(0,0,canvas.width,canvas.height)
    particleArr.forEach( particle => {
        move(particle)
        render.square(particle)
    })
}

start()
main()<|endoftext|>


<commit_before>var MedicineAccountsCard = {
    name: 'MedicineAccountsCard',
    dom_target: undefined,

    render_init: function() {
        MedicineAccountsCard._render();
    },

    _render: function() {
        var source   = $("#accounts_medicine").html();
        var template = Handlebars.compile(source);
        var compiled = template({"card_name": AccountsCard.name});
        MedicineAccountsCard.dom_target.html(compiled);
    }
};
<commit_msg>swapping acct card name<commit_after>var MedicineAccountsCard = {
    name: 'MedicineAccountsCard',
    dom_target: undefined,

    render_init: function() {
        MedicineAccountsCard._render();
    },

    _render: function() {
        var source   = $("#accounts_medicine").html();
        var template = Handlebars.compile(source);
        var compiled = template({"card_name": MedicineAccountsCard.name});
        MedicineAccountsCard.dom_target.html(compiled);
    }
};
<|endoftext|>