<commit_before>class Cli {
  constructor (JiraApi, TableRenderer, Logger) {
    this.api = JiraApi
    this.tableRenderer = TableRenderer
    this.logger = Logger
  }

  renderIssue (issue) {
    return this.api
      .getIssue((issue))
      .then((issue) => {
        this.tableRenderer.renderTitle('Issue detail summary')
        this.tableRenderer.renderVertical([
          {'Key': issue.key},
          {'Issue Type': issue.type},
          {'Summary': issue.summary},
          {'Status': issue.status},
          {'Project': issue.projectName + ' (' + issue.projectKey + ')'}
        ])
      })
      .catch((error) => {
        this.logger.error(error.toString())
      })
  }

  renderIssues (options) {
    return this.api
      .getIssues(options)
      .then((issues) => {
        let head = ['Issue key', 'Status', 'Summary', 'Project key']
        let rows = []
        issues.map((issue) => {
          rows.push([
            issue.key,
            issue.status,
            issue.summary,
            issue.projectKey
          ])
        })
        this.tableRenderer.render(head, rows)
      })
      .catch((error) => {
        this.logger.error(error.toString())
      })
  }

  renderTransitions (options) {
    return this.api
      .getTransitions(options.key)
      .then((transitions) => {
        let head = ['Id', 'Name']
        let rows = []
        transitions.map((transition) => {
          rows.push([
            transition.id,
            transition.name
          ])
        })
        this.tableRenderer.render(head, rows)
      })
      .catch((error) => {
        this.logger.error(error.toString())
      })
  }

  transitionIssue (issue, status) {
    return this.api
      .transitionIssue(issue, status)
      .then((response) => {
        this.logger.success('Issue ' + issue + ' transitioned to ' + status + ' status')
      })
      .catch((error) => {
        this.logger.error(error.toString())
      })
  }

  addComment (issue, comment) {
    return this.api
      .addComment(issue, comment)
      .then((response) => {
        this.logger.success('Comment added to issue ' + issue)
      })
      .catch((error) => {
        this.logger.error(error.toString())
      })
  }

  addWorklog (issue, timeSpent, comment) {
    return this.api
      .addWorklog(issue, timeSpent, comment)
      .then((response) => {
        this.logger.success('Worklog ' + timeSpent + ' added to issue ' + issue)
      })
      .catch((error) => {
        this.logger.error(error.toString())
      })
  }

  renderIssueWorklogs (issue) {
    return this.api
      .getIssueWorklogs(issue)
      .then((worklogs) => {
        let head = ['Worklog Id', 'Timespent', 'Comment', 'Author', 'Created']
        let rows = []
        worklogs.map((worklog) => {
          rows.push([
            worklog.id,
            worklog.timeSpent,
            worklog.comment,
            worklog.author,
            worklog.created.split('T')[0]
          ])
        })
        this.tableRenderer.render(head, rows)
      })
      .catch((error) => {
        this.logger.error(error.message)
      })
  }
}

module.exports = (JiraApi, TableRenderer, Logger) => (new Cli(JiraApi, TableRenderer, Logger))
<commit_msg>Remove un necessary variables<commit_after>class Cli {
  constructor (JiraApi, TableRenderer, Logger) {
    this.api = JiraApi
    this.tableRenderer = TableRenderer
    this.logger = Logger
  }

  renderIssue (issue) {
    return this.api
      .getIssue((issue))
      .then((issue) => {
        this.tableRenderer.renderTitle('Issue detail summary')
        this.tableRenderer.renderVertical([
          {'Key': issue.key},
          {'Issue Type': issue.type},
          {'Summary': issue.summary},
          {'Status': issue.status},
          {'Project': issue.projectName + ' (' + issue.projectKey + ')'}
        ])
      })
      .catch((error) => {
        this.logger.error(error.toString())
      })
  }

  renderIssues (options) {
    return this.api
      .getIssues(options)
      .then((issues) => {
        this.tableRenderer.render(
          ['Issue key', 'Status', 'Summary', 'Project key'],
          issues.map((issue) => {
            return [issue.key, issue.status, issue.summary, issue.projectKey]
          })
        )
      })
      .catch((error) => {
        this.logger.error(error.toString())
      })
  }

  renderTransitions (options) {
    return this.api
      .getTransitions(options.key)
      .then((transitions) => {
        this.tableRenderer.render(
          ['Id', 'Name'],
          transitions.map((transition) => {
            return [transition.id, transition.name]
          })
        )
      })
      .catch((error) => {
        this.logger.error(error.toString())
      })
  }

  transitionIssue (issue, status) {
    return this.api
      .transitionIssue(issue, status)
      .then((response) => {
        this.logger.success('Issue ' + issue + ' transitioned to ' + status + ' status')
      })
      .catch((error) => {
        this.logger.error(error.toString())
      })
  }

  addComment (issue, comment) {
    return this.api
      .addComment(issue, comment)
      .then((response) => {
        this.logger.success('Comment added to issue ' + issue)
      })
      .catch((error) => {
        this.logger.error(error.toString())
      })
  }

  addWorklog (issue, timeSpent, comment) {
    return this.api
      .addWorklog(issue, timeSpent, comment)
      .then((response) => {
        this.logger.success('Worklog ' + timeSpent + ' added to issue ' + issue)
      })
      .catch((error) => {
        this.logger.error(error.toString())
      })
  }

  renderIssueWorklogs (issue) {
    return this.api
      .getIssueWorklogs(issue)
      .then((worklogs) => {
        this.tableRenderer.render(
          ['Worklog Id', 'Timespent', 'Comment', 'Author', 'Created'],
          worklogs.map((worklog) => {
            return [
              worklog.id,
              worklog.timeSpent,
              worklog.comment,
              worklog.author,
              worklog.created.split('T')[0]
            ]
          })
        )
      })
      .catch((error) => {
        this.logger.error(error.message)
      })
  }
}

module.exports = (JiraApi, TableRenderer, Logger) => (new Cli(JiraApi, TableRenderer, Logger))
<|endoftext|>


<commit_before><commit_msg>Delete jquery-1.11.0.min.js<commit_after><|endoftext|>


