<commit_before>describe("Jasmine Test Runner", function() {

  it("Runs", function() {
    expect(true).toBeTruthy();
    expect(false).toBeFalsy();
    expect(42).toEqual(42);
  });

  describe("Pig Latin", function() {

    beforeEach(function() {
      // any startup code goes here
    });

    it("..first test goes here..", function() {
    });

  });

});

<commit_msg>Adding tests for first kata<commit_after>describe("Jasmine Test Runner", function() {

  it("Runs", function() {
    expect(true).toBeTruthy();
    expect(false).toBeFalsy();
    expect(42).toEqual(42);
  });

  describe("Pig Latin", function() {

    beforeEach(function() {
      // any startup code goes here
    });

    it("add 'way' to end of word that begins and ends with vowels", function() {
      expect(PigLatin.say('echo')).toEqual('echoway');
    });

    it("add 'ay' to end of word that begins with vowel and ends in a consonant", function() {
      expect(PigLatin.say('eight')).toEqual('eightay');
    });

    it("empty string stays empty", function() {
      expect(PigLatin.say('')).toEqual('');
    });

    it("move beginning consonant to the end and add 'ay'", function(){
      expect(PigLatin.say("pizza")).toEqual("izzapay");
    });

    it("move multiple consonants to end + 'ay'", function(){
      expect(PigLatin.say("school")).toEqual("oolschay");
    });

  });

});
<|endoftext|>


<commit_before>"use strict";
const rx_1 = require('rxjs/rx');
const operation_1 = require('./operation');
class PagedResult {
}
exports.PagedResult = PagedResult;
class ODataQuery extends operation_1.ODataOperation {
    constructor(_typeName, config, http) {
        super(_typeName, config, http);
    }
    Filter(filter) {
        this._filter = filter;
        return this;
    }
    ;
    Top(top) {
        this._top = top;
        return this;
    }
    ;
    Skip(skip) {
        this._skip = skip;
        return this;
    }
    OrderBy(orderBy) {
        this._orderBy = orderBy;
        return this;
    }
    Exec() {
        let params = this.getQueryParams();
        let config = this.config;
        return this.http.get(this.buildResourceURL(), { search: params })
            .map(res => this.extractArrayData(res, config))
            .catch((err, caught) => {
            if (this.config.handleError)
                this.config.handleError(err, caught);
            return rx_1.Observable.throw(err);
        });
    }
    ExecWithCount() {
        let params = this.getQueryParams();
        params.set('$count', 'true'); // OData v4 only
        let config = this.config;
        return this.http.get(this.buildResourceURL(), { search: params })
            .map(res => this.extractArrayDataWithCount(res, config))
            .catch((err, caught) => {
            if (this.config.handleError)
                this.config.handleError(err, caught);
            return rx_1.Observable.throw(err);
        });
    }
    buildResourceURL() {
        return this.config.baseUrl + '/' + this._typeName + '/';
    }
    getQueryParams() {
        let params = super.getParams();
        if (this._filter)
            params.set(this.config.keys.filter, this._filter);
        if (this._top)
            params.set(this.config.keys.top, this._top.toString());
        if (this._skip)
            params.set(this.config.keys.skip, this._skip.toString());
        if (this._orderBy)
            params.set(this.config.keys.orderBy, this._orderBy);
        return params;
    }
    extractArrayData(res, config) {
        return config.extractQueryResultData(res);
    }
    extractArrayDataWithCount(res, config) {
        return config.extractQueryResultDataWithCount(res);
    }
}
exports.ODataQuery = ODataQuery;
//# sourceMappingURL=query.js.map<commit_msg>Update query.js<commit_after>"use strict";
const rx_1 = require('rxjs/Rx');
const operation_1 = require('./operation');
class PagedResult {
}
exports.PagedResult = PagedResult;
class ODataQuery extends operation_1.ODataOperation {
    constructor(_typeName, config, http) {
        super(_typeName, config, http);
    }
    Filter(filter) {
        this._filter = filter;
        return this;
    }
    ;
    Top(top) {
        this._top = top;
        return this;
    }
    ;
    Skip(skip) {
        this._skip = skip;
        return this;
    }
    OrderBy(orderBy) {
        this._orderBy = orderBy;
        return this;
    }
    Exec() {
        let params = this.getQueryParams();
        let config = this.config;
        return this.http.get(this.buildResourceURL(), { search: params })
            .map(res => this.extractArrayData(res, config))
            .catch((err, caught) => {
            if (this.config.handleError)
                this.config.handleError(err, caught);
            return rx_1.Observable.throw(err);
        });
    }
    ExecWithCount() {
        let params = this.getQueryParams();
        params.set('$count', 'true'); // OData v4 only
        let config = this.config;
        return this.http.get(this.buildResourceURL(), { search: params })
            .map(res => this.extractArrayDataWithCount(res, config))
            .catch((err, caught) => {
            if (this.config.handleError)
                this.config.handleError(err, caught);
            return rx_1.Observable.throw(err);
        });
    }
    buildResourceURL() {
        return this.config.baseUrl + '/' + this._typeName + '/';
    }
    getQueryParams() {
        let params = super.getParams();
        if (this._filter)
            params.set(this.config.keys.filter, this._filter);
        if (this._top)
            params.set(this.config.keys.top, this._top.toString());
        if (this._skip)
            params.set(this.config.keys.skip, this._skip.toString());
        if (this._orderBy)
            params.set(this.config.keys.orderBy, this._orderBy);
        return params;
    }
    extractArrayData(res, config) {
        return config.extractQueryResultData(res);
    }
    extractArrayDataWithCount(res, config) {
        return config.extractQueryResultDataWithCount(res);
    }
}
exports.ODataQuery = ODataQuery;
//# sourceMappingURL=query.js.map
<|endoftext|>


<commit_before>'use babel'

// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.
import assert from 'assert'
import fs from 'fs'
import Path from 'path'

// FIXME: FakeXMLHttpRequest is not working properly in atom 1.16.0-beta0
import FakeXMLHttpRequest from "fake-xml-http-request"

import {Range, Point} from'atom'

import AmnesiaIo from '../lib/amnesia-io'

let readFile = (path) => {
  return fs.readFileSync(Path.join(__dirname, "./fixtures/", path), "utf8")
}

let getEditor = () => {
  return atom.workspace.getActiveTextEditor()
}

let atomCommand = (editor, cmd) => {
  atom.commands.dispatch(atom.views.getView(editor), cmd)
}

let makeAssertions = function(requests, payload) {
  assert(!!requests[0])
  assert.equal(requests[0].method, 'POST')
  assert.equal(requests[0].requestHeaders['Content-Type'], 'application/json')
  assert.deepEqual(JSON.parse(requests[0].requestBody), payload)
}

describe('AmnesiaIo', function() {
  let requests

  beforeEach(function() {

    atom.packages.activatePackage('amnesia-io')
    editor = atom.workspace.getActiveTextEditor()

    requests = []

    global.XMLHttpRequest = () => {
      let r =  new FakeXMLHttpRequest(arguments)
      requests.push(r)
      return r
    }

  })

  describe('amnesia-io:share-file', function() {

    beforeEach(function() {
      waitsForPromise(function() {
        return atom.workspace.open('code.js')
      })
    })

    it('shares file content', function() {
      let payload = {
        content: readFile('code.js'),
        extension: 'js',
        ttl: 43200
      }

      let editor = getEditor()
      editor.setCursorBufferPosition([1, 1])

      atomCommand(editor, 'amnesia-io:share-file')
      makeAssertions(requests, payload)
    })
  })

  describe('amnesia-io:share-selection', function() {

    beforeEach(function() {
      waitsForPromise(function() {
        return atom.workspace.open('code.js')
      })
    })

    it('shares selected content', function() {
      let payload = {
        content: 'let test = true',
        extension: 'js',
        ttl: 43200
      }

      let editor = getEditor()
      let range = new Range(new Point(2, 0), new Point(2, 15))
      editor.setSelectedBufferRange(range)

      atomCommand(editor, 'amnesia-io:share-selected')
      makeAssertions(requests, payload)
    })
  })

  describe('amnesia-io:shareBlock', function() {

    beforeEach(function() {
      waitsForPromise(function() {
        return atom.workspace.open('code.js')
      })
    })

    it('shares selected content', function() {
      let payload = {
        content: 'let test = true\nlet thing = false\nlet somethingElse = 12',
        extension: 'js',
        ttl: 43200
      }

      let editor = getEditor()
      editor.setCursorBufferPosition([3, 1])

      atomCommand(editor, 'amnesia-io:share-block')
      makeAssertions(requests, payload)
    })
  })

  describe('amnesia-io:share-line', function() {
    beforeEach(function() {
      waitsForPromise(function() {
        return atom.workspace.open('code.js')
      })
    })

    it('shares the current line', function() {
      let payload = {
        content: 'let thing = false',
        extension: 'js',
        ttl: 43200
      }

      let editor = getEditor()
      editor.setCursorBufferPosition([3, 5])

      atomCommand(editor, 'amnesia-io:share-line')
      makeAssertions(requests, payload)
    })
  })

  describe('highlighting format', function() {

    describe('with extension', function() {

      beforeEach(function() {
        waitsForPromise(function() {
          return atom.workspace.open('code.js')
        })
      })

      it('gets format from file extension', function() {
        atomCommand(getEditor(), 'amnesia-io:share-file')
        assert.equal(JSON.parse(requests[0].requestBody).extension, 'js')
      })
    })

    describe('no extension', function() {

      beforeEach(function() {
        waitsForPromise(function() {
          return atom.workspace.open('no_extension')
        })
      })

      it('uses default format if no extension', function() {
        atomCommand(getEditor(), 'amnesia-io:share-file')
        assert.equal(JSON.parse(requests[0].requestBody).extension, 'bash')
      })

    })

  })
})
<commit_msg>make XMLHttpRequest replacement an actual constructor<commit_after>'use babel'

// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.
import assert from 'assert'
import fs from 'fs'
import Path from 'path'

// FIXME: FakeXMLHttpRequest is not working properly in atom 1.16.0-beta0
import FakeXMLHttpRequest from "fake-xml-http-request"

import {Range, Point} from'atom'

import AmnesiaIo from '../lib/amnesia-io'

let readFile = (path) => {
  return fs.readFileSync(Path.join(__dirname, "./fixtures/", path), "utf8")
}

let getEditor = () => {
  return atom.workspace.getActiveTextEditor()
}

let atomCommand = (editor, cmd) => {
  atom.commands.dispatch(atom.views.getView(editor), cmd)
}

let makeAssertions = function(requests, payload) {
  assert(!!requests[0])
  assert.equal(requests[0].method, 'POST')
  assert.equal(requests[0].requestHeaders['Content-Type'], 'application/json')
  assert.deepEqual(JSON.parse(requests[0].requestBody), payload)
}

