<commit_before>import { expect } from "chai";
import { hexToRgb, rgbToHex, rgbToHsl, hslToRgb } from "../src/conversion";
import parse from "../src/parse";
import { darken, lighten } from "../src/lightness";
import { desaturate, saturate, setSaturation } from "../src/saturation";
import { complimentary, setHue, spin } from "../src/hue";
import { mix, shade, tint } from "../src/mix";

describe("hexToRgb", () => {
  it("should convert a 3 channel hexadecimal color to the rgb color space", () =>{
    const [r, g, b] = hexToRgb("8E", "6B", "71");
    expect(r).to.equal(142);
    expect(g).to.equal(107);
    expect(b).to.equal(113);
  });
});

describe("rgbToHex", () => {
  it("should convert a 3 channel rgb color to 3 hexadecimal values", () =>{
    const [rHex, gHex, bHex] = rgbToHex(142, 107, 113);
    expect(rHex).to.equal("8E");
    expect(gHex).to.equal("6B");
    expect(bHex).to.equal("71");
  });
});

describe("rgbToHsl", () => {
  it("should convert a 3 channel rgb color to the hsl color space", () =>{
    const [h, s, l] = rgbToHsl(142, 107, 113);
    expect(h).to.equal(350);
    expect(s).to.equal(14);
    expect(l).to.equal(49);
  });
});

describe("hslToRgb", () => {
  it("should convert a 3 channel hsl color to the rgb color space", () =>{
    const [r, g, b] = hslToRgb(350, 14, 49);
    expect(r).to.equal(142);
    expect(g).to.equal(107);
    expect(b).to.equal(113);
  });
});

describe("parse", () => {
  it("should be a function", () => {
    expect(parse).to.be.a("function");
  });

  it("should return an object with a hex red property", () => {
    expect(parse("#333")).to.have.property("rHex");
  });

  it("should return an object with a hex green property", () => {
    expect(parse("#333")).to.have.property("gHex");
  });

  it("should return an object with a hex blue property", () => {
    expect(parse("#333")).to.have.property("bHex");
  });

  it("should return an object with a red property", () => {
    expect(parse("#333")).to.have.property("r");
  });

  it("should return an object with a green property", () => {
    expect(parse("#333")).to.have.property("g");
  });

  it("should return an object with a blue property", () => {
    expect(parse("#333")).to.have.property("b");
  });

  it("should return an object with a hue property", () => {
    expect(parse("#333")).to.have.property("h");
  });

  it("should return an object with a saturation property", () => {
    expect(parse("#333")).to.have.property("s");
  });

  it("should return an object with a lightness property", () => {
    expect(parse("#333")).to.have.property("l");
  });
});

describe("parse", () => {
  it("should throw an error if a string cannot be parsed to a color", () => {
    expect(() => parse("rgb(0,0")).to.throw(Error, /No matching color patterns found/);
  });
});

describe("hex", () => {
  it("should parse a 3 digit hex string", () => {
    expect(parse("#000").rgb()).to.equal("rgb(0,0,0)");
  });
  it("should parse a 6 digit hex string", () => {
    expect(parse("#000000").rgb()).to.equal("rgb(0,0,0)");
  });
  it("should output a hex string", () => {
    expect(parse("rgba(51,51,51)").hex()).to.equal("#333333");
  });
});

describe("rgb", () => {
  it("should parse an rgb string", () => {
    expect(parse("rgb(0,0,255)").hex()).to.equal("#0000FF");
  });
  it("should parse an rgba string", () => {
    expect(parse("rgba(0,0,255,0.5)").hsl()).to.equal("hsla(240,100%,50%,0.5)");
  });
  it("should output an rgb string", () => {
    expect(parse("#333").rgb()).to.equal("rgb(51,51,51)");
  });
  it("should parse an rgba string", () => {
    expect(parse("rgba(51,51,51,0.5)").hsl()).to.equal("hsla(0,0%,20%,0.5)");
  });
});

describe("hsl", () => {
  it("should parse an hsl string", () => {
    expect(parse("hsl(211,73%,13%)").hex()).to.equal("#092039");
  });
  it("should output an hsl string", () => {
    expect(parse("#092039").hsl()).to.equal("hsl(211,73%,13%)");
  });
});

describe("hsla", () => {
  it("should parse an hsla string", () => {
    expect(parse("hsla(211, 73%, 13%, 0.5)").rgb()).to.equal("rgba(9,32,57,0.5)");
  });
  it("should output an hsla string", () => {
    expect(parse("rgba(9, 32, 57, 0.5)").hsl()).to.equal("hsla(211,73%,13%,0.5)");
  });
});

describe("lighten", () => {
  it("should lighten a color by 10%", () => {
    const blue = parse("#00F");
    expect(lighten(blue).hsl()).to.equal("hsl(240,100%,55%)");
  });

  it("should not lighten a color higher than 100%", () => {
    const white = parse("#FFF");
    expect(lighten(white).rgb()).to.equal("rgb(255,255,255)");
  });

  it("should set the lightness absolutely", () => {
    const black = parse("rgb(0,0,0)");
    expect(black.setLightness(100).l).to.equal(100);
  });
});

describe("darken", () => {
  it("should darken a color by 25%", () => {
    const blue = parse("#00F");
    expect(darken(blue, 25).hsl()).to.equal("hsl(240,100%,37.5%)");
  });

  it("should not darken a color lower than 0%", () => {
    const black = parse("#000");
    expect(darken(black).rgb()).to.equal("rgb(0,0,0)");
  });

  it("should chain the darken method on a color object", () => {
    const blue = parse("#00f");
    expect(blue.darken).to.be.a("function");

    expect(blue.darken(20).hex()).to.equal("#0000CC");
  });

  it("should set the darkness absolutely", () => {
    const white = parse("rgb(255,255,255)");
    expect(white.setLightness(0).l).to.equal(0);
  });
});

describe("saturation", () => {
  const bostonBlue = parse("#4097bf");

  it("should chain saturate, desaturate, and setSaturation on polychromes", () => {
    expect(bostonBlue.desaturate).to.be.a("function");
    expect(bostonBlue.saturate).to.be.a("function");
    expect(bostonBlue.setSaturation).to.be.a("function");
  });

  it("should saturate a color by 20%", () => {
    expect(saturate(bostonBlue, 20).s).to.equal(60);
  });

  it("should desaturate a color by 20%", () => {
    expect(desaturate(bostonBlue, 20).s).to.equal(40);
  });

  it("should absolutely set saturation to 20%", () => {
    expect(setSaturation(bostonBlue, 20).s).to.equal(20);
  });
});

describe("hue", () => {
  const bostonBlue = parse("#4097bf");

  it("should chain complimentary, setHue, and spin on polychromes", () => {
    expect(bostonBlue.complimentary).to.be.a("function");
    expect(bostonBlue.setHue).to.be.a("function");
    expect(bostonBlue.spin).to.be.a("function");
  });

  it("should return a complimentary color", () => {
    expect(complimentary(bostonBlue, 20).h).to.equal(19);
  });

  it("should spin a color by a positive number", () => {
    expect(spin(bostonBlue, 150).h).to.equal(349);
  });

  it("should spin a color by a negative number", () => {
    expect(spin(bostonBlue, -100).h).to.equal(99);
  });

  it("should absolutely set hue to 0 (red)", () => {
    expect(setHue(bostonBlue, 0).h).to.equal(0);
  });
});

describe("mix", () => {
  const bostonBlue = parse("#4097bf");

  it("should chain mix, shade, and tint on polychromes", () => {
    expect(bostonBlue.mix).to.be.a("function");
    expect(bostonBlue.shade).to.be.a("function");
    expect(bostonBlue.tint).to.be.a("function");
  });

  it("should mix two colors", () => {
    expect(mix(bostonBlue, "#F00").hex()).to.equal("#9F4B5F");
  });

  it("should tint a color with white", () => {
    expect(tint(bostonBlue).hex()).to.equal("#9FCBDF");
  });

  it("should shade a color with black", () => {
    expect(shade(bostonBlue).hex()).to.equal("#204B5F");
  });
})

describe("alpha", () => {
  it("should fade out a color by 50%", () => {
    const black = parse();
    expect(black.fadeOut().a).to.equal(0.5);
  });

  it("should fade in a color by 50%", () => {
    const transparentBlack = parse("rgba(0,0,0,.5)");
    expect(transparentBlack.fadeIn().a).to.equal(0.75);
  });

  it("should set the alpha channel absolutely", () => {
    const reallyTransparentWhite = parse("rgba(255,255,255,.1)");
    expect(reallyTransparentWhite.setAlpha(100).a).to.equal(1);
  });
});
<commit_msg>Add tests for contrast<commit_after>import { expect } from "chai";
import { hexToRgb, rgbToHex, rgbToHsl, hslToRgb } from "../src/conversion";
import parse from "../src/parse";
import { darken, lighten } from "../src/lightness";
import { desaturate, saturate, setSaturation } from "../src/saturation";
import { complimentary, setHue, spin } from "../src/hue";
import { mix, shade, tint } from "../src/mix";

describe("hexToRgb", () => {
  it("should convert a 3 channel hexadecimal color to the rgb color space", () =>{
    const [r, g, b] = hexToRgb("8E", "6B", "71");
    expect(r).to.equal(142);
    expect(g).to.equal(107);
    expect(b).to.equal(113);
  });
});

describe("rgbToHex", () => {
  it("should convert a 3 channel rgb color to 3 hexadecimal values", () =>{
    const [rHex, gHex, bHex] = rgbToHex(142, 107, 113);
    expect(rHex).to.equal("8E");
    expect(gHex).to.equal("6B");
    expect(bHex).to.equal("71");
  });
});

describe("rgbToHsl", () => {
  it("should convert a 3 channel rgb color to the hsl color space", () =>{
    const [h, s, l] = rgbToHsl(142, 107, 113);
    expect(h).to.equal(350);
    expect(s).to.equal(14);
    expect(l).to.equal(49);
  });
});

describe("hslToRgb", () => {
  it("should convert a 3 channel hsl color to the rgb color space", () =>{
    const [r, g, b] = hslToRgb(350, 14, 49);
    expect(r).to.equal(142);
    expect(g).to.equal(107);
    expect(b).to.equal(113);
  });
});