<commit_before>describe("Scene", function(){
    var core, scene;

    beforeEach(function(){
        enchant();
        core = new Core();
        scene = new Scene();
    });

    afterEach(function(){
        core = null;
    });

    describe("#initialize", function(){
        it("makes div tag with styles which posesses its layer", function(){
            expect(scene._element.tagName).to.equal("DIV");
            expect(scene._element.style.position).to.equal("absolute");
            expect(scene._element.style.overflow).to.equal("hidden");
        });

        it("sets event listeners to itself", function(){
            expect(scene._listeners[enchant.Event.CHILD_ADDED][0]).to.equal(scene._onchildadded);
            expect(scene._listeners[enchant.Event.CHILD_REMOVED][0]).to.equal(scene._onchildremoved);
            expect(scene._listeners[enchant.Event.ENTER][0]).to.equal(scene._onenter);
            expect(scene._listeners[enchant.Event.EXIT][0]).to.equal(scene._onexit);
            expect(scene._listeners[enchant.Event.CORE_RESIZE][0]).to.equal(scene._oncoreresize);
        });
    });

    describe("with no layer", function(){
        it("can be set x position", function(){
            expect(scene.x).to.be.zero;
            expect(scene._x, "borrow from enchant.Node").to.be.zero;
            scene.x = 10;
            expect(scene.x).to.equal(10);
            expect(scene._x).to.equal(10);
        });

        it("can be set y position", function(){
            expect(scene.y).to.be.zero;
            expect(scene._y, "borrow from enchant.Node").to.be.zero;
            scene.y = 10;
            expect(scene.y).to.equal(10);
            expect(scene._y).to.equal(10);
        });

        it("can be set width", function(){
            expect(scene.width, "sets on _oncoreresize").to.equal(320);
            expect(scene._width).to.equal(320);
            scene.width = 640;
            expect(scene.width).to.equal(640);
            expect(scene._width).to.equal(640);
        });

        it("can be set height", function(){
            expect(scene.height, "sets on _oncoreresize").to.equal(320);
            expect(scene._height).to.equal(320);
            scene.height = 640;
            expect(scene.height).to.be.equal(640);
            expect(scene._height).to.be.equal(640);
        });

        it("can be set its rotation", function(){
            expect(scene.rotation, "borrow from enchant.Group").to.be.zero;
            expect(scene._rotation).to.be.zero;
            scene.rotation = 60;
            expect(scene.rotation).to.equal(60);
            expect(scene._rotation).to.equal(60);
        });

        it("can be set scaleX", function(){
            expect(scene.scaleX, "borrow from enchant.Group").to.equal(1);
            expect(scene._scaleX).to.equal(1);
            scene.scaleX = 10;
            expect(scene.scaleX).to.equal(10);
            expect(scene._scaleX).to.equal(10);
        });

        it("can be set scaleY", function(){
            expect(scene.scaleY, "borrow from enchant.Group").to.equal(1);
            expect(scene._scaleY).to.equal(1);
            scene.scaleY = 10;
            expect(scene.scaleY).to.equal(10);
            expect(scene._scaleY).to.equal(10);
        });

        it("resizes its width and height when coreresize event occurred", function(){
            core.pushScene(scene);
            expect(scene.width, "borrow from core").to.equal(320);
            expect(scene.height, "borrow from core").to.equal(320);
            core.width = 400; // coreresize event occurrs
            expect(scene.width).to.equal(400);
            expect(scene.height).to.equal(320);
            core.height = 500; // coreresize event occurrs
            expect(scene.width).to.equal(400);
            expect(scene.height).to.equal(500);
        });
    });

    it("can be set background color", function(){
        expect(scene.backgroundColor).to.be.null;
        expect(scene._backgroundColor).to.be.null;
        scene.backgroundColor = "#f00";
        expect(scene.backgroundColor).to.equal("#f00");
        expect(scene._backgroundColor).to.equal("#f00");
        expect(scene._element.style.backgroundColor).to.equal("rgb(255, 0, 0)");
    });

    describe("adding layers", function(){
        it("can be add DomLyer or CanvasLayer or both", function(){
            expect(Object.keys(scene._layers).length).to.be.zero;
            scene.addLayer("Canvas");
            expect(Object.keys(scene._layers).length).to.equal(1);
            expect(scene._layers["Canvas"]).to.exist;
            expect(scene._element.lastChild.tagName).to.equal("CANVAS");
            expect(scene._layerPriority[0]).to.equal("Canvas");
            scene.addLayer("Dom");
            expect(Object.keys(scene._layers).length).to.equal(2);
            expect(scene._layers["Dom"]).to.exist;
            expect(scene._element.lastChild.tagName).to.equal("DIV");
            expect(scene._layerPriority[0]).to.equal("Canvas");
            expect(scene._layerPriority[1]).to.equal("Dom");
            scene = null;
            scene = new Scene();
            expect(Object.keys(scene._layers).length).to.be.zero;
            scene.addLayer("Dom");
            expect(Object.keys(scene._layers).length).to.equal(1);
            expect(scene._layers["Dom"]).to.exist;
            expect(scene._element.lastChild.tagName).to.equal("DIV");
            expect(scene._layerPriority[0]).to.equal("Dom");
            scene.addLayer("Canvas");
            expect(scene._element.lastChild.tagName).to.equal("CANVAS");
            expect(scene._layerPriority[0]).to.equal("Dom");
            expect(scene._layerPriority[1]).to.equal("Canvas");
        });

        it("can not be add same type of layer", function(){
            scene.addLayer("Canvas");
            expect(Object.keys(scene._layers).length).to.equal(1);
            expect(scene._element.childNodes.length).to.equal(1);
            expect(scene._layerPriority.length).to.equal(1);
            scene.addLayer("Canvas");
            expect(Object.keys(scene._layers).length).to.equal(1);
            expect(scene._element.childNodes.length).to.equal(1);
            expect(scene._layerPriority.length).to.equal(1);
            scene = null;
            scene = new Scene();
            scene.addLayer("Dom");
            expect(Object.keys(scene._layers).length).to.equal(1);
            expect(scene._element.childNodes.length).to.equal(1);
            expect(scene._layerPriority.length).to.equal(1);
            scene.addLayer("Dom");
            expect(Object.keys(scene._layers).length).to.equal(1);
            expect(scene._element.childNodes.length).to.equal(1);
            expect(scene._layerPriority.length).to.equal(1);
        });

        it("can be set layer priority when adding layer", function(){
            scene.addLayer("Canvas");
            expect(scene._element.childNodes.length).to.equal(1);
            expect(scene._element.childNodes[0].tagName).to.equal("CANVAS");
            expect(scene._layerPriority[0]).to.equal("Canvas");
            scene.addLayer("Dom", 0);
            expect(scene._element.childNodes.length).to.equal(2);
            expect(scene._element.childNodes[0].tagName).to.equal("DIV");
            expect(scene._element.childNodes[1].tagName).to.equal("CANVAS");
            expect(scene._layerPriority[0]).to.equal("Dom");
            expect(scene._layerPriority[1]).to.equal("Canvas");
        });
    });

    describe("with layer", function(){
        beforeEach(function(){
            scene.addLayer("Dom");
            scene.addLayer("Canvas");
        });

        it("can be set x position and it affects to all layers", function(){
            expect(scene.x).to.be.zero;
            expect(scene._layers["Dom"].x).to.be.zero;
            expect(scene._layers["Canvas"].x).to.be.zero;
            scene.x = 10;
            expect(scene.x).to.equal(10);
            expect(scene._layers["Dom"].x).to.equal(10);
            expect(scene._layers["Canvas"].x).to.equal(10);
        });

        it("can be set y position and it affects to all layers", function(){
            expect(scene.y).to.be.zero;
            expect(scene._layers["Dom"].y).to.be.zero;
            expect(scene._layers["Canvas"].y).to.be.zero;
            scene.y = 10;
            expect(scene.y).to.equal(10);
            expect(scene._layers["Dom"].y).to.equal(10);
            expect(scene._layers["Canvas"].y).to.equal(10);
        });

        it("can be set width and it affects to all layers", function(){
            expect(scene.width).to.equal(320);
            expect(scene._layers["Dom"].width).to.equal(320);
            expect(scene._layers["Canvas"].width).to.equal(320);
            scene.width = 640;
            expect(scene.width).to.equal(640);
            expect(scene._layers["Dom"].width).to.equal(640);
            expect(scene._layers["Canvas"].width).to.equal(640);
        });

        it("can be set height and it affects to all layers", function(){
            expect(scene.height).to.equal(320);
            expect(scene._layers["Dom"].height).to.equal(320);
            expect(scene._layers["Canvas"].height).to.equal(320);
            scene.height = 640;
            expect(scene.height).to.be.equal(640);
            expect(scene._layers["Dom"].height).to.equal(640);
            expect(scene._layers["Canvas"].height).to.equal(640);
        });

        it("can be set its rotation and it affects to all layers", function(){
            expect(scene.rotation).to.be.zero;
            expect(scene._layers["Dom"].rotation).to.be.zero;
            expect(scene._layers["Canvas"].rotation).to.be.zero;
            scene.rotation = 60;
            expect(scene.rotation).to.equal(60);
            expect(scene._layers["Dom"].rotation).to.equal(60);
            expect(scene._layers["Canvas"].rotation).to.equal(60);
        });

        it("can be set scaleX and it affects to all layers", function(){
            expect(scene.scaleX).to.equal(1);
            expect(scene._layers["Dom"].scaleX).to.equal(1);
            expect(scene._layers["Canvas"].scaleX).to.equal(1);
            scene.scaleX = 10;
            expect(scene.scaleX).to.equal(10);
            expect(scene._layers["Dom"].scaleX).to.equal(10);
            expect(scene._layers["Canvas"].scaleX).to.equal(10);
        });

        it("can be set scaleY it affects to all layers", function(){
            expect(scene.scaleY).to.equal(1);
            expect(scene._layers["Dom"].scaleY).to.equal(1);
            expect(scene._layers["Canvas"].scaleY).to.equal(1);
            scene.scaleY = 10;
            expect(scene.scaleY).to.equal(10);
            expect(scene._layers["Dom"].scaleY).to.equal(10);
            expect(scene._layers["Canvas"].scaleY).to.equal(10);
        });

        it("all layers dispatches coreresize event when coreresize event occurred", function(){
            core.pushScene(scene);
            var callback1 = sinon.spy(),
                callback2 = sinon.spy();
            scene._layers["Dom"].addEventListener(enchant.Event.CORE_RESIZE, callback1);
            scene._layers["Canvas"].addEventListener(enchant.Event.CORE_RESIZE, callback2);
            expect(callback1.called).to.be.false;
            expect(callback2.called).to.be.false;
            core.width = 400; // coreresize event occurrs
            expect(callback1.callCount).to.equal(1);
            expect(callback2.callCount).to.equal(1);
        });

        it("#_determineEventTarget returns target layer", function(){
            var target = scene._determineEventTarget(new enchant.Event("touchstart"));
            expect(target).to.equal(scene);
            var spriteOnCanvas = new Sprite();
            var stubCanvas = sinon.stub(scene._layers["Canvas"], "_determineEventTarget");
            stubCanvas.returns(spriteOnCanvas);
            target = scene._determineEventTarget(new enchant.Event("touchstart"));
            expect(target).to.equal(spriteOnCanvas);
            expect(stubCanvas.callCount).to.equal(1);
            var spriteOnDom = new Sprite();
            var stubDom = sinon.stub(scene._layers["Dom"], "_determineEventTarget");
            stubDom.returns(spriteOnDom);
            target = scene._determineEventTarget(new enchant.Event("touchstart"));
            expect(target).to.equal(spriteOnCanvas);
            expect(stubCanvas.callCount).to.equal(2);
            expect(stubDom.callCount).to.equal(0);
        });

        it("adds layer to child when childadded event occurred", function(){
            core.pushScene(scene);
            var sprite = new Sprite();
            var callback = sinon.spy();
            scene.addEventListener(enchant.Event.CHILD_ADDED, callback);
            scene.addChild(sprite);
            expect(callback.called).to.be.true;
            expect(sprite.parentNode).to.equal(scene);
            expect(scene._layers["Canvas"].lastChild).to.deep.equal(sprite);

        });

        it("removes child layer when childremoved event occurred", function(){
            core.pushScene(scene);
            var sprite = new Sprite();
            scene.addChild(sprite);
            expect(scene._layers["Canvas"].lastChild).to.equal(sprite);
            scene.removeChild(sprite);
            expect(scene._layers["Canvas"].lastChild).to.not.equal(sprite);
        });

        it("starts rendering when the scene started", function(){
            var stub = sinon.stub(scene._layers["Canvas"], "_startRendering");
            expect(stub.called).to.be.false;
            scene.dispatchEvent(new enchant.Event("enter"));
            expect(stub.called).to.be.true;
        });

        it("stops rendering when the scene stops", function(){
            var stub = sinon.stub(scene._layers["Canvas"], "_stopRendering");
            expect(stub.called).to.be.false;
            scene.dispatchEvent(new enchant.Event("exit"));
            expect(stub.called).to.be.true;
        });
    });
});
<commit_msg>add Scene test!<commit_after>describe("Scene", function(){
    var core, scene;

    beforeEach(function(){
        enchant();
        core = new Core();
        scene = new Scene();
    });

    afterEach(function(){
        core = null;
    });

    describe("#initialize", function(){
        it("makes div tag with styles which posesses its layer", function(){
            expect(scene._element.tagName).to.equal("DIV");
            expect(scene._element.style.position).to.equal("absolute");
            expect(scene._element.style.overflow).to.equal("hidden");
        });

        it("sets event listeners to itself", function(){
            expect(scene._listeners[enchant.Event.CHILD_ADDED][0]).to.equal(scene._onchildadded);
            expect(scene._listeners[enchant.Event.CHILD_REMOVED][0]).to.equal(scene._onchildremoved);
            expect(scene._listeners[enchant.Event.ENTER][0]).to.equal(scene._onenter);
            expect(scene._listeners[enchant.Event.EXIT][0]).to.equal(scene._onexit);
            expect(scene._listeners[enchant.Event.CORE_RESIZE][0]).to.equal(scene._oncoreresize);
        });
    });

    describe("with no layer", function(){
        it("can be set x position", function(){
            expect(scene.x).to.be.zero;
            expect(scene._x, "borrow from enchant.Node").to.be.zero;
            scene.x = 10;
            expect(scene.x).to.equal(10);
            expect(scene._x).to.equal(10);
        });

        it("can be set y position", function(){
            expect(scene.y).to.be.zero;
            expect(scene._y, "borrow from enchant.Node").to.be.zero;
            scene.y = 10;
            expect(scene.y).to.equal(10);
            expect(scene._y).to.equal(10);
        });

        it("can be set width", function(){
            expect(scene.width, "sets on _oncoreresize").to.equal(320);
            expect(scene._width).to.equal(320);
            scene.width = 640;
            expect(scene.width).to.equal(640);
            expect(scene._width).to.equal(640);
        });

        it("can be set height", function(){
            expect(scene.height, "sets on _oncoreresize").to.equal(320);
            expect(scene._height).to.equal(320);
            scene.height = 640;
            expect(scene.height).to.be.equal(640);
            expect(scene._height).to.be.equal(640);
        });

        it("can be set its rotation", function(){
            expect(scene.rotation, "borrow from enchant.Group").to.be.zero;
            expect(scene._rotation).to.be.zero;
            scene.rotation = 60;
            expect(scene.rotation).to.equal(60);
            expect(scene._rotation).to.equal(60);
        });

        it("can be set scaleX", function(){
            expect(scene.scaleX, "borrow from enchant.Group").to.equal(1);
            expect(scene._scaleX).to.equal(1);
            scene.scaleX = 10;
            expect(scene.scaleX).to.equal(10);
            expect(scene._scaleX).to.equal(10);
        });

        it("can be set scaleY", function(){
            expect(scene.scaleY, "borrow from enchant.Group").to.equal(1);
            expect(scene._scaleY).to.equal(1);
            scene.scaleY = 10;
            expect(scene.scaleY).to.equal(10);
            expect(scene._scaleY).to.equal(10);
        });

        it("resizes its width and height when coreresize event occurred", function(){
            core.pushScene(scene);
            expect(scene.width, "borrow from core").to.equal(320);
            expect(scene.height, "borrow from core").to.equal(320);
            core.width = 400; // coreresize event occurrs
            expect(scene.width).to.equal(400);
            expect(scene.height).to.equal(320);
            core.height = 500; // coreresize event occurrs
            expect(scene.width).to.equal(400);
            expect(scene.height).to.equal(500);
        });
    });

    it("can be set background color", function(){
        expect(scene.backgroundColor).to.be.null;
        expect(scene._backgroundColor).to.be.null;
        scene.backgroundColor = "#f00";
        expect(scene.backgroundColor).to.equal("#f00");
        expect(scene._backgroundColor).to.equal("#f00");
        expect(scene._element.style.backgroundColor).to.equal("rgb(255, 0, 0)");
    });

    describe("adding layers", function(){
        it("can be add DomLyer or CanvasLayer or both", function(){
            expect(Object.keys(scene._layers).length).to.be.zero;
            scene.addLayer("Canvas");
            expect(Object.keys(scene._layers).length).to.equal(1);
            expect(scene._layers["Canvas"]).to.exist;
            expect(scene._element.lastChild.tagName).to.equal("CANVAS");
            expect(scene._layerPriority[0]).to.equal("Canvas");
            scene.addLayer("Dom");
            expect(Object.keys(scene._layers).length).to.equal(2);
            expect(scene._layers["Dom"]).to.exist;
            expect(scene._element.lastChild.tagName).to.equal("DIV");
            expect(scene._layerPriority[0]).to.equal("Canvas");
            expect(scene._layerPriority[1]).to.equal("Dom");
            scene = null;
            scene = new Scene();
            expect(Object.keys(scene._layers).length).to.be.zero;
            scene.addLayer("Dom");
            expect(Object.keys(scene._layers).length).to.equal(1);
            expect(scene._layers["Dom"]).to.exist;
            expect(scene._element.lastChild.tagName).to.equal("DIV");
            expect(scene._layerPriority[0]).to.equal("Dom");
            scene.addLayer("Canvas");
            expect(scene._element.lastChild.tagName).to.equal("CANVAS");
            expect(scene._layerPriority[0]).to.equal("Dom");
            expect(scene._layerPriority[1]).to.equal("Canvas");
        });

        it("can not be add same type of layer", function(){
            scene.addLayer("Canvas");
            expect(Object.keys(scene._layers).length).to.equal(1);
            expect(scene._element.childNodes.length).to.equal(1);
            expect(scene._layerPriority.length).to.equal(1);
            scene.addLayer("Canvas");
            expect(Object.keys(scene._layers).length).to.equal(1);
            expect(scene._element.childNodes.length).to.equal(1);
            expect(scene._layerPriority.length).to.equal(1);
            scene = null;
            scene = new Scene();
            scene.addLayer("Dom");
            expect(Object.keys(scene._layers).length).to.equal(1);
            expect(scene._element.childNodes.length).to.equal(1);
            expect(scene._layerPriority.length).to.equal(1);
            scene.addLayer("Dom");
            expect(Object.keys(scene._layers).length).to.equal(1);
            expect(scene._element.childNodes.length).to.equal(1);
            expect(scene._layerPriority.length).to.equal(1);
        });

        it("can be set layer priority when adding layer", function(){
            scene.addLayer("Canvas");
            expect(scene._element.childNodes.length).to.equal(1);
            expect(scene._element.childNodes[0].tagName).to.equal("CANVAS");
            expect(scene._layerPriority[0]).to.equal("Canvas");
            scene.addLayer("Dom", 0);
            expect(scene._element.childNodes.length).to.equal(2);
            expect(scene._element.childNodes[0].tagName).to.equal("DIV");
            expect(scene._element.childNodes[1].tagName).to.equal("CANVAS");
            expect(scene._layerPriority[0]).to.equal("Dom");
            expect(scene._layerPriority[1]).to.equal("Canvas");
        });
    });

    describe("with layer", function(){
        beforeEach(function(){
            scene.addLayer("Dom");
            scene.addLayer("Canvas");
        });

        it("can be set x position and it affects to all layers", function(){
            expect(scene.x).to.be.zero;
            expect(scene._layers["Dom"].x).to.be.zero;
            expect(scene._layers["Canvas"].x).to.be.zero;
            scene.x = 10;
            expect(scene.x).to.equal(10);
            expect(scene._layers["Dom"].x).to.equal(10);
            expect(scene._layers["Canvas"].x).to.equal(10);
        });

        it("can be set y position and it affects to all layers", function(){
            expect(scene.y).to.be.zero;
            expect(scene._layers["Dom"].y).to.be.zero;
            expect(scene._layers["Canvas"].y).to.be.zero;
            scene.y = 10;
            expect(scene.y).to.equal(10);
            expect(scene._layers["Dom"].y).to.equal(10);
            expect(scene._layers["Canvas"].y).to.equal(10);
        });

        it("can be set width and it affects to all layers", function(){
            expect(scene.width).to.equal(320);
            expect(scene._layers["Dom"].width).to.equal(320);
            expect(scene._layers["Canvas"].width).to.equal(320);
            scene.width = 640;
            expect(scene.width).to.equal(640);
            expect(scene._layers["Dom"].width).to.equal(640);
            expect(scene._layers["Canvas"].width).to.equal(640);
        });

        it("can be set height and it affects to all layers", function(){
            expect(scene.height).to.equal(320);
            expect(scene._layers["Dom"].height).to.equal(320);
            expect(scene._layers["Canvas"].height).to.equal(320);
            scene.height = 640;
            expect(scene.height).to.be.equal(640);
            expect(scene._layers["Dom"].height).to.equal(640);
            expect(scene._layers["Canvas"].height).to.equal(640);
        });

        it("can be set its rotation and it affects to all layers", function(){
            expect(scene.rotation).to.be.zero;
            expect(scene._layers["Dom"].rotation).to.be.zero;
            expect(scene._layers["Canvas"].rotation).to.be.zero;
            scene.rotation = 60;
            expect(scene.rotation).to.equal(60);
            expect(scene._layers["Dom"].rotation).to.equal(60);
            expect(scene._layers["Canvas"].rotation).to.equal(60);
        });

        it("can be set scaleX and it affects to all layers", function(){
            expect(scene.scaleX).to.equal(1);
            expect(scene._layers["Dom"].scaleX).to.equal(1);
            expect(scene._layers["Canvas"].scaleX).to.equal(1);
            scene.scaleX = 10;
            expect(scene.scaleX).to.equal(10);
            expect(scene._layers["Dom"].scaleX).to.equal(10);
            expect(scene._layers["Canvas"].scaleX).to.equal(10);
        });

        it("can be set scaleY it affects to all layers", function(){
            expect(scene.scaleY).to.equal(1);
            expect(scene._layers["Dom"].scaleY).to.equal(1);
            expect(scene._layers["Canvas"].scaleY).to.equal(1);
            scene.scaleY = 10;
            expect(scene.scaleY).to.equal(10);
            expect(scene._layers["Dom"].scaleY).to.equal(10);
            expect(scene._layers["Canvas"].scaleY).to.equal(10);
        });

        it("all layers dispatches coreresize event when coreresize event occurred", function(){
            core.pushScene(scene);
            var callback1 = sinon.spy(),
                callback2 = sinon.spy();
            scene._layers["Dom"].addEventListener(enchant.Event.CORE_RESIZE, callback1);
            scene._layers["Canvas"].addEventListener(enchant.Event.CORE_RESIZE, callback2);
            expect(callback1.called).to.be.false;
            expect(callback2.called).to.be.false;
            core.width = 400; // coreresize event occurrs
            expect(callback1.callCount).to.equal(1);
            expect(callback2.callCount).to.equal(1);
        });

        it("#_determineEventTarget returns target layer", function(){
            var target = scene._determineEventTarget(new enchant.Event("touchstart"));
            expect(target).to.equal(scene);
            var spriteOnCanvas = new Sprite();
            var stubCanvas = sinon.stub(scene._layers["Canvas"], "_determineEventTarget");
            stubCanvas.returns(spriteOnCanvas);
            target = scene._determineEventTarget(new enchant.Event("touchstart"));
            expect(target).to.equal(spriteOnCanvas);
            expect(stubCanvas.callCount).to.equal(1);
            var spriteOnDom = new Sprite();
            var stubDom = sinon.stub(scene._layers["Dom"], "_determineEventTarget");
            stubDom.returns(spriteOnDom);
            target = scene._determineEventTarget(new enchant.Event("touchstart"));
            expect(target).to.equal(spriteOnCanvas);
            expect(stubCanvas.callCount).to.equal(2);
            expect(stubDom.callCount).to.equal(0);
        });

        it("adds layer to child when childadded event occurred", function(){
            core.pushScene(scene);
            var sprite = new Sprite();
            var callback = sinon.spy();
            scene.addEventListener(enchant.Event.CHILD_ADDED, callback);
            scene.addChild(sprite);
            expect(callback.called).to.be.true;
            expect(sprite.parentNode).to.equal(scene);
            expect(scene._layers["Canvas"].lastChild).to.deep.equal(sprite);

        });

        it("removes child layer when childremoved event occurred", function(){
            core.pushScene(scene);
            var sprite = new Sprite();
            scene.addChild(sprite);
            expect(scene._layers["Canvas"].lastChild).to.equal(sprite);
            scene.removeChild(sprite);
            expect(scene._layers["Canvas"].lastChild).to.not.equal(sprite);
        });

        it("starts rendering when the scene started", function(){
            var stub = sinon.stub(scene._layers["Canvas"], "_startRendering");
            expect(stub.called).to.be.false;
            scene.dispatchEvent(new enchant.Event("enter"));
            expect(stub.called).to.be.true;
        });

        it("stops rendering when the scene stops", function(){
            var stub = sinon.stub(scene._layers["Canvas"], "_stopRendering");
            expect(stub.called).to.be.false;
            scene.dispatchEvent(new enchant.Event("exit"));
            expect(stub.called).to.be.true;
        });
<<<<<<< HEAD
=======

>>>>>>> add Scene test!
    });
});
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