describe('AmnesiaIo', function() {
  let requests

  beforeEach(function() {

    atom.packages.activatePackage('amnesia-io')
    editor = atom.workspace.getActiveTextEditor()

    requests = []

    global.XMLHttpRequest = function() {
      let r =  new FakeXMLHttpRequest(arguments)
      requests.push(r)
      return r
    }

  })

  describe('amnesia-io:share-file', function() {

    beforeEach(function() {
      waitsForPromise(function() {
        return atom.workspace.open('code.js')
      })
    })

    it('shares file content', function() {
      let payload = {
        content: readFile('code.js'),
        extension: 'js',
        ttl: 43200
      }

      let editor = getEditor()
      editor.setCursorBufferPosition([1, 1])

      atomCommand(editor, 'amnesia-io:share-file')
      makeAssertions(requests, payload)
    })
  })

  describe('amnesia-io:share-selection', function() {

    beforeEach(function() {
      waitsForPromise(function() {
        return atom.workspace.open('code.js')
      })
    })

    it('shares selected content', function() {
      let payload = {
        content: 'let test = true',
        extension: 'js',
        ttl: 43200
      }

      let editor = getEditor()
      let range = new Range(new Point(2, 0), new Point(2, 15))
      editor.setSelectedBufferRange(range)

      atomCommand(editor, 'amnesia-io:share-selected')
      makeAssertions(requests, payload)
    })
  })

  describe('amnesia-io:shareBlock', function() {

    beforeEach(function() {
      waitsForPromise(function() {
        return atom.workspace.open('code.js')
      })
    })

    it('shares selected content', function() {
      let payload = {
        content: 'let test = true\nlet thing = false\nlet somethingElse = 12',
        extension: 'js',
        ttl: 43200
      }

      let editor = getEditor()
      editor.setCursorBufferPosition([3, 1])

      atomCommand(editor, 'amnesia-io:share-block')
      makeAssertions(requests, payload)
    })
  })

  describe('amnesia-io:share-line', function() {
    beforeEach(function() {
      waitsForPromise(function() {
        return atom.workspace.open('code.js')
      })
    })

    it('shares the current line', function() {
      let payload = {
        content: 'let thing = false',
        extension: 'js',
        ttl: 43200
      }

      let editor = getEditor()
      editor.setCursorBufferPosition([3, 5])

      atomCommand(editor, 'amnesia-io:share-line')
      makeAssertions(requests, payload)
    })
  })

  describe('highlighting format', function() {

    describe('with extension', function() {

      beforeEach(function() {
        waitsForPromise(function() {
          return atom.workspace.open('code.js')
        })
      })

      it('gets format from file extension', function() {
        atomCommand(getEditor(), 'amnesia-io:share-file')
        assert.equal(JSON.parse(requests[0].requestBody).extension, 'js')
      })
    })

    describe('no extension', function() {

      beforeEach(function() {
        waitsForPromise(function() {
          return atom.workspace.open('no_extension')
        })
      })

      it('uses default format if no extension', function() {
        atomCommand(getEditor(), 'amnesia-io:share-file')
        assert.equal(JSON.parse(requests[0].requestBody).extension, 'bash')
      })

    })

  })
})
<|endoftext|>


<commit_before>var interpreter = require('../src/interpreter').Interpreter;
var library = require('../src/library').Library;

describe('library', function() {
  describe('write', function(){
    describe('Generic', function(){
      it('should print attributes', function() {
        var code = "pluto is a planet\npluto density is '3'\npluto radius is '7'\nwrite pluto";
        var env = interpreter.interpret(code);

        expect(env.ret).toEqual("a planet\n  density is '3'\n  radius is '7'\n");
      });

      it('should print attribute that is obj, too', function() {
        var code = "pluto is a planet\nneptune is a planet\nneptune density is '20'\npluto density is '3'\npluto neighbour is neptune\npluto radius is '6'\nwrite pluto";
        var env = interpreter.interpret(code);
        expect(env.ret).toEqual("a planet\n  density is '3'\n  neighbour is a planet\n    density is '20'\n  radius is '6'\n");
      });

      it('should print no attributes if Generic has none', function() {
        var code = "pluto is a planet\nwrite pluto";
        var env = interpreter.interpret(code);
        expect(env.ret).toEqual("a planet\n");
      });
    });

    describe('List', function(){
      it('should print elements of List', function() {
        var code = "l is a list\nadd 'a' to l\nadd 'b' to l\nwrite l";
        var env = interpreter.interpret(code);
        expect(env.ret).toEqual("a list\n  'a'\n  'b'\n");
      });

      it('should print element that is obj, too', function() {
        var code = "l is a list\nneptune is a planet\nneptune density is '1'\nadd '1' to l\nadd neptune to l\nadd '2' to l\nwrite l";
        var env = interpreter.interpret(code);
        expect(env.ret).toEqual("a list\n  '1'\n  a planet\n    density is '1'\n  '2'\n");
      });

      it('should indicate empty list has nothing in it', function() {
        var code = "l is a list\n\nwrite l";
        var env = interpreter.interpret(code);
        expect(env.ret).toEqual("an empty list");
      });
    });

    describe('clone', function() {
      describe('List', function(){
        it('should have two elements in clone that appear in original', function() {
          var l = new library.List();
          l.add("1");
          l.add("2");
          expect(library.clone(l).items()[0]).toEqual("1");
          expect(library.clone(l).items()[1]).toEqual("2");
          expect(library.clone(l) !== l).toEqual(true);
          expect(library.clone(l).constructor === library.List).toEqual(true);
        });

        it('should clone list inside list', function() {
          var l = new library.List();
          var innerL = new library.List();
          innerL.add("1");
          l.add(innerL);
          expect(library.clone(l).items()[0].items()[0]).toEqual("1");
          expect(library.clone(l).items()[0] !== innerL).toEqual(true);
          expect(library.clone(l).items()[0].constructor === library.List).toEqual(true);
        });

        it('should clone generic inside list', function() {
          var l = new library.List();
          var g = new library.Generic();
          g.la = "1";
          l.add(g);
          expect(library.clone(l).items()[0].la).toEqual("1");
          expect(library.clone(l) !== l).toEqual(true);
          expect(library.clone(l).items()[0].constructor === library.Generic).toEqual(true);
        });
      });

      describe('Generic', function(){
        it('should have two elements in clone that appear in original', function() {
          var g = new library.Generic();
          g.one = "1";
          g.two = "2";
          expect(library.clone(g).one).toEqual("1");
          expect(library.clone(g).two).toEqual("2");
          expect(library.clone(g) !== g).toEqual(true);
          expect(library.clone(g) instanceof library.Generic).toEqual(true);
        });

        it('should clone a list inside a generic', function() {
          var g = new library.Generic();
          var l = new library.List();
          l.add("1");
          g.l = l;
          expect(library.clone(g).l.items()[0]).toEqual("1");
          expect(library.clone(g).l !== l).toEqual(true);
          expect(library.clone(g).l.constructor === library.List).toEqual(true);
        });

        it('should clone generic inside generic', function() {
          var g = new library.Generic();
          var innerG = new library.Generic();
          innerG.one = "1";
          g.innerG = innerG;
          expect(library.clone(g).innerG.one).toEqual("1");
          expect(library.clone(g).innerG !== innerG).toEqual(true);
          expect(library.clone(g).innerG.constructor === library.Generic).toEqual(true);
        });
      });

      describe('env', function(){
        it('should copy string ret', function() {
          var e = library.getInitialEnv()
          e.ret = "1";
          expect(e.clone().ret).toEqual("1");
        });

        it('should clone obj ret', function() {
          var e = library.getInitialEnv()
          e.ret = {};
          expect(e.clone().ret !== e.ret).toEqual(true);
        });

        it('should clone obj ctx', function() {
          var e = library.getInitialEnv()
          e.ctx.generic = new library.Generic();
          e.ctx.generic.one = "1";
          expect(e.clone().ctx.generic.one).toEqual("1");
        });

        it('should clone built in write fn', function() {
          var clonedEnv = library.getInitialEnv().clone();
          expect(clonedEnv.ctx.write.fn instanceof Function).toEqual(true);
          expect(clonedEnv.ctx.write.description instanceof Function).toEqual(true);
        });

        it('should clone built in types', function() {
          var clonedEnv = library.getInitialEnv().clone();
          expect(clonedEnv.ctx._types.list instanceof Function).toEqual(true);
          expect(clonedEnv.ctx._types.generic instanceof Function).toEqual(true);
        });

        it('should not find vars added to clone in original', function() {
          var e = library.getInitialEnv();
          var c = e.clone();
          interpreter.interpret("a is '1'", c);
          expect(e.ctx.a).toBeUndefined();
          expect(c.ctx.a).toEqual("1");
        });
      });

      describe('references', function(){
        it('should reproduce in clone shared generic via ref', function() {
          var e = library.getInitialEnv()
          e.ctx.shared = new library.Generic();
          e.ctx.a = new library.Generic();
          e.ctx.b = new library.Generic();
          e.ctx.a.shared = e.ctx.b.shared = e.ctx.shared;
          expect(e.ctx.a.shared === e.ctx.b.shared).toEqual(true);
          expect(e.ctx.a === e.ctx.b).toEqual(false);

          var c = e.clone();
          expect(c.ctx.a.shared === c.ctx.b.shared).toEqual(true);
        });

        it('should reproduce in clone shared list via ref', function() {
          var e = library.getInitialEnv()
          e.ctx.shared = new library.List();
          e.ctx.shared.add(1);
          e.ctx.shared.add(2);
          e.ctx.a = new library.Generic();
          e.ctx.b = new library.Generic();
          e.ctx.a.shared = e.ctx.b.shared = e.ctx.shared;
          expect(e.ctx.a.shared === e.ctx.b.shared).toEqual(true);

          var c = e.clone();
          expect(c.ctx.a.shared === c.ctx.b.shared).toEqual(true);
        });

        it('should reproduce in clone shared obj via ref', function() {
          var e = library.getInitialEnv()
          e.ctx.shared = {};
          e.ctx.a = { shared: e.ctx.shared };
          e.ctx.b = { shared: e.ctx.shared };
          expect(e.ctx.a.shared === e.ctx.b.shared).toEqual(true);
          expect(e.ctx.a === e.ctx.b).toEqual(false);

          var c = e.clone();
          expect(c.ctx.a.shared === c.ctx.b.shared).toEqual(true);
        });

        it('should reproduce in clone shared array via ref', function() {
          var e = library.getInitialEnv()
          e.ctx.shared = [1, 2];
          e.ctx.a = new library.Generic();
          e.ctx.b = new library.Generic();
          e.ctx.a.shared = e.ctx.b.shared = e.ctx.shared;
          expect(e.ctx.a.shared === e.ctx.b.shared).toEqual(true);

          var c = e.clone();
          expect(c.ctx.a.shared === c.ctx.b.shared).toEqual(true);
        });

        it('should reproduce in clone shared obj inside shared obj via refs', function() {
          var e = library.getInitialEnv()
          e.ctx.shared1 = {};
          e.ctx.shared2 = { shared: e.ctx.shared1 }
          e.ctx.a = { shared: e.ctx.shared2 };
          e.ctx.b = { shared: e.ctx.shared2 };
          expect(e.ctx.a.shared === e.ctx.b.shared).toEqual(true);
          expect(e.ctx.a === e.ctx.b).toEqual(false);

          var c = e.clone();
          expect(c.ctx.a.shared === c.ctx.b.shared).toEqual(true);
          expect(c.ctx.a.shared.shared === c.ctx.b.shared.shared).toEqual(true);
          expect(c.ctx.a.shared === c.ctx.shared2).toEqual(true);
          expect(c.ctx.a.shared.shared === c.ctx.shared1).toEqual(true);
        });
      });
    });
  });
});
<commit_msg>Test refs not just refs to originals.<commit_after>var interpreter = require('../src/interpreter').Interpreter;
var library = require('../src/library').Library;

