<commit_before>var context = function(description, specDefinitions) {
  return jasmine.getEnv().describe(description, specDefinitions);
};

function wait(millis) {
  var date = new Date();
  var curDate = null;

  do { curDate = new Date(); }
  while(curDate-date < millis);
}

describe("Compass App", function(){
  beforeEach(function() {
    // stubs
    app.createProjectBySelectingDirectory = function(callback){
      app.createProject({
        name: "project-a",
        projectDir: "/some/path/project-a"
      });
    };
    app.nukeAllProjects();
  });

  context("with no projects", function(){
    it("lists no projects", function(){
      expect($(".project").length).toBe(0);
    });
  });

  describe("adding a project", function(){
    it("adds the project to the list", function(){
      $(".option.add").click();
      expect($(".project:visible").length).toBe(1);
    });

    it("sets the project name to the folder name", function(){
      $(".option.add").click();
      Projects.get($(".project:last").attr("data-key"), function(project){
        expect(project.name).toBe("project-a");
      });
    });

    it("displays the configuration after adding the project", function(){
      $(".option.add").click();
      var project = $(".project:last");
      var visible_project_details = $(".project_details[data-key=" + project.attr('data-key') + "]:visible");
      expect(visible_project_details.length).toBe(1);
    });
  });

  describe("adding multiple projects", function(){
    beforeEach(function(){
      Projects.save({name: 'project-a'});
      app.listProjects();
    });

    it("lists both projects", function(){
      app.createProjectBySelectingDirectory = function(callback){
        app.createProject({
          name: "project-b",
          projectDir: "/some/path/project-b"
        });
      };
      $(".option.add").click();
      expect($(".project:visible").length).toBe(2);
    });
  });

  describe("editing a project in the project list", function(){
    beforeEach(function(){
      app.createProject({
        name: "project-a",
        projectDir: "/project-a/",
        sassDir: "/project-a/sass",
        cssDir: "/project-a/css",
        javascriptsDir: "/project-a/js",
        imagesDir: "/project-a/images"
      });
      app.listProjects();
      this.project = $(".project:contains('project-a')");
    });

    describe("double clicking a project's name", function(){
      beforeEach(function(){
        expect(this.project.find("a.name").is(":visible")).toBe(true);
        expect(this.project.find("input").is(":visible")).toBe(false);
        this.project.find("a.name").dblclick();
      });

      it("puts you in inline-edit mode for the project name", function(){
        expect(this.project.find("a.name").is(":visible")).toBe(false);
        expect(this.project.find("input").is(":visible")).toBe(true);
      });
    });

    describe("pressing the <esc> key while editing a project's name", function(){
      beforeEach(function(){
        this.project_name = this.project.find("a.name").text();
        this.project.find("a.name").dblclick();
        this.project.find("input").val("foobarbaz");

        var e = jQuery.Event("keyup");
        e.which = 27; // # escape key code value
        this.project.find("input").trigger(e);
      });

      it("cancels editing the name", function(){
        expect(this.project.find("a.name").is(":visible")).toBe(true);
        expect(this.project.find("input").is(":visible")).toBe(false);
        expect(this.project.find("a.name").text()).toBe(this.project_name);
      });
    });

    describe("pressing the <enter> key while editing a project's name", function(){
      beforeEach(function(){
        this.project_name = "foobarbaz";
        this.project.find("a.name").dblclick();
        this.project.find("input").val(this.project_name);

        var e = jQuery.Event("keyup");
        e.which = 13; // # escape key code value
        this.project.find("input").trigger(e);
      });

      it("saves the project name", function(){
        expect(this.project.find("a.name").is(":visible")).toBe(true);
        expect(this.project.find("input").is(":visible")).toBe(false);
        expect(this.project.find("a.name").text()).toBe(this.project_name);
      });
    });

    describe("moving focus to another part of the app while editing a project's name", function(){
      beforeEach(function(){
        this.project_name = "foobarbaz";
        this.project.find("a.name").dblclick();
        this.project.find("input").val(this.project_name);

        var e = jQuery.Event("blur");
        this.project.find("input").trigger(e);
      });

      it("saves the project name", function(){
        expect(this.project.find("a.name").is(":visible")).toBe(true);
        expect(this.project.find("input").is(":visible")).toBe(false);
        expect(this.project.find("a.name").text()).toBe(this.project_name);
      });
    });
  });

  describe("switching between projects", function(){
    beforeEach(function(){
      app.createProject({
        name: "project-a",
        projectDir: "/project-a/",
        sassDir: "/project-a/sass",
        cssDir: "/project-a/css",
        javascriptsDir: "/project-a/js",
        imagesDir: "/project-a/images"
      });
      app.createProject({
        name: "project-b",
        projectDir: "/project-b/",
        sassDir: "/project-b/sass",
        cssDir: "/project-b/css",
        javascriptsDir: "/project-b/js",
        imagesDir: "/project-b/images"
      });
      app.listProjects();
    });

    context("when viewing project a and the log is selected", function() {
      beforeEach(function(){
        $(".project:contains('project-a') .source").click();
        $(".project_details:visible .mode.log").click();
      });

      it("switches to the configuration screen when switching to project b", function() {
        var project = $(".project:contains('project-b')");
        project.find(".source").click();
        var selected_project_details = $(".project_details.configure.selected[data-key=" + project.attr('data-key') + "]");
        expect(selected_project_details.length).toBe(1);
      });
    });

    context("when viewing project a and the configuration is selected", function() {
      beforeEach(function(){
        $(".project:contains('project-a') .source").click();
        $(".project_details:visible .mode.configure").click();
      });

      it("keeps the configuration selected when switching to project b", function() {
        var project = $(".project:contains('project-b')");
        project.find(".source").click();
        var visible_project_details = $(".project_details.configure[data-key=" + project.attr('data-key') + "]:visible");
        expect(visible_project_details.length).toBe(1);
      });
    });
  });

  describe("watching a project", function(){
    beforeEach(function(){
      var project_dir = air.File.createTempDirectory(),
        sass_dir = project_dir.resolvePath("sass"),
        css_dir = project_dir.resolvePath("css");
        javascripts_dir = project_dir.resolvePath("js");
        images_dir = project_dir.resolvePath("images");
      app.createProject({
        name: "project-a",
        projectDir: project_dir.nativePath,
        sassDir: sass_dir.nativePath,
        cssDir: css_dir.nativePath,
        javascriptsDir: javascripts_dir.nativePath,
        imagesDir: images_dir.nativePath
      });
      app.listProjects();
      this.project = $(".project:contains('project-a')");
    });

    it("displays the project's log screen by default", function(){
      var key = this.project.attr('data-key');
      // start watching the project
      this.project.find(".start").click();
      expect($(".project_details[data-key=" + key + "] .mode.log").is(":visible")).toBe(true);
    });

    describe("logged output", function(){
      it("is empty before a project is watched", function(){
        $(".project_details.selected:visible .mode.log").click();
        this.project.find(".source").click();

        var output = $(".project_details.selected:visible .log_output");
        expect(output.html().length).toBe(0);
      });

      it("is updated with text that compass sends to STDOUT", function(){
        this.project.find(".source").click();
        this.project.find(".start").click();
        $(".project_details:visible .mode.log").click();

        var output = $(".project_details .log_output:visible");
        waitsFor(function(){
          return output.html().length > 0; // should no longer be empty
        }, "Did not find expected log output", 5000);
      });

      it("can be cleared", function(){
        this.project.find(".source").click();
        $(".project_details.selected .mode.log").click();
        var output = $(".project_details.selected .log_output");
        output.html("foo");
        expect(output.html().length).toBeGreaterThan(0);
        $(".footer .clear_log.command").click();
        expect(output.html().length).toBe(0);
      });
    });

    context("given I have a valid project with scss files", function(){
      beforeEach(function() {

        // make the scss files to watch
        Projects.find(function (project) {
          return project.name == "project-a";
        }, function(project) {
          sassDir = new air.File(project.sassDir);
          sassDir.createDirectory();
          sassFile = sassDir.resolvePath("file.scss");
          stream = new air.FileStream();
          stream.open(sassFile, air.FileMode.WRITE);
          stream.writeUTFBytes("body { color: red; }");
          stream.close();
        });

        // start watching the project
        this.project = $(".project:contains('project-a')");
        this.project.find(".start").click();
      });

      describe("when I make changes to the input files", function() {
        beforeEach(function() {
          waitsFor(function(){
            var output = $(".project_details:visible .log_output");
            if(output.length === 0) return false;

            if(output.html().length > 0) {
              setTimeout(function(){
                Projects.find(function (project) {
                  return project.name == "project-a";
                }, function(project) {
                  sassDir = new air.File(project.sassDir);
                  sassFile = sassDir.resolvePath("file.scss");
                  stream = new air.FileStream();
                  stream.open(sassFile, air.FileMode.WRITE);
                  stream.writeUTFBytes("body { color: blue; }");
                  stream.close();
                });
              }, 1000);
              return true;
            }
            return false;
          }, "Never started logging output", 10000);
        });

        it("then I expect the output the show", function() {
          //assert that the log output has some text
          var output = $(".project_details:visible .log_output");
          waitsFor(function(){
            if(output.length === 0) return false;
            return output.html().match(/overwrite/);
          }, "Overwrite never found.", 10000);
        });
      });
    });
  });

});
<commit_msg>Updating old Compass App reference to be Scout App.<commit_after>var context = function(description, specDefinitions) {
  return jasmine.getEnv().describe(description, specDefinitions);
};