var request = require('request');
var dedupeArray = require('./utils').dedupeArray;

/**
 * Simple client to handle simple push notifications
 **/
var SimplePush = function(statsdClient, logError) {
  this.statsdClient = statsdClient;
  this.logError = logError;
}

SimplePush.prototype = {
  notify: function(reason, urls, version){
    if (!Array.isArray(urls)) {
      urls = [urls];
    }

    urls = dedupeArray(urls);

    var self = this;

    urls.forEach(function(simplePushUrl) {
      if (self.statsdClient !== undefined) {
        self.statsdClient.count("loop.simplepush.call", 1);
        self.statsdClient.count("loop.simplepush.call." + reason, 1);
      }
      request.put({
        url: simplePushUrl,
        form: { version: version }
      }, function(err) {
        if (self.statsdClient !== undefined) {
          if (err) {
            self.logError(err);
            self.statsdClient.count("loop.simplepush.call.failures", 1);
            self.statsdClient.count("loop.simplepush.call." + reason + ".failures", 1);
          } else {
            self.statsdClient.count("loop.simplepush.call.success", 1);
            self.statsdClient.count("loop.simplepush.call." + reason + ".success", 1);
          }
        }
      });
    });
  }
}

module.exports = SimplePush;
<commit_msg>Don't log anything if no logError is passed.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