describe('library', function() {
  describe('write', function(){
    describe('Generic', function(){
      it('should print attributes', function() {
        var code = "pluto is a planet\npluto density is '3'\npluto radius is '7'\nwrite pluto";
        var env = interpreter.interpret(code);

        expect(env.ret).toEqual("a planet\n  density is '3'\n  radius is '7'\n");
      });

      it('should print attribute that is obj, too', function() {
        var code = "pluto is a planet\nneptune is a planet\nneptune density is '20'\npluto density is '3'\npluto neighbour is neptune\npluto radius is '6'\nwrite pluto";
        var env = interpreter.interpret(code);
        expect(env.ret).toEqual("a planet\n  density is '3'\n  neighbour is a planet\n    density is '20'\n  radius is '6'\n");
      });

      it('should print no attributes if Generic has none', function() {
        var code = "pluto is a planet\nwrite pluto";
        var env = interpreter.interpret(code);
        expect(env.ret).toEqual("a planet\n");
      });
    });

    describe('List', function(){
      it('should print elements of List', function() {
        var code = "l is a list\nadd 'a' to l\nadd 'b' to l\nwrite l";
        var env = interpreter.interpret(code);
        expect(env.ret).toEqual("a list\n  'a'\n  'b'\n");
      });

      it('should print element that is obj, too', function() {
        var code = "l is a list\nneptune is a planet\nneptune density is '1'\nadd '1' to l\nadd neptune to l\nadd '2' to l\nwrite l";
        var env = interpreter.interpret(code);
        expect(env.ret).toEqual("a list\n  '1'\n  a planet\n    density is '1'\n  '2'\n");
      });

      it('should indicate empty list has nothing in it', function() {
        var code = "l is a list\n\nwrite l";
        var env = interpreter.interpret(code);
        expect(env.ret).toEqual("an empty list");
      });
    });

    describe('clone', function() {
      describe('List', function(){
        it('should have two elements in clone that appear in original', function() {
          var l = new library.List();
          l.add("1");
          l.add("2");
          expect(library.clone(l).items()[0]).toEqual("1");
          expect(library.clone(l).items()[1]).toEqual("2");
          expect(library.clone(l) !== l).toEqual(true);
          expect(library.clone(l).constructor === library.List).toEqual(true);
        });

        it('should clone list inside list', function() {
          var l = new library.List();
          var innerL = new library.List();
          innerL.add("1");
          l.add(innerL);
          expect(library.clone(l).items()[0].items()[0]).toEqual("1");
          expect(library.clone(l).items()[0] !== innerL).toEqual(true);
          expect(library.clone(l).items()[0].constructor === library.List).toEqual(true);
        });

        it('should clone generic inside list', function() {
          var l = new library.List();
          var g = new library.Generic();
          g.la = "1";
          l.add(g);
          expect(library.clone(l).items()[0].la).toEqual("1");
          expect(library.clone(l) !== l).toEqual(true);
          expect(library.clone(l).items()[0].constructor === library.Generic).toEqual(true);
        });
      });

      describe('Generic', function(){
        it('should have two elements in clone that appear in original', function() {
          var g = new library.Generic();
          g.one = "1";
          g.two = "2";
          expect(library.clone(g).one).toEqual("1");
          expect(library.clone(g).two).toEqual("2");
          expect(library.clone(g) !== g).toEqual(true);
          expect(library.clone(g) instanceof library.Generic).toEqual(true);
        });

        it('should clone a list inside a generic', function() {
          var g = new library.Generic();
          var l = new library.List();
          l.add("1");
          g.l = l;
          expect(library.clone(g).l.items()[0]).toEqual("1");
          expect(library.clone(g).l !== l).toEqual(true);
          expect(library.clone(g).l.constructor === library.List).toEqual(true);
        });

        it('should clone generic inside generic', function() {
          var g = new library.Generic();
          var innerG = new library.Generic();
          innerG.one = "1";
          g.innerG = innerG;
          expect(library.clone(g).innerG.one).toEqual("1");
          expect(library.clone(g).innerG !== innerG).toEqual(true);
          expect(library.clone(g).innerG.constructor === library.Generic).toEqual(true);
        });
      });

      describe('env', function(){
        it('should copy string ret', function() {
          var e = library.getInitialEnv()
          e.ret = "1";
          expect(e.clone().ret).toEqual("1");
        });

        it('should clone obj ret', function() {
          var e = library.getInitialEnv()
          e.ret = {};
          expect(e.clone().ret !== e.ret).toEqual(true);
        });

        it('should clone obj ctx', function() {
          var e = library.getInitialEnv()
          e.ctx.generic = new library.Generic();
          e.ctx.generic.one = "1";
          expect(e.clone().ctx.generic.one).toEqual("1");
        });

        it('should clone built in write fn', function() {
          var clonedEnv = library.getInitialEnv().clone();
          expect(clonedEnv.ctx.write.fn instanceof Function).toEqual(true);
          expect(clonedEnv.ctx.write.description instanceof Function).toEqual(true);
        });

        it('should clone built in types', function() {
          var clonedEnv = library.getInitialEnv().clone();
          expect(clonedEnv.ctx._types.list instanceof Function).toEqual(true);
          expect(clonedEnv.ctx._types.generic instanceof Function).toEqual(true);
        });

        it('should not find vars added to clone in original', function() {
          var e = library.getInitialEnv();
          var c = e.clone();
          interpreter.interpret("a is '1'", c);
          expect(e.ctx.a).toBeUndefined();
          expect(c.ctx.a).toEqual("1");
        });
      });

      describe('references', function(){
        it('should reproduce in clone shared generic via ref', function() {
          var e = library.getInitialEnv()
          e.ctx.shared = new library.Generic();
          e.ctx.a = new library.Generic();
          e.ctx.b = new library.Generic();
          e.ctx.a.shared = e.ctx.b.shared = e.ctx.shared;
          expect(e.ctx.a.shared === e.ctx.b.shared).toEqual(true);
          expect(e.ctx.a === e.ctx.b).toEqual(false);

          var c = e.clone();
          expect(e.ctx.a.shared !== c.ctx.a.shared).toEqual(true);
          expect(c.ctx.a.shared === c.ctx.b.shared).toEqual(true);
        });

        it('should reproduce in clone shared list via ref', function() {
          var e = library.getInitialEnv()
          e.ctx.shared = new library.List();
          e.ctx.shared.add(1);
          e.ctx.shared.add(2);
          e.ctx.a = new library.Generic();
          e.ctx.b = new library.Generic();
          e.ctx.a.shared = e.ctx.b.shared = e.ctx.shared;
          expect(e.ctx.a.shared === e.ctx.b.shared).toEqual(true);

          var c = e.clone();
          expect(e.ctx.a.shared !== c.ctx.a.shared).toEqual(true);
          expect(c.ctx.a.shared === c.ctx.b.shared).toEqual(true);
        });

        it('should reproduce in clone shared obj via ref', function() {
          var e = library.getInitialEnv()
          e.ctx.shared = {};
          e.ctx.a = { shared: e.ctx.shared };
          e.ctx.b = { shared: e.ctx.shared };
          expect(e.ctx.a.shared === e.ctx.b.shared).toEqual(true);
          expect(e.ctx.a === e.ctx.b).toEqual(false);

          var c = e.clone();
          expect(e.ctx.a.shared !== c.ctx.a.shared).toEqual(true);
          expect(c.ctx.a.shared === c.ctx.b.shared).toEqual(true);
        });

        it('should reproduce in clone shared array via ref', function() {
          var e = library.getInitialEnv()
          e.ctx.shared = [1, 2];
          e.ctx.a = new library.Generic();
          e.ctx.b = new library.Generic();
          e.ctx.a.shared = e.ctx.b.shared = e.ctx.shared;
          expect(e.ctx.a.shared === e.ctx.b.shared).toEqual(true);

          var c = e.clone();
          expect(e.ctx.a.shared !== c.ctx.a.shared).toEqual(true);
          expect(c.ctx.a.shared === c.ctx.b.shared).toEqual(true);
        });

        it('should reproduce in clone shared obj inside shared obj via refs', function() {
          var e = library.getInitialEnv()
          e.ctx.shared1 = {};
          e.ctx.shared2 = { shared: e.ctx.shared1 }
          e.ctx.a = { shared: e.ctx.shared2 };
          e.ctx.b = { shared: e.ctx.shared2 };
          expect(e.ctx.a.shared === e.ctx.b.shared).toEqual(true);
          expect(e.ctx.a === e.ctx.b).toEqual(false);

          var c = e.clone();
          expect(e.ctx.a.shared !== c.ctx.a.shared).toEqual(true);
          expect(c.ctx.a.shared === c.ctx.b.shared).toEqual(true);

          expect(e.ctx.a.shared.shared !== c.ctx.a.shared.shared).toEqual(true);
          expect(c.ctx.a.shared.shared === c.ctx.b.shared.shared).toEqual(true);

          expect(c.ctx.a.shared === c.ctx.shared2).toEqual(true);
          expect(c.ctx.a.shared.shared === c.ctx.shared1).toEqual(true);
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>/*
   _            _     __
  | |_ __ _ ___| | __/ _| ___  _ __ ___ ___
  | __/ _` / __| |/ / |_ / _ \| '__/ __/ _ \
  | || (_| \__ \   <|  _| (_) | | | (_|  __/
   \__\__,_|___/_|\_\_|  \___/|_|  \___\___|

  ===============================================================================

  CALL CONGRESS WIDGET

  ===============================================================================

  A generic widget include script to connect calls to congress

  http://github.com/tfrce/call-widget or <thomasalwyndavis@gmail.com> or http://taskforce.is for support

  ===============================================================================

  @source: https://raw.github.com/tfrce/call-widget/call-widget.js

  @licstart  The following is the entire license notice for the
             JavaScript code in this page.

  Copyright (C) 2013 Taskforce <http://taskforce.is>

  The JavaScript code in this page is free software: you can
  redistribute it and/or modify it under the terms of the GNU Affero
  General Public License (GNU GPL) as published by the Free Software
  Foundation, either version 3 of the License, or (at your option) any
  later version.  The code is distributed WITHOUT ANY WARRANTY;
  without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  A PARTICULAR PURPOSE.  See the GNU GPL for more details.

  As additional permission under GNU AGPL version 3 section 7, you may
  distribute non-source (e.g., minimized or compacted) forms of that
  code without the copy of the GNU AGPL normally required by section
  4, provided you include this license notice and a URL through which
  recipients can access the Corresponding Source.

 @license  The above is the entire license notice for the JavaScript
          code in this page.

*/
(function(window, document, version, callback) {
    // Load jQuery is not loaded
    var j, d;
    var loaded = false;
    // TODO - Version check doesn't work correctly
    if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js";
        script.onload = script.onreadystatechange = function() {
            if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
                callback((j = window.jQuery).noConflict(1), loaded = true);
                j(script).remove();
            }
        };
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script);
    }
})(window, document, "1.10.2", function($, jquery_loaded) {
  // Execute widget code here

  var tforce_config = window.tforce_config;

  if(typeof tforce_config.campaign === 'undefined') {
    return false;
  }

  var campaign = tforce_config.campaign;

  function isValidPhoneNumber(value) {
    if (!value) return false;
    var count = value.length;

    return count == 10 || count == 11;
  }

  function isValidZipCode(value) {
      if (!value) return false;
      var count = value.length;

      return count == 5;
  }

  // Widget code here
  $('#tf-call-tool').on('submit', function (ev){

    // Select form elements
    var form = $(ev.currentTarget);
    var zipCodeEl = $('#tf-zip-code', form);
    var phoneNumberEl = $('#tf-phone-number', form);
    var zipCodeLabelEl = $('[for="tf-zip-code"]', form);
    var phoneNumberLabelEl = $('[for="tf-phone-number"]', form);
    var submitEl = $('#tf-submit', form);
    var submitText = submitEl.val();
    var submitWaitingText = submitEl.attr('data-waiting-text') || 'Calling';

    // Reset any error messages
    $(zipCodeEl).removeClass('tf-input-error');
    $(phoneNumberEl).removeClass('tf-input-error');
    $(phoneNumberLabelEl).removeClass('tf-input-error');
    $(zipCodeLabelEl).removeClass('tf-input-error');
    $('#tf-error-text').text('');
    var errors = false;

    // Validate form inputs
    if(zipCodeEl.length > 0) {
      var zipCode = zipCodeEl.val().replace(/[^\d.]/g, '');
      // Valid Zip?
      if (!isValidZipCode(zipCode)) {
          zipCodeEl.addClass('tf-input-error');
          zipCodeLabelEl.addClass('tf-input-error');
          errors = true;
      }
    }

    // Valid Phone?
    var phoneNumber = phoneNumberEl.val().replace(/[^\d.]/g, '');

    if (!isValidPhoneNumber(phoneNumber)) {
        phoneNumberEl.addClass('tf-input-error');
        phoneNumberLabelEl.addClass('tf-input-error');
        errors = true;
    }

    // If any errors, cancel submitting the form
    if(errors) {
      return false;
    }

    // Disable buttons
    zipCodeEl.attr('disabled', 'disabled');
    phoneNumberEl.attr('disabled', 'disabled');
    submitEl.attr('disabled', 'disabled').val(submitWaitingText);
    console.log(campaign, phoneNumber, zipCode)
    // 9498788202 - sina
    // 4242351643 - skype
    // 4154949855 - gvoice
    //http://call.taskforce.is/create?campaignId=restrict-nsa&userzip=94110&userPhone=4242351643
    var url = 'http://call-congress.taskforce.is/create?campaignId=' + campaign + '&userPhone=' + phoneNumber;
    if(typeof zipCode !== 'undefined') {
      url += '&userzip=' + zipCode;
    }
    $.ajax({
      url: url,
      type: 'GET',
      dataType: 'jsonp',
      crossDomain: true,
      success: function (res) {
        if(res.message !== 'queued') {
          $('#tf-error-text').text(res.message);
        } else {
          $('#tf-call-widget-form').hide();
          $('#tf-call-widget-success').show();
        }
        zipCodeEl.removeAttr('disabled');
        phoneNumberEl.removeAttr('disabled');
        submitEl.removeAttr('disabled').val(submitText);
      },
      error: function () {
        $('#tf-error-text').text('An Unknown error happened');
        zipCodeEl.removeAttr('disabled');
        phoneNumberEl.removeAttr('disabled');
        submitEl.removeAttr('disabled').val(submitText);
      }
    });
    return false;
  });
  $('body').on('click', '#tf-reset', function (ev){
    $('#tf-zip-code').val('');
    $('#tf-phone-number').val('');
    $('#tf-call-widget-form').show();
    $('#tf-call-widget-success').hide();
    $('#tf-phone-number').focus();

  });

});
<commit_msg>added perma https<commit_after>/*
   _            _     __
  | |_ __ _ ___| | __/ _| ___  _ __ ___ ___
  | __/ _` / __| |/ / |_ / _ \| '__/ __/ _ \
  | || (_| \__ \   <|  _| (_) | | | (_|  __/
   \__\__,_|___/_|\_\_|  \___/|_|  \___\___|

  ===============================================================================

  CALL CONGRESS WIDGET

  ===============================================================================

  A generic widget include script to connect calls to congress

  http://github.com/tfrce/call-widget or <thomasalwyndavis@gmail.com> or http://taskforce.is for support

  ===============================================================================

  @source: https://raw.github.com/tfrce/call-widget/call-widget.js

  @licstart  The following is the entire license notice for the
             JavaScript code in this page.

  Copyright (C) 2013 Taskforce <http://taskforce.is>

  The JavaScript code in this page is free software: you can
  redistribute it and/or modify it under the terms of the GNU Affero
  General Public License (GNU GPL) as published by the Free Software
  Foundation, either version 3 of the License, or (at your option) any
  later version.  The code is distributed WITHOUT ANY WARRANTY;
  without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  A PARTICULAR PURPOSE.  See the GNU GPL for more details.

  As additional permission under GNU AGPL version 3 section 7, you may
  distribute non-source (e.g., minimized or compacted) forms of that
  code without the copy of the GNU AGPL normally required by section
  4, provided you include this license notice and a URL through which
  recipients can access the Corresponding Source.

 @license  The above is the entire license notice for the JavaScript
          code in this page.

*/
(function(window, document, version, callback) {
    // Load jQuery is not loaded
    var j, d;
    var loaded = false;
    // TODO - Version check doesn't work correctly
    if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js";
        script.onload = script.onreadystatechange = function() {
            if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
                callback((j = window.jQuery).noConflict(1), loaded = true);
                j(script).remove();
            }
        };
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script);
    }
})(window, document, "1.10.2", function($, jquery_loaded) {
  // Execute widget code here

  var tforce_config = window.tforce_config;

  if(typeof tforce_config.campaign === 'undefined') {
    return false;
  }

  var campaign = tforce_config.campaign;

  function isValidPhoneNumber(value) {
    if (!value) return false;
    var count = value.length;

    return count == 10 || count == 11;
  }

  function isValidZipCode(value) {
      if (!value) return false;
      var count = value.length;

      return count == 5;
  }

  // Widget code here
  $('#tf-call-tool').on('submit', function (ev){

    // Select form elements
    var form = $(ev.currentTarget);
    var zipCodeEl = $('#tf-zip-code', form);
    var phoneNumberEl = $('#tf-phone-number', form);
    var zipCodeLabelEl = $('[for="tf-zip-code"]', form);
    var phoneNumberLabelEl = $('[for="tf-phone-number"]', form);
    var submitEl = $('#tf-submit', form);
    var submitText = submitEl.val();
    var submitWaitingText = submitEl.attr('data-waiting-text') || 'Calling';

    // Reset any error messages
    $(zipCodeEl).removeClass('tf-input-error');
    $(phoneNumberEl).removeClass('tf-input-error');
    $(phoneNumberLabelEl).removeClass('tf-input-error');
    $(zipCodeLabelEl).removeClass('tf-input-error');
    $('#tf-error-text').text('');
    var errors = false;

    // Validate form inputs
    if(zipCodeEl.length > 0) {
      var zipCode = zipCodeEl.val().replace(/[^\d.]/g, '');
      // Valid Zip?
      if (!isValidZipCode(zipCode)) {
          zipCodeEl.addClass('tf-input-error');
          zipCodeLabelEl.addClass('tf-input-error');
          errors = true;
      }
    }

    // Valid Phone?
    var phoneNumber = phoneNumberEl.val().replace(/[^\d.]/g, '');

    if (!isValidPhoneNumber(phoneNumber)) {
        phoneNumberEl.addClass('tf-input-error');
        phoneNumberLabelEl.addClass('tf-input-error');
        errors = true;
    }

    // If any errors, cancel submitting the form
    if(errors) {
      return false;
    }

    // Disable buttons
    zipCodeEl.attr('disabled', 'disabled');
    phoneNumberEl.attr('disabled', 'disabled');
    submitEl.attr('disabled', 'disabled').val(submitWaitingText);
    console.log(campaign, phoneNumber, zipCode)
    // 9498788202 - sina
    // 4242351643 - skype
    // 4154949855 - gvoice
    //http://call.taskforce.is/create?campaignId=restrict-nsa&userzip=94110&userPhone=4242351643
    var url = 'https://call-congress.taskforce.is/create?campaignId=' + campaign + '&userPhone=' + phoneNumber;
    if(typeof zipCode !== 'undefined') {
      url += '&userzip=' + zipCode;
    }
    $.ajax({
      url: url,
      type: 'GET',
      dataType: 'jsonp',
      crossDomain: true,
      success: function (res) {
        if(res.message !== 'queued') {
          $('#tf-error-text').text(res.message);
        } else {
          $('#tf-call-widget-form').hide();
          $('#tf-call-widget-success').show();
        }
        zipCodeEl.removeAttr('disabled');
        phoneNumberEl.removeAttr('disabled');
        submitEl.removeAttr('disabled').val(submitText);
      },
      error: function () {
        $('#tf-error-text').text('An Unknown error happened');
        zipCodeEl.removeAttr('disabled');
        phoneNumberEl.removeAttr('disabled');
        submitEl.removeAttr('disabled').val(submitText);
      }
    });
    return false;
  });
  $('body').on('click', '#tf-reset', function (ev){
    $('#tf-zip-code').val('');
    $('#tf-phone-number').val('');
    $('#tf-call-widget-form').show();
    $('#tf-call-widget-success').hide();
    $('#tf-phone-number').focus();

  });

});
<|endoftext|>


<commit_before>var fs = require('fs');
var webdriver = require('selenium-webdriver');
webdriver.promise.controlFlow().on('uncaughtException', function(e) {
    console.error('Unhandled error: ' + e);
});

function getWebDriver(options) {
    if (!options) {
        options = {timeout: 10000, capabilities: {'browserName': 'chrome','chromeOptions': {"args": ['--incognito']}}};
    }

    var driver = new webdriver.Builder().
                usingServer('http://127.0.0.1:4444/wd/hub').
                withCapabilities(options.capabilities).
                build();
    driver.manage().timeouts().setScriptTimeout(options.timeout);

    return driver;
}

module.exports = {
    Client: function (driver, clientName, baseURL) {

        this.driver = driver;
        this.clientName = clientName;
        this.baseURL = baseURL || 'http://localhost:1337'

        this.init = function (appId) {
            return this.driver.executeScript("window['" + this.clientName + "'] = webrtc.Client({clientSettings: {appId: '" + appId + "', baseURL: '" + this.baseURL + "'}});");
        };
        this.connect = function () {
            return this.driver.executeScript("window['" + this.clientName + "'].connect();");
        };
        this.disconnect = function () {
            return this.driver.executeScript("window['" + this.clientName + "'].disconnect();");
        };
        this.login = function (username, password) {
            return this.driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                "var userPromise = window['" + this.clientName + "'].login('" + username + "', '" + password + "'); " +
                "userPromise.then(function (user) { " +
                "    window['" + clientName + "']['user'] = user; " +
                "    callback(user);" +
                "});");
        };
        this.logout = function () {
            return this.driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                 "var logoutPromise = window['" + this.clientName + "'].logout();" +
                 "logoutPromise.then(function () { " +
                 "    callback();" +
                 "});");
        };
        this.isConnected = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].isConnected();");
        };
        this.isLoggedIn = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].isLoggedIn();");
        };
        this.getClientSettings = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].getClientSettings();");
        };
        this.getMediaSettings = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].getMediaSettings();");
        };
        this.setDefaultMediaSettings = function (mediaSettings) {
            return this.driver.executeScript("window['" + this.clientName + "'].setDefaultMediaSettings(" + mediaSettings + ");");
        };
        this.getSignalingChannel = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].getSignalingChannel();");
        };
        this.getContacts = function () {
            return this.driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                    "window['" + this.clientName + "'].user.getContacts().then(function (contactList) { " +
                    "    window['" + this.clientName + "']['contacts'] = contactList;" +
                    "    callback(contactList); " +
                    " });");
        };
        this.listen = function (method, event, varName) {
            return this.driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                    "window['" + this.clientName + "']." + method + ".listen('" + event + "', function (message) {" +
                    "    window['" + this.clientName + "']['" + varName +"'] = message; " +
                    " }); callback();");
        };
        this.listenOnContactEvent = function (username, event, varName) {
            return this.driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                    "window['" + this.clientName + "'].user.getContacts().then(function (contactList) { " +
                    "    var contacts = contactList.getContacts(); " +
                    "    for(var i = 0; i < contacts.length; i ++) { " +
                    "         if (contacts[i].username == '" + username + "') { " +
                    "               contacts[i].listen('" + event + "', function (message) {" +
                    "                   window['" + this.clientName + "']['" + varName +"'] = message; " +
                    "               }); " +
                    "         } " +
                    "    } " +
                    "    callback();" +
                    " }); ");
        };
        this.getValue = function (varName) {
            return this.driver.executeScript("return window['" + this.clientName + "']." + varName +";");
        };
        this.setPresence = function (status) {
            return this.driver.executeScript("window['" + this.clientName + "'].user.setPresence('" + status + "');");
        };
        this.getPresence = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.getPresence();");
        };
        this.getDisplayName = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.getDisplayName();");
        };
        this.getUsername = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.getUsername();");
        };
        this.getName = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.getName();");
        };
        this.getID = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.getID();");
        };
        this.canSendAudio = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.canSendAudio();");
        };
        this.canSendVideo = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.canSendVideo();");
        };
        this.hasMedia = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.hasMedia();");
        };
        this.sendMessage = function (username, message) {
            return this.driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                    "window['" + this.clientName + "'].user.getContacts().then(function (contactList) { " +
                    "    var contacts = contactList.getContacts(); " +
                    "    for(var i = 0; i < contacts.length; i ++) { " +
                    "         if (contacts[i].username == '" + username + "') { " +
                    "               contacts[i].sendMessage('" + message + "'); " +
                    "         } " +
                    "    } " +
                    "    callback(); " +
                    " }); ");
        };
        this.getMessages = function (username) {
            return this.driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                    " window['" + this.clientName + "'].user.getContacts().then(function (contactList) { " +
                    "    var contacts = contactList.getContacts(); " +
                    "    var contact; " +
                    "    for(var i = 0; i < contacts.length; i ++) { " +
                    "         if (contacts[i].username == '" + username + "') { " +
                    "               contact = contacts[i]; " +
                    "         } " +
                    "    } " +
                    "    var messages = contact.getMessages(); " +
                    "    callback(messages); " +
                    " }); ");
        };
        this.createEndpoint = function (varName, id) {
            return this.driver.executeScript("window['" + this.clientName + "']." + varName +" = webrtc.Endpoint({id: " + id + ", client: window['" + this.clientName + "'].getID()});");
        };
        this.sendEndpointMessage = function (varName, message) {
            return this.driver.executeScript("window['" + this.clientName + "']." + varName + ".sendMessage('" + message + "');");
        };
        this.getID = function () {
            return this.driver.executeScript("return webrtc.getClient(window['" + this.clientName + "'].getID()).user.getID();")
        };

    },

    webDriver: function (options) {
        return getWebDriver();
    },

    testFixtureBeforeTest: function (options, cb) {
        fs.readFile(process.cwd() + '/collective/spec/util/jquery.js', {encoding: 'utf8'}, function (err, data) {
        var jquery = data;
        fs.readFile(process.cwd() + '/collective/spec/util/api_client.js', {encoding: 'utf8'}, function (err, data) {
            var apiClientString = data;
            fs.readFile(process.cwd() + '/collective/spec/util/fixture.js', {encoding: 'utf8'}, function (err, data) {
                var fixtureString = data;
                fixtureString = fixtureString.replace('var fixture', "window['fixture']");
                driver = getWebDriver();
                driver.get('http://localhost:' + process.env.SERVER_PORT + '/test.html').then(function () {
                    driver.executeScript(jquery + "    " + apiClientString + "    " + fixtureString).then(function () {
                            driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                                    "window['fix'] = window['fixture']('Events Spec', " + JSON.stringify(options) + "); " +
                                    "window['fix'].beforeTest(function (err, env) { " +
                                    "   callback(env); " +
                                    "}); "
                                    ).then(function (environment) {
                                        cb(driver, environment);
                                    });
                        });
                    });
                });
            });
        });
    },

    testFixtureAfterTest: function (driver, cb) {
        driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
            "window['fix'].afterTest(function () { " +
            "    callback(); " +
            "}); ").then(function () {
                driver.quit();
                cb();
            });
    }
}<commit_msg>configuration for selenium server and browser<commit_after>var fs = require('fs');
var webdriver = require('selenium-webdriver');
webdriver.promise.controlFlow().on('uncaughtException', function(e) {
    console.error('Unhandled error: ' + e);
});

