<commit_before>/* eslint max-nested-callbacks: [2, 5] react/jsx-wrap-multilines:0 */
/* eslint handle-callback-err: 0 no-magic-numbers:0  */
import request from "supertest";
import HttpResponseHandler from "../../common/src/HttpResponseHandler";
import ApplicationConfig from "../src/config/ApplicationConfig";
import { assert, expect } from "chai";
import CouchSession from "../src/CouchSession";

const requestTime = 7000;
describe("RssRoutesSpec", () => {
    describe("RssRoutesSpec", () => {
        let accessToken = null, applicationConfig = null, serverIp = null;
        before("RssRoutesSpec", (done)=> {
            applicationConfig = new ApplicationConfig();
            serverIp = applicationConfig.serverIpAddress() + ":" + applicationConfig.serverPort();
            CouchSession.login("test", "test").then((token) => {
                accessToken = token;
                done();
            });
        });

        it("should return status OK if the url is empty", (done) => {
            request(serverIp)
                .get("/rss-feeds")
                .query("url=")
                .set("Cookie", accessToken)
                .end((err, res) => {
                    assert.strictEqual(HttpResponseHandler.codes.BAD_REQUEST, res.statusCode);
                    done();
                });
        });

        it("should return data if the url is valid", (done) => {
            let expectedValues = {
                "items": [{ "title": "sample1", "description": "news cricket" },
                    { "title": "sample2", "description": "news politics" }
                ]
            };

            request(serverIp)
                .get("/rss-feeds")
                .query("url=http://localhost:3000/thehindu/rss-feeds/")
                .set("Cookie", accessToken)
                .end((err, res) => {
                    assert.strictEqual(HttpResponseHandler.codes.OK, res.statusCode);
                    let items = res.body.items;
                    let expectedItems = expectedValues.items;
                    expect(items.length).to.eq(expectedItems.length);
                    for(let index = 0; index < items.length; index += 1) {
                        expect(items[index].title).to.eq(expectedItems[index].title);
                        expect(items[index].description).to.eq(expectedItems[index].description);
                    }
                    done();
                });
        });

        it("responds with 400 for /rss-feeds if rss fetch returns error", (done) => {
            request(serverIp)
                .get("/rss-feeds")
                .query("url=http://localhost:3000/thehindu/error-feeds/")
                .set("Cookie", accessToken)
                .end((err, res) => {
                    assert.strictEqual(res.statusCode, HttpResponseHandler.codes.BAD_REQUEST);
                    assert.strictEqual(res.body.message, "bad request");
                    done();
                });
        });

        it("should timeout if fetching rss feeds exceeds time out", (done) => {
            request(serverIp)
                .get("/rss-feeds")
                .query("url=http://localhost:3000/gardian/timeout-feeds/")
                .set("Cookie", accessToken)
                .end((err, res) => {
                    assert.strictEqual(res.statusCode, HttpResponseHandler.codes.BAD_REQUEST);
                    assert.strictEqual(res.body.message, "bad request");
                    done();
                });
        }).timeout(requestTime);

        it("should fetch feeds for multiple rss urls", (done) => {
            let expectedResponse = {
                "B7CF1576-05BB-DD75-BA53-9E9EC1E6C5D4": {
                    "items": [
                        {
                            "title": "CNG stations ready, where are the buses?",
                            "description": "Will any bus use the Compressed Natural Gas (CNG) that is expected to be supplied from March"
                        },
                        {
                            "title": "Leaders fret over traffic congestion",
                            "description": "It is not only common people who are cribbing about traffic congestion"
                        }
                    ]
                },
                "214F7943-36F3-84F3-9E21-CDC9939E1468": {
                    "items": [
                        {
                            "title": "Sewage woes plague road-users in Chennai",
                            "description": "Incidents of sewage overflowing on arterial roads due to obstructions in the underground sewer network have been reported from different localities across the city"
                        },
                        {
                            "title": "Not many takers for first class in Metro",
                            "description": "As the majority of Metro users believe the fares for the first class have been priced too high, this coach has less takers, commuters say"
                        }
                    ]

                }
            };

            request(serverIp)
                .post("/fetch-all-rss")
                .send({
                    "data": [
                        {
                            "timestamp": "2016-02-04T04:46:39+00:00",
                            "url": "http://localhost:3000/news/cities/bangalore/?service=rss",
                            "id": "B7CF1576-05BB-DD75-BA53-9E9EC1E6C5D4"
                        },
                        {
                            "timestamp": "2016-02-04T04:48:10+00:00",
                            "url": "http://localhost:3000/news/cities/chennai/?service=rss",
                            "id": "214F7943-36F3-84F3-9E21-CDC9939E1468"
                        }
                    ]
                })
                .set("Cookie", accessToken)
                .end((err, res) => {
                    assert.strictEqual(res.body["B7CF1576-05BB-DD75-BA53-9E9EC1E6C5D4"].items[0].title, expectedResponse["B7CF1576-05BB-DD75-BA53-9E9EC1E6C5D4"].items[0].title);
                    assert.strictEqual(res.body["B7CF1576-05BB-DD75-BA53-9E9EC1E6C5D4"].items[0].description, expectedResponse["B7CF1576-05BB-DD75-BA53-9E9EC1E6C5D4"].items[0].description);
                    assert.strictEqual(res.body["B7CF1576-05BB-DD75-BA53-9E9EC1E6C5D4"].items[1].title, expectedResponse["B7CF1576-05BB-DD75-BA53-9E9EC1E6C5D4"].items[1].title);
                    assert.strictEqual(res.body["B7CF1576-05BB-DD75-BA53-9E9EC1E6C5D4"].items[1].description, expectedResponse["B7CF1576-05BB-DD75-BA53-9E9EC1E6C5D4"].items[1].description);

                    assert.strictEqual(res.body["214F7943-36F3-84F3-9E21-CDC9939E1468"].items[0].title, expectedResponse["214F7943-36F3-84F3-9E21-CDC9939E1468"].items[0].title);
                    assert.strictEqual(res.body["214F7943-36F3-84F3-9E21-CDC9939E1468"].items[0].description, expectedResponse["214F7943-36F3-84F3-9E21-CDC9939E1468"].items[0].description);
                    assert.strictEqual(res.body["214F7943-36F3-84F3-9E21-CDC9939E1468"].items[1].title, expectedResponse["214F7943-36F3-84F3-9E21-CDC9939E1468"].items[1].title);
                    assert.strictEqual(res.body["214F7943-36F3-84F3-9E21-CDC9939E1468"].items[1].description, expectedResponse["214F7943-36F3-84F3-9E21-CDC9939E1468"].items[1].description);

                    assert.strictEqual(HttpResponseHandler.codes.OK, res.statusCode);
                    done();
                });

        });
    });
});
<commit_msg>[Mht]- fixed functional test for RssRoutesSpec<commit_after>/* eslint max-nested-callbacks: [2, 5] react/jsx-wrap-multilines:0 */
/* eslint handle-callback-err: 0 no-magic-numbers:0  */
import request from "supertest";
import HttpResponseHandler from "../../common/src/HttpResponseHandler";
import ApplicationConfig from "../src/config/ApplicationConfig";
import { assert, expect } from "chai";
import CouchSession from "../src/CouchSession";