var request = require('request');
var dedupeArray = require('./utils').dedupeArray;

/**
 * Simple client to handle simple push notifications
 **/
var SimplePush = function(statsdClient, logError) {
  this.statsdClient = statsdClient;
  this.logError = logError || function() {};
}

SimplePush.prototype = {
  notify: function(reason, urls, version){
    if (!Array.isArray(urls)) {
      urls = [urls];
    }

    urls = dedupeArray(urls);

    var self = this;

    urls.forEach(function(simplePushUrl) {
      if (self.statsdClient !== undefined) {
        self.statsdClient.count("loop.simplepush.call", 1);
        self.statsdClient.count("loop.simplepush.call." + reason, 1);
      }
      request.put({
        url: simplePushUrl,
        form: { version: version }
      }, function(err) {
        if (self.statsdClient !== undefined) {
          if (err) {
            self.logError(err);
            self.statsdClient.count("loop.simplepush.call.failures", 1);
            self.statsdClient.count("loop.simplepush.call." + reason + ".failures", 1);
          } else {
            self.statsdClient.count("loop.simplepush.call.success", 1);
            self.statsdClient.count("loop.simplepush.call." + reason + ".success", 1);
          }
        }
      });
    });
  }
}

module.exports = SimplePush;
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    main.consumes = [
        "Editor", "editors", "ui", "save", "test.coverage", "Datagrid",
        "layout", "settings", "tabManager", "commands", "Divider", "MenuItem",
        "console"
    ];
    main.provides = ["test.coverageview"];
    return main;

    function main(options, imports, register) {
        var ui = imports.ui;
        var save = imports.save;
        var Editor = imports.Editor;
        var Datagrid = imports.Datagrid;
        var editors = imports.editors;
        var layout = imports.layout;
        var Divider = imports.Divider;
        var MenuItem = imports.MenuItem;
        var tabManager = imports.tabManager;
        var settings = imports.settings;
        var console = imports.console;
        var commands = imports.commands;
        var coverage = imports["test.coverage"];

        /***** Initialization *****/

        var extensions = [];

        var handle = editors.register("coverageview", "Coverage View", CoverageView, extensions);

        handle.on("load", function(){
            commands.addCommand({
                name: "opencoverageview",
                // hint: "runs the selected test(s) in the test panel",
                // bindKey: { mac: "F6", win: "F6" },
                group: "Test",
                exec: function(editor, args){
                    var tab;
                    if (tabManager.getTabs().some(function(t){
                        if (t.editorType == "coverageview") {
                            tab = t;
                            return true;
                        }
                    })) {
                        tabManager.focusTab(tab);
                    }
                    else {
                        console.show();
                        tabManager.open({
                            editorType: "coverageview",
                            focus: true,
                            pane: console.getPanes()[0]
                        }, function(){});
                    }
                }
            }, handle);

            coverage.on("draw", function(){
                coverage.buttonMenu.append(new Divider());
                coverage.buttonMenu.append(new MenuItem({
                    caption: "Open Code Coverage View",
                    command: "opencoverageview"
                }));
            }, handle);
        });

        function CoverageView(){
            var plugin = new Editor("Ajax.org", main.consumes, extensions);
            var datagrid;

            var BGCOLOR = {
                "flat-light": "#f7f7f7",
                "light": "#D3D3D3",
                "light-gray": "#D3D3D3",
                "dark": "#3D3D3D",
                "dark-gray": "#3D3D3D"
            };

            plugin.on("draw", function(e) {
                datagrid = new Datagrid({
                    container: e.htmlNode,

                    columns : [
                        {
                            caption: "Hierarchy",
                            value: "label",
                            width: "60%",
                            type: "tree"
                        },
                        {
                            caption: "Covered (%)",
                            width: "20%",
                            getText: function(node){
                                return node.covered + "%";
                            }
                        },
                        {
                            caption: "Not Covered",
                            value: "uncovered",
                            width: "20%"
                        }
                    ]
                }, plugin);

                datagrid.on("afterChoose", function(){
                    tabManager.openFile("/" + datagrid.selectedNode.label, true, function(){});
                });

                coverage.on("update", function(){
                    update();
                }, plugin);

                e.htmlNode.style.padding = 0;

                update();
            });

            /***** Method *****/

            function update(){
                var nodes = datagrid.root || [];
                var lookup = nodes.lookup || (nodes.lookup = {});

                var files = coverage.files;
                for (var path in files) {
                    var file = files[path];
                    var node = lookup[path];
                    if (!node) nodes.push(node = lookup[path] = { label: path.substr(1) });
                    node.covered = Math.round(file.coveredLines / file.totalLines * 100);
                    node.uncovered = file.totalLines - file.coveredLines;
                }

                datagrid.setRoot(nodes);
            }

            /***** Lifecycle *****/

            plugin.on("documentLoad", function(e) {
                var doc = e.doc;

                function setTheme(e) {
                    var tab = doc.tab;
                    var isDark = e.theme == "dark";

                    tab.backgroundColor = BGCOLOR[e.theme];

                    if (isDark) tab.classList.add("dark");
                    else tab.classList.remove("dark");
                }

                layout.on("themeChange", setTheme, doc);
                setTheme({ theme: settings.get("user/general/@skin") });

                doc.tab.title = "Code Coverage";
            });

            plugin.on("documentActivate", function(e) {

            });

            /***** Register and define API *****/

            plugin.freezePublicAPI({});

            plugin.load(null, "coverageview");

            return plugin;
        }

        register(null, {
            "test.coverageview": handle
        });
    }
});
<commit_msg>Make flat dark theme a proper theme and converted the save as dialog<commit_after>define(function(require, exports, module) {
    main.consumes = [
        "Editor", "editors", "ui", "save", "test.coverage", "Datagrid",
        "layout", "settings", "tabManager", "commands", "Divider", "MenuItem",
        "console"
    ];
    main.provides = ["test.coverageview"];
    return main;

    function main(options, imports, register) {
        var ui = imports.ui;
        var save = imports.save;
        var Editor = imports.Editor;
        var Datagrid = imports.Datagrid;
        var editors = imports.editors;
        var layout = imports.layout;
        var Divider = imports.Divider;
        var MenuItem = imports.MenuItem;
        var tabManager = imports.tabManager;
        var settings = imports.settings;
        var console = imports.console;
        var commands = imports.commands;
        var coverage = imports["test.coverage"];

        /***** Initialization *****/

        var extensions = [];

        var handle = editors.register("coverageview", "Coverage View", CoverageView, extensions);

        handle.on("load", function(){
            commands.addCommand({
                name: "opencoverageview",
                // hint: "runs the selected test(s) in the test panel",
                // bindKey: { mac: "F6", win: "F6" },
                group: "Test",
                exec: function(editor, args){
                    var tab;
                    if (tabManager.getTabs().some(function(t){
                        if (t.editorType == "coverageview") {
                            tab = t;
                            return true;
                        }
                    })) {
                        tabManager.focusTab(tab);
                    }
                    else {
                        console.show();
                        tabManager.open({
                            editorType: "coverageview",
                            focus: true,
                            pane: console.getPanes()[0]
                        }, function(){});
                    }
                }
            }, handle);

            coverage.on("draw", function(){
                coverage.buttonMenu.append(new Divider());
                coverage.buttonMenu.append(new MenuItem({
                    caption: "Open Code Coverage View",
                    command: "opencoverageview"
                }));
            }, handle);
        });

        function CoverageView(){
            var plugin = new Editor("Ajax.org", main.consumes, extensions);
            var datagrid;

            var BGCOLOR = {
                "flat-light": "#f7f7f7",
                "flat-dark": "#3D3D3D",
                "light": "#D3D3D3",
                "light-gray": "#D3D3D3",
                "dark": "#3D3D3D",
                "dark-gray": "#3D3D3D"
            };

            plugin.on("draw", function(e) {
                datagrid = new Datagrid({
                    container: e.htmlNode,

                    columns : [
                        {
                            caption: "Hierarchy",
                            value: "label",
                            width: "60%",
                            type: "tree"
                        },
                        {
                            caption: "Covered (%)",
                            width: "20%",
                            getText: function(node){
                                return node.covered + "%";
                            }
                        },
                        {
                            caption: "Not Covered",
                            value: "uncovered",
                            width: "20%"
                        }
                    ]
                }, plugin);

                datagrid.on("afterChoose", function(){
                    tabManager.openFile("/" + datagrid.selectedNode.label, true, function(){});
                });

                coverage.on("update", function(){
                    update();
                }, plugin);

                e.htmlNode.style.padding = 0;

                update();
            });

            /***** Method *****/

            function update(){
                var nodes = datagrid.root || [];
                var lookup = nodes.lookup || (nodes.lookup = {});

                var files = coverage.files;
                for (var path in files) {
                    var file = files[path];
                    var node = lookup[path];
                    if (!node) nodes.push(node = lookup[path] = { label: path.substr(1) });
                    node.covered = Math.round(file.coveredLines / file.totalLines * 100);
                    node.uncovered = file.totalLines - file.coveredLines;
                }

                datagrid.setRoot(nodes);
            }

            /***** Lifecycle *****/

            plugin.on("documentLoad", function(e) {
                var doc = e.doc;

                function setTheme(e) {
                    var tab = doc.tab;
                    var isDark = e.theme == "dark";

                    tab.backgroundColor = BGCOLOR[e.theme];

                    if (isDark) tab.classList.add("dark");
                    else tab.classList.remove("dark");
                }

                layout.on("themeChange", setTheme, doc);
                setTheme({ theme: settings.get("user/general/@skin") });

                doc.tab.title = "Code Coverage";
            });

            plugin.on("documentActivate", function(e) {

            });

            /***** Register and define API *****/

            plugin.freezePublicAPI({});

            plugin.load(null, "coverageview");

            return plugin;
        }

        register(null, {
            "test.coverageview": handle
        });
    }
});
<|endoftext|>