function getWebDriver(options) {
    var selenium_server_url = process.env["SELENIUM_SERVER_URL"] || "http://127.0.0.1:4444/wd/hub";
    var browserName = process.env["SELENIUM_BROWSER"] || 'chrome';

    if (!options) {
        options = {timeout: 10000, capabilities: {'browserName': browserName,'chromeOptions': {"args": ['--incognito']}}};
    }
    var driver = new webdriver.Builder().
            usingServer(selenium_server_url).
            withCapabilities(options.capabilities).
            build();
    driver.manage().timeouts().setScriptTimeout(options.timeout);

    return driver;
}

module.exports = {
    Client: function (driver, clientName, baseURL) {

        this.driver = driver;
        this.clientName = clientName;
        this.baseURL = baseURL || 'http://localhost:1337'

        this.init = function (appId) {
            return this.driver.executeScript("window['" + this.clientName + "'] = webrtc.Client({clientSettings: {appId: '" + appId + "', baseURL: '" + this.baseURL + "'}});");
        };
        this.connect = function () {
            return this.driver.executeScript("window['" + this.clientName + "'].connect();");
        };
        this.disconnect = function () {
            return this.driver.executeScript("window['" + this.clientName + "'].disconnect();");
        };
        this.login = function (username, password) {
            return this.driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                "var userPromise = window['" + this.clientName + "'].login('" + username + "', '" + password + "'); " +
                "userPromise.then(function (user) { " +
                "    window['" + clientName + "']['user'] = user; " +
                "    callback(user);" +
                "});");
        };
        this.logout = function () {
            return this.driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                 "var logoutPromise = window['" + this.clientName + "'].logout();" +
                 "logoutPromise.then(function () { " +
                 "    callback();" +
                 "});");
        };
        this.isConnected = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].isConnected();");
        };
        this.isLoggedIn = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].isLoggedIn();");
        };
        this.getClientSettings = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].getClientSettings();");
        };
        this.getMediaSettings = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].getMediaSettings();");
        };
        this.setDefaultMediaSettings = function (mediaSettings) {
            return this.driver.executeScript("window['" + this.clientName + "'].setDefaultMediaSettings(" + mediaSettings + ");");
        };
        this.getSignalingChannel = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].getSignalingChannel();");
        };
        this.getContacts = function () {
            return this.driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                    "window['" + this.clientName + "'].user.getContacts().then(function (contactList) { " +
                    "    window['" + this.clientName + "']['contacts'] = contactList;" +
                    "    callback(contactList); " +
                    " });");
        };
        this.listen = function (method, event, varName) {
            return this.driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                    "window['" + this.clientName + "']." + method + ".listen('" + event + "', function (message) {" +
                    "    window['" + this.clientName + "']['" + varName +"'] = message; " +
                    " }); callback();");
        };
        this.listenOnContactEvent = function (username, event, varName) {
            return this.driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                    "window['" + this.clientName + "'].user.getContacts().then(function (contactList) { " +
                    "    var contacts = contactList.getContacts(); " +
                    "    for(var i = 0; i < contacts.length; i ++) { " +
                    "         if (contacts[i].username == '" + username + "') { " +
                    "               contacts[i].listen('" + event + "', function (message) {" +
                    "                   window['" + this.clientName + "']['" + varName +"'] = message; " +
                    "               }); " +
                    "         } " +
                    "    } " +
                    "    callback();" +
                    " }); ");
        };
        this.getValue = function (varName) {
            return this.driver.executeScript("return window['" + this.clientName + "']." + varName +";");
        };
        this.setPresence = function (status) {
            return this.driver.executeScript("window['" + this.clientName + "'].user.setPresence('" + status + "');");
        };
        this.getPresence = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.getPresence();");
        };
        this.getDisplayName = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.getDisplayName();");
        };
        this.getUsername = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.getUsername();");
        };
        this.getName = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.getName();");
        };
        this.getID = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.getID();");
        };
        this.canSendAudio = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.canSendAudio();");
        };
        this.canSendVideo = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.canSendVideo();");
        };
        this.hasMedia = function () {
            return this.driver.executeScript("return window['" + this.clientName + "'].user.hasMedia();");
        };
        this.sendMessage = function (username, message) {
            return this.driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                    "window['" + this.clientName + "'].user.getContacts().then(function (contactList) { " +
                    "    var contacts = contactList.getContacts(); " +
                    "    for(var i = 0; i < contacts.length; i ++) { " +
                    "         if (contacts[i].username == '" + username + "') { " +
                    "               contacts[i].sendMessage('" + message + "'); " +
                    "         } " +
                    "    } " +
                    "    callback(); " +
                    " }); ");
        };
        this.getMessages = function (username) {
            return this.driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                    " window['" + this.clientName + "'].user.getContacts().then(function (contactList) { " +
                    "    var contacts = contactList.getContacts(); " +
                    "    var contact; " +
                    "    for(var i = 0; i < contacts.length; i ++) { " +
                    "         if (contacts[i].username == '" + username + "') { " +
                    "               contact = contacts[i]; " +
                    "         } " +
                    "    } " +
                    "    var messages = contact.getMessages(); " +
                    "    callback(messages); " +
                    " }); ");
        };
        this.createEndpoint = function (varName, id) {
            return this.driver.executeScript("window['" + this.clientName + "']." + varName +" = webrtc.Endpoint({id: " + id + ", client: window['" + this.clientName + "'].getID()});");
        };
        this.sendEndpointMessage = function (varName, message) {
            return this.driver.executeScript("window['" + this.clientName + "']." + varName + ".sendMessage('" + message + "');");
        };
        this.getID = function () {
            return this.driver.executeScript("return webrtc.getClient(window['" + this.clientName + "'].getID()).user.getID();")
        };

    },

    webDriver: function (options) {
        return getWebDriver();
    },

    testFixtureBeforeTest: function (options, cb) {
        fs.readFile(process.cwd() + '/collective/spec/util/jquery.js', {encoding: 'utf8'}, function (err, data) {
        var jquery = data;
        fs.readFile(process.cwd() + '/collective/spec/util/api_client.js', {encoding: 'utf8'}, function (err, data) {
            var apiClientString = data;
            fs.readFile(process.cwd() + '/collective/spec/util/fixture.js', {encoding: 'utf8'}, function (err, data) {
                var fixtureString = data;
                fixtureString = fixtureString.replace('var fixture', "window['fixture']");
                driver = getWebDriver();
                driver.get('http://localhost:' + process.env.SERVER_PORT + '/test.html').then(function () {
                    driver.executeScript(jquery + "    " + apiClientString + "    " + fixtureString).then(function () {
                            driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
                                    "window['fix'] = window['fixture']('Events Spec', " + JSON.stringify(options) + "); " +
                                    "window['fix'].beforeTest(function (err, env) { " +
                                    "   callback(env); " +
                                    "}); "
                                    ).then(function (environment) {
                                        cb(driver, environment);
                                    });
                        });
                    });
                });
            });
        });
    },

    testFixtureAfterTest: function (driver, cb) {
        driver.executeAsyncScript("var callback = arguments[arguments.length - 1]; " +
            "window['fix'].afterTest(function () { " +
            "    callback(); " +
            "}); ").then(function () {
                driver.quit();
                cb();
            });
    }
}<|endoftext|>


