<commit_before>function initGL(canvas) {
  var gl;
  try {
    gl = canvas.getContext("experimental-webgl", {preserveDrawingBuffer: true});
    gl.viewportWidth = canvas.width;
    gl.viewportHeight = canvas.height;
  } catch (e) {
  }
  if (!gl) {
    alert("Could not initialise WebGL, sorry :-(");
  }
  return gl;
}

function getShader(id) {
  var shaderScript = document.getElementById(id);
  if (!shaderScript) {
    return null;
  }

  var str = "";
  var k = shaderScript.firstChild;
  while (k) {
    if (k.nodeType == 3) {
      str += k.textContent;
    }
    k = k.nextSibling;
  }

  var shader;
  if (shaderScript.type == "x-shader/x-fragment") {
    shader = gl.createShader(gl.FRAGMENT_SHADER);
  } else if (shaderScript.type == "x-shader/x-vertex") {
    shader = gl.createShader(gl.VERTEX_SHADER);
  } else {
    return null;
  }

  gl.shaderSource(shader, str);
  gl.compileShader(shader);

  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    alert(gl.getShaderInfoLog(shader));
    return null;
  }

  return shader;
}

function initShaders(type) {
  var shaderProgram;

  var fragmentShader = getShader(type+"-fs");
  var vertexShader = getShader("shader-vs");

  shaderProgram = gl.createProgram();

  gl.attachShader(shaderProgram, vertexShader);
  gl.attachShader(shaderProgram, fragmentShader);
  gl.linkProgram(shaderProgram);

  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
      alert("Could not initialise shaders");
  }

  gl.useProgram(shaderProgram);

  shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
  gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

  shaderProgram.samplerUniform = gl.getUniformLocation(shaderProgram, "uSampler");
  shaderProgram.aUniform = gl.getUniformLocation(shaderProgram, "a");
  shaderProgram.bUniform = gl.getUniformLocation(shaderProgram, "b");
  shaderProgram.cUniform = gl.getUniformLocation(shaderProgram, "c");
  return shaderProgram;
}

function handleLoadedTexture(texture) {
  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.image);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  gl.bindTexture(gl.TEXTURE_2D, null);
}

function initTexture(src) {
  var tex;
  tex = gl.createTexture();
  tex.image = new Image();
  tex.image.onload = function () {
    handleLoadedTexture(tex);
  };
  tex.image.src = src;
  return tex;
}

var rttFramebuffer;
var rttTexture;

function initTextureFramebuffer() {
    var rttFramebuffer;
    var rttTexture;
    rttFramebuffer = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, rttFramebuffer);
    rttFramebuffer.width = 512;
    rttFramebuffer.height = 512;

    rttTexture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, rttTexture);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, rttFramebuffer.width, rttFramebuffer.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);

    var renderbuffer = gl.createRenderbuffer();
    gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer);
    gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, rttFramebuffer.width, rttFramebuffer.height);

    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, rttTexture, 0);
    gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer);

    gl.bindTexture(gl.TEXTURE_2D, null);
    gl.bindRenderbuffer(gl.RENDERBUFFER, null);
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);

    return [rttTexture,rttFramebuffer];
}

function initBuffers() {
  var positionBuffer;
  positionBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  vertices = [
      // Front face
      -1, -1,  0,
       1, -1,  0,
       1,  1,  0,
      -1,  1,  0,
  ];
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  positionBuffer.itemSize = 3;
  positionBuffer.numItems = 4;
  return positionBuffer;
}
var b = 0.8;
var a = 0.8;
var c = 1;
function draw(program,texture){
  gl.useProgram(program);
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.vertexAttribPointer(program.vertexPositionAttribute, buffer.itemSize, gl.FLOAT, false, 0, 0);

  gl.activeTexture(gl.TEXTURE0);
  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.uniform1i(program.samplerUniform, 0);

  gl.uniform1f(program.aUniform, a);
  gl.uniform1f(program.bUniform, b);
  gl.uniform1f(program.cUniform, c);
  gl.drawArrays(gl.TRIANGLE_FAN, 0,4);
}

function drawScene(){
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  gl.bindFramebuffer(gl.FRAMEBUFFER, recreate.buffer);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.viewport(0, 0, recreate.buffer.width, recreate.buffer.height);
    draw(simulate.program,simulate.texture);
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);

  gl.viewport(0,gl.viewportHeight/2, gl.viewportWidth/2, gl.viewportHeight/2);
  draw(simple.program,simple.texture);
  gl.viewport(gl.viewportWidth/2, gl.viewportHeight/2, gl.viewportWidth/2, gl.viewportHeight/2);
  draw(simulate.program,simulate.texture);
  gl.bindFramebuffer(gl.FRAMEBUFFER, diff.buffer);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.viewport(0, 0, diff.buffer.width, diff.buffer.height);
    draw(recreate.program,recreate.texture);
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  gl.viewport(0,0, gl.viewportWidth/2, gl.viewportHeight/2);
  draw(simple.program,diff.texture);

  gl.viewport(gl.viewportWidth/2,0, gl.viewportWidth/2, gl.viewportHeight/2);
  gl.useProgram(diff.program);
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.vertexAttribPointer(diff.program.vertexPositionAttribute, buffer.itemSize, gl.FLOAT, false, 0, 0);

  gl.activeTexture(gl.TEXTURE0);
  gl.bindTexture(gl.TEXTURE_2D, simple.texture);
  gl.uniform1i(diff.program.samplerUniform, 0);
  gl.activeTexture(gl.TEXTURE1);
  gl.bindTexture(gl.TEXTURE_2D, diff.texture);
  gl.uniform1i(diff.program.samplerBUniform, 1);
  gl.activeTexture(gl.TEXTURE0);

  gl.uniform1f(diff.program.aUniform, a);
  gl.uniform1f(diff.program.bUniform, b);
  gl.uniform1f(diff.program.cUniform, c);
  gl.drawArrays(gl.TRIANGLE_FAN, 0,4);

  drawing = false;
}

var canvas = document.getElementById("canvas");
var gl = initGL(canvas);
var buffer = initBuffers();

var simple = {};
simple.program = initShaders('simple');
simple.texture = initTexture('test.gif');

var simulate = {};
simulate.program = initShaders('simulate');
simulate.texture = simple.texture;

var recreate = {};
recreate.program = initShaders('recreate');
var framebuffer = initTextureFramebuffer();
recreate.texture = framebuffer[0];
recreate.buffer = framebuffer[1];

var diff = {};
diff.program = initShaders('diff');
gl.useProgram(diff.program);
diff.program.samplerBUniform = gl.getUniformLocation(diff.program, "samplerB");
framebuffer = initTextureFramebuffer();
diff.texture = framebuffer[0];
diff.buffer = framebuffer[1];

gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.enable(gl.DEPTH_TEST);

var drawing = false;
document.onkeydown = function(e){
  if(e.keyCode == 40){
    b+=0.01;
  }
  if(e.keyCode == 39){
    a+=0.01;
  }
  if(e.keyCode == 38){
    b-=0.01;
  }
  if(e.keyCode == 37){
    a-=0.01;
  }
  if(!drawing){
    requestAnimationFrame(drawScene);
    drawing = true;
  }
};

var input = document.getElementById('input');
var ctx=input.getContext("2d");
ctx.beginPath();
ctx.fillRect(0,0,512,512);
ctx.stroke();
var x,y,down;
input.onmousedown = function(e){
  down = true;
  console.log('down');
  x = e.offsetX;
  y = e.offsetY;
};
input.onmousemove = function(e){
  if(down){
    ctx.beginPath();
    ctx.strokeStyle="#FFFFFF";
    ctx.lineWidth = 15;
    ctx.moveTo(x,y);
    ctx.lineTo(e.offsetX,e.offsetY);
    ctx.lineCap = 'round';
    ctx.stroke();
    x = e.x;
    y = e.y;
  }else{
    console.log('not down yet');
  }
};
input.onmouseup = function(e){
  down = false;
  console.log('up');
};

function setImage(){
  var url = input.toDataURL();
  simple.texture = initTexture(url);
  simulate.texture = simple.texture;
  setTimeout(drawScene,10);
}
<commit_msg>fix done derp<commit_after>function initGL(canvas) {
  var gl;
  try {
    gl = canvas.getContext("experimental-webgl", {preserveDrawingBuffer: true});
    gl.viewportWidth = canvas.width;
    gl.viewportHeight = canvas.height;
  } catch (e) {
  }
  if (!gl) {
    alert("Could not initialise WebGL, sorry :-(");
  }
  return gl;
}

function getShader(id) {
  var shaderScript = document.getElementById(id);
  if (!shaderScript) {
    return null;
  }

  var str = "";
  var k = shaderScript.firstChild;
  while (k) {
    if (k.nodeType == 3) {
      str += k.textContent;
    }
    k = k.nextSibling;
  }

  var shader;
  if (shaderScript.type == "x-shader/x-fragment") {
    shader = gl.createShader(gl.FRAGMENT_SHADER);
  } else if (shaderScript.type == "x-shader/x-vertex") {
    shader = gl.createShader(gl.VERTEX_SHADER);
  } else {
    return null;
  }

  gl.shaderSource(shader, str);
  gl.compileShader(shader);

  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    alert(gl.getShaderInfoLog(shader));
    return null;
  }

  return shader;
}

function initShaders(type) {
  var shaderProgram;

  var fragmentShader = getShader(type+"-fs");
  var vertexShader = getShader("shader-vs");

  shaderProgram = gl.createProgram();

  gl.attachShader(shaderProgram, vertexShader);
  gl.attachShader(shaderProgram, fragmentShader);
  gl.linkProgram(shaderProgram);

  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
      alert("Could not initialise shaders");
  }

  gl.useProgram(shaderProgram);

  shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
  gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

  shaderProgram.samplerUniform = gl.getUniformLocation(shaderProgram, "uSampler");
  shaderProgram.aUniform = gl.getUniformLocation(shaderProgram, "a");
  shaderProgram.bUniform = gl.getUniformLocation(shaderProgram, "b");
  shaderProgram.cUniform = gl.getUniformLocation(shaderProgram, "c");
  return shaderProgram;
}

function handleLoadedTexture(texture) {
  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.image);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  gl.bindTexture(gl.TEXTURE_2D, null);
}

function initTexture(src) {
  var tex;
  tex = gl.createTexture();
  tex.image = new Image();
  tex.image.onload = function () {
    handleLoadedTexture(tex);
  };
  tex.image.src = src;
  return tex;
}

var rttFramebuffer;
var rttTexture;

function initTextureFramebuffer() {
    var rttFramebuffer;
    var rttTexture;
    rttFramebuffer = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, rttFramebuffer);
    rttFramebuffer.width = 512;
    rttFramebuffer.height = 512;

    rttTexture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, rttTexture);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, rttFramebuffer.width, rttFramebuffer.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);

    var renderbuffer = gl.createRenderbuffer();
    gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer);
    gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, rttFramebuffer.width, rttFramebuffer.height);

    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, rttTexture, 0);
    gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer);

    gl.bindTexture(gl.TEXTURE_2D, null);
    gl.bindRenderbuffer(gl.RENDERBUFFER, null);
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);

    return [rttTexture,rttFramebuffer];
}

function initBuffers() {
  var positionBuffer;
  positionBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  vertices = [
      // Front face
      -1, -1,  0,
       1, -1,  0,
       1,  1,  0,
      -1,  1,  0,
  ];
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  positionBuffer.itemSize = 3;
  positionBuffer.numItems = 4;
  return positionBuffer;
}
var b = 0.8;
var a = 0.8;
var c = 1;
function draw(program,texture){
  gl.useProgram(program);
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.vertexAttribPointer(program.vertexPositionAttribute, buffer.itemSize, gl.FLOAT, false, 0, 0);

  gl.activeTexture(gl.TEXTURE0);
  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.uniform1i(program.samplerUniform, 0);

  gl.uniform1f(program.aUniform, a);
  gl.uniform1f(program.bUniform, b);
  gl.uniform1f(program.cUniform, c);
  gl.drawArrays(gl.TRIANGLE_FAN, 0,4);
}