<commit_before>
App.MentionsResultListView = Backbone.View.extend({
    initialize: function (options) {
        this.render();
    },
    render: function () {
        App.debug('App.MentionsResultListView.render()');
        this.$el.html('');
        this.collection.each(function (m) {
            var view = new App.MentionsResultView({model:m})
            this.$el.append(view.el);
        }, this);
    }
});

App.MentionsResultView = Backbone.View.extend({
    template: _.template($('#tpl-mentions-result-view').html()),
    initialize: function (options) {
        this.render();
    },
    render: function () {
        App.debug('MenionResultView.render()');
        this.$el.html(this.template());
        this.$('.progress').html(
            _.template($('#tpl-progress').html())()
        ).show();
        this.listenTo(this.model.collection.resources, 'sync:sentence', function (sentences) {
            App.debug('App.MentionsResultView.collection: sync');
            this.$('.progress').hide();
            // figure out the total sentence count
            totalSentences = sentences.last(1)[0].get('totalSentences');
            this.$('.count').html('(' + totalSentences + ' found)');
            this.$('.query-name').html(this.model.get('name'));
            this.$('mentions-result-view-content').html('');
            // now list some of the sentences
            _.each(sentences.last(10), function (m) {
                var p = $('
').html('' + m.media() + ' - ' + m.date() + ': '
                    + '' + m.escape('sentence') + ''
                    );
                this.$('.mentions-result-view-content').append(p);
            }, this);
        });
    }
});
<commit_msg>Add csv download to mentions front end.<commit_after>
App.MentionsResultListView = Backbone.View.extend({
    initialize: function (options) {
        this.render();
    },
    render: function () {
        App.debug('App.MentionsResultListView.render()');
        this.$el.html('');
        this.collection.each(function (m) {
            var view = new App.MentionsResultView({model:m})
            this.$el.append(view.el);
        }, this);
    }
});

App.MentionsResultView = Backbone.View.extend({
    template: _.template($('#tpl-mentions-result-view').html()),
    initialize: function (options) {
        this.render();
    },
    render: function () {
        App.debug('MenionResultView.render()');
        this.$el.html(this.template());
        this.$('.progress').html(
            _.template($('#tpl-progress').html())()
        ).show();
        console.log(this.model);
        var csvUrl = this.model.get('results').get('sentences').csvUrl();
        this.$('li.csv a').attr('href', csvUrl);
        this.listenTo(this.model.collection.resources, 'sync:sentence', function (sentences) {
            App.debug('App.MentionsResultView.collection: sync');
            this.$('.progress').hide();
            // figure out the total sentence count
            totalSentences = sentences.last(1)[0].get('totalSentences');
            this.$('.count').html('(' + totalSentences + ' found)');
            this.$('.query-name').html(this.model.get('name'));
            this.$('mentions-result-view-content').html('');
            // now list some of the sentences
            _.each(sentences.last(10), function (m) {
                var p = $('
').html('' + m.media() + ' - ' + m.date() + ': '
                    + '' + m.escape('sentence') + ''
                    );
                this.$('.mentions-result-view-content').append(p);
            }, this);
        });
    }
});
<|endoftext|>


<commit_before>/*
 * Auxiliary functions
 */

/**
 * Convert topic to regex
 *
 * @param topic
 * @returns {*}
 */
export function topicToRegex(topic) {

    // deep copy
    let regex = (' ' + topic).slice(1);

    // Parse topic
    if (regex.indexOf('+') >= 0) {
        regex = regex.replace(/\+/g, "[^/]+");
    }
    if (regex.indexOf('#') === regex.length - 1) {
        regex = regex.replace("#", "[a-zA-Z0-9_/ ]+");
    }
    // Invalid topic
    if (regex.indexOf('#') >= 0) {
        throw new Error("Invalid topic '" + topic + "'");
    }

    // compile regex?
    if (topic !== regex)
        return new RegExp('^' + regex + '$');
    else
        return topic;

}

function matchStringOrRegExp(regex, topic) {
    if (regex.length > 1 && regex[0] === '/' && regex[regex.length - 1] === '/')
        return topic.match(regex)
    else
        return topic === regex;
}

/**
 * Matches topic to all possible entries in array of regexps.
 *
 * @param array the array of regexps
 * @param topic the topic to be matched
 * @returns {Array}
 */