function wait(millis) {
  var date = new Date();
  var curDate = null;

  do { curDate = new Date(); }
  while(curDate-date < millis);
}

describe("Scout App", function(){
  beforeEach(function() {
    // stubs
    app.createProjectBySelectingDirectory = function(callback){
      app.createProject({
        name: "project-a",
        projectDir: "/some/path/project-a"
      });
    };
    app.nukeAllProjects();
  });

  context("with no projects", function(){
    it("lists no projects", function(){
      expect($(".project").length).toBe(0);
    });
  });

  describe("adding a project", function(){
    it("adds the project to the list", function(){
      $(".option.add").click();
      expect($(".project:visible").length).toBe(1);
    });

    it("sets the project name to the folder name", function(){
      $(".option.add").click();
      Projects.get($(".project:last").attr("data-key"), function(project){
        expect(project.name).toBe("project-a");
      });
    });

    it("displays the configuration after adding the project", function(){
      $(".option.add").click();
      var project = $(".project:last");
      var visible_project_details = $(".project_details[data-key=" + project.attr('data-key') + "]:visible");
      expect(visible_project_details.length).toBe(1);
    });
  });

  describe("adding multiple projects", function(){
    beforeEach(function(){
      Projects.save({name: 'project-a'});
      app.listProjects();
    });

    it("lists both projects", function(){
      app.createProjectBySelectingDirectory = function(callback){
        app.createProject({
          name: "project-b",
          projectDir: "/some/path/project-b"
        });
      };
      $(".option.add").click();
      expect($(".project:visible").length).toBe(2);
    });
  });

  describe("editing a project in the project list", function(){
    beforeEach(function(){
      app.createProject({
        name: "project-a",
        projectDir: "/project-a/",
        sassDir: "/project-a/sass",
        cssDir: "/project-a/css",
        javascriptsDir: "/project-a/js",
        imagesDir: "/project-a/images"
      });
      app.listProjects();
      this.project = $(".project:contains('project-a')");
    });

    describe("double clicking a project's name", function(){
      beforeEach(function(){
        expect(this.project.find("a.name").is(":visible")).toBe(true);
        expect(this.project.find("input").is(":visible")).toBe(false);
        this.project.find("a.name").dblclick();
      });

      it("puts you in inline-edit mode for the project name", function(){
        expect(this.project.find("a.name").is(":visible")).toBe(false);
        expect(this.project.find("input").is(":visible")).toBe(true);
      });
    });

    describe("pressing the <esc> key while editing a project's name", function(){
      beforeEach(function(){
        this.project_name = this.project.find("a.name").text();
        this.project.find("a.name").dblclick();
        this.project.find("input").val("foobarbaz");

        var e = jQuery.Event("keyup");
        e.which = 27; // # escape key code value
        this.project.find("input").trigger(e);
      });

      it("cancels editing the name", function(){
        expect(this.project.find("a.name").is(":visible")).toBe(true);
        expect(this.project.find("input").is(":visible")).toBe(false);
        expect(this.project.find("a.name").text()).toBe(this.project_name);
      });
    });

    describe("pressing the <enter> key while editing a project's name", function(){
      beforeEach(function(){
        this.project_name = "foobarbaz";
        this.project.find("a.name").dblclick();
        this.project.find("input").val(this.project_name);

        var e = jQuery.Event("keyup");
        e.which = 13; // # escape key code value
        this.project.find("input").trigger(e);
      });

      it("saves the project name", function(){
        expect(this.project.find("a.name").is(":visible")).toBe(true);
        expect(this.project.find("input").is(":visible")).toBe(false);
        expect(this.project.find("a.name").text()).toBe(this.project_name);
      });
    });

    describe("moving focus to another part of the app while editing a project's name", function(){
      beforeEach(function(){
        this.project_name = "foobarbaz";
        this.project.find("a.name").dblclick();
        this.project.find("input").val(this.project_name);

        var e = jQuery.Event("blur");
        this.project.find("input").trigger(e);
      });

      it("saves the project name", function(){
        expect(this.project.find("a.name").is(":visible")).toBe(true);
        expect(this.project.find("input").is(":visible")).toBe(false);
        expect(this.project.find("a.name").text()).toBe(this.project_name);
      });
    });
  });

  describe("switching between projects", function(){
    beforeEach(function(){
      app.createProject({
        name: "project-a",
        projectDir: "/project-a/",
        sassDir: "/project-a/sass",
        cssDir: "/project-a/css",
        javascriptsDir: "/project-a/js",
        imagesDir: "/project-a/images"
      });
      app.createProject({
        name: "project-b",
        projectDir: "/project-b/",
        sassDir: "/project-b/sass",
        cssDir: "/project-b/css",
        javascriptsDir: "/project-b/js",
        imagesDir: "/project-b/images"
      });
      app.listProjects();
    });

    context("when viewing project a and the log is selected", function() {
      beforeEach(function(){
        $(".project:contains('project-a') .source").click();
        $(".project_details:visible .mode.log").click();
      });

      it("switches to the configuration screen when switching to project b", function() {
        var project = $(".project:contains('project-b')");
        project.find(".source").click();
        var selected_project_details = $(".project_details.configure.selected[data-key=" + project.attr('data-key') + "]");
        expect(selected_project_details.length).toBe(1);
      });
    });

    context("when viewing project a and the configuration is selected", function() {
      beforeEach(function(){
        $(".project:contains('project-a') .source").click();
        $(".project_details:visible .mode.configure").click();
      });

      it("keeps the configuration selected when switching to project b", function() {
        var project = $(".project:contains('project-b')");
        project.find(".source").click();
        var visible_project_details = $(".project_details.configure[data-key=" + project.attr('data-key') + "]:visible");
        expect(visible_project_details.length).toBe(1);
      });
    });
  });

  describe("watching a project", function(){
    beforeEach(function(){
      var project_dir = air.File.createTempDirectory(),
        sass_dir = project_dir.resolvePath("sass"),
        css_dir = project_dir.resolvePath("css");
        javascripts_dir = project_dir.resolvePath("js");
        images_dir = project_dir.resolvePath("images");
      app.createProject({
        name: "project-a",
        projectDir: project_dir.nativePath,
        sassDir: sass_dir.nativePath,
        cssDir: css_dir.nativePath,
        javascriptsDir: javascripts_dir.nativePath,
        imagesDir: images_dir.nativePath
      });
      app.listProjects();
      this.project = $(".project:contains('project-a')");
    });

    it("displays the project's log screen by default", function(){
      var key = this.project.attr('data-key');
      // start watching the project
      this.project.find(".start").click();
      expect($(".project_details[data-key=" + key + "] .mode.log").is(":visible")).toBe(true);
    });

    describe("logged output", function(){
      it("is empty before a project is watched", function(){
        $(".project_details.selected:visible .mode.log").click();
        this.project.find(".source").click();

        var output = $(".project_details.selected:visible .log_output");
        expect(output.html().length).toBe(0);
      });

      it("is updated with text that compass sends to STDOUT", function(){
        this.project.find(".source").click();
        this.project.find(".start").click();
        $(".project_details:visible .mode.log").click();

        var output = $(".project_details .log_output:visible");
        waitsFor(function(){
          return output.html().length > 0; // should no longer be empty
        }, "Did not find expected log output", 5000);
      });

      it("can be cleared", function(){
        this.project.find(".source").click();
        $(".project_details.selected .mode.log").click();
        var output = $(".project_details.selected .log_output");
        output.html("foo");
        expect(output.html().length).toBeGreaterThan(0);
        $(".footer .clear_log.command").click();
        expect(output.html().length).toBe(0);
      });
    });

    context("given I have a valid project with scss files", function(){
      beforeEach(function() {

        // make the scss files to watch
        Projects.find(function (project) {
          return project.name == "project-a";
        }, function(project) {
          sassDir = new air.File(project.sassDir);
          sassDir.createDirectory();
          sassFile = sassDir.resolvePath("file.scss");
          stream = new air.FileStream();
          stream.open(sassFile, air.FileMode.WRITE);
          stream.writeUTFBytes("body { color: red; }");
          stream.close();
        });

        // start watching the project
        this.project = $(".project:contains('project-a')");
        this.project.find(".start").click();
      });

      describe("when I make changes to the input files", function() {
        beforeEach(function() {
          waitsFor(function(){
            var output = $(".project_details:visible .log_output");
            if(output.length === 0) return false;

            if(output.html().length > 0) {
              setTimeout(function(){
                Projects.find(function (project) {
                  return project.name == "project-a";
                }, function(project) {
                  sassDir = new air.File(project.sassDir);
                  sassFile = sassDir.resolvePath("file.scss");
                  stream = new air.FileStream();
                  stream.open(sassFile, air.FileMode.WRITE);
                  stream.writeUTFBytes("body { color: blue; }");
                  stream.close();
                });
              }, 1000);
              return true;
            }
            return false;
          }, "Never started logging output", 10000);
        });

        it("then I expect the output the show", function() {
          //assert that the log output has some text
          var output = $(".project_details:visible .log_output");
          waitsFor(function(){
            if(output.length === 0) return false;
            return output.html().match(/overwrite/);
          }, "Overwrite never found.", 10000);
        });
      });
    });
  });

});
<|endoftext|>