function drawScene(){
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  gl.bindFramebuffer(gl.FRAMEBUFFER, recreate.buffer);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.viewport(0, 0, recreate.buffer.width, recreate.buffer.height);
    draw(simulate.program,simulate.texture);
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);

  gl.viewport(0,gl.viewportHeight/2, gl.viewportWidth/2, gl.viewportHeight/2);
  draw(simple.program,simple.texture);
  gl.viewport(gl.viewportWidth/2, gl.viewportHeight/2, gl.viewportWidth/2, gl.viewportHeight/2);
  draw(simulate.program,simulate.texture);
  gl.bindFramebuffer(gl.FRAMEBUFFER, diff.buffer);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.viewport(0, 0, diff.buffer.width, diff.buffer.height);
    draw(recreate.program,recreate.texture);
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  gl.viewport(0,0, gl.viewportWidth/2, gl.viewportHeight/2);
  draw(simple.program,diff.texture);

  gl.viewport(gl.viewportWidth/2,0, gl.viewportWidth/2, gl.viewportHeight/2);
  gl.useProgram(diff.program);
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.vertexAttribPointer(diff.program.vertexPositionAttribute, buffer.itemSize, gl.FLOAT, false, 0, 0);

  gl.activeTexture(gl.TEXTURE0);
  gl.bindTexture(gl.TEXTURE_2D, simple.texture);
  gl.uniform1i(diff.program.samplerUniform, 0);
  gl.activeTexture(gl.TEXTURE1);
  gl.bindTexture(gl.TEXTURE_2D, diff.texture);
  gl.uniform1i(diff.program.samplerBUniform, 1);
  gl.activeTexture(gl.TEXTURE0);

  gl.uniform1f(diff.program.aUniform, a);
  gl.uniform1f(diff.program.bUniform, b);
  gl.uniform1f(diff.program.cUniform, c);
  gl.drawArrays(gl.TRIANGLE_FAN, 0,4);

  drawing = false;
}

var canvas = document.getElementById("canvas");
var gl = initGL(canvas);
var buffer = initBuffers();

var simple = {};
simple.program = initShaders('simple');
simple.texture = initTexture('test.gif');

var simulate = {};
simulate.program = initShaders('simulate');
simulate.texture = simple.texture;

var recreate = {};
recreate.program = initShaders('recreate');
var framebuffer = initTextureFramebuffer();
recreate.texture = framebuffer[0];
recreate.buffer = framebuffer[1];

var diff = {};
diff.program = initShaders('diff');
gl.useProgram(diff.program);
diff.program.samplerBUniform = gl.getUniformLocation(diff.program, "samplerB");
framebuffer = initTextureFramebuffer();
diff.texture = framebuffer[0];
diff.buffer = framebuffer[1];

gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.enable(gl.DEPTH_TEST);

var drawing = false;
document.onkeydown = function(e){
  if(e.keyCode == 40){
    b+=0.01;
  }
  if(e.keyCode == 39){
    a+=0.01;
  }
  if(e.keyCode == 38){
    b-=0.01;
  }
  if(e.keyCode == 37){
    a-=0.01;
  }
  if(!drawing){
    requestAnimationFrame(drawScene);
    drawing = true;
  }
};

var input = document.getElementById('input');
var ctx=input.getContext("2d");
ctx.beginPath();
ctx.fillRect(0,0,512,512);
ctx.stroke();
var x,y,down;
input.onmousedown = function(e){
  down = true;
  console.log('down');
  x = e.offsetX;
  y = e.offsetY;
};
input.onmousemove = function(e){
  if(down){
    ctx.beginPath();
    ctx.strokeStyle="#FFFFFF";
    ctx.lineWidth = 15;
    ctx.moveTo(x,y);
    ctx.lineTo(e.offsetX,e.offsetY);
    ctx.lineCap = 'round';
    ctx.stroke();
    x = e.offsetX;
    y = e.offsetY;
  }else{
    console.log('not down yet');
  }
};
input.onmouseup = function(e){
  down = false;
  console.log('up');
};

function setImage(){
  var url = input.toDataURL();
  simple.texture = initTexture(url);
  simulate.texture = simple.texture;
  setTimeout(drawScene,10);
}
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-20 10:12:51<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>/*!
 * git-repo-name <https://github.com/jonschlinkert/git-repo-name>
 *
 * Copyright (c) 2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var assert = require('assert');
var name = require('./');

describe('name', function () {
  it('should return the name from git config:', function () {
    assert(name() === 'git-repo-name');
  });
});
<commit_msg>adds async/sync tests<commit_after>'use strict';

require('mocha');
var assert = require('assert');
var repoName = require('./');

describe('async', function () {
  it('should return the name from git config:', function (done) {
    repoName(function (err, res) {
      if (err) return done(err);
      assert(res === 'git-repo-name');
      done();
    });
  });
});

describe('sync', function () {
  it('should return the name from git config:', function () {
    assert(repoName.sync() === 'git-repo-name');
  });
});
<|endoftext|>


<commit_before>/**
 * Created by gucheng on 5/18/16.
 */
var expect = require('chai').expect;
var fetch = require('node-fetch');
var FetchQL = require('./index.mjs');

const testQuery = `
  query Query {
    user(username: "BlinkTunnel") {
      name
      id
      avatar_url
      html_url
      type
      name
      company
      blog
      location
      email
      bio
      public_repos
      followers
      following
      repositories {
        id
        name
        description
        stargazers_count
      }
    }
  }
`;

const testUrl = 'http://127.0.0.1:3000/another';
const testQueryParams = {
  operationName: 'Query',
  query: testQuery,
  variables: {}
};

var testQL = new FetchQL({
  url: testUrl
});

describe('FetchQL', () => {
  describe('#constructor', () => {
    it('should return an Object', () => {
      expect(testQL).to.be.a('object');
    });
  });

  describe('#methods', () => {
    const methods = ['query', 'getUrl', 'setUrl', 'getEnumTypes'];
    methods.map((method) => {
      it(`${method}() should be a function`, () => {
        expect(testQL[method]).to.be.a('function');
      })
    })
  });

  describe('#getUrl()', () => {
    let currentUrl = testQL.getUrl();
    it(`should return url "${testUrl}"`, () => {
      expect(currentUrl).to.be.a('string');
      expect(currentUrl).to.eql(testUrl);
    });
  });

  describe('#query()', () => {
    let call = testQL.query(testQueryParams);
    it('should return a Promise', () => {
      expect(call).to.be.a('promise');
    });

    it('should pass an object of response data in promise', () => {
      return call
        .then(response => expect(response).to.be.a('object'))
        .catch(error => expect(error).to.be.a('object'))
    });
  });

  describe('#getEnumTypes(["UserType"])', () => {
    let call = testQL.getEnumTypes(['UserType']);
    it('should return a Promise', () => {
      expect(call).to.be.a('promise');
    });

    it('should pass an Object cotains GraphQL enum type for "UserType" in promise', () => {
      return call
        .then(response => {
          expect(response).to.be.a('object');
          expect(response).to.have.property('UserType');
          expect(response.UserType).to.have.all.keys('name', 'kinde', 'enumValues');
        })
        .catch(error => {
          expect(error).to.be.a('object');
        })
    })
  });

  const newUrl = 'http://127.0.0.1:3000/graphql';
  describe(`#setUrl("${newUrl}")`, () => {
    it(`should set url to "${newUrl}"`, () => {
      testQL.setUrl(newUrl);
      expect(testQL.getUrl()).to.equal(newUrl);
    });
  });
});
<commit_msg>update: shrink test query content<commit_after>/**
 * Created by gucheng on 5/18/16.
 */
var expect = require('chai').expect;
var fetch = require('node-fetch');
var FetchQL = require('./index.mjs');

const testQuery = `
  query Query {
    user(username: "BlinkTunnel") {
      name
      id
    }
  }
`;

const testUrl = 'http://127.0.0.1:3000/another';
const testQueryParams = {
  operationName: 'Query',
  query: testQuery,
  variables: {}
};

var testQL = new FetchQL({
  url: testUrl
});

describe('FetchQL', () => {
  describe('#constructor', () => {
    it('should return an Object', () => {
      expect(testQL).to.be.a('object');
    });
  });

  describe('#methods', () => {
    const methods = ['query', 'getUrl', 'setUrl', 'getEnumTypes'];
    methods.map((method) => {
      it(`${method}() should be a function`, () => {
        expect(testQL[method]).to.be.a('function');
      })
    })
  });

  describe('#getUrl()', () => {
    let currentUrl = testQL.getUrl();
    it(`should return url "${testUrl}"`, () => {
      expect(currentUrl).to.be.a('string');
      expect(currentUrl).to.eql(testUrl);
    });
  });

  describe('#query()', () => {
    let call = testQL.query(testQueryParams);
    it('should return a Promise', () => {
      expect(call).to.be.a('promise');
    });

    it('should pass an object of response data in promise', () => {
      return call
        .then(response => expect(response).to.be.a('object'))
        .catch(error => expect(error).to.be.a('object'))
    });
  });

  describe('#getEnumTypes(["UserType"])', () => {
    let call = testQL.getEnumTypes(['UserType']);
    it('should return a Promise', () => {
      expect(call).to.be.a('promise');
    });

    it('should pass an Object cotains GraphQL enum type for "UserType" in promise', () => {
      return call
        .then(response => {
          expect(response).to.be.a('object');
          expect(response).to.have.property('UserType');
          expect(response.UserType).to.have.all.keys('name', 'kinde', 'enumValues');
        })
        .catch(error => {
          expect(error).to.be.a('object');
        })
    })
  });

  const newUrl = 'http://127.0.0.1:3000/graphql';
  describe(`#setUrl("${newUrl}")`, () => {
    it(`should set url to "${newUrl}"`, () => {
      testQL.setUrl(newUrl);
      expect(testQL.getUrl()).to.equal(newUrl);
    });
  });
});
<|endoftext|>


<commit_before>define(['./node'], function(Node) {
	// Text node
	function Text(content) {
		Node.call(this, Node.TEXT_NODE);
		this.nodeValue = content;
	}
	Text.prototype = new Node(Node.TEXT_NODE);
	Text.prototype.constructor = Text;

	// Breaks the Text node into two nodes at the specified offset, keeping both nodes in the tree as siblings.
	Text.prototype.splitText = function(index) {
		// Split the text
		var newNode = this.ownerDocument.createTextNode(this.nodeValue.substring(index));
		this.nodeValue = this.nodeValue.substring(0, index);

		// If the current node is part of a tree, insert the new node
		if (this.parentNode) {
			this.parentNode.insertBefore(this.nextSibling, newNode);
		}

		return newNode;
	};

	Text.prototype.toString = function() {
		return this.nodeValue;
	};

	return Text;
});
<commit_msg>Fixed wrong argument order bug in splitText.<commit_after>define(['./node'], function(Node) {
	// Text node
	function Text(content) {
		Node.call(this, Node.TEXT_NODE);
		this.nodeValue = content;
	}
	Text.prototype = new Node(Node.TEXT_NODE);
	Text.prototype.constructor = Text;

	// Breaks the Text node into two nodes at the specified offset, keeping both nodes in the tree as siblings.
	Text.prototype.splitText = function(index) {
		// Split the text
		var newNode = this.ownerDocument.createTextNode(this.nodeValue.substring(index));
		this.nodeValue = this.nodeValue.substring(0, index);

		// If the current node is part of a tree, insert the new node
		if (this.parentNode) {
			this.parentNode.insertBefore(newNode, this.nextSibling);
		}

		return newNode;
	};

	Text.prototype.toString = function() {
		return this.nodeValue;
	};

	return Text;
});
<|endoftext|>


<commit_before>// var chai = require('chai')
//    expect = chai.expect;

var expect = require('chai').expect;

var taskList = [ ];

// I can list my tasks...
function listTasks(){
}