export function matchAllTopics(array, topic) {

    const topics = [];
    for(let i = 0; i < array.length; i++) {
        const regex = array[i]
        if (matchStringOrRegExp(regex, topic))
            topics.push(regex);
    }
    return topics;

}

/**
 * Matches topic to first possible entry in array of regexps.
 *
 * @param array the array of regexps
 * @param topic the topic to be matched
 * @returns {*}
 */
export function matchFirstTopic(array, topic) {

    for(let i = 0; i < array.length; i++) {
        const regex = array[i]
        if (matchStringOrRegExp(regex, topic))
            return regex;

    }
    return null;

}

/**
 * Topic observer pattern base class
 */
export class TopicObserver {

    constructor() {
        this.observers = { __all__: [] };
        this.keys = Object.keys(this.observers);
    }

    matchesTopic(topic) {
        return matchFirstTopic(this.keys, topic) !== null;
    }

    hasTopic(topic) {
        return this.observers.hasOwnProperty(topicToRegex(topic));
    }

    observe(fn, topic) {

        // default is all
        topic = topic || '__all__';

        // compile topic as regex if needed
        if (topic !== '__all__') {
            topic = topicToRegex(topic);
        }

        // create topic if needed
        if (!this.observers.hasOwnProperty(topic)) {
            this.observers[topic] = [];
            this.keys = Object.keys(this.observers);
        }

        this.observers[topic].push(fn);
    }

    remove(fn, topic) {

        // default is all
        topic = topic || '__all__';

        // compile topic as regex if needed
        if (topic !== '__all__') {
            topic = topicToRegex(topic);
        }

        this.observers[topic] = this.observers[topic].filter((subscriber) => subscriber !== fn);
    }

     broadcast(data, topic) {

        // default is all
        topic = topic || '__all__';

        // is that a particular topic?
        if (topic !== '__all__') {

            // match topics and broadcast
            const topics = matchAllTopics(this.keys, topic);
            if (topics.length > 0)
                topics.forEach(
                    (topic) => this.observers[topic].forEach((subscriber) => subscriber(data))
                );
            else
                console.warn('No topics matched!');

        }

        // broadcast for all
        this.observers['__all__'].forEach((subscriber) => subscriber(data));
    }

}<commit_msg>TopicObserver pattern.<commit_after>/*
 * Auxiliary functions
 */

/**
 * Convert topic to regex
 *
 * @param topic
 * @returns {*}
 */
export function topicToRegex(topic) {

    // deep copy
    let regex = (' ' + topic).slice(1);

    // Parse topic
    if (regex.indexOf('+') >= 0) {
        regex = regex.replace(/\+/g, "[^/]+");
    }
    if (regex.indexOf('#') === regex.length - 1) {
        regex = regex.replace("#", "[a-zA-Z0-9_/ ]+");
    }
    // Invalid topic
    if (regex.indexOf('#') >= 0) {
        throw new Error("Invalid topic '" + topic + "'");
    }

    // compile regex?
    if (topic !== regex)
        return new RegExp('^' + regex + '$');
    else
        return topic;

}

function matchStringOrRegExp(regex, topic) {
    if (regex.length > 1 && regex[0] === '/' && regex[regex.length - 1] === '/')
        return topic.match(regex);
    else
        return topic === regex;
}

/**
 * Matches topic to all possible entries in array of regexps.
 *
 * @param array the array of regexps
 * @param topic the topic to be matched
 * @returns {Array}
 */
export function matchAllTopics(array, topic) {

    const topics = [];
    for(let i = 0; i < array.length; i++) {
        const regex = array[i]
        if (matchStringOrRegExp(regex, topic))
            topics.push(regex);
    }
    return topics;

}

/**
 * Matches topic to first possible entry in array of regexps.
 *
 * @param array the array of regexps
 * @param topic the topic to be matched
 * @returns {*}
 */
export function matchFirstTopic(array, topic) {

    for(let i = 0; i < array.length; i++) {
        const regex = array[i]
        if (matchStringOrRegExp(regex, topic))
            return regex;

    }
    return null;

}

/**
 * Topic observer pattern base class
 */
export class TopicObserver {

    constructor() {
        this.observers = { __all__: [] };
        this.keys = Object.keys(this.observers);
    }

    matchesTopic(topic) {
        return matchFirstTopic(this.keys, topic) !== null;
    }

    hasTopic(topic) {
        return this.observers.hasOwnProperty(topicToRegex(topic));
    }

    observe(fn, topic) {

        // default is all
        topic = topic || '__all__';

        // compile topic as regex if needed
        if (topic !== '__all__') {
            topic = topicToRegex(topic);
        }

        // create topic if needed
        if (!this.observers.hasOwnProperty(topic)) {
            this.observers[topic] = [];
            this.keys = Object.keys(this.observers);
        }

        this.observers[topic].push(fn);
    }

    remove(fn, topic) {

        // default is all
        topic = topic || '__all__';

        // compile topic as regex if needed
        if (topic !== '__all__') {
            topic = topicToRegex(topic);
        }

        this.observers[topic] = this.observers[topic].filter((subscriber) => subscriber !== fn);
    }

     broadcast(data, topic) {

        // default is all
        topic = topic || '__all__';

        // is that a particular topic?
        if (topic !== '__all__') {

            // match topics and broadcast
            const topics = matchAllTopics(this.keys, topic);
            if (topics.length > 0)
                topics.forEach(
                    (topic) => this.observers[topic].forEach((subscriber) => subscriber(data))
                );
            else
                console.warn('No topics matched!');

        }

        // broadcast for all
        this.observers['__all__'].forEach((subscriber) => subscriber(data));
    }

}<|endoftext|>


<commit_before>/*!
 * Module dependencies.
 */

var util = require('util');
var marked = require('marked');
var super_ = require('../Type');

/**
 * Markdown FieldType Constructor
 * @extends Field
 * @api public
 */

function markdown (list, path, options) {

	this._defaultSize = 'full';

	// TODO: implement filtering, usage disabled for now
	options.nofilter = true;

	this.toolbarOptions = options.toolbarOptions || {};
	this.markedOptions = options.markedOptions || {};
	this.height = options.height || 90;

	// since wysiwyg option can be falsey this needs to use `in` instead of ||
	this.wysiwyg = ('wysiwyg' in options) ? options.wysiwyg : true;

	this._properties = ['wysiwyg', 'height', 'toolbarOptions'];

	markdown.super_.call(this, list, path, options);

}

/*!
 * Inherit from Field
 */

util.inherits(markdown, super_);

/**
 * Registers the field on the List's Mongoose Schema.
 *
 * Adds String properties for .markdown and .html markdown, and a setter
 * for .markdown that generates html when it is updated.
 *
 * @api public
 */

markdown.prototype.addToSchema = function () {

	var schema = this.list.schema;

	var paths = this.paths = {
		md: this._path.append('.md'),
		html: this._path.append('.html'),
	};

	var markedOptions = this.markedOptions;

	var setMarkdown = function (value) {

		if (value === this.get(paths.md)) {
			return value;
		}

		if (typeof value === 'string') {
			this.set(paths.html, marked(value, markedOptions));
			return value;
		} else {
			this.set(paths.html, undefined);
			return undefined;
		}

	};

	schema.nested[this.path] = true;
	schema.add({
		html: { type: String },
		md: { type: String, set: setMarkdown },
	}, this.path + '.');

	this.bindUnderscoreMethods();
};

/**
 * Formats the field value
 *
 * @api public
 */

markdown.prototype.format = function (item) {
	return item.get(this.paths.html);
};

/**
 * Validates that a value for this field has been provided in a data object
 *
 * Will accept either the field path, or paths.md
 *
 * @api public
 */

markdown.prototype.inputIsValid = function (data, required, item) {
	if (!(this.path in data || this.paths.md in data) && item && item.get(this.paths.md)) {
		return true;
	}
	return (!required || data[this.path] || data[this.paths.md]) ? true : false;
};

/**
 * Detects whether the field has been modified
 *
 * @api public
 */

markdown.prototype.isModified = function (item) {
	return item.isModified(this.paths.md);
};

/**
 * Updates the value for this field in the item from a data object
 *
 * Will accept either the field path, or paths.md
 *
 * @api public
 */

markdown.prototype.updateItem = function (item, data, callback) {
	var value = this.getValueFromData(data);
	if (value !== undefined) {
		item.set(this.paths.md, value);
	} else if (this.paths.md in data) {
		item.set(this.paths.md, data[this.paths.md]);
	}
	process.nextTick(callback);
};

/*!
 * Export class
 */

module.exports = markdown;
<commit_msg>Cleaning up Markdown field type<commit_after>var FieldType = require('../Type');
var marked = require('marked');
var util = require('util');

/**
 * Markdown FieldType Constructor
 * @extends Field
 * @api public
 */

function markdown (list, path, options) {
	this._defaultSize = 'full';

	this.toolbarOptions = options.toolbarOptions || {};
	this.markedOptions = options.markedOptions || {};
	this.height = options.height || 90;
	this.wysiwyg = ('wysiwyg' in options) ? options.wysiwyg : true;

	this._properties = ['wysiwyg', 'height', 'toolbarOptions'];
	markdown.super_.call(this, list, path, options);
}
util.inherits(markdown, FieldType);

/**
 * Registers the field on the List's Mongoose Schema.
 *
 * Adds String properties for .md and .html markdown, and a setter for .md
 * that generates html when it is updated.
 *
 * @api public
 */