<commit_before>;
/*
 * Copyright (c) 2012, Betable Limited
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Betable Limited nor the names of its contributors
 *       may be used to endorse or promote products derived from this software
 *       without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL BETABLE LIMITED BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

function Betable(gameId, accessToken) {
    this.endpoint = 'https://api.betable.com/1.0'
    this.gameId = gameId
    this.accessToken = accessToken
}

Betable.prototype.account = function Betable_account(callback, errback) {
    this.xhr('GET', '/account', void 0, callback, errback)
}

Betable.prototype.bet = function Betable_bet(options, callback, errback) {
    this.xhr(
        'POST'
      , '/games/' + this.gameId + '/bet'
      , options
      , callback
      , errback
    )
}

Betable.prototype.unbackedBet = function Betable_unbackedBet(options, callback, errback) {
    this.xhr(
        'POST'
      , '/games/' + this.gameId + '/unbacked-bet'
      , options
      , callback
      , errback
    )
}

Betable.prototype.betCredits = function Betable_bet_credits(gameId, options, callback, errback) {
    this.xhr(
        'POST'
      , '/games/' + this.gameId + '/' + gameId + '/bet'
      , options
      , callback
      , errback
    )
}

Betable.prototype.canIGamble = function Betable_canIGamble(callback, errback) {
    this.xhr('GET', '/can-i-gamble', void 0, callback, errback)
}

Betable.prototype.wallet = function Betable_wallet(callback, errback) {
    this.xhr('GET', '/account/wallet', void 0, callback, errback)
}

Betable.prototype.xhr = function Betable_xhr(
    method
  , path
  , body
  , callback
  , errback
) {
    var xhr = function() {
        try { return new XMLHttpRequest() } catch (e) {}
        try { return new ActiveXObject('Msxml2.XMLHTTP.6.0') } catch (e) {}
        try { return new ActiveXObject('Msxml2.XMLHTTP.3.0') } catch (e) {}
        try { return new ActiveXObject('Microsoft.XMLHTTP') } catch (e) {}
        throw new Error('no XMLHttpRequest')
    }()
    xhr.open(
        method
      , this.endpoint + path + '?access_token=' + this.accessToken
      , true
    )
    xhr.onreadystatechange = function Betable_account_onreadystatechange() {
        if (4 === xhr.readyState) {
            var response = JSON.parse(xhr.responseText)
            if (400 > xhr.status) {
                callback(response,xhr)
            } else {
                errback(response)
            }
        }
    }
    if (body) {
        xhr.setRequestHeader('Content-Type', 'application/json; charset=utf8')
        xhr.send(JSON.stringify(body))
    } else {
        xhr.send()
    }
}
;<commit_msg>Reformat and reorder a couple of things.<commit_after>;
/*
 * Copyright (c) 2012, Betable Limited
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Betable Limited nor the names of its contributors
 *       may be used to endorse or promote products derived from this software
 *       without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL BETABLE LIMITED BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

function Betable(gameId, accessToken) {
    this.endpoint = 'https://api.betable.com/1.0'
    this.gameId = gameId
    this.accessToken = accessToken
}

Betable.prototype.account = function Betable_account(callback, errback) {
    this.xhr('GET', '/account', void 0, callback, errback)
}

Betable.prototype.bet = function Betable_bet(options, callback, errback) {
    this.xhr(
        'POST'
      , '/games/' + this.gameId + '/bet'
      , options
      , callback
      , errback
    )
}

Betable.prototype.betCredits = function Betable_betCredits(gameId, options, callback, errback) {
    this.xhr(
        'POST'
      , '/games/' + this.gameId + '/' + gameId + '/bet'
      , options
      , callback
      , errback
    )
}

Betable.prototype.unbackedBet = function Betable_unbackedBet(options, callback, errback) {
    this.xhr(
        'POST'
      , '/games/' + this.gameId + '/unbacked-bet'
      , options
      , callback
      , errback
    )
}

Betable.prototype.canIGamble = function Betable_canIGamble(callback, errback) {
    this.xhr('GET', '/can-i-gamble', void 0, callback, errback)
}

Betable.prototype.wallet = function Betable_wallet(callback, errback) {
    this.xhr('GET', '/account/wallet', void 0, callback, errback)
}

Betable.prototype.xhr = function Betable_xhr(
    method
  , path
  , body
  , callback
  , errback
) {
    var xhr = function() {
        try { return new XMLHttpRequest() } catch (e) {}
        try { return new ActiveXObject('Msxml2.XMLHTTP.6.0') } catch (e) {}
        try { return new ActiveXObject('Msxml2.XMLHTTP.3.0') } catch (e) {}
        try { return new ActiveXObject('Microsoft.XMLHTTP') } catch (e) {}
        throw new Error('no XMLHttpRequest')
    }()
    xhr.open(
        method
      , this.endpoint + path + '?access_token=' + this.accessToken
      , true
    )
    xhr.onreadystatechange = function Betable_account_onreadystatechange() {
        if (4 === xhr.readyState) {
            var response = JSON.parse(xhr.responseText)
            if (400 > xhr.status) {
                callback(response, xhr)
            } else {
                errback(response)
            }
        }
    }
    if (body) {
        xhr.setRequestHeader('Content-Type', 'application/json; charset=utf8')
        xhr.send(JSON.stringify(body))
    } else {
        xhr.send()
    }
}
;
<|endoftext|>


<commit_before>'use strict';

const Hapi = require('hapi');
const fs = require('fs');
const server = new Hapi.Server();

server.connection({ port: 22935,
                    tls: {
                        key: fs.readFileSync('/certs/privkey.pem'),
                        cert: fs.readFileSync('/certs/fullchain.pem'),
                        ca: fs.readFileSync('/certs/chain.pem')
                    }

});

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        reply('Coming soon....... :)');
    }
});

server.register(require('inert'), (err) => {
    if (err) {
        throw err;
    }

    server.route({
        method: 'GET',
        path: '/experiment/{param*}',
        handler: {
            directory: {
            path: 'experiment',
            listing: true
            }
        }
    });
});

server.start(() => {
    console.log('Server running at:', server.info.uri);
});<commit_msg>adding letsencrypt...<commit_after>'use strict';

const Hapi = require('hapi');
const fs = require('fs');
const server = new Hapi.Server();

server.connection({ port: 22935,
                    tls: {
                        key: fs.readFileSync('/home/kamil/kamiljozwiak.main/certs/privkey.pem'),
                        cert: fs.readFileSync('/home/kamil/kamiljozwiak.main/certs/fullchain.pem'),
                        ca: fs.readFileSync('/home/kamil/kamiljozwiak.main/certs/chain.pem')
                    }

});

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        reply('Coming soon....... :)');
    }
});

server.register(require('inert'), (err) => {
    if (err) {
        throw err;
    }

    server.route({
        method: 'GET',
        path: '/experiment/{param*}',
        handler: {
            directory: {
            path: 'experiment',
            listing: true
            }
        }
    });
});

server.start(() => {
    console.log('Server running at:', server.info.uri);
});<|endoftext|>


<commit_before>// add http module and client
var http = require('http');
var express = require('express');
var request = require('request');
var tokens = require('./tokens');
var callback = require('./callback');
var settings = require('./settings');
var ua = require('universal-analytics');

//set the global variable to hold the time to next match
global.nextMatch = null;
global.nextOpponent = null;

//let the server port be configurable. it really doesn't matter since this
//is a listening port. Moubot v1 does not listen.
var PORT = settings.serverPort;

//initialize Google Analytics
var visitor = ua(settings.GA);

//initiate the express web app
var app = express();
app.use(express.static(__dirname + '/web'));
app.use(ua.middleware(settings.GA));

//api call that returns the infomation about the next match. this needs to
//be tidyed up.
app.get('/api', function(req, res){
  //google pageview tracking
  visitor.pageview("/api").send();
  res.send('Next match is ' + (nextMatch || 'not scheduled') + '.');
});

//early slack api. only knows how to respond with the time till next match
app.get('/api/slack', function(req, res){
  visitor.pageview("/api/slack").send();
  res.send('{ "text": "Next match is ' + (nextMatch || 'not scheduled') + '."}');
});

//let's define options for our recurrent http request
var options = {
  url: tokens.resultsEndpoint,
  headers: {
    'X-Auth-Token' : process.env.resultsToken
  }
};

var server = app.listen(process.env.PORT || PORT, function(){
  console.log("Server started at localhost:%s", PORT);

  //keep a track of last matchday commented, to avoid duplicates.
  //this needs refactoring
  global.lastPreMatchComment = null;
  global.lastPostMatchComment = null;

  //set up a timer.
  setInterval(function(){
    console.log("Tick...next match is " + (nextMatch || "not scheduled.") );
    request(options, callback.callback);
  }, settings.pingInteralInMilliseconds);
});
<commit_msg>#14 is now complete<commit_after>// add http module and client
var http = require('http');
var express = require('express');
var request = require('request');
var tokens = require('./tokens');
var callback = require('./callback');
var settings = require('./settings');
var ua = require('universal-analytics');

//set the global variable to hold the time to next match
global.nextMatch = null;
global.nextOpponent = null;

//let the server port be configurable. it really doesn't matter since this
//is a listening port. Moubot v1 does not listen.
var PORT = settings.serverPort;

//initialize Google Analytics
var visitor = ua(settings.GA);

//initiate the express web app
var app = express();
app.use(express.static(__dirname + '/web'));
app.use(ua.middleware(settings.GA));

//api call that returns the infomation about the next match. this needs to
//be tidyed up.
app.get('/api', function(req, res){
  //google pageview tracking
  visitor.pageview("/api").send();
  res.send('Next match is ' + (nextMatch || 'not scheduled') + '.');
});

//early slack api. only knows how to respond with the time left until the next match
app.get('/api/slack', function(req, res){
  visitor.pageview("/api/slack").send();
  res.send('{ "text": "Next match is ' + (nextMatch || 'not scheduled') + '."}');
});

//let's define options for our recurrent http request
var options = {
  url: tokens.resultsEndpoint,
  headers: {
    'X-Auth-Token' : process.env.resultsToken
  }
};

var server = app.listen(process.env.PORT || PORT, function(){
  console.log("Server started at localhost:%s", PORT);

  //keep a track of last matchday commented, to avoid duplicates.
  //this needs refactoring
  global.lastPreMatchComment = null;
  global.lastPostMatchComment = null;

  //set up a timer.
  setInterval(function(){
    console.log("Tick...next match is " + (nextMatch || "not scheduled.") );
    request(options, callback.callback);
  }, settings.pingInteralInMilliseconds);
});
<|endoftext|>


<commit_before>var _ = require('lodash'),
    config = require('nconf'),
    rest = require('rest'),
    mime = require('rest/interceptor/mime'),
    client = rest.wrap(mime, { mime: 'application/json' });

exports.receiveEvent = function (req, res) {
  var endpoint, body, transition, shortMessage, configProps, projectKey,
      ev = req.body;

  var hasTransition = _.has(ev, 'transition');

  if (!hasTransition && _.has(ev, 'changelog')) { // Newer jira versions
    _.each(ev.changelog.items, function (change) {
      if (change.field == 'status' && change.fromString) {
        ev.transition = { from_status: change.fromString, transitionName: change.toString }
        hasTransition = true;
      }
    });
  }

  projectKey = ev.issue.key.split('-')[0];

  configProps = {
    slackUrl: projectKey + ':SLACK_URL',
    jiraDomain: projectKey + ':JIRA_DOMAIN'
  };

  if (!config.get(configProps.slackUrl) || !config.get(configProps.jiraDomain))
    return;

  endpoint = config.get(configProps.slackUrl);

  if(_.has(ev, 'issue'))
    var issueUrl = 'https://' + config.get(configProps.jiraDomain) + '/browse/' + ev.issue.key;

  if (_.has(ev, 'webhookEvent') && ev.webhookEvent == 'jira:issue_created') {
    /* jshint camelcase:false */
    transition = {
      issue: ev.issue.key,
      issueUrl: issueUrl,
      description: ev.issue.fields.summary,
      who: ev.user.displayName,
      priority: ev.issue.fields.priority.name,
      icon: ''
    };

    transition.assignee = (ev.issue.fields.assignee) ?
        ev.issue.fields.assignee.displayName : 'Unassigned';

    var issueTypes = {
      'Task': ':memo:',
      'New Feature': ':sparkles:',
      'Bug': ':boom:',
      'Improvement': ':wrench:',
      'Epic': ':book:',
      'Story': ':bulb:'
    };

    if(typeof issueTypes[ev.issue.fields.issuetype.name] !== 'undefined') {
      transition.icon = issueTypes[ev.issue.fields.issuetype.name] + ' ';
    }

    shortMessage = _.template(
        '<%= t.icon %>*<%= t.who %>* created <<%= t.issueUrl %>|<%= t.issue %>>',
        { t: transition }
    );

    body = {
      attachments: [
        {
          "mrkdwn_in": ["pretext", "fallback"],
          fallback: shortMessage,
          pretext: shortMessage,
          color: '#42B854',
          fields: [
            {
              title: 'Current Assignee',
              value: _.template(
                  '<%= t.assignee %>',
                  { t: transition }
              ),
              short: true
            },
            {
              title: 'Priority',
              value: _.template(
                  '<%= t.priority %>',
                  { t: transition }
              ),
              short: true
            },
            {
              title: 'Summary',
              value: _.template(
                  '<%= t.description %>',
                  { t: transition }
              ),
              short: false
            }
          ]
        }
      ]
    };

    client({
      path: endpoint,
      entity: body
    }).then(function (response) {
      console.log('POST -- ' + endpoint);
      console.log(response.status);
    });
  }

  if (hasTransition) {
    /* jshint camelcase:false */
    transition = {
      issue: ev.issue.key,
      issueUrl: issueUrl,
      description: ev.issue.fields.summary,
      fromStatus: ev.transition.from_status,
      toStatus: ev.transition.transitionName,
      who: ev.user.displayName
    };

    transition.assignee = (ev.issue.fields.assignee) ?
        ev.issue.fields.assignee.displayName : 'Unassigned';

    shortMessage = _.template(
        '*<%= t.who %>* moved <<%= t.issueUrl %>|<%= t.issue %>>',
        { t: transition }
    );

    body = {
      attachments: [
        {
          "mrkdwn_in": ["pretext", "fallback"],
          fallback: shortMessage,
          pretext: shortMessage,
          color: '#C0C0C0',
          fields: [
            {
              title: 'Transition',
              value: _.template(
                  '<%= t.fromStatus %> → <%= t.toStatus %>',
                  { t: transition }
              ),
              short: true
            },
            {
              title: 'Current Assignee',
              value: _.template(
                  '<%= t.assignee %>',
                  { t: transition }
              ),
              short: true
            },
            {
              title: 'Summary',
              value: _.template(
                  '<%= t.description %>',
                  { t: transition }
              ),
              short: false
            }
          ]
        }
      ]
    };

    client({
      path: endpoint,
      entity: body
    }).then(function (response) {
      console.log('POST -- ' + endpoint);
      console.log(response.status);
    });
  }

  if (_.has(ev, 'comment') && !_.isNull(ev.comment)) {
    var isEdit = ev.comment.created != ev.comment.updated;

    var action = isEdit ? 'updated a comment' : 'commented';

    var commentUrl = issueUrl + '?focusedCommentId=' + ev.comment.id + '&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-' + ev.comment.id;

    var shortMessage = _.template(
        '*<%= c.author.displayName %>* <<%= commentUrl %>|<%= action %>> on issue <<%= issueUrl %>|#<%= t.issue.key %> - <%= issueSummary %>>',
        { c: ev.comment, t: ev, issueUrl: issueUrl, action: action, commentUrl: commentUrl,
          issueSummary: ev.issue.fields.summary.replace(/&/g, '&').replace(/>/g, '>').replace(/</g, '<')
        }
    );

    var body = {
      attachments: [
        {
          "mrkdwn_in": ["pretext", "fallback", "text"],
          fallback: shortMessage,
          pretext: shortMessage,
          color: '#C0C0C0',
          text: ev.comment.body.replace(/!([^\s]+)!/g, "$1").replace(/\{\{(.+)\}\}/g, "`$1`")
        }
      ]
    };

    client({
      path: endpoint,
      entity: body
    }).then(function (response) {
      console.log('POST -- ' + endpoint);
      console.log(response.status);
    });
  }

  res.json(200);
};
<commit_msg>Added fix version and component fields to issue created event<commit_after>var _ = require('lodash'),
    config = require('nconf'),
    rest = require('rest'),
    mime = require('rest/interceptor/mime'),
    client = rest.wrap(mime, { mime: 'application/json' });

