<commit_before>module('users.timfelgentreff.babelsberg.PerformanceTests').requires('lively.TestFramework', 'users.timfelgentreff.babelsberg.constraintinterpreter').toRun(function() {

TestCase.subclass('users.timfelgentreff.babelsberg.PerformanceTests.PerformanceTests', {
    Iterations: 10000,
    testImperativeDragSimulation: function () {
        var mouse = {},
            mercury = {},
            thermometer = {},
            temperature = 0,
            gray = {},
            white = {},
            display = {};

        for (var i = 0; i < this.Iterations; i++) {
            mouse.location_y = i
            var old = mercury.top
            mercury.top = mouse.location_y
            if (mercury.top > thermometer.top) {
                mercury.top = thermometer.top
            }
            temperature = mercury.top
            if (old < mercury.top) {
                // moves upwards (draws over the white)
                gray.top = mercury.top
            } else {
                // moves downwards (draws over the gray)
                white.bottom = mercury.top
            }
            display.number = temperature
        }
    },
    setUp: function() {
        this.thermometer = lively.PartsBin.getPart("Thermometer", "users/timfelgentreff/PartsBin/");
        this.thermometer.remove();
        var sumObj = {a: 1, b: 1, c:1, d:1, e:1};
        this.sumObj = sumObj;
        this.sumObj2 = {
            get a() { return this.$$a }, $$a: 0,
            get b() { return this.$$b }, $$b: 0,
            get c() { return this.$$c }, $$c: 0,
            get d() { return this.$$d }, $$d: 0,
            get e() { return this.$$e }, $$e: 0,
        }
        bbb.unconstrain(this, "constrainedSumObj");
        this.constrainedSumObj = {a: 1, b: 1, c:1, d:1, e:1};
        this.constraint = bbb.always({solver: new ClSimplexSolver(), ctx: {self: this}}, function () {
            return self.constrainedSumObj.a == 1 &&
                    self.constrainedSumObj.b == 1 &&
                    self.constrainedSumObj.c == 1 &&
                    self.constrainedSumObj.d == 1 &&
                    self.constrainedSumObj.e == 1
        });
    },

    testThermometer: function() {
        var c = this.thermometer.get("Celsius");
        for(var i = 0; i < 100; i++) {
            try {
                c.value = (i % 30) / 100.0;
            } catch(e) {} // ignore
        }
    },
    testMidpointEdit: function() {
        var cassowary = new ClSimplexSolver(),
            deltablue = new DBPlanner();
        cassowary.setAutosolve(false);
        hand = $world.firstHand();

        pos = hand.getPosition().addPt(pt(200, 0));
        start = $part('Rectangle', 'PartsBin/Basic').openInWorld(pos);
        end = $part('Rectangle', 'PartsBin/Basic').openInWorld(pos.addXY(100,100));
        [start,end].invoke('applyStyle', {extent: pt(10,10)});
        midP = $part('Ellipse', 'PartsBin/Basic').openInWorld(pos);
        midP.setExtent(pt(20,20));

        // ugly: we need a script to force render refresh
        midP.addScript(function update() {
            this.setPosition(this.getPosition());
            start.setPosition(start.getPosition());
        });
        midP.startStepping(100, 'update') // this can be solved with an additional DeltaBlue constraint
                                          // see the C/F converter label update for code -- Tim

        // constraint
        (function () {
            var center = start.getPosition().addPt(end.getPosition()).scaleBy(0.5);
            return midP.getPosition().eqPt(center);
        }).shouldBeTrue({midP: midP, start: start, end: end});

        // start editing.
        // first argument is the object to be edited, the second a list of accessors or fields
        // note that in the JavaScript implementation, the accessor methods have to return a single value
        // the Ruby version does not have this limitation (so we could write
        //      bbb.edit(start, ["getPosition"])
        // ), but I haven't ported that, yet.
        editCallback = bbb.edit(start.getPosition(), ["x", "y"]);
        this.onMouseMove = function (evt) {
            editCallback(evt.getPosition().addPt(pt(20, 20)));
        }

        // end edit by calling callback without values
        editCallback();
        editCallback = null;

        // cleanup
        this.onMouseMove = function (evt) {};
        [start,end,midP].invoke('remove');
        start = end = midP = hand = null;
    },

    testDeclarativeDragSimulation: function () {
        var ctx = {
                mouse: {location_y: 0},
                mercury: {top: 0, bottom: 0},
                thermometer: {top: 0, bottom: 0},
                temperature: {c: 0},
                gray: {top: 0, bottom: 0},
                white: {top: 0, bottom: 0},
                display: {number: 0}},
            solver = new ClSimplexSolver();
        solver.setAutosolve(false);

        bbb.always({solver: solver, ctx: ctx}, function () { return temperature.c == mercury.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return white.top == thermometer.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return white.bottom == mercury.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return gray.top == mercury.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return gray.bottom == mercury.bottom });
        bbb.always({solver: solver, ctx: ctx}, function () { return display.number == temperature.c });
        bbb.always({solver: solver, ctx: ctx}, function () { return mercury.top == mouse.location_y });
        bbb.always({solver: solver, ctx: ctx}, function () { return mercury.top <= thermometer.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return mercury.bottom == thermometer.bottom });

        for (var i = 0; i < this.Iterations; i++) {
            ctx.mouse.location_y = i
        }
    },

    testEditDragSimulation: function () {
        var ctx = {
                mouse: {location_y: 0},
                mercury: {top: 0, bottom: 0},
                thermometer: {top: 0, bottom: 0},
                temperature: {c: 0},
                gray: {top: 0, bottom: 0},
                white: {top: 0, bottom: 0},
                display: {number: 0}};
        var solver = new ClSimplexSolver();

        bbb.always({solver: solver, ctx: ctx}, function () { return temperature.c == mercury.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return white.top == thermometer.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return white.bottom == mercury.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return gray.top == mercury.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return gray.bottom == mercury.bottom });
        bbb.always({solver: solver, ctx: ctx}, function () { return display.number == temperature.c });
        bbb.always({solver: solver, ctx: ctx}, function () { return mercury.top == mouse.location_y });
        bbb.always({solver: solver, ctx: ctx}, function () { return mercury.top <= thermometer.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return mercury.bottom == thermometer.bottom });

        var cb = bbb.edit(ctx.mouse, ["location_y"]);
        for (var i = 0; i < this.Iterations; i++) {
            cb(i);
        }
        // cb();
    },
    testLibraryEditDragSimulation: function () {
        var ctx = {
                mouse: {location_y: 0},
                mercury: {top: 0, bottom: 0},
                thermometer: {top: 0, bottom: 0},
                temperature: {c: 0},
                gray: {top: 0, bottom: 0},
                white: {top: 0, bottom: 0},
                display: {number: 0}};
        var solver = new ClSimplexSolver();
        solver.setAutosolve(false);

        var cctx = {
            mouse_loc_y: new ClVariable(),
            mercury_top: new ClVariable(),
            mercury_bottom: new ClVariable(),
            thermometer_top: new ClVariable(),
            thermometer_bottom: new ClVariable(),
            temperature_c: new ClVariable(),
            gray_top: new ClVariable(),
            gray_bottom: new ClVariable(),
            white_top: new ClVariable(),
            white_bottom: new ClVariable(),
            display_number: new ClVariable(),
        };

        solver.addConstraint(cctx.mercury_top.cnEquals(cctx.temperature_c));
        solver.addConstraint(cctx.white_top.cnEquals(cctx.thermometer_top));
        solver.addConstraint(cctx.white_bottom.cnEquals(cctx.mercury_top));
        solver.addConstraint(cctx.gray_top.cnEquals(cctx.mercury_top));
        solver.addConstraint(cctx.gray_bottom.cnEquals(cctx.mercury_bottom));
        solver.addConstraint(cctx.display_number.cnEquals(cctx.temperature_c));
        solver.addConstraint(cctx.mercury_top.cnEquals(cctx.mouse_loc_y));
        solver.addConstraint(cctx.mercury_top.cnEquals(cctx.thermometer_top));
        solver.addConstraint(cctx.mercury_bottom.cnEquals(cctx.thermometer_bottom));

        solver.addEditVar(cctx.mouse_loc_y);
        solver.beginEdit();
        for (var i = 0; i < this.Iterations; i++) {
            solver.resolveArray([i]);
            ctx.mouse.location_y = cctx.mouse_loc_y.value()
            ctx.mercury.top = cctx.mercury_top.value()
            ctx.mercury.bottom = cctx.mercury_bottom.value()
            ctx.thermometer.top = cctx.thermometer_top.value()
            ctx.thermometer.bottom = cctx.thermometer_bottom.value()
            ctx.temperature.c = cctx.temperature_c.value()
            ctx.gray.top = cctx.gray_top.value()
            ctx.gray.bottom = cctx.gray_bottom.value()
            ctx.white.top = cctx.white_top.value()
            ctx.white.bottom = cctx.white_bottom.value()
            ctx.display.number = cctx.display_number.value()
        }
        solver.endEdit();
    },

    testReadAccessPerformance: function() {
        for (var i = 0; i < this.Iterations; i++) {
            this.sumObj.a + this.sumObj.b + this.sumObj.c + this.sumObj.d + this.sumObj.e
        }
    },
    testReadAccessPerformanceWithProperties: function() {
        var sum = 0;
        for (var i = 0; i < this.Iterations; i++) {
            sum += this.sumObj2.a + this.sumObj2.b + this.sumObj2.c + this.sumObj2.d + this.sumObj2.e
        }
    },

    testReadAccessConstrainedPerformance: function() {
        for (var i = 0; i < this.Iterations; i++) {
            this.constrainedSumObj.a + this.constrainedSumObj.b +
                this.constrainedSumObj.c + this.constrainedSumObj.d +
                this.constrainedSumObj.e
        }
    },
    testReadAccessConstraintDisabledPerformance: function() {
        this.constraint.disable()
        for (var i = 0; i < this.Iterations; i++) {
            this.constrainedSumObj.a + this.constrainedSumObj.b +
                this.constrainedSumObj.c + this.constrainedSumObj.d +
                this.constrainedSumObj.e
        }
    },
    testCreatingConstraint: function() {
        var c = new ClSimplexSolver(),
            a = pt(0,0);
        bbb.always({
            ctx: {
                a: a,
                _$_self: this.doitContext || this
            },
            solver: c
        }, function() {
            return a.equals(a);;
        });
    },

    testReadAccessUnconstrainedPerformance: function() {
        this.constraint.disable()
        bbb.unconstrain(this.constrainedSumObj);
        for (var i = 0; i < this.Iterations; i++) {
            this.constrainedSumObj.a + this.constrainedSumObj.b +
                this.constrainedSumObj.c + this.constrainedSumObj.d +
                this.constrainedSumObj.e
        }
    },});

}) // end of module
<commit_msg>Fix testEditDragSimulation() to using edit callback correctly, now it's slower than testDeclarativeDragSimulation()<commit_after>module('users.timfelgentreff.babelsberg.PerformanceTests').requires('lively.TestFramework', 'users.timfelgentreff.babelsberg.constraintinterpreter').toRun(function() {