markdown.prototype.addToSchema = function () {

	var schema = this.list.schema;

	var paths = this.paths = {
		md: this._path.append('.md'),
		html: this._path.append('.html'),
	};

	var markedOptions = this.markedOptions;

	var setMarkdown = function (value) {
		if (value === this.get(paths.md)) {
			return value;
		}
		if (typeof value === 'string') {
			this.set(paths.html, marked(value, markedOptions));
			return value;
		} else {
			this.set(paths.html, undefined);
			return undefined;
		}
	};

	schema.nested[this.path] = true;
	schema.add({
		html: { type: String },
		md: { type: String, set: setMarkdown },
	}, this.path + '.');

	this.bindUnderscoreMethods();
};

/**
 * Formats the field value
 *
 * @api public
 */
markdown.prototype.format = function (item) {
	return item.get(this.paths.html);
};

/**
 * Validates that a value for this field has been provided in a data object
 *
 * Will accept either the field path, or paths.md
 *
 * @api public
 */
markdown.prototype.inputIsValid = function (data, required, item) {
	if (!(this.path in data || this.paths.md in data) && item && item.get(this.paths.md)) {
		return true;
	}
	return (!required || data[this.path] || data[this.paths.md]) ? true : false;
};

/**
 * Detects whether the field has been modified
 *
 * @api public
 */
markdown.prototype.isModified = function (item) {
	return item.isModified(this.paths.md);
};

/**
 * Updates the value for this field in the item from a data object
 *
 * Will accept either the field path, or paths.md
 *
 * @api public
 */
markdown.prototype.updateItem = function (item, data, callback) {
	var value = this.getValueFromData(data);
	if (value !== undefined) {
		item.set(this.paths.md, value);
	} else if (this.paths.md in data) {
		item.set(this.paths.md, data[this.paths.md]);
	}
	process.nextTick(callback);
};

/* Export Field Type */
module.exports = markdown;
<|endoftext|>