const requestTime = 7000;
describe("RssRoutesSpec", () => {
    describe("RssRoutesSpec", () => {
        let accessToken = null, applicationConfig = null, serverIp = null;
        before("RssRoutesSpec", (done)=> {
            applicationConfig = new ApplicationConfig();
            serverIp = applicationConfig.serverIpAddress() + ":" + applicationConfig.serverPort();
            CouchSession.login("test", "test").then((token) => {
                accessToken = token;
                done();
            });
        });

        it("should return status OK if the url is empty", (done) => {
            request(serverIp)
                .get("/rss-feeds")
                .query("url=")
                .set("Cookie", accessToken)
                .end((err, res) => {
                    assert.strictEqual(HttpResponseHandler.codes.BAD_REQUEST, res.statusCode);
                    done();
                });
        });

        it("should return data if the url is valid", (done) => {
            let expectedValues = {
                "items": [{ "title": "sample1", "description": "news cricket" },
                    { "title": "sample2", "description": "news politics" }
                ]
            };

            request(serverIp)
                .get("/rss-feeds")
                .query("url=http://localhost:3000/thehindu/rss-feeds/")
                .set("Cookie", accessToken)
                .end((err, res) => {
                    assert.strictEqual(HttpResponseHandler.codes.OK, res.statusCode);
                    let items = res.body.items;
                    let expectedItems = expectedValues.items;
                    expect(items.length).to.eq(expectedItems.length);
                    for(let index = 0; index < items.length; index += 1) {
                        expect(items[index].title).to.eq(expectedItems[index].title);
                        expect(items[index].description).to.eq(expectedItems[index].description);
                    }
                    done();
                });
        });

        it("responds with 400 for /rss-feeds if rss fetch returns error", (done) => {
            request(serverIp)
                .get("/rss-feeds")
                .query("url=http://localhost:3000/thehindu/error-feeds/")
                .set("Cookie", accessToken)
                .end((err, res) => {
                    assert.strictEqual(res.statusCode, HttpResponseHandler.codes.BAD_REQUEST);
                    assert.strictEqual(res.body.message, "bad request");
                    done();
                });
        });

        it("should timeout if fetching rss feeds exceeds time out", (done) => {
            request(serverIp)
                .get("/rss-feeds")
                .query("url=http://localhost:3000/gardian/timeout-feeds/")
                .set("Cookie", accessToken)
                .end((err, res) => {
                    assert.strictEqual(res.statusCode, HttpResponseHandler.codes.BAD_REQUEST);
                    assert.strictEqual(res.body.message, "bad request");
                    done();
                });
        }).timeout(requestTime);

        it("should return successful message when feeds saved for multiple rss urls", (done) => {
            let expectedResponse = "sucessfully added feeds";
            request(serverIp)
                .post("/fetch-all-rss")
                .send({
                    "data": [
                        {
                            "timestamp": "2016-02-04T04:46:39+00:00",
                            "url": "http://localhost:3000/news/cities/bangalore/?service=rss",
                            "id": "B7CF1576-05BB-DD75-BA53-9E9EC1E6C5D4"
                        },
                        {
                            "timestamp": "2016-02-04T04:48:10+00:00",
                            "url": "http://localhost:3000/news/cities/chennai/?service=rss",
                            "id": "214F7943-36F3-84F3-9E21-CDC9939E1468"
                        }
                    ]
                })
                .set("Cookie", accessToken)
                .end((err, res) => {
                    assert.equal(res.body.message, expectedResponse);
                    assert.strictEqual(HttpResponseHandler.codes.OK, res.statusCode);
                    done();
                });

        });
    });
});
<|endoftext|>


<commit_before>// Generate calls to "testing functions" shared between the SpiderMonkey shell and Firefox browser.
// http://mxr.mozilla.org/mozilla-central/source/js/src/builtin/TestingFunctions.cpp

var fuzzTestingFunctions = (function(glob){

  var browser = "window" in glob;

  function tf(funName) {
    if (!browser && (rnd(5) == 0)) {
      // Differential testing hack!
      // Take advantage of the fact that --no-asmjs flips isAsmJSCompilationAvailable().
      // (I couldn't find a better way to communicate from compareJIT to jsfunfuzz:
      // doing --execute='gcslice=function(){}' changes the result of uneval(this)!)
      var cond = (rnd(2) ? "!" : "") + "isAsmJSCompilationAvailable()";
      return "(" + cond + " ? " + funName + " : (function(){}))";
    }
    return browser ? "fuzzPriv." + funName : funName;
  }

  function numberOfAllocs() { return Math.floor(Math.exp(rnd(rnd(6000)) / 1000)); }

  function global(d, b) { return browser ? Things.instance("Window") : makeExpr(d - 1, b); }
  function object(d, b) { return browser ? Things.any() : makeExpr(d - 1, b); }

  function enableGCZeal()
  {
    var level = rnd(14);
    if (browser && level == 9) level = 0; // bug 815241
    var period = numberOfAllocs();
    return tf("gczeal") + "(" + level + ", " + period + ")";
  }

  var testingFunctions = Random.weighted([
    // Force garbage collection (global or specific compartment)
    { w: 10, v: function(d, b) { return "(void " + tf("gc") + "()" + ")"; } },
    { w: 10, v: function(d, b) { return "(void " + tf("gc") + "('compartment')" + ")"; } },
    { w: 5,  v: function(d, b) { return "(void " + tf("gc") + "(" + global(d, b) + ")" + ")"; } },

    // Run a minor garbage collection on the nursery.
    // (void is for bug 940253)
    { w: 20, v: function(d, b) { return "(void " + tf("minorgc") + "(false)" + ")"; } },
    { w: 20, v: function(d, b) { return "(void " + tf("minorgc") + "(true)" + ")"; } },

    // Invoke an incremental garbage collection slice.
    { w: 20, v: function(d, b) { return tf("gcslice") + "(" + Math.floor(Math.pow(2, Random.float() * 32)) + ")"; } },

    // Schedule the given objects to be marked in the next GC slice.
    { w: 10, v: function(d, b) { return tf("selectforgc") + "(" + object(d, b) + ")"; } },

    // Add a compartment to the next garbage collection.
    { w: 10, v: function(d, b) { return tf("schedulegc") + "(" + global(d, b) + ")"; } },

    // Schedule a GC for after N allocations.
    { w: 10, v: function(d, b) { return tf("schedulegc") + "(" + numberOfAllocs() + ")"; } },

    // Make garbage collection extremely frequent (SLOW)
    { w: 1,  v: function(d, b) { return (!browser || rnd(100) == 0) ? (enableGCZeal()) : "0"; } },

    // Verify write barriers. These functions are effective in pairs.
    // The first call sets up the start barrier, the second call sets up the end barrier.
    // Nothing happens when there is only one call.
    { w: 10, v: function(d, b) { return tf("verifyprebarriers") + "()"; } },
    { w: 10, v: function(d, b) { return tf("verifypostbarriers") + "()"; } },

    // Trace the heap using non-GC tracing code
    { w: 1,  v: function(d, b) { return "(void " + tf("countHeap") + "()" + ")"; } },

    // Toggle various validations.
    { w: 5,  v: function(d, b) { return tf("validategc") + "(false)"; } },
    { w: 1,  v: function(d, b) { return tf("validategc") + "(true)"; } },
    { w: 5,  v: function(d, b) { return tf("fullcompartmentchecks") + "(false)"; } },
    { w: 1,  v: function(d, b) { return tf("fullcompartmentchecks") + "(true)"; } },
    { w: 5,  v: function(d, b) { return tf("setIonAssertGraphCoherency") + "(false)"; } },
    { w: 1,  v: function(d, b) { return tf("setIonAssertGraphCoherency") + "(true)"; } },
    { w: 1,  v: function(d, b) { return tf("enableOsiPointRegisterChecks") + "()"; } },

    // Run-time equivalents to --baseline-eager or --baseline-uses-before-compile, --no-baseline, etc
    { w: 1,  v: function(d, b) { return tf("setJitCompilerOption") + "('baseline.usecount.trigger', " + rnd(20) + ")"; } },
    { w: 1,  v: function(d, b) { return tf("setJitCompilerOption") + "('ion.usecount.trigger', " + rnd(40) + ")"; } },
    { w: 1,  v: function(d, b) { return tf("setJitCompilerOption") + "('ion.enable', " + rnd(2) + ")"; } },
    //{ w: 1,  v: function(d, b) { return tf("setJitCompilerOption") + "('baseline.enable', " + rnd(2) + ")"; } }, // bug 932284

    // I'm not sure what this does in the shell.
    { w: 5,  v: function(d, b) { return tf("deterministicgc") + "(false)"; } },
    { w: 1,  v: function(d, b) { return tf("deterministicgc") + "(true)"; } },

    // Causes JIT code to always be preserved by GCs afterwards (see https://bugzilla.mozilla.org/show_bug.cgi?id=750834)
    { w: 5,  v: function(d, b) { return tf("gcPreserveCode") + "()"; } },
  ]);

  return { testingFunctions: testingFunctions, enableGCZeal: enableGCZeal }

})(this);
<commit_msg>Work around bug 944153<commit_after>// Generate calls to "testing functions" shared between the SpiderMonkey shell and Firefox browser.
// http://mxr.mozilla.org/mozilla-central/source/js/src/builtin/TestingFunctions.cpp