function addTaskToList(task, list){
  // What is the task? @param task
  // Where is the task going? @param list
  // What order / prioity? lowest, on the bottom
  return list.push(task)

}
expect(taskList.length).to.equal(0);
addTaskToList("Remember the milk", taskList);
expect(taskList[0]).to.equal("Remember the milk");
expect(taskList.length).to.equal(1);

expect(taskList[0]).to.equal("Remember the milk");
expect(taskList.length).to.equal(1);
addTaskToList("Take out the trash", taskList);
expect(taskList[1]).to.equal("Take out the trash");
expect(taskList.length).to.equal(2);

console.log(taskList)
<commit_msg>I can add new tasks!!<commit_after>// var chai = require('chai')
//    expect = chai.expect;

var expect = require('chai').expect;

var taskList = [ ];

// I can list my tasks...
function listTasks(){
}

function addTaskToList(task, list){
  // What is the task? @param task
  // Where is the task going? @param list
  // What order / prioity? lowest, on the bottom
  return list.push(task)

}
expect(taskList.length).to.equal(0);
addTaskToList("Remember the milk", taskList);
expect(taskList[0]).to.equal("Remember the milk");
expect(taskList.length).to.equal(1);

expect(taskList.length).to.equal(1);
addTaskToList("Take out the trash", taskList);
expect(taskList[1]).to.equal("Take out the trash");
expect(taskList.length).to.equal(2);

expect(taskList.length).to.equal(2);
addTaskToList("Clean up cat litter", taskList);
expect(taskList[2]).to.equal("Clean up cat litter");
expect(taskList.length).to.equal(3);

console.log(taskList)
<|endoftext|>


<commit_before>var expect = require('chai').expect;

var taskList = [ ];

function listTasks(){
}

// I can add a task to my list...
function addTaskToList(task, list){
  //What is the task? @parameter task
  //Where is the task going? @List Parameter
  //What order / priority? lowest on the bottom(push)
  return list.push(task);
}

expect(taskList.length).to.equal(0);

addTaskToList("Remember the milk", taskList);
expect(taskList[0]).to.equal("Remember the milk");
expect(taskList.length).to.equal(1);

//expect what?
addTaskToList("Take out the trash", taskList);
//expect what now?
expect(taskList[1]).to.equal("Take out the trash");
expect(taskList.length).to.equal(2);

addTaskToList("Mow the lawn", taskList);
expect(taskList[2]).to.equal("Mow the lawn")
expect(taskList.length).to.equal(3);

addTaskToList("Wash the car", taskList);
expect(taskList[3]).to.equal("Wash the car")
expect(taskList.length).to.equal(4)

addTaskToList("Walk the dogs", taskList);
expect(taskList[4]).to.equal("Walk the dogs")
expect(taskList.length).to.equal(5)

//How do I delete an item from my taskList???
taskList.splice(2,1);

taskList.sort([1,2,3,4,5,6]);

console.log(taskList[1], taskList[3], taskList[2], taskList[4]);
<commit_msg>Tried to remove task with adding another array(Failed test)<commit_after>var expect = require('chai').expect;

var taskList = [ ];

function listTasks(){
}

// I can add a task to my list...
function addTaskToList(task, list){
  //What is the task? @parameter task
  //Where is the task going? @List Parameter
  //What order / priority? lowest on the bottom(push)
  return list.push(task);
}

expect(taskList.length).to.equal(0);

addTaskToList("Remember the milk", taskList);
expect(taskList[0]).to.equal("Remember the milk");
expect(taskList.length).to.equal(1);

//expect what?
addTaskToList("Take out the trash", taskList);
//expect what now?
expect(taskList[1]).to.equal("Take out the trash");
expect(taskList.length).to.equal(2);

addTaskToList("Mow the lawn", taskList);
expect(taskList[2]).to.equal("Mow the lawn")
expect(taskList.length).to.equal(3);

addTaskToList("Wash the car", taskList);
expect(taskList[3]).to.equal("Wash the car")
expect(taskList.length).to.equal(4)

addTaskToList("Walk the dogs", taskList);
expect(taskList[4]).to.equal("Walk the dogs")
expect(taskList.length).to.equal(5)

//How do I delete an item from my taskList???
addTaskToList(2) = addTaskToList[addTaskToList.length - 1];

//Sorting my taskList
taskList.sort([1,2,3,4,5,6]);

console.log(addTaskToList);
<|endoftext|>


<commit_before>var expect = require('chai').expect;

var taskList = [ ];

function listTasks(){
}

// I can add a task to my list...
function addTaskToList(task, list){
  //What is the task? @parameter task
  //Where is the task going? @List Parameter
  //What order / priority? lowest on the bottom(push)
  return list.push(task);
}

expect(taskList.length).to.equal(0);

addTaskToList("Remember the milk", taskList);
expect(taskList[0]).to.equal("Remember the milk");
expect(taskList.length).to.equal(1);

//expect what?
addTaskToList("Take out the trash", taskList);
//expect what now?
expect(taskList[1]).to.equal("Take out the trash");
expect(taskList.length).to.equal(2);

addTaskToList("Mow the lawn", taskList);
expect(taskList[2]).to.equal("Mow the lawn")
expect(taskList.length).to.equal(3);

addTaskToList("Wash the car", taskList);
expect(taskList[3]).to.equal("Wash the car")
expect(taskList.length).to.equal(4)

addTaskToList("Walk the dogs", taskList);
expect(taskList[4]).to.equal("Walk the dogs")
expect(taskList.length).to.equal(5)

//How do I delete an item from my taskList???
taskList.splice(3,1);

console.log(taskList[1], taskList[3], taskList[2], taskList[4]);
<commit_msg>Trying to sort taskList(Failed Test)<commit_after>var expect = require('chai').expect;

var taskList = [ ];

function listTasks(){
}

// I can add a task to my list...
function addTaskToList(task, list){
  //What is the task? @parameter task
  //Where is the task going? @List Parameter
  //What order / priority? lowest on the bottom(push)
  return list.push(task);
}

expect(taskList.length).to.equal(0);

addTaskToList("Remember the milk", taskList);
expect(taskList[0]).to.equal("Remember the milk");
expect(taskList.length).to.equal(1);

//expect what?
addTaskToList("Take out the trash", taskList);
//expect what now?
expect(taskList[1]).to.equal("Take out the trash");
expect(taskList.length).to.equal(2);

addTaskToList("Mow the lawn", taskList);
expect(taskList[2]).to.equal("Mow the lawn")
expect(taskList.length).to.equal(3);

addTaskToList("Wash the car", taskList);
expect(taskList[3]).to.equal("Wash the car")
expect(taskList.length).to.equal(4)

addTaskToList("Walk the dogs", taskList);
expect(taskList[4]).to.equal("Walk the dogs")
expect(taskList.length).to.equal(5)

//How do I delete an item from my taskList???
taskList.splice(3,1);

taskList.sort(function(a,b));

console.log(taskList[1], taskList[3], taskList[2], taskList[4]);
<|endoftext|>


<commit_before>#!/usr/bin/env node

var yaml = require("yamljs");
var glob = require('glob');
var touch = require('touch');
var path = require('path');

var vccutil = require("./vccutil.js");

// define the required arguments
opt = require('node-getopt').create([
  ['', 'cluster=NAME', 'name of cluster to join'],
  ['', 'storage-type=TYPE', 'storage service type, supports: etcd'],
  ['', 'storage-host=IP', 'ip address of storage host'],
  ['', 'storage-port=PORT', 'port of storage service'],
  ['', 'service=SERVICE', 'for a multi service image, specify the service to start'],
  ['', 'force-address=IP', 'manually set the advertised IP of this instance'],
  ['', 'no-dns', 'don\'t use the ClusterDNS service'],
  ['', 'just-yml', 'just dump the generated cluster init.yml and nothing else'],
  ['i', 'info', 'display information about this vcc image'],
  ['h', 'help', 'display this help'],
  ['v', 'version', 'show version']
]); // parse command line

var options = opt.parseSystem().options;

// help command
if (options.help) {
    opt.showHelp();
    process.exit(1);
}

// version command
if (options.version) {
    console.log("vccjs tool 0.2");
    process.exit(1);
}
// info command
if (options.info) {
    // get some basic details about this image
    var clusteryml = yaml.load("/etc/cluster.yml");
    var info = {};
    if(!clusteryml.image_info) {
        console.error("This image does not define any author info in the init.yml");
    } else {
        info['Name'] = clusteryml.image_info.name;
        info['Version'] = clusteryml.image_info.version;
        info['Author'] = clusteryml.image_info.author;
    }
    // check for service providers and dependencies
    try {
        var deps = yaml.load("/etc/vcc/dependencies.yml");
    } catch (err) {
        var deps = {};
    }
    info.Services['Dependencies'] = deps;
    // print out in yaml
    console.log(yaml.stringify(info, 8));
    process.exit(1);
}

// otherwise, start the VCC!
// check cluster name is specified
if (!options.cluster) {
    console.error("You must specify a cluster name using --cluster=NAME");
    process.exit(1);
}
// check we have either --start-storage or --storage-host and --storage-port
if (!(options['storage-host'] && options['storage-port'])) {
    console.error("You must specify --storage-host and --storage-port");
    process.exit(1);
}
// generate yml config with cluster name and storage details in
// since the tool is executed within the image itself, we can just look at /etc/init.yml
var clusteryml = yaml.load("/etc/cluster.yml");
// storage settings
if(!options['storage-type']) {
    clusteryml.kvstore.type = "etcd";
} else {
    clusteryml.kvstore.type = options['storage-type'];
}
clusteryml.kvstore.host = options['storage-host'];
clusteryml.kvstore.port = options['storage-port'];
// address override
if(options['force-address']) {
    clusteryml.myaddress = options['force-address'];
}
// cluster dns
if(options['no-dns'] || options.usermode) {
    clusteryml.nodns = true;
}
// set cluster name and service
clusteryml.cluster = options.cluster;
if (options.service) {
    clusteryml.service = options.service;
}

// touch the service context file
touch.sync(path.join(vccutil.getRunDir(), "/vccservice-"+clusteryml.service));

// write the new cluster.yml file
vccutil.writeConfig(clusteryml).then(function () {
    console.log("written cluster.yml");
    process.exit(0);
},
function (err) {
    console.error("failed to write cluster.yml");
    console.error(err);
    process.exit(1);
});
<commit_msg>change force-address to more friendly cluster-address option<commit_after>#!/usr/bin/env node

var yaml = require("yamljs");
var glob = require('glob');
var touch = require('touch');
var path = require('path');

var vccutil = require("./vccutil.js");

// define the required arguments
opt = require('node-getopt').create([
  ['', 'cluster=NAME', 'name of cluster to join'],
  ['', 'storage-type=TYPE', 'storage service type, supports: etcd'],
  ['', 'storage-host=IP', 'ip address of storage host'],
  ['', 'storage-port=PORT', 'port of storage service'],
  ['', 'service=SERVICE', 'for a multi service image, specify the service to start'],
  ['', 'cluster-address=IP', 'set the advertised IP of this instance (when dual homed)'],
  ['', 'no-dns', 'don\'t use the ClusterDNS service'],
  ['', 'just-yml', 'just dump the generated cluster init.yml and nothing else'],
  ['i', 'info', 'display information about this vcc image'],
  ['h', 'help', 'display this help'],
  ['v', 'version', 'show version']
]); // parse command line

var options = opt.parseSystem().options;

// help command
if (options.help) {
    opt.showHelp();
    process.exit(1);
}

// version command
if (options.version) {
    console.log("vccjs tool 0.2");
    process.exit(1);
}
// info command
if (options.info) {
    // get some basic details about this image
    var clusteryml = yaml.load("/etc/cluster.yml");
    var info = {};
    if(!clusteryml.image_info) {
        console.error("This image does not define any author info in the init.yml");
    } else {
        info['Name'] = clusteryml.image_info.name;
        info['Version'] = clusteryml.image_info.version;
        info['Author'] = clusteryml.image_info.author;
    }
    // check for service providers and dependencies
    try {
        var deps = yaml.load("/etc/vcc/dependencies.yml");
    } catch (err) {
        var deps = {};
    }
    info.Services['Dependencies'] = deps;
    // print out in yaml
    console.log(yaml.stringify(info, 8));
    process.exit(1);
}