TestCase.subclass('users.timfelgentreff.babelsberg.PerformanceTests.PerformanceTests', {
    Iterations: 10000,
    testImperativeDragSimulation: function () {
        var mouse = {},
            mercury = {},
            thermometer = {},
            temperature = 0,
            gray = {},
            white = {},
            display = {};

        for (var i = 0; i < this.Iterations; i++) {
            mouse.location_y = i
            var old = mercury.top
            mercury.top = mouse.location_y
            if (mercury.top > thermometer.top) {
                mercury.top = thermometer.top
            }
            temperature = mercury.top
            if (old < mercury.top) {
                // moves upwards (draws over the white)
                gray.top = mercury.top
            } else {
                // moves downwards (draws over the gray)
                white.bottom = mercury.top
            }
            display.number = temperature
        }
    },
    setUp: function() {
        this.thermometer = lively.PartsBin.getPart("Thermometer", "users/timfelgentreff/PartsBin/");
        this.thermometer.remove();
        var sumObj = {a: 1, b: 1, c:1, d:1, e:1};
        this.sumObj = sumObj;
        this.sumObj2 = {
            get a() { return this.$$a }, $$a: 0,
            get b() { return this.$$b }, $$b: 0,
            get c() { return this.$$c }, $$c: 0,
            get d() { return this.$$d }, $$d: 0,
            get e() { return this.$$e }, $$e: 0,
        }
        bbb.unconstrain(this, "constrainedSumObj");
        this.constrainedSumObj = {a: 1, b: 1, c:1, d:1, e:1};
        this.constraint = bbb.always({solver: new ClSimplexSolver(), ctx: {self: this}}, function () {
            return self.constrainedSumObj.a == 1 &&
                    self.constrainedSumObj.b == 1 &&
                    self.constrainedSumObj.c == 1 &&
                    self.constrainedSumObj.d == 1 &&
                    self.constrainedSumObj.e == 1
        });
    },

    testThermometer: function() {
        var c = this.thermometer.get("Celsius");
        for(var i = 0; i < 100; i++) {
            try {
                c.value = (i % 30) / 100.0;
            } catch(e) {} // ignore
        }
    },
    testMidpointEdit: function() {
        var cassowary = new ClSimplexSolver(),
            deltablue = new DBPlanner();
        cassowary.setAutosolve(false);
        hand = $world.firstHand();

        pos = hand.getPosition().addPt(pt(200, 0));
        start = $part('Rectangle', 'PartsBin/Basic').openInWorld(pos);
        end = $part('Rectangle', 'PartsBin/Basic').openInWorld(pos.addXY(100,100));
        [start,end].invoke('applyStyle', {extent: pt(10,10)});
        midP = $part('Ellipse', 'PartsBin/Basic').openInWorld(pos);
        midP.setExtent(pt(20,20));

        // ugly: we need a script to force render refresh
        midP.addScript(function update() {
            this.setPosition(this.getPosition());
            start.setPosition(start.getPosition());
        });
        midP.startStepping(100, 'update') // this can be solved with an additional DeltaBlue constraint
                                          // see the C/F converter label update for code -- Tim

        // constraint
        (function () {
            var center = start.getPosition().addPt(end.getPosition()).scaleBy(0.5);
            return midP.getPosition().eqPt(center);
        }).shouldBeTrue({midP: midP, start: start, end: end});

        // start editing.
        // first argument is the object to be edited, the second a list of accessors or fields
        // note that in the JavaScript implementation, the accessor methods have to return a single value
        // the Ruby version does not have this limitation (so we could write
        //      bbb.edit(start, ["getPosition"])
        // ), but I haven't ported that, yet.
        editCallback = bbb.edit(start.getPosition(), ["x", "y"]);
        this.onMouseMove = function (evt) {
            editCallback(evt.getPosition().addPt(pt(20, 20)));
        }

        // end edit by calling callback without values
        editCallback();
        editCallback = null;

        // cleanup
        this.onMouseMove = function (evt) {};
        [start,end,midP].invoke('remove');
        start = end = midP = hand = null;
    },

    testDeclarativeDragSimulation: function () {
        var ctx = {
                mouse: {location_y: 0},
                mercury: {top: 0, bottom: 0},
                thermometer: {top: 0, bottom: 0},
                temperature: {c: 0},
                gray: {top: 0, bottom: 0},
                white: {top: 0, bottom: 0},
                display: {number: 0}},
            solver = new ClSimplexSolver();
        solver.setAutosolve(false);

        bbb.always({solver: solver, ctx: ctx}, function () { return temperature.c == mercury.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return white.top == thermometer.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return white.bottom == mercury.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return gray.top == mercury.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return gray.bottom == mercury.bottom });
        bbb.always({solver: solver, ctx: ctx}, function () { return display.number == temperature.c });
        bbb.always({solver: solver, ctx: ctx}, function () { return mercury.top == mouse.location_y });
        bbb.always({solver: solver, ctx: ctx}, function () { return mercury.top <= thermometer.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return mercury.bottom == thermometer.bottom });

        for (var i = 0; i < this.Iterations; i++) {
            ctx.mouse.location_y = i
        }
    },

    testEditDragSimulation: function () {
        var ctx = {
                mouse: {location_y: 0},
                mercury: {top: 0, bottom: 0},
                thermometer: {top: 0, bottom: 0},
                temperature: {c: 0},
                gray: {top: 0, bottom: 0},
                white: {top: 0, bottom: 0},
                display: {number: 0}};
        var solver = new ClSimplexSolver();

        bbb.always({solver: solver, ctx: ctx}, function () { return temperature.c == mercury.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return white.top == thermometer.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return white.bottom == mercury.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return gray.top == mercury.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return gray.bottom == mercury.bottom });
        bbb.always({solver: solver, ctx: ctx}, function () { return display.number == temperature.c });
        bbb.always({solver: solver, ctx: ctx}, function () { return mercury.top == mouse.location_y });
        bbb.always({solver: solver, ctx: ctx}, function () { return mercury.top <= thermometer.top });
        bbb.always({solver: solver, ctx: ctx}, function () { return mercury.bottom == thermometer.bottom });

        var cb = bbb.edit(ctx.mouse, ["location_y"]);
        for (var i = 0; i < this.Iterations; i++) {
            cb([i]);
        }
        // cb();
    },
    testLibraryEditDragSimulation: function () {
        var ctx = {
                mouse: {location_y: 0},
                mercury: {top: 0, bottom: 0},
                thermometer: {top: 0, bottom: 0},
                temperature: {c: 0},
                gray: {top: 0, bottom: 0},
                white: {top: 0, bottom: 0},
                display: {number: 0}};
        var solver = new ClSimplexSolver();
        solver.setAutosolve(false);

        var cctx = {
            mouse_loc_y: new ClVariable(),
            mercury_top: new ClVariable(),
            mercury_bottom: new ClVariable(),
            thermometer_top: new ClVariable(),
            thermometer_bottom: new ClVariable(),
            temperature_c: new ClVariable(),
            gray_top: new ClVariable(),
            gray_bottom: new ClVariable(),
            white_top: new ClVariable(),
            white_bottom: new ClVariable(),
            display_number: new ClVariable(),
        };

        solver.addConstraint(cctx.mercury_top.cnEquals(cctx.temperature_c));
        solver.addConstraint(cctx.white_top.cnEquals(cctx.thermometer_top));
        solver.addConstraint(cctx.white_bottom.cnEquals(cctx.mercury_top));
        solver.addConstraint(cctx.gray_top.cnEquals(cctx.mercury_top));
        solver.addConstraint(cctx.gray_bottom.cnEquals(cctx.mercury_bottom));
        solver.addConstraint(cctx.display_number.cnEquals(cctx.temperature_c));
        solver.addConstraint(cctx.mercury_top.cnEquals(cctx.mouse_loc_y));
        solver.addConstraint(cctx.mercury_top.cnEquals(cctx.thermometer_top));
        solver.addConstraint(cctx.mercury_bottom.cnEquals(cctx.thermometer_bottom));

        solver.addEditVar(cctx.mouse_loc_y);
        solver.beginEdit();
        for (var i = 0; i < this.Iterations; i++) {
            solver.resolveArray([i]);
            ctx.mouse.location_y = cctx.mouse_loc_y.value()
            ctx.mercury.top = cctx.mercury_top.value()
            ctx.mercury.bottom = cctx.mercury_bottom.value()
            ctx.thermometer.top = cctx.thermometer_top.value()
            ctx.thermometer.bottom = cctx.thermometer_bottom.value()
            ctx.temperature.c = cctx.temperature_c.value()
            ctx.gray.top = cctx.gray_top.value()
            ctx.gray.bottom = cctx.gray_bottom.value()
            ctx.white.top = cctx.white_top.value()
            ctx.white.bottom = cctx.white_bottom.value()
            ctx.display.number = cctx.display_number.value()
        }
        solver.endEdit();
    },

    testReadAccessPerformance: function() {
        for (var i = 0; i < this.Iterations; i++) {
            this.sumObj.a + this.sumObj.b + this.sumObj.c + this.sumObj.d + this.sumObj.e
        }
    },
    testReadAccessPerformanceWithProperties: function() {
        var sum = 0;
        for (var i = 0; i < this.Iterations; i++) {
            sum += this.sumObj2.a + this.sumObj2.b + this.sumObj2.c + this.sumObj2.d + this.sumObj2.e
        }
    },

    testReadAccessConstrainedPerformance: function() {
        for (var i = 0; i < this.Iterations; i++) {
            this.constrainedSumObj.a + this.constrainedSumObj.b +
                this.constrainedSumObj.c + this.constrainedSumObj.d +
                this.constrainedSumObj.e
        }
    },
    testReadAccessConstraintDisabledPerformance: function() {
        this.constraint.disable()
        for (var i = 0; i < this.Iterations; i++) {
            this.constrainedSumObj.a + this.constrainedSumObj.b +
                this.constrainedSumObj.c + this.constrainedSumObj.d +
                this.constrainedSumObj.e
        }
    },
    testCreatingConstraint: function() {
        var c = new ClSimplexSolver(),
            a = pt(0,0);
        bbb.always({
            ctx: {
                a: a,
                _$_self: this.doitContext || this
            },
            solver: c
        }, function() {
            return a.equals(a);;
        });
    },

    testReadAccessUnconstrainedPerformance: function() {
        this.constraint.disable()
        bbb.unconstrain(this.constrainedSumObj);
        for (var i = 0; i < this.Iterations; i++) {
            this.constrainedSumObj.a + this.constrainedSumObj.b +
                this.constrainedSumObj.c + this.constrainedSumObj.d +
                this.constrainedSumObj.e
        }
    },});

}) // end of module
<|endoftext|>