exports.receiveEvent = function (req, res) {
  var endpoint, body, transition, shortMessage, configProps, projectKey,
      ev = req.body;

  var hasTransition = _.has(ev, 'transition');

  if (!hasTransition && _.has(ev, 'changelog')) { // Newer jira versions
    _.each(ev.changelog.items, function (change) {
      if (change.field == 'status' && change.fromString) {
        ev.transition = { from_status: change.fromString, transitionName: change.toString }
        hasTransition = true;
      }
    });
  }

  projectKey = ev.issue.key.split('-')[0];

  configProps = {
    slackUrl: projectKey + ':SLACK_URL',
    jiraDomain: projectKey + ':JIRA_DOMAIN'
  };

  if (!config.get(configProps.slackUrl) || !config.get(configProps.jiraDomain))
    return;

  endpoint = config.get(configProps.slackUrl);

  if(_.has(ev, 'issue'))
    var issueUrl = 'https://' + config.get(configProps.jiraDomain) + '/browse/' + ev.issue.key;

  if (_.has(ev, 'webhookEvent') && ev.webhookEvent == 'jira:issue_created') {
    var fixVersions = _.map(ev.issue.fields.fixVersions, function(v){ return v.name }).join(', ');
    var components = _.map(ev.issue.fields.components, function(v){ return v.name }).join(', ');

    /* jshint camelcase:false */
    transition = {
      issue: ev.issue.key,
      issueUrl: issueUrl,
      description: ev.issue.fields.summary,
      who: ev.user.displayName,
      priority: ev.issue.fields.priority.name,
      icon: '',
      fixVersion: fixVersions != '' ? fixVersions : 'Not set',
      components: components != '' ? components : 'Not set'
    };

    transition.assignee = (ev.issue.fields.assignee) ?
        ev.issue.fields.assignee.displayName : 'Unassigned';

    var issueTypes = {
      'Task': ':memo:',
      'New Feature': ':sparkles:',
      'Bug': ':boom:',
      'Improvement': ':wrench:',
      'Epic': ':book:',
      'Story': ':bulb:'
    };

    if(typeof issueTypes[ev.issue.fields.issuetype.name] !== 'undefined') {
      transition.icon = issueTypes[ev.issue.fields.issuetype.name] + ' ';
    }

    shortMessage = _.template(
        '<%= t.icon %>*<%= t.who %>* created <<%= t.issueUrl %>|<%= t.issue %>>',
        { t: transition }
    );

    body = {
      attachments: [
        {
          "mrkdwn_in": ["pretext", "fallback"],
          fallback: shortMessage,
          pretext: shortMessage,
          color: '#42B854',
          fields: [
            {
              title: 'Current Assignee',
              value: _.template(
                  '<%= t.assignee %>',
                  { t: transition }
              ),
              short: true
            },
            {
              title: 'Priority',
              value: _.template(
                  '<%= t.priority %>',
                  { t: transition }
              ),
              short: true
            },
            {
              title: 'Fix Version',
              value: _.template(
                  '<%= t.fixVersion %>',
                  { t: transition }
              ),
              short: true
            },
            {
              title: 'Components',
              value: _.template(
                  '<%= t.components %>',
                  { t: transition }
              ),
              short: true
            },
            {
              title: 'Summary',
              value: _.template(
                  '<%= t.description %>',
                  { t: transition }
              ),
              short: false
            }
          ]
        }
      ]
    };

    client({
      path: endpoint,
      entity: body
    }).then(function (response) {
      console.log('POST -- ' + endpoint);
      console.log(response.status);
    });
  }

  if (hasTransition) {
    /* jshint camelcase:false */
    transition = {
      issue: ev.issue.key,
      issueUrl: issueUrl,
      description: ev.issue.fields.summary,
      fromStatus: ev.transition.from_status,
      toStatus: ev.transition.transitionName,
      who: ev.user.displayName
    };

    transition.assignee = (ev.issue.fields.assignee) ?
        ev.issue.fields.assignee.displayName : 'Unassigned';

    shortMessage = _.template(
        '*<%= t.who %>* moved <<%= t.issueUrl %>|<%= t.issue %>>',
        { t: transition }
    );

    body = {
      attachments: [
        {
          "mrkdwn_in": ["pretext", "fallback"],
          fallback: shortMessage,
          pretext: shortMessage,
          color: '#C0C0C0',
          fields: [
            {
              title: 'Transition',
              value: _.template(
                  '<%= t.fromStatus %> → <%= t.toStatus %>',
                  { t: transition }
              ),
              short: true
            },
            {
              title: 'Current Assignee',
              value: _.template(
                  '<%= t.assignee %>',
                  { t: transition }
              ),
              short: true
            },
            {
              title: 'Summary',
              value: _.template(
                  '<%= t.description %>',
                  { t: transition }
              ),
              short: false
            }
          ]
        }
      ]
    };

    client({
      path: endpoint,
      entity: body
    }).then(function (response) {
      console.log('POST -- ' + endpoint);
      console.log(response.status);
    });
  }

  if (_.has(ev, 'comment') && !_.isNull(ev.comment)) {
    var isEdit = ev.comment.created != ev.comment.updated;

    var action = isEdit ? 'updated a comment' : 'commented';

    var commentUrl = issueUrl + '?focusedCommentId=' + ev.comment.id + '&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-' + ev.comment.id;

    var shortMessage = _.template(
        '*<%= c.author.displayName %>* <<%= commentUrl %>|<%= action %>> on issue <<%= issueUrl %>|#<%= t.issue.key %> - <%= issueSummary %>>',
        { c: ev.comment, t: ev, issueUrl: issueUrl, action: action, commentUrl: commentUrl,
          issueSummary: ev.issue.fields.summary.replace(/&/g, '&').replace(/>/g, '>').replace(/</g, '<')
        }
    );

    var body = {
      attachments: [
        {
          "mrkdwn_in": ["pretext", "fallback", "text"],
          fallback: shortMessage,
          pretext: shortMessage,
          color: '#C0C0C0',
          text: ev.comment.body.replace(/!([^\s]+)!/g, "$1").replace(/\{\{(.+)\}\}/g, "`$1`")
        }
      ]
    };

    client({
      path: endpoint,
      entity: body
    }).then(function (response) {
      console.log('POST -- ' + endpoint);
      console.log(response.status);
    });
  }

  res.json(200);
};
<|endoftext|>