// otherwise, start the VCC!
// check cluster name is specified
if (!options.cluster) {
    console.error("You must specify a cluster name using --cluster=NAME");
    process.exit(1);
}
// check we have either --start-storage or --storage-host and --storage-port
if (!(options['storage-host'] && options['storage-port'])) {
    console.error("You must specify --storage-host and --storage-port");
    process.exit(1);
}
// generate yml config with cluster name and storage details in
// since the tool is executed within the image itself, we can just look at /etc/init.yml
var clusteryml = yaml.load("/etc/cluster.yml");
// storage settings
if(!options['storage-type']) {
    clusteryml.kvstore.type = "etcd";
} else {
    clusteryml.kvstore.type = options['storage-type'];
}
clusteryml.kvstore.host = options['storage-host'];
clusteryml.kvstore.port = options['storage-port'];
// address override
if(options['cluster-address']) {
    clusteryml.myaddress = options['cluster-address'];
}
// cluster dns
if(options['no-dns'] || options.usermode) {
    clusteryml.nodns = true;
}
// set cluster name and service
clusteryml.cluster = options.cluster;
if (options.service) {
    clusteryml.service = options.service;
}

// touch the service context file
touch.sync(path.join(vccutil.getRunDir(), "/vccservice-"+clusteryml.service));

// write the new cluster.yml file
vccutil.writeConfig(clusteryml).then(function () {
    console.log("written cluster.yml");
    process.exit(0);
},
function (err) {
    console.error("failed to write cluster.yml");
    console.error(err);
    process.exit(1);
});
<|endoftext|>


<commit_before>var Trie = function(name, isWord) {
  this.name = name || '';
  this.isWord = false;
	this.children = [];
};

var isEmpty = function(ob) {
  for(var i in ob){ return false; }
  return true;
};

Trie.prototype.set = function(word) {
  if ( typeof(word) !== 'string' ) {
    console.log('Word', word, 'could not be added it was not a string');
    return;
  }
  if (word === '') {
    if (this.name !== '')
      this.isWord = true;
    return;
  }
  var child = this.children[word[0]] = this.children[word[0]] || new Trie(word[0]);
  child.set(word.substr(1));
};

Trie.prototype.del = function(word) {
  if ( typeof(word) !== 'string' ) {
    console.log('Word', word, 'could not be added it was not a string');
    return;
  }
  if (word === '') {
    if (this.name === '') return;
    this.isWord = false;
  } else {
    if (this.children[word[0]].del(word.substr(1)))
      delete this.children[word[0]];
  }
  return !this.isWord && isEmpty(this.children);
};

Trie.prototype.sets = function(words) {
  if ( !Array.isArray(words) ) {
    console.log('Words', words, 'were not in an array');
    return;
  }
  for (var i = 0; i < words.length; i++)
    this.set(words[i]);
};

Trie.prototype.__bottomNodeOfWord = function(word) {
  var child = this;
  for (var i = 0; i < word.length; i++) {
    if (typeof(child.children[word[i]]) === 'undefined') throw new Error('Word doesn\'t exist');
    child = child.children[word[i]];
  }
  return child;
};

Trie.prototype.exists = function(word) {
  try { return this.__bottomNodeOfWord(word).isWord; }
  catch (e) { return false; }
};

Trie.prototype.__DFS = function(word) {
  var word = word || '';
  var words = [];

  word += this.name;
  if (this.isWord) words.push(word);
  for ( var i in this.children )
     words = words.concat(this.children[i].__DFS(word));
  return words;
};

Trie.prototype.match = function(word) {
  //DFS to return all possible words that match a prefix
  var child;
  try { child = this.__bottomNodeOfWord(word); }
  catch (e) { console.log(e); return; }

	return child.__DFS(word.substr(0,word.length-1));
};

exports.Trie = Trie;<commit_msg>Only set() or del() should modify isWord, not the constructor.<commit_after>var Trie = function(name) {
  this.name = name || '';
  this.isWord = false;
	this.children = {};
};

var isEmpty = function(ob) {
  for(var i in ob){ return false; }
  return true;
};

Trie.prototype.set = function(word) {
  if ( typeof(word) !== 'string' ) {
    console.log('Word', word, 'could not be added it was not a string');
    return;
  }
  if (word === '') {
    if (this.name !== '')
      this.isWord = true;
    return;
  }
  var child = this.children[word[0]] = this.children[word[0]] || new Trie(word[0]);
  child.set(word.substr(1));
};

Trie.prototype.del = function(word) {
  if ( typeof(word) !== 'string' ) {
    console.log('Word', word, 'could not be added it was not a string');
    return;
  }
  if (word === '') {
    if (this.name === '') return;
    this.isWord = false;
  } else {
    if (this.children[word[0]].del(word.substr(1)))
      delete this.children[word[0]];
  }
  return !this.isWord && isEmpty(this.children);
};

Trie.prototype.sets = function(words) {
  if ( !Array.isArray(words) ) {
    console.log('Words', words, 'were not in an array');
    return;
  }
  for (var i = 0; i < words.length; i++)
    this.set(words[i]);
};

Trie.prototype.__bottomNodeOfWord = function(word) {
  var child = this;
  for (var i = 0; i < word.length; i++) {
    if (typeof(child.children[word[i]]) === 'undefined') throw new Error('Word doesn\'t exist');
    child = child.children[word[i]];
  }
  return child;
};

Trie.prototype.exists = function(word) {
  try { return this.__bottomNodeOfWord(word).isWord; }
  catch (e) { return false; }
};

Trie.prototype.__DFS = function(word) {
  var word = word || '';
  var words = [];

  word += this.name;
  if (this.isWord) words.push(word);
  for ( var i in this.children )
     words = words.concat(this.children[i].__DFS(word));
  return words;
};

Trie.prototype.match = function(word) {
  //DFS to return all possible words that match a prefix
  var child;
  try { child = this.__bottomNodeOfWord(word); }
  catch (e) { console.log(e); return; }

	return child.__DFS(word.substr(0,word.length-1));
};

exports.Trie = Trie;<|endoftext|>


<commit_before>/**
 * The Sexy Page Turn JQuery Plugin
 * By Elliott Kember - http://twitter.com/elliottkember
 * Released under the MIT license (MIT-LICENSE.txt)
 */

(function($){
 $.fn.fold = function(options) {

		// Default awesomeness
	  var defaults = {
			directory: 'turn',			// The directory we're in
		  side: 'left',           // change me to "right" if you want rightness
			turnImage: 'fold3.png', // The triangle-shaped fold image
	    maxHeight: 400,					// The maximum height. Duh.
			starting_width: 80,			// The height and width
			starting_height: 80			// with which	to start
	  };

		// Change turnImage if we're running the default image, and they've specified 'right'
		if (options.side == 'right' && !options.turnImage) {
			defaults.turnImage = 'fold-sw.png';
		}

		// Merge options with the defaults
	  var options = $.extend(defaults, options);

		// It's nicer-looking this way. Sorry if it breaks your stuff.
		var el = function(type){
			return $(document.createElement(type))
		}

		// Set up the wrapper objects
		h		 = el('div').attr({id: 'turn_hideme'});
		c  	 = el('div').attr({id: 'turn_wrapper'});
		turn = el('div').attr({id: 'turn_object'});
		img  = el('img').attr({id: 'turn_fold', src: (options.directory+'/'+options.turnImage)});

		// Set starting width and height
		turn.css({
			width: options.starting_width,
			height: options.starting_height
		});

		// There are different CSS considerations for a top-right fold.
		if (options.side == 'right'){
			c.addClass('right');
		}

		// Rappin', I'm rappin' - I'm rap-rap-rappin'.
		this.wrap(c).wrap(turn).after(img).wrap(h);

		// Hit 'em with the drag-stick.
		$('#turn_object').resizable({
	       maxHeight: options.maxHeight,
	       aspectRatio: true,
	       ratio: true,
	       border: false,
	       dragHandle: false,
	       knobHandles: true,
	       handles:  options.side == 'left' ? 'se' : 'sw'
		});
	};
})(jQuery);<commit_msg>Message and filename fix<commit_after>/**
 * The Sexy Curls JQuery Plugin
 * By Elliott Kember - http://twitter.com/elliottkember
 * Released under the MIT license (MIT-LICENSE.txt)
 *
 * My only request is: please don't over-use this plugin.
 * If this ends up being used all over the internets, and becomes "that annoying effect", I'll be upset.
 *
 * I dragged a curl, and I liked it - I hope @jresig don't mind it.
 */

(function($){
 $.fn.fold = function(options) {

		// Default awesomeness
	  var defaults = {
			directory: 'turn',			// The directory we're in
		  side: 'left',           // change me to "right" if you want rightness
			turnImage: 'fold.png', // The triangle-shaped fold image
	    maxHeight: 400,					// The maximum height. Duh.
			starting_width: 80,			// The height and width
			starting_height: 80			// with which	to start
	  };

		// Change turnImage if we're running the default image, and they've specified 'right'
		if (options.side == 'right' && !options.turnImage) {
			defaults.turnImage = 'fold-sw.png';
		}

		// Merge options with the defaults
	  var options = $.extend(defaults, options);

		// It's nicer-looking this way. Sorry if it breaks your stuff.
		var el = function(type){
			return $(document.createElement(type))
		}

		// Set up the wrapper objects
		h		 = el('div').attr({id: 'turn_hideme'});
		c  	 = el('div').attr({id: 'turn_wrapper'});
		turn = el('div').attr({id: 'turn_object'});
		img  = el('img').attr({id: 'turn_fold', src: (options.directory+'/'+options.turnImage)});

		// Set starting width and height
		turn.css({
			width: options.starting_width,
			height: options.starting_height
		});

		// There are different CSS considerations for a top-right fold.
		if (options.side == 'right'){
			c.addClass('right');
		}

		// Rappin', I'm rappin' - I'm rap-rap-rappin'.
		this.wrap(c).wrap(turn).after(img).wrap(h);

		// Hit 'em with the drag-stick.
		$('#turn_object').resizable({
	       maxHeight: options.maxHeight,
	       aspectRatio: true,
	       ratio: true,
	       border: false,
	       dragHandle: false,
	       knobHandles: true,
	       handles:  options.side == 'left' ? 'se' : 'sw'
		});
	};
})(jQuery);<|endoftext|>


<commit_before>"use strict";