describe("parse", () => {
  it("should be a function", () => {
    expect(parse).to.be.a("function");
  });

  it("should return an object with a hex red property", () => {
    expect(parse("#333")).to.have.property("rHex");
  });

  it("should return an object with a hex green property", () => {
    expect(parse("#333")).to.have.property("gHex");
  });

  it("should return an object with a hex blue property", () => {
    expect(parse("#333")).to.have.property("bHex");
  });

  it("should return an object with a red property", () => {
    expect(parse("#333")).to.have.property("r");
  });

  it("should return an object with a green property", () => {
    expect(parse("#333")).to.have.property("g");
  });

  it("should return an object with a blue property", () => {
    expect(parse("#333")).to.have.property("b");
  });

  it("should return an object with a hue property", () => {
    expect(parse("#333")).to.have.property("h");
  });

  it("should return an object with a saturation property", () => {
    expect(parse("#333")).to.have.property("s");
  });

  it("should return an object with a lightness property", () => {
    expect(parse("#333")).to.have.property("l");
  });
});

describe("parse", () => {
  it("should throw an error if a string cannot be parsed to a color", () => {
    expect(() => parse("rgb(0,0")).to.throw(Error, /No matching color patterns found/);
  });
});

describe("hex", () => {
  it("should parse a 3 digit hex string", () => {
    expect(parse("#000").rgb()).to.equal("rgb(0,0,0)");
  });
  it("should parse a 6 digit hex string", () => {
    expect(parse("#000000").rgb()).to.equal("rgb(0,0,0)");
  });
  it("should output a hex string", () => {
    expect(parse("rgba(51,51,51)").hex()).to.equal("#333333");
  });
});

describe("rgb", () => {
  it("should parse an rgb string", () => {
    expect(parse("rgb(0,0,255)").hex()).to.equal("#0000FF");
  });
  it("should parse an rgba string", () => {
    expect(parse("rgba(0,0,255,0.5)").hsl()).to.equal("hsla(240,100%,50%,0.5)");
  });
  it("should output an rgb string", () => {
    expect(parse("#333").rgb()).to.equal("rgb(51,51,51)");
  });
  it("should parse an rgba string", () => {
    expect(parse("rgba(51,51,51,0.5)").hsl()).to.equal("hsla(0,0%,20%,0.5)");
  });
});

describe("hsl", () => {
  it("should parse an hsl string", () => {
    expect(parse("hsl(211,73%,13%)").hex()).to.equal("#092039");
  });
  it("should output an hsl string", () => {
    expect(parse("#092039").hsl()).to.equal("hsl(211,73%,13%)");
  });
});

describe("hsla", () => {
  it("should parse an hsla string", () => {
    expect(parse("hsla(211, 73%, 13%, 0.5)").rgb()).to.equal("rgba(9,32,57,0.5)");
  });
  it("should output an hsla string", () => {
    expect(parse("rgba(9, 32, 57, 0.5)").hsl()).to.equal("hsla(211,73%,13%,0.5)");
  });
});

describe("lighten", () => {
  it("should lighten a color by 10%", () => {
    const blue = parse("#00F");
    expect(lighten(blue).hsl()).to.equal("hsl(240,100%,55%)");
  });

  it("should not lighten a color higher than 100%", () => {
    const white = parse("#FFF");
    expect(lighten(white).rgb()).to.equal("rgb(255,255,255)");
  });

  it("should set the lightness absolutely", () => {
    const black = parse("rgb(0,0,0)");
    expect(black.setLightness(100).l).to.equal(100);
  });
});

describe("darken", () => {
  it("should darken a color by 25%", () => {
    const blue = parse("#00F");
    expect(darken(blue, 25).hsl()).to.equal("hsl(240,100%,37.5%)");
  });

  it("should not darken a color lower than 0%", () => {
    const black = parse("#000");
    expect(darken(black).rgb()).to.equal("rgb(0,0,0)");
  });

  it("should chain the darken method on a color object", () => {
    const blue = parse("#00f");
    expect(blue.darken).to.be.a("function");

    expect(blue.darken(20).hex()).to.equal("#0000CC");
  });

  it("should set the darkness absolutely", () => {
    const white = parse("rgb(255,255,255)");
    expect(white.setLightness(0).l).to.equal(0);
  });
});

describe("saturation", () => {
  const bostonBlue = parse("#4097bf");

  it("should chain saturate, desaturate, and setSaturation on polychromes", () => {
    expect(bostonBlue.desaturate).to.be.a("function");
    expect(bostonBlue.saturate).to.be.a("function");
    expect(bostonBlue.setSaturation).to.be.a("function");
  });

  it("should saturate a color by 20%", () => {
    expect(saturate(bostonBlue, 20).s).to.equal(60);
  });

  it("should desaturate a color by 20%", () => {
    expect(desaturate(bostonBlue, 20).s).to.equal(40);
  });

  it("should absolutely set saturation to 20%", () => {
    expect(setSaturation(bostonBlue, 20).s).to.equal(20);
  });
});

describe("hue", () => {
  const bostonBlue = parse("#4097bf");

  it("should chain complimentary, setHue, and spin on polychromes", () => {
    expect(bostonBlue.complimentary).to.be.a("function");
    expect(bostonBlue.setHue).to.be.a("function");
    expect(bostonBlue.spin).to.be.a("function");
  });

  it("should return a complimentary color", () => {
    expect(complimentary(bostonBlue, 20).h).to.equal(19);
  });

  it("should spin a color by a positive number", () => {
    expect(spin(bostonBlue, 150).h).to.equal(349);
  });

  it("should spin a color by a negative number", () => {
    expect(spin(bostonBlue, -100).h).to.equal(99);
  });

  it("should absolutely set hue to 0 (red)", () => {
    expect(setHue(bostonBlue, 0).h).to.equal(0);
  });
});

describe("mix", () => {
  const bostonBlue = parse("#4097bf");

  it("should chain mix, shade, and tint on polychromes", () => {
    expect(bostonBlue.mix).to.be.a("function");
    expect(bostonBlue.shade).to.be.a("function");
    expect(bostonBlue.tint).to.be.a("function");
  });

  it("should mix two colors", () => {
    expect(mix(bostonBlue, "#F00").hex()).to.equal("#9F4B5F");
  });

  it("should tint a color with white", () => {
    expect(tint(bostonBlue).hex()).to.equal("#9FCBDF");
  });

  it("should shade a color with black", () => {
    expect(shade(bostonBlue).hex()).to.equal("#204B5F");
  });
})

describe("alpha", () => {
  it("should fade out a color by 50%", () => {
    const black = parse();
    expect(black.fadeOut().a).to.equal(0.5);
  });

  it("should fade in a color by 50%", () => {
    const transparentBlack = parse("rgba(0,0,0,.5)");
    expect(transparentBlack.fadeIn().a).to.equal(0.75);
  });

  it("should set the alpha channel absolutely", () => {
    const reallyTransparentWhite = parse("rgba(255,255,255,.1)");
    expect(reallyTransparentWhite.setAlpha(100).a).to.equal(1);
  });
});

describe("contrast", () => {
  const marinerBlue = parse("#1d5fdb");
  const whiteSmoke = parse("#f2f2f2");

  it("should return the correct contrast object for a dark color", () => {
    expect(marinerBlue.contrast().rgb()).to.equal("rgb(255,255,255)");
  });

  it("should return the correct contrast object for a light color", () => {
    expect(whiteSmoke.contrast().rgb()).to.equal("rgb(0,0,0)");
  });
});
<|endoftext|>


<commit_before>
var db = require("mongojs").connect("localhost:27017/taupe", ["url"]);

var generateSlug = function(){

};

exports.getUrl = function(request, response){
  response.json(db.url.find({"slug": request.params.id}));
};

exports.addUrl = function(request, response){

  var urlRegex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

  if(urlRegex.test(request.body.url)){
    var result = db.url.insert({
      "url": request.body.url,
      "slug": generateSlug(),
      "ip": request.connection.remoteAddress,
      "date": Date.now()
    });
  }

  response.json(result);
};
<commit_msg>getUrl api setup<commit_after>
var db = require("mongojs").connect("localhost:27017/taupe", ["url"]);

var generateSlug = function(){

};

exports.getUrl = function(request, response){
  db.url.find({"slug": request.params.id}, function(err, url){
    if(err){
      response.json(err);
    } else {
      response.json(url);
    }
  });
};

exports.addUrl = function(request, response){

  var urlRegex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

  if(urlRegex.test(request.body.url)){
    var result = db.url.insert({
      "url": request.body.url,
      "slug": generateSlug(),
      "ip": request.connection.remoteAddress,
      "date": Date.now()
    });
  }

  response.json(result);
};
<|endoftext|>


<commit_before>'use strict';

var Code = require('code');
var Lab = require('lab');
var lab = exports.lab = Lab.script();

var bs2 = require('../');
var Protocol = require('../mock/protocol');

var hi = require('./fixtures/hi');

lab.experiment('bs2', function(){

  var protocol;
  var options;

  lab.beforeEach(function(done){
    protocol = new Protocol();
    protocol._setData(new Buffer([0xBE, 0xAD, 0xCE, 0x10]));
    options = {
      protocol: protocol,
      revision: 'bs2'
    };
    done();
  });

  lab.experiment('challenge', function () {

    lab.test('works without creating a new programmer instance first', function(done){
      bs2.challenge(options, function(err){
        Code.expect(err).to.not.exist();
        done();
      });
    });

    lab.test('supports the promise pattern', function(done){
      bs2.challenge(options)
        .then(function(){
          done();
        })
        .catch(function(err){
          Code.expect(err).to.not.exist();
        })
        .done();
    });
  });

  lab.experiment('identify', function(){

    lab.test('works without creating a new programmer instance first', function(done){
      bs2.identify(options, function(err, result){
        Code.expect(err).to.not.exist();
        Code.expect(result).to.deep.equal({name: 'BS2', version: '1.0'});
        done();
      });
    });

    lab.test('supports the promise pattern', function(done){
      bs2.identify(options)
        .then(function(result){
          Code.expect(result).to.deep.equal({name: 'BS2', version: '1.0'});
          done();
        })
        .catch(function(err){
          console.log(err);
          Code.expect(err).to.not.exist();
        })
        .done();
    });
  });

  lab.experiment('bootload', function(){

    lab.beforeEach(function(done){
      //send bs2 response bytes, then the success byte
      protocol._setData(new Buffer([0xBE, 0xAD, 0xCE, 0x10, 0x00]));
      done();
    });

    lab.test('works without creating a new programmer instance first', function(done){
      bs2.bootload(hi, options, function(err){
        Code.expect(err).to.not.exist();
        done();
      });
    });

    lab.test('supports the promise pattern', function(done){
      bs2.bootload(hi, options)
        .then(function(){
          done();
        })
        .catch(function(err){
          Code.expect(err).to.not.exist();
        });
    });
  });
});
<commit_msg>Remove console log<commit_after>'use strict';