<commit_before>describe("ClientJS", function(){
  var client;
  beforeEach(function(){
    client = new ClientJS();
  });

  it("should initialize an instance", function(){
    expect(client).not.toBeNull();
  });

  describe("#getSoftwareVersion", function(){
    it("should be a string", function(){
      expect(client.getSoftwareVersion()).toEqual(jasmine.any(String))
    });
  });

  describe("browser data", function(){
    var browserData;
    beforeEach(function() {
      browserData = client.getBrowserData();
    })

    describe("#getBrowserData", function(){
      it("should return a UAParser result", function(){
        var parser = (new (window.UAParser||exports.UAParser));
        expect(browserData).toEqual(parser.getResult())
      });

      it("should be something", function(){
        expect(browserData).not.toBeNull()
      })
    });

    describe("#getUserAgent", function(){
      it("should be equal to browserData.ua", function(){
        expect(client.getUserAgent()).toEqual(browserData.ua);
      });
    });

    describe("#getUserAgentLowerCase", function(){
      it("should be equal to client.getUserAgent, but in lower case", function(){
        expect(client.getUserAgentLowerCase()).toEqual(client.getUserAgent().toLowerCase());
      });
    });

    describe("#getBrowser", function(){
      it("should be equal to browserData.browser.name", function(){
        expect(client.getBrowser()).toEqual(browserData.browser.name);
      });
    });

    describe("#getBrowserVersion", function(){
      it("should be equal to browserData.browser.version", function(){
        expect(client.getBrowserVersion()).toEqual(browserData.browser.version);
      });
    });

    describe("#getBrowserMajorVersion", function(){
      it("should be equal to browserData.browser.major", function(){
        expect(client.getBrowserMajorVersion()).toEqual(browserData.browser.major);
      });
    });

    describe("#isIE|Chrome|Firefox|Safari|Opera|iPhone|iPad", function(){
      it("should return true with the correct browser", function(){
        var browsers = ["IE", "Chrome", "Firefox", "Safari", "Opera", "Mobile Safari"];
        for (var i = 0; i < browsers.length; i++) {
          var browser = browsers[i],
            isBrowser = client["is" + browser]();
          if (client.getBrowser() == browser) {
            expect(isBrowser).toBeTruthy()
          } else expect(isBrowser).toBeFalsy()
        }
      });
    });

    describe("#getCanvasPrint", function(){
      it("should return a String", function(){
        expect(client.getCanvasPrint()).toEqual(jasmine.any(String));
      });
    });

    describe("Fingerprint generators", function(){
      var fingerprint;
      beforeEach(function() {
        fingerprint = client.getFingerprint();
      });

      describe("#getFingerPrint", function(){
        it("should return a Number", function(){
          expect(fingerprint).toEqual(jasmine.any(Number));
        });
      });

      describe("#getCustomFingerprint", function(){
        var customFingerprint;
        beforeEach(function() {
          customFingerprint = client.getCustomFingerprint("custom", "fingerprint")
        });

        it("should return a Number", function(){
          expect(customFingerprint).toEqual(jasmine.any(Number));
        });

        it("should not generate the same fingerprint than getCustomFingerprint", function(){
          expect(customFingerprint).not.toEqual(fingerprint);
        });

        //Fix to https://github.com/jackspirou/clientjs/issues/19
        it("should not ignore the last argument", function(){
          var newCustomFingerprint = client.getCustomFingerprint("custom", "fingerprint :)");
          expect(customFingerprint).not.toEqual(newCustomFingerprint);
        });
      });
    });
  });
});
<commit_msg>git iphone ipod and ipad return Mobile Safari, not Safari<commit_after>describe("ClientJS", function(){
  var client;
  beforeEach(function(){
    client = new ClientJS();
  });

  it("should initialize an instance", function(){
    expect(client).not.toBeNull();
  });

  describe("#getSoftwareVersion", function(){
    it("should be a string", function(){
      expect(client.getSoftwareVersion()).toEqual(jasmine.any(String))
    });
  });

  describe("browser data", function(){
    var browserData;
    beforeEach(function() {
      browserData = client.getBrowserData();
    })

    describe("#getBrowserData", function(){
      it("should return a UAParser result", function(){
        var parser = (new (window.UAParser||exports.UAParser));
        expect(browserData).toEqual(parser.getResult())
      });

      it("should be something", function(){
        expect(browserData).not.toBeNull()
      })
    });

    describe("#getUserAgent", function(){
      it("should be equal to browserData.ua", function(){
        expect(client.getUserAgent()).toEqual(browserData.ua);
      });
    });

    describe("#getUserAgentLowerCase", function(){
      it("should be equal to client.getUserAgent, but in lower case", function(){
        expect(client.getUserAgentLowerCase()).toEqual(client.getUserAgent().toLowerCase());
      });
    });

    describe("#getBrowser", function(){
      it("should be equal to browserData.browser.name", function(){
        expect(client.getBrowser()).toEqual(browserData.browser.name);
      });
    });

    describe("#getBrowserVersion", function(){
      it("should be equal to browserData.browser.version", function(){
        expect(client.getBrowserVersion()).toEqual(browserData.browser.version);
      });
    });

    describe("#getBrowserMajorVersion", function(){
      it("should be equal to browserData.browser.major", function(){
        expect(client.getBrowserMajorVersion()).toEqual(browserData.browser.major);
      });
    });

    describe("#isIE|Chrome|Firefox|Safari|Opera|Mobile Safari", function(){
      it("should return true with the correct browser", function(){
        var browsers = ["IE", "Chrome", "Firefox", "Safari", "Opera", "Mobile Safari"];
        for (var i = 0; i < browsers.length; i++) {
          var browser = browsers[i],
            isBrowser = client["is" + browser]();
          if (client.getBrowser() == browser) {
            expect(isBrowser).toBeTruthy()
          } else expect(isBrowser).toBeFalsy()
        }
      });
    });

    describe("#getCanvasPrint", function(){
      it("should return a String", function(){
        expect(client.getCanvasPrint()).toEqual(jasmine.any(String));
      });
    });

    describe("Fingerprint generators", function(){
      var fingerprint;
      beforeEach(function() {
        fingerprint = client.getFingerprint();
      });

      describe("#getFingerPrint", function(){
        it("should return a Number", function(){
          expect(fingerprint).toEqual(jasmine.any(Number));
        });
      });

      describe("#getCustomFingerprint", function(){
        var customFingerprint;
        beforeEach(function() {
          customFingerprint = client.getCustomFingerprint("custom", "fingerprint")
        });

        it("should return a Number", function(){
          expect(customFingerprint).toEqual(jasmine.any(Number));
        });

        it("should not generate the same fingerprint than getCustomFingerprint", function(){
          expect(customFingerprint).not.toEqual(fingerprint);
        });

        //Fix to https://github.com/jackspirou/clientjs/issues/19
        it("should not ignore the last argument", function(){
          var newCustomFingerprint = client.getCustomFingerprint("custom", "fingerprint :)");
          expect(customFingerprint).not.toEqual(newCustomFingerprint);
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>var crawlPage = require('../biz').crawlPage;
var model = require('../model');
var co = require('co');
var cheerio = require('cheerio');
var _ = require('underscore');
var _s = require('underscore.string');
var resolve = require('url').resolve;
var getRootURL = require('../../modules/other/pathUtils').getRootURL;
var extractImgSrc = require('../biz').extractImgSrc;
/*
 详情
 * */
module.exports = Detail;
function Detail(url) {
    this.url = url;
}

/*
 crawl detail page
 * */
Detail.prototype.getDetail = function () {
    var boundParse = parse.bind(this);
    return crawlPage(this.url, boundParse);
};

/*
 * parse houses
 * */
function parse(fn) {
    var url = this.url;
    return function (err, res) {
        var $ = cheerio.load(res, {
            normalizeWhitespace: true,
            xmlMode: true
        });
        //collect page info
        var house = {};
        house.title = $('div.bigtitle h1').text().trim();
        var $time = $('li.time');
        if($time){
            var $timeScript = $time.children();
            if($timeScript.length > 0){
                house.publishDate = new Date();
            } else {
                house.publishDate = $time.text().trim();
            }
        }
        var $price = $('span.bigpri');
        house.price = $price.text().trim();
        house.payment = $price.next().text().trim();
        var $infos = $('div.su_tit:contains("概况")').next().text().trim().split('  ');
        console.log($infos);
        house.houseType = $infos[0].trim();
        house.area = $infos[1].trim();
        house.buildingType = $infos[2].trim();
        if($infos[3])
            house.fitment = $infos[3].trim();
        if($infos[4])
            house.orientation = $infos[4].trim();
        house.floor = $('div.su_tit:contains("楼层")').next().text().trim();
        var $zones = $('div.su_tit:contains("区域")').next().text().replace('找附近工作','').trim().split('-');
        house.district = $zones[0].trim();
        house.bizDistrict = $zones[1].trim();
        house.building = $zones[2].trim();
        house.address = $('div.su_tit:contains("地址")').next().text().trim();
        var $contact = $('div.su_tit:contains("联系")').next();
        house.contact = $contact.find('a').text();
        house.publisher = $contact.find('em').text();
        var $phone = $('#t_phone');
        if($phone) {
            var $phoneScript = $phone.children();
            if($phoneScript.length > 0){ // 必须加Referer
                house.phonePic =  extractImgSrc($($phoneScript[0]).html());
            } else {
                house.phone = $phone.text().trim();
            }
        }
        fn(err, house);
    };
}

co(function*() {
    var d = new Detail('http://cd.58.com/zufang/20059098777351x.shtml');
    var house = yield d.getDetail();
    console.log(house);
});<commit_msg>re-construct detail.<commit_after>var crawlPage = require('../biz').crawlPage;
var model = require('../model');
var co = require('co');
var cheerio = require('cheerio');
var _ = require('underscore');
var _s = require('underscore.string');
var resolve = require('url').resolve;
var getRootURL = require('../../modules/other/pathUtils').getRootURL;
var extractImgSrc = require('../biz').extractImgSrc;
var ent = require('ent');
/*
 详情
 * */
module.exports = Detail;
function Detail(url) {
    this.url = url;
}

/*
 crawl detail page
 * */
Detail.prototype.getDetail = function () {
    var boundParse = parse.bind(this);
    return crawlPage(this.url, boundParse);
};

/*
 * parse houses
 * */
function parse(fn) {
    var url = this.url;
    return function (err, res) {
        var $ = cheerio.load(res, {
            normalizeWhitespace: true,
            xmlMode: true
        });
        //collect page info
        var house = {};
        house.title = $('div.bigtitle h1').text().trim();
        var $time = $('li.time');
        if ($time) {
            var $timeScript = $time.children();
            if ($timeScript.length > 0) {
                house.publishDate = new Date();
            } else {
                house.publishDate = $time.text().trim();
            }
        }
        var $price = $('span.bigpri');
        house.price = $price.text().trim();
        house.payment = $price.next().text().trim();
        house.overview = ent.decode($('div.su_tit:contains("概况")').next().text()).trim();
        var $zone = $('div.su_tit:contains("区域")').next();
        if ($zone.children() && $zone.children().length > 0) {
            var zoneText = ent.decode($zone.text());
            house.zone = new RegExp(/(\S+\s-\s\S+\s-\s\S+).?/g).exec(zoneText)[1];
        } else {
            house.zone = $zone.text() + ' - ' + $zone.next().text() + ' - ' + $zone.next().next().text();
        }
        var $address = $('div.su_tit:contains("地址")').next();
        house.address = new RegExp(/([^\s]+)/g).exec($address.text())[1];
        fn(err, house);
    };
}

co(function*() {
    //var d = new Detail('http://cd.58.com/zufang/20059098777351x.shtml');
    //var d = new Detail('http://bj.58.com/zufang/20114437262986x.shtml');
    var d = new Detail('http://bj.58.com/zufang/19562028299138x.shtml');
    var house = yield d.getDetail();
    console.log(house);
});<|endoftext|>


<commit_before>//calling animation
var Site = (function() {
    return {
        init: function() {
            // this.moto_init();
            // this.mob_nav_init();
            this.jpre_loader_init();
            this.accordx('#sidebar-wtengah');
            this.hoverxa();
            this.datenya();
            this.build_prefetch();
        },
        moto_init: function() {
            var
                frame = $('#header-wrapper')[0],
                motio = new Motio(frame, {
                    fps: 30,
                    speedX: 60,
                    bgWidth: 1024,
                    bgHeight: 1024
                });
            motio.play();
            // Update the animation speed & direction based on a cursor position
            $('#header-wrapper').on('mousemove', function(event) {
                motio.set('speedX', event.pageX - 0 - motio.width / 2);
                motio.set('speedY', event.pageY - 0 - motio.height / 2);
            });
            $('#header-wrapper').on('mouseout', function(event) {
                motio.set('speedX', 30);
                motio.set('speedY', 0);
            });
        },
        mob_nav_init: function() {
            $("#navinti ul").removeClass("hidden");
            $("#navinti li").hoverTimeout(100, function() {
                $(this).parent("ul").css("overflow", "visible");
                $(this).children("ul").filter(":not(:animated)").slideDown()
            }, 500, function() {
                $(this).parent("ul").css("overflow", "visible");
                $(this).children("ul").slideUp(800, "easeInExpo")
            });
            $("#mobilenav").toggle(function() {
                $(this).addClass("active");
                $("#navinti").slideDown();
                return false
            }, function() {
                $(this).removeClass("active");
                $("#navinti").slideUp();
                return false
            });

            function a() {
                if ($(window).width() > 767) {
                    $("#navinti").css("display", "block")
                } else {
                    if ($(window).width() <= 767 && $("#mobilenav").attr("class") === "active") {
                        $("#navinti").css("display", "block")
                    } else {
                        if ($(window).width() <= 767 && $("#mobilenav").attr("class") !== "active") {
                            $("#navinti").css("display", "none")
                        }
                    }
                }
            }
            $(window).resize(a);
        },
        jpre_loader_init: function() {
            $('body').jpreLoader({
                splashID: "#jSplash",
                showSplash: true,
                showPercentage: false,
                autoClose: true,
                splashFunction: function() {
                    $('#ball, #ball-0, #ball-1').delay(250).animate({
                        'opacity': 1
                    }, 1500, 'easeOutExpo');
                }

            }, function() { //callback function
                $("#outer-wrapper")
                    .delay(150)
                    .animate({
                        'opacity': 1,
                        'marginTop': 0
                    }, 500, 'easeOutExpo');
                $("#header-wrapper")
                    .delay(200)
                    .animate({
                        'opacity': 1,
                        'marginTop': 0
                    }, 500, 'easeOutExpo');
                $("#main-wrapper")
                    .delay(250)
                    .animate({
                        'opacity': 1,
                        'marginLeft': 0
                    }, 500, 'easeOutExpo');
                $("#sidebar-wrapper")
                    .delay(300)
                    .animate({
                        'opacity': 1,
                        'marginRight': 0
                    }, 500, 'easeOutExpo');
            });
        },
        accordx: function(b) {
            $(b + " .widget-content").hide();
            $(b + " h2:last").addClass("active").next().slideDown("slow");
            $(b + " h2").css("cursor", "pointer").click(function() {
                if ($(this).next().is(":hidden")) {
                    $(b + " h2").removeClass("active").next().slideUp("slow");
                    $(this).toggleClass("active").next().slideDown("slow")
                }
            });
        },
        hoverxa: function() {
            $(".post").hover(function() {
                $(".jump-link", this).animate({
                    opacity: 1,
                    bottom: 0
                }, 500)
            }, function() {
                $(".jump-link", this).animate({
                    opacity: 0,
                    bottom: -25
                }, 700)
            });
            $("a").hover(function() {
                $("img", this).animate({
                    opacity: 0.5
                }, 500)
            }, function() {
                $("img", this).animate({
                    opacity: 1
                }, 300)
            });
        },
        build_prefetch: function() {
            $('a,img,script').each(function(){
                $(this).attr('rel','prefetch');
            });
        },
        datenya: function() {
            $(".timestamp-link .updated.published").each(function() {
                var g = $(this).attr("title");
                var a = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
                if (g != "") {
                    var i = g.substring(0, 10),
                        f = i.substring(0, 4),
                        b = i.substring(5, 7),
                        e = i.substring(8, 10),
                        c = a[parseInt(b, 10) - 1]
                }
                var d = $(this).parents(".post");
                var h = d.children(".datex");
                $("strong", h).html("posted by " +e+f+c);
                // $("small", h).html(f);
                // $("span", h).html(c)
            });
        },
    }
}());

Site.init();<commit_msg>added<commit_after>//calling animation
var Site = (function() {
    return {
        init: function() {
            // this.moto_init();
            // this.mob_nav_init();
            this.jpre_loader_init();
            this.accordx('#sidebar-wtengah');
            this.hoverxa();
            this.datenya();
            this.build_prefetch();
        },
        moto_init: function() {
            var
                frame = $('#header-wrapper')[0],
                motio = new Motio(frame, {
                    fps: 30,
                    speedX: 60,
                    bgWidth: 1024,
                    bgHeight: 1024
                });
            motio.play();
            // Update the animation speed & direction based on a cursor position
            $('#header-wrapper').on('mousemove', function(event) {
                motio.set('speedX', event.pageX - 0 - motio.width / 2);
                motio.set('speedY', event.pageY - 0 - motio.height / 2);
            });
            $('#header-wrapper').on('mouseout', function(event) {
                motio.set('speedX', 30);
                motio.set('speedY', 0);
            });
        },
        mob_nav_init: function() {
            $("#navinti ul").removeClass("hidden");
            $("#navinti li").hoverTimeout(100, function() {
                $(this).parent("ul").css("overflow", "visible");
                $(this).children("ul").filter(":not(:animated)").slideDown()
            }, 500, function() {
                $(this).parent("ul").css("overflow", "visible");
                $(this).children("ul").slideUp(800, "easeInExpo")
            });
            $("#mobilenav").toggle(function() {
                $(this).addClass("active");
                $("#navinti").slideDown();
                return false
            }, function() {
                $(this).removeClass("active");
                $("#navinti").slideUp();
                return false
            });

            function a() {
                if ($(window).width() > 767) {
                    $("#navinti").css("display", "block")
                } else {
                    if ($(window).width() <= 767 && $("#mobilenav").attr("class") === "active") {
                        $("#navinti").css("display", "block")
                    } else {
                        if ($(window).width() <= 767 && $("#mobilenav").attr("class") !== "active") {
                            $("#navinti").css("display", "none")
                        }
                    }
                }
            }
            $(window).resize(a);
        },
        jpre_loader_init: function() {
            $('body').jpreLoader({
                splashID: "#jSplash",
                showSplash: true,
                showPercentage: false,
                autoClose: true,
                splashFunction: function() {
                    $('#ball, #ball-0, #ball-1').delay(250).animate({
                        'opacity': 1
                    }, 1500, 'easeOutExpo');
                }

            }, function() { //callback function
                $("#outer-wrapper")
                    .delay(150)
                    .animate({
                        'opacity': 1,
                        'marginTop': 0
                    }, 500, 'easeOutExpo');
                $("#header-wrapper")
                    .delay(200)
                    .animate({
                        'opacity': 1,
                        'marginTop': 0
                    }, 500, 'easeOutExpo');
                $("#main-wrapper")
                    .delay(250)
                    .animate({
                        'opacity': 1,
                        'marginLeft': 0
                    }, 500, 'easeOutExpo');
                $("#sidebar-wrapper")
                    .delay(300)
                    .animate({
                        'opacity': 1,
                        'marginRight': 0
                    }, 500, 'easeOutExpo');
            });
        },
        accordx: function(b) {
            $(b + " .widget-content").hide();
            $(b + " h2:last").addClass("active").next().slideDown("slow");
            $(b + " h2").css("cursor", "pointer").click(function() {
                if ($(this).next().is(":hidden")) {
                    $(b + " h2").removeClass("active").next().slideUp("slow");
                    $(this).toggleClass("active").next().slideDown("slow")
                }
            });
        },
        hoverxa: function() {
            $(".post").hover(function() {
                $(".jump-link", this).animate({
                    opacity: 1,
                    bottom: 0
                }, 500)
            }, function() {
                $(".jump-link", this).animate({
                    opacity: 0,
                    bottom: -25
                }, 700)
            });
            $("a").hover(function() {
                $("img", this).animate({
                    opacity: 0.5
                }, 500)
            }, function() {
                $("img", this).animate({
                    opacity: 1
                }, 300)
            });
        },
        build_prefetch: function() {
            $('a,img,script').each(function(){
                $(this).attr('rel','prefetch');
            });
        },
        datenya: function() {
            $(".timestamp-link .updated.published").each(function() {
                var g = $(this).attr("title");
                var a = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
                if (g != "") {
                    var i = g.substring(0, 10),
                        f = i.substring(0, 4),
                        b = i.substring(5, 7),
                        e = i.substring(8, 10),
                        c = a[parseInt(b, 10) - 1]
                }
                var d = $(this).parents(".post");
                var h = d.children(".datex");
                $("strong", h).html("Posted by " +e+" "+f+" "+c);
                // $("small", h).html(f);
                // $("span", h).html(c)
            });
        },
    }
}());

Site.init();<|endoftext|>


<commit_before>// Welcome!
// Add your github user if you accepted the challenge!

var players = [
    'raphamorim',
    'israelst',
    'afonsopacifer',
    'rafaelfragosom',
    'brunokinoshita',
    'paulinhoerry',
    'enieber',
    'alanrsoares',
    'viniciusdacal',
    'thiagosantana',
    'brunodsgn',
    'danilorb',
    'douglasPinheiro',
    'michelwilhelm',
    'joaovsilva',
    'rafaelstz',
    'andersonweb',
    'luhad',
    'pablobfonseca',
    'willianjusten',
    'vitorleal',
    'IAMFELIPEMATTOS',
    'JulianSansat',
    'brenopolanski',
    'Pompeu',
    'filipedeschamps',
    'felipesousa',
    'gpedro',
    'leaofelipe',
    'wedneyyuri',
    'jonathanveg',
    'filipe1309',
    'afgoulart',
    'helquisson',
    'vulcanobr',
    'guilouro',
    'pedropolisenso',
    'jozadaquebatista',
    'alfv89',
    'jugoncalves',
    'guilhermeepaixaoo',
	'morvanabonin',
    'andrecgro',
    'thulioph',
    'lucasviola',
    'iceberg20',
];

module.exports = players;
<commit_msg>add username in challengers.js<commit_after>// Welcome!
// Add your github user if you accepted the challenge!

var players = [
    'raphamorim',
    'israelst',
    'afonsopacifer',
    'rafaelfragosom',
    'brunokinoshita',
    'paulinhoerry',
    'enieber',
    'alanrsoares',
    'viniciusdacal',
    'thiagosantana',
    'brunodsgn',
    'danilorb',
    'douglasPinheiro',
    'michelwilhelm',
    'joaovsilva',
    'rafaelstz',
    'andersonweb',
    'luhad',
    'pablobfonseca',
    'willianjusten',
    'vitorleal',
    'IAMFELIPEMATTOS',
    'JulianSansat',
    'brenopolanski',
    'Pompeu',
    'filipedeschamps',
    'felipesousa',
    'gpedro',
    'leaofelipe',
    'wedneyyuri',
    'jonathanveg',
    'filipe1309',
    'afgoulart',
    'helquisson',
    'vulcanobr',
    'guilouro',
    'pedropolisenso',
    'jozadaquebatista',
    'alfv89',
    'jugoncalves',
    'guilhermeepaixaoo',
	'morvanabonin',
    'andrecgro',
    'thulioph',
    'lucasviola',
    'iceberg20',
    'welksonramos',
];

module.exports = players;
<|endoftext|>


<commit_before>import express from 'express';
import bodyParser from 'body-parser';

const app = express();

// Set express up to automatically parse incoming JSON requests
// into the request object
app.use(bodyParser.json());

// Set up static content paths
app.use('/jspm_packages', express.static(`${__dirname}/../jspm_packages`));
app.use('/dist-client', express.static(`${__dirname}/../dist-client`));
app.use('/assets', express.static(`${__dirname}/../assets`));

// Any request without a path should render index.html
app.get('/', (req, res) => {
  res.sendFile(path.resolve(`${__dirname}/../index.html`));
});

// Any request to /config.js should render the root config.js
app.get('/config.js', (req, res) => {
  res.sendFile(path.resolve(`${__dirname}/../config.js`));
});

// Store the app globally for convenience
global.app = app;
<commit_msg>Added app.listen with a default port.<commit_after>import express from 'express';
import bodyParser from 'body-parser';
import path from 'path';

const app = express();

// Set express up to automatically parse incoming JSON requests
// into the request object
app.use(bodyParser.json());

// Set up static content paths
app.use('/jspm_packages', express.static(`${__dirname}/../jspm_packages`));
app.use('/dist-client', express.static(`${__dirname}/../dist-client`));
app.use('/assets', express.static(`${__dirname}/../assets`));

// Any request without a path should render index.html
app.get('/', (req, res) => {
  res.sendFile(path.resolve(`${__dirname}/../index.html`));
});

// Any request to /config.js should render the root config.js
app.get('/config.js', (req, res) => {
  res.sendFile(path.resolve(`${__dirname}/../config.js`));
});

// Store the app globally for convenience
global.app = app;

// Start the web server
var server = app.listen(3000, () => {
  const host = server.address().address;
  const port = server.address().port;

  console.log(`Server listening at http://${host}:${port}`);
});
<|endoftext|>


<commit_before>/* ***************************************
 * CLASS: DOM -> DATA
 * ***************************************/
class Dom_DATA extends Dom_CSS
{
	constructor ()
	{
		let self = super();

		self.data 		= (key, val) => {

			// Start timing now
			console.time("EXECUTION_TIME_DATA");

			let returnAttr = false;

			(self.element.length >= 1 ) &&
		 	self.element.forEach(( element ) => {

		 		('undefined' == typeof element.dataset[key] && 'undefined' == typeof val) && console.error("This data '"+key+"' no exist in this element: " +element.nodeName);

		 		('undefined' == typeof element.dataset[key] && 'undefined' != typeof val) && (element.dataset[key]=val, returnAttr=true);

		 		('undefined' != typeof element.dataset[key]) && (returnAttr=element.dataset[key]);

		 	});

			// Start timing now
			console.timeEnd("EXECUTION_TIME_DATA");

			return returnAttr;
		}

		self.attr 		= (key, val) => {

			// Start timing now
			console.time("EXECUTION_TIME_ATTR");

			val = ('boolean' == typeof val && val == true) && 'true';

			let exe = (type) => {

				let returnAttr = '';

				(self.element.length >= 1 ) &&
			 	self.element.forEach(( element ) => {

			 		(!element.hasAttribute(key) && type == 'get') && console.error('This atribute not exist on element');

			 		returnAttr = element[type+"Attribute"](key,val);

			 	});

			 	return returnAttr;
			}

			('boolean' == typeof val && val == false) && exe('remove');

			('string' == typeof key && 'string' == typeof val) && exe('set');

			// Start timing now
			console.timeEnd("EXECUTION_TIME_ATTR");

			return ('string' == typeof key && 'undefined' == typeof val) && exe('get');

		} // val = string or bool
		self.prop 		= (key, val) => {

			// Start timing now
			console.time("EXECUTION_TIME_PROP");

			let returnVal = false;

			(self.element.length >= 1 ) &&
		 	self.element.forEach(( element ) => {

		 		('boolean' == typeof val) && (element[key]=val);
		 		returnVal = element[key];
		 	});

			// Start timing now
			console.timeEnd("EXECUTION_TIME_PROP");

			return returnVal;

		} // val = string or bool

		self.val 		= (val) => {

			// Start timing now
			console.time("EXECUTION_TIME_VAL");

			let returnVal = '';

			(self.element.length >= 1 ) &&
		 	self.element.forEach(( element ) => {

		 		returnVal = ('string' == typeof val) ? (element.value=val) : element.value;
		 	});

		 	// Start timing now
			console.timeEnd("EXECUTION_TIME_VAL");

		 	return returnVal;
		}

		return self;
	}
}<commit_msg>Delete 07_2_Dom_DATA.js<commit_after><|endoftext|>