var fuzzTestingFunctions = (function(glob){

  var browser = "window" in glob;

  function tf(funName) {
    if (!browser && (rnd(5) == 0)) {
      // Differential testing hack!
      // Take advantage of the fact that --no-asmjs flips isAsmJSCompilationAvailable().
      // (I couldn't find a better way to communicate from compareJIT to jsfunfuzz:
      // doing --execute='gcslice=function(){}' changes the result of uneval(this)!)
      var cond = (rnd(2) ? "!" : "") + "isAsmJSCompilationAvailable()";
      return "(" + cond + " ? " + funName + " : (function(){}))";
    }
    return browser ? "fuzzPriv." + funName : funName;
  }

  function numberOfAllocs() { return Math.floor(Math.exp(rnd(rnd(6000)) / 1000)); }

  function global(d, b) { return browser ? Things.instance("Window") : makeExpr(d - 1, b); }
  function object(d, b) { return browser ? Things.any() : makeExpr(d - 1, b); }

  function enableGCZeal()
  {
    var level = rnd(14);
    if (browser && level == 9) level = 0; // bug 815241
    var period = numberOfAllocs();
    return tf("gczeal") + "(" + level + ", " + period + ")";
  }

  var testingFunctions = Random.weighted([
    // Force garbage collection (global or specific compartment)
    { w: 10, v: function(d, b) { return "(void " + tf("gc") + "()" + ")"; } },
    { w: 10, v: function(d, b) { return "(void " + tf("gc") + "('compartment')" + ")"; } },
    { w: 5,  v: function(d, b) { return "(void " + tf("gc") + "(" + global(d, b) + ")" + ")"; } },

    // Run a minor garbage collection on the nursery.
    // (void is for bug 940253)
    { w: 20, v: function(d, b) { return "(void " + tf("minorgc") + "(false)" + ")"; } },
    { w: 20, v: function(d, b) { return "(void " + tf("minorgc") + "(true)" + ")"; } },

    // Invoke an incremental garbage collection slice.
    { w: 20, v: function(d, b) { return tf("gcslice") + "(" + Math.floor(Math.pow(2, Random.float() * 32)) + ")"; } },

    // Schedule the given objects to be marked in the next GC slice.
    { w: 10, v: function(d, b) { return tf("selectforgc") + "(" + object(d, b) + ")"; } },

    // Add a compartment to the next garbage collection.
    { w: 10, v: function(d, b) { return tf("schedulegc") + "(" + global(d, b) + ")"; } },

    // Schedule a GC for after N allocations.
    { w: 10, v: function(d, b) { return tf("schedulegc") + "(" + numberOfAllocs() + ")"; } },

    // Make garbage collection extremely frequent (SLOW)
    { w: 1,  v: function(d, b) { return (!browser || rnd(100) == 0) ? (enableGCZeal()) : "0"; } },

    // Verify write barriers. These functions are effective in pairs.
    // The first call sets up the start barrier, the second call sets up the end barrier.
    // Nothing happens when there is only one call.
    { w: 10, v: function(d, b) { return tf("verifyprebarriers") + "()"; } },
    { w: 10, v: function(d, b) { return tf("verifypostbarriers") + "()"; } },

    // Trace the heap using non-GC tracing code
    { w: 1,  v: function(d, b) { return "(void " + tf("countHeap") + "()" + ")"; } },

    // Toggle various validations.
    { w: 5,  v: function(d, b) { return tf("validategc") + "(false)"; } },
    { w: 1,  v: function(d, b) { return tf("validategc") + "(true)"; } },
    { w: 5,  v: function(d, b) { return tf("fullcompartmentchecks") + "(false)"; } },
    { w: 1,  v: function(d, b) { return tf("fullcompartmentchecks") + "(true)"; } },
    { w: 5,  v: function(d, b) { return tf("setIonAssertGraphCoherency") + "(false)"; } },
    { w: 1,  v: function(d, b) { return tf("setIonAssertGraphCoherency") + "(true)"; } },
    { w: 1,  v: function(d, b) { return tf("enableOsiPointRegisterChecks") + "()"; } },

    // Run-time equivalents to --baseline-eager or --baseline-uses-before-compile, --no-baseline, etc
    // (void is for bug 944153)
    { w: 1,  v: function(d, b) { return "(void " + tf("setJitCompilerOption") + "('baseline.usecount.trigger', " + rnd(20) + ")" + ")"; } },
    { w: 1,  v: function(d, b) { return "(void " + tf("setJitCompilerOption") + "('ion.usecount.trigger', " + rnd(40) + ")" + ")"; } },
    { w: 1,  v: function(d, b) { return "(void " + tf("setJitCompilerOption") + "('ion.enable', " + rnd(2) + ")" + ")"; } },
    //{ w: 1,  v: function(d, b) { return tf("setJitCompilerOption") + "('baseline.enable', " + rnd(2) + ")"; } }, // bug 932284

    // I'm not sure what this does in the shell.
    { w: 5,  v: function(d, b) { return tf("deterministicgc") + "(false)"; } },
    { w: 1,  v: function(d, b) { return tf("deterministicgc") + "(true)"; } },

    // Causes JIT code to always be preserved by GCs afterwards (see https://bugzilla.mozilla.org/show_bug.cgi?id=750834)
    { w: 5,  v: function(d, b) { return tf("gcPreserveCode") + "()"; } },
  ]);

  return { testingFunctions: testingFunctions, enableGCZeal: enableGCZeal }

})(this);
<|endoftext|>


<commit_before>
angular.module('ng-xCharts', [])
    .directive('xchart', function () {
        var graphIdCount = 0;
        return {
            restrict: 'EACM',
            template: '

',
            replace: true,

            link: function (scope, elem, attrs) {
                var elemId;
                if(!(elemId = elem.attr('id'))){
                    graphIdCount++;
                    elemId = 'graph-' + graphIdCount;
                    elem.attr('id', elemId);
                }
                new xChart(scope.$eval(attrs.type), scope.$eval(attrs.data), '#' + elemId, scope.$eval(attrs.opts));
            }
        };
    });<commit_msg>Add watch on 'data' for redraw on data changes<commit_after>angular.module('ng-xCharts', [])
    .directive('xchart', function () {
        var graphIdCount = 0;
        return {
            restrict: 'EACM',
            template: '

',
            replace: true,

            link: function (scope, elem, attrs) {
                var elemId;
                if(!(elemId = elem.attr('id'))){
                    graphIdCount++;
                    elemId = 'graph-' + graphIdCount;
                    elem.attr('id', elemId);
                }

                var chart = null;

                scope.$watch(attrs.data, function(v) {
                    if (!chart) {
                        chart = new xChart(scope.$eval(attrs.type), v, '#' + elemId, scope.$eval(attrs.opts));
                    } else {
                        chart.setData(v);
                    }
                }, true);
            }
        };
    });
<|endoftext|>


<commit_before>//// NPM
const simpleGit = require('simple-git/promise')
//// CORE
const path = require('path')
//// LOCAL
const { confirm, input } = require('../lib/api')
const { format, log } = require('../lib/log')
const { words } = require('../lib/store')
const { name } = require('../lib/viewer')

const { appRepo } = require('../package.json')
const config = require('../config/config.json')

const git = simpleGit(process.cwd())

module.exports = repo = {
  commit: async (comment) => {
    return new Promise( async (resolve, reject) => {
      try {
        if (!await git.checkIsRepo()) {
          resolve(log('error', `${name()} git repository not found.` ))
        }
        const status = await git.status()
        for (const key of Object.keys(status)) {
          if (Array.isArray(status[key]) && status[key].length>0) {
            log('log', status)
            break
          }
        }
        if (await confirm(`Commit changes to ${name()} repo now?`)) {
          return git.add('.')
          .then( async () => {
            const comment = await input('Commit comment', `CLI source file changes detected at startup`)
            resolve(git.commit(comment))
          })
          .catch( err => resolve(log('error', `(commitChanges) error\n${format(err)}`)))
        }
      }
      catch(err) {
        resolve(log('error', `(commitChanges) error\n${format(err)}`))
      }
    })
  },
  git,
  push: async (user, phrase, origin) => {
    try {
      const remote = `https://${user}:${phrase}@${origin}`;
      if (origin && (await git.status()).ahead>0) {
        if (await confirm(`Push changes to '${origin}' now?`)) {
          if (await git.listRemote()) {
            await git.push(remote, 'master')
          }
          log('log', `tracked changes pushed`)
        }
      }
    }
    catch(err) {
      log('error', `(push) error \n${format(err)}`)
    }
  }
}
<commit_msg>CLI source file changes detected<commit_after>//// NPM
const simpleGit = require('simple-git/promise')
//// CORE
const path = require('path')
//// LOCAL
const { confirm, input } = require('../lib/api')
const { format, log } = require('../lib/log')
const { words } = require('../lib/store')
const { name } = require('../lib/viewer')

const { appRepo } = require('../package.json')
const config = require('../config/config.json')

const git = simpleGit(process.cwd())