<commit_before>var Backbone = require('backbone');

const TYPE_CLASS = 1;
const TYPE_ID = 2;

const Selector = Backbone.Model.extend(
  {
    idAttribute: 'name',

    defaults: {
      name: '',

      label: '',

      // Type of the selector
      type: TYPE_CLASS,

      // If not active it's not selectable by the style manager (uncheckboxed)
      active: true,

      // Can't be seen by the style manager, therefore even by the user
      // Will be rendered only in export code
      private: false,

      // If true, can't be removed from the attacched element
      protected: false
    },

    initialize() {
      const name = this.get('name');
      const label = this.get('label');

      if (!name) {
        this.set('name', label);
      } else if (!label) {
        this.set('label', name);
      }

      this.set('name', Selector.escapeName(this.get('name')));
    },

    /**
     * Get full selector name
     * @return {string}
     */
    getFullName() {
      let init = '';

      switch (this.get('type')) {
        case TYPE_CLASS:
          init = '.';
          break;
        case TYPE_ID:
          init = '#';
          break;
      }

      return init + this.get('name');
    }
  },
  {
    // All type selectors: https://developer.mozilla.org/it/docs/Web/CSS/CSS_Selectors
    // Here I define only what I need
    TYPE_CLASS,

    TYPE_ID,

    /**
     * Escape string
     * @param {string} name
     * @return {string}
     * @private
     */
    escapeName(name) {
      return `${name}`.trim().replace(/([^a-z0-9\w-]+)/gi, '-');
    }
  }
);

module.exports = Selector;
<commit_msg>Added support for colon in css class names<commit_after>var Backbone = require('backbone');

const TYPE_CLASS = 1;
const TYPE_ID = 2;

const Selector = Backbone.Model.extend(
  {
    idAttribute: 'name',

    defaults: {
      name: '',

      label: '',

      // Type of the selector
      type: TYPE_CLASS,

      // If not active it's not selectable by the style manager (uncheckboxed)
      active: true,

      // Can't be seen by the style manager, therefore even by the user
      // Will be rendered only in export code
      private: false,

      // If true, can't be removed from the attacched element
      protected: false
    },

    initialize() {
      const name = this.get('name');
      const label = this.get('label');

      if (!name) {
        this.set('name', label);
      } else if (!label) {
        this.set('label', name);
      }

      this.set('name', Selector.escapeName(this.get('name')));
    },

    /**
     * Get full selector name
     * @return {string}
     */
    getFullName() {
      let init = '';

      switch (this.get('type')) {
        case TYPE_CLASS:
          init = '.';
          break;
        case TYPE_ID:
          init = '#';
          break;
      }

      return init + this.get('name');
    }
  },
  {
    // All type selectors: https://developer.mozilla.org/it/docs/Web/CSS/CSS_Selectors
    // Here I define only what I need
    TYPE_CLASS,

    TYPE_ID,

    /**
     * Escape string
     * @param {string} name
     * @return {string}
     * @private
     */
    escapeName(name) {
      return `${name}`.trim().replace(/([^a-z0-9\w-\:]+)/gi, '-');
    }
  }
);

module.exports = Selector;
<|endoftext|>


<commit_before>var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');
var mongoose   = require('mongoose');
var morgan = require('morgan');

var logger = morgan('combined')

//User Models
var User       = require('./models/user');
mongoose.connect('mongodb://10.132.126.169/battle-api');
// mongoose.connect('mongodb://localhost/battle-api');

// ADD MIDDLEWARE
app.use(morgan('combined'))
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = '8080';
var private_ip = '10.132.125.55';

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

router.get('/', function(req, res, next) {
  console.log('hitting home')
    res.end("Hello, World!!!");
});

router.route('/users')
    .post(function(req, res) {
        var user = new User();
        user.name = req.body.name;

        user.save(function(err) {
            if (err) res.send(err);

            res.json({ message: 'User created!' });
        })
    })
    .get(function(req,res) {
        User.find(function(err,users) {
          if(err) req.send(err);
          res.send(users);
        })
      });

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api',router);

// START THE SERVER
// =============================================================================
app.listen(port, private_ip);
console.log('Server started on port ' + port);
<commit_msg>removing home route<commit_after>var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');
var mongoose   = require('mongoose');
var morgan = require('morgan');

var logger = morgan('combined')

//User Models
var User       = require('./models/user');
mongoose.connect('mongodb://10.132.126.169/battle-api');
// mongoose.connect('mongodb://localhost/battle-api');

// ADD MIDDLEWARE
app.use(morgan('combined'))
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = '8080';
var private_ip = '10.132.125.55';

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

router.route('/users')
    .post(function(req, res) {
        var user = new User();
        user.name = req.body.name;

        user.save(function(err) {
            if (err) res.send(err);

            res.json({ message: 'User created!' });
        })
    })
    .get(function(req,res) {
        User.find(function(err,users) {
          if(err) req.send(err);
          res.send(users);
        })
      });

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api',router);