<commit_before>/**
* Copyright 2011 Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

var fs = require('fs');
var path = require('path');
var xml2js = require('xml2js');
var assert = require('assert');
var pfx2pem = require('../../util/certificates/pkcs').pfx2pem;

exports.init = function (cli) {

  var log = cli.output;

  var account = cli.category('account');

  var config = cli.category('config')
        .description('Manage tool local settings');

  config.command('list')
        .whiteListPowershell()
        .description('Display config settings')
        .action(function (options) {
          log.info('Displaying config settings');

          var cfg = account.readConfig();

          log.table(cfg, function (row, name) {
            row.cell('Setting', name);
            row.cell('Value', cfg[name]);
          });
        });

  config.command('set <name> <value>')

        .usage('<name> <value>')

        .whiteListPowershell()
        .description('Change a config setting')
        .action(function (name, value, options) {
          var cfg = account.readConfig();
          if(name === 'endpoint') {
            endpointInfo = validateEndpoint(value);
            log.info('Setting \'port\' to value \'' + endpointInfo.endpointPort + '\'');
            cfg['port'] = endpointInfo.endpointPort;
            value = endpointInfo.endpointHost;
          }

          log.info('Setting \'' + name + '\' to value \'' + value + '\'');
          cfg[name] = value;
          account.writeConfig(cfg);
          log.info('Changes saved.');
        });

  var azurePath = path.join(homeFolder(), '.azure');
  var azureConfigPath = path.join(azurePath, 'config.json');

  config.readConfig = function () {
    var cfg = {};
    log.silly('Reading config', azureConfigPath);

    if (path.existsSync(azureConfigPath)) {
      try {
        cfg = JSON.parse(fs.readFileSync(azureConfigPath));
      } catch (err) {
        log.warn('Unable to read settings');
        cfg = {};
      }
      log.json('silly', cfg);
    }

    return cfg;
  };

  config.writeConfig = function (cfg) {
    if (!path.existsSync(azurePath)) {
      log.silly('Creating folder', azurePath);
      fs.mkdirSync(azurePath, 502); //0766
    }

    log.silly('Writing config', azureConfigPath);
    fs.writeFileSync(azureConfigPath, JSON.stringify(cfg));
  };

  config.clearConfig = function() {
    log.silly('Removing', azureConfigPath);
    if (path.existsSync(azureConfigPath)) {
      fs.unlinkSync(azureConfigPath);
      return true;
    }
  };

  // added temporarily for back-compat
  cli.category('account').readConfig = config.readConfig;
  cli.category('account').writeConfig = config.writeConfig;
  cli.category('account').clearConfig = config.clearConfig;

  // apply any persistant switches at load-time
  function applyGlobalSettings() {
    var cfg = config.readConfig();
    if (!cfg) {
      return;
    }

    if (cfg.labels === 'off') {
      log.format({ terse: true });
    }

    if (cfg.logo === 'off') {
      log.format({ logo: 'off' });
    } else {
      log.format({ logo: 'on' });
    }
  }

  applyGlobalSettings();

  function homeFolder() {
    if (process.env.HOME !== undefined) {
      return process.env.HOME;
    }

    if (process.env.HOMEDRIVE && process.env.HOMEPATH) {
      return process.env.HOMEDRIVE + process.env.HOMEPATH;
    }

    throw new Error('No HOME path available');
  }

  function validateEndpoint(endpoint) {
    var parts = endpoint.split('://');
    var hostname = parts[0];
    if(parts.length > 2){
      throw Error('Invalid Url');
    } else if (parts.length === 2) {
       if(!parts[0]) {
        throw Error('Invalid Url');
       }

       if((parts[0] !== 'https') && (parts[0] !== 'HTTPS')) {
          throw Error('Only https protocol supported in the endpoint');
       }

       hostname = parts[1];
    }

    var parts2 = hostname.split('/');

    // Check url contain path(s) after the hostname if so error
    // This will handle in case if user pass endpoint value starting
    // with / char
    if(parts2.length > 2 || (parts2.length === 2 && parts2[1])) {
      throw Error('Invalid Url');
    }

    var parts3 = (parts2[0]).split(':');

    port = 443;
    // Check host name contain ':', if so only one and it should be
    // followed by a valid port number
    if(parts3.length > 2) {
      throw Error('Invalid Url');
    } else if(parts3.length === 2) {
      if(!parts3[1]) {
        throw Error('Invalid Url');
      }

      var intValue = parseInt(parts3[1], 10);
      if (intValue != parts3[1] || parts3[1] < 1 || parts3[1] > 65535) {
        throw Error('Port number should be a number in the range [1, 65535]');
      }

      port = intValue;
    }

    return {endpointHost: parts3[0], endpointPort: port};
  }
};
<commit_msg>output user-frendly 'No config settings found' if this is the case<commit_after>/**
* Copyright 2011 Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

var fs = require('fs');
var path = require('path');
var xml2js = require('xml2js');
var assert = require('assert');
var pfx2pem = require('../../util/certificates/pkcs').pfx2pem;

exports.init = function (cli) {

  var log = cli.output;

  var account = cli.category('account');

  var config = cli.category('config')
        .description('Manage tool local settings');

  config.command('list')
        .whiteListPowershell()
        .description('Display config settings')
        .action(function (options) {
          log.info('Displaying config settings');

          var cfg = account.readConfig();
          if (!log.format().json && Object.keys(cfg).length === 0) {
            log.info('No config values found');
            return;
          }
          log.table(cfg, function (row, name) {
            row.cell('Setting', name);
            row.cell('Value', cfg[name]);
          });
        });

  config.command('set <name> <value>')

        .usage('<name> <value>')

        .whiteListPowershell()
        .description('Change a config setting')
        .action(function (name, value, options) {
          var cfg = account.readConfig();
          if(name === 'endpoint') {
            endpointInfo = validateEndpoint(value);
            log.info('Setting \'port\' to value \'' + endpointInfo.endpointPort + '\'');
            cfg['port'] = endpointInfo.endpointPort;
            value = endpointInfo.endpointHost;
          }

          log.info('Setting \'' + name + '\' to value \'' + value + '\'');
          cfg[name] = value;
          account.writeConfig(cfg);
          log.info('Changes saved.');
        });

  var azurePath = path.join(homeFolder(), '.azure');
  var azureConfigPath = path.join(azurePath, 'config.json');

  config.readConfig = function () {
    var cfg = {};
    log.silly('Reading config', azureConfigPath);

    if (path.existsSync(azureConfigPath)) {
      try {
        cfg = JSON.parse(fs.readFileSync(azureConfigPath));
      } catch (err) {
        log.warn('Unable to read settings');
        cfg = {};
      }
      log.json('silly', cfg);
    }

    return cfg;
  };

  config.writeConfig = function (cfg) {
    if (!path.existsSync(azurePath)) {
      log.silly('Creating folder', azurePath);
      fs.mkdirSync(azurePath, 502); //0766
    }

    log.silly('Writing config', azureConfigPath);
    fs.writeFileSync(azureConfigPath, JSON.stringify(cfg));
  };

  config.clearConfig = function() {
    log.silly('Removing', azureConfigPath);
    if (path.existsSync(azureConfigPath)) {
      fs.unlinkSync(azureConfigPath);
      return true;
    }
  };

  // added temporarily for back-compat
  cli.category('account').readConfig = config.readConfig;
  cli.category('account').writeConfig = config.writeConfig;
  cli.category('account').clearConfig = config.clearConfig;

  // apply any persistant switches at load-time
  function applyGlobalSettings() {
    var cfg = config.readConfig();
    if (!cfg) {
      return;
    }

    if (cfg.labels === 'off') {
      log.format({ terse: true });
    }

    if (cfg.logo === 'off') {
      log.format({ logo: 'off' });
    } else {
      log.format({ logo: 'on' });
    }
  }

  applyGlobalSettings();

  function homeFolder() {
    if (process.env.HOME !== undefined) {
      return process.env.HOME;
    }

    if (process.env.HOMEDRIVE && process.env.HOMEPATH) {
      return process.env.HOMEDRIVE + process.env.HOMEPATH;
    }

    throw new Error('No HOME path available');
  }

  function validateEndpoint(endpoint) {
    var parts = endpoint.split('://');
    var hostname = parts[0];
    if(parts.length > 2){
      throw Error('Invalid Url');
    } else if (parts.length === 2) {
       if(!parts[0]) {
        throw Error('Invalid Url');
       }

       if((parts[0] !== 'https') && (parts[0] !== 'HTTPS')) {
          throw Error('Only https protocol supported in the endpoint');
       }

       hostname = parts[1];
    }

    var parts2 = hostname.split('/');

    // Check url contain path(s) after the hostname if so error
    // This will handle in case if user pass endpoint value starting
    // with / char
    if(parts2.length > 2 || (parts2.length === 2 && parts2[1])) {
      throw Error('Invalid Url');
    }

    var parts3 = (parts2[0]).split(':');

    port = 443;
    // Check host name contain ':', if so only one and it should be
    // followed by a valid port number
    if(parts3.length > 2) {
      throw Error('Invalid Url');
    } else if(parts3.length === 2) {
      if(!parts3[1]) {
        throw Error('Invalid Url');
      }

      var intValue = parseInt(parts3[1], 10);
      if (intValue != parts3[1] || parts3[1] < 1 || parts3[1] > 65535) {
        throw Error('Port number should be a number in the range [1, 65535]');
      }

      port = intValue;
    }

    return {endpointHost: parts3[0], endpointPort: port};
  }
};
<|endoftext|>


<commit_before>require('es6-shim');
var _ = require('lodash');

/**
 * @dgProcessor renderDoc
 * @description
 * Render the set of documents using the provided `templateEngine`, to `doc.renderedContent`
 * using the `extraData`, `helpers` and the templates found by `templateFinder`.
 *
 * @param {Logger} log                       A service for logging error and information messages
 * @param {TemplateFinder} templateFinder    A service that matches templates to docs.  A default
 *                                           templateFinder is provided in this base package.
 * @param {TemplateEngine} templateEngine    An instance of a templateEngine that will render the
 *                                           docs/templates. A templateEngine is an object that has
 *                                           a `getRenderer()` method, which itself returns a
 *                                           `render(template, data)` function. The base package
 *                                           doesn't provide a default templateEngine.
 *                                           There is a Nunjucks based engine in the nunjucks module.
 *
 * @property {Map} extraData      Extra data that will be passed to the rendering engine. Your
 *                                services and processors can add data to this object to be made
 *                                available in templates when they are rendered.
 * @property {Map} helpers        Extra helper functions that will be passed to the rendering engine.
 *                                Your services and processors can add helper functions to this
 *                                object to be made available in templates when they are rendered.
 */