module.exports = repo = {
  commit: async (comment) => {
    return new Promise( async (resolve, reject) => {
      try {
        if (!await git.checkIsRepo()) {
          resolve(log('error', `${name()} git repository not found.` ))
        }
        const status = await git.status()
        for (const key of Object.keys(status)) {
          if (Array.isArray(status[key]) && status[key].length>0) {
            log('log', status)
            break
          }
        }
        if (await confirm(`Commit changes to ${name()} repo now?`)) {
          return git.add('.')
          .then( async () => {
            const comment = await input('Commit comment', `CLI source file changes detected`)
            await git.commit(comment)
          })
          .catch( err => resolve(log('error', `(commitChanges) error\n${format(err)}`)))
        }
        resolve()
      }
      catch(err) {
        resolve(log('error', `(commitChanges) error\n${format(err)}`))
      }
    })
  },
  git,
  push: async (user, phrase, origin) => {
    try {
      const remote = `https://${user}:${phrase}@${origin}`;
      if (origin && (await git.status()).ahead>0) {
        if (await confirm(`Push changes to '${origin}' now?`)) {
          if (await git.listRemote()) {
            await git.push(remote, 'master')
          }
          log('log', `tracked changes pushed`)
        }
      }
    }
    catch(err) {
      log('error', `(push) error \n${format(err)}`)
    }
  }
}
<|endoftext|>


<commit_before>function Ising() {
    var l=100;
    var n = l*l;
    var tc = 2.0/(Math.log(Math.sqrt(2.0)+1.0)); // T_c(SQ)
    var temp = tc;
    var algorithm = 0;

    var running = false;
    var timerID;
    var basetime = 0;
    var interval = 40; // [msec]

    var w=3;
    var canvas = document.getElementById('ising');
    var context = canvas.getContext('2d');
    canvas.width = canvas.height = l*(w+1)-1;

    var spin = new Array(n);
    var spinBefore = new Array(n);
    for(var i=0;i<n;++i) {
        spin[i] = (Math.random()<0.5) ? 1 : -1;
        spinBefore[i] = 0;
    }

    var cluster = new Array(n);

    function draw() {
        context.fillStyle = '#3366cc';
        for(var i=0;i<l;++i) {
            for(var j=0;j<l;++j) {
                var idx = i*l+j;
                if(spin[idx]==1 && spinBefore[idx]!=1)
                    context.fillRect(j*(w+1),i*(w+1),w,w);
            }
        }
        context.fillStyle = '#ffffff';
        for(var i=0;i<l;++i) {
            for(var j=0;j<l;++j) {
                var idx = i*l+j;
                if(spin[idx]==-1 && spinBefore[idx]!=-1)
                    context.fillRect(j*(w+1),i*(w+1),w,w);
            }
        }
        for(var i=0;i<n;++i) spinBefore[i] = spin[i];
    }

    function updateSpin() {
        if(algorithm==0) heatBath();
        else if(algorithm==1) swendsenWang();
        else if(algorithm==2) wolff();
        else randomUpdate();
    }

    function heatBath() {
        interval = 40;
        // 1MCS update
        for(var k=0;k<n;++k) {
            var i = randomInt(0,n);
            var s0 = spin[i];
            var s1 = spin[(i+1)%n];
            var s2 = spin[(i-1+n)%n];
            var s3 = spin[(i+l)%n];
            var s4 = spin[(i-l+n)%n];
            var prob = 1.0/(1.0+Math.exp(2.0*s0*(s1+s2+s3+s4)/temp))
            if(Math.random()<prob) spin[i] = -s0;
        }
    }

    function swendsenWang() {
        interval = 100;
        var prob = 1.0-Math.exp(-2.0/temp);
        makeCluster(prob);
        for(var i=0;i<n;++i) {
            var root = cluster[i];
            if(i == root) {
                spin[i] = (Math.random()<0.5) ? 1 : -1;
            } else {
                spin[i] = spin[root];
            }
        }
    }

    function wolff() {
        interval = 100;
        var prob = 1.0-Math.exp(-2.0/temp);
        var count = 0;

        makeCluster(prob);
        while(count<n/5) {
            var updateCluster = cluster[randomInt(0,n)];
            for(var i=0;i<n;++i) {
                if(cluster[i] == updateCluster) {
                    spin[i] = -spin[i];
                    count++;
                }
            }
        }
    }

    function findRoot(i) {
        var child = i;
        var parent = cluster[child];
        while(child != parent) {
            child = parent;
            parent = cluster[child];
        }
        return child;
    }

    function connect(i,j) {
        var ri = findRoot(i);
        var rj = findRoot(j);
        var root = (ri<rj) ? ri : rj;
        var child = i;
        while(child != root) {
            var parent = cluster[child];
            cluster[child] = root;
            child = parent;
        }
        var child = j;
        while(child != root) {
            var parent = cluster[child];
            cluster[child] = root;
            child = parent;
        }
    }

    function makeCluster(prob) {
        for(var i=0;i<n;++i) cluster[i]=i;
        for(var i=0;i<n;++i) { // horizontal bonds
            var j = (i+1)%n;
            if(spin[i]==spin[j] && Math.random()<prob) connect(i,j);
        }
        for(var i=0;i<n;++i) { // vartical bonds
            var j = (i+l)%n;
            if(spin[i]==spin[j] && Math.random()<prob) connect(i,j);
        }
        for(var i=0;i<n;++i) {
            cluster[i] = findRoot(i);
        }
    }

    function randomInt(min,max) {
        return Math.floor(Math.random() * (max-min))+min;
    }

    function magnetization() {
        var m = 0.0;
        for(var i=0;i<n;++i) {
            m += spin[i];
        }
        return m/n;
    }

    function randomUpdate() {
        interval = 200;
        for(var i=0;i<n;++i) {
            if(Math.random()<0.5) spin[i] = 1;
            else spin[i] = -1;
        }
    }

    function update() {
        updateSpin();
        draw();
        graph.addPoint(temp,magnetization(),algorithm);
    }

    function loop() {
        var now = Date.now();
        if(now-basetime>interval) {
            basetime = now;
            update();
        }
        timerID = requestAnimationFrame(loop);
    }

    return {
        start: function() {
            if(!running) loop();
            running = true;
        },
        stop: function() {
            cancelAnimationFrame(timerID);
            running = false;
        },
        step: function() {
            cancelAnimationFrame(timerID);
            running = false;
            update();
        },
        setTemp: function(t) {temp=t;},
        setTempTc: function() {temp=tc;},
        getTemp: function() {return temp;},
        setAlgorithm: function(a) {algorithm=a;}
    }
}

function Graph() {
    var canvas = document.getElementById("graph");
    var context = canvas.getContext("2d");
    var offset = 7.5;
    var w = 11;
    var t_min = 0.5;
    var t_del = 0.1;

    var width = canvas.width = 400-1;
    var height = canvas.height = w*10+offset*2;

    reset();

    function x(t) {return w*(t-t_min)/t_del+offset;}
    function y(m) {return w*(1.0-m)/0.2+offset;}
    function t(x) {
        var t = t_del*(x-offset)/w+t_min;
        t = Math.round(t*100)/100;
        if(t<0.5) t=0.5;
        if(t>4.0) t=4.0;
        return t;
    }

    function addPoint(t,m,a) {
        // console.log(t+" "+m+" "+x+" "+y);
        if(a==0) context.fillStyle = "#9999ff";
        else if(a==1) context.fillStyle = "#99ff99";
        else if(a==2) context.fillStyle = "#ff9999";
        else context.fillStyle = "#ffffff";
        context.beginPath();
        context.arc( x(t), y(m), 2,0,2*Math.PI,true);
        context.fill();
    }

    function reset() {
        context.fillStyle = "#161616";
        context.fillRect(0,0,width,height)

        context.lineWidth = 1;

        context.strokeStyle = "#333333";
        for(var i=0;i<36;++i)  {
            context.beginPath();
            context.moveTo(offset+i*w, 0);
            context.lineTo(offset+i*w, height);
            context.stroke();
        }
        for(var i=0;i<11;++i) {
            context.beginPath();
            context.moveTo(0, offset+i*w);
            context.lineTo(width, offset+i*w);
            context.stroke();
        }

        context.strokeStyle = "#666666";
        for(var i=0;i<36;i+=5)  {
            context.beginPath();
            context.moveTo(offset+i*w, 0);
            context.lineTo(offset+i*w, height);
            context.stroke();
        }
        for(var i=0;i<11;i+=5) {
            context.beginPath();
            context.moveTo(0, offset+i*w);
            context.lineTo(width, offset+i*w);
            context.stroke();
        }

        context.strokeStyle = "#cccccc";
        context.beginPath();
        context.moveTo(0, height/2);
        context.lineTo(width, height/2);
        context.stroke();
    }

    return {
        addPoint: addPoint,
        reset: reset,
        getT: t
    }
}