//Options still needs to be implemented.
function UFOs(container, options){

	//scene elements, I wouldn't mess with these if you are trying to work with this
	var scene, camera, renderer, map;

	//Mess with these if you don't want a full screen visualization
	var WIDTH  = window.innerWidth;
	var HEIGHT = window.innerHeight;

	//These are the map dimensions
	var MAXWIDTH = 928, MAXHEIGHT = 592;
	var cancelled = false;

	//Variables required to create UFOs
	var counter = 0;
	var ufo_geo1 = new THREE.TorusGeometry(17,3,40,50);
	var ufo_geo2 = new THREE.SphereGeometry(14,32,32);
	var ufo_material = new THREE.MeshPhongMaterial({color: 0xcccccc,reflectivity:.4});
	var ufo_material2 = new THREE.MeshPhongMaterial({color: 0xcccccc,reflectivity:.4});

	var ival;//interval val for touch listeners

	//These handle the stars
	var diskGeo = new THREE.CircleGeometry(7,40,40,40);
	var diskMaterial = new THREE.MeshBasicMaterial({color: 0xff0000, transparent:true,opacity:1});

	//cant just use this.speed because of the calls to bind later on.
	var speed = 50;
	this.setSpeed = function(spd){speed = spd;};

	//SECTION INITIALIZATION
	function init(container) {
		scene = new THREE.Scene();
		initCamera();
		if(!window.renderer)
			initRenderer();
		renderer = window.renderer;
		initMap();
		renderer.domElement.className = "grabbable";
		container.body.appendChild(renderer.domElement);
		renderer.domElement.style.cursor="grab";
		setTimeout(function(){addMouseHandler.call(renderer.domElement);},1000);
		render();
	}

	//fires whenever the window resizes to keep the map accurate
	function resize(){
		WIDTH  = window.innerWidth;
		HEIGHT = window.innerHeight
		camera.aspect = WIDTH/HEIGHT;
		camera.updateProjectionMatrix();
		renderer.setSize(WIDTH, HEIGHT);
	}

	function initCamera() {
		camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 4000);
		camera.position.set(0,-200,600);
		camera.lookAt(scene.position);
	}

	//Prevents excessive WebGLRenderer instances
	function initRenderer() {

		renderer = new THREE.WebGLRenderer({ antialias: true });
		renderer.setClearColor(0x000000);
		renderer.setPixelRatio( window.devicePixelRatio );

		renderer.setSize(WIDTH, HEIGHT);
		window.renderer = renderer;
	}

	function initMap() {
		var loader = new THREE.TextureLoader();

		var texture = loader.load("img/usa.jpg");
		var material = new THREE.MeshPhongMaterial({map:texture});
		material.bumpMap =texture;
		material.bumpScale = 22;

		map = new THREE.Mesh(new THREE.CubeGeometry(MAXWIDTH,MAXHEIGHT, 2), material);
		var light = new THREE.DirectionalLight( 0xffffff );
		light.position.set( 1000, 1000, 1000);
		light.castShadow = true;
		map.receiveShadow = true;
		scene.add(light);
		scene.add(map);
	}
	// END INITIALIZATION

	function addUFO(x,y){
		if(cancelled){
			return;
		}
		counter++;
      		var ufo = new THREE.Mesh(ufo_geo1,ufo_material);
		var sub_ufo = new THREE.Mesh(ufo_geo2,ufo_material2);
		ufo.add(sub_ufo);
      		ufo.castShadow = true;
      		ufo.receiveShadow = true;
		ufo.name = counter.toString();
		ufo.isUFO = true;
		map.add(ufo);
		ufo.position.set(-928/2 +x,592/2 -y,400);
		loopWrapper(animateUFO.bind(ufo));
	}

	//Adds a ufo at a certain percentage of the way across the screen
	function addUFOPercent(x,y){
		addUFO(x*MAXWIDTH, y*MAXHEIGHT);
	}

	//loops for animation until the function returns false.
	function loopWrapper(callback){
			if(cancelled){
					return;
			}
			if(callback()){
					setTimeout(function(){loopWrapper(callback);},Math.floor(20*((150-(speed))/150)));
			}
	}

	//transitions a ufo in.
	function animateUFO(){
		this.position.z-=3;

		if(this.position.z<=130){
				var disk = new THREE.Mesh(diskGeo,diskMaterial.clone());
				disk.position.copy(this.position);

				map.add(disk);
				var tempJson = {
						disk:disk,
						ufo:this,
						counter:1000
				};

				loopWrapper(castBeam.bind(tempJson));
				return false;
		}
		return true;
	}

	//casts stars onto the map.
	function castBeam(){
				this.counter++;
				if(this.counter > 5){
						var disk = new THREE.Mesh(diskGeo,diskMaterial);
						disk.position.copy(this.ufo.position);
						map.add(disk);
						loopWrapper(castDown.bind(disk));
						this.counter = 0;
				}

				this.disk.position.z-=2;
				if(this.disk.position.z <= 3){
						var fun = remove.bind(this.ufo);
						setTimeout(function(){loopWrapper(fun);},Math.floor(200*(150-speed)/150));
						loopWrapper(fadeOut.bind(this.disk));
						return false;
				}
				return true;
	}
	function castDown(){
			this.position.z-=2;
			if(this.position.z <=3){
				map.remove(this);
				return false;
			}
			return true;
	}

	function fadeOut(){

		if(this.material.opacity <= .01){
			map.remove(this);
			return false;
		}
		else{
			this.material.opacity-=.001;
		}
			return true;
	}

	//fly away and remove.
	function remove(){
				this.position.z+=5;
				if(this.position.z >=700){
					map.remove(this);
					return false;
				}
				return true;
	}

	//This removes all children.
	function resetStars(){
		//this clears nested children too, kind of a funky behavior but just had to deal with it.
		//Threejs struggles with removing objects.  Sometimes you have to try a few times to get it to work.
		//This probably has to do with the fact that these objects still exist in the event loop due to my animation implementation.
		cancelled = true;
		for(var i = map.children.length; i >= 0; i--){
			map.remove(map.children[i])
		}
		setTimeout(function(){cancelled = false;},Math.floor(40*((150-(speed))/150)));

	}

	function render(){
                renderer.render(scene, camera);
                requestAnimationFrame(render);
	}

	//Mouse handlers
	//This section handles mouse events for rotation.  I kept the variables down here so that they are easier to keep track of.
	//This is all a closure, so these functions aren't available outside which is good.
	function addMouseHandler() {

			var mouseDown = false,mouseX,mouseY;
			function onMouseMove(e) {
			  e.preventDefault();

			  var deltaX = e.clientX - mouseX, deltaY = e.clientY - mouseY;
			  mouseX = e.clientX;
			  mouseY = e.clientY;

			  if (mouseDown) {
					rotateScene(deltaX);
					moveScene(deltaY);
			  }
			}

			function onMouseUp(evt) {
				evt.preventDefault();
				mouseDown = false;
			}

			function onMouseDown(evt){
				evt.preventDefault();
				mouseDown = true;
			}

			var touchX, touchY, touched = false,touched_first = false;

		this.addEventListener("touchstart", function(e){
			if(!touched_first){
				setInterval(touchHandler,20);
				touched_first = true;
			}
			touched = true;
			touchX= e.touches[0].clientX;
			touchY = e.touches[0].clientY;
			e.preventDefault();
		}, true);

		this.addEventListener("touchmove",function(e){
			touchX= e.touches[0].clientX;
			touchY = e.touches[0].clientY;
			e.preventDefault();
		});

		this.addEventListener("touchend", function(e){
			touched = false;
			e.preventDefault();
		}, true);

		function touchHandler(){
			if(touched){
				rotateScene(5 * (touchX - (WIDTH/2))/(WIDTH/2));
				moveScene(-5 * (touchY - HEIGHT/2)/(HEIGHT/2));
			}
		}

		//TODO implement zoom
		function wheelHandler(e){

		}

		this.addEventListener("wheel",wheelHandler,false);

		this.addEventListener('mousemove',onMouseMove,false);

		this.addEventListener('mousedown', onMouseDown,false);

		this.addEventListener('mouseup', onMouseUp,false);

	}

	//This is outside of addMouseHandler because I want these to be publicly available for people to add custom controls if they so desire.
	function rotateScene(deltaX){
			map.rotation.z-= deltaX/100;
	}
	function moveScene(deltaY) {
		if((camera.position.z > 300 || deltaY > 0) && (camera.position.z < 700 || deltaY < 0)){
			camera.position.z += deltaY;
			camera.position.y += deltaY*1.5;
			camera.rotation.x-=deltaY/360;
		}
	}

		//Call init and define public functions.
		init(container);
		moveScene(-50);
		this.addUFO = addUFO;
		this.resize = resize;
		this.addUFOPercent = addUFOPercent;
		this.resetStars = resetStars;
		this.rotateScene = rotateScene;
		this.moveScene = moveScene;
		this.destroy = function(){renderer.domElement.parentNode.removeChild(renderer.domElement);}
}
<commit_msg>Removed unneccesary comments<commit_after>"use strict";

//Options still needs to be implemented.
function UFOs(container, options){

	//scene elements, I wouldn't mess with these if you are trying to work with this
	var scene, camera, renderer, map;

	//Mess with these if you don't want a full screen visualization
	var WIDTH  = window.innerWidth;
	var HEIGHT = window.innerHeight;

	//These are the map dimensions
	var MAXWIDTH = 928, MAXHEIGHT = 592;
	var cancelled = false;

	//Variables required to create UFOs
	var counter = 0;
	var ufo_geo1 = new THREE.TorusGeometry(17,3,40,50);
	var ufo_geo2 = new THREE.SphereGeometry(14,32,32);
	var ufo_material = new THREE.MeshPhongMaterial({color: 0xcccccc,reflectivity:.4});
	var ufo_material2 = new THREE.MeshPhongMaterial({color: 0xcccccc,reflectivity:.4});

	var ival;//interval val for touch listeners

	//These handle the stars
	var diskGeo = new THREE.CircleGeometry(7,40,40,40);
	var diskMaterial = new THREE.MeshBasicMaterial({color: 0xff0000, transparent:true,opacity:1});

	//cant just use this.speed because of the calls to bind later on.
	var speed = 50;
	this.setSpeed = function(spd){speed = spd;};

	//SECTION INITIALIZATION
	function init(container) {
		scene = new THREE.Scene();
		initCamera();
		if(!window.renderer)
			initRenderer();
		renderer = window.renderer;
		initMap();
		renderer.domElement.className = "grabbable";
		container.body.appendChild(renderer.domElement);
		renderer.domElement.style.cursor="grab";
		setTimeout(function(){addMouseHandler.call(renderer.domElement);},1000);
		render();
	}

	//fires whenever the window resizes to keep the map accurate
	function resize(){
		WIDTH  = window.innerWidth;
		HEIGHT = window.innerHeight
		camera.aspect = WIDTH/HEIGHT;
		camera.updateProjectionMatrix();
		renderer.setSize(WIDTH, HEIGHT);
	}

	function initCamera() {
		camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 4000);
		camera.position.set(0,-200,600);
		camera.lookAt(scene.position);
	}

	//Prevents excessive WebGLRenderer instances
	function initRenderer() {

		renderer = new THREE.WebGLRenderer({ antialias: true });
		renderer.setClearColor(0x000000);
		renderer.setPixelRatio( window.devicePixelRatio );

		renderer.setSize(WIDTH, HEIGHT);
		window.renderer = renderer;
	}

	function initMap() {
		var loader = new THREE.TextureLoader();

		var texture = loader.load("img/usa.jpg");
		var material = new THREE.MeshPhongMaterial({map:texture});
		material.bumpMap =texture;
		material.bumpScale = 22;

		map = new THREE.Mesh(new THREE.CubeGeometry(MAXWIDTH,MAXHEIGHT, 2), material);
		var light = new THREE.DirectionalLight( 0xffffff );
		light.position.set( 1000, 1000, 1000);
		light.castShadow = true;
		map.receiveShadow = true;
		scene.add(light);
		scene.add(map);
	}
	// END INITIALIZATION

	function addUFO(x,y){
		if(cancelled){
			return;
		}
		counter++;
      		var ufo = new THREE.Mesh(ufo_geo1,ufo_material);
		var sub_ufo = new THREE.Mesh(ufo_geo2,ufo_material2);
		ufo.add(sub_ufo);
      		ufo.castShadow = true;
      		ufo.receiveShadow = true;
		ufo.name = counter.toString();
		ufo.isUFO = true;
		map.add(ufo);
		ufo.position.set(-928/2 +x,592/2 -y,400);
		loopWrapper(animateUFO.bind(ufo));
	}

	//Adds a ufo at a certain percentage of the way across the screen
	function addUFOPercent(x,y){
		addUFO(x*MAXWIDTH, y*MAXHEIGHT);
	}

	//loops for animation until the function returns false.
	function loopWrapper(callback){
			if(cancelled){
					return;
			}
			if(callback()){
					setTimeout(function(){loopWrapper(callback);},Math.floor(20*((150-(speed))/150)));
			}
	}

	//transitions a ufo in.
	function animateUFO(){
		this.position.z-=3;

		if(this.position.z<=130){
				var disk = new THREE.Mesh(diskGeo,diskMaterial.clone());
				disk.position.copy(this.position);

				map.add(disk);
				var tempJson = {
						disk:disk,
						ufo:this,
						counter:1000
				};

				loopWrapper(castBeam.bind(tempJson));
				return false;
		}
		return true;
	}

	//casts stars onto the map.
	function castBeam(){
				this.counter++;
				if(this.counter > 5){
						var disk = new THREE.Mesh(diskGeo,diskMaterial);
						disk.position.copy(this.ufo.position);
						map.add(disk);
						loopWrapper(castDown.bind(disk));
						this.counter = 0;
				}

				this.disk.position.z-=2;
				if(this.disk.position.z <= 3){
						var fun = remove.bind(this.ufo);
						setTimeout(function(){loopWrapper(fun);},Math.floor(200*(150-speed)/150));
						loopWrapper(fadeOut.bind(this.disk));
						return false;
				}
				return true;
	}
	function castDown(){
			this.position.z-=2;
			if(this.position.z <=3){
				map.remove(this);
				return false;
			}
			return true;
	}

	function fadeOut(){

		if(this.material.opacity <= .01){
			map.remove(this);
			return false;
		}
		else{
			this.material.opacity-=.001;
		}
			return true;
	}

	//fly away and remove.
	function remove(){
				this.position.z+=5;
				if(this.position.z >=700){
					map.remove(this);
					return false;
				}
				return true;
	}

	//This removes all children.
	function resetStars(){
		cancelled = true;
		for(var i = map.children.length; i >= 0; i--){
			map.remove(map.children[i])
		}
		setTimeout(function(){cancelled = false;},Math.floor(40*((150-(speed))/150)));

	}

	function render(){
                renderer.render(scene, camera);
                requestAnimationFrame(render);
	}

	//Mouse handlers
	//This section handles mouse events for rotation.  I kept the variables down here so that they are easier to keep track of.
	//This is all a closure, so these functions aren't available outside which is good.
	function addMouseHandler() {

			var mouseDown = false,mouseX,mouseY;
			function onMouseMove(e) {
			  e.preventDefault();

			  var deltaX = e.clientX - mouseX, deltaY = e.clientY - mouseY;
			  mouseX = e.clientX;
			  mouseY = e.clientY;

			  if (mouseDown) {
					rotateScene(deltaX);
					moveScene(deltaY);
			  }
			}

			function onMouseUp(evt) {
				evt.preventDefault();
				mouseDown = false;
			}

			function onMouseDown(evt){
				evt.preventDefault();
				mouseDown = true;
			}

			var touchX, touchY, touched = false,touched_first = false;

		this.addEventListener("touchstart", function(e){
			if(!touched_first){
				setInterval(touchHandler,20);
				touched_first = true;
			}
			touched = true;
			touchX= e.touches[0].clientX;
			touchY = e.touches[0].clientY;
			e.preventDefault();
		}, true);

		this.addEventListener("touchmove",function(e){
			touchX= e.touches[0].clientX;
			touchY = e.touches[0].clientY;
			e.preventDefault();
		});

		this.addEventListener("touchend", function(e){
			touched = false;
			e.preventDefault();
		}, true);

		function touchHandler(){
			if(touched){
				rotateScene(5 * (touchX - (WIDTH/2))/(WIDTH/2));
				moveScene(-5 * (touchY - HEIGHT/2)/(HEIGHT/2));
			}
		}

		//TODO implement zoom
		function wheelHandler(e){

		}

		this.addEventListener("wheel",wheelHandler,false);

		this.addEventListener('mousemove',onMouseMove,false);

		this.addEventListener('mousedown', onMouseDown,false);

		this.addEventListener('mouseup', onMouseUp,false);

	}

	//This is outside of addMouseHandler because I want these to be publicly available for people to add custom controls if they so desire.
	function rotateScene(deltaX){
			map.rotation.z-= deltaX/100;
	}
	function moveScene(deltaY) {
		if((camera.position.z > 300 || deltaY > 0) && (camera.position.z < 700 || deltaY < 0)){
			camera.position.z += deltaY;
			camera.position.y += deltaY*1.5;
			camera.rotation.x-=deltaY/360;
		}
	}

		//Call init and define public functions.
		init(container);
		moveScene(-50);
		this.addUFO = addUFO;
		this.resize = resize;
		this.addUFOPercent = addUFOPercent;
		this.resetStars = resetStars;
		this.rotateScene = rotateScene;
		this.moveScene = moveScene;
		this.destroy = function(){renderer.domElement.parentNode.removeChild(renderer.domElement);}
}
<|endoftext|>