module.exports = function renderDocsProcessor(log, templateFinder, templateEngine) {
  return {
    helpers: {},
    extraData: {},

    $runAfter: ['rendering-docs'],
    $runBefore: ['docs-rendered'],
    $validate: {
      helpers: {  },
      extraData: {  }
    },
    $process: function process(docs) {

      var render = templateEngine.getRenderer();
      var findTemplate = templateFinder.getFinder();

      docs.forEach(function(doc) {
        log.debug('Rendering doc', doc.id, doc.name);
        try {
          var data = _.defaults(
            { doc: doc, docs: docs },
            this.extraData,
            this.helpers);
          var templateFile = findTemplate(data.doc);
          doc.renderedContent = render(templateFile, data);
        } catch(ex) {
          console.log(_.omit(doc, ['content', 'moduleDoc', 'components', 'serviceDoc', 'providerDoc']));
          throw new Error('Failed to render doc "' + doc.id + '"' +
            ' from file "' + doc.file + '" line ' + doc.startingLine + '\n' +
            'Error Message follows:\n' + ex.stack);
        }
      }, this);

    }
  };
};<commit_msg>chore(renderDocsProcessor): improve log messages<commit_after>require('es6-shim');
var _ = require('lodash');

/**
 * @dgProcessor renderDoc
 * @description
 * Render the set of documents using the provided `templateEngine`, to `doc.renderedContent`
 * using the `extraData`, `helpers` and the templates found by `templateFinder`.
 *
 * @param {Logger} log                       A service for logging error and information messages
 * @param {TemplateFinder} templateFinder    A service that matches templates to docs.  A default
 *                                           templateFinder is provided in this base package.
 * @param {TemplateEngine} templateEngine    An instance of a templateEngine that will render the
 *                                           docs/templates. A templateEngine is an object that has
 *                                           a `getRenderer()` method, which itself returns a
 *                                           `render(template, data)` function. The base package
 *                                           doesn't provide a default templateEngine.
 *                                           There is a Nunjucks based engine in the nunjucks module.
 *
 * @property {Map} extraData      Extra data that will be passed to the rendering engine. Your
 *                                services and processors can add data to this object to be made
 *                                available in templates when they are rendered.
 * @property {Map} helpers        Extra helper functions that will be passed to the rendering engine.
 *                                Your services and processors can add helper functions to this
 *                                object to be made available in templates when they are rendered.
 */
module.exports = function renderDocsProcessor(log, templateFinder, templateEngine) {
  return {
    helpers: {},
    extraData: {},

    $runAfter: ['rendering-docs'],
    $runBefore: ['docs-rendered'],
    $validate: {
      helpers: {  },
      extraData: {  }
    },
    $process: function process(docs) {

      var render = templateEngine.getRenderer();
      var findTemplate = templateFinder.getFinder();

      docs.forEach(function(doc) {
        log.debug('Rendering doc:', doc.id || doc.name || doc.path);
        try {
          var data = _.defaults(
            { doc: doc, docs: docs },
            this.extraData,
            this.helpers);
          var templateFile = findTemplate(data.doc);
          doc.renderedContent = render(templateFile, data);
        } catch(ex) {
          console.log(_.omit(doc, ['content', 'moduleDoc', 'components', 'serviceDoc', 'providerDoc']));
          throw new Error('Failed to render doc "' + (doc.id || doc.name || doc.path) + '"' +
            ' from file "' + doc.fileInfo.filePath + '" line ' + doc.startingLine + '\n' +
            'Error Message follows:\n' + ex.stack);
        }
      }, this);

    }
  };
};<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Comment = mongoose.model('Comment');
var User = mongoose.model('User');

exports.createComment = function(req, res, next) {
  var comment = new Comment(req.body);

  comment.save(function(err, comment) {
    if (err) {
      res.status(500);
      res.json({
        type: false,
        data: 'Error occurred: ' + err
      });
    } else {
      User.findOne({ _id: comment.target }, function(err, user) {
        user.comments.push(comment);
        user.save();
      });

      res.json({
        type: true,
        data: comment
      });
    }
  });
};

exports.deleteComment = function(req, res, next) {
  Comment.findOneAndRemove({ username: req.params.username }, function(err, user) {
    if (err) {
      res.status(500);
      res.json({
        type: false,
        data: 'Error occurred: ' + err
      });
    } else {
      if (user) {
        res.json({
          type: true,
          data: 'Comment ' + req.params.username + ' deleted successfully'
        });
      } else {
        res.json({
          type: false,
          data: 'Comment ' + req.params.username + ' not found'
        });
      }
    }
  });
};

exports.listComments = function(req, res, next) {
  Comment.find().populate('author target').exec(function(err, comments) {
    res.send(comments);
  });
};

exports.viewComment = function(req, res, next) {
  Comment.findOne({ _id: req.params.id }).populate('author target').exec(function(err, comment) {
    if (err) {
      res.status(500);
      res.json({
        type: false,
        data: 'Error occurred: ' + err
      });
    } else {
      if (comment) {
        res.json({
          type: true,
          data: comment
        });
      } else {
        res.json({
          type: false,
          data: 'Comment ' + req.params.id + ' not found'
        });
      }
    }
  });
};
<commit_msg>Add deleteComment implementation<commit_after>var mongoose = require('mongoose');
var Comment = mongoose.model('Comment');
var User = mongoose.model('User');

exports.createComment = function(req, res, next) {
  var comment = new Comment(req.body);

  comment.save(function(err, comment) {
    if (err) {
      res.status(500);
      res.json({
        type: false,
        data: 'Error occurred: ' + err
      });
    } else {
      User.findOne({ _id: comment.target }, function(err, user) {
        user.comments.push(comment);
        user.save();
      });

      res.json({
        type: true,
        data: comment
      });
    }
  });
};

exports.deleteComment = function(req, res, next) {
  Comment.findOneAndRemove({ _id: req.params.id }, function(err, comment) {
    if (err) {
      res.status(500);
      res.json({
        type: false,
        data: 'Error occurred: ' + err
      });
    } else {
      if (comment) {
        res.json({
          type: true,
          data: 'Comment ' + req.params.id + ' deleted successfully'
        });
      } else {
        res.json({
          type: false,
          data: 'Comment ' + req.params.id + ' not found'
        });
      }
    }
  });
};

exports.listComments = function(req, res, next) {
  Comment.find().populate('author target').exec(function(err, comments) {
    res.send(comments);
  });
};

exports.viewComment = function(req, res, next) {
  Comment.findOne({ _id: req.params.id }).populate('author target').exec(function(err, comment) {
    if (err) {
      res.status(500);
      res.json({
        type: false,
        data: 'Error occurred: ' + err
      });
    } else {
      if (comment) {
        res.json({
          type: true,
          data: comment
        });
      } else {
        res.json({
          type: false,
          data: 'Comment ' + req.params.id + ' not found'
        });
      }
    }
  });
};
<|endoftext|>


<commit_before>'use babel';

import OneLineInputView from './OneLineInputView';
import CopyingNotificationView from './copyingNotificationView';
import {
	CompositeDisposable
} from 'atom';
import {
	exec
} from 'child_process';
import path from 'path';
import os from 'os';
import fs from 'fs-plus';