var ising = Ising();
var graph = Graph();

$(function () {
    var initT = 2.27;

    function setT(t) {
        $( "#temperature_value" ).text( t );
        ising.setTemp(t);
        $("#temperature").slider("setValue", t);
    }

    var t_slider = $("#temperature").slider({
        min: 0.5,
        max: 4.0,
        step: 0.01,
        value: initT
    });

    t_slider.on("slide", function(e) {
        setT( e.value );
    });
    t_slider.prev().on("click",function() {
        setT( t_slider.slider("getValue") );
    });

    $("#start").on("click", ising.start);
    $("#stop" ).on("click", ising.stop);
    $("#step" ).on("click", ising.step);

    $("#algorithm").on("change", function() {
        ising.setAlgorithm( $(this).val() );
    });

    $("#graph").on("click", function(e) {
        setT( graph.getT(e.offsetX) );
    });

    $("#clear").on("click", graph.reset);

    setT(initT);
    ising.start();
});
<commit_msg>Modified for Firefox<commit_after>function Ising() {
    var l=100;
    var n = l*l;
    var tc = 2.0/(Math.log(Math.sqrt(2.0)+1.0)); // T_c(SQ)
    var temp = tc;
    var algorithm = 0;

    var running = false;
    var timerID;
    var basetime = 0;
    var interval = 40; // [msec]

    var w=3;
    var canvas = document.getElementById('ising');
    var context = canvas.getContext('2d');
    canvas.width = canvas.height = l*(w+1)-1;

    var spin = new Array(n);
    var spinBefore = new Array(n);
    for(var i=0;i<n;++i) {
        spin[i] = (Math.random()<0.5) ? 1 : -1;
        spinBefore[i] = 0;
    }

    var cluster = new Array(n);

    function draw() {
        context.fillStyle = '#3366cc';
        for(var i=0;i<l;++i) {
            for(var j=0;j<l;++j) {
                var idx = i*l+j;
                if(spin[idx]==1 && spinBefore[idx]!=1)
                    context.fillRect(j*(w+1),i*(w+1),w,w);
            }
        }
        context.fillStyle = '#ffffff';
        for(var i=0;i<l;++i) {
            for(var j=0;j<l;++j) {
                var idx = i*l+j;
                if(spin[idx]==-1 && spinBefore[idx]!=-1)
                    context.fillRect(j*(w+1),i*(w+1),w,w);
            }
        }
        for(var i=0;i<n;++i) spinBefore[i] = spin[i];
    }

    function updateSpin() {
        if(algorithm==0) heatBath();
        else if(algorithm==1) swendsenWang();
        else if(algorithm==2) wolff();
        else randomUpdate();
    }

    function heatBath() {
        interval = 40;
        // 1MCS update
        for(var k=0;k<n;++k) {
            var i = randomInt(0,n);
            var s0 = spin[i];
            var s1 = spin[(i+1)%n];
            var s2 = spin[(i-1+n)%n];
            var s3 = spin[(i+l)%n];
            var s4 = spin[(i-l+n)%n];
            var prob = 1.0/(1.0+Math.exp(2.0*s0*(s1+s2+s3+s4)/temp))
            if(Math.random()<prob) spin[i] = -s0;
        }
    }

    function swendsenWang() {
        interval = 100;
        var prob = 1.0-Math.exp(-2.0/temp);
        makeCluster(prob);
        for(var i=0;i<n;++i) {
            var root = cluster[i];
            if(i == root) {
                spin[i] = (Math.random()<0.5) ? 1 : -1;
            } else {
                spin[i] = spin[root];
            }
        }
    }

    function wolff() {
        interval = 100;
        var prob = 1.0-Math.exp(-2.0/temp);
        var count = 0;

        makeCluster(prob);
        while(count<n/5) {
            var updateCluster = cluster[randomInt(0,n)];
            for(var i=0;i<n;++i) {
                if(cluster[i] == updateCluster) {
                    spin[i] = -spin[i];
                    count++;
                }
            }
        }
    }

    function findRoot(i) {
        var child = i;
        var parent = cluster[child];
        while(child != parent) {
            child = parent;
            parent = cluster[child];
        }
        return child;
    }

    function connect(i,j) {
        var ri = findRoot(i);
        var rj = findRoot(j);
        var root = (ri<rj) ? ri : rj;
        var child = i;
        while(child != root) {
            var parent = cluster[child];
            cluster[child] = root;
            child = parent;
        }
        var child = j;
        while(child != root) {
            var parent = cluster[child];
            cluster[child] = root;
            child = parent;
        }
    }

    function makeCluster(prob) {
        for(var i=0;i<n;++i) cluster[i]=i;
        for(var i=0;i<n;++i) { // horizontal bonds
            var j = (i+1)%n;
            if(spin[i]==spin[j] && Math.random()<prob) connect(i,j);
        }
        for(var i=0;i<n;++i) { // vartical bonds
            var j = (i+l)%n;
            if(spin[i]==spin[j] && Math.random()<prob) connect(i,j);
        }
        for(var i=0;i<n;++i) {
            cluster[i] = findRoot(i);
        }
    }

    function randomInt(min,max) {
        return Math.floor(Math.random() * (max-min))+min;
    }

    function magnetization() {
        var m = 0.0;
        for(var i=0;i<n;++i) {
            m += spin[i];
        }
        return m/n;
    }

    function randomUpdate() {
        interval = 200;
        for(var i=0;i<n;++i) {
            if(Math.random()<0.5) spin[i] = 1;
            else spin[i] = -1;
        }
    }

    function update() {
        updateSpin();
        draw();
        graph.addPoint(temp,magnetization(),algorithm);
    }

    function loop() {
        var now = Date.now();
        if(now-basetime>interval) {
            basetime = now;
            update();
        }
        timerID = requestAnimationFrame(loop);
    }

    return {
        start: function() {
            if(!running) loop();
            running = true;
        },
        stop: function() {
            cancelAnimationFrame(timerID);
            running = false;
        },
        step: function() {
            cancelAnimationFrame(timerID);
            running = false;
            update();
        },
        setTemp: function(t) {temp=t;},
        setTempTc: function() {temp=tc;},
        getTemp: function() {return temp;},
        setAlgorithm: function(a) {algorithm=a;}
    }
}

function Graph() {
    var canvas = document.getElementById("graph");
    var context = canvas.getContext("2d");
    var offset = 7.5;
    var w = 11;
    var t_min = 0.5;
    var t_del = 0.1;

    var width = canvas.width = 400-1;
    var height = canvas.height = w*10+offset*2;

    reset();

    function x(t) {return w*(t-t_min)/t_del+offset;}
    function y(m) {return w*(1.0-m)/0.2+offset;}
    function t(x) {
        var t = t_del*(x-offset)/w+t_min;
        t = Math.round(t*100)/100;
        if(t<0.5) t=0.5;
        if(t>4.0) t=4.0;
        return t;
    }

    function addPoint(t,m,a) {
        // console.log(t+" "+m+" "+x+" "+y);
        if(a==0) context.fillStyle = "#9999ff";
        else if(a==1) context.fillStyle = "#99ff99";
        else if(a==2) context.fillStyle = "#ff9999";
        else context.fillStyle = "#ffffff";
        context.beginPath();
        context.arc( x(t), y(m), 2,0,2*Math.PI,true);
        context.fill();
    }

    function reset() {
        context.fillStyle = "#161616";
        context.fillRect(0,0,width,height)

        context.lineWidth = 1;

        context.strokeStyle = "#333333";
        for(var i=0;i<36;++i)  {
            context.beginPath();
            context.moveTo(offset+i*w, 0);
            context.lineTo(offset+i*w, height);
            context.stroke();
        }
        for(var i=0;i<11;++i) {
            context.beginPath();
            context.moveTo(0, offset+i*w);
            context.lineTo(width, offset+i*w);
            context.stroke();
        }

        context.strokeStyle = "#666666";
        for(var i=0;i<36;i+=5)  {
            context.beginPath();
            context.moveTo(offset+i*w, 0);
            context.lineTo(offset+i*w, height);
            context.stroke();
        }
        for(var i=0;i<11;i+=5) {
            context.beginPath();
            context.moveTo(0, offset+i*w);
            context.lineTo(width, offset+i*w);
            context.stroke();
        }

        context.strokeStyle = "#cccccc";
        context.beginPath();
        context.moveTo(0, height/2);
        context.lineTo(width, height/2);
        context.stroke();
    }

    return {
        addPoint: addPoint,
        reset: reset,
        getT: t
    }
}