<commit_before>var request    = require('request');
var cheerio    = require('cheerio');
var fs         = require('fs');
var mkdirp     = require('mkdirp');
var getDirName = require('path').dirname;
var Sensor     = require('./sensor.js');

module.exports = {

  getData: function(url, fireSensorName, meatSensorName, callback) {
    request(url, (err, status, html) => {
      var json = {};
      if (!err) {
        var $ = cheerio.load(html);
        json.fireSensor = parse($, fireSensorName);
        json.meatSensor = parse($, meatSensorName);
      }
      callback(err, json);
    });
  },

  updateLog: function(path, time, fireTemp, meatTemp) {
    var line = time + ',' + fireTemp + ',' + meatTemp + '\n';

    fs.access(path, fs.R_OK | fs.W_OK, (err) => {
      if (err) {
        console.log('File not found. Creating new file: ' + path);
        line = 'time,fireTemp,meatTemp\n' + line;
      }

      mkdirp(getDirName(path), (err) => {
        if (err) return console.log(err);
        console.log(line);
        fs.appendFile(path, line);
      });
    });
  },

  // returns "month/date/year hours:minutes:seconds"
  // ex: "06/07/2014 06:30:00"
  getFormattedTime: function(d) {
    var month = d.getMonth() + 1;
    var date  = d.getDate();
    var year  = d.getFullYear();
    var hours = d.getHours();
    var mins  = d.getMinutes();
    var secs  = d.getSeconds();

    if (month < 10) month = '0' + month;
    if (date  < 10) date  = '0' + date;
    if (hours < 10) hours = '0' + hours;
    if (mins  < 10) mins  = '0' + mins;
    if (secs  < 10) secs  = '0' + secs;

    return month + '/' + date + '/' + year + ' ' + hours + ':' + mins + ':' + secs;
  }

}

function parse($, sensorName) {
  var sensor = {};
  $('input[value=' + sensorName + ']').filter(function() {
    var serialNumber = $(this).attr("name").substring(Sensor.prefixSerial.length);
    sensor = new Sensor({
      name: sensorName,
      serial: serialNumber,
      temps: {
        current : $(this).parent().next('td').text(),
        target  : $('input[name=' + Sensor.prefixTarget + serialNumber + ']').val(),
        low     : $('input[name=' + Sensor.prefixLow    + serialNumber + ']').val(),
        high    : $('input[name=' + Sensor.prefixHigh   + serialNumber + ']').val()
      }
    });
  });
  return sensor;
}<commit_msg>pass html rather than cheerio<commit_after>var request    = require('request');
var cheerio    = require('cheerio');
var fs         = require('fs');
var mkdirp     = require('mkdirp');
var getDirName = require('path').dirname;
var Sensor     = require('./sensor.js');

module.exports = {

  getData: function(url, fireSensorName, meatSensorName, callback) {
    request(url, (err, statusCode, html) => {
      var json = {};
      if (!err) {
        json.fireSensor = parse(html, fireSensorName);
        json.meatSensor = parse(html, meatSensorName);
      }
      callback(err, json);
    });
  },

  updateLog: function(path, time, fireTemp, meatTemp) {
    var line = time + ',' + fireTemp + ',' + meatTemp + '\n';

    fs.access(path, fs.R_OK | fs.W_OK, (err) => {
      if (err) {
        console.log('File not found. Creating new file: ' + path);
        line = 'time,fireTemp,meatTemp\n' + line;
      }

      mkdirp(getDirName(path), (err) => {
        if (err) return console.log(err);
        console.log(line);
        fs.appendFile(path, line);
      });
    });
  },

  // returns "month/date/year hours:minutes:seconds"
  // ex: "06/07/2014 06:30:00"
  getFormattedTime: function(d) {
    var month = d.getMonth() + 1;
    var date  = d.getDate();
    var year  = d.getFullYear();
    var hours = d.getHours();
    var mins  = d.getMinutes();
    var secs  = d.getSeconds();

    if (month < 10) month = '0' + month;
    if (date  < 10) date  = '0' + date;
    if (hours < 10) hours = '0' + hours;
    if (mins  < 10) mins  = '0' + mins;
    if (secs  < 10) secs  = '0' + secs;

    return month + '/' + date + '/' + year + ' ' + hours + ':' + mins + ':' + secs;
  }

}

function parse(html, sensorName) {
  var sensor = {};
  var $ = cheerio.load(html);
  $('input[value=' + sensorName + ']').filter(function() {
    var serialNumber = $(this).attr("name").substring(Sensor.prefixSerial.length);
    sensor = new Sensor({
      name: sensorName,
      serial: serialNumber,
      temps: {
        current : $(this).parent().next('td').text(),
        target  : $('input[name=' + Sensor.prefixTarget + serialNumber + ']').val(),
        low     : $('input[name=' + Sensor.prefixLow    + serialNumber + ']').val(),
        high    : $('input[name=' + Sensor.prefixHigh   + serialNumber + ']').val()
      }
    });
  });
  return sensor;
}
<|endoftext|>