// START THE SERVER
// =============================================================================
app.listen(port, private_ip);
console.log('Server started on port ' + port);
<|endoftext|>


<commit_before>const zlib = require('zlib')
const fs = require('fs')
const http = require('http')
const express = require('express')
const app = express()
const WebSocket = require('ws')
const conf = require('nconf')
const bodyParser = require('body-parser')
const maxmind = require('maxmind')
const moment = require('moment')
const request = require('request')
const uuid = require('uuid/v1')
const CronJob = require('cron').CronJob
const db = require('./database.js')
const log = console.log

conf.file({file: 'cfg.json'})
conf.defaults({
  port: 3013,
  bind: '127.0.0.1',
  servers: [{id: 0, name: 'Server'}],
  ipFile: './GeoLite2-City.mmdb'
})
app.use('/static', express.static(`${__dirname}/dist/static`))
app.use(bodyParser.json())
const ipFile = conf.get('ipFile')
const cityLookup = {}
const clients = new Map()
let servers = conf.get('servers') || []

const logBuffer = {}
const logEvent = (server, data, event) => {
  const record = {server: server, node: data.name, event: event, timestamp: moment().unix()}
  if (event === 'connect') {
    record.pub = data.pub
    record.vpn = data.vpn
    record.country_code = data.country_code
    record.country_name = data.country_name
  }
  if (!logBuffer[data.name])
    logBuffer[data.name] = setTimeout(() => {
      logBuffer[data.name] = false
      clients.forEach((ws) => ws.send(JSON.stringify(record)))
      db.Log.create(record)
    }, 1500)
  else {
    clearTimeout(logBuffer[data.name])
    logBuffer[data.name] = false
  }
}
const validateIPaddress = (ipaddress) => /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress.toString())
const loadIPdatabase = () => {
  return new Promise((resolve) => {
    fs.stat(ipFile, (err, stat) => {
      const now = new Date().getTime()
      const expire = new Date((stat ? stat.ctime : '')).getTime() + 30 * 24 * 60 * 60 * 1000
      if (err || now > expire) {
        const req = request('http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz')
        req.on('response', (resp) => {
          if(resp.statusCode === 200) {
            req.pipe(zlib.createGunzip()).pipe(fs.createWriteStream(ipFile))
              .on('finish', () => {
                maxmind.open('./GeoLite2-City.mmdb', (err, lookup) => {
                  cityLookup.get = (ip) => (ip ? lookup.get(ip) : false)
                  resolve(cityLookup)
                })
              })
          } else
            maxmind.open('./GeoLite2-City.mmdb', (err, lookup) => {
              if (err)
                log(err)
              cityLookup.get = (ip) => (ip ? lookup.get(ip) : false)
              resolve(cityLookup)
            })
        })
      } else
        maxmind.open('./GeoLite2-City.mmdb', (err, lookup) => {
          if (err)
            log(err)
          cityLookup.get = (ip) => (ip ? lookup.get(ip) : false)
          resolve(cityLookup)
        })
    })
  })
}

new CronJob({
  cronTime: '00 10 * 10 * *',
  onTick: loadIPdatabase,
  start: true
})

app.get('/', (req, res) => res.sendFile(`${__dirname}/dist/index.html`))
app.get('/servers', (req, res) => res.json(servers.map((server, idx) => ({name: server.name, id: idx}))))
const compare = (a,b) => {
  if (a.country_code < b.country_code)
    return -1
  if (a.country_code > b.country_code)
    return 1
  if (a.pub < b.pub)
    return -1
  if (a.pub > b.pub)
    return 1
  if (a.timestamp < b.timestamp)
    return 1
  if (a.timestamp > b.timestamp)
    return -1
  return 0
}
app.post('/server/:id/connect', (req, res) => {
  const serverId = parseInt(req.params.id, 10)
  const pub = req.body.pub
  const cn = (req.body.cn || '').trim()
  const vpn = req.body.vpn
  if (!validateIPaddress(pub) || !validateIPaddress(vpn) || !cn.length)
    res.sendStatus(400)
  else {
    const loc = cityLookup.get(pub)
    const entry = {name: cn, pub: pub, vpn: vpn, timestamp: moment().unix()}
    if (loc) {
      entry.country_code = loc.country.iso_code
      entry.country_name = loc.country.names.en
    }
    logEvent(serverId, entry, 'connect')
    servers[serverId].entries.push(entry)
    res.sendStatus(200)
  }
})
app.post('/server/:id/disconnect', (req, res) => {
  const serverId = parseInt(req.params.id, 10)
  const cn = (req.body.cn || '').trim()
  if (!cn.length)
    res.sendStatus(400)
  else {
    logEvent(serverId, {name: cn}, 'disconnect')
    servers[serverId].entries = servers[serverId].entries.filter((itm) => itm.name !== cn)
    res.sendStatus(200)
  }
})
app.get('/entries/:id', (req, res) => res.json(servers[req.params.id].entries.sort(compare)))
app.get('/log/:id/size', (req, res) => db.Log.count({where: {server: req.params.id}}).then((size) => res.json({value: size})))
app.get('/log/:id/:page/:size', (req, res) => {
  const page = parseInt(req.params.page, 10)
  const size = parseInt(req.params.size, 10)
  const query = db.Log.findAll({where: {server: req.params.id}, offset: (page - 1) * size, limit: size, order: [['timestamp', 'DESC']]})
  query.then((data) => {
    res.json(data.map((item) => ({server: item.server, node: item.node, timestamp: item.timestamp, event: item.event})))
  })
})

const server = http.createServer(app)
const wss = new WebSocket.Server({server})

wss.on('connection', (ws) => {
  const id = uuid()
  clients.set(id, ws)
  ws.on('close', () => clients.delete(id))
  ws.on('error', (err) => {
    log(err)
    clients.delete(id)
  })
})

db.init().then(() => db.state()).then((entries) => {
  loadIPdatabase().then(() => {
    servers.forEach((server, idx) => {
      server.entries = entries.filter((entry) => entry.server === idx).map((entry) => {
        const data = {
          name: entry.node,
          timestamp: entry.timestamp,
          pub: entry.pub,
          vpn: entry.vpn
        }
        const loc = cityLookup.get(entry.pub)
        if (entry.pub && loc) {
          data.country_code = loc.country.iso_code
          data.country_name = loc.country.names.en
        }
        return data
      })
    })
    server.listen({host: conf.get('bind'),port: conf.get('port'),exclusive: true})
  })
})
<commit_msg>Input validation<commit_after>const zlib = require('zlib')
const fs = require('fs')
const http = require('http')
const express = require('express')
const app = express()
const WebSocket = require('ws')
const conf = require('nconf')
const bodyParser = require('body-parser')
const maxmind = require('maxmind')
const moment = require('moment')
const request = require('request')
const uuid = require('uuid/v1')
const CronJob = require('cron').CronJob
const db = require('./database.js')
const log = console.log

conf.file({file: 'cfg.json'})
conf.defaults({
  port: 3013,
  bind: '127.0.0.1',
  servers: [{id: 0, name: 'Server'}],
  ipFile: './GeoLite2-City.mmdb'
})
app.use('/static', express.static(`${__dirname}/dist/static`))
app.use(bodyParser.json())
const ipFile = conf.get('ipFile')
const cityLookup = {}
const clients = new Map()
let servers = conf.get('servers') || []

const logBuffer = {}
const logEvent = (server, data, event) => {
  const record = {server: server, node: data.name, event: event, timestamp: moment().unix()}
  if (event === 'connect') {
    record.pub = data.pub
    record.vpn = data.vpn
    record.country_code = data.country_code
    record.country_name = data.country_name
  }
  if (!logBuffer[data.name])
    logBuffer[data.name] = setTimeout(() => {
      logBuffer[data.name] = false
      clients.forEach((ws) => ws.send(JSON.stringify(record)))
      db.Log.create(record)
    }, 1500)
  else {
    clearTimeout(logBuffer[data.name])
    logBuffer[data.name] = false
  }
}
const validateIPaddress = (ipaddress) => /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress.toString())
const validateNumber = (n) => !isNaN(parseFloat(n)) && isFinite(n)
const loadIPdatabase = () => {
  return new Promise((resolve) => {
    fs.stat(ipFile, (err, stat) => {
      const now = new Date().getTime()
      const expire = new Date((stat ? stat.ctime : '')).getTime() + 30 * 24 * 60 * 60 * 1000
      if (err || now > expire) {
        const req = request('http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz')
        req.on('response', (resp) => {
          if(resp.statusCode === 200) {
            req.pipe(zlib.createGunzip()).pipe(fs.createWriteStream(ipFile))
              .on('finish', () => {
                maxmind.open('./GeoLite2-City.mmdb', (err, lookup) => {
                  cityLookup.get = (ip) => (ip ? lookup.get(ip) : false)
                  resolve(cityLookup)
                })
              })
          } else
            maxmind.open('./GeoLite2-City.mmdb', (err, lookup) => {
              if (err)
                log(err)
              cityLookup.get = (ip) => (ip ? lookup.get(ip) : false)
              resolve(cityLookup)
            })
        })
      } else
        maxmind.open('./GeoLite2-City.mmdb', (err, lookup) => {
          if (err)
            log(err)
          cityLookup.get = (ip) => (ip ? lookup.get(ip) : false)
          resolve(cityLookup)
        })
    })
  })
}