var ising = Ising();
var graph = Graph();

$(function () {
    var initT = 2.27;

    function setT(t) {
        $( "#temperature_value" ).text( t );
        ising.setTemp(t);
        $("#temperature").slider("setValue", t);
    }

    var t_slider = $("#temperature").slider({
        min: 0.5,
        max: 4.0,
        step: 0.01,
        value: initT
    });

    t_slider.on("slide", function(e) {
        console.log(t_slider.slider("getValue"));
        setT( e.value );
    });
    t_slider.prev().on("mouseup",function() {
        setT( t_slider.slider("getValue") );
    });

    $("#start").on("click", ising.start);
    $("#stop" ).on("click", ising.stop);
    $("#step" ).on("click", ising.step);

    $("#algorithm").on("change", function() {
        ising.setAlgorithm( $(this).val() );
    });

    $("#graph").on("click", function(e) {
        var x  = (e.offsetX || e.clientX - $(e.target).offset().left); // polyfill for firefox
        setT( graph.getT(x) );
    });

    $("#clear").on("click", graph.reset);

    setT(initT);
    ising.start();
});
<|endoftext|>


<commit_before>
/*!
 * Analytics Machine - Mongoose Rest
 * Copyright(c) Thomas Blobaum
 * MIT Licensed
 */

var _ = require('underscore')
  , Mongoose = require('mongoose')

function mongooseRest (schema, options) {
  options = options || {};

  schema.static('get', _get)
  schema.static('post', _update)
  schema.static('put', _update)
  schema.static('del', _del)
  schema.static('search', _search)
  schema.static('bulk', _search)
  schema.static('controller', _controller)

  function _controller () {
    var modelName = schema.virtuals.modelName.getters[0]()
      , Model = Mongoose.model(modelName, schema)
    this.get = Model.get
    this.post = Model.post
    this.put = Model.put
    this.del = Model.del
    this.bulk = Model.bulk
    this.search = Model.search
  }

  function _search (query, callback) {
    var Model = Mongoose.model(schema.virtuals.modelName.getters[0](), schema)
      , query = query || {}
      , limit = query.limit || 10
      , page = query.page || 1
    delete query.limit
    delete query.page
    Model.find(query, [], { skip: (limit * (page-1)), limit: limit }, function (e, documents) {
      if (e) {
        if (options.debug) console.log('search', e)
        callback(e, false)
        return
      }
      else if (!documents) {
        callback(false, false)
        return
      }
      else {
        callback(false, JSON.parse(JSON.stringify(documents)))
        return
      }
    })
  }

  function _get (id, callback) {
    var Model = Mongoose.model(schema.virtuals.modelName.getters[0](), schema)
    Model.find({_id:id}, function (e, documents) {
      if (e) {
        if (options.debug) console.log('get', e)
        callback(e, false)
        return
      }
      else if (!documents) {
        callback(false, false)
        return
      }
      else {
        callback(false, JSON.parse(JSON.stringify(documents)))
        return
      }
    })
  }

  function _update (doc, callback) {
    var modelName = schema.virtuals.modelName.getters[0]()
      , Model = Mongoose.model(modelName, schema)
    Model.findById(doc._id, function (e, document) {
      if (e) {
        if (options.debug) console.log('put', e)
        callback(e, false)
        return
      }
      if (!document) {
        if (doc.domain) doc.href = doc.domain // move to model schema
        var model = new Model(doc)
        model.save(function (e) {
          if (e) {
            if (options.debug) console.log('post', e)
            callback(e, false)
            return
          }
          callback(false, true)
        })
      }
      else {
        document.merge(doc)
        document.save()
        callback(false, true)
      }
    })
  }

  function _del (id, callback) {
    var modelName = schema.virtuals.modelName.getters[0]()
      , Model = Mongoose.model(modelName, schema)
    Model
      .findById(id)
      .populate('_owner')
      .run(function (err, document) {
        if (!document) {
          callback(false, false)
          return
        }
        else {
          var list = document._owner[modelName]
          list = _.reject(list, function (val) {
            if (_.isEqual(String(val), String(id))) return true
          })
          document._owner.save()
          document.remove()
          callback(false, true)
        }
      })
  }

}

module.exports = mongooseRest

<commit_msg>removing underscore dep<commit_after>
/*!
 * Analytics Machine - Mongoose Rest
 * Copyright(c) Thomas Blobaum
 * MIT Licensed
 */

var Mongoose = require('mongoose')

function mongooseRest (schema, options) {
  options = options || {};

  schema.static('get', _get)
  schema.static('post', _update)
  schema.static('put', _update)
  schema.static('del', _del)
  schema.static('search', _search)
  schema.static('bulk', _search)
  schema.static('controller', _controller)

  function _controller () {
    var modelName = schema.virtuals.modelName.getters[0]()
      , Model = Mongoose.model(modelName, schema)
    this.get = Model.get
    this.post = Model.post
    this.put = Model.put
    this.del = Model.del
    this.bulk = Model.bulk
    this.search = Model.search
  }

  function _search (query, callback) {
    var Model = Mongoose.model(schema.virtuals.modelName.getters[0](), schema)
      , query = query || {}
      , limit = query.limit || 10
      , page = query.page || 1
    delete query.limit
    delete query.page
    Model.find(query, [], { skip: (limit * (page-1)), limit: limit }, function (e, documents) {
      if (e) {
        if (options.debug) console.log('search', e)
        callback(e, false)
        return
      }
      else if (!documents) {
        callback(false, false)
        return
      }
      else {
        callback(false, JSON.parse(JSON.stringify(documents)))
        return
      }
    })
  }

  function _get (id, callback) {
    var Model = Mongoose.model(schema.virtuals.modelName.getters[0](), schema)
    Model.find({_id:id}, function (e, documents) {
      if (e) {
        if (options.debug) console.log('get', e)
        callback(e, false)
        return
      }
      else if (!documents) {
        callback(false, false)
        return
      }
      else {
        callback(false, JSON.parse(JSON.stringify(documents)))
        return
      }
    })
  }

  function _update (doc, callback) {
    var modelName = schema.virtuals.modelName.getters[0]()
      , Model = Mongoose.model(modelName, schema)
    Model.findById(doc._id, function (e, document) {
      if (e) {
        if (options.debug) console.log('put', e)
        callback(e, false)
        return
      }
      if (!document) {
        if (doc.domain) doc.href = doc.domain // move to model schema
        var model = new Model(doc)
        model.save(function (e) {
          if (e) {
            if (options.debug) console.log('post', e)
            callback(e, false)
            return
          }
          callback(false, true)
        })
      }
      else {
        document.merge(doc)
        document.save()
        callback(false, true)
      }
    })
  }

  function _del (id, callback) {
    var modelName = schema.virtuals.modelName.getters[0]()
      , Model = Mongoose.model(modelName, schema)
    Model.findById(id, function (e, doc) {
      if (!document) {
        callback(false, false)
        return
      }
      else {
        document.remove()
        callback(false, true)
      }
    })
  }

}

module.exports = mongooseRest

<|endoftext|>