var Code = require('code');
var Lab = require('lab');
var lab = exports.lab = Lab.script();

var bs2 = require('../');
var Protocol = require('../mock/protocol');

var hi = require('./fixtures/hi');

lab.experiment('bs2', function(){

  var protocol;
  var options;

  lab.beforeEach(function(done){
    protocol = new Protocol();
    protocol._setData(new Buffer([0xBE, 0xAD, 0xCE, 0x10]));
    options = {
      protocol: protocol,
      revision: 'bs2'
    };
    done();
  });

  lab.experiment('challenge', function () {

    lab.test('works without creating a new programmer instance first', function(done){
      bs2.challenge(options, function(err){
        Code.expect(err).to.not.exist();
        done();
      });
    });

    lab.test('supports the promise pattern', function(done){
      bs2.challenge(options)
        .then(function(){
          done();
        })
        .catch(function(err){
          Code.expect(err).to.not.exist();
        })
        .done();
    });
  });

  lab.experiment('identify', function(){

    lab.test('works without creating a new programmer instance first', function(done){
      bs2.identify(options, function(err, result){
        Code.expect(err).to.not.exist();
        Code.expect(result).to.deep.equal({name: 'BS2', version: '1.0'});
        done();
      });
    });

    lab.test('supports the promise pattern', function(done){
      bs2.identify(options)
        .then(function(result){
          Code.expect(result).to.deep.equal({name: 'BS2', version: '1.0'});
          done();
        })
        .catch(function(err){
          Code.expect(err).to.not.exist();
        })
        .done();
    });
  });

  lab.experiment('bootload', function(){

    lab.beforeEach(function(done){
      //send bs2 response bytes, then the success byte
      protocol._setData(new Buffer([0xBE, 0xAD, 0xCE, 0x10, 0x00]));
      done();
    });

    lab.test('works without creating a new programmer instance first', function(done){
      bs2.bootload(hi, options, function(err){
        Code.expect(err).to.not.exist();
        done();
      });
    });

    lab.test('supports the promise pattern', function(done){
      bs2.bootload(hi, options)
        .then(function(){
          done();
        })
        .catch(function(err){
          Code.expect(err).to.not.exist();
        });
    });
  });
});
<|endoftext|>


<commit_before>// Copyright 2013 Web Notes Technologies Pvt Ltd
// License: MIT. See license.txt