new CronJob({
  cronTime: '00 10 * 10 * *',
  onTick: loadIPdatabase,
  start: true
})

app.get('/', (req, res) => res.sendFile(`${__dirname}/dist/index.html`))
app.get('/servers', (req, res) => res.json(servers.map((server, idx) => ({name: server.name, id: idx}))))
const compare = (a,b) => {
  if (a.country_code < b.country_code)
    return -1
  if (a.country_code > b.country_code)
    return 1
  if (a.pub < b.pub)
    return -1
  if (a.pub > b.pub)
    return 1
  if (a.timestamp < b.timestamp)
    return 1
  if (a.timestamp > b.timestamp)
    return -1
  return 0
}
const validateServer = (req, res, next) => {
  if (!validateNumber(req.params.id))
    return res.sendStatus(400)
  if (!servers[req.params.id])
    return res.sendStatus(404)
  next()
}
app.post('/server/:id/connect', validateServer, (req, res) => {
  const serverId = parseInt(req.params.id, 10)
  const pub = req.body.pub
  const cn = (req.body.cn || '').trim()
  const vpn = req.body.vpn
  if (!validateIPaddress(pub) || !validateIPaddress(vpn) || !cn.length)
    return res.sendStatus(400)
  const loc = cityLookup.get(pub)
  const entry = {name: cn, pub: pub, vpn: vpn, timestamp: moment().unix()}
  if (loc) {
    entry.country_code = loc.country.iso_code
    entry.country_name = loc.country.names.en
  }
  logEvent(serverId, entry, 'connect')
  servers[serverId].entries.push(entry)
  res.sendStatus(200)
})
app.post('/server/:id/disconnect', validateServer, (req, res) => {
  const serverId = parseInt(req.params.id, 10)
  const cn = (req.body.cn || '').trim()
  if (!cn.length)
    return res.sendStatus(400)
  logEvent(serverId, {name: cn}, 'disconnect')
  servers[serverId].entries = servers[serverId].entries.filter((itm) => itm.name !== cn)
  res.sendStatus(200)
})
app.get('/entries/:id', validateServer, (req, res) => res.json(servers[req.params.id].entries.sort(compare)))
app.get('/log/:id/size', validateServer, (req, res) => db.Log.count({where: {server: req.params.id}}).then((size) => res.json({value: size})))
app.get('/log/:id/:page/:size', validateServer, (req, res) => {
  if (!validateNumber(req.params.page) || !validateNumber(req.params.size))
    return res.sendStatus(400)
  const page = parseInt(req.params.page, 10)
  const size = parseInt(req.params.size, 10)
  const query = db.Log.findAll({where: {server: req.params.id}, offset: (page - 1) * size, limit: size, order: [['timestamp', 'DESC']]})
  query.then((data) => {
    res.json(data.map((item) => ({server: item.server, node: item.node, timestamp: item.timestamp, event: item.event})))
  })
})

const server = http.createServer(app)
const wss = new WebSocket.Server({server})

wss.on('connection', (ws) => {
  const id = uuid()
  clients.set(id, ws)
  ws.on('close', () => clients.delete(id))
  ws.on('error', (err) => {
    log(err)
    clients.delete(id)
  })
})

db.init().then(() => db.state()).then((entries) => {
  loadIPdatabase().then(() => {
    servers.forEach((server, idx) => {
      server.entries = entries.filter((entry) => entry.server === idx).map((entry) => {
        const data = {
          name: entry.node,
          timestamp: entry.timestamp,
          pub: entry.pub,
          vpn: entry.vpn
        }
        const loc = cityLookup.get(entry.pub)
        if (entry.pub && loc) {
          data.country_code = loc.country.iso_code
          data.country_name = loc.country.names.en
        }
        return data
      })
    })
    server.listen({host: conf.get('bind'),port: conf.get('port'),exclusive: true})
  })
})
<|endoftext|>


<commit_before>'use strict';

var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
var AppDispatcher = require('../dispatcher/AppDispatcher');
var CalculatorConstants = require('../constants/CalculatorConstants');

var CHANGE_EVENT = 'change';

var _numericKeyTyped = [];
var _signKeyTyped = null;
var _numberTyped = [];
var _displayScreen = 0;
var _displayFormulae = [];

var CalculatorStore = assign({}, EventEmitter.prototype, {

  getDisplayScreen: function() {
    return _displayScreen;
  },
  getDisplayFormulae: function() {
    var maxNumberOfChar = 40;

    var characterCount = 0;
    _displayFormulae = _displayFormulae.reverse().filter(function(formula) {
      characterCount += formula.literal.length;
      return characterCount < maxNumberOfChar;
    }).reverse();

    return _displayFormulae;
  },

  emitChange: function() {
    this.emit(CHANGE_EVENT);
  },

  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },
  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  },
});

function processKey(key) {

  if(key === '+' || key === '-' || key === 'x' || key === '÷' || key === '=' || key === '<<') {

    // if a nuber was being typed we reset it otherwise we reset everything
    if(key === '<<') {
      if(_numericKeyTyped.length) {
        _numericKeyTyped = [];
      } else {
        _numberTyped = [];
      }
      _displayScreen = 0;
    }

    if(key === '+' || key === '-' || key === 'x' || key === '÷') {
      _signKeyTyped = key;
    }

    // a number was previously typed
    if(_numericKeyTyped.length) {

      var number = parseFloat(_numericKeyTyped.join(''));
      _numberTyped.push(number);

      _numericKeyTyped = [];

      if(_numberTyped.length === 2) {
        var calculation = 0;

        switch(_signKeyTyped) {
          case '+':
            calculation = _numberTyped[0] + _numberTyped[1];
            break;
          case '-':
            calculation = _numberTyped[0] - _numberTyped[1];
            break;
          case 'x':
            calculation = _numberTyped[0] * _numberTyped[1];
            break;
          case '÷':
            calculation = _numberTyped[0] / _numberTyped[1];
            break;
          default:
        }

        _displayFormulae.push({
          literal: '' + _numberTyped[0].toString() + ' ' +
            _signKeyTyped + ' ' +  _numberTyped[1].toString(),
          sign: _signKeyTyped
        });
        _displayScreen = calculation;
        _numberTyped = [calculation];
      }
    }
  } else {
    _numericKeyTyped.push(key);
    _displayScreen = _numericKeyTyped;
  }
}

CalculatorStore.dispatchToken = AppDispatcher.register(function(action) {

  switch(action.type) {
    case CalculatorConstants.KEY_TYPED:
      var key = action.key;
      if (key !== '') {
        processKey(key);
        CalculatorStore.emitChange();
      }
      break;
    default:
      // no op
  }
});

module.exports = CalculatorStore;
<commit_msg>Adds some checks on user inputs<commit_after>'use strict';

var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
var AppDispatcher = require('../dispatcher/AppDispatcher');
var CalculatorConstants = require('../constants/CalculatorConstants');

var CHANGE_EVENT = 'change';

var _numericKeyTyped = [];
var _signKeyTyped = null;
var _numberTyped = [];
var _displayScreen = 0;
var _displayFormulae = [];

var CalculatorStore = assign({}, EventEmitter.prototype, {

  getDisplayScreen: function() {
    return _displayScreen;
  },
  getDisplayFormulae: function() {
    var maxNumberOfChar = 40;

    var characterCount = 0;
    _displayFormulae = _displayFormulae.reverse().filter(function(formula) {
      characterCount += formula.literal.length;
      return characterCount < maxNumberOfChar;
    }).reverse();

    return _displayFormulae;
  },

  emitChange: function() {
    this.emit(CHANGE_EVENT);
  },

  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },
  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  },
});

function processKey(key) {

  if(key === '+' || key === '-' || key === 'x' || key === '÷' || key === '=' || key === '<<') {

    // if a nuber was being typed we reset it otherwise we reset everything
    if(key === '<<') {
      if(_numericKeyTyped.length) {
        _numericKeyTyped = [];
      } else {
        _numberTyped = [];
      }
      _displayScreen = 0;
    }

    if(key === '+' || key === '-' || key === 'x' || key === '÷') {
      _signKeyTyped = key;
    }

    // a number was previously typed
    if(_numericKeyTyped.length) {

      var number = parseFloat(_numericKeyTyped.join(''));
      _numberTyped.push(number);

      _numericKeyTyped = [];

      if(_numberTyped.length === 2) {
        var calculation = 0;

        switch(_signKeyTyped) {
          case '+':
            calculation = _numberTyped[0] + _numberTyped[1];
            break;
          case '-':
            calculation = _numberTyped[0] - _numberTyped[1];
            break;
          case 'x':
            calculation = _numberTyped[0] * _numberTyped[1];
            break;
          case '÷':
            calculation = _numberTyped[0] / _numberTyped[1];
            break;
          default:
        }

        _displayFormulae.push({
          literal: '' + _numberTyped[0].toString() + ' ' +
            _signKeyTyped + ' ' +  _numberTyped[1].toString(),
          sign: _signKeyTyped
        });
        _displayScreen = calculation;
        _numberTyped = [calculation];
      }
    }
  } else {
    // avoid multiple '.' character
    if(key === '.') {
      if(~_numericKeyTyped.indexOf('.')) {
        return;
      } else {
        // if no '.' is found then we push first a '0'
        _numericKeyTyped.push('0');
      }
    }
    if(key === '0') {
      // if there no other character, '0's can not accumulate
      if(!_numericKeyTyped.length) {
        return;
      }
    }
    _numericKeyTyped.push(key);
    _displayScreen = _numericKeyTyped;
  }
}