<commit_before>$.ajax(
	{
		url: basePepUrl + "lista_pareamentos.php",
		success: function OnAjaxSuccess(data, textStatus, jqXHR)
		{
			console.log(typeof data, textStatus, jqXHR);
			if(data.result === true)
			{
				$.each(data.data,function(index,obj)
				{
					 if(obj.aceito == 0){
						 $('#lista').append("
"+
											"" + obj.email + "" +
											"
" +
												"<button class='btn btn-positive emp-aceitar'>Aceitar</button>" +
												"<button class='btn btn-negative emp-recusar'>Recusar</button>" +
											"
" +
										"
");
					 }else{
						 $('#lista').append(Constr_Li_Aceito(obj.id, obj.email));
					 }
				});
			}
			else
			{

			}
		},
		error: function OnAjaxError(jqXHR, textStatus, errorThrown)
		{
			console.log(jqXHR, textStatus, errorThrown);
		},
		complete: function OnAjaxComplete(jqXHR, textStatus)
		{
			console.log(jqXHR, textStatus);
		}
});

function Constr_Li_Aceito(id, email)
{
	var str = 	"
"+
					"" + email + "" +
					"
" +
						"<button class='btn btn-negative emp-remover'>Remover</button>" +
						"
" +
							"

" +
						"
" +
					"
" +
				"
";
	return str;
}

$(document).ready(function()
{
	$('#lista').on('click','.emp-aceitar',function(event)
	{
		aceitaRecusa($(this).closest('li'), true);
	});
	$('#lista').on('click','.emp-recusar, .emp-remover',function(event)
	{
		aceitaRecusa($(this).closest('li'), false);
	});

	function aceitaRecusa(li, resp)
	{
		var id = li.data('id');
		var email = li.find('.email').text();
		$.ajax(
		{
			url: basePepUrl + "resp_pareamento.php",
			data:
			{
				id: id,
				resp: resp
			},
			success: function OnAjaxSuccess(data, textStatus, jqXHR)
			{
				console.log(data, textStatus, jqXHR);
				if(data.result === true)
				{
					alert(data.message);
					if(resp === false)
					{
						li.remove();
					}
					else
					{
						li.replaceWith(Constr_Li_Aceito(id, email));
					}
				}
				else
				{
					alert(data.message);
				}
			},
			error: function OnAjaxError(jqXHR, textStatus, errorThrown)
			{
				console.log(jqXHR, textStatus, errorThrown);
			},
			complete: function OnAjaxComplete(jqXHR, textStatus)
			{
				console.log(jqXHR, textStatus);
			}
		});
	}

});
<commit_msg>Pequena mexida no JS emparelhados<commit_after>$.ajax(
	{
		url: basePepUrl + "lista_pareamentos.php",
		success: function OnAjaxSuccess(data, textStatus, jqXHR)
		{
			console.log(typeof data, textStatus, jqXHR);
			if(data.result === true)
			{
				$.each(data.data,function(index,obj)
				{
					 if(obj.aceito == 0){
						 $('#lista').append("
"+
												"" + obj.email + "" +
												"
" +
													"<button class='btn btn-positive emp-aceitar'>Aceitar</button>" +
													"<button class='btn btn-negative emp-recusar'>Recusar</button>" +
												"
" +
											"
");
					 }else{
						 $('#lista').append(Constr_Li_Aceito(obj.id, obj.email));
					 }
				});
			}
			else
			{

			}
		},
		error: function OnAjaxError(jqXHR, textStatus, errorThrown)
		{
			console.log(jqXHR, textStatus, errorThrown);
		},
		complete: function OnAjaxComplete(jqXHR, textStatus)
		{
			console.log(jqXHR, textStatus);
		}
});

function Constr_Li_Aceito(id, email)
{
	var str = 	"
"+
					"" + email + "" +
					"
" +
						"<button class='btn btn-negative emp-remover'>Remover</button>" +
						"
" +
							"

" +
						"
" +
					"
" +
				"
";
	return str;
}

$(document).ready(function()
{
	$('#lista').on('click','.emp-aceitar',function(event)
	{
		aceitaRecusa($(this).closest('li'), true);
	});
	$('#lista').on('click','.emp-recusar, .emp-remover',function(event)
	{
		aceitaRecusa($(this).closest('li'), false);
	});

	function aceitaRecusa(li, resp)
	{
		var id = li.data('id');
		var email = li.find('.email').text();
		var had = !!(li.find('.emp-remover').length === 1);
		$.ajax(
		{
			url: basePepUrl + "resp_pareamento.php",
			data:
			{
				id: id,
				resp: resp,
				had: had
			},
			success: function OnAjaxSuccess(data, textStatus, jqXHR)
			{
				console.log(data, textStatus, jqXHR);
				if(data.result === true)
				{
					alert(data.message);
					if(resp === false)
					{
						li.remove();
					}
					else
					{
						li.replaceWith(Constr_Li_Aceito(id, email));
					}
				}
				else
				{
					alert(data.message);
				}
			},
			error: function OnAjaxError(jqXHR, textStatus, errorThrown)
			{
				console.log(jqXHR, textStatus, errorThrown);
			},
			complete: function OnAjaxComplete(jqXHR, textStatus)
			{
				console.log(jqXHR, textStatus);
			}
		});
	}

});
<|endoftext|>


<commit_before>var chalk = require('chalk');
var ansi = require('ansi-escapes');
var readline = require('readline');
var execSync = require('child_process').execSync;

function Interactive() {
	this.prompt = 'Enter a file glob: ';
	this.input = '';
	this.getGitFiles = true;
	this.getCommitMessage = false;
	this.inputColor = 'red';

	this.setup();
};

var proto = Interactive.prototype;

proto.setup = function() {
	readline.emitKeypressEvents(process.stdin);
	process.stdin.setRawMode(true);
	process.stdin.resume();

	process.stdin.on('keypress', function(char, key) {
		if (key.ctrl && key.name === 'c') {
	    process.exit();
	  }
	});

	process.stdin.on('keypress', function(char, key) {
		if (key.name === 'backspace') {
			this.onBackspace();
		} else if (key.name === 'return') {
			this.onReturn();
		} else {
			this.onType(char, key);
		}

		if (this.getGitFiles) {
			this.renderGitFiles();
		}
	}.bind(this));

	process.on('exit', function() {
		this.eraseBelow();
		console.log();
		process.stdin.write('Resetting all added files...');
		execSync('git reset .');
		process.stdin.write('Done.');
		console.log();
	}.bind(this));
};

proto.onReturn = function() {
	if (this.getGitFiles) {
		this.getGitFiles = false;
		this.getCommitMessage = true;
		this.renderAddSuccess();

		this.prompt = 'Commit message: ' + chalk.green('"');
		this.input = '';
		this.inputColor = 'green';

		this.renderLine();
	} else if (this.getCommitMessage) {
		var message = this.input;
		execSync('git commit -m "' + message + '"');

		console.log();
		console.log();
		console.log('----------------');
		console.log();
		console.log('Files committed successfully.');
		process.exit();
	}
};

proto.onBackspace = function() {
	this.input = this.input.slice(0, this.input.length - 1);

	if (this.input.length !== 0) {
		process.stdout.write(ansi.cursorMove(-1));
	}
	this.renderLine();
};

proto.onType = function(char, key) {
	if (typeof char !== 'undefined') {
		this.input += char + ''
	}
	this.renderLine();
};

proto.colorInput = function(input) {
	return chalk[this.inputColor](input);
};

proto.run = function() {
	this.renderLine();
	let files = this.getAllGitFiles();
	this.printBelow(files);
};

proto.renderLine = function() {
	var string = this.prompt + this.colorInput(this.input);
	if (this.getCommitMessage) {
		string += chalk.green('"');
	}

	process.stdout.clearLine();
	process.stdout.cursorTo(0);
	process.stdout.write(string);

	if (this.getCommitMessage) {
		process.stdout.write(ansi.cursorMove(-1));
	}
};

proto.renderGitFiles = function() {
	this.eraseBelow();
	var glob = this.input;
	var files = this.getAllGitFiles(glob);
	this.printBelow(files);
};

proto.renderAddSuccess = function() {
	this.eraseBelow();
	process.stdout.clearLine();
	process.stdout.write(ansi.cursorLeft);

	var glob = this.input;
	var files = this.getAllGitFiles(glob);

	try {
		execSync('git add *' + glob + '* &> /dev/null');
	} catch (e) {

	}

	console.log('Files added: ');
	console.log(chalk.green(files));
	console.log('----------------');
	console.log();
};

proto.getAllGitFiles = function(glob) {
	if (typeof glob === 'undefined') {
		glob = '';
	}

	try {
		var files = execSync("{ git diff --name-only; git ls-files --other --exclude-standard; } | sort | uniq | grep '" + glob +  "' 2> /dev/null");
		return files.toString('utf8');
	} catch (e) {
		return '';
	}
};

proto.eraseBelow = function() {
	process.stdout.write(ansi.eraseDown);
};

proto.printBelow = function(files) {
	process.stdout.write(ansi.cursorSavePosition);
	console.log();
	console.log();
	console.log(chalk.green('Files found: '));
	console.log(chalk.red(files));
	process.stdout.write(ansi.cursorRestorePosition);
};

module.exports = Interactive;
<commit_msg>Only reset if no commit is completed.<commit_after>var chalk = require('chalk');
var ansi = require('ansi-escapes');
var readline = require('readline');
var execSync = require('child_process').execSync;

function Interactive() {
	this.prompt = 'Enter a file glob: ';
	this.input = '';
	this.getGitFiles = true;
	this.getCommitMessage = false;
	this.inputColor = 'red';
	this.done = false;

	this.setup();
};

var proto = Interactive.prototype;

proto.setup = function() {
	readline.emitKeypressEvents(process.stdin);
	process.stdin.setRawMode(true);
	process.stdin.resume();

	process.stdin.on('keypress', function(char, key) {
		if (key.ctrl && key.name === 'c') {
	    process.exit();
	  }
	});

	process.stdin.on('keypress', function(char, key) {
		if (key.name === 'backspace') {
			this.onBackspace();
		} else if (key.name === 'return') {
			this.onReturn();
		} else {
			this.onType(char, key);
		}

		if (this.getGitFiles) {
			this.renderGitFiles();
		}
	}.bind(this));

	process.on('exit', function() {
		this.eraseBelow();
		console.log();

		if (!this.done) {
			process.stdin.write('Resetting all added files...');
			execSync('git reset .');
			process.stdin.write('Done.');
			console.log();
		}
	}.bind(this));
};

proto.onReturn = function() {
	if (this.getGitFiles) {
		this.getGitFiles = false;
		this.getCommitMessage = true;
		this.renderAddSuccess();

		this.prompt = 'Commit message: ' + chalk.green('"');
		this.input = '';
		this.inputColor = 'green';

		this.renderLine();
	} else if (this.getCommitMessage) {
		var message = this.input;
		execSync('git commit -m "' + message + '"');

		console.log();
		console.log();
		console.log('----------------');
		console.log();
		console.log('Files committed successfully.');

		this.done = true;
		process.exit();
	}
};

proto.onBackspace = function() {
	this.input = this.input.slice(0, this.input.length - 1);

	if (this.input.length !== 0) {
		process.stdout.write(ansi.cursorMove(-1));
	}
	this.renderLine();
};

proto.onType = function(char, key) {
	if (typeof char !== 'undefined') {
		this.input += char + ''
	}
	this.renderLine();
};

proto.colorInput = function(input) {
	return chalk[this.inputColor](input);
};

proto.run = function() {
	this.renderLine();
	let files = this.getAllGitFiles();
	this.printBelow(files);
};

proto.renderLine = function() {
	var string = this.prompt + this.colorInput(this.input);
	if (this.getCommitMessage) {
		string += chalk.green('"');
	}

	process.stdout.clearLine();
	process.stdout.cursorTo(0);
	process.stdout.write(string);

	if (this.getCommitMessage) {
		process.stdout.write(ansi.cursorMove(-1));
	}
};

proto.renderGitFiles = function() {
	this.eraseBelow();
	var glob = this.input;
	var files = this.getAllGitFiles(glob);
	this.printBelow(files);
};

proto.renderAddSuccess = function() {
	this.eraseBelow();
	process.stdout.clearLine();
	process.stdout.write(ansi.cursorLeft);

	var glob = this.input;
	var files = this.getAllGitFiles(glob);

	try {
		execSync('git add *' + glob + '* &> /dev/null');
	} catch (e) {

	}

	console.log('Files added: ');
	console.log(chalk.green(files));
	console.log('----------------');
	console.log();
};

proto.getAllGitFiles = function(glob) {
	if (typeof glob === 'undefined') {
		glob = '';
	}

	try {
		var files = execSync("{ git diff --name-only; git ls-files --other --exclude-standard; } | sort | uniq | grep '" + glob +  "' 2> /dev/null");
		return files.toString('utf8');
	} catch (e) {
		return '';
	}
};

proto.eraseBelow = function() {
	process.stdout.write(ansi.eraseDown);
};

proto.printBelow = function(files) {
	process.stdout.write(ansi.cursorSavePosition);
	console.log();
	console.log();
	console.log(chalk.green('Files found: '));
	console.log(chalk.red(files));
	process.stdout.write(ansi.cursorRestorePosition);
};

module.exports = Interactive;
<|endoftext|>


<commit_before>define([
    'jquery',
    'Underscore',
    'Backbone',
    'models/expense',
    'text!../../tpl/expense-detail.html'
], function ($, _, Backbone, expense, template) {
    var ExpenseDetailsView = Backbone.View.extend({
        self:this,
        initialize:function () {
            this.model.bind("reset", this.render, this);
        },
        events:{
            "click #put":"saveExpense",
            "click #add":"addLine"
        },

        render:function (eventName) {
            var $element=$(_.template(template, this.model.toJSON()));
            _.each(this.model.get('lines'), function(line,index){
                var selectedOption = $element.find('#expenseType').eq(index).children('option[value='+line.expenseType+']');
                selectedOption.attr('selected',true);
            });
            this.setElement($element);
            $('#content').replaceWith($element);
        },

        saveExpense:function () {
            var elements = $('#content td#expense-line');
            var view =this;
            var lines = _.map(elements, function (template) {
                t = $(template);
                return {
                    "expense":(+t.find('#amount').val()),
                    "description":t.find('#description').val(),
                    "valueDate":moment(t.find('#valueDate').val(), window.dateFormat).format(moment.defaultFormat),
                    "expenseType":t.find('#expenseType').val(),
                    "id":null,
                    "expenseReportId":null,
                    "account":"Xebia"
                };
            });
            this.model.set();
            if (this.model.isNew()) {
                this.model.unset('id')
            }
            this.model.save({
                startDate:moment($('#startDate').val(), window.dateFormat).format(),
                endDate:moment($('#endDate').val(), window.dateFormat).format(),
                total:$('#total').val(),
                lines:lines
            });
            return false;
        },
        addLine:function(){
             var table=$("#content table");
            _.each( this.model.defaults.lines, function (line) {
                console.log(line);
                line.valueDate = moment().format(window.dateFormat);
                var el = $(_.template(lineTemplate, line));
                el.find('select option[value=' + line.expenseType + ']').attr('selected', true)
                table.append(el);
            })
        },
        close:function () {
            $(this.el).unbind();
            $(this.el).empty();
        }

    });
    return ExpenseDetailsView;
});
<commit_msg>Fix add new expense line<commit_after>define([
    'jquery',
    'Underscore',
    'Backbone',
    'models/expense',
    'text!../../tpl/expense-detail.html'
], function ($, _, Backbone, expense, template) {
    var ExpenseDetailsView = Backbone.View.extend({
        self:this,
        initialize:function () {
            this.model.on("reset", this.render, this);
        },
        events:{
            "click #put":"saveExpense",
            "click #add":"addLine"
        },

        renderTemplate:function (json) {
            var $element = $(_.template(template, json));
            _.each(json.lines, function (line, index) {
                var selectedOption = $element.find('#expenseType').eq(index).children('option[value=' + line.expenseType + ']');
                selectedOption.attr('selected', true);
            });
            return $element;
        },

        render:function () {
            var $element = this.renderTemplate(this.model.toJSON());
            this.setElement($element);
            $('#content').replaceWith($element);
        },

        saveExpense:function () {
            var elements = $('#content td#expense-line');
            var view = this;
            var lines = _.map(elements, function (template) {
                t = $(template);
                return {
                    "expense":(+t.find('#amount').val()),
                    "description":t.find('#description').val(),
                    "valueDate":t.find('#valueDate').val(),
                    "expenseType":t.find('#expenseType').val(),
                    "id":null,
                    "expenseReportId":null,
                    "account":"Xebia"
                };
            });
            this.model.set();
            if (this.model.isNew()) {
                this.model.unset('id')
            }
            this.model.save({
                startDate:$('#startDate').val(),
                endDate:$('#endDate').val(),
                total:$('#total').val(),
                lines:lines
            });
            return false;
        },
        addLine:function () {
            var $table = $("#content table");
            var $element = this.renderTemplate(this.model.defaults);
            $table.append($element.find('table tbody tr'));
        },
        close:function () {
            $(this.el).unbind();
            $(this.el).empty();
        }

    });
    return ExpenseDetailsView;
});
<|endoftext|>