<commit_before>// Here is the business logic that we will use for the progress
/*globals angular:true*/
/**
* ngProgress.provider Module
*
* This is the singleton that handles the actual progress of ngProgress
*/
angular.module('ngProgress.provider', ['ngProgress.directive'])
    .provider('progressbar', function () {
        'use strict';
        //Default values for provider
        this.autoStyle = true;
        this.count = 0;
        this.height = '2px';
        this.color = 'firebrick';

        this.$get = ['$document',
            '$window',
            '$compile',
            '$rootScope', function ($document, $window, $compile, $rootScope) {
            var count = this.count,
                height = this.height,
                color = this.color,
                $scope = $rootScope,
                $body = $document.find('body');
                // Create elements that is needed
                // progressbarEl = '
{{ count }}
';

            $rootScope.count = count;
            var el = $compile('
{{' + count + '}}
')($rootScope);
            $body.prepend(el);
            // $body.append(progressbarEl);
            // $compile(progressbarEl)($scope);
            // $body.prepend(progressbarEl);
                // console.log(progressbarEl.eq(0).html());
                // progressbarContainer = angular.element('

'),
                // progressbar = angular.element('

');

            var intervalCounterId = 0;
            // $rootScope.$digest();
            // Add progressbar to progressbar-container and progressbar-container
            // to body
            // progressbarContainer.append(progressbar);
            // $body.append(progressbarContainer);

            // Styling for the progressbar itself
            // if (this.autoStyle) {
            //     progressbarContainer.css({
            //         position: 'fixed',
            //         margin: 0,
            //         padding: 0,
            //         top: 0,
            //         left: 0,
            //         right: 0,
            //         'z-index': 99999
            //     });
            //     progressbar.css({
            //         height: height,
            //         width:  count + '%',
            //         'background-color': color,
            //         color: color,
            //         'box-shadow': '0 0 10px 0',
            //         margin: 0,
            //         padding: 0,
            //         'z-index': 99998,
            //         '-webkit-transition': 'all 0.5s ease-in-out',
            //         '-moz-transition': 'all 0.5s ease-in-out',

            //         '-o-transition': 'all 0.5s ease-in-out',
            //         'transition': 'all 0.5s ease-in-out'
            //     });
            // }

            return {
                // Starts the animation and adds between 0 - 5 percent to loading
                // each 400 milliseconds. Should always be finished with progressbar.complete()
                // to hide it
                start: function () {
                    // TODO Use requestAnimationFrame instead of setInterval
                    // https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame
                    console.log('start called!');
                    intervalCounterId = setInterval(function () {
                        if (isNaN(count)) {
                            clearInterval(intervalCounterId);
                            count = 0;
                        }
                        var remaining = 100 - count;
                        console.log('count: ' + count);
                        count = count + (0.15 * Math.pow(1 - Math.sqrt(remaining), 2));
                    }, 200);
                },
                // Sets the height of the progressbar. Use any valid CSS value
                // Eg '10px', '1em' or '1%'
                height: function (new_height) {
                    if (new_height !== undefined) {
                        height = new_height;
                    }
                    return height;
                },
                // Sets the color of the progressbar and it's shadow. Use any valid HTML
                // color
                color: function (new_color) {
                    if (new_color !== undefined) {
                        color = new_color;
                    }
                    return color;
                },
                // Returns on how many percent the progressbar is at. Should'nt be needed
                status: function () {
                    return count;
                },
                // Stops the progressbar at it's current location
                stop: function () {
                    clearInterval(intervalCounterId);
                },
                // Set's the progressbar percentage. Use a number between 0 - 100.
                // If 100 is provided, complete will be called.
                set: function (new_count) {
                    count = new_count;
                    clearInterval(intervalCounterId);
                    return count;
                },
                // Resets the progressbar to percetage 0 and therefore will be hided after
                // it's rollbacked
                reset: function () {
                    clearInterval(intervalCounterId);
                    count = 0;
                    // progressbar.css('width', count + '%');
                    // progressbar.css('opacity', '1');
                    return 0;
                },
                // Jumps to 100% progress and fades away progressbar.
                complete: function () {
                    // this.reset();
                    count = 100;
                    // progressbar.css('width', count + '%');
                    // setTimeout(function () {
                    //     progressbar.css('opacity', '0');
                    // }, 500);
                    // setTimeout(function () {
                    //     count = 0;
                    //     progressbar.css('width', count + '%');
                    // }, 1000);
                    return count;
                }
            };
        }];

        this.setColor = function (color) {
            this.color = color;
        };

        this.setHeight = function (height) {
            this.height = height;
        };
    });
// Here we have our dom manipulation
/*globals angular:true*/
angular.module('ngProgress.directive', [])
    .directive('ngProgress', function () {
        var directiveObj = {
            replace: true,
            // scope: {
            //     'counter': '=ngModel'
            // },
            // template: '
hello {{ counter }}
'
            template: '
fucker
'
        };
        return directiveObj;
    });
// Here is the main module<commit_msg>Newest compiled distrobution<commit_after>// Here is the business logic that we will use for the progress
/*globals angular:true*/
/**
* ngProgress.provider Module
*
* This is the singleton that handles the actual progress of ngProgress
*/
angular.module('ngProgress.provider', ['ngProgress.directive'])
    .provider('ngProgress', function () {
        'use strict';
        //Default values for provider
        this.autoStyle = true;
        this.count = 0;
        this.height = '2px';
        this.color = 'firebrick';

        this.$get = ['$document',
            '$window',
            '$compile',
            '$rootScope',
            '$timeout', function ($document, $window, $compile, $rootScope, $timeout) {
            var count = this.count,
                height = this.height,
                color = this.color,
                $scope = $rootScope,
                $body = $document.find('body');

            var progressbarEl = $compile('<ng-progress></ng-progress>')($scope);
            $body.append(progressbarEl);
            $scope.count = count;
            if (height !== undefined) {
                progressbarEl.eq(0).children().css('height', height);
            }
            if (color !== undefined) {
                progressbarEl.eq(0).children().css('background-color', color);
                progressbarEl.eq(0).children().css('color', color);
            }
            var intervalCounterId = 0;
            return {
                // Starts the animation and adds between 0 - 5 percent to loading
                // each 400 milliseconds. Should always be finished with progressbar.complete()
                // to hide it
                start: function () {
                    // TODO Use requestAnimationFrame instead of setInterval
                    // https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame
                    this.show();
                    var self = this;
                    intervalCounterId = setInterval(function () {
                        if (isNaN(count)) {
                            clearInterval(intervalCounterId);
                            count = 0;
                            self.hide();
                        } else {
                            var remaining = 100 - count;
                            count = count + (0.15 * Math.pow(1 - Math.sqrt(remaining), 2));
                            self.updateCount(count);
                        }
                    }, 200);
                },
                updateCount: function (new_count) {
                    $scope.count = new_count;
                    $scope.$apply();
                },
                // Sets the height of the progressbar. Use any valid CSS value
                // Eg '10px', '1em' or '1%'
                height: function (new_height) {
                    if (new_height !== undefined) {
                        height = new_height;
                        $scope.height = height;
                        $scope.$apply();
                    }
                    return height;
                },
                // Sets the color of the progressbar and it's shadow. Use any valid HTML
                // color
                color: function (new_color) {
                    if (new_color !== undefined) {
                        color = new_color;
                        $scope.color = color;
                        $scope.$apply();
                    }
                    return color;
                },
                hide: function () {
                    progressbarEl.children().css('opacity', '0');
                    var self = this;
                    $timeout(function () {
                        progressbarEl.children().css('width', '0%');
                        $timeout(function () {
                            self.show();
                        }, 500);
                    }, 500);
                },
                show: function () {
                    $timeout(function () {
                        progressbarEl.children().css('opacity', '1');
                    }, 100);
                },
                // Returns on how many percent the progressbar is at. Should'nt be needed
                status: function () {
                    return count;
                },
                // Stops the progressbar at it's current location
                stop: function () {
                    clearInterval(intervalCounterId);
                },
                // Set's the progressbar percentage. Use a number between 0 - 100.
                // If 100 is provided, complete will be called.
                set: function (new_count) {
                    this.show();
                    this.updateCount(new_count);
                    count = new_count;
                    clearInterval(intervalCounterId);
                    return count;
                },
                css: function (args) {
                    return progressbarEl.children().css(args);
                },
                // Resets the progressbar to percetage 0 and therefore will be hided after
                // it's rollbacked
                reset: function () {
                    clearInterval(intervalCounterId);
                    count = 0;
                    this.updateCount(count);
                    return 0;
                },
                // Jumps to 100% progress and fades away progressbar.
                complete: function () {
                    count = 100;
                    this.updateCount(count);
                    var self = this;
                    $timeout(function () {
                        self.hide();
                        $timeout(function () {
                            count = 0;
                            self.updateCount(count);
                        }, 500);
                    }, 1000);
                    return count;
                }
            };
        }];

        this.setColor = function (color) {
            if (color !== undefined) {
                this.color = color;
            }
            return this.color;
        };

        this.setHeight = function (height) {
            if (height !== undefined) {
                this.height = height;
            }
            return this.height;
        };
    });
// Here we have our dom manipulation
/*globals angular:true*/
angular.module('ngProgress.directive', [])
    .directive('ngProgress', function ($window, $rootScope) {
        var directiveObj = {
            replace: true,
            restrict: 'E',
            link: function ($scope, $element, $attrs, $controller) {
                $rootScope.$watch('count', function (newVal) {
                    if (newVal !== undefined || newVal !== null) {
                        $scope.counter = newVal;
                        $element.eq(0).children().css('width', newVal + '%');
                    }
                });
                $rootScope.$watch('color', function (newVal) {
                    if (newVal !== undefined || newVal !== null) {
                        $scope.color = newVal;
                        $element.eq(0).children().css('background-color', newVal);
                        $element.eq(0).children().css('color', newVal);
                    }
                });
                $rootScope.$watch('height', function (newVal) {
                    if (newVal !== undefined || newVal !== null) {
                        $scope.height = newVal;
                        $element.eq(0).children().css('height', newVal);
                    }
                });
            },
            template: '

'
        };
        return directiveObj;
    });
// Here is the main module

angular.module('ngProgress', ['ngProgress.directive', 'ngProgress.provider']);<|endoftext|>


<commit_before>/*PathNode.js
* path object
* extends GeometryNode
*/

define([
  'underscore',
  'models/data/GeometryNode',
  'models/PaperManager',
  'models/data/Instance',

], function(_, GeometryNode, PaperManager, Instance) {

  var PathNode = GeometryNode.extend({
     defaults: _.extend({},GeometryNode.prototype.defaults, {
           type: 'path',
        }),

    initialize: function(){
      //call the super constructor
      GeometryNode.prototype.initialize.call(this);
      console.log("path visible"+this.visible);
      //create a paperjs path object and set its parent to this
      this.paper = PaperManager.getPaperInstance('path');
      this.path = new this.paper.Path();
      this.path.nodeParent = this;
      this.path.strokeColor = this.get('strokeColor');

      //bind an update event to the path
      this.path.on('mouseup',function(){
        this.nodeParent.updateInstances(this);
        });
      //intialize array to store instances
      this.instances = [];
    },

    //update all instance members
    updateInstances: function(path){
          console.log('update event called on path');

          for (var i = 0; i < this.instances.length; i++) {
            if(this.instances[i].data!=path){
              var clone = path.clone();
              clone.rotate(-path.nodeParent.rotation);
              this.instances[i].update(clone);
            }
          }

        },

    update: function(path){

    },

    //checks for intersections between this path and any of its siblings in the scene graph
    checkIntersections: function(){
      var siblings = this.getSiblings();

      //currently assumes that siblings have no children- will need to update to a
      //recursive function to handle checking for intersections in groups...
      for(var i=0;i<siblings.length;i++){

        if(siblings[i]!=this && siblings[i].visible){
          var intersections = this.path.getIntersections(siblings[i].path);
          if(intersections.length>0){
            this.trigger('intersect-found');
            this.createInstances(10);
            this.followPath(siblings[i], this.instances);
            break;
          }

          for (var j = 0; j < intersections.length; j++) {
             var ellipse = new this.paper.Path.Circle({
              center: intersections[j].point,
               radius: 5,
                fillColor: '#009dec'
                });
              ellipse.removeOnMove();
            }
          }
      }
    },

    //creates and stores an instance which is identical to this path
    createInstance: function(){
      /*for now it is neccesary to make a copy of the shape data
      * rather than reference it due to the drawing structure of
      * paperjs. update this for efficency in the future
      */
        var instance = new Instance(this.path.clone());
        this.listenTo(instance,'change:updateInstances',this.updateInstances);
        this.instances.push(instance);

        return instance;

    },

    //creates a specified number of instances, with option to clear existing instances
    createInstances: function(num, clear){
        if(clear){
          this.deleteInstances();
        }
        for(var i=0;i<num;i++){
          this.createInstance();
        }
        return this.instances;

    },

    deleteInstances: function(){
       for(var i=0;i<this.instances.length;i++){
          this.instances[i].clear();
          this.instances[i] = null;
        }
        this.instances = [];
    },

    //renders a given instance static and adds it to the scene graph as its own object
    bakeInstance: function(instance){

    },

//projects a set of instances along a parent path
    followPath: function(parent, instances){
      var path = parent.path;
      var num =instances.length;
      var maxDist = path.length/(num-1);
      var position = path.clone();
      position.flatten(maxDist);
      //console.log(position);
      var location;
      for(var i=0;i<instances.length;i++){
         //console.log(location);
         var location_n = position.segments[i].point;
        var instance = instances[i];
         if(location){

          var delta = location_n.subtract(location);
          delta.angle+=90;
          instance.data.position = location_n;
          instance.data.rotate(delta.angle,instance.data.position);
          instance.rotation=delta.angle;

        }
        location = location_n;

      }
      this.remove();
      parent.addChildNode(this);
      position.remove();

    }

  });

  return PathNode;

});<commit_msg>parenting to path for follow path implemented<commit_after>/*PathNode.js
* path object
* extends GeometryNode
*/

define([
  'underscore',
  'models/data/GeometryNode',
  'models/data/SceneNode',
  'models/PaperManager',
  'models/data/Instance',

], function(_, GeometryNode, SceneNode, PaperManager, Instance) {

  var PathNode = GeometryNode.extend({
     defaults: _.extend({},GeometryNode.prototype.defaults, {
           type: 'path',
        }),

    initialize: function(){
      //call the super constructor
      GeometryNode.prototype.initialize.call(this);
      console.log("path visible"+this.visible);
      //create a paperjs path object and set its parent to this
      this.paper = PaperManager.getPaperInstance('path');
      this.path = new this.paper.Path();
      this.path.nodeParent = this;
      this.path.strokeColor = this.get('strokeColor');

      //bind an update event to the path
      this.path.on('mouseup',function(){
        this.nodeParent.updateInstances(this);
        this.nodeParent.update();
        });
      //intialize array to store instances
      this.instances = [];
    },

    //update all instance members
    updateInstances: function(path){
          console.log('update event called on path');

          for (var i = 0; i < this.instances.length; i++) {
            if(this.instances[i].data!=path){
              var clone = path.clone();
              clone.rotate(-path.nodeParent.rotation);
              this.instances[i].update(clone);
            }
          }

        },

    update: function(){
      console.log("number of children="+this.getNumChildren());
      if(this.getParentNode() instanceof PathNode){
        console.log("updating follow path");
        this.followPath(this.parent, this.instances);
      }

      if(this.children.length>0){
                for(var i=0; i<this.children.length;i++){
                    if(this.children[i]!==null){
                        this.children[i].update();
                    }
                }
            }

            this.trigger('change:update');

    },

    //checks for intersections between this path and any of its siblings in the scene graph
    checkIntersections: function(){
      var siblings = this.getSiblings();

      //currently assumes that siblings have no children- will need to update to a
      //recursive function to handle checking for intersections in groups...
      for(var i=0;i<siblings.length;i++){

        if(siblings[i]!=this && siblings[i].visible){
          var intersections = this.path.getIntersections(siblings[i].path);
          if(intersections.length>0){
            this.trigger('intersect-found');
            this.createInstances(10);
            this.followPath(siblings[i], this.instances);
            break;
          }

          for (var j = 0; j < intersections.length; j++) {
             var ellipse = new this.paper.Path.Circle({
              center: intersections[j].point,
               radius: 5,
                fillColor: '#009dec'
                });
              ellipse.removeOnMove();
            }
          }
      }
    },

    //creates and stores an instance which is identical to this path
    createInstance: function(){
      /*for now it is neccesary to make a copy of the shape data
      * rather than reference it due to the drawing structure of
      * paperjs. update this for efficency in the future
      */
        var instance = new Instance(this.path.clone());
        this.listenTo(instance,'change:updateInstances',this.updateInstances);
        this.instances.push(instance);

        return instance;

    },

    //creates a specified number of instances, with option to clear existing instances
    createInstances: function(num, clear){
        if(clear){
          this.deleteInstances();
        }
        for(var i=0;i<num;i++){
          this.createInstance();
        }
        return this.instances;

    },

    deleteInstances: function(){
       for(var i=0;i<this.instances.length;i++){
          this.instances[i].clear();
          this.instances[i] = null;
        }
        this.instances = [];
    },

    //renders a given instance static and adds it to the scene graph as its own object
    bakeInstance: function(instance){

    },

//projects a set of instances along a parent path
    followPath: function(parent, instances){
      var path = parent.path;
      var num =instances.length;
      var maxDist = path.length/(num-1);
      var position = path.clone();
      position.flatten(maxDist);
      //console.log(position);
      var location;
      for(var i=0;i<instances.length;i++){
         //console.log(location);
         var location_n = position.segments[i].point;
        var instance = instances[i];
         if(location){

          var delta = location_n.subtract(location);
          delta.angle+=90;
          instance.data.position = location_n;
          instance.data.rotate(delta.angle,instance.data.position);
          instance.rotation=delta.angle;

        }
        location = location_n;

      }
      if(this.visible){
        this.remove();
      }
      if(this.getParentNode!=parent){
        parent.addChildNode(this);
      }
      position.remove();

    }

  });

  return PathNode;

});<|endoftext|>