CalculatorStore.dispatchToken = AppDispatcher.register(function(action) {

  switch(action.type) {
    case CalculatorConstants.KEY_TYPED:
      var key = action.key;
      if (key !== '') {
        processKey(key);
        CalculatorStore.emitChange();
      }
      break;
    default:
      // no op
  }
});

module.exports = CalculatorStore;
<|endoftext|>


<commit_before>import Storage from '../../utils/Storage';
import { dissoc } from 'ramda';

const SERVERS_STORAGE_KEY = 'servers';

export class ServersService {
  constructor(storage) {
    this.storage = storage;
  }

  listServers = () => {
    return this.storage.get(SERVERS_STORAGE_KEY) || [];
  };

  findServerById = serverId => {
    const servers = this.listServers();
    return servers[serverId];
  };

  createServer = server => {
    const servers = this.listServers();
    servers[server.id] = server;
    this.storage.set(SERVERS_STORAGE_KEY, servers);
  };

  deleteServer = server => {
    const servers = dissoc(server.id, this.listServers());
    this.storage.set(SERVERS_STORAGE_KEY, servers);
  };
}

export default new ServersService(Storage);
<commit_msg>Fixed default servers object value<commit_after>import Storage from '../../utils/Storage';
import { dissoc } from 'ramda';

const SERVERS_STORAGE_KEY = 'servers';

export class ServersService {
  constructor(storage) {
    this.storage = storage;
  }

  listServers = () => {
    return this.storage.get(SERVERS_STORAGE_KEY) || {};
  };

  findServerById = serverId => {
    const servers = this.listServers();
    return servers[serverId];
  };

  createServer = server => {
    const servers = this.listServers();
    servers[server.id] = server;
    this.storage.set(SERVERS_STORAGE_KEY, servers);
  };

  deleteServer = server => {
    const servers = dissoc(server.id, this.listServers());
    this.storage.set(SERVERS_STORAGE_KEY, servers);
  };
}

export default new ServersService(Storage);
<|endoftext|>


<commit_before>require('colors');
var cli = require('optimist'),
    p = require('path'),
    u = require('util'),
    fs = require('fs'),
    exec = require('child_process').exec,
    Seq = require('seq'),
    read = require('read');

var available = require(p.join(process.mainModule.paths[0],'..','..','package.json')).ngn;

// Basic CLI
var argv = cli
		  .usage('Usage: ngn remove <module or group>')
		  .argv,
		mod = argv._.filter(function(value){return value !== 'remove'})[0];

// Global Package Installer
var uninstall = function(ngnpkg){
  exec('npm uninstall -g '+ngnpkg+' --json --loglevel=silent',function(err,stdout,stderr){
    if (stdout.toString().trim().length == 0){
      console.log((ngnpkg+' support not found/installed. Skipped.').yellow);
      return;
    }
    try {
      var out = stdout.toString().trim().replace(/unbuild/gi,'').replace(/\s/,'').split('@');
      console.log(((out[0]||'Unknown').toString()+' support removed --> '+' v'+(out[1]||'?').toString()).red.bold);
    } catch (e) {
      console.log('Module removed, but there were errors:'.yellow.bold);
      console.log(e.message.toString().yellow);
    }
  });
};

// Check first for a module or group and install/warn accordingly
if (available.modules[mod] !== undefined){
  uninstall(mod);
} else if (available.groups[mod] !== undefined){
  available.groups[mod].forEach(function(m){
    uninstall(m);
  });
} else if (['all','*'].indexOf(mod.toString().trim().toLowerCase()) >= 0){
  console.log(('Removing every add-on ('+Object.keys(available.modules).length.toString()+' total). This may take a few moments.').cyan.bold);
  for (var m in available.modules){
    uninstall(m);
  };
} else {
  throw 'No module or group called \"'+mod+'\" is available.';
}
<commit_msg>Added user permission check for remove functionality. Addresses part of issue #36.<commit_after>require('colors');
var cli = require('optimist'),
    p = require('path'),
    fs = require('fs'),
    exec = require('child_process').exec;

var available = require(p.join(process.mainModule.paths[0],'..','..','package.json')).ngn;

var rmDir = function(path) {
  var files = [];
  if( fs.existsSync(path) ) {
    files = fs.readdirSync(path);
    files.forEach(function(file,index){
      var curPath = path + "/" + file;
      if(fs.statSync(curPath).isDirectory()) { // recurse
        rmDir(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
};

// Basic CLI
var argv = cli
    .usage('Usage: ngn remove <module or group>')
    .argv,
  mod = argv._.filter(function(value){return value !== 'remove'})[0];

// Global Package Installer
var uninstall = function(ngnpkg){
  var path = p.join(__dirname,'..','..','..',ngnpkg);
  if (fs.existsSync(path)){
    var v = require(p.join(path,'package.json')).version;
    try {
      rmDir(path);
      console.log((ngnpkg+' support removed --> '+' v'+v).red.bold);
    } catch (e) {
      if (e.message.toString().toLowerCase().indexOf('permission') >= 0){
        console.log('You have insufficient permission to remove modules.'.red.bold);
        if (require('os').platform() == 'win32'){
          console.log('\nPlease run this command with an admin account.'.yellow.bold);
        } else {
          console.log('\nPlease run this command as root (or sudo).'.yellow.bold);
        }
      }
    }
  } else {
    console.log((ngnpkg+' support not found/installed. Skipped.').yellow);
  }
  /*exec('npm uninstall -g '+ngnpkg+' --json --loglevel=silent',function(err,stdout,stderr){
    if (stdout.toString().trim().length == 0){
      console.log((ngnpkg+' support not found/installed. Skipped.').yellow);
      return;
    }
    try {
      var out = stdout.toString().trim().replace(/unbuild/gi,'').replace(/\s/,'').split('@');
      console.log(((out[0]||'Unknown').toString()+' support removed --> '+' v'+(out[1]||'?').toString()).red.bold);
    } catch (e) {
      console.log('Module removed, but there were errors:'.yellow.bold);
      console.log(e.message.toString().yellow);
    }
  });*/
};

// Check first for a module or group and install/warn accordingly
if (available.modules[mod] !== undefined){
  uninstall(mod);
} else if (available.groups[mod] !== undefined){
  available.groups[mod].forEach(function(m){
    uninstall(m);
  });
} else if (['all','*'].indexOf(mod.toString().trim().toLowerCase()) >= 0){
  console.log(('Removing every add-on ('+Object.keys(available.modules).length.toString()+' total). This may take a few moments.').cyan.bold);
  for (var m in available.modules){
    uninstall(m);
  };
} else {
  throw 'No module or group called \"'+mod+'\" is available.';
}
<|endoftext|>


<commit_before>var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('./key.pem', 'utf8');
var certificate = fs.readFileSync('./cert.pem', 'utf8');
var path = require('path');

var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

app.set('port', (process.env.PORT || 8080));

app.use(function(request, response, next) {
  if (path.extname(request.path).length > 0) {
    next();
  } else {
    request.url = '/index.html';
    next();
  }
});

app.use(express.static(__dirname + '/dist'))
  .get('/', function (req, res) {
    res.sendFile('index.html', {
      root: __dirname + '/dist'
    });
});

var httpsServer = https.createServer(credentials, app);

httpsServer.listen(app.get('port'), function() {
  console.log('Listening on port', app.get('port'));
});
<commit_msg>come on heroku<commit_after>var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('./key.pem', 'utf8');
var certificate = fs.readFileSync('./cert.pem', 'utf8');
var path = require('path');

var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

app.set('port', (process.env.PORT || 8080));

app.use(function(request, response, next) {
  if (path.extname(request.path).length > 0) {
    next();
  } else {
    request.url = '/index.html';
    next();
  }
});

app.use(express.static(__dirname + '/dist'))
  .get('/', function (req, res) {
    res.sendFile('index.html', {
      root: __dirname + '/dist'
    });
}).get('/silent_renew.html', {
    res.sendFile('silent_renew.html', {
      root: __dirname + '/dist'
    });
});

var httpsServer = https.createServer(credentials, app);

httpsServer.listen(app.get('port'), function() {
  console.log('Listening on port', app.get('port'));
});
<|endoftext|>


<commit_before>var toString = require('../lang/toString')
var slugify = require('./case-slugify')
var unCamelCase = require('./case-uncamelize')

// Replaces spaces with underscores, split camelCase text, remove non-word chars,
// remove accents and convert to lower case.

function underscore (str) {
  str = toString(str)
  str = unCamelCase(str)
  return slugify(str, '_')
}

module.exports = underscore
<commit_msg>update string/case-underscore adjust dependencies<commit_after>var stringify  = require('./stringify')
var slugify    = require('./case-slugify')
var uncamelize = require('./case-uncamelize')

// Replaces spaces with underscores, split camelCase text, remove non-word chars,
// remove accents and convert to lower case.

function underscore (str) {
  return slugify(uncamelize(stringify(str)), '_')
}

module.exports = underscore
<|endoftext|>