<commit_before>/******************************************************************************
* view.js                                                                     *
* Copyright 2012                                                              *
* For details about the copyright holders, see the COPYRIGHT file.            *
* This software is freely distributed under the ISC License.                  *
* For details about the license, see the LICENSE file.                        *
******************************************************************************/
(function() {
	var comments_div,
	highlight_start = -1,
	highlight_end = -1,
	selection_start = -1,
	selection_end = -1,
	comment_ob = null,
	comment_box_ob = null,
	num_lines = -1,
	comments = {},
	language_data = null,
	codeMirror = null,
	diffMirror = null,
	noSelect = false,
	codeOptions = null,
	diffOptions = null,
	commentOptions = null,
	commentMirrors = [];

/******************************************************************************
* Utility Functions                                                           *
******************************************************************************/

	function modulo(n,m) {
		while(n < 0)
			n += m;
		return n%m;
	}

	function logError(text) {
		console.log('ERROR: ' + text);
	}

	function reportError(text) {
		logError(text);
		$('#error').text(text).show();
	}

	function handleAjaxError(jqXHR, textStatus, errorThrown) {
		reportError(errorThrown);
	}

	function include(filename) {
		if(filename.indexOf('.js') != -1) {
			$('


<commit_before>// Whole-script strict mode syntax
"use strict";

var request = require('request');
var GitHub = require("github");
var util = require('util');
var dashboard = require('./dashboard.js');

var allEvents = {};
var allBugs = {};

// add lpad to string
String.prototype.lpad = function(padString, length) {
  var str = this;
  while (str.length < length)
    str = padString + str;
  return str;
}

var github = new GitHub({
    // required
    version: "3.0.0",
    // optional
    debug: false,
    protocol: "https",
    host: "api.github.com",
    timeout: 30000
  });

github.authenticate({
  type: "oauth",
  token: process.env.SEKRIT
});

// go find all the bugs we are tracking for WADI

// TODO get all history https://bugzilla.mozilla.org/rest/bug/707428/history
// TODO get attachments look for review status https://bugzilla.mozilla.org/rest/bug/707428/attachment

function addBugsTrackedBy(inBugID) {
  request("http://bugzilla.mozilla.org/rest/bug/" + inBugID + "?include_fields=id,depends_on", function(error, response, body) {
    var tracker = JSON.parse(body);
    var depends_on_list = tracker.bugs[0].depends_on;

    // loop through the list of tracked bug ID's
    for (var bugIndex in depends_on_list) {
      var bugID = depends_on_list[bugIndex];

      // and for each tracked bug ID, go find info for that bug

      request("http://bugzilla.mozilla.org/rest/bug/" + depends_on_list[bugIndex] + "?include_fields=id,status,summary,assigned_to", function(error, response, body) {
        try {
          var parsedResult = JSON.parse(body);

          if (parsedResult.bugs) {
            var trackedBug = parsedResult.bugs[0];

            if (trackedBug.status == 'RESOLVED' || trackedBug.status == 'VERIFIED') {
              // do nothing
            } else {
              allBugs['' + trackedBug.id] = dashboard.formatForBugBox(trackedBug);
              dashboard.redrawBugs(allBugs);
            }
          }
        }
        catch (e) {
          allBugs['' + bugID] = bugID + ' error ' + e;
          dashboard.redrawBugs(allBugs);
        }
      });
    }
  });
}

function addEventsFromRepo(inRepoName) {
  github.events.getFromRepo( { 'user': 'mozilla', 'repo': inRepoName, per_page: 100 }, function(err, activities) {
    try {
      if (err) {
        throw new Error(err.message);
      }

      for (var activityIndex in activities) {
        var anActivity = activities[activityIndex];
        allEvents[anActivity.created_at] = dashboard.formatForEventBox(inRepoName, anActivity);
      }
      dashboard.redrawEvents(allEvents);
    }
    catch(e) {
      console.log('cannot parse events json', e);
      console.log(e.stack);
    }
  });
}

// go find all the activity for wadi repo's

addEventsFromRepo('oghliner');
addEventsFromRepo('platatus');
addEventsFromRepo('serviceworker-cookbook');

addBugsTrackedBy(1201717);
addBugsTrackedBy(1059784);

dashboard.initializeBlessedDashboard();
<commit_msg>add code to get attachments (commented out)<commit_after>// Whole-script strict mode syntax
"use strict";

var request = require('request');
var GitHub = require("github");
var util = require('util');
var dashboard = require('./dashboard.js');

var allEvents = {};
var allBugs = {};
var allAttachments = {};

var github = new GitHub({
    // required
    version: "3.0.0",
    // optional
    debug: false,
    protocol: "https",
    host: "api.github.com",
    timeout: 30000
  });

github.authenticate({
  type: "oauth",
  token: process.env.SEKRIT
});

// go find all the bugs we are tracking for WADI

// TODO get all history https://bugzilla.mozilla.org/rest/bug/707428/history
// TODO get attachments look for review status https://bugzilla.mozilla.org/rest/bug/707428/attachment

function addBugsTrackedBy(inBugID) {
  request("http://bugzilla.mozilla.org/rest/bug/" + inBugID + "?include_fields=id,depends_on", function(error, response, body) {
    var tracker = JSON.parse(body);
    var depends_on_list = tracker.bugs[0].depends_on;

    // loop through the list of tracked bug ID's
    for (var bugIndex in depends_on_list) {
      var bugID = depends_on_list[bugIndex];

      // and for each tracked bug ID, go find info for that bug

      // request("http://bugzilla.mozilla.org/rest/bug/" + depends_on_list[bugIndex] + "/attachment", function(error, response, body) {
      //   try {
      //     var parsedResult = JSON.parse(body);
      //     if (parsedResult.bugs[depends_on_list[bugIndex]]) {
      //       var attachmentContent = parsedResult.bugs[depends_on_list[bugIndex]];
      //       allAttachments[depends_on_list[bugIndex]] = attachmentContent;
      //       // console.log(bugID, attachmentContent);
      //       allBugs['' + trackedBug.id] = dashboard.formatForBugBox(trackedBug, attachmentContent);
      //       dashboard.redrawBugs(allBugs);
      //     }
      //   }
      //   catch (e) {
      //   }
      // });

      request("http://bugzilla.mozilla.org/rest/bug/" + depends_on_list[bugIndex] + "?include_fields=id,status,summary,assigned_to", function(error, response, body) {
        try {
          var parsedResult = JSON.parse(body);

          if (parsedResult.bugs) {
            var trackedBug = parsedResult.bugs[0];

            if (trackedBug.status == 'RESOLVED' || trackedBug.status == 'VERIFIED') {
              // do nothing
            } else {
              allBugs['' + trackedBug.id] = dashboard.formatForBugBox(trackedBug);
              dashboard.redrawBugs(allBugs);
            }
          } else {
            // missing buglist!
            allBugs['' + bugID] = bugID + ' missing bug info';
          }
        }
        catch (e) {
          allBugs['' + bugID] = bugID + ' error ' + e;
          dashboard.redrawBugs(allBugs);
        }
      });
    }
  });
}

function addEventsFromRepo(inRepoName) {
  github.events.getFromRepo( { 'user': 'mozilla', 'repo': inRepoName, per_page: 100 }, function(err, activities) {
    try {
      if (err) {
        throw new Error(err.message);
      }

      for (var activityIndex in activities) {
        var anActivity = activities[activityIndex];
        allEvents[anActivity.created_at] = dashboard.formatForEventBox(inRepoName, anActivity);
      }
      dashboard.redrawEvents(allEvents);
    }
    catch(e) {
      console.log('cannot parse events json', e);
      console.log(e.stack);
    }
  });
}

// go find all the activity for wadi repo's

addEventsFromRepo('oghliner');
addEventsFromRepo('platatus');
addEventsFromRepo('serviceworker-cookbook');

addBugsTrackedBy(1201717);
addBugsTrackedBy(1059784);

dashboard.initializeBlessedDashboard();
<|endoftext|>


<commit_before>$.fn.setUrduInput = function (options)
{
	var m={"q":"ق","w":"و","e":"ع","r":"ر","t":"ت","y":"ے","u":"ء","i":"ی","o":"ہ","p":"پ","a":"ا","s":"س","d":"د","f":"ف","g":"گ","h":"ح","j":"ج","k":"ک","l":"ل","z":"ز","x":"ش","c":"چ","v":"ط","b":"ب","n":"ن","m":"م","`":"ً",",":"،",".":"۔","Q":"ْ","W":"ّ","E":"ٰ","R":"ڑ","T":"ٹ","Y":"َ","U":"ئ","I":"ِ","O":"ۃ","P":"ُ","A":"آ","S":"ص","D":"ڈ","G":"غ","H":"ھ","J":"ض","K":"خ","Z":"ذ","X":"ژ","C":"ث","V":"ظ","N":"ں","M":"٘","~":"ٍ","?":"؟","F":"ٔ","L":"ل","B":"ب"};
	var last = '';
	$(this).bind('input', function ()
	{
		var pos = document.querySelector("#q").selectionEnd;
		var s = $(this).val();
		var isLastPos = (pos==s.length);
		if (last==s) return;
		var S = [];
		for (var x = 0; x < s.length; x++)
		{
			var c = s.charAt(x);
			S.push(m[c]||c);
		}
		$(this).val(S.join(''));
		last = $(this).val();
		if (!isLastPos) {
			document.querySelector("#q").selectionStart = document.querySelector("#q").selectionEnd = pos;
		}
	});
};
<commit_msg>remove hardcoded #q from the plugin and make it generic<commit_after>$.fn.setUrduInput = function (options)
{
	var m={"q":"ق","w":"و","e":"ع","r":"ر","t":"ت","y":"ے","u":"ء","i":"ی","o":"ہ","p":"پ","a":"ا","s":"س","d":"د","f":"ف","g":"گ","h":"ح","j":"ج","k":"ک","l":"ل","z":"ز","x":"ش","c":"چ","v":"ط","b":"ب","n":"ن","m":"م","`":"ً",",":"،",".":"۔","Q":"ْ","W":"ّ","E":"ٰ","R":"ڑ","T":"ٹ","Y":"َ","U":"ئ","I":"ِ","O":"ۃ","P":"ُ","A":"آ","S":"ص","D":"ڈ","G":"غ","H":"ھ","J":"ض","K":"خ","Z":"ذ","X":"ژ","C":"ث","V":"ظ","N":"ں","M":"٘","~":"ٍ","?":"؟","F":"ٔ","L":"ل","B":"ب"};
	var last = '';
	$(this).bind('input', function ()
	{
		var pos = $(this)[0].selectionEnd;
		var s = $(this).val();
		var isLastPos = (pos==s.length);
		if (last==s) return;
		var S = [];
		for (var x = 0; x < s.length; x++)
		{
			var c = s.charAt(x);
			S.push(m[c]||c);
		}
		$(this).val(S.join(''));
		last = $(this).val();
		if (!isLastPos) {
			$(this)[0].selectionStart = $(this)[0].selectionEnd = pos;
		}
	});
};
<|endoftext|>


<commit_before>/*
    by liz
*/

;(function(exports, undefined){

var zita = exports.zita = {};

// array or object

var Slice = function(arr, start, end){
    return Array.prototype.slice.call(arr, start, end);
}

zita.each = function(obj, callback){
    var i = 0, key;

    if(obj == null) return;

    if(obj.forEach){
        obj.forEach(function(){
            return callback.apply(zita, arguments);
        })

        return;
    }

    if(obj.length){
        // if obj is array
        for(; i < obj.length; i++){
            if(callback.call(zita, i, obj[i], obj) === false) break;
        }
    }else{
        // if obj is object
        key = zita.key(obj);
        for(; i < key.length; i++){
            if(callback.call(zita, key[i], obj[key[i]], obj) === false) break;
        }
    }

    return;
}

zita.merge = function(dest, orig){
    var res = Slice(dest, 1);

    zita.each(orig, function(value){
        res.push(value);
    });

    return res;
}

var IS_DONTENUM_BUG = (function(){
    for(var prop in {toString : 1}){
        if(prop == 'toString') return false;
    }
    return true;
})();

zita.keys = function(obj){
    var res = [],
        prop;

    for(prop in obj){
        if(!obj.hasOwnProperty(prop)) continue;
        res.push(prop);
    }

    // fix don't enum bug
    if(IS_DONTENUM_BUG){
        if(obj.toString !== Object.prototype.toString){
            res.push('toString');
        }

        if(obj.valueOf !== Object.prototype.valueOf){
            res.push('valueOf');
        }
    }

    return res;
}

zita.values = function(obj){
    var res = [];
        prop;

    for(prop in obj){
        if(!obj.hasOwnProperty(prop)) continue;
        res.push(obj[prop]);
    }

    return res;
}

zita.extend = function(dest, orig){
    var keys = zita.keys(orig);

    zita.each(keys, function(key){
        dest[key] = orig[key];
    });

    return dest;
}

// function

zita.debounce = function(callback, delay){
    var timer = null;

    function clear(){
        clearTimeout(timer);
        timer = null;
    }

    delay = delay || 200;

    return function(){
        var orig = callback,
            context = this,
            args = arguments;

        callback = function(){
            clear();
            orig.apply(context, args);
        }

        timer && clear();
        timer = setTimeout(callback, delay);
    }
}

zita.pulse = function(callback, period, delay){
    var timer = null,
        endtime, active;

    function now(){
        return (new Date).getTime();
    }

    function clear(){
        clearInterval(timer);
        timer = null;
        active = false;
    }

    delay = delay || 200;
    period = period || 1000;

    return function(){
        var orig = callback,
            context = this,
            args = arguments;

        callback = function(){
            orig.apply(context, args);
            if(now() > endtime){
                clear();
            }
        }

        endtime = now() + period;
        if(!active){
            active = true;
            timer = setInterval(callback, delay);
        }
    }
}

// dom and cssom

zita.Node = (function(){

    var win = window,
        doc = document,
        docRoot = doc.documentElement,
        body = doc.body;

    function getElementNode(node){
        if(node && node.nodeType){
            if(node.nodeType == 3){
                node = node.parentNode;
            }

            return node;
        }

        if(node && node.zita){
            return node.self;
        }

        return false
    }

    function Node(node){
        if(node.length){
            node = node[0];
        }

        if(!(node = getElementNode(node))){
            throw Error('not element node');
        }

        this.self = node;
    }

    Node.fn = Node.prototype = {
        zita : '0.0.1'
    }

    Node.fn.contains = function(node){
        var self = this.self,
            cur;

        if(!(node = getElementNode(node))) return false;

        if(self.contains){
            return self.contains(node);
        }

        if(self.compareDocumentPosition){
            // DOCUMENT_POSITION_DISCONNECTED            1
            // DOCUMENT_POSITION_PRECEDING               2
            // DOCUMENT_POSITION_FOLLOWING               4
            // DOCUMENT_POSITION_CONTAINS                8
            // DOCUMENT_POSITION_CONTAINED_BY            16
            // DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC 32
            return !!(self.compareDocumentPosition(node) & 16);
        }

        cur = node;
        while(cur){
            if(cur == self) return true;
            cur = node.parentNode;
        }

        return false;
    }

    Node.fn.offset = function(){
        var self = this.self,
            cur, offsetParent,
            crect,
            rect = null;

        if(self.getBoundingClientRect){
            crect = self.getBoundingClientRect();
            rect = {};

            zita.each('left top'.split(' '), function(dir){
                // firefox not round the top and bottom
                if(crect[dir] === undefined){
                    rect = null;
                    return false;
                }
                rect[dir] = crect[dir];
            });
        }

        if(!rect){
            offsetParent = self.offsetParent;
            rect = {
                left : self.offsetLeft,
                top : self.offsetTop
            };

            cur = self;
            while((cur = cur.parentNode) && cur != body){
                rect.left -= cur.scrollLeft;
                rect.top += cur.scrollTop;

                if(cur == offsetParent){
                    // use clientLeft/Top to replace calculating elem border width
                    rect.left += cur.offsetLeft + cur.clientLeft;
                    rect.top += cur.offsetTop + cur.clientTop;

                    offsetParent = cur.offsetParent;
                }
            }
        }else{
            // subtract clientLeft/Top to correct double counting
            rect.left += (win.pageXOffset || docRoot.scrollLeft) - docRoot.clientLeft;
            rect.top += (win.pageYOffset || docRoot.scrollTop) - docRoot.clientTop;
        }

        return rect;
    }

    return function(node){
        return new Node(node);
    };

})();

// tools

zita.Ticker = (function(){

    var win = exports,

        // internal identity is used to mark a registered function
        tickId = 0,
        tickers = [],

        timerId = null,

        requestAnimFrame,
        cancelAnimFrame,

        settings = {
            useRAF : true,
            interval : 1000 / 60
        };

    (function(){
        var vendors = ' ms moz webkit o'.split(' '),
            i = 0,
            len = vendors.length;

        if(settings.useRAF){
            for(; i < len && !requestAnimFrame; i++){
                requestAnimFrame = win[vendors[i] + 'RequestAnimationFrame'];
                cancelAnimFrame = win[vendors[i] + 'CancelAnimationFrame'] || win[vendors[i] + 'CancelRequestAnimationFrame'];
            }
        }

        requestAnimFrame || (requestAnimFrame = function(callback){
            return win.setTimeout(callback, settings.interval);
        });

        cancelAnimFrame || (cancelAnimFrame = function(timerId){
            return win.clearTimeout(timerId);
        });
    })();

    function tick(){
        var ticker,
            i = 0,
            len = tickers.length;

        for(; i < len; i++){
            ticker = tickers[i];
            ticker.callback.call(ticker.context);
        }
    }

    function run(){
        timerId = requestAnimFrame(arguments.callee);
        tick();
    }

    function stop(){
        cancelAnimFrame(timerId);
        timerId = null;
    }

    return {
        add : function(callback, context){
            // if the callback function has registered, skip it
            if(callback.tickId) return;

            callback.tickId = 'tick-' + tickId++;
            tickers.push({
                callback : callback,
                context : context || win
            });

            if(tickers.length == 1) run();

            return callback;
        },
        remove : function(callback){
            var ticker,
                i = 0,
                len = runers.length;

            if(!callback){
                tickers = [];
            }else{
                if(!callback.tickId) return;

                for(; i < len; i++){
                    ticker = tickers[i];
                    if(callback.tickId == ticker.callback.tickId){
                        callback = tickers.splice(i, 1);
                        delete callback.tickId;
                        break;
                    }
                }
            }

            if(!tickers.length){
                stop();
            }

            return callback;
        }
    }

})();

})(window);
<commit_msg>fix bug and add the clone function<commit_after>/*
    by liz
*/

;(function(exports, undefined){

var zita = exports.zita = {
    version : 0.0.1
};

// array or object

var slice = function(arr, start, end){
    return Array.prototype.slice.call(arr, start, end);
}

zita.each = function(obj, callback){
    var keys,
        i = 0;

    if(obj == null) return;

    if(obj.forEach){
        obj.forEach(function(){
            return callback.apply(zita, arguments);
        })

        return;
    }

    if(obj.length){
        // if obj is array
        for(; i < obj.length; i++){
            if(callback.call(zita, i, obj[i], obj) === false) break;
        }
    }else{
        // if obj is object
        keys = zita.keys(obj);
        for(; i < keys.length; i++){
            if(callback.call(zita, keys[i], obj[keys[i]], obj) === false) break;
        }
    }

    return;
}

zita.merge = function(dest, orig){
    var res = slice(dest, 1),
        offset = res.length,
        i = 0;

    for(; i < res.length; i++){
        res[offset + i] = orig[i];
    }

    return res;
}

var IS_DONTENUM_BUG = (function(){
    for(var prop in {toString : 1}){
        if(prop == 'toString') return false;
    }
    return true;
})();

zita.keys = function(obj){
    var res = [],
        prop;

    for(prop in obj){
        if(!obj.hasOwnProperty(prop)) continue;
        res.push(prop);
    }

    // fix don't enum bug
    if(IS_DONTENUM_BUG){
        if(obj.toString !== Object.prototype.toString){
            res.push('toString');
        }

        if(obj.valueOf !== Object.prototype.valueOf){
            res.push('valueOf');
        }
    }

    return res;
}

zita.values = function(obj){
    var res = [];
        prop;

    for(prop in obj){
        if(!obj.hasOwnProperty(prop)) continue;
        res.push(obj[prop]);
    }

    // fix don't enum bug
    if(IS_DONTENUM_BUG){
        if(obj.toString !== Object.prototype.toString){
            res.push(obj.toString);
        }

        if(obj.valueOf !== Object.prototype.valueOf){
            res.push(obj.valueOf);
        }
    }

    return res;
}

zita.extend = function(dest, orig){
    var keys = zita.keys(orig),
        i = 0;

    for(; i < keys.length; i++){
        dest[keys[i]] = orig[keys[i]];
    });

    return dest;
}

zita.clone = function(orig){
    return zita.extend({}, orig);
}

// function

var now = Date.now || function(){
    return (new Date).getTime();
}

zita.debounce = function(callback, delay){
    var timer = null;

    function clear(){
        clearTimeout(timer);
        timer = null;
    }

    delay = delay || 200;

    return function(){
        var orig = callback,
            context = this,
            args = arguments;

        callback = function(){
            clear();
            orig.apply(context, args);
        }

        timer && clear();
        timer = setTimeout(callback, delay);
    }
}

zita.pulse = function(callback, period, delay){
    var timer = null,
        endtime, active;

    function clear(){
        clearInterval(timer);
        timer = null;
        active = false;
    }

    delay = delay || 200;
    period = period || 1000;

    return function(){
        var orig = callback,
            context = this,
            args = arguments;

        callback = function(){
            orig.apply(context, args);
            if(now() > endtime){
                clear();
            }
        }

        endtime = now() + period;
        if(!active){
            active = true;
            timer = setInterval(callback, delay);
        }
    }
}

// dom and cssom

zita.Node = (function(){

    var win = window,
        doc = document,
        docRoot = doc.documentElement,
        body = doc.body;

    function getElementNode(node){
        if(node && node.nodeType){
            if(node.nodeType == 3){
                node = node.parentNode;
            }

            return node;
        }

        if(node && node.zita){
            return node.self;
        }

        return false
    }

    function Node(node){
        if(node.length){
            node = node[0];
        }

        if(!(node = getElementNode(node))){
            throw Error('not element node');
        }

        this.self = node;
    }

    Node.fn = Node.prototype = {
        zita : zita.version
    }

    Node.fn.contains = function(node){
        var self = this.self,
            cur;

        if(!(node = getElementNode(node))) return false;

        if(self.contains){
            return self.contains(node);
        }

        if(self.compareDocumentPosition){
            // DOCUMENT_POSITION_DISCONNECTED            1
            // DOCUMENT_POSITION_PRECEDING               2
            // DOCUMENT_POSITION_FOLLOWING               4
            // DOCUMENT_POSITION_CONTAINS                8
            // DOCUMENT_POSITION_CONTAINED_BY            16
            // DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC 32
            return !!(self.compareDocumentPosition(node) & 16);
        }

        cur = node;
        while(cur){
            if(cur == self) return true;
            cur = node.parentNode;
        }

        return false;
    }

    Node.fn.offset = function(){
        var self = this.self,
            cur, offsetParent,
            crect,
            rect = null;

        if(self.getBoundingClientRect){
            crect = self.getBoundingClientRect();
            rect = {};

            zita.each('left top'.split(' '), function(dir){
                // firefox not round the top and bottom
                if(crect[dir] === undefined){
                    rect = null;
                    return false;
                }
                rect[dir] = crect[dir];
            });
        }

        if(!rect){
            offsetParent = self.offsetParent;
            rect = {
                left : self.offsetLeft,
                top : self.offsetTop
            };

            cur = self;
            while((cur = cur.parentNode) && cur != body){
                rect.left -= cur.scrollLeft;
                rect.top += cur.scrollTop;

                if(cur == offsetParent){
                    // use clientLeft/Top to replace calculating elem border width
                    rect.left += cur.offsetLeft + cur.clientLeft;
                    rect.top += cur.offsetTop + cur.clientTop;

                    offsetParent = cur.offsetParent;
                }
            }
        }else{
            // subtract clientLeft/Top to correct double counting
            rect.left += (win.pageXOffset || docRoot.scrollLeft) - docRoot.clientLeft;
            rect.top += (win.pageYOffset || docRoot.scrollTop) - docRoot.clientTop;
        }

        return rect;
    }

    return function(node){
        return new Node(node);
    };

})();

// tools

zita.Ticker = (function(){

    var win = exports,

        // internal identity is used to mark a registered function
        tickId = 0,
        tickers = [],

        timerId = null,

        requestAnimFrame,
        cancelAnimFrame,

        settings = {
            useRAF : true,
            interval : 1000 / 60
        };

    (function(){
        var vendors = ' ms moz webkit o'.split(' '),
            i = 0,
            len = vendors.length;

        if(settings.useRAF){
            for(; i < len && !requestAnimFrame; i++){
                requestAnimFrame = win[vendors[i] + 'RequestAnimationFrame'];
                cancelAnimFrame = win[vendors[i] + 'CancelAnimationFrame'] || win[vendors[i] + 'CancelRequestAnimationFrame'];
            }
        }

        requestAnimFrame || (requestAnimFrame = function(callback){
            return win.setTimeout(callback, settings.interval);
        });

        cancelAnimFrame || (cancelAnimFrame = function(timerId){
            return win.clearTimeout(timerId);
        });
    })();

    function tick(){
        var ticker,
            i = 0,
            len = tickers.length;

        for(; i < len; i++){
            ticker = tickers[i];
            ticker.callback.call(ticker.context);
        }
    }

    function run(){
        timerId = requestAnimFrame(arguments.callee);
        tick();
    }

    function stop(){
        cancelAnimFrame(timerId);
        timerId = null;
    }

    return {
        add : function(callback, context){
            // if the callback function has registered, skip it
            if(callback.tickId) return;

            callback.tickId = 'tick-' + tickId++;
            tickers.push({
                callback : callback,
                context : context || win
            });

            if(tickers.length == 1) run();

            return callback;
        },
        remove : function(callback){
            var ticker,
                i = 0,
                len = runers.length;

            if(!callback){
                tickers = [];
            }else{
                if(!callback.tickId) return;

                for(; i < len; i++){
                    ticker = tickers[i];
                    if(callback.tickId == ticker.callback.tickId){
                        callback = tickers.splice(i, 1);
                        delete callback.tickId;
                        break;
                    }
                }
            }

            if(!tickers.length){
                stop();
            }

            return callback;
        }
    }

})();

})(window);
<|endoftext|>