// opts - parent, list, doc, email
wn.views.CommunicationList = Class.extend({
	init: function(opts) {
		this.comm_list = [];
		$.extend(this, opts);

		if(this.doc.__islocal) {
			$(this.parent).empty();
			return;
		}

		var sortfn = function (a, b) { return (b.creation > a.creation) ? 1 : -1; }
		this.list = this.list.sort(sortfn);

		this.make();
	},
	make: function() {
		var me = this;
		this.make_body();

		if(this.list && this.list.length) {
			$.each(this.list, function(i, d) {
				me.prepare(d);
				me.make_line(d);
			});
			// show first
			this.comm_list[0].find('.comm-content').toggle(true);
		} else {
			this.clear_list()
		}
	},
	clear_list: function() {
		this.body.remove();
		$("
" + wn._("No Communication tagged with this ")
			+ this.doc.doctype +" yet.
").appendTo(this.wrapper);
	},
	make_body: function() {
		$(this.parent)
			.empty()
			.css({"margin":"10px 0px"});

		this.wrapper = $("

"+wn._("Communication History")+"
\

\
				<button class='btn' \
					onclick='cur_frm.communication_view.add_reply()'>\
				 "+wn._("Add Message")+"</button>
\

")
			.appendTo(this.parent);

		this.body = $("
")
			.appendTo(this.wrapper);
	},

	add_reply: function() {
		new wn.views.CommunicationComposer({
			doc: this.doc,
			subject: this.doc.subject,
			recipients: this.recipients
		})
	},

	prepare: function(doc) {
		//doc.when = comment_when(this.doc.modified);
		doc.when = doc.modified;
		if(!doc.content) doc.content = "[no content]";
		if(doc.content.indexOf("
")== -1 && doc.content.indexOf("
")== -1) {
			doc.content = doc.content.replace(/\n/g, "
");
		}
		if(!doc.sender) doc.sender = "[unknown sender]";
		doc._sender = doc.sender.replace(/</, "<").replace(/>/, ">");
		doc.content = doc.content.split("-----"+wn._("In response to")+"-----")[0];
		doc.content = doc.content.split("-----"+wn._("Original Message")+"-----")[0];
	},

	make_line: function(doc) {
		var me = this;
		var comm = $(repl('
\
				'
					+wn._('Show Details')+'\

\
					%(_sender)s on %(when)s
\

\

', doc))
			.appendTo(this.body);

		if(!doc.name) {
			comm.find(".show-details").toggle(false);
		}

		comm.find(".comm-header")
			.css({"cursor":"pointer"})
			.click(function() {
				$(this).parent().find(".comm-content").toggle();
			});

		this.comm_list.push(comm);
		comm.find(".comm-content").html(doc.content);
	}
});

wn.views.CommunicationComposer = Class.extend({
	init: function(opts) {
		$.extend(this, opts)
		this.make();
		this.dialog.show();
	},
	make: function() {
		this.dialog = new wn.ui.Dialog({
			width: 640,
			title: wn._("Add Reply") + ": " + (this.subject || ""),
			no_submit_on_enter: true,
			fields: [
				{label:wn._("To"), fieldtype:"Data", reqd: 1, fieldname:"recipients",
					description:wn._("Email addresses, separted by commas")},
				{label:wn._("Subject"), fieldtype:"Data", reqd: 1,
					fieldname:"subject"},
				{label:wn._("Send"), fieldtype:"Button",
					fieldname:"send"},
				{label:wn._("Message"), fieldtype:"Text Editor", reqd: 1,
					fieldname:"content"},
				{label:wn._("Send Email"), fieldtype:"Check",
					fieldname:"send_email"},
				{label:wn._("Send Me A Copy"), fieldtype:"Check",
					fieldname:"send_me_a_copy"},
				{label:wn._("Attach Document Print"), fieldtype:"Check",
					fieldname:"attach_document_print"},
				{label:wn._("Select Print Format"), fieldtype:"Select",
					fieldname:"select_print_format"},
				{label:wn._("Select Attachments"), fieldtype:"HTML",
					fieldname:"select_attachments"}
			]
		});
		this.prepare();
	},
	prepare: function() {
		this.setup_print();
		this.setup_attach();
		this.setup_email();
		this.setup_autosuggest();
		$(this.dialog.fields_dict.recipients.input).val(this.recipients || "").change();
		$(this.dialog.fields_dict.subject.input).val(this.subject || "").change();
		this.setup_earlier_reply();
	},
	setup_print: function() {
		// print formats
		var fields = this.dialog.fields_dict;

		// toggle print format
		$(fields.attach_document_print.input).click(function() {
			$(fields.select_print_format.wrapper).toggle($(this).is(":checked"));
		});

		// select print format
		$(fields.select_print_format.wrapper).toggle(false);
		$(fields.select_print_format.input)
			.empty()
			.add_options(cur_frm.print_formats)
			.val(cur_frm.print_formats[0]);

	},
	setup_attach: function() {
		var fields = this.dialog.fields_dict;
		var attach = $(fields.select_attachments.wrapper);

		var files = cur_frm.get_files();
		if(files.length) {
			$("
"+wn._("Add Attachments")+":
").appendTo(attach);
			$.each(files, function(i, f) {
				$(repl("
<input type='checkbox' \
					data-file-name='%(file)s'> %(file)s
", {file:f})).appendTo(attach)
			});
		}
	},
	setup_email: function() {
		// email
		var me = this;
		var fields = this.dialog.fields_dict;

		if(this.attach_document_print) {
			$(fields.send_me_a_copy.input).click();
			$(fields.attach_document_print.input).click();
			$(fields.select_print_format.wrapper).toggle(true);
		}

		$(fields.send_email.input).attr("checked", "checked")
		$(fields.send.input).click(function() {
			var form_values = me.dialog.get_values();
			if(!form_values) return;

			var selected_attachments = $.map($(me.dialog.wrapper)
				.find("[data-file-name]:checked"), function(element) {
					return $(element).attr("data-file-name");
				})

			_p.build(form_values.select_print_format || "", function(print_format_html) {
				me.dialog.hide();
				if(form_values.attach_document_print) {
					var print_html = print_format_html
					form_values.content = form_values.content
						+ "

" + print_html;
				} else {
					print_html = "";
				}
				wn.call({
					method:"core.doctype.communication.communication.make",
					args: {
						sender: wn.user_info(user).fullname + " <" + wn.boot.profile.email + ">",
						recipients: form_values.recipients,
						subject: form_values.subject,
						content: form_values.content,
						doctype: me.doc.doctype,
						name: me.doc.name,
						lead: me.doc.lead,
						contact: me.doc.contact,
						send_me_a_copy: form_values.send_me_a_copy,
						send_email: form_values.send_email,
						print_html: print_html,
						attachments: selected_attachments
					},
					callback: function(r) {
						if(!r.exc) {
							if(form_values.send_email)
								msgprint("Email sent to " + form_values.recipients);
							cur_frm.reload_doc();
						}
					}
				});
			})
		});
	},
	setup_earlier_reply: function() {
		var fields = this.dialog.fields_dict;
		var comm_list = cur_frm.communication_view
			? cur_frm.communication_view.list
			: [];
		var signature = wn.boot.profile.email_signature || "";

		if(signature.indexOf("
")==-1 && signature.indexOf("<p")==-1
			&& signature.indexOf("<img")==-1 && signature.indexOf(" 0) {
			fields.content.input.set_input((this.message || "") +
				"

"
				+ signature
				+"

"
				+"-----"+wn._("In response to")+"-----

"
				+ comm_list[0].content);
		} else {
			fields.content.input.set_input((this.message || "")
				+ "

" + signature)
		}
	},
	setup_autosuggest: function() {
		var me = this;

		function split( val ) {
			return val.split( /,\s*/ );
		}
		function extractLast( term ) {
			return split(term).pop();
		}

		$(this.dialog.fields_dict.recipients.input)
			.bind( "keydown", function(event) {
				if (event.keyCode === $.ui.keyCode.TAB &&
						$(this).data( "autocomplete" ).menu.active ) {
					event.preventDefault();
				}
			})
			.autocomplete({
				source: function(request, response) {
					wn.call({
						method:'webnotes.utils.email_lib.get_contact_list',
						args: {
							'select': "email_id",
							'from': "Contact",
							'where': "email_id",
							'txt': extractLast(request.term).value || '%'
						},
						callback: function(r) {
							response($.ui.autocomplete.filter(
								r.cl || [], extractLast(request.term)));
						}
					});
				},
				focus: function() {
					// prevent value inserted on focus
					return false;
				},
				select: function( event, ui ) {
					var terms = split( this.value );
					// remove the current input
					terms.pop();
					// add the selected item
					terms.push( ui.item.value );
					// add placeholder to get the comma-and-space at the end
					terms.push( "" );
					this.value = terms.join( ", " );
					return false;
				}
			});
	}
});

<commit_msg>fixed communication subject<commit_after>// Copyright 2013 Web Notes Technologies Pvt Ltd
// License: MIT. See license.txt

// opts - parent, list, doc, email
wn.views.CommunicationList = Class.extend({
	init: function(opts) {
		this.comm_list = [];
		$.extend(this, opts);

		if(this.doc.__islocal) {
			$(this.parent).empty();
			return;
		}

		var sortfn = function (a, b) { return (b.creation > a.creation) ? 1 : -1; }
		this.list = this.list.sort(sortfn);

		this.make();
	},
	make: function() {
		var me = this;
		this.make_body();

		if(this.list && this.list.length) {
			$.each(this.list, function(i, d) {
				me.prepare(d);
				me.make_line(d);
			});
			// show first
			this.comm_list[0].find('.comm-content').toggle(true);
		} else {
			this.clear_list()
		}
	},
	clear_list: function() {
		this.body.remove();
		$("
" + wn._("No Communication tagged with this ")
			+ this.doc.doctype +" yet.
").appendTo(this.wrapper);
	},
	make_body: function() {
		$(this.parent)
			.empty()
			.css({"margin":"10px 0px"});

		this.wrapper = $("

"+wn._("Communication History")+"
\

\
				<button class='btn' \
					onclick='cur_frm.communication_view.add_reply()'>\
				 "+wn._("Add Message")+"</button>
\

")
			.appendTo(this.parent);

		this.body = $("
")
			.appendTo(this.wrapper);
	},

	add_reply: function() {
		var subject = this.doc.subject;
		if(!subject && this.list.length) {
			// get subject from previous message
			subject = this.list[0].subject;
		}
		new wn.views.CommunicationComposer({
			doc: this.doc,
			subject: subject,
			recipients: this.recipients
		})
	},

	prepare: function(doc) {
		//doc.when = comment_when(this.doc.modified);
		doc.when = doc.modified;
		if(!doc.content) doc.content = "[no content]";
		if(doc.content.indexOf("
")== -1 && doc.content.indexOf("
")== -1) {
			doc.content = doc.content.replace(/\n/g, "
");
		}
		if(!doc.sender) doc.sender = "[unknown sender]";
		doc._sender = doc.sender.replace(/</, "<").replace(/>/, ">");
		doc.content = doc.content.split("-----"+wn._("In response to")+"-----")[0];
		doc.content = doc.content.split("-----"+wn._("Original Message")+"-----")[0];
	},

	make_line: function(doc) {
		var me = this;
		var comm = $(repl('
\
				'
					+wn._('Show Details')+'\

\
					%(_sender)s on %(when)s
\

\

', doc))
			.appendTo(this.body);

		if(!doc.name) {
			comm.find(".show-details").toggle(false);
		}

		comm.find(".comm-header")
			.css({"cursor":"pointer"})
			.click(function() {
				$(this).parent().find(".comm-content").toggle();
			});

		this.comm_list.push(comm);
		comm.find(".comm-content").html(doc.content);
	}
});

wn.views.CommunicationComposer = Class.extend({
	init: function(opts) {
		$.extend(this, opts)
		this.make();
		this.dialog.show();
	},
	make: function() {
		this.dialog = new wn.ui.Dialog({
			width: 640,
			title: wn._("Add Reply") + ": " + (this.subject || ""),
			no_submit_on_enter: true,
			fields: [
				{label:wn._("To"), fieldtype:"Data", reqd: 1, fieldname:"recipients",
					description:wn._("Email addresses, separted by commas")},
				{label:wn._("Subject"), fieldtype:"Data", reqd: 1,
					fieldname:"subject"},
				{label:wn._("Send"), fieldtype:"Button",
					fieldname:"send"},
				{label:wn._("Message"), fieldtype:"Text Editor", reqd: 1,
					fieldname:"content"},
				{label:wn._("Send Email"), fieldtype:"Check",
					fieldname:"send_email"},
				{label:wn._("Send Me A Copy"), fieldtype:"Check",
					fieldname:"send_me_a_copy"},
				{label:wn._("Attach Document Print"), fieldtype:"Check",
					fieldname:"attach_document_print"},
				{label:wn._("Select Print Format"), fieldtype:"Select",
					fieldname:"select_print_format"},
				{label:wn._("Select Attachments"), fieldtype:"HTML",
					fieldname:"select_attachments"}
			]
		});
		this.prepare();
	},
	prepare: function() {
		this.setup_print();
		this.setup_attach();
		this.setup_email();
		this.setup_autosuggest();
		$(this.dialog.fields_dict.recipients.input).val(this.recipients || "").change();
		$(this.dialog.fields_dict.subject.input).val(this.subject || "").change();
		this.setup_earlier_reply();
	},
	setup_print: function() {
		// print formats
		var fields = this.dialog.fields_dict;

		// toggle print format
		$(fields.attach_document_print.input).click(function() {
			$(fields.select_print_format.wrapper).toggle($(this).is(":checked"));
		});

		// select print format
		$(fields.select_print_format.wrapper).toggle(false);
		$(fields.select_print_format.input)
			.empty()
			.add_options(cur_frm.print_formats)
			.val(cur_frm.print_formats[0]);

	},
	setup_attach: function() {
		var fields = this.dialog.fields_dict;
		var attach = $(fields.select_attachments.wrapper);

		var files = cur_frm.get_files();
		if(files.length) {
			$("
"+wn._("Add Attachments")+":
").appendTo(attach);
			$.each(files, function(i, f) {
				$(repl("
<input type='checkbox' \
					data-file-name='%(file)s'> %(file)s
", {file:f})).appendTo(attach)
			});
		}
	},
	setup_email: function() {
		// email
		var me = this;
		var fields = this.dialog.fields_dict;

		if(this.attach_document_print) {
			$(fields.send_me_a_copy.input).click();
			$(fields.attach_document_print.input).click();
			$(fields.select_print_format.wrapper).toggle(true);
		}

		$(fields.send_email.input).attr("checked", "checked")
		$(fields.send.input).click(function() {
			var form_values = me.dialog.get_values();
			if(!form_values) return;

			var selected_attachments = $.map($(me.dialog.wrapper)
				.find("[data-file-name]:checked"), function(element) {
					return $(element).attr("data-file-name");
				})

			_p.build(form_values.select_print_format || "", function(print_format_html) {
				me.dialog.hide();
				if(form_values.attach_document_print) {
					var print_html = print_format_html
					form_values.content = form_values.content
						+ "

" + print_html;
				} else {
					print_html = "";
				}
				wn.call({
					method:"core.doctype.communication.communication.make",
					args: {
						sender: wn.user_info(user).fullname + " <" + wn.boot.profile.email + ">",
						recipients: form_values.recipients,
						subject: form_values.subject,
						content: form_values.content,
						doctype: me.doc.doctype,
						name: me.doc.name,
						lead: me.doc.lead,
						contact: me.doc.contact,
						send_me_a_copy: form_values.send_me_a_copy,
						send_email: form_values.send_email,
						print_html: print_html,
						attachments: selected_attachments
					},
					callback: function(r) {
						if(!r.exc) {
							if(form_values.send_email)
								msgprint("Email sent to " + form_values.recipients);
							cur_frm.reload_doc();
						}
					}
				});
			})
		});
	},
	setup_earlier_reply: function() {
		var fields = this.dialog.fields_dict;
		var comm_list = cur_frm.communication_view
			? cur_frm.communication_view.list
			: [];
		var signature = wn.boot.profile.email_signature || "";

		if(signature.indexOf("
")==-1 && signature.indexOf("<p")==-1
			&& signature.indexOf("<img")==-1 && signature.indexOf(" 0) {
			fields.content.input.set_input((this.message || "") +
				"

"
				+ signature
				+"

"
				+"-----"+wn._("In response to")+"-----

"
				+ comm_list[0].content);
		} else {
			fields.content.input.set_input((this.message || "")
				+ "

" + signature)
		}
	},
	setup_autosuggest: function() {
		var me = this;

		function split( val ) {
			return val.split( /,\s*/ );
		}
		function extractLast( term ) {
			return split(term).pop();
		}

		$(this.dialog.fields_dict.recipients.input)
			.bind( "keydown", function(event) {
				if (event.keyCode === $.ui.keyCode.TAB &&
						$(this).data( "autocomplete" ).menu.active ) {
					event.preventDefault();
				}
			})
			.autocomplete({
				source: function(request, response) {
					wn.call({
						method:'webnotes.utils.email_lib.get_contact_list',
						args: {
							'select': "email_id",
							'from': "Contact",
							'where': "email_id",
							'txt': extractLast(request.term).value || '%'
						},
						callback: function(r) {
							response($.ui.autocomplete.filter(
								r.cl || [], extractLast(request.term)));
						}
					});
				},
				focus: function() {
					// prevent value inserted on focus
					return false;
				},
				select: function( event, ui ) {
					var terms = split( this.value );
					// remove the current input
					terms.pop();
					// add the selected item
					terms.push( ui.item.value );
					// add placeholder to get the comma-and-space at the end
					terms.push( "" );
					this.value = terms.join( ", " );
					return false;
				}
			});
	}
});

<|endoftext|>


<commit_before>'use strict';

module.exports = Object.assign(require('./development'), {
    sentry: {
        privateDsn: 'https://userID:password@ci.sentry.data.gouv.fr/17'
    },
});
<commit_msg>Utilise un nom de domaine qui existe<commit_after>'use strict';

module.exports = Object.assign(require('./development'), {
    sentry: {
        privateDsn: 'https://userID:password@sentry.data.gouv.fr/17'
    },
});
<|endoftext|>


<commit_before>var should = require('chai').should(),
    urlgenerator = require('../index'),
    createURLwithParameters = urlgenerator.createURLwithParameters,
    chaiHttp = require('chai-http');
var chai = require('chai');

chai.use(chaiHttp);

describe('Blobs', function() {
  it('converts base url to complete;', function() {
    var baseURL = "www.google.com";
   var parameters = {};
   parameters.mobile = '7838185123';
   parameters.shit = 'xxx';

    createURLwithParameters(baseURL,parameters).should.equal('www.google.com?mobile=7838185123&shit=xxx');
  });
});

<commit_msg>adding a test<commit_after>var should = require('chai').should(),
    urlgenerator = require('../index'),
    createURLwithParameters = urlgenerator.createURLwithParameters,
    chaiHttp = require('chai-http');
var chai = require('chai');

chai.use(chaiHttp);

describe('Blobs', function() {
  it('converts base url to complete;', function() {
    var baseURL = "www.google.com";
   var parameters = {};
   parameters.mobile = '7838185123';
   parameters.shit = 'xxx';

    createURLwithParameters(baseURL,parameters).should.equal('www.google.com?mobile=7838185123&shit=xxx');
  });

  it('converts base url to complete;', function() {
    var baseURL = "www.google.com";
   var parameters = {};

    createURLwithParameters(baseURL,parameters).should.equal('www.google.com');
  });
});

<|endoftext|>


<commit_before>/* jshint node: true */

'use strict';

var express = require('express'),
    router = express.Router(),
    mongoose = require('mongoose'), //mongo connection
    bodyParser = require('body-parser'), //parses information from POST
    methodOverride = require('method-override'), //used to manipulate POST
    Promise = require('bluebird'),
    GameReposiory = require('../repository/game'),
    aFunction;

router.use(bodyParser.urlencoded({ extended: true }));
router.use(methodOverride(function(req, res) {
    var method;
    if (req.body && typeof req.body === 'object' && '_method' in req.body) {
        // look in urlencoded POST bodies and delete it
        method = req.body._method;
        delete req.body._method;
        return method;
    }
}));

aFunction = function(param) {
    return new Promise(function(resolve, reject) {

        if (param === 2) {
            resolve('param was 2');
        }
        else {
            reject('param was not 2');
        }

    });
};

// route middleware to validate :gameId and add it to the req-object
router.param('gameId', function(req, res, next, gameId) {
    // @todo gameId validation
    req.gameId = gameId;
    next();
});

router.route('/')
    // GET
    .get(function(req, res, next) {
        var moveData = {
            x: 5,
            y: 6,
            username: 'spieler 1',
            gameId: '1444404958379'
        };
        GameReposiory.getGame(moveData.gameId, 'finished', moveData.username).then(function(game) {
            // resolve callback

            // making the move
            game.makeMove(moveData);

            game.checkForWin(moveData);

            res.format({
                json: function() {
                    res.json({
                        route: 'GET /dev',
                        message: 'success'
                    });
                }
            });
        }, function(error) {
            // error callback
            res.format({
                json: function() {
                    res.json({
                        route: 'GET /dev',
                        message: 'getGame() failed'
                    });
                }
            });
        });

    })
    // POST
    .post(function(req, res) {
        res.format({
            json: function() {
                res.json({
                    route: 'POST /dev',
                    payload: req.body
                });
            }
        });
    });

router.route('/:gameId')
    // PUT
    .put(function(req, res) {
        res.format({
            json: function() {
                res.json({
                    route: 'PUT /dev',
                    payload: this.gameId
                });
            }
        });

    });

module.exports = router;<commit_msg>code cleaning<commit_after>/* jshint node: true */

'use strict';

var express = require('express'),
    router = express.Router(),
    mongoose = require('mongoose'), //mongo connection
    bodyParser = require('body-parser'), //parses information from POST
    methodOverride = require('method-override'), //used to manipulate POST
    Promise = require('bluebird'),
    GameReposiory = require('../repository/game'),
    aFunction;

router.use(bodyParser.urlencoded({ extended: true }));
router.use(methodOverride(function(req, res) {
    var method;
    if (req.body && typeof req.body === 'object' && '_method' in req.body) {
        // look in urlencoded POST bodies and delete it
        method = req.body._method;
        delete req.body._method;
        return method;
    }
}));

aFunction = function(param) {
    return new Promise(function(resolve, reject) {

        if (param === 2) {
            resolve('param was 2');
        }
        else {
            reject('param was not 2');
        }

    });
};

// route middleware to validate :gameId and add it to the req-object
router.param('gameId', function(req, res, next, gameId) {
    req.gameId = gameId;
    next();
});

router.route('/')
    // GET
    .get(function(req, res, next) {
        var moveData = {
            x: 5,
            y: 6,
            username: 'spieler 1',
            gameId: '1444404958379'
        };
        GameReposiory.getGame(moveData.gameId, 'finished', moveData.username).then(function(game) {
            // resolve callback

            // making the move
            game.makeMove(moveData);

            game.checkForWin(moveData);

            res.format({
                json: function() {
                    res.json({
                        route: 'GET /dev',
                        message: 'success'
                    });
                }
            });
        }, function(error) {
            // error callback
            res.format({
                json: function() {
                    res.json({
                        route: 'GET /dev',
                        message: 'getGame() failed'
                    });
                }
            });
        });

    })
    // POST
    .post(function(req, res) {
        res.format({
            json: function() {
                res.json({
                    route: 'POST /dev',
                    payload: req.body
                });
            }
        });
    });

router.route('/:gameId')
    // PUT
    .put(function(req, res) {
        res.format({
            json: function() {
                res.json({
                    route: 'PUT /dev',
                    payload: this.gameId
                });
            }
        });

    });

module.exports = router;<|endoftext|>


<commit_before>angular.module('jp.ng-bs-animated-button', []).
  directive('jpNgBsAnimatedButton', function($timeout) {
    return {
      restrict: 'AE',
      replace: true,
      scope: {
        progressIsSubmit: '=',
        progressIsComplete: '=',
        formIsInvalid: '=',
        animationCompleteTime: '@',
        buttonClass: '@',
        buttonText: '@'
      },
      template:
        '<button type="submit" class="btn {{buttonClass}} btn-ng-bs-animated clearfix" ng-disabled="formIsInvalid">' +
          '
' +
            '' +
            '' +
          '
' +
          '
{{buttonText}}
' +
        '</button>',
      link: function(scope, element) {
        var el = element;
        var iconSubmitting = el.find('[data-icon="submitting"]');
        var iconComplete = el.find('[data-icon="complete"]');
        var endAnimation = function() {
          el.removeClass('is-active').attr('disabled', false);
          iconComplete.hide();
          scope.progressIsComplete = false;
        };
        scope.$watch('progressIsSubmit', function(newValue) {
            if (newValue) {
              el.attr('disabled', true).addClass('is-active');
              iconSubmitting.show();
            }
          }, true).bind(this);
        scope.$watch('progressIsComplete', function(newValue) {
            if (newValue) {
              iconSubmitting.hide();
              iconComplete.show();
              scope.progressIsSubmit = false;
              $timeout(endAnimation, scope.animationCompleteTime);
            }
          }, true).bind(this);
      }
    };
  });
<commit_msg>Update ng-bs-animated-button.js<commit_after>angular.module('jp.ng-bs-animated-button', []).
  directive('jpNgBsAnimatedButton', function($timeout) {
    return {
      restrict: 'AE',
      replace: true,
      scope: {
        progressIsSubmit: '=',
        progressIsComplete: '=',
        formIsInvalid: '=',
        animationCompleteTime: '@',
        buttonClass: '@',
        buttonText: '@'
      },
      template:
        '<button type="submit" class="btn {{buttonClass}} btn-ng-bs-animated clearfix" ng-disabled="formIsInvalid">' +
          '
' +
            '' +
            '' +
          '
' +
          '
{{buttonText}}
' +
        '</button>',
      link: function(scope, element) {
        var el = angular.element(element);
        var iconSubmitting = angular.element(el[0].querySelector('.icon-submit'));
        var iconComplete = angular.element(el[0].querySelector('.icon-complete'));
        var endAnimation = function() {
          el.removeClass('is-active').attr('disabled', false);
          iconComplete.addClass('hidden');
          scope.progressIsComplete = false;
        };
        scope.$watch('progressIsSubmit', function(newValue) {
            if (newValue) {
              el.attr('disabled', true).addClass('is-active');
              iconSubmitting.removeClass('hidden');
            }
          }, true).bind(this);
        scope.$watch('progressIsComplete', function(newValue) {
            if (newValue) {
              iconSubmitting.addClass('hidden');
              iconComplete.removeClass('hidden');
              scope.progressIsSubmit = false;
              $timeout(endAnimation, scope.animationCompleteTime);
            }
          }, true).bind(this);
      }
    };
  });
<|endoftext|>


<commit_before>var path = require('path');
var helpers = require('yeoman-generator').test;
var assert = require('yeoman-generator').assert;
var fs = require('fs-extra');

describe('donejs-cordova', function() {
  describe('when no build.js exists', function() {
    before(function(done) {
      helpers.run(path.join(__dirname, '../default'))
        .withPrompts({
          name: 'Foo',
          id: 'com.bar.foo',
          platforms: ['test']
        }).on('end', done);
    });

    it('should write build.js and add os specific platforms', function() {
      assert.file(['build.js']);
      assert.fileContent('build.js', /id: "com\.bar\.foo"/);
      assert.fileContent('build.js', /name: "Foo"/);
      assert.fileContent('build.js', /platforms: \["test"\]/);
    });
  });

  describe('when build.js was already created by generator-donejs', function() {
    before(function(done) {
      helpers.run(path.join(__dirname, '../default'))
      .inTmpDir(function(dir) {
        var done = this.async();
        fs.copy(path.join(__dirname, 'templates/generator-donejs'), dir, done);
      })
      .withPrompts({
        name: 'Foo',
        id: 'com.bar.foo',
        platforms: ['test']
      }).on('end', done);
    });

    it('should add cordovaOptions to build.js', function() {
      assert.file(['build.js']);
      assert.fileContent('build.js', /generator-donejs build\.js/);
      assert.fileContent('build.js', /id: "com\.bar\.foo"/);
      assert.fileContent('build.js', /name: "Foo"/);
      assert.fileContent('build.js', /platforms: \["test"\]/);
    });
  });

  describe('when build.js was already created by generator-donejs and updated by donejs-cordvoa', function() {
    before(function(done) {
      helpers.run(path.join(__dirname, '../default'))
      .inTmpDir(function(dir) {
        var done = this.async();
        fs.copy(path.join(__dirname, 'templates/donejs-cordova'), dir, done);
      })
      .withPrompts({
        name: 'Foo',
        id: 'com.bar.foo'
      }).on('end', done);
    });

    it('should not overwrite build.js', function() {
      assert.file(['build.js']);
      assert.fileContent('build.js', /generator-donejs \+ donejs-cordova build\.js/);
      assert.fileContent('build.js', /id: "com\.bar\.foo\.existing"/);
      assert.fileContent('build.js', /name: "Existing Foo"/);
    });
  });

  describe("when android is chosen as the platform", function() {
    before(function(done){
        helpers.run(path.join(__dirname, "../default"))
        .inTmpDir(function(dir){
          var done = this.async();
          fs.copy(path.join(__dirname, 'templates/donejs-cordova2'), dir, done);
        })
        .withPrompts({
          name: 'AndroidFoo',
          id: 'com.bar.android',
          platforms: ['android']
        }).on('end', done);
    })

    it('should write out to launch the android emulator', function() {
      assert.file(['build.js']);
      assert.fileContent('build.js', /android\.emulate/);
    });
  });
});
<commit_msg>Fix lint errors<commit_after>var path = require('path');
var helpers = require('yeoman-generator').test;
var assert = require('yeoman-generator').assert;
var fs = require('fs-extra');

describe('donejs-cordova', function() {
  describe('when no build.js exists', function() {
    before(function(done) {
      helpers.run(path.join(__dirname, '../default'))
        .withPrompts({
          name: 'Foo',
          id: 'com.bar.foo',
          platforms: ['test']
        }).on('end', done);
    });

    it('should write build.js and add os specific platforms', function() {
      assert.file(['build.js']);
      assert.fileContent('build.js', /id: "com\.bar\.foo"/);
      assert.fileContent('build.js', /name: "Foo"/);
      assert.fileContent('build.js', /platforms: \["test"\]/);
    });
  });

  describe('when build.js was already created by generator-donejs', function() {
    before(function(done) {
      helpers.run(path.join(__dirname, '../default'))
      .inTmpDir(function(dir) {
        var done = this.async();
        fs.copy(path.join(__dirname, 'templates/generator-donejs'), dir, done);
      })
      .withPrompts({
        name: 'Foo',
        id: 'com.bar.foo',
        platforms: ['test']
      }).on('end', done);
    });

    it('should add cordovaOptions to build.js', function() {
      assert.file(['build.js']);
      assert.fileContent('build.js', /generator-donejs build\.js/);
      assert.fileContent('build.js', /id: "com\.bar\.foo"/);
      assert.fileContent('build.js', /name: "Foo"/);
      assert.fileContent('build.js', /platforms: \["test"\]/);
    });
  });

  describe('when build.js was already created by generator-donejs and updated by donejs-cordvoa', function() {
    before(function(done) {
      helpers.run(path.join(__dirname, '../default'))
      .inTmpDir(function(dir) {
        var done = this.async();
        fs.copy(path.join(__dirname, 'templates/donejs-cordova'), dir, done);
      })
      .withPrompts({
        name: 'Foo',
        id: 'com.bar.foo'
      }).on('end', done);
    });

    it('should not overwrite build.js', function() {
      assert.file(['build.js']);
      assert.fileContent('build.js', /generator-donejs \+ donejs-cordova build\.js/);
      assert.fileContent('build.js', /id: "com\.bar\.foo\.existing"/);
      assert.fileContent('build.js', /name: "Existing Foo"/);
    });
  });

  describe("when android is chosen as the platform", function() {
    before(function(done){
        helpers.run(path.join(__dirname, "../default"))
        .inTmpDir(function(dir){
          var done = this.async();
          fs.copy(path.join(__dirname, 'templates/donejs-cordova2'), dir, done);
        })
        .withPrompts({
          name: 'AndroidFoo',
          id: 'com.bar.android',
          platforms: ['android']
        }).on('end', done);
    });

    it('should write out to launch the android emulator', function() {
      assert.file(['build.js']);
      assert.fileContent('build.js', /android\.emulate/);
    });
  });
});
<|endoftext|>


<commit_before>module.exports = function (app) {

    var Util = require("../util");
    var skinChanger = require("../generator/skinChanger");

    // Schemas
    var Account = require("../db/schemas/account").Account;
    var Skin = require("../db/schemas/skin").Skin;
    var Traffic = require("../db/schemas/traffic").Traffic;
    var Stat = require("../db/schemas/stat").Stat;

    app.get("/get/delay", function (req, res) {
        var ip = req.realAddress;
        Util.getGeneratorDelay().then(function (delay) {
            Traffic.findOne({ip: ip}, function (err, traffic) {
                if (err) return console.log(err);
                if (traffic) {
                    res.json({delay: delay, next: (traffic.lastRequest.getTime() / 1000) + delay, nextRelative: ((traffic.lastRequest.getTime() / 1000) + delay) - (Date.now() / 1000)});
                } else {
                    res.json({delay: delay, next: Date.now() / 1000, nextRelative: 0});
                }
            })
        })
    })

    app.get("/get/stats/:details?", function (req, res) {
        var stats = {};

        Util.getGeneratorDelay().then(function (delay) {
            stats.delay = delay;

            // Skin.find({}, "duplicate views visibility time name type via generateDuration", function (err, skins) {
            //     if (err) return console.log(err);
            //     var skinStats = buildSkinStats(skins);
            //     Object.assign(stats, skinStats);
            //
            //     Account.count({enabled: true}, function (err, count) {
            //         if (err) return console.log(err);
            //         stats.accounts = count;
            //
            //         Stat.find({}, function (err, s) {
            //             var generateSuccess = 0;
            //             var generateFail = 0;
            //             s.forEach(function (stat) {
            //                 if (stat.key === "generate.success") generateSuccess = stat.value;
            //                 if (stat.key === "generate.fail") generateFail = stat.value;
            //             })
            //
            //             var generateTotal = generateSuccess + generateFail;
            //             stats.successRate = Number((generateSuccess / generateTotal).toFixed(3));
            //
            //             res.json(stats);
            //         })
            //     })
            // })

            Account.count({enabled: true}, function (err, count) {
                if (err) return console.log(err);
                stats.accounts = count;
                Stat.find({$or: [{key: "generate.success"}, {key: "generate.fail"}]}, function (err, s) {
                    if (err) return console.log(err);
                    var generateSuccess = 0;
                    var generateFail = 0;
                    s.forEach(function (stat) {
                        if (stat.key === "generate.success") generateSuccess = stat.value;
                        if (stat.key === "generate.fail") generateFail = stat.value;
                    })
                    var generateTotal = generateSuccess + generateFail;
                    stats.successRate = Number((generateSuccess / generateTotal).toFixed(3));

                    Skin.aggregate([
                        {
                            "$group":
                                {
                                    _id: "$type",
                                    duplicate: {$sum: "$duplicate"},
                                    views: {$sum: "$views"},
                                    count: {$sum: 1}
                                }
                        }
                    ], function (err, agg) {
                        if (err) return console.log(err);
                        var user = agg[0];
                        var url = agg[1];
                        var upload = agg[2];

                        stats.genUpload = upload.count;
                        stats.genUrl = url.count;
                        stats.genUser = user.count;

                        stats.unique = user.count + url.count + upload.count;

                        stats.duplicate = user.duplicate + url.duplicate + upload.duplicate;
                        stats.views = user.views + url.views + upload.views;
                        stats.private = 0;
                        stats.withNames = 0;

                        stats.lastHour = 0;
                        stats.lastDay = 0;
                        stats.lastMonth = 0;
                        stats.lastYear = 0;

                        stats.viaApi = 0;
                        stats.viaWebsite = 0;

                        stats.total = stats.unique + stats.duplicate;

                        res.json(stats);
                    })
                })
            })

        })
    });

    function buildSkinStats(skins) {
        var lastHour = new Date(new Date() - 3.6e+6) / 1000;
        var lastDay = new Date(new Date() - 8.64e+7) / 1000;
        var lastMonth = new Date(new Date() - 2.628e+9) / 1000;
        var lastYear = new Date(new Date() - 3.154e+10) / 1000;

        var stats = {};

        stats.unique = skins.length;

        stats.duplicate = 0;
        stats.views = 0;
        stats.private = 0;
        stats.withNames = 0;

        stats.lastHour = 0;
        stats.lastDay = 0;
        stats.lastMonth = 0;
        stats.lastYear = 0;

        stats.genUpload = 0;
        stats.genUrl = 0;
        stats.genUser = 0;

        stats.viaApi = 0;
        stats.viaWebsite = 0;

        var totalDuration = 0;
        skins.forEach(function (skin) {
            stats.duplicate += skin.duplicate;
            stats.views += skin.views;
            if (skin.visibility !== 0) stats.private++;
            if (skin.name && skin.name.length > 0) stats.withNames++;

            if (skin.time > lastHour) stats.lastHour++;
            if (skin.time > lastDay) stats.lastDay++;
            if (skin.time > lastMonth) stats.lastMonth++;
            if (skin.time > lastYear) stats.lastYear++;

            if (skin.type === "upload") stats.genUpload++;
            if (skin.type === "url") stats.genUrl++;
            if (skin.type === "user") stats.genUser++;

            if (skin.via === "api") stats.viaApi++;
            if (skin.via === "website") stats.viaWebsite++;

            if (skin.generateDuration)
                totalDuration += skin.generateDuration;
        });
        stats.total = stats.unique + stats.duplicate;

        stats.avgDuration = Number((totalDuration / skins.length).toFixed(4));

        return stats;
    }

    app.get("/get/id/:id", function (req, res) {
        Skin.findOne({id: req.params.id}, function (err, skin) {
            if (err) return console.log(err);
            if (skin) {
                skin.views += 1;
                skin.save(function (err, skin) {
                    if (err) return console.log(err);
                    res.json(Util.skinToJson(skin, 0));
                })
            } else {
                res.status(404).json({error: "Skin not found"});
            }
        })
    })

    app.get("/get/list/:page?", function (req, res) {
        var page = Math.max(req.params.page || 1, 1);
        var size = Math.max(req.query.size || 16, 1);
        var sort = req.query.sort || -1;

        var query = {visibility: 0};
        if (req.query.filter) {
            query.name = {'$regex': ".*" + req.query.filter + ".*"};
        }
        Skin.count(query, function (err, count) {
            if (err) return console.log(err);
            Skin
                .find(query)
                .skip(size * (page - 1))
                .limit(size)
                .select({'_id': 0, id: 1, name: 1, url: 1})
                .sort({id: sort})
                .exec(function (err, skins) {
                    if (err) return console.log(err)

                    res.json({
                        skins: skins,
                        page: {
                            index: page,
                            amount: Math.round(count / size),
                            total: count
                        },
                        filter: req.query.filter
                    })
                })
        })

    })

};<commit_msg>add the last* stats again - using aggregation this time, to hopefully not run out of memory all the time<commit_after>module.exports = function (app) {

    var Util = require("../util");
    var skinChanger = require("../generator/skinChanger");

    // Schemas
    var Account = require("../db/schemas/account").Account;
    var Skin = require("../db/schemas/skin").Skin;
    var Traffic = require("../db/schemas/traffic").Traffic;
    var Stat = require("../db/schemas/stat").Stat;

    app.get("/get/delay", function (req, res) {
        var ip = req.realAddress;
        Util.getGeneratorDelay().then(function (delay) {
            Traffic.findOne({ip: ip}, function (err, traffic) {
                if (err) return console.log(err);
                if (traffic) {
                    res.json({delay: delay, next: (traffic.lastRequest.getTime() / 1000) + delay, nextRelative: ((traffic.lastRequest.getTime() / 1000) + delay) - (Date.now() / 1000)});
                } else {
                    res.json({delay: delay, next: Date.now() / 1000, nextRelative: 0});
                }
            })
        })
    })

    app.get("/get/stats/:details?", function (req, res) {
        var stats = {};

        Util.getGeneratorDelay().then(function (delay) {
            stats.delay = delay;

            // Skin.find({}, "duplicate views visibility time name type via generateDuration", function (err, skins) {
            //     if (err) return console.log(err);
            //     var skinStats = buildSkinStats(skins);
            //     Object.assign(stats, skinStats);
            //
            //     Account.count({enabled: true}, function (err, count) {
            //         if (err) return console.log(err);
            //         stats.accounts = count;
            //
            //         Stat.find({}, function (err, s) {
            //             var generateSuccess = 0;
            //             var generateFail = 0;
            //             s.forEach(function (stat) {
            //                 if (stat.key === "generate.success") generateSuccess = stat.value;
            //                 if (stat.key === "generate.fail") generateFail = stat.value;
            //             })
            //
            //             var generateTotal = generateSuccess + generateFail;
            //             stats.successRate = Number((generateSuccess / generateTotal).toFixed(3));
            //
            //             res.json(stats);
            //         })
            //     })
            // })

            Account.count({enabled: true}, function (err, count) {
                if (err) return console.log(err);
                stats.accounts = count;
                Stat.find({$or: [{key: "generate.success"}, {key: "generate.fail"}]}, function (err, s) {
                    if (err) return console.log(err);
                    var generateSuccess = 0;
                    var generateFail = 0;
                    s.forEach(function (stat) {
                        if (stat.key === "generate.success") generateSuccess = stat.value;
                        if (stat.key === "generate.fail") generateFail = stat.value;
                    })
                    var generateTotal = generateSuccess + generateFail;
                    stats.successRate = Number((generateSuccess / generateTotal).toFixed(3));

                    Skin.aggregate([
                        {
                            "$group":
                                {
                                    _id: "$type",
                                    duplicate: {$sum: "$duplicate"},
                                    views: {$sum: "$views"},
                                    count: {$sum: 1}
                                }
                        }
                    ], function (err, agg) {
                        if (err) return console.log(err);
                        var user = agg[0];
                        var url = agg[1];
                        var upload = agg[2];

                        stats.genUpload = upload.count;
                        stats.genUrl = url.count;
                        stats.genUser = user.count;

                        stats.unique = user.count + url.count + upload.count;

                        stats.duplicate = user.duplicate + url.duplicate + upload.duplicate;
                        stats.views = user.views + url.views + upload.views;
                        stats.private = 0;
                        stats.withNames = 0;

                        stats.lastHour = 0;
                        stats.lastDay = 0;
                        stats.lastMonth = 0;
                        stats.lastYear = 0;

                        stats.viaApi = 0;
                        stats.viaWebsite = 0;

                        stats.total = stats.unique + stats.duplicate;

                        if (req.params.details) {
                            var lastHour = new Date(new Date() - 3.6e+6) / 1000;
                            var lastDay = new Date(new Date() - 8.64e+7) / 1000;
                            var lastMonth = new Date(new Date() - 2.628e+9) / 1000;
                            var lastYear = new Date(new Date() - 3.154e+10) / 1000;

                            Skin.aggregate([
                                {
                                    $group: {
                                        _id: null,
                                        lastYear: {$sum: {$cond: [{$gte: ["$time", lastYear]}, 1, 0]}},
                                        lastMonth: {$sum: {$cond: [{$gte: ["$time", lastMonth]}, 1, 0]}},
                                        lastDay: {$sum: {$cond: [{$gte: ["$time", lastDay]}, 1, 0]}},
                                        lastHour: {$sum: {$cond: [{$gte: ["$time", lastHour]}, 1, 0]}}
                                    }
                                }
                            ], function (err, agg1) {
                                if (err) return console.log(err);

                                stats.lastYear = agg1[0].lastYear;
                                stats.lastMonth = agg1[0].lastMonth;
                                stats.lastDay = agg1[0].lastDay;
                                stats.lastHour = agg1[0].lastHour;

                                res.json(stats);
                            })

                        } else {
                            res.json(stats);
                        }
                    })
                })
            })

        })
    });

    function buildSkinStats(skins) {
        var lastHour = new Date(new Date() - 3.6e+6) / 1000;
        var lastDay = new Date(new Date() - 8.64e+7) / 1000;
        var lastMonth = new Date(new Date() - 2.628e+9) / 1000;
        var lastYear = new Date(new Date() - 3.154e+10) / 1000;

        var stats = {};

        stats.unique = skins.length;

        stats.duplicate = 0;
        stats.views = 0;
        stats.private = 0;
        stats.withNames = 0;

        stats.lastHour = 0;
        stats.lastDay = 0;
        stats.lastMonth = 0;
        stats.lastYear = 0;

        stats.genUpload = 0;
        stats.genUrl = 0;
        stats.genUser = 0;

        stats.viaApi = 0;
        stats.viaWebsite = 0;

        var totalDuration = 0;
        skins.forEach(function (skin) {
            stats.duplicate += skin.duplicate;
            stats.views += skin.views;
            if (skin.visibility !== 0) stats.private++;
            if (skin.name && skin.name.length > 0) stats.withNames++;

            if (skin.time > lastHour) stats.lastHour++;
            if (skin.time > lastDay) stats.lastDay++;
            if (skin.time > lastMonth) stats.lastMonth++;
            if (skin.time > lastYear) stats.lastYear++;

            if (skin.type === "upload") stats.genUpload++;
            if (skin.type === "url") stats.genUrl++;
            if (skin.type === "user") stats.genUser++;

            if (skin.via === "api") stats.viaApi++;
            if (skin.via === "website") stats.viaWebsite++;

            if (skin.generateDuration)
                totalDuration += skin.generateDuration;
        });
        stats.total = stats.unique + stats.duplicate;

        stats.avgDuration = Number((totalDuration / skins.length).toFixed(4));

        return stats;
    }

    app.get("/get/id/:id", function (req, res) {
        Skin.findOne({id: req.params.id}, function (err, skin) {
            if (err) return console.log(err);
            if (skin) {
                skin.views += 1;
                skin.save(function (err, skin) {
                    if (err) return console.log(err);
                    res.json(Util.skinToJson(skin, 0));
                })
            } else {
                res.status(404).json({error: "Skin not found"});
            }
        })
    })

    app.get("/get/list/:page?", function (req, res) {
        var page = Math.max(req.params.page || 1, 1);
        var size = Math.max(req.query.size || 16, 1);
        var sort = req.query.sort || -1;

        var query = {visibility: 0};
        if (req.query.filter) {
            query.name = {'$regex': ".*" + req.query.filter + ".*"};
        }
        Skin.count(query, function (err, count) {
            if (err) return console.log(err);
            Skin
                .find(query)
                .skip(size * (page - 1))
                .limit(size)
                .select({'_id': 0, id: 1, name: 1, url: 1})
                .sort({id: sort})
                .exec(function (err, skins) {
                    if (err) return console.log(err)

                    res.json({
                        skins: skins,
                        page: {
                            index: page,
                            amount: Math.round(count / size),
                            total: count
                        },
                        filter: req.query.filter
                    })
                })
        })

    })

};<|endoftext|>


<commit_before>'use strict';

//TODO: add to double click google maps DOM event listener

function clickStateInfo(e) {

  let clickedState = Data.all.filter((data) => data.state === e.target );
  console.log(clickedState);
  }

map.addListener('dblclick', clickStateInfo(e));

geocodeLatLng(geocoder, map, infowindow);

function geocodeLatLng(geocoder, map, infowindow) {
  var input = document.getElementById('latlng').value;
  var latlngStr = input.split(',', 2);
  var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
  geocoder.geocode({'location': latlng}, function(results, status) {
    if (status === 'OK') {
      if (results[6]) {
        map.setZoom(11);
        var marker = new google.maps.Marker({
          position: latlng,
          map: map
        });
        infowindow.setContent(results[6].formatted_address);
        infowindow.open(map, marker);
      } else {
        window.alert('No results found');
      }
    } else {
      window.alert('Geocoder failed due to: ' + status);
    }
  });
}
<commit_msg>commit to rebase master in branch<commit_after>'use strict';

//TODO: add to double click google maps DOM event listener

function clickStateInfo(e) {

  let clickedState = Data.all.filter((data) => data.state === e.target );
  console.log(clickedState);
}
<|endoftext|>


<commit_before>'use strict';

var chai = require('chai'),
    should = chai.should(),
    expect = chai.expect,
    spies = require('chai-spies'),
    hackerfire = require('../index');

describe('top stories', function() {

  beforeEach(function(){
    chai.use(spies);
  });

  it('should return a list of top stories', function() {

    hackerfire.getTopStories(function(res) {
      expect(res).to.not.be.undefined;
    });
  });

});

describe('users', function() {

  beforeEach(function(){
    chai.use(spies);
  });

  it('should return a list of users with a single string input', function() {

    hackerfire.getUserById('mot0rola', function(res) {
      expect(res).to.not.be.undefined;
    });

  });

  it('should return a list of users with an array input of users', function() {

    hackerfire.getUserById(['pg', 'mot0rola'], function(res) {
      expect(res).to.not.be.undefined;
    });

  });

});

describe('item', function() {

  beforeEach(function(){
    chai.use(spies);
  });

  it('should return a list of items with a single string input', function() {

    hackerfire.getUserById('8265435', function(res) {
      expect(res).to.not.be.undefined;
    });

  });

  it('should return a list of items with an array input of users', function() {

    hackerfire.getUserById([ '8265435', '8168423' ], function(res) {
      expect(res).to.not.be.undefined;
    });

  });

});
<commit_msg>use hackerfire npm package! :D<commit_after>'use strict';

var chai = require('chai'),
    should = chai.should(),
    expect = chai.expect,
    spies = require('chai-spies'),
    hackerfire = require('hackerfire');

describe('top stories', function() {

  beforeEach(function(){
    chai.use(spies);
  });

  it('should return a list of top stories', function() {

    hackerfire.getTopStories(function(res) {
      expect(res).to.not.be.undefined;
    });
  });

});

describe('users', function() {

  beforeEach(function(){
    chai.use(spies);
  });

  it('should return a list of users with a single string input', function() {

    hackerfire.getUserById('mot0rola', function(res) {
      expect(res).to.not.be.undefined;
    });

  });

  it('should return a list of users with an array input of users', function() {

    hackerfire.getUserById(['pg', 'mot0rola'], function(res) {
      expect(res).to.not.be.undefined;
    });

  });

});

describe('item', function() {

  beforeEach(function(){
    chai.use(spies);
  });

  it('should return a list of items with a single string input', function() {

    hackerfire.getUserById('8265435', function(res) {
      expect(res).to.not.be.undefined;
    });

  });

  it('should return a list of items with an array input of users', function() {

    hackerfire.getUserById([ '8265435', '8168423' ], function(res) {
      expect(res).to.not.be.undefined;
    });

  });

});
<|endoftext|>


<commit_before>'use strict';

var Job = require('../models/jobs_model');
var User = require('../models/user_model');

module.exports = function(app, jwtauth) {
  app.post('/jobs', jwtauth, function(req, res) {
    console.log('the user for this job post is: ' + req.user);
    console.log('the users name for this job post is: ' + req.user.name);
    var newJob = new Job({
      jobDate: req.body.jobDate,
      parent: req.user._id,
      recurring: req.body.recurring,
      parentName: req.user.name,
      parentNumber: req.user.phone
    });

    newJob.save(function(err, job) {
      if (err) return res.send(err);
      User.findById(req.user._id, function(err, user) {
        if (err) return console.log('error finding user by ID for New Job Save: ' + err);
        if (user === null) return console.log('user is null during New Job save.');
        user.jobs.push(job._id);
        user.save(function(err) {
          if (err) return console.log('error saving job to user array');
          console.log('successfully saved job to user array.');
        });
      });
      res.json(job);
    });
  });

  app.get('/jobs', jwtauth, function(req, res) {
    Job.find({parent:req.user._id}, function(err, jobs) {
      if (err) return res.json({msg: 'no jobs found'});
      res.json(jobs);
    });
  });

};
<commit_msg>job post wip<commit_after>'use strict';

var Job = require('../models/jobs_model');
var User = require('../models/user_model');

module.exports = function(app, jwtauth) {
  app.post('/jobs', jwtauth, function(req, res) {
    console.log('the user for this job post is: ' + req.user);
    console.log('the users first name for this job post is: ' + req.user.name.first);
    var newJob = new Job({
      jobDate: req.body.jobDate,
      parent: req.user._id,
      recurring: req.body.recurring,
      parentName: {first: req.user.name.first, last: req.user.name.last},
      parentNumber: req.user.phone
    });

    newJob.save(function(err, job) {
      if (err) return res.send(err);
      User.findById(req.user._id, function(err, user) {
        if (err) return console.log('error finding user by ID for New Job Save: ' + err);
        if (user === null) return console.log('user is null during New Job save.');
        user.jobs.push(job._id);
        user.save(function(err) {
          if (err) return console.log('error saving job to user array');
          console.log('successfully saved job to user array.');
        });
      });
      res.json(job);
    });
  });

  app.get('/jobs', jwtauth, function(req, res) {
    Job.find({parent:req.user._id}, function(err, jobs) {
      if (err) return res.json({msg: 'no jobs found'});
      res.json(jobs);
    });
  });

};
<|endoftext|>


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

'use strict';

var HyperbahnCluster = require('./lib/hyperbahn-cluster.js');

require('./errors.js');
require('./event_emitter.js');
require('./argstream.js');
require('./circuits.js');
require('./safe-quit.js');
require('./timeouts.js');
require('./send.js');
require('./retry.js');
require('./relay.js');
require('./streaming.js');
require('./streaming_bisect.js');
require('./register.js');
require('./identify.js');
require('./max_pending.js');
require('./tchannel.js');
require('./regression-inOps-leak.js');
require('./regression-listening-on-used-port.js');
require('./as-thrift.js');
require('./as-json.js');
require('./as-http.js');
require('./peer.js');
require('./peers.js');
require('./peer_states.js');
require('./streaming-resp-err.js');
require('./double-response.js');
require('./ping.js');
require('./request-stats.js');
require('./request-with-statsd.js');
require('./response-stats.js');
require('./response-with-statsd.js');
require('./ping.js');
require('./permissions_cache.js');
require('./connection-stats.js');
require('./connection-with-statsd.js');
require('./request-error-context.js');
require('./max-call-overhead.js');
require('./non-zero-ttl.js');
require('./examples.js');
require('./busy.js');
require('./ephemeral-client.js');
require('./relay-to-dead.js');
require('./rate-limiter.js');
require('./time_heap.js');

require('./trace/basic_server.js');
require('./trace/server_2_requests.js');
require('./trace/outpeer_span_handle.js');

require('./v2/frame.js');
require('./v2/init.js');
require('./v2/checksum.js');
require('./v2/header.js');
require('./v2/tracing.js');
require('./v2/call.js');
require('./v2/cancel.js');
require('./v2/cont.js');
require('./v2/claim.js');
require('./v2/ping.js');
require('./v2/error_response.js');
require('./v2/args.js');
require('./v2/lazy_frame.js');

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

'use strict';

var HyperbahnCluster = require('./lib/hyperbahn-cluster.js');

require('./errors.js');
require('./event_emitter.js');
require('./argstream.js');
require('./circuits.js');
require('./safe-quit.js');
require('./timeouts.js');
require('./send.js');
require('./retry.js');
require('./relay.js');
require('./streaming.js');
require('./streaming_bisect.js');
require('./register.js');
require('./identify.js');
require('./max_pending.js');
require('./tchannel.js');
require('./regression-inOps-leak.js');
require('./regression-listening-on-used-port.js');
require('./as-thrift.js');
require('./as-json.js');
require('./as-http.js');
require('./peer.js');
require('./peers.js');
require('./peer_states.js');
require('./streaming-resp-err.js');
require('./double-response.js');
require('./ping.js');
require('./request-stats.js');
require('./request-with-statsd.js');
require('./response-stats.js');
require('./response-with-statsd.js');
require('./ping.js');
require('./permissions_cache.js');
require('./connection-stats.js');
require('./connection-with-statsd.js');
require('./request-error-context.js');
require('./max-call-overhead.js');
require('./non-zero-ttl.js');
require('./examples.js');
require('./busy.js');
require('./ephemeral-client.js');
require('./relay-to-dead.js');
require('./rate-limiter.js');
require('./time_heap.js');
require('./balance_peer_requests.js');
require('./tcollector-reporter.js');

require('./trace/basic_server.js');
require('./trace/server_2_requests.js');
require('./trace/outpeer_span_handle.js');

require('./v2/frame.js');
require('./v2/init.js');
require('./v2/checksum.js');
require('./v2/header.js');
require('./v2/tracing.js');
require('./v2/call.js');
require('./v2/cancel.js');
require('./v2/cont.js');
require('./v2/claim.js');
require('./v2/ping.js');
require('./v2/error_response.js');
require('./v2/args.js');
require('./v2/lazy_frame.js');

require('./hyperbahn/')(HyperbahnCluster);
<|endoftext|>


<commit_before>exports.tile = function(req, res) {
    "use strict";

    var path = __dirname + '../static/map_tiles/' + req.params.x +
               '/' + req.params.y +
               '/' + req.params.zoom + '.png';

    res.sendfile(path, function(err) {
        console.dir(err);
    });
};<commit_msg>tile implementation<commit_after>var path = require('path');

exports.tile = function(req, res) {
    "use strict";

    var isInteger = function(string) {
        return isFinite(parseInt(string, 10));
    };

    var x = req.params.x,
        y = req.params.y,
        zoom = req.params.zoom;

    if (isInteger(x) && isInteger(y) && isInteger(zoom)) {

        var pathRoot = path.normalize(__dirname + '/../static/map_tiles/');
        var sendfileOptions = {root: pathRoot};
        var tilePath =  x + '/' + y + '/' + zoom + '.png';

        res.sendfile(tilePath, sendfileOptions, function(err) {
            if (err && err.status === 404) {
                res.sendfile('blank.png', sendfileOptions);
            }
        });
    } else {
        res.send(404);
    }
};<|endoftext|>