export default {
	oneLineInputView: null,
	copyingNotificationView: null,
	subscriptions: null,

	// パッケージ実行時にここから処理される
	activate(state) {
		console.log(state);

		// 外部クラスをインスタンス
		this.oneLineInputView = new OneLineInputView(state.oneLineInputViewState);
		this.copyingNotificationView = new CopyingNotificationView(state.copyingNotificationViewState);

		// Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
		this.subscriptions = new CompositeDisposable();

		// Register command that toggles this view
		this.subscriptions.add(atom.commands.add('atom-workspace', {
			'copy-to-folder-path:CopyToPath': () => this.sendFileCurrentProjectPath(),
			'copy-to-folder-path:ConfigureCopyPath': () => this.CreateConfigFile(),
			'copy-to-folder-path:CopyingPanelEnd': () => this.copyingNotificationView.hidePanel(),
		}));

	},

	// ウインドウが閉じられた時に呼び出される
	serialize() {
		return {
			oneLineInputViewState: this.oneLineInputView.serialize(),
			copyingNotificationViewState: this.copyingNotificationView.serialize()
		};
	},

	// 本パッケージを無効にする処理 ウインドウを閉じた時に呼び出される
	deactivate() {
		this.subscriptions.dispose();
		this.oneLineInputView.destroy();
		this.copyingNotificationView.destroy();
	},

	// 各プロジェクトにある設定ファイルのパスを読み込む
	getJsonPath() {
		let projectPath = this.getOpenCurrentProjectPath();
		let configPath = path.join(projectPath, atom.config.get('copy-to-folder-path.configFileName'));
		console.log(`Jsonのパス :${configPath}`);
		return configPath;
	},

	// 各プロジェクトにある設定ファイルのJsonの中身を取得
	readConfigJson() {
		let configPath = this.getJsonPath();
		let readjson = JSON.parse(fs.readFileSync(configPath, 'utf8'));
		return readjson;
	},

	// 現在開いているファイルのプロジェクトのパスをCMDで開く処理を投げる
	sendFileCurrentProjectPath() {
		// 現在開いているファイルのルートプロジェクトを開く
		var projectPath = this.getOpenCurrentProjectPath();
		if (projectPath !== null) { // projectPathはツリーに追加されていないファイルの場合はNullになる
			if (fs.isFileSync(this.getJsonPath())) {
				// 設定ファイルが存在するならそのまま開く
				return this.open_terminal(projectPath);
			} else {
				// 設定ファイルが存在しないため作成
				this.CreateConfigFile();
			}
		}
		return;
	},

	// ツリーに存在するすべてのプロジェクトをCMDで開く処理を投げる
	sendAllProjectPath() {
		// ツリーに追加されているすべてのプロジェクトを開く
		var i, len, pathname, ref, results;
		ref = atom.project.getPaths();
		ref2 = atom.project.getDirectories();
		console.log(ref);
		console.log(ref2);
		results = [];
		for (i = 0, len = ref.length; i < len; i++) {
			pathname = ref[i];
			results.push(this.open_terminal(pathname));
		}
		return results;
	},

	// 現在開いているファイルのパスをCMDで開く処理を投げる
	sendFilePath() {
		// 現在開いているファイルのパスを開く(ファイルのパスは含めない)
		var editor, file, filepath, ref;
		editor = atom.workspace.getActivePaneItem();
		file = editor !== null ? (ref = editor.buffer) !== null ? ref.file : void 0 : void 0;
		filepath = file !== null ? file.path : void 0;
		if (filepath) {
			console.log(path.dirname());
			return this.open_terminal(path.dirname(filepath));
		}
	},

	// 各プロジェクトごとに設定ファイルを作成する
	CreateConfigFile() {
		console.log("ConfigureCopyPath create");
		var projectPath = this.getOpenCurrentProjectPath(); // 現在開いているプロジェクトのパスを取得
		if (projectPath !== null) { // projectPathはツリーに追加されていないファイルの場合はNullになる
			console.log(projectPath);
			var configPath = this.getJsonPath(); // 設定ファイルのパスを取得
			console.log(configPath);
			if (!fs.isFileSync(configPath)) {
				//configPath のファイルが存在しな時の処理
				this.inputPanelOpen();
			} else {
				var results = atom.confirm({
					message: "すでに設定ファイルは存在しますが上書きしますか?",
					buttons: ["Cancel", "上書き"]
				});
				console.log(`results :${results}`);
				if (results === 1) {
					this.inputPanelOpen();
				}
			}
		}
		return;
	},

	inputPanelOpen(jsonWritePath) {
		console.log("file out put start");
		this.oneLineInputView.showPanel();
		var log = this.oneLineInputView.setCallback(function(text) {
			var editor;
			console.log("入力したパスは" + text);
			editor = atom.workspace.getActiveTextEditor();
			atom.views.getView(editor).focus();
			this.createJson(text);
			return
		});
	},

	// CMDを起動する処理 ここでCMDで開く処理を投げる
	open_terminal(readProjectPath) {
		this.copyingNotificationView.showPanel();
		console.log(readProjectPath);
		var writePath, cmdline;
		app = atom.packages.resolvePackagePath("copy-to-folder-path");
		app += atom.config.get('copy-to-folder-path.app');
		console.log(`実行CMDパス :${app}`);

		var readjson = this.readConfigJson();
		writePath = readjson.CopyToPath; //転送先を読み込む

		cmdline = "\"" + app + "\" " + writePath;
		cmdline = "start /B \"\" " + cmdline;
		console.log("cmdline: ", cmdline);
		if (readProjectPath !== null) {
			return exec(cmdline, {
				cwd: readProjectPath
			}, function(error, stdout, stderr) {
				console.log('-------cmd end-------');
				console.log('stdout: ' + stdout);
				console.log('stderr: ' + stderr);
				// 表示しているCopyingパネルの表示を隠すためにコマンドを投げる
				// ここはコールバック先であるためthis.copyingNotificationView.hidePanel()が使えないため
				atom.commands.dispatch(atom.views.getView(atom.workspace), "copy-to-folder-path:CopyingPanelEnd");
				if (error !== null) {
					console.log('exec error: ' + error);
					atom.notifications.addError("コピー失敗
" + error);
				} else {
					atom.notifications.addSuccess("コピー完了
パス:" + writePath);
				}
			});
		}
	},

	// 現在開いているプロジェクトのパスを取得する
	getOpenCurrentProjectPath() {
		var editor, file, filepath, projectPath, ref, ref2, relativePath;
		editor = atom.workspace.getActivePaneItem();
		file = editor !== null ? (ref = editor.buffer) !== null ? ref.file : void 0 : void 0;
		filepath = file !== null ? file.path : void 0;
		if (filepath) {
			ref2 = atom.project.relativizePath(filepath);
			projectPath = ref2[0];
			relativePath = ref2[1];
		} else {
			console.error("error filepath : " + filepath);
		}
		return projectPath;
	},

};
<commit_msg>cmdへ投げるパスをutf8で渡す、ファイルを開いていない時エラーを投げる<commit_after>'use babel';

import OneLineInputView from './OneLineInputView';
import CopyingNotificationView from './copyingNotificationView';
import {
	CompositeDisposable
} from 'atom';
import {
	exec
} from 'child_process';
import path from 'path';
import os from 'os';
import fs from 'fs-plus';

export default {
	oneLineInputView: null,
	copyingNotificationView: null,
	subscriptions: null,

	// パッケージ実行時にここから処理される
	activate(state) {
		console.log(state);

		// 外部クラスをインスタンス
		this.oneLineInputView = new OneLineInputView(state.oneLineInputViewState);
		this.copyingNotificationView = new CopyingNotificationView(state.copyingNotificationViewState);

		// Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
		this.subscriptions = new CompositeDisposable();

		// Register command that toggles this view
		this.subscriptions.add(atom.commands.add('atom-workspace', {
			'copy-to-folder-path:CopyToPath': () => this.sendFileCurrentProjectPath(),
			'copy-to-folder-path:ConfigureCopyPath': () => this.CreateConfigFile(),
			'copy-to-folder-path:CopyingPanelEnd': () => this.copyingNotificationView.hidePanel(),
		}));

	},

	// ウインドウが閉じられた時に呼び出される
	serialize() {
		return {
			oneLineInputViewState: this.oneLineInputView.serialize(),
			copyingNotificationViewState: this.copyingNotificationView.serialize()
		};
	},

	// 本パッケージを無効にする処理 ウインドウを閉じた時に呼び出される
	deactivate() {
		this.subscriptions.dispose();
		this.oneLineInputView.destroy();
		this.copyingNotificationView.destroy();
	},

	// 各プロジェクトにある設定ファイルのパスを読み込む
	getJsonPath() {
		let projectPath = this.getOpenCurrentProjectPath();
		let configPath = path.join(projectPath, atom.config.get('copy-to-folder-path.configFileName'));
		console.log(`Jsonのパス :${configPath}`);
		return configPath;
	},

	// 各プロジェクトにある設定ファイルのJsonの中身を取得
	readConfigJson() {
		let configPath = this.getJsonPath();
		let readjson = JSON.parse(fs.readFileSync(configPath, 'utf8'));
		return readjson;
	},

	// 現在開いているファイルのプロジェクトのパスをCMDで開く処理を投げる
	sendFileCurrentProjectPath() {
		// 現在開いているファイルのルートプロジェクトを開く
		var projectPath = this.getOpenCurrentProjectPath();
		if (projectPath !== null) { // projectPathはツリーに追加されていないファイルの場合はNullになる
			if (fs.isFileSync(this.getJsonPath())) {
				// 設定ファイルが存在するならそのまま開く
				return this.open_terminal(projectPath);
			} else {
				// 設定ファイルが存在しないため作成
				this.CreateConfigFile();
			}
		}
		return;
	},

	// ツリーに存在するすべてのプロジェクトをCMDで開く処理を投げる
	sendAllProjectPath() {
		// ツリーに追加されているすべてのプロジェクトを開く
		var i, len, pathname, ref, results;
		ref = atom.project.getPaths();
		ref2 = atom.project.getDirectories();
		console.log(ref);
		console.log(ref2);
		results = [];
		for (i = 0, len = ref.length; i < len; i++) {
			pathname = ref[i];
			results.push(this.open_terminal(pathname));
		}
		return results;
	},

	// 現在開いているファイルのパスをCMDで開く処理を投げる
	sendFilePath() {
		// 現在開いているファイルのパスを開く(ファイルのパスは含めない)
		var editor, file, filepath, ref;
		editor = atom.workspace.getActivePaneItem();
		file = editor !== null ? (ref = editor.buffer) !== null ? ref.file : void 0 : void 0;
		filepath = file !== null ? file.path : void 0;
		if (filepath) {
			console.log(path.dirname());
			return this.open_terminal(path.dirname(filepath));
		}
	},

	// 各プロジェクトごとに設定ファイルを作成する
	CreateConfigFile() {
		console.log("ConfigureCopyPath create");
		var projectPath = this.getOpenCurrentProjectPath(); // 現在開いているプロジェクトのパスを取得
		if (projectPath !== null) { // projectPathはツリーに追加されていないファイルの場合はNullになる
			console.log(projectPath);
			var configPath = this.getJsonPath(); // 設定ファイルのパスを取得
			console.log(configPath);
			if (!fs.isFileSync(configPath)) {
				//configPath のファイルが存在しな時の処理
				this.inputPanelOpen();
			} else {
				var results = atom.confirm({
					message: "すでに設定ファイルは存在しますが上書きしますか?",
					buttons: ["Cancel", "上書き"]
				});
				console.log(`results :${results}`);
				if (results === 1) {
					this.inputPanelOpen();
				}
			}
		}
		return;
	},

	inputPanelOpen(jsonWritePath) {
		console.log("file out put start");
		this.oneLineInputView.showPanel();
		var log = this.oneLineInputView.setCallback(function(text) {
			var editor;
			console.log("入力したパスは" + text);
			editor = atom.workspace.getActiveTextEditor();
			atom.views.getView(editor).focus();
			this.createJson(text);
			return
		});
	},

	// CMDを起動する処理 ここでCMDで開く処理を投げる
	open_terminal(readProjectPath) {
		this.copyingNotificationView.showPanel();
		console.log(readProjectPath);
		var writePath, cmdline;
		app = atom.packages.resolvePackagePath("copy-to-folder-path");
		app += atom.config.get('copy-to-folder-path.app');
		console.log(`実行CMDパス :${app}`);

		var readjson = this.readConfigJson();
		writePath = readjson.CopyToPath; //転送先を読み込む

		cmdline = "\"" + app + "\" " + writePath;
		cmdline = "start /B \"\" " + cmdline;
		console.log("cmdline: ", cmdline);
		if (readProjectPath !== null) {
			return exec(cmdline, {
				cwd: readProjectPath,
				encoding: 'utf8'
			}, function(error, stdout, stderr) {
				console.log('-------cmd end-------');
				console.log('stdout: ' + stdout);
				console.log('stderr: ' + stderr);
				// 表示しているCopyingパネルの表示を隠すためにコマンドを投げる
				// ここはコールバック先であるためthis.copyingNotificationView.hidePanel()が使えないため
				atom.commands.dispatch(atom.views.getView(atom.workspace), "copy-to-folder-path:CopyingPanelEnd");
				if (error !== null) {
					console.log('exec error: ' + error);
					atom.notifications.addError("コピー失敗
" + error);
				} else {
					atom.notifications.addSuccess("コピー完了
パス:" + writePath);
				}
			});
		}
	},

	// 現在開いているプロジェクトのパスを取得する
	getOpenCurrentProjectPath() {
		var editor, file, filepath, projectPath, ref, ref2, relativePath;
		editor = atom.workspace.getActivePaneItem();
		if (typeof editor !== "undefined") {
			file = editor !== null ? (ref = editor.buffer) !== null ? ref.file : void 0 : void 0;
			filepath = file !== null ? file.path : void 0;
			if (filepath) {
				ref2 = atom.project.relativizePath(filepath);
				projectPath = ref2[0];
				relativePath = ref2[1];
			} else {
				console.error("error filepath : " + filepath);
			}
			return projectPath;
		} else {
			throw "ファイルを開いてください!!";
		}
	},

};
<|endoftext|>


<commit_before>var fs = require("fs");
var q = require("q");

function resolveCredential(value) {
	if (!value) return value;
	if(/-----BEGIN ([A-Z\s*]+)-----/.test(value)) {
		return value;
	}
	else if(Buffer.isBuffer(value)) {
		return value;
	}
	else {
		return q.nfbind(fs.readFile)(value);
	}
}

module.exports = resolveCredential;<commit_msg>Never use implicit `if` blocks. {} FTW.<commit_after>var fs = require("fs");
var q = require("q");

function resolveCredential(value) {
	if (!value) {
		return value;
	}
	if(/-----BEGIN ([A-Z\s*]+)-----/.test(value)) {
		return value;
	}
	else if(Buffer.isBuffer(value)) {
		return value;
	}
	else {
		return q.nfbind(fs.readFile)(value);
	}
}

module.exports = resolveCredential;<|endoftext|>


<commit_before>var profiles = require('../collections/profiles'),
    uuid     = require('../helpers/uuid'),
    wrap	   = require('../helpers/wrapper'),
    time     = require('microtime')

function profile (fn) {
  var initd = time.now()

  function BROfile () {
    var u    = uuid(fn),
        prof = createProfile(u, fn, initd),
        last = profiles.mostRecent()

    function createProfile (u) {
      var cawl = callTrace()

      return {
        id          : u.id,
        invokation  : u.invokations,
        initialized : initd,
        observers   : [ ],
        anonymous   : u.anonymous,
        file        : cawl.file,
        line        : cawl.line
      }
    }

    function callTrace() {
      var err  = new Error,
    	    data = [ ]

      Error.captureStackTrace(err, fn.callee)
      var lines = err.stack.split("\n")

      for (var i = 0; i < lines.length; i++) {
        if (lines[i].search(/.*Error|wrap|decorate|__profile__|Object\.\.js|eval at profile|Module|Function|require.*/) === -1) {
          var file = lines[i].split('(')
              line = file.length === 1 ? lines[i] : file[1],
              data = line.substring(0, line.length - 2)

          break
        }
      }

    	return { file: data[0], line: data[1] }
    }

    function decorate (af, uid) {
      var a = [ ]

      for (var k = 0; k < af.length; k++)
        if (typeof af[k] === 'function') {
          if (!af[k].isWrappedWithProfiler()) {
            a.push(wrap(profile, 'OWNER:' + uid, af[k]))

            var afk = uuid(af[k], false)

            prof.observers.push(afk.id + '.0')
          } else {
            a.push(af[k])

            // Get the uuid for the wrapped function
            var afk = uuid(af[k].__wrapped)

            prof.observers.push(afk.uid)
          }
        } else if (af[k] instanceof String && af[k].indexOf('OWNER:') === 0) {
          prof.owner = af[k].substring(6)
        } else {
          a.push(af[k])
        }
      return a
    }

    if (last && last.anonymous) {
      prof.owner = last.id + '.' + last.invokation
      last.observers.push(u.uid)
    }

    profiles.add(prof)

    prof.rawArgs = arguments
    prof.args 	 = decorate(arguments, u.uid)
    prof.start   = time.now()
    prof.result  = fn.apply(this, prof.args)
    prof.end     = time.now()

    return prof.result
  }

  var str = BROfile.toString(),
      idx = str.indexOf('('),
      p = eval('(function ' + fn.name + str.substring(idx) + ')')

  p.__wrapped = fn

  return p
}

module.exports = profile<commit_msg>Extracted the profile's helper functions to the top level<commit_after>var profiles = require('../collections/profiles'),
    uuid     = require('../helpers/uuid'),
    wrap	   = require('../helpers/wrapper'),
    time     = require('microtime')

function createProfile (u, fn, initd) {
  var cawl = callTrace(fn)

  return {
    id          : u.id,
    invokation  : u.invokations,
    initialized : initd,
    observers   : [ ],
    anonymous   : u.anonymous,
    file        : cawl.file,
    line        : cawl.line
  }
}

function callTrace(fn) {
  var err  = new Error,
	    data = [ ]

  Error.captureStackTrace(err, fn.callee)
  var lines = err.stack.split("\n")

  for (var i = 0; i < lines.length; i++) {
    if (lines[i].search(/.*Error|wrap|decorate|__profile__|Object\.\.js|eval at profile|Module|Function|require.*/) === -1) {
      var file = lines[i].split('(')
          line = file.length === 1 ? lines[i] : file[1],
          data = line.substring(0, line.length - 2)

      break
    }
  }

	return { file: data[0], line: data[1] }
}

function decorate (af, uid, prof) {
  var a = [ ]

  for (var k = 0; k < af.length; k++)
    if (typeof af[k] === 'function') {
      if (!af[k].isWrappedWithProfiler()) {
        a.push(wrap(profile, 'OWNER:' + uid, af[k]))

        var afk = uuid(af[k], false)

        prof.observers.push(afk.id + '.0')
      } else {
        a.push(af[k])

        // Get the uuid for the wrapped function
        var afk = uuid(af[k].__wrapped)

        prof.observers.push(afk.uid)
      }
    } else if (af[k] instanceof String && af[k].indexOf('OWNER:') === 0) {
      prof.owner = af[k].substring(6)
    } else {
      a.push(af[k])
    }
  return a
}

function profile (fn) {
  var initd = time.now()

  function BROfile () {
    var u    = uuid(fn),
        prof = createProfile(u, fn, initd),
        last = profiles.mostRecent()

    if (last && last.anonymous) {
      prof.owner = last.id + '.' + last.invokation
      last.observers.push(u.uid)
    }

    profiles.add(prof)

    prof.rawArgs = arguments
    prof.args 	 = decorate(arguments, u.uid, prof)
    prof.start   = time.now()
    prof.result  = fn.apply(this, prof.args)
    prof.end     = time.now()

    return prof.result
  }

  var str = BROfile.toString(),
      idx = str.indexOf('('),
      p = eval('(function ' + fn.name + str.substring(idx) + ')')

  p.__wrapped = fn

  return p
}

module.exports = profile<|endoftext|>


<commit_before>/* global define: false */
define([], function() {
  'use strict';

  /**
   * This directive ensures that form fields
   * filled by browsers are properly recognized by angular.
   *
   * @example
   *
   * <input ng-model="password" auto-fill />
   */
  return [
    '$interval',
  function(
    $interval
  ) {
    return {
      restrict: 'A',

      require: 'ngModel',

      link: function (scope, element, attrs, model) {
        // console.info('start watching for auto-filled field', attrs.name);

        var interval = $interval(function() {
          var value = element.val();
          if (value !== model.$viewValue) {
            model.$setViewValue(value);
          }

          if (!document.contains(element[0])) {
            // console.info('stop watching for auto-filled field', attrs.name);
            $interval.cancel(interval);
          }
        }, 500);
      }
    };
  }];
});
<commit_msg>fix(autofill): prevent using the DOMelement conatins method<commit_after>/* global define: false */
define([], function() {
  'use strict';

  /**
   * This directive ensures that form fields
   * filled by browsers are properly recognized by angular.
   *
   * @example
   *
   * <input ng-model="password" auto-fill />
   */
  return [
    '$interval',
  function(
    $interval
  ) {
    return {
      restrict: 'A',

      require: 'ngModel',

      link: function (scope, element, attrs, model) {
        // console.info('start watching for auto-filled field', attrs.name);

        var interval = $interval(function() {
          var value = element.val();
          if (value !== model.$viewValue) {
            model.$setViewValue(value);
          }

          if (typeof document.contains === 'function' && !document.contains(element[0])) {
            // console.info('stop watching for auto-filled field', attrs.name);
            $interval.cancel(interval);
          }
          else if (typeof document.contains !== 'function') {
            $interval.cancel(interval);
          }
        }, 500);
      }
    };
  }];
});
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const minimatch = require('minimatch');
const walk = require('fs-extra').walk;
const _ = require('lodash');

const Info = require('../Info');

function getFiles(dirPath, recursive, pattern, files) {
    files = files || [];
    let items = fs.readdirSync(dirPath);

    for (let item of items) {
        let fullPath = path.resolve(dirPath, item);
        let stats = getStats(fullPath);
        if (stats) {
            if (recursive && stats.isDirectory()) {
                getFiles(item, true, files);
            } else {
                let base = path.basename(item);
                if (minimatch(base, pattern)) {
                    files.push(item);
                }
            }
        }
    }

    return files;
}

function getDirectories(dirPath, recursive, dirs) {
    dirs = dirs || [];
    let items = fs.readdirSync(dirPath);

    for (let item of items) {
        let fullPath = path.resolve(dirPath, item);
        let stats = getStats(fullPath);
        if (stats) {
            if (recursive && stats.isDirectory()) {
                dirs.push(item);
                getFiles(item, true, files);
            }
        }
    }

    return dirs;
}

function getStats(fullPath) {
    try {
        return fs.statSync(fullPath);
    } catch (err) {
        return undefined;
    }
}

class Directory extends Info {

    /**
     * @param dirPath: directory path
     * @param options.recursive: (Boolean) get files recursive or stay. default: false
     * @param options.pattern: (String) get specific files pattern. default: *.*
     * @param cb: callback
     */
    static getFiles(dirPath, options, cb) {
        let defaultOptions = {recursive: false, pattern: '*.*'};
        if (typeof options === 'function') {
            cb = options;
            options = defaultOptions;
        } else {
            options = Object.assign(defaultOptions, options);
        }
        let files = [];
        let recursive = options.recursive;
        let pattern = options.pattern;

        if (!recursive) {
            files = getFiles(dirPath, recursive, pattern);
            return cb(null, files);
        }

        walk(dirPath)
            .on('data', (item) => {
                if (!item.stats.isDirectory()) {
                    let base = path.basename(item);
                    if (minimatch(base, pattern)) {
                        files.push(item.path);
                    }
                }
            })
            .on('end', () => {
                if (cb) {
                    cb(null, files);
                }
            })
            .on('error', (err) => {
                cb(err);
            });
    }

    static getFilesSync(dirPath, recursive, pattern) {
        recursive = recursive || false;
        pattern = pattern || '*.*';

        return getFiles(dirPath, recursive, pattern);
    }

    static getDirectories(dirPath, cb) {
        let dirs = [];
        walk(dirPath)
            .on('data', (item) => {
                if (item.stats.isDirectory()) {
                    dirs.push(item.path);
                }
            })
            .on('end', () => {
                if (cb) {
                    cb(null, dirs);
                }
            })
            .on('error', (err) => {
                cb(err);
            });
    }

    static getDirectoriesSync(dirPath, recursive) {
        return getDirectories(dirPath, recursive);
    }

    static deleteContentSync(dirPath) {
        let files = Directory.getFilesSync(dirPath, false);
        let dirs = Directory.getDirectoriesSync(dirPath, false);

        let all = _.union(files, dirs);
        Info.deleteSync(all);
    }
}

module.exports = Directory;<commit_msg>bug fixed<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const minimatch = require('minimatch');
const walk = require('fs-extra').walk;
const _ = require('lodash');

const Info = require('../Info');

function getFiles(dirPath, recursive, pattern, files) {
    files = files || [];
    let items = fs.readdirSync(dirPath);

    for (let item of items) {
        let fullPath = path.resolve(dirPath, item);
        let stats = getStats(fullPath);
        if (stats) {
            if (recursive && stats.isDirectory()) {
                getFiles(fullPath, true, pattern, files);
            } else {
                let base = path.basename(item);
                if (minimatch(base, pattern)) {
                    files.push(item);
                }
            }
        }
    }

    return files;
}

function getDirectories(dirPath, recursive, dirs) {
    dirs = dirs || [];
    let items = fs.readdirSync(dirPath);

    for (let item of items) {
        let fullPath = path.resolve(dirPath, item);
        let stats = getStats(fullPath);
        if (stats) {
            if (recursive && stats.isDirectory()) {
                dirs.push(item);
                getFiles(item, true, files);
            }
        }
    }

    return dirs;
}

function getStats(fullPath) {
    try {
        return fs.statSync(fullPath);
    } catch (err) {
        return undefined;
    }
}

class Directory extends Info {

    /**
     * @param dirPath: directory path
     * @param options.recursive: (Boolean) get files recursive or stay. default: false
     * @param options.pattern: (String) get specific files pattern. default: *.*
     * @param cb: callback
     */
    static getFiles(dirPath, options, cb) {
        let defaultOptions = {recursive: false, pattern: '*.*'};
        if (typeof options === 'function') {
            cb = options;
            options = defaultOptions;
        } else {
            options = Object.assign(defaultOptions, options);
        }
        let files = [];
        let recursive = options.recursive;
        let pattern = options.pattern;

        if (!recursive) {
            files = getFiles(dirPath, recursive, pattern);
            return cb(null, files);
        }

        walk(dirPath)
            .on('data', (item) => {
                if (!item.stats.isDirectory()) {
                    let base = path.basename(item);
                    if (minimatch(base, pattern)) {
                        files.push(item.path);
                    }
                }
            })
            .on('end', () => {
                if (cb) {
                    cb(null, files);
                }
            })
            .on('error', (err) => {
                cb(err);
            });
    }

    static getFilesSync(dirPath, recursive, pattern) {
        recursive = recursive || false;
        pattern = pattern || '*.*';

        return getFiles(dirPath, recursive, pattern);
    }

    static getDirectories(dirPath, cb) {
        let dirs = [];
        walk(dirPath)
            .on('data', (item) => {
                if (item.stats.isDirectory()) {
                    dirs.push(item.path);
                }
            })
            .on('end', () => {
                if (cb) {
                    cb(null, dirs);
                }
            })
            .on('error', (err) => {
                cb(err);
            });
    }

    static getDirectoriesSync(dirPath, recursive) {
        return getDirectories(dirPath, recursive);
    }

    static deleteContentSync(dirPath) {
        let files = Directory.getFilesSync(dirPath, false);
        let dirs = Directory.getDirectoriesSync(dirPath, false);

        let all = _.union(files, dirs);
        Info.deleteSync(all);
    }
}

let p = path.resolve(__dirname, '..', '..' , 'lib');
let f = Directory.getFilesSync(p, true);

console.log(f);

module.exports = Directory;<|endoftext|>


<commit_before>//
// generic comparator implementations our types can use
//
var collation = exports

//
// scalar comparisons
//
collation.inequality = function (a, b) {
  return a < b ? -1 : ( a > b ? 1 : 0 )
}

collation.difference = function (a, b) {
  return a - b
}

//
// recursive collations have to be provided a collation function to delegate to
//
collation.recursive = {}

//
// element by element (comparison for list-like structures
//
collation.recursive.elementwise = function (compare, shortlex) {
  return function (a, b) {
    var aLength = a.length
    var bLength = b.length
    var difference

    //
    // short-circuit on length difference for shortlex semantics
    //
    if (shortlex && aLength !== bLength)
        return aLength - bLength

    for (var i = 0, length = Math.min(aLength, bLength); i < length; ++i) {
      if (difference = compare(a[i], b[i]))
        return difference
    }

    return aLength - bLength
  }
}

//
// field by field comparison of record-like structures
//
collation.recursive.fieldwise = function (compare, shortlex) {
  return function (a, b) {
    var aKeys = Object.keys(a)
    var bKeys = Object.keys(b)
    var aLength = aKeys.length
    var bLength = bKeys.length
    var difference

    //
    // short-circuit on length difference for shortlex semantics
    //
    if (shortlex && aLength !== bLength)
        return aLength - bLength

    for (var i = 0, length = Math.min(aLength, bLength); i < length; ++i) {
      //
      // first compare keys
      //
      if (difference = compare(aKeys[i], bKeys[i]))
        return difference

      //
      // then compare values
      //
      if (difference = compare(a[aKeys[i]], b[bKeys[i]]))
        return difference
    }

    return aLength - bLength
  }
}

//
// elementwise compare with inequality can be used for binary equality
//
collation.bitwise = Buffer.compare
if (!typeof collation.bitwise === 'function')
  collation.bitwise = collation.recursive.elementwise(exports.inequality)

<commit_msg>Fix bitwise collation fallback<commit_after>//
// generic comparator implementations our types can use
//
var collation = exports

//
// scalar comparisons
//
collation.inequality = function (a, b) {
  return a < b ? -1 : ( a > b ? 1 : 0 )
}

collation.difference = function (a, b) {
  return a - b
}

//
// recursive collations have to be provided a collation function to delegate to
//
collation.recursive = {}

//
// element by element (comparison for list-like structures
//
collation.recursive.elementwise = function (compare, shortlex) {
  return function (a, b) {
    var aLength = a.length
    var bLength = b.length
    var difference

    //
    // short-circuit on length difference for shortlex semantics
    //
    if (shortlex && aLength !== bLength)
        return aLength - bLength

    for (var i = 0, length = Math.min(aLength, bLength); i < length; ++i) {
      if (difference = compare(a[i], b[i]))
        return difference
    }

    return aLength - bLength
  }
}

//
// field by field comparison of record-like structures
//
collation.recursive.fieldwise = function (compare, shortlex) {
  return function (a, b) {
    var aKeys = Object.keys(a)
    var bKeys = Object.keys(b)
    var aLength = aKeys.length
    var bLength = bKeys.length
    var difference

    //
    // short-circuit on length difference for shortlex semantics
    //
    if (shortlex && aLength !== bLength)
        return aLength - bLength

    for (var i = 0, length = Math.min(aLength, bLength); i < length; ++i) {
      //
      // first compare keys
      //
      if (difference = compare(aKeys[i], bKeys[i]))
        return difference

      //
      // then compare values
      //
      if (difference = compare(a[aKeys[i]], b[bKeys[i]]))
        return difference
    }

    return aLength - bLength
  }
}

//
// elementwise compare with inequality can be used for binary equality
//
collation.bitwise = Buffer.compare
if (typeof collation.bitwise !== 'function')
  collation.bitwise = collation.recursive.elementwise(exports.inequality)

<|endoftext|>


<commit_before>// collector.js v0.1
// by Matt Sacks <matt.s.sacks@gmail.com>

;(function(window) {
  // constructor
  function Collector(options) {
    this.options = options || {};
  };

  // version
  Collector.version = Collector.v = '0.1';

  // loops over an array of data and applies a mapping function for each item in
  // the array. after each mapping is applied, a rolling reduction is then
  // called onto the datum.
  //
  // - **data** (Array): array of data to call mappings and reductions onto
  // - **mappings** (Object): an object of unique keys whose values are
  // functions that will be called onto each object in the data
  // - **reductions** (Object): similar to mappings, these are functions
  // called after mapping a datum. each key needs to be exact to the same key in
  // mappings to coordinate the data.
  Collector.prototype.collect = function(data, mappings, reductions) {
    if (data == null || mappings == null) return;

    // the returned object
    var collection = {};

    for (var i = 0, len = data.length; i < len; i++) {
      var datum = data[i];
      for (var key in mappings) {
        var map = mappings[key], reduce;
        if (map == null) continue;

        reductions != null && (reduce = reductions[key]);

        // call a map on the piece of data
        var result  = map(datum, i);
        var rolling = collection[key];

        // if a reduce function isn't defined for this key, then just map
        if (reduce == null) {
          collection[key] = collection[key] || [];
          collection[key].push(result);
          continue;
        }

        // if there was a result from the mapping, call it as the first
        // argument.  otherwise, same format as the mapping
        result = result != null ?
          reduce(rolling, result, datum, i) :
          reduce(rolling, datum, i);

        if (result != null) collection[key] = result;
      }
    };

    return collection;
  };

  // expose class and default instantiation
  window.Collector = Collector;
  window.collector = new Collector;
})(window);
<commit_msg>remove reduction result check<commit_after>// collector.js v0.1
// by Matt Sacks <matt.s.sacks@gmail.com>

;(function(window) {
  // constructor
  function Collector(options) {
    this.options = options || {};
  };

  // version
  Collector.version = Collector.v = '0.1';

  // loops over an array of data and applies a mapping function for each item in
  // the array. after each mapping is applied, a rolling reduction is then
  // called onto the datum.
  //
  // - **data** (Array): array of data to call mappings and reductions onto
  // - **mappings** (Object): an object of unique keys whose values are
  // functions that will be called onto each object in the data
  // - **reductions** (Object): similar to mappings, these are functions
  // called after mapping a datum. each key needs to be exact to the same key in
  // mappings to coordinate the data.
  Collector.prototype.collect = function(data, mappings, reductions) {
    if (data == null || mappings == null) return;

    // the returned object
    var collection = {};

    for (var i = 0, len = data.length; i < len; i++) {
      var datum = data[i];

      for (var key in mappings) {
        var map = mappings[key], reduce;
        if (map == null) continue;

        reductions != null && (reduce = reductions[key]);

        // call a map on the piece of data
        var result  = map(datum, i);
        var rolling = collection[key];

        // if a reduce function isn't defined for this key, then just map
        if (reduce == null) {
          collection[key] = collection[key] || [];
          collection[key].push(result);
          continue;
        }

        // if there was a result from the mapping, call it as the first
        // argument.  otherwise, same format as the mapping
        result = result != null ?
          reduce(rolling, result, datum, i) :
          reduce(rolling, datum, i);

        collection[key] = result;
      }
    };

    return collection;
  };

  // expose class and default instantiation
  window.Collector = Collector;
  window.collector = new Collector;
})(window);
<|endoftext|>


<commit_before>/* from http://jsfiddle.net/sUK45/ */
function stringToColor(str) {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
        hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    let color = '#';
    for (let i = 0; i < 3; i++) {
        let value = (hash >> (i * 8)) & 0xFF;
        color += ('00' + value.toString(16)).substr(-2);
    }
    return color;
}

document.querySelectorAll('a[href^="profile.php"], a[href^="profile.php"] font').forEach(link => {
    let color = stringToColor(link.textContent);
    link.style.color = color;
});
<commit_msg>Colorize posts!<commit_after>/* from http://jsfiddle.net/sUK45/ */
function stringToColor(str) {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
        hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    let color = '#';
    for (let i = 0; i < 3; i++) {
        let value = (hash >> (i * 8)) & 0xFF;
        color += ('00' + value.toString(16)).substr(-2);
    }
    return color;
}

document.querySelectorAll('a[href^="profile.php"], a[href^="profile.php"] font, td[style="width:100%"][class="normalfont"][align="left"]').forEach(element => {
    let color = stringToColor(element.textContent);
    element.style.color = color;
});
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

/**
 * Define a module along with a payload.
 * @param moduleName Name for the payload
 * @param deps Ignored. For compatibility with CommonJS AMD Spec
 * @param payload Function with (require, exports, module) params
 */
function define(moduleName, deps, payload) {
  if (typeof moduleName != "string") {
    console.error(this.depth + " Error: Module name is not a string.");
    console.trace();
    return;
  }

  if (arguments.length == 2) {
    payload = deps;
  }

  if (define.debugDependencies) {
    console.log("define: " + moduleName + " -> " + payload.toString()
        .slice(0, 40).replace(/\n/, '\\n').replace(/\r/, '\\r') + "...");
  }

  if (moduleName in define.modules) {
    console.error(this.depth + " Error: Redefining module: " + moduleName);
  }
  define.modules[moduleName] = payload;
}

/**
 * The global store of un-instantiated modules
 */
define.modules = {};

/**
 * Should we console.log on module definition/instantiation/requirement?
 */
define.debugDependencies = false;

/**
 * Self executing function in which Domain is defined, and attached to define
 */
(function() {
  /**
   * We invoke require() in the context of a Domain so we can have multiple
   * sets of modules running separate from each other.
   * This contrasts with JSMs which are singletons, Domains allows us to
   * optionally load a CommonJS module twice with separate data each time.
   * Perhaps you want 2 command lines with a different set of commands in each,
   * for example.
   */
  function Domain() {
    this.modules = {};

    if (define.debugDependencies) {
      this.depth = "";
    }
  }

  /**
   * Lookup module names and resolve them by calling the definition function if
   * needed.
   * There are 2 ways to call this, either with an array of dependencies and a
   * callback to call when the dependencies are found (which can happen
   * asynchronously in an in-page context) or with a single string an no
   * callback where the dependency is resolved synchronously and returned.
   * The API is designed to be compatible with the CommonJS AMD spec and
   * RequireJS.
   * @param deps A name, or array of names for the payload
   * @param callback Function to call when the dependencies are resolved
   * @return The module required or undefined for array/callback method
   */
  Domain.prototype.require = function(deps, callback) {
    if (Array.isArray(deps)) {
      var params = deps.map(function(dep) {
        return this.lookup(dep);
      }, this);
      if (callback) {
        callback.apply(null, params);
      }
      return undefined;
    }
    else {
      return this.lookup(deps);
    }
  };

  /**
   * Lookup module names and resolve them by calling the definition function if
   * needed.
   * @param moduleName A name for the payload to lookup
   * @return The module specified by aModuleName or null if not found
   */
  Domain.prototype.lookup = function(moduleName) {
    if (moduleName in this.modules) {
      var module = this.modules[moduleName];
      if (define.debugDependencies) {
        console.log(this.depth + " Using module: " + moduleName);
      }
      return module;
    }

    if (!(moduleName in define.modules)) {
      console.error(this.depth + " Missing module: " + moduleName);
      return null;
    }

    var module = define.modules[moduleName];

    if (define.debugDependencies) {
      console.log(this.depth + " Compiling module: " + moduleName);
    }

    if (typeof module == "function") {
      if (define.debugDependencies) {
        this.depth += ".";
      }

      var exports = {};
      try {
        module(this.require.bind(this), exports, { id: moduleName, uri: "" });
      }
      catch (ex) {
        console.error("Error using module: " + moduleName, ex);
        throw ex;
      }
      module = exports;

      if (define.debugDependencies) {
        this.depth = this.depth.slice(0, -1);
      }
    }

    // cache the resulting module object for next time
    this.modules[moduleName] = module;

    return module;
  };

  /**
   * Expose the Domain constructor and a global domain (on the define function
   * to avoid exporting more than we need. This is a common pattern with
   * require systems)
   */
  define.Domain = Domain;
  define.globalDomain = new Domain();
})();

/**
 * Expose a default require function which is the require of the global
 * sandbox to make it easy to use.
 */
var require = define.globalDomain.require.bind(define.globalDomain);
<commit_msg>initial support for amd format modules<commit_after>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

/**
 * Define a module along with a payload.
 * @param moduleName Name for the payload
 * @param deps Ignored. For compatibility with CommonJS AMD Spec
 * @param payload Function with (require, exports, module) params
 */
function define(moduleName, deps, payload) {
  if (typeof moduleName != "string") {
    console.error(this.depth + " Error: Module name is not a string.");
    console.trace();
    return;
  }

  if (arguments.length == 2) {
    payload = deps;
  }
  else {
    payload.deps = deps;
  }

  if (define.debugDependencies) {
    console.log("define: " + moduleName + " -> " + payload.toString()
        .slice(0, 40).replace(/\n/, '\\n').replace(/\r/, '\\r') + "...");
  }

  if (moduleName in define.modules) {
    console.error(this.depth + " Error: Redefining module: " + moduleName);
  }
  define.modules[moduleName] = payload;
}

/**
 * The global store of un-instantiated modules
 */
define.modules = {};

/**
 * Should we console.log on module definition/instantiation/requirement?
 */
define.debugDependencies = false;

/**
 * Self executing function in which Domain is defined, and attached to define
 */
(function() {
  var Syntax = {
    COMMON_JS: 'commonjs',
    AMD: 'amd'
  };

  /**
   * We invoke require() in the context of a Domain so we can have multiple
   * sets of modules running separate from each other.
   * This contrasts with JSMs which are singletons, Domains allows us to
   * optionally load a CommonJS module twice with separate data each time.
   * Perhaps you want 2 command lines with a different set of commands in each,
   * for example.
   */
  function Domain() {
    this.modules = {};
    this.syntax = Syntax.COMMON_JS;

    if (define.debugDependencies) {
      this.depth = "";
    }
  }

  /**
   * Lookup module names and resolve them by calling the definition function if
   * needed.
   * There are 2 ways to call this, either with an array of dependencies and a
   * callback to call when the dependencies are found (which can happen
   * asynchronously in an in-page context) or with a single string an no
   * callback where the dependency is resolved synchronously and returned.
   * The API is designed to be compatible with the CommonJS AMD spec and
   * RequireJS.
   * @param deps A name, or array of names for the payload
   * @param callback Function to call when the dependencies are resolved
   * @return The module required or undefined for array/callback method
   */
  Domain.prototype.require = function(config, deps, callback) {
    if (arguments.length === 2) {
      callback = deps;
      deps = config;
      config = undefined;
    }

    if (Array.isArray(deps)) {
      this.syntax = Syntax.AMD;
      var params = deps.map(function(dep) {
        return this.lookup(dep);
      }, this);
      if (callback) {
        callback.apply(null, params);
      }
      return undefined;
    }
    else {
      return this.lookup(deps);
    }
  };

  /**
   * Lookup module names and resolve them by calling the definition function if
   * needed.
   * @param moduleName A name for the payload to lookup
   * @return The module specified by aModuleName or null if not found
   */
  Domain.prototype.lookup = function(moduleName) {
    if (moduleName in this.modules) {
      var module = this.modules[moduleName];
      if (define.debugDependencies) {
        console.log(this.depth + " Using module: " + moduleName);
      }
      return module;
    }

    if (!(moduleName in define.modules)) {
      console.error(this.depth + " Missing module: " + moduleName);
      return null;
    }

    var module = define.modules[moduleName];

    if (define.debugDependencies) {
      console.log(this.depth + " Compiling module: " + moduleName);
    }

    if (typeof module == "function") {
      if (define.debugDependencies) {
        this.depth += ".";
      }

      var exports;
      try {
        if (this.syntax === Syntax.COMMON_JS) {
          exports = {};
          module(this.require.bind(this), exports, { id: moduleName, uri: "" });
        }
        else {
          var modules = module.deps.map(function(dep) {
            return this.lookup(dep);
          }.bind(this));
          exports = module.apply(null, modules);
        }
      }
      catch (ex) {
        console.error("Error using module: " + moduleName, ex);
        throw ex;
      }
      module = exports;

      if (define.debugDependencies) {
        this.depth = this.depth.slice(0, -1);
      }
    }

    // cache the resulting module object for next time
    this.modules[moduleName] = module;

    return module;
  };

  /**
   * Expose the Domain constructor and a global domain (on the define function
   * to avoid exporting more than we need. This is a common pattern with
   * require systems)
   */
  define.Domain = Domain;
  define.globalDomain = new Domain();
})();

/**
 * Expose a default require function which is the require of the global
 * sandbox to make it easy to use.
 */
var require = define.globalDomain.require.bind(define.globalDomain);
<|endoftext|>