<commit_before>var Pex = require("../../src/pex/pex-plask");

Pex.run([
  "pex/core/Core",
  "pex/core/Vec3",
  "pex/sys/Window",
  "pex/cameras/PerspectiveCamera",
  "pex/cameras/Arcball",
  "pex/geom/Geom",
  "pex/materials/Materials",
  "pex/geom/hem/HEMesh",
  "pex/geom/hem/HEFace",
  "pex/geom/hem/HEEdge",
  "pex/geom/hem/HEVertex",
  "pex/geom/hem/CatmullClark",
  "pex/geom/hem/Extrude"
  ],
  function(Core, Vec3, Window, PerspectiveCamera, Arcball, Geom, Materials, HEMesh, HEFace, HEEdge, HEVertex, CatmullClark, Extrude) {
    Window.create({
      settings: {
        width: 1280,
        height: 720,
        type: '3d',
        vsync: true,
        multisample: true,
        fullscreen: false,
        center: true
      },
      init: function() {
        var gl = Core.Context.currentContext.gl;

        gl.clearColor(0, 0, 0, 1);
        gl.enable(gl.DEPTH_TEST);

        this.camera = new PerspectiveCamera(60, this.width/this.height);
        this.arcball = new Arcball(this, this.camera, 10);

        var hemesh = new HEMesh();

        hemesh.vertices.push(new HEVertex( 1, 1, 1)); //trf 0
        hemesh.vertices.push(new HEVertex(-1, 1, 1)); //tlf 1
        hemesh.vertices.push(new HEVertex(-1,-1, 1)); //blf 2
        hemesh.vertices.push(new HEVertex( 1,-1, 1)); //brf 3
        hemesh.vertices.push(new HEVertex( 1, 1,-1)); //trb 4
        hemesh.vertices.push(new HEVertex(-1, 1,-1)); //tlb 5
        hemesh.vertices.push(new HEVertex(-1,-1,-1)); //blb 6
        hemesh.vertices.push(new HEVertex( 1,-1,-1)); //brb 7

        var self = this;
        this.selection = [];

        function addFace4(a, b, c, d) {
          var face = new HEFace();

          self.selection.push(face);

          var edge0 = new HEEdge(a, null, face, null);
          var edge1 = new HEEdge(b, null, face, null);
          var edge2 = new HEEdge(c, null, face, null);
          var edge3 = new HEEdge(d, null, face, null);

          edge0.next = edge1;
          edge1.next = edge2;
          edge2.next = edge3;
          edge3.next = edge0;

          hemesh.edges.push(edge0);
          hemesh.edges.push(edge1);
          hemesh.edges.push(edge2);
          hemesh.edges.push(edge3);

          face.edge = edge0;
          hemesh.faces.push(face);
        }

        addFace4(hemesh.vertices[0], hemesh.vertices[1], hemesh.vertices[2], hemesh.vertices[3]);
        addFace4(hemesh.vertices[4], hemesh.vertices[0], hemesh.vertices[3], hemesh.vertices[7]);
        addFace4(hemesh.vertices[5], hemesh.vertices[4], hemesh.vertices[7], hemesh.vertices[6]);
        addFace4(hemesh.vertices[1], hemesh.vertices[5], hemesh.vertices[6], hemesh.vertices[2]);
        addFace4(hemesh.vertices[4], hemesh.vertices[5], hemesh.vertices[1], hemesh.vertices[0]);
        addFace4(hemesh.vertices[3], hemesh.vertices[2], hemesh.vertices[6], hemesh.vertices[7]);

        hemesh.assignEdgesToVertices();
        hemesh.assignEdgePairs();

        var catmullClark = new CatmullClark();
        var extrude = new Extrude();
        hemesh = extrude.apply(hemesh, 2.5, self.selection);
        //hemesh = catmullClark.apply(hemesh);
        //hemesh = catmullClark.apply(hemesh);
        //hemesh = catmullClark.apply(hemesh);
        //hemesh = catmullClark.apply(hemesh);
        //hemesh = catmullClark.apply(hemesh);
        //console.log(hemesh.vertices.length, hemesh.edges.length);

        var scale = 3;
        this.on('keyDown', function(e) {
          if (e.keyCode == 48 || e.str == 's') {
              hemesh = catmullClark.apply(hemesh);
              //self.buildLineMesh(hemesh);
              this.buildSolidMesh(hemesh);
              //self.buildFlatMesh(hemesh);
              self.selection = [];
          }
          else if (e.str == ' ') {
            self.selection = [];
            for(var i=0; i<25; i++) {
              self.selection.push(hemesh.faces[Math.floor(Math.random() * hemesh.faces.length)]);
            }
            hemesh = extrude.apply(hemesh, scale, self.selection);
            scale *= 0.75;
            //self.buildLineMesh(hemesh);
            //self.buildFlatMesh(hemesh);
            self.buildSolidMesh(hemesh);
          }
        })

        var edge01 = hemesh.getEdgeBetween(hemesh.vertices[0], hemesh.vertices[1]);

        //select edge
        //edge01.selected = 1;
        //edge01.pair.next.selected = 1;
        //edge01.pair.next.pair.next.selected = 1;

        //select edge face
        //var selectedEdge = edge01;
        //do {
        //  selectedEdge.selected = 1;
        //  selectedEdge = selectedEdge.next;
        //} while(selectedEdge != edge01);

        //edge01.pair.next.selected = 1;

        //drawing

        this.buildLineMesh(hemesh);
        this.buildSolidMesh(hemesh);
        //this.buildFlatMesh(hemesh);
        this.framerate(30);
      },
      buildLineMesh: function(hemesh) {
        var lineBuilder = new Geom.LineBuilder();
        for(var i in hemesh.vertices) {
          //lineBuilder.addGizmo(hemesh.vertices[i], 0.01, Core.Color.Yellow);
        }

        var i = 0;
        for(var i in hemesh.faces) {
          var face = hemesh.faces[i];

          //collect all the vertices of a face
          var faceVertices = [];
          var edge = face.edge;
          do {
            faceVertices.push(edge.vert);
            edge = edge.next;
          } while(edge != face.edge);

          var center = face.getCenter();

          //drawing all the adges of the face shifted a bit towards the center
          for(var j=0; j<faceVertices.length; j++) {
            var a = faceVertices[j];
            var b = faceVertices[(j+1)%faceVertices.length];
            var ac = center.subbed(a).scale(0.01);
            var bc = center.subbed(b).scale(0.01);
            ac.add(a);
            bc.add(b);
            var edgeAB = hemesh.getEdgeBetween(a, b);
            lineBuilder.addLine(ac, bc, edgeAB.selected ? Core.Color.Yellow : Core.Color.White);
          }

          //drawing face normals
          var normal = face.getNormal();
          //lineBuilder.addLine(center, center.added(normal.scaled(0.1)), Core.Color.Green);
        }

        this.lineMesh = new Core.Mesh(lineBuilder, new Materials.ShowColorMaterial(), {useEdges:true, primitiveType:Core.Geometry.LINES});
      },
      buildSolidMesh: function(hemesh) {
        var geometry = new Core.Geometry();
        geometry.vertices = [];
        geometry.faces = [];
        geometry.normals = [];

        for(var i in hemesh.vertices) {
          geometry.vertices.push(hemesh.vertices[i]);
          geometry.normals.push(hemesh.vertices[i].getNormal());
        }

        for(var i in hemesh.faces) {
          var faceVertices = hemesh.faces[i].getAllVertices();
          var faceVertexIndices = [];
          for(var j=0; j<faceVertices.length; j++) {
            faceVertexIndices[j] = geometry.vertices.indexOf(faceVertices[j]);
          }
          if (faceVertices.length == 3) {
            geometry.faces.push(new Core.Face3(faceVertexIndices[0], faceVertexIndices[1], faceVertexIndices[2]));
          }
          else if (faceVertices.length == 4){
            geometry.faces.push(new Core.Face4(faceVertexIndices[0], faceVertexIndices[1], faceVertexIndices[2], faceVertexIndices[3]));
          }
          else {
            throw "Invalid mesh. Only triangles and quads are supported. Not " + faceVertices.length + "-gons";
          }
        }
        this.mesh = new Core.Mesh(geometry, new Materials.TestMaterial());
      },
      buildFlatMesh: function(hemesh) {
        var geometry = new Core.Geometry();
        geometry.vertices = [];
        geometry.faces = [];
        geometry.normals = [];

        var idx = 0;
        for(var i in hemesh.faces) {
          var face = hemesh.faces[i];
          var faceVertices = face.getAllVertices();
          for(var j in faceVertices) {
            var v = faceVertices[j];
            geometry.vertices.push(new Core.Vec3(v.x, v.y, v.z));
            geometry.normals.push(face.getNormal());
          }
          if (faceVertices.length == 3) {
            geometry.faces.push(new Core.Face3(idx++, idx++, idx++));
          }
          else if (faceVertices.length == 4){
            geometry.faces.push(new Core.Face4(idx++, idx++, idx++, idx++));
          }
          else {
            throw "Invalid mesh. Only triangles and quads are supported. Not " + faceVertices.length + "-gons";
          }
        }
        console.log("geometry v:" + geometry.vertices.length);
        this.mesh = new Core.Mesh(geometry, new Materials.TestMaterial());
      },
      draw: function() {
        var gl = Core.Context.currentContext.gl;
        gl.clearColor(1, 0, 0, 1);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

        this.mesh.draw(this.camera);
        this.lineMesh.draw(this.camera);
      }
    });
  }
);

<commit_msg>Hemesh example updates<commit_after>var Pex = require("../../src/pex/pex-plask");

Pex.run([
  "pex/core/Core",
  "pex/core/Vec3",
  "pex/sys/Window",
  "pex/util/Time",
  "pex/cameras/PerspectiveCamera",
  "pex/cameras/Arcball",
  "pex/geom/Geom",
  "pex/materials/Materials",
  "pex/geom/hem/HEMesh",
  "pex/geom/hem/HEFace",
  "pex/geom/hem/HEEdge",
  "pex/geom/hem/HEVertex",
  "pex/geom/hem/CatmullClark",
  "pex/geom/hem/Extrude"
  ],
  function(Core, Vec3, Window, Time, PerspectiveCamera, Arcball, Geom, Materials, HEMesh, HEFace, HEEdge, HEVertex, CatmullClark, Extrude) {
    Window.create({
      settings: {
        width: 1280,
        height: 720,
        type: '3d',
        vsync: true,
        multisample: true,
        fullscreen: false,
        center: true
      },
      init: function() {
        var gl = Core.Context.currentContext.gl;

        gl.clearColor(0, 0, 0, 1);
        gl.enable(gl.DEPTH_TEST);

        this.camera = new PerspectiveCamera(60, this.width/this.height);
        this.arcball = new Arcball(this, this.camera, 3);

        var hemesh = new HEMesh();

        hemesh.vertices.push(new HEVertex( 1, 1, 1)); //trf 0
        hemesh.vertices.push(new HEVertex(-1, 1, 1)); //tlf 1
        hemesh.vertices.push(new HEVertex(-1,-1, 1)); //blf 2
        hemesh.vertices.push(new HEVertex( 1,-1, 1)); //brf 3
        hemesh.vertices.push(new HEVertex( 1, 1,-1)); //trb 4
        hemesh.vertices.push(new HEVertex(-1, 1,-1)); //tlb 5
        hemesh.vertices.push(new HEVertex(-1,-1,-1)); //blb 6
        hemesh.vertices.push(new HEVertex( 1,-1,-1)); //brb 7

        var self = this;
        this.selection = [];

        function addFace4(a, b, c, d) {
          var face = new HEFace();

          self.selection.push(face);

          var edge0 = new HEEdge(a, null, face, null);
          var edge1 = new HEEdge(b, null, face, null);
          var edge2 = new HEEdge(c, null, face, null);
          var edge3 = new HEEdge(d, null, face, null);

          edge0.next = edge1;
          edge1.next = edge2;
          edge2.next = edge3;
          edge3.next = edge0;

          hemesh.edges.push(edge0);
          hemesh.edges.push(edge1);
          hemesh.edges.push(edge2);
          hemesh.edges.push(edge3);

          face.edge = edge0;
          hemesh.faces.push(face);
        }

        addFace4(hemesh.vertices[0], hemesh.vertices[1], hemesh.vertices[2], hemesh.vertices[3]);
        addFace4(hemesh.vertices[4], hemesh.vertices[0], hemesh.vertices[3], hemesh.vertices[7]);
        addFace4(hemesh.vertices[5], hemesh.vertices[4], hemesh.vertices[7], hemesh.vertices[6]);
        addFace4(hemesh.vertices[1], hemesh.vertices[5], hemesh.vertices[6], hemesh.vertices[2]);
        addFace4(hemesh.vertices[4], hemesh.vertices[5], hemesh.vertices[1], hemesh.vertices[0]);
        addFace4(hemesh.vertices[3], hemesh.vertices[2], hemesh.vertices[6], hemesh.vertices[7]);

        hemesh.assignEdgesToVertices();
        hemesh.assignEdgePairs();

        hemesh.vertices[0].selected = true;
        hemesh.vertices[0].edge.next.next.vert.selected = true;
        //hemesh.vertices[0].edge.selected = true;
        var newVertPos = hemesh.vertices[0].dup();
        newVertPos.add(hemesh.vertices[0].edge.next.vert.subbed(hemesh.vertices[0]).scale(0.5));

        hemesh.clearEdgeSelection();
        hemesh.vertices[0].edge.face.selected = true;

        //var newEdge = hemesh.splitVertex(hemesh.vertices[0], newVertPos, hemesh.vertices[0].edge, hemesh.vertices[0].edge);
        //hemesh.splitFace(hemesh.vertices[0].edge.findPrev(), newEdge);
        //var newEdge = hemesh.splitVertex(hemesh.vertices[0], hemesh.vertices[0].edge.face.getCenter(), null, null);
        //hemesh.splitFace(newEdge.next, newEdge.next.next.next);
        //hemesh.splitFace(newEdge.next, newEdge.next.next.next);
        //hemesh.splitFace(newEdge.next, newEdge.next.next.next);

        var topFace = hemesh.vertices[0].edge.face;
        hemesh.splitFaceAtPoint(topFace, topFace.getCenter());
        hemesh.splitFaceAtPoint(topFace, topFace.getCenter());
        hemesh.splitFaceAtPoint(topFace, topFace.getCenter());

        hemesh.check();

        var numEdges = hemesh.edges.length;
        //hemesh.clearEdgeSelection();
        for(var i=0; i<numEdges; i++) {
          var edge = hemesh.edges[i];
          if (edge.selected) {
            continue;
          }

          //edge.selected = true;
          //edge.pair.selected = true;

          //hemesh.splitEdge(edge);
        }

        var catmullClark = new CatmullClark();
        var extrude = new Extrude();
        //hemesh = extrude.apply(hemesh, 2.5, self.selection);
        //hemesh = catmullClark.apply(hemesh);
        //hemesh = catmullClark.apply(hemesh);
        //hemesh = catmullClark.apply(hemesh);
        //hemesh = catmullClark.apply(hemesh);
        //hemesh = catmullClark.apply(hemesh);
        //console.log(hemesh.vertices.length, hemesh.edges.length);

        var scale = 3;
        var subdivisionLevel = 0;
        this.on('keyDown', function(e) {
          if (e.keyCode == 48 || e.str == 's') {
            Time.startMeasuringTime();
            subdivisionLevel++
            hemesh = catmullClark.apply(hemesh);
            Time.stopMeasuringTime("Camtull-Clark subdivision at level:" + subdivisionLevel + " = ");
            Time.startMeasuringTime();
            self.buildLineMesh(hemesh);
            Time.stopMeasuringTime("Building line mesh at level:" + subdivisionLevel + " = ");
            //this.buildSolidMesh(hemesh);
            //self.buildFlatMesh(hemesh);
            self.selection = [];
          }
          else if (e.str == ' ') {
            self.selection = [];
            for(var i=0; i<25; i++) {
              self.selection.push(hemesh.faces[Math.floor(Math.random() * hemesh.faces.length)]);
            }
            hemesh = extrude.apply(hemesh, scale, self.selection);
            scale *= 0.75;
            self.buildLineMesh(hemesh);
            //self.buildFlatMesh(hemesh);
            //self.buildSolidMesh(hemesh);
          }
        })

        var edge01 = hemesh.getEdgeBetween(hemesh.vertices[0], hemesh.vertices[1]);

        //select edge
        //edge01.selected = 1;
        //edge01.pair.next.selected = 1;
        //edge01.pair.next.pair.next.selected = 1;

        //select edge face
        //var selectedEdge = edge01;
        //do {
        //  selectedEdge.selected = 1;
        //  selectedEdge = selectedEdge.next;
        //} while(selectedEdge != edge01);

        //edge01.pair.next.selected = 1;

        //drawing

        this.buildLineMesh(hemesh);
        //this.buildSolidMesh(hemesh);
        //this.buildFlatMesh(hemesh);
        this.framerate(30);
      },
      buildLineMesh: function(hemesh) {
        var lineBuilder = new Geom.LineBuilder();
        if (hemesh.vertices < 100) {
          for(var i in hemesh.vertices) {
            lineBuilder.addGizmo(hemesh.vertices[i], 0.01, hemesh.vertices[i].selected ? Core.Color.Red : Core.Color.Black);
          }
        }

        var i = 0;
        for(var i in hemesh.faces) {
          var face = hemesh.faces[i];

          //collect all the vertices of a face
          var faceVertices = [];
          var edge = face.edge;
          do {
            faceVertices.push(edge.vert);
            edge = edge.next;
          } while(edge != face.edge);

          var center = face.getCenter();

          //drawing all the adges of the face shifted a bit towards the center
          for(var j=0; j<faceVertices.length; j++) {
            var a = faceVertices[j];
            var b = faceVertices[(j+1)%faceVertices.length];
            var ac = center.subbed(a).scale(0.01);
            var bc = center.subbed(b).scale(0.01);
            ac.add(a);
            bc.add(b);
            var edgeAB = hemesh.getEdgeBetween(a, b);
            var selected = edgeAB.selected || face.selected;
            lineBuilder.addLine(ac, bc, selected ? Core.Color.Red : Core.Color.Black);
          }

          //drawing face normals
          var normal = face.getNormal();
          //lineBuilder.addLine(center, center.added(normal.scaled(0.1)), Core.Color.Green);
        }

        this.lineMesh = new Core.Mesh(lineBuilder, new Materials.ShowColorMaterial(), {useEdges:true, primitiveType:Core.Geometry.LINES});
      },
      buildSolidMesh: function(hemesh) {
        var geometry = new Core.Geometry();
        geometry.vertices = [];
        geometry.faces = [];
        geometry.normals = [];

        for(var i in hemesh.vertices) {
          geometry.vertices.push(hemesh.vertices[i]);
          geometry.normals.push(hemesh.vertices[i].getNormal());
        }

        for(var i in hemesh.faces) {
          var faceVertices = hemesh.faces[i].getAllVertices();
          var faceVertexIndices = [];
          for(var j=0; j<faceVertices.length; j++) {
            faceVertexIndices[j] = geometry.vertices.indexOf(faceVertices[j]);
          }
          if (faceVertices.length == 3) {
            geometry.faces.push(new Core.Face3(faceVertexIndices[0], faceVertexIndices[1], faceVertexIndices[2]));
          }
          else if (faceVertices.length == 4){
            geometry.faces.push(new Core.Face4(faceVertexIndices[0], faceVertexIndices[1], faceVertexIndices[2], faceVertexIndices[3]));
          }
          else {
            throw "Invalid mesh. Only triangles and quads are supported. Not " + faceVertices.length + "-gons";
          }
        }
        this.mesh = new Core.Mesh(geometry, new Materials.TestMaterial());
      },
      buildFlatMesh: function(hemesh) {
        var geometry = new Core.Geometry();
        geometry.vertices = [];
        geometry.faces = [];
        geometry.normals = [];

        var idx = 0;
        for(var i in hemesh.faces) {
          var face = hemesh.faces[i];
          var faceVertices = face.getAllVertices();
          for(var j in faceVertices) {
            var v = faceVertices[j];
            geometry.vertices.push(new Core.Vec3(v.x, v.y, v.z));
            geometry.normals.push(face.getNormal());
          }
          if (faceVertices.length == 3) {
            geometry.faces.push(new Core.Face3(idx++, idx++, idx++));
          }
          else if (faceVertices.length == 4){
            geometry.faces.push(new Core.Face4(idx++, idx++, idx++, idx++));
          }
          else {
            throw "Invalid mesh. Only triangles and quads are supported. Not " + faceVertices.length + "-gons";
          }
        }
        console.log("geometry v:" + geometry.vertices.length);
        this.mesh = new Core.Mesh(geometry, new Materials.TestMaterial());
      },
      draw: function() {
        var gl = Core.Context.currentContext.gl;
        gl.clearColor(1, 1, 1, 1);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

        if (this.mesh) this.mesh.draw(this.camera);
        if (this.lineMesh) this.lineMesh.draw(this.camera);
      }
    });
  }
);

<|endoftext|>


<commit_before>var gulp = require('gulp');
var watch = require('gulp-watch');
var awspublish = require('gulp-awspublish');
var _ = require('underscore');
var fs = require('fs');
var del = require('del');
var awspublishRouter = require("gulp-awspublish-router");
var minimist = require('minimist');
var rename = require("gulp-rename");
var download = require('gulp-downloader');
var jeditor = require("gulp-json-editor");
var parallelize = require("concurrent-transform");

var sts_url = require('./config').sts_url;

var options = minimist(process.argv.slice(2));

var temporaryCredentialsFile = 'temporary-credentials.json';

function dist(folder){

    // get credentials
    var storedData = JSON.parse(fs.readFileSync(temporaryCredentialsFile, 'utf8'));

    var credentials = storedData.credentials;
    var info = storedData.info;
    var dir = info.dir;
    // create a new publisher using S3 options
    // http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#constructor-property
    var publisherOptions = _.extend(credentials,
      {
        params: {
          Bucket: info.bucket,
          // ACL: "public-read"
        },
        logger: process.stdout
      }
    );

    var publisher = awspublish.create(publisherOptions);

    // this will publish and sync bucket files with the one in your public directory
    return gulp.src(folder + '/**/*.*')

        // rename extensions to lower case
        .pipe(rename(function (path) {
            path.extname = path.extname.toLowerCase();
        }))

        // set content type
        .pipe(awspublishRouter({
            routes: {

                "[\\w/\-\\s\.]*\\.css$": {
                    headers: {
                        "Content-Type": "text/css"
                    },
                    key: dir + "/" + "$&"
                },

                "[\\w/\-\\s\.]*\\.js$": {
                    headers: {
                        "Content-Type": "application/javascript"
                    },
                    key: dir + "/" + "$&"
                },

                "[\\w/\-\\s\.]*\\.jpg$": {
                    headers: {
                        "Content-Type": "image/jpg"
                    },
                    key: dir + "/" + "$&"
                },

                "[\\w/\-\\s\.]*\\.ico$": {
                  headers: {
                    "Content-Type": "image/x-icon"
                  },
                  key: dir + "/" + "$&"
                },

                "[\\w/\-\\s\.]*\\.jpeg$": {
                    headers: {
                        "Content-Type": "image/jpg"
                    },
                    key: dir + "/" + "$&"
                },

                "[\\w/\-\\s\.]*\\.gif$": {
                    headers: {
                        "Content-Type": "image/gif"
                    },
                    key: dir + "/" + "$&"
                },

                "[\\w/\-\\s\.]*\\.png$": {
                    headers: {
                        "Content-Type": "image/png"
                    },
                    key: dir + "/" + "$&"
                },

                "[\\w/\-\\s\.]*\\.html": {
                  headers: {
                    "Content-Type": "text/html"
                  },
                  key: dir + "/" + "$&"
                },

                "^.+$": {
                    headers: {
                        "Content-Type": "text/plain"
                    },
                    key: dir + "/" + "$&"
                },

            }
        }))

        // publisher will add Content-Length, Content-Type and headers specified above
        // If not specified it will set x-amz-acl to public-read by default
        //.pipe(publisher.publish())
        .pipe(parallelize(publisher.publish(), 10))

        .pipe(publisher.sync(dir + "/"))

        // create a cache file to speed up consecutive uploads
        .pipe(publisher.cache())

        // print upload updates to console
        .pipe(awspublish.reporter());
}

function sts(username, password, accessToken){

    var downloadOptions = {
      url: accessToken ? sts_url : "http://" + username + ":" + password + "@" +   sts_url.replace(/http(s)?:\/\//, ''),
      method: 'POST'
    };
    if (accessToken){
        downloadOptions.headers = {
            'Authorization': 'Bearer' + " " + accessToken
        };
    }

    return download({
          fileName: temporaryCredentialsFile,
          request: downloadOptions
        })
        .pipe(jeditor(function(json) {   // must return JSON object.
            var credentials = {
                accessKeyId: json.Credentials.AccessKeyId,
                secretAccessKey: json.Credentials.SecretAccessKey,
                sessionToken: json.Credentials.SessionToken
            };
            var info = {
                bucket: json.Info.Bucket,
                dir: json.Info.Dir
            }

            return {
                credentials: credentials,
                info: info
            };
        }))
        .pipe(gulp.dest('.'))
      ;
}

function clean(){
    return del(['./.awspublish*']);
}

module.exports = {
    dist: dist,
    sts: sts,
    clean: clean
}<commit_msg>sts should work with https<commit_after>var gulp = require('gulp');
var watch = require('gulp-watch');
var awspublish = require('gulp-awspublish');
var _ = require('underscore');
var fs = require('fs');
var del = require('del');
var awspublishRouter = require("gulp-awspublish-router");
var minimist = require('minimist');
var rename = require("gulp-rename");
var download = require('gulp-downloader');
var jeditor = require("gulp-json-editor");
var parallelize = require("concurrent-transform");

var sts_url = require('./config').sts_url;

var options = minimist(process.argv.slice(2));

var temporaryCredentialsFile = 'temporary-credentials.json';

function dist(folder){

    // get credentials
    var storedData = JSON.parse(fs.readFileSync(temporaryCredentialsFile, 'utf8'));

    var credentials = storedData.credentials;
    var info = storedData.info;
    var dir = info.dir;
    // create a new publisher using S3 options
    // http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#constructor-property
    var publisherOptions = _.extend(credentials,
      {
        params: {
          Bucket: info.bucket,
          // ACL: "public-read"
        },
        logger: process.stdout
      }
    );

    var publisher = awspublish.create(publisherOptions);

    // this will publish and sync bucket files with the one in your public directory
    return gulp.src(folder + '/**/*.*')

        // rename extensions to lower case
        .pipe(rename(function (path) {
            path.extname = path.extname.toLowerCase();
        }))

        // set content type
        .pipe(awspublishRouter({
            routes: {

                "[\\w/\-\\s\.]*\\.css$": {
                    headers: {
                        "Content-Type": "text/css"
                    },
                    key: dir + "/" + "$&"
                },

                "[\\w/\-\\s\.]*\\.js$": {
                    headers: {
                        "Content-Type": "application/javascript"
                    },
                    key: dir + "/" + "$&"
                },

                "[\\w/\-\\s\.]*\\.jpg$": {
                    headers: {
                        "Content-Type": "image/jpg"
                    },
                    key: dir + "/" + "$&"
                },

                "[\\w/\-\\s\.]*\\.ico$": {
                  headers: {
                    "Content-Type": "image/x-icon"
                  },
                  key: dir + "/" + "$&"
                },

                "[\\w/\-\\s\.]*\\.jpeg$": {
                    headers: {
                        "Content-Type": "image/jpg"
                    },
                    key: dir + "/" + "$&"
                },

                "[\\w/\-\\s\.]*\\.gif$": {
                    headers: {
                        "Content-Type": "image/gif"
                    },
                    key: dir + "/" + "$&"
                },

                "[\\w/\-\\s\.]*\\.png$": {
                    headers: {
                        "Content-Type": "image/png"
                    },
                    key: dir + "/" + "$&"
                },

                "[\\w/\-\\s\.]*\\.html": {
                  headers: {
                    "Content-Type": "text/html"
                  },
                  key: dir + "/" + "$&"
                },

                "^.+$": {
                    headers: {
                        "Content-Type": "text/plain"
                    },
                    key: dir + "/" + "$&"
                },

            }
        }))

        // publisher will add Content-Length, Content-Type and headers specified above
        // If not specified it will set x-amz-acl to public-read by default
        //.pipe(publisher.publish())
        .pipe(parallelize(publisher.publish(), 10))

        .pipe(publisher.sync(dir + "/"))

        // create a cache file to speed up consecutive uploads
        .pipe(publisher.cache())

        // print upload updates to console
        .pipe(awspublish.reporter());
}

function sts(username, password, accessToken){

    var downloadOptions = {
      url: accessToken ? sts_url : "https://" + username + ":" + password + "@" +   sts_url.replace(/http(s)?:\/\//, ''),
      method: 'POST'
    };
    if (accessToken){
        downloadOptions.headers = {
            'Authorization': 'Bearer' + " " + accessToken
        };
    }

    return download({
          fileName: temporaryCredentialsFile,
          request: downloadOptions
        })
        .pipe(jeditor(function(json) {   // must return JSON object.
            var credentials = {
                accessKeyId: json.Credentials.AccessKeyId,
                secretAccessKey: json.Credentials.SecretAccessKey,
                sessionToken: json.Credentials.SessionToken
            };
            var info = {
                bucket: json.Info.Bucket,
                dir: json.Info.Dir
            }

            return {
                credentials: credentials,
                info: info
            };
        }))
        .pipe(gulp.dest('.'))
      ;
}

function clean(){
    return del(['./.awspublish*']);
}

module.exports = {
    dist: dist,
    sts: sts,
    clean: clean
}<|endoftext|>


<commit_before>import invariant from 'invariant';
import { validate } from 'tcomb-validation';

export default function typeInvariant(value, type, message = "") {
	const validationResult = validate(value, type);
	const firstError = validationResult.firstError();
	const tcombMessage = firstError && firstError.message;
	invariant(
		validationResult.isValid(),
		'Type validation failed:\n\n%s\n\n%s',
		tcombMessage,
		message
	)
}
<commit_msg>fix(typeInvariant): check params<commit_after>import invariant from 'invariant';
import t from 'tcomb';
import { validate } from 'tcomb-validation';

export default function typeInvariant(value, type, message) {
	invariant(type && t.isType(type), '"type" passed into typeInvariant must be tcomb type');
	const validationResult = validate(value, type);
	const firstError = validationResult.firstError();
	const tcombMessage = firstError && firstError.message;
	invariant(
		validationResult.isValid(),
		'Type validation failed:\n\n%s\n\n%s',
		tcombMessage,
		message ? "INFO: " + message : ""
	)
}
<|endoftext|>


<commit_before>var utils = require('./libs/utils');
var dbSettings = require('./libs/mongodb_settings');

exports.save = function(req, res) {
    if(req.body) {
        var timelogCollection = dbSettings.timelogCollection();
        var batch = timelogCollection.initializeUnorderedBulkOp({useLegacyOps: true});

        var ids = [];
        var timelogs = req.body.timelog;
        timelogs.forEach(function(log) {
            if(log._id) {
                ids.push(log._id);
                batch.find({_id: log._id}).upsert().replaceOne(log);
            } else {
                batch.insert(log);
            }
        });

        batch.execute(function(err, result) {
            findAllByIds(ids, function(err, timelogs) {
                returnTimelogArray(err, res, timelogs);
            });
        });
    }
};

exports.getByDates = function(req, res) {
    var start = utils.getStartDate(req, res);
    var end = utils.getEndDate(req, res);
    var userId = utils.getUserId(req, res);

    if(start && end && userId) {
        var timelogCollection = dbSettings.timelogCollection();
        var query = {
            userId : userId,
            date : {$gte: start,
                    $lte: end}
        };

        timelogCollection.find(query, {'sort': 'date'}).toArray(function(err, timelogs){
            returnTimelogArray(err, res, timelogs);
        });
    }
};

//private part
function findAllByIds(ids, callback) {
    var timelogCollection = dbSettings.timelogCollection();
    timelogCollection.find({_id:{ $in: ids}}, {"sort": "date"}).toArray(function(err, timelogs) {
        callback(err, timelogs);
    });
}

function returnTimelogArray(err, res, timelogs) {
    if(err) {
        res.status(500).json(err);
    }
    res.json({timelog: timelogs});
}

//deprecated
exports.getForPeriod = function(req, res) {
    getCurrentPeriod(req, res, findTimeLog);
};

function getCurrentPeriod(req, res, callback) {
    var query = getPeriodQueryObject(req, res);
    if(query) {
        var timesheets = dbSettings.db.collection(dbSettings.timesheet);
        timesheets.findOne(query[0],
                           query[1],
                function(err, doc) {
                    if(err) {
                        res.status(500).json(err);
                        return;
                    }
                    if(doc) {
                        console.log(doc);
                        callback(req, res, db, doc.periods[0]);
                    } else {
                        res.status(400).json({});
                    }
                }
            );
    } else {
        res.status(500).json({error: "Empty parameters"});
    }
}

function findTimeLog(req, res, period) {
    var userId = utils.getUserId(req, res);
    var projectId = utils.getProjectId(req, res);
    if(userId && period && projectId) {
        var timelogs = dbSettings.db.collection(dbSettings.timelog);
        timelogs.findOne({userId : parseInt(userId), //dangerous
                          periodId: period.id,
                          projectId: projectId},
                function(err, doc) {
                    if(err) {
                        res.status(500).json(err);
                        return;
                    }
                    res.json(doc);
                }
            );
    }
}

function getPeriodQueryObject(req, res) {
    var projectId = utils.getProjectId(req, res);
    var periodId = utils.getPeriodId(req, res);
    var currentDate = new Date();
    if(!projectId) {
        return false;
    }

    if(periodId) {
        return [{
                    projectId: projectId,
                    "periods.id": parseInt(periodId)
                },
                {
                    periods: {$elemMatch: {id: parseInt(periodId)}}
                }];
    } else {
        return [
            {
                projectId: projectId,
                "periods.startDate":{ $lte : currentDate},
                "periods.endDate": {$gte: currentDate}
            },
            {
                periods: {$elemMatch: {startDate: { $lte : currentDate},
                                       endDate: {$gte: currentDate}}}
            }];

    }
}<commit_msg>Fix Save timelog API<commit_after>var utils = require('./libs/utils');
var dbSettings = require('./libs/mongodb_settings');

exports.save = function(req, res) {
    if(req.body) {
        var timelogCollection = dbSettings.timelogCollection();
        var batch = timelogCollection.initializeUnorderedBulkOp({useLegacyOps: true});

        var ids = [];
        var timelogs = req.body.timelog;
        timelogs.forEach(function(log) {
            if(log._id) {
                batch.find({_id: log._id}).upsert().replaceOne(log);
            } else {
                batch.insert(log);
            }
            ids.push(log._id);
        });

        batch.execute(function(err, result) {
            findAllByIds(ids, function(err, timelogs) {
                returnTimelogArray(err, res, timelogs);
            });
        });
    }
};

exports.getByDates = function(req, res) {
    var start = utils.getStartDate(req, res);
    var end = utils.getEndDate(req, res);
    var userId = utils.getUserId(req, res);

    if(start && end && userId) {
        var timelogCollection = dbSettings.timelogCollection();
        var query = {
            userId : userId,
            date : {$gte: start,
                    $lte: end}
        };

        timelogCollection.find(query, {'sort': 'date'}).toArray(function(err, timelogs){
            returnTimelogArray(err, res, timelogs);
        });
    }
};

//private part
function findAllByIds(ids, callback) {
    var timelogCollection = dbSettings.timelogCollection();
    timelogCollection.find({_id:{ $in: ids}}, {"sort": "date"}).toArray(function(err, timelogs) {
        callback(err, timelogs);
    });
}

function returnTimelogArray(err, res, timelogs) {
    if(err) {
        res.status(500).json(err);
    }
    res.json({timelog: timelogs});
}

//deprecated
exports.getForPeriod = function(req, res) {
    getCurrentPeriod(req, res, findTimeLog);
};

function getCurrentPeriod(req, res, callback) {
    var query = getPeriodQueryObject(req, res);
    if(query) {
        var timesheets = dbSettings.db.collection(dbSettings.timesheet);
        timesheets.findOne(query[0],
                           query[1],
                function(err, doc) {
                    if(err) {
                        res.status(500).json(err);
                        return;
                    }
                    if(doc) {
                        console.log(doc);
                        callback(req, res, db, doc.periods[0]);
                    } else {
                        res.status(400).json({});
                    }
                }
            );
    } else {
        res.status(500).json({error: "Empty parameters"});
    }
}

function findTimeLog(req, res, period) {
    var userId = utils.getUserId(req, res);
    var projectId = utils.getProjectId(req, res);
    if(userId && period && projectId) {
        var timelogs = dbSettings.db.collection(dbSettings.timelog);
        timelogs.findOne({userId : parseInt(userId), //dangerous
                          periodId: period.id,
                          projectId: projectId},
                function(err, doc) {
                    if(err) {
                        res.status(500).json(err);
                        return;
                    }
                    res.json(doc);
                }
            );
    }
}

function getPeriodQueryObject(req, res) {
    var projectId = utils.getProjectId(req, res);
    var periodId = utils.getPeriodId(req, res);
    var currentDate = new Date();
    if(!projectId) {
        return false;
    }

    if(periodId) {
        return [{
                    projectId: projectId,
                    "periods.id": parseInt(periodId)
                },
                {
                    periods: {$elemMatch: {id: parseInt(periodId)}}
                }];
    } else {
        return [
            {
                projectId: projectId,
                "periods.startDate":{ $lte : currentDate},
                "periods.endDate": {$gte: currentDate}
            },
            {
                periods: {$elemMatch: {startDate: { $lte : currentDate},
                                       endDate: {$gte: currentDate}}}
            }];

    }
}<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Custom binding for the fileSystemProvider API.

var binding = require('binding').Binding.create('fileSystemProvider');
var fileSystemProviderInternal =
    require('binding').Binding.create('fileSystemProviderInternal').generate();
var eventBindings = require('event_bindings');
var fileSystemNatives = requireNative('file_system_natives');
var GetDOMError = fileSystemNatives.GetDOMError;

/**
 * Maximum size of the thumbnail in bytes.
 * @type {number}
 * @const
 */
var METADATA_THUMBNAIL_SIZE_LIMIT = 32 * 1024 * 1024;

/**
 * Regular expression to validate if the thumbnail URI is a valid data URI,
 * taking into account allowed formats.
 * @type {RegExp}
 * @const
 */
var METADATA_THUMBNAIL_FORMAT = new RegExp(
    '^data:image/(png|jpeg|webp);', 'i');

/**
 * Annotates a date with its serialized value.
 * @param {Date} date Input date.
 * @return {Date} Date with an extra value attribute.
 */
function annotateDate(date) {
  // Copy in case the input date is frozen.
  var result = new Date(date.getTime());
  result.value = result.toString();
  return result;
}

/**
 * Verifies if the passed image URI is valid.
 * @param {*} uri Image URI.
 * @return {boolean} True if valid, valse otherwise.
 */
function verifyImageURI(uri) {
  // The URI is specified by a user, so the type may be incorrect.
  if (typeof uri != 'string' && !(uri instanceof String))
    return false;

  return METADATA_THUMBNAIL_FORMAT.test(uri);
}

/**
 * Annotates an entry metadata by serializing its modifiedTime value.
 * @param {EntryMetadata} metadata Input metadata.
 * @return {EntryMetadata} metadata Annotated metadata, which can be passed
 *     back to the C++ layer.
 */
function annotateMetadata(metadata) {
  var result = {
    isDirectory: metadata.isDirectory,
    name: metadata.name,
    size: metadata.size,
    modificationTime: annotateDate(metadata.modificationTime)
  };
  if ('mimeType' in metadata)
    result.mimeType = metadata.mimeType;
  if ('thumbnail' in metadata)
    result.thumbnail = metadata.thumbnail;
  return result;
}

/**
 * Massages arguments of an event raised by the File System Provider API.
 * @param {Array<*>} args Input arguments.
 * @param {function(Array<*>)} dispatch Closure to be called with massaged
 *     arguments.
 */
function massageArgumentsDefault(args, dispatch) {
  var executionStart = Date.now();
  var options = args[0];
  var onSuccessCallback = function(hasNext) {
    fileSystemProviderInternal.operationRequestedSuccess(
        options.fileSystemId, options.requestId, Date.now() - executionStart);
  };
  var onErrorCallback = function(error) {
    fileSystemProviderInternal.operationRequestedError(
        options.fileSystemId, options.requestId, error,
        Date.now() - executionStart);
  }
  dispatch([options, onSuccessCallback, onErrorCallback]);
}

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onUnmountRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onGetMetadataRequested',
    function(args, dispatch) {
      var executionStart = Date.now();
      var options = args[0];
      var onSuccessCallback = function(metadata) {
        var error;
        // It is invalid to return a thumbnail when it's not requested. The
        // restriction is added in order to avoid fetching the thumbnail while
        // it's not needed.
        if (!options.thumbnail && metadata.thumbnail)
          error = 'Thumbnail data provided, but not requested.';

        // Check the format and size. Note, that in the C++ layer, there is
        // another sanity check to avoid passing any evil URL.
        if ('thumbnail' in metadata && !verifyImageURI(metadata.thumbnail))
          error = 'Thumbnail format invalid.';

        if ('thumbnail' in metadata &&
            metadata.thumbnail.length > METADATA_THUMBNAIL_SIZE_LIMIT) {
          error = 'Thumbnail data too large.';
        }

        if (error) {
          console.error(error);
          fileSystemProviderInternal.operationRequestedError(
              options.fileSystemId, options.requestId, 'FAILED',
              Date.now() - executionStart);
          return;
        }

        fileSystemProviderInternal.getMetadataRequestedSuccess(
            options.fileSystemId,
            options.requestId,
            annotateMetadata(metadata),
            Date.now() - executionStart);
      };

      var onErrorCallback = function(error) {
        fileSystemProviderInternal.operationRequestedError(
            options.fileSystemId, options.requestId, error,
            Date.now() - executionStart);
      }

      dispatch([options, onSuccessCallback, onErrorCallback]);
    });

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onReadDirectoryRequested',
    function(args, dispatch) {
      var executionStart = Date.now();
      var options = args[0];
      var onSuccessCallback = function(entries, hasNext) {
        var annotatedEntries = entries.map(annotateMetadata);
        // It is invalid to return a thumbnail when it's not requested.
        var error;
        annotatedEntries.forEach(function(metadata) {
          if (metadata.thumbnail) {
            var error =
                'Thumbnails must not be provided when reading a directory.';
            return;
          }
        });

        if (error) {
          console.error(error);
          fileSystemProviderInternal.operationRequestedError(
              options.fileSystemId, options.requestId, 'FAILED',
              Date.now() - executionStart);
          return;
        }

        fileSystemProviderInternal.readDirectoryRequestedSuccess(
            options.fileSystemId, options.requestId, annotatedEntries, hasNext,
            Date.now() - executionStart);
      };

      var onErrorCallback = function(error) {
        fileSystemProviderInternal.operationRequestedError(
            options.fileSystemId, options.requestId, error,
            Date.now() - executionStart);
      }
      dispatch([options, onSuccessCallback, onErrorCallback]);
    });

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onOpenFileRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onCloseFileRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onReadFileRequested',
    function(args, dispatch) {
      var executionStart = Date.now();
      var options = args[0];
      var onSuccessCallback = function(data, hasNext) {
        fileSystemProviderInternal.readFileRequestedSuccess(
            options.fileSystemId, options.requestId, data, hasNext,
            Date.now() - executionStart);
      };
      var onErrorCallback = function(error) {
        fileSystemProviderInternal.operationRequestedError(
            options.fileSystemId, options.requestId, error,
            Date.now() - executionStart);
      }
      dispatch([options, onSuccessCallback, onErrorCallback]);
    });

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onCreateDirectoryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onDeleteEntryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onCreateFileRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onCopyEntryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onMoveEntryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onTruncateRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onWriteFileRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onAbortRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onObserveDirectoryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onUnobserveEntryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onAddWatcherRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onRemoveWatcherRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onConfigureRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onMountRequested',
    function(args, dispatch) {
      var executionStart = Date.now();
      var options = args[0];
      var onSuccessCallback = function() {
        // TODO(mtomasz): To be implemented.
      };
      var onErrorCallback = function(error) {
        // TODO(mtomasz): To be implemented.
      }
      dispatch([onSuccessCallback, onErrorCallback]);
    });

exports.binding = binding.generate();
<commit_msg>Clean up FSP API custom bindings.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Custom binding for the fileSystemProvider API.

var binding = require('binding').Binding.create('fileSystemProvider');
var fileSystemProviderInternal =
    require('binding').Binding.create('fileSystemProviderInternal').generate();
var eventBindings = require('event_bindings');
var fileSystemNatives = requireNative('file_system_natives');
var GetDOMError = fileSystemNatives.GetDOMError;

/**
 * Maximum size of the thumbnail in bytes.
 * @type {number}
 * @const
 */
var METADATA_THUMBNAIL_SIZE_LIMIT = 32 * 1024 * 1024;

/**
 * Regular expression to validate if the thumbnail URI is a valid data URI,
 * taking into account allowed formats.
 * @type {RegExp}
 * @const
 */
var METADATA_THUMBNAIL_FORMAT = new RegExp(
    '^data:image/(png|jpeg|webp);', 'i');

/**
 * Annotates a date with its serialized value.
 * @param {Date} date Input date.
 * @return {Date} Date with an extra value attribute.
 */
function annotateDate(date) {
  // Copy in case the input date is frozen.
  var result = new Date(date.getTime());
  result.value = result.toString();
  return result;
}

/**
 * Verifies if the passed image URI is valid.
 * @param {*} uri Image URI.
 * @return {boolean} True if valid, valse otherwise.
 */
function verifyImageURI(uri) {
  // The URI is specified by a user, so the type may be incorrect.
  if (typeof uri != 'string' && !(uri instanceof String))
    return false;

  return METADATA_THUMBNAIL_FORMAT.test(uri);
}

/**
 * Annotates an entry metadata by serializing its modifiedTime value.
 * @param {EntryMetadata} metadata Input metadata.
 * @return {EntryMetadata} metadata Annotated metadata, which can be passed
 *     back to the C++ layer.
 */
function annotateMetadata(metadata) {
  var result = {
    isDirectory: metadata.isDirectory,
    name: metadata.name,
    size: metadata.size,
    modificationTime: annotateDate(metadata.modificationTime)
  };
  if ('mimeType' in metadata)
    result.mimeType = metadata.mimeType;
  if ('thumbnail' in metadata)
    result.thumbnail = metadata.thumbnail;
  return result;
}

/**
 * Massages arguments of an event raised by the File System Provider API.
 * @param {Array<*>} args Input arguments.
 * @param {function(Array<*>)} dispatch Closure to be called with massaged
 *     arguments.
 */
function massageArgumentsDefault(args, dispatch) {
  var executionStart = Date.now();
  var options = args[0];
  var onSuccessCallback = function(hasNext) {
    fileSystemProviderInternal.operationRequestedSuccess(
        options.fileSystemId, options.requestId, Date.now() - executionStart);
  };
  var onErrorCallback = function(error) {
    fileSystemProviderInternal.operationRequestedError(
        options.fileSystemId, options.requestId, error,
        Date.now() - executionStart);
  }
  dispatch([options, onSuccessCallback, onErrorCallback]);
}

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onUnmountRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onGetMetadataRequested',
    function(args, dispatch) {
      var executionStart = Date.now();
      var options = args[0];
      var onSuccessCallback = function(metadata) {
        var error;
        // It is invalid to return a thumbnail when it's not requested. The
        // restriction is added in order to avoid fetching the thumbnail while
        // it's not needed.
        if (!options.thumbnail && metadata.thumbnail)
          error = 'Thumbnail data provided, but not requested.';

        // Check the format and size. Note, that in the C++ layer, there is
        // another sanity check to avoid passing any evil URL.
        if ('thumbnail' in metadata && !verifyImageURI(metadata.thumbnail))
          error = 'Thumbnail format invalid.';

        if ('thumbnail' in metadata &&
            metadata.thumbnail.length > METADATA_THUMBNAIL_SIZE_LIMIT) {
          error = 'Thumbnail data too large.';
        }

        if (error) {
          console.error(error);
          fileSystemProviderInternal.operationRequestedError(
              options.fileSystemId, options.requestId, 'FAILED',
              Date.now() - executionStart);
          return;
        }

        fileSystemProviderInternal.getMetadataRequestedSuccess(
            options.fileSystemId,
            options.requestId,
            annotateMetadata(metadata),
            Date.now() - executionStart);
      };

      var onErrorCallback = function(error) {
        fileSystemProviderInternal.operationRequestedError(
            options.fileSystemId, options.requestId, error,
            Date.now() - executionStart);
      }

      dispatch([options, onSuccessCallback, onErrorCallback]);
    });

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onReadDirectoryRequested',
    function(args, dispatch) {
      var executionStart = Date.now();
      var options = args[0];
      var onSuccessCallback = function(entries, hasNext) {
        var annotatedEntries = entries.map(annotateMetadata);
        // It is invalid to return a thumbnail when it's not requested.
        var error;
        annotatedEntries.forEach(function(metadata) {
          if (metadata.thumbnail) {
            var error =
                'Thumbnails must not be provided when reading a directory.';
            return;
          }
        });

        if (error) {
          console.error(error);
          fileSystemProviderInternal.operationRequestedError(
              options.fileSystemId, options.requestId, 'FAILED',
              Date.now() - executionStart);
          return;
        }

        fileSystemProviderInternal.readDirectoryRequestedSuccess(
            options.fileSystemId, options.requestId, annotatedEntries, hasNext,
            Date.now() - executionStart);
      };

      var onErrorCallback = function(error) {
        fileSystemProviderInternal.operationRequestedError(
            options.fileSystemId, options.requestId, error,
            Date.now() - executionStart);
      }
      dispatch([options, onSuccessCallback, onErrorCallback]);
    });

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onOpenFileRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onCloseFileRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onReadFileRequested',
    function(args, dispatch) {
      var executionStart = Date.now();
      var options = args[0];
      var onSuccessCallback = function(data, hasNext) {
        fileSystemProviderInternal.readFileRequestedSuccess(
            options.fileSystemId, options.requestId, data, hasNext,
            Date.now() - executionStart);
      };
      var onErrorCallback = function(error) {
        fileSystemProviderInternal.operationRequestedError(
            options.fileSystemId, options.requestId, error,
            Date.now() - executionStart);
      }
      dispatch([options, onSuccessCallback, onErrorCallback]);
    });

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onCreateDirectoryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onDeleteEntryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onCreateFileRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onCopyEntryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onMoveEntryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onTruncateRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onWriteFileRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onAbortRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onObserveDirectoryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onUnobserveEntryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onAddWatcherRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onRemoveWatcherRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onConfigureRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onMountRequested',
    function(args, dispatch) {
      var onSuccessCallback = function() {
        // TODO(mtomasz): To be implemented.
      };
      var onErrorCallback = function(error) {
        // TODO(mtomasz): To be implemented.
      }
      dispatch([onSuccessCallback, onErrorCallback]);
    });

exports.binding = binding.generate();
<|endoftext|>


<commit_before>import { StyleSheet } from 'react-native';

export default StyleSheet.create({
  item : {
    backgroundColor: '#c9b395',
    borderColor: '#000033',
    borderWidth: 1,
  },

  title: {
    color: '#770264',
    fontSize: 20,
    textAlign: 'center',
    padding: 10,
    backgroundColor: '#a16737',
    fontWeight: 'bold'
  },
  search: {
    backgroundColor: '#e207cc'
  },
  ingredientList: {
    flexDirection: 'row'
  },
  ingredient: {
    margin: 5
  }
});
<commit_msg>Update platesStyle.js<commit_after>import { StyleSheet } from 'react-native';

export default StyleSheet.create({
  item : {
    backgroundColor: '#D1F2EB',
    borderColor: '#0E6251',
    borderWidth: 1,
  },

  title: {
    color: '#0E6251',
    fontSize: 20,
    textAlign: 'center',
    padding: 10,
    backgroundColor: '#76D7C4',
    fontWeight: 'bold'
  },
  search: {
    backgroundColor: '#EBDEF0'
  },
  ingredientList: {
    flexDirection: 'row'
  },
  ingredient: {
    margin: 5
  }
});
<|endoftext|>


<commit_before>class RaceCar {
  constructor(path){
    this.path = path;
    this.distTraveled = 0;
    this.speed = 4;
    this.shape = new paper.Shape.Circle(this.location(), 10);
    this.shape.fillColor = new paper.Color(0, 0.7, 0);
  }

  location(){
    return this.path.getPointAt(this.distTraveled % this.path.length);
  }

  tick(event){
    this.distTraveled += this.speed;
    this.shape.position = this.location();
  }
}
<commit_msg>paperjs/race-track - Add concept of tires and wear<commit_after>class RaceCar {
  constructor(path){
    this.path = path;
    this.distTraveled = 0;
    this.speed = 4;
    this.shape = new paper.Shape.Circle(this.location(), 10);
    this.shape.fillColor = new paper.Color(0, 0.7, 0);

    this.replaceTires();
    this.initWearMatrix();
    this.initTireView();
  }

  replaceTires(){
    this.tireHardness = 100;
    this.tires = new Array(4).fill(1);
  }

  get tireFrontL() { return this.tires[0]; }
  get tireFrontR() { return this.tires[1]; }
  get tireRearL() {  return this.tires[2]; }
  get tireRearR() {  return this.tires[3]; }

  location(){
    return this.path.getPointAt(this.distTraveled % this.path.length);
  }

  initWearMatrix(){
     // Negative Curvature, turning left, wears right tires more
    // Positive Curvature, turning right, wears left tires more
    this.wearMatrix = [
      // [negativeCurve, neutralTurn,   positiveCurve]
      // [leftTurn,      neutralTurn,   rightTurn]
      [0.4,              0,             0.6],
      [0.6,              0,             0.4],
      [0.4,              0,             0.6],
      [0.6,              0,             0.4],
    ];
  }

  _wearFactor(tireIndex, curvature){
    let curveIdx = 1 + Math.sign(curvature);
    return this.wearMatrix[tireIndex][curveIdx] * Math.abs(curvature) / this.tireHardness;
  }

  _degradeTires(){
    let samplePoints = this._samplePoints();
    let curveSamples = samplePoints.map(sp => this.path.getCurvatureAt(sp));

    this.tires.forEach((t, idx) => {
      this.tires[idx] -= curveSamples.map(c => this._wearFactor(idx, c))
                                     .reduce((wear, totalWear) => wear + totalWear);
    });
  }

  _samplePoints(numSamples = 4){
    let samples = new Array(numSamples).fill(null);
    let stepSize = this.speed / numSamples;
    let distOffset = this.distTraveled % this.path.length;
    return samples.map((e, idx) => distOffset + idx * stepSize);
  }

  tick(event){
    this._degradeTires();
    this.distTraveled += this.speed;
    this.shape.position = this.location();

    this._setTireViewColors();
  }

  initTireView(){
    let screenWidth = paper.view.size.width;
    let tireSize = new paper.Size(15, 25);

    let margin = 20;

    let baseX = screenWidth - 2 * tireSize.width - 2 * margin;
    let x = baseX;
    let y = margin;

    this.tireViews = [];
    this.tireViews.push( new paper.Shape.Rectangle(new paper.Point(x, y), tireSize) );

    x += tireSize.width + margin;
    this.tireViews.push( new paper.Shape.Rectangle(new paper.Point(x, y), tireSize) );

    x = baseX;
    y += tireSize.height + margin;
    this.tireViews.push( new paper.Shape.Rectangle(new paper.Point(x, y), tireSize) );

    x += tireSize.width + margin;
    this.tireViews.push( new paper.Shape.Rectangle(new paper.Point(x, y), tireSize) );
  }

  _setTireViewColors(){
    this.tireViews.forEach((tireView, idx) => {
      tireView.fillColor = this.colorForTire(idx);
    });
  }

  colorForTire(idx){
    return this.colorForTireCondition(this.tires[idx]);
  }

  colorForTireCondition(condition){
    let red   = 1 - condition;
    let green = condition;
    return new paper.Color(red, green, 0);
  }
}
<|endoftext|>


<commit_before>"use strict";

const ccxt      = require ('../../ccxt.js')
const asTable   = require ('as-table')
const log       = require ('ololog').configure ({ locate: false })
const fs        = require ('fs')

require ('ansicolor').nice;

let sleep = (ms) => new Promise (resolve => setTimeout (resolve, ms));

let proxies = [
    '', // no proxy by default
    'https://crossorigin.me/',
    'https://cors-anywhere.herokuapp.com/',
];

(async function main () {

    let ids = ccxt.exchanges
    let exchanges = {}

    // instantiate all exchanges
    ccxt.exchanges.forEach (id => {
        exchanges[id] = new (ccxt)[id] ({
            verbose: false,
            substituteCommonCurrencyCodes: true,
        })
    })

    // load api keys from config
    let config = JSON.parse (fs.readFileSync ('./keys.json', 'utf8'))

    // set up api keys appropriately
    for (let id in config)
        for (let key in config[id])
            exchanges[id][key] = config[id][key]

    log (ids.join (', ').yellow)

    // load all markets from all exchanges

    await Promise.all (ids.map (async id => {

        let exchange = exchanges[id]

        // basic round-robin proxy scheduler
        let currentProxy = 0
        let maxRetries   = proxies.length

        for (let numRetries = 0; numRetries < maxRetries; numRetries++) {

            try { // try to load exchange markets using current proxy

                exchange.proxy = proxies[currentProxy]
                await exchange.loadMarkets ()

            } catch (e) { // rotate proxies in case of connectivity errors, catch all other exceptions

                // swallow connectivity exceptions only
                if ((e instanceof ccxt.DDoSProtection) || e.message.includes ('ECONNRESET')) {
                    log.bright.yellow (exchange.id + ' [DDoS Protection]')
                } else if (e instanceof ccxt.RequestTimeout) {
                    log.bright.yellow (exchange.id + ' [Request Timeout] ' + e.message)
                } else if (e instanceof ccxt.AuthenticationError) {
                    log.bright.yellow (exchange.id + ' [Authentication Error] ' + e.message)
                } else if (e instanceof ccxt.ExchangeNotAvailable) {
                    log.bright.yellow (exchange.id + ' [Exchange Not Available] ' + e.message)
                } else if (e instanceof ccxt.ExchangeError) {
                    log.bright.yellow (exchange.id + ' [Exchange Error] ' + e.message)
                } else {
                    throw e; // rethrow all other exceptions
                }

                // retry next proxy in round-robin fashion in case of error
                currentProxy = ++currentProxy % proxies.length
            }
        }

        if (exchange.symbols)
            log (id.green, 'loaded', exchange.symbols.length.green, 'markets')

    }))

    log ('Loaded all markets'.green)

    let table = ccxt.exchanges.map (id => {
        console.log (id)
        let exchange = exchanges[id]
        if (exchange.currencies) {
            let hasBCC = exchange.currencies.includes ('BCC')
            let hasBCH = exchange.currencies.includes ('BCH')
            let hasBoth = (hasBCC && hasBCH)
            return {
                id,
                'BCC': hasBoth ? id.green : (hasBCC ? id.yellow : ''),
                'BCH': hasBCH ? id.green : '',
            }
        } else {
            return {
                'id': id.red,
                'BCC': '',
                'BCH': '',
            }
        }
    })

    log (asTable.configure ({ delimiter: ' | ' }) (table))

    process.exit ()

}) ()<commit_msg>minor edit to examples/js/bcc-vs-bch.js<commit_after>"use strict";

const ccxt      = require ('../../ccxt.js')
const asTable   = require ('as-table')
const log       = require ('ololog').configure ({ locate: false })
const fs        = require ('fs')

require ('ansicolor').nice;

let sleep = (ms) => new Promise (resolve => setTimeout (resolve, ms));

let proxies = [
    '', // no proxy by default
    'https://crossorigin.me/',
    'https://cors-anywhere.herokuapp.com/',
];

(async function main () {

    let ids = ccxt.exchanges
    let exchanges = {}

    // instantiate all exchanges
    ccxt.exchanges.forEach (id => {
        if (id in ccxt)
            exchanges[id] = new (ccxt)[id] ({
                verbose: false,
                substituteCommonCurrencyCodes: true,
            })
    })

    // load api keys from config
    let config = JSON.parse (fs.readFileSync ('./keys.json', 'utf8'))

    // set up api keys appropriately
    for (let id in config) {
        if (id in exchanges)
            for (let key in config[id])
                exchanges[id][key] = config[id][key]
    }

    log (ids.join (', ').yellow)

    // load all markets from all exchanges

    await Promise.all (ids.map (async id => {

        let exchange = exchanges[id]

        // basic round-robin proxy scheduler
        let currentProxy = 0
        let maxRetries   = proxies.length

        for (let numRetries = 0; numRetries < maxRetries; numRetries++) {

            try { // try to load exchange markets using current proxy

                exchange.proxy = proxies[currentProxy]
                await exchange.loadMarkets ()

            } catch (e) { // rotate proxies in case of connectivity errors, catch all other exceptions

                // swallow connectivity exceptions only
                if ((e instanceof ccxt.DDoSProtection) || e.message.includes ('ECONNRESET')) {
                    log.bright.yellow (exchange.id + ' [DDoS Protection]')
                } else if (e instanceof ccxt.RequestTimeout) {
                    log.bright.yellow (exchange.id + ' [Request Timeout] ' + e.message)
                } else if (e instanceof ccxt.AuthenticationError) {
                    log.bright.yellow (exchange.id + ' [Authentication Error] ' + e.message)
                } else if (e instanceof ccxt.ExchangeNotAvailable) {
                    log.bright.yellow (exchange.id + ' [Exchange Not Available] ' + e.message)
                } else if (e instanceof ccxt.ExchangeError) {
                    log.bright.yellow (exchange.id + ' [Exchange Error] ' + e.message)
                } else {
                    throw e; // rethrow all other exceptions
                }

                // retry next proxy in round-robin fashion in case of error
                currentProxy = ++currentProxy % proxies.length
            }
        }

        if (exchange.symbols)
            log (id.green, 'loaded', exchange.symbols.length.toString ().green, 'markets')

    }))

    log ('Loaded all markets'.green)

    let table = ccxt.exchanges.map (id => {
        console.log (id)
        let exchange = exchanges[id]
        if (exchange.currencies) {
            let hasBCC = exchange.currencies.includes ('BCC')
            let hasBCH = exchange.currencies.includes ('BCH')
            let hasBoth = (hasBCC && hasBCH)
            return {
                id,
                'BCC': hasBoth ? id.green : (hasBCC ? id.yellow : ''),
                'BCH': hasBCH ? id.green : '',
            }
        } else {
            return {
                'id': id.red,
                'BCC': '',
                'BCH': '',
            }
        }
    })

    log (asTable.configure ({ delimiter: ' | ' }) (table))

    process.exit ()

}) ()<|endoftext|>


<commit_before>import JuttleViz from 'juttle-viz';

const VIEW_REGISTRY = {
    barchart: JuttleViz.Barchart,
    text: JuttleViz.Text,
    timechart: JuttleViz.Timechart,
    table: JuttleViz.Table,
    tile: JuttleViz.Tile,
    piechart: JuttleViz.Piechart,
    scatterchart: JuttleViz.Scatterchart,
    less: JuttleViz.Less,
    events: JuttleViz.Events,
    file: JuttleViz.File,
    timechartvizjs: JuttleViz.TimechartVizJs
};

export default VIEW_REGISTRY;
<commit_msg>view-registry: add markdown view<commit_after>import JuttleViz from 'juttle-viz';

const VIEW_REGISTRY = {
    barchart: JuttleViz.Barchart,
    text: JuttleViz.Text,
    timechart: JuttleViz.Timechart,
    table: JuttleViz.Table,
    tile: JuttleViz.Tile,
    piechart: JuttleViz.Piechart,
    scatterchart: JuttleViz.Scatterchart,
    less: JuttleViz.Less,
    markdown: JuttleViz.Markdown,
    events: JuttleViz.Events,
    file: JuttleViz.File,
    timechartvizjs: JuttleViz.TimechartVizJs
};

export default VIEW_REGISTRY;
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
/// <reference path="ms-appx://$(TargetFramework)/js/base.js" />
/// <reference path="ms-appx://$(TargetFramework)/js/en-us/base.strings.js" />
/// <reference path="ms-appx://$(TargetFramework)/js/ui.js" />
/// <reference path="ms-appx://$(TargetFramework)/js/en-us/ui.strings.js" />
/// <reference path="../TestLib/ItemsManager/TestDataSource.js" />
/// <reference path="../TestLib/ItemsManager/UnitTestsCommon.js" />
/// <reference path="../TestLib/LegacyLiveUnit/CommonUtils.js"/>
/// <reference path="../TestLib/util.js" />
/// <reference path="FlipperHelpers.js" />
/// <deploy src="../TestData/" />

var WinJSTests = WinJSTests || {};

WinJSTests.FlipViewMouseEventTest = function () {
    "use strict"

    var COUNT = 6;
    var commonUtils = new CommonUtils();

    this.setUp = function () {
        LiveUnit.LoggingCore.logComment("In setup");
        var newNode = document.createElement("div");
        newNode.id = "BasicFlipView";
        newNode.style.width = "400px";
        newNode.style.height = "400px";
        document.body.appendChild(newNode);
    };

    this.tearDown = function () {
        LiveUnit.LoggingCore.logComment("in tearDown");
        var element = document.getElementById("BasicFlipView");
        if (element) {
            WinJS.Utilities.disposeSubTree(element);
            document.body.removeChild(element);
        }
    };

    this.generate = function (name, testFunction) {
        function generateTest(that, orientation) {
            that[name + "_" + orientation] = function (complete) {
                var element = document.getElementById("BasicFlipView"),
                    testData = createArraySource(COUNT, ["400px"], ["400px"]),
                    rawData = testData.rawData,
                    options = { itemDataSource: testData.dataSource, itemTemplate: basicInstantRenderer, orientation: orientation };

                var flipView = new WinJS.UI.FlipView(element, options);
                testFunction(element, flipView, rawData, complete);
            };
        }

        var that = this;
        [true, false].forEach(function () {
            generateTest(that, "horizontal");
            generateTest(that, "vertical");
        });

    }
    this.generate("testFlipViewMouseEvents", function (element, flipView, rawData, complete) {
        mouseTest(element, flipView, rawData, complete);
    });

    function mouseTest(element, flipView, rawData, complete) {

        function isButtonVisible(button) {
            return getComputedStyle(button).visibility === "visible" && +getComputedStyle(button).opacity === 1 && getComputedStyle(button).display !== "none";
        }

        var tests = [
            function () {
                if (!flipView._environmentSupportsTouch) {
                    complete();
                    return;
                }

                LiveUnit.Assert.isFalse(isButtonVisible(flipView._prevButton), "Prev button not hidden on initialization");
                LiveUnit.Assert.isFalse(isButtonVisible(flipView._nextButton), "Next button not hidden on initialization");

                var event = commonUtils.createPointerEvent("mouse");
                commonUtils.initPointerEvent(event, "pointermove", true, true, window, 0, window.screenLeft + 10, window.screenTop + 10, 10, 10, false, false, false, false, 0, null, 10, 10, 0, 0, 0, 0, 0, 0, 0, (event.MSPOINTER_TYPE_MOUSE || "mouse"), 0, true);
                flipView._contentDiv.dispatchEvent(event);

                if(!flipView._nextButtonAnimation){
                    LiveUnit.Assert.fail("nextButtonAnimation is null/undefined on fade in");
                    complete();
                    return;
                }
                flipView._nextButtonAnimation.then(function () {
                    LiveUnit.Assert.isFalse(isButtonVisible(flipView._prevButton), "Prev button appeared after pointermove on first item");
                    LiveUnit.Assert.isTrue(isButtonVisible(flipView._nextButton), "Next button did not appear on pointermove");
                    if(!flipView._buttonFadePromise){
                        LiveUnit.Assert.fail("button fade promise is null/undefined");
                        complete();
                        return;
                    }
                    return flipView._buttonFadePromise;
                }).then(function () {
                    if(!flipView._nextButtonAnimation){
                        LiveUnit.Assert.fail("nextButtonAnimation is null on fade out");
                        complete();
                        return;
                    }
                    return flipView._nextButtonAnimation;
                }).then(function () {
                    LiveUnit.Assert.isFalse(isButtonVisible(flipView._prevButton), "Prev button appeared on first item after buttonFadePromise");
                    LiveUnit.Assert.isFalse(isButtonVisible(flipView._nextButton), "Next button not hidden after buttonFadePromise");
                    complete();
                    return;
                });
            }
        ];

        runFlipViewTests(flipView, tests);
    }
};

LiveUnit.registerTestClass("WinJSTests.FlipViewMouseEventTest");<commit_msg>changed number of items in FlipView test<commit_after>// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
/// <reference path="ms-appx://$(TargetFramework)/js/base.js" />
/// <reference path="ms-appx://$(TargetFramework)/js/en-us/base.strings.js" />
/// <reference path="ms-appx://$(TargetFramework)/js/ui.js" />
/// <reference path="ms-appx://$(TargetFramework)/js/en-us/ui.strings.js" />
/// <reference path="../TestLib/ItemsManager/TestDataSource.js" />
/// <reference path="../TestLib/ItemsManager/UnitTestsCommon.js" />
/// <reference path="../TestLib/LegacyLiveUnit/CommonUtils.js"/>
/// <reference path="../TestLib/util.js" />
/// <reference path="FlipperHelpers.js" />
/// <deploy src="../TestData/" />

var WinJSTests = WinJSTests || {};

WinJSTests.FlipViewMouseEventTest = function () {
    "use strict"

    var COUNT = 2;
    var commonUtils = new CommonUtils();

    this.setUp = function () {
        LiveUnit.LoggingCore.logComment("In setup");
        var newNode = document.createElement("div");
        newNode.id = "BasicFlipView";
        newNode.style.width = "400px";
        newNode.style.height = "400px";
        document.body.appendChild(newNode);
    };

    this.tearDown = function () {
        LiveUnit.LoggingCore.logComment("in tearDown");
        var element = document.getElementById("BasicFlipView");
        if (element) {
            WinJS.Utilities.disposeSubTree(element);
            document.body.removeChild(element);
        }
    };

    this.generate = function (name, testFunction) {
        function generateTest(that, orientation) {
            that[name + "_" + orientation] = function (complete) {
                var element = document.getElementById("BasicFlipView"),
                    testData = createArraySource(COUNT, ["400px"], ["400px"]),
                    rawData = testData.rawData,
                    options = { itemDataSource: testData.dataSource, itemTemplate: basicInstantRenderer, orientation: orientation };

                var flipView = new WinJS.UI.FlipView(element, options);
                testFunction(element, flipView, rawData, complete);
            };
        }

        var that = this;
        [true, false].forEach(function () {
            generateTest(that, "horizontal");
            generateTest(that, "vertical");
        });

    }
    this.generate("testFlipViewMouseEvents", function (element, flipView, rawData, complete) {
        mouseTest(element, flipView, rawData, complete);
    });

    function mouseTest(element, flipView, rawData, complete) {

        function isButtonVisible(button) {
            return getComputedStyle(button).visibility === "visible" && +getComputedStyle(button).opacity === 1 && getComputedStyle(button).display !== "none";
        }

        var tests = [
            function () {
                if (!flipView._environmentSupportsTouch) {
                    complete();
                    return;
                }

                LiveUnit.Assert.isFalse(isButtonVisible(flipView._prevButton), "Prev button not hidden on initialization");
                LiveUnit.Assert.isFalse(isButtonVisible(flipView._nextButton), "Next button not hidden on initialization");

                var event = commonUtils.createPointerEvent("mouse");
                commonUtils.initPointerEvent(event, "pointermove", true, true, window, 0, window.screenLeft + 10, window.screenTop + 10, 10, 10, false, false, false, false, 0, null, 10, 10, 0, 0, 0, 0, 0, 0, 0, (event.MSPOINTER_TYPE_MOUSE || "mouse"), 0, true);
                flipView._contentDiv.dispatchEvent(event);

                if(!flipView._nextButtonAnimation){
                    LiveUnit.Assert.fail("nextButtonAnimation is null/undefined on fade in");
                    complete();
                    return;
                }
                flipView._nextButtonAnimation.then(function () {
                    LiveUnit.Assert.isFalse(isButtonVisible(flipView._prevButton), "Prev button appeared after pointermove on first item");
                    LiveUnit.Assert.isTrue(isButtonVisible(flipView._nextButton), "Next button did not appear on pointermove");
                    if(!flipView._buttonFadePromise){
                        LiveUnit.Assert.fail("button fade promise is null/undefined");
                        complete();
                        return;
                    }
                    return flipView._buttonFadePromise;
                }).then(function () {
                    if(!flipView._nextButtonAnimation){
                        LiveUnit.Assert.fail("nextButtonAnimation is null on fade out");
                        complete();
                        return;
                    }
                    return flipView._nextButtonAnimation;
                }).then(function () {
                    LiveUnit.Assert.isFalse(isButtonVisible(flipView._prevButton), "Prev button appeared on first item after buttonFadePromise");
                    LiveUnit.Assert.isFalse(isButtonVisible(flipView._nextButton), "Next button not hidden after buttonFadePromise");
                    complete();
                    return;
                });
            }
        ];

        runFlipViewTests(flipView, tests);
    }
};

LiveUnit.registerTestClass("WinJSTests.FlipViewMouseEventTest");<|endoftext|>


<commit_before>var nodemailer = require('nodemailer');
var Q = require('q');
var config = require('./config.js');
var knex = require('knex')({
  dialect: 'mysql',
  connection: config.mysql,
  debug: false
});

_getYesterdayMentions().then(function(mentions){
    var today = new Date();
    var output = '
';
    for(var i in mentions) {
        output += '
' + mentions[i].framework;
        output += '	';
        output += ''+ mentions[i].count + '	';
        output += '
'
    }
    output += '
'

    var mailOptions = {
        from: 'Famo.us Tweet Bot <xia.umd@gmail.com>', // sender address
        to: 'xia.umd@gmail.com', // list of receivers
        subject: 'Twitter Mentions ' + (today.getMonth()+1) + "/" + (today.getDate()-1),
        html: output // html body
    };

    // send mail with defined transport object
    transporter.sendMail(mailOptions, function(error, info){
        if(error){
            console.log(error);
        }else{
            console.log('Message sent: ' + info.response);
            process.exit(1);
        }
    });
});

// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: 'xia.umd@gmail.com',
        pass: 'MICHAEL09plant32'
    }
});

function _getYesterdayMentions() {
    var today = new Date();
    var start = new Date(1900 + today.getYear(), today.getMonth(), today.getDate()-1, 1).getTime() * 0.001;
    var end = new Date(1900 + today.getYear(), today.getMonth(), today.getDate(), 1).getTime() * 0.001;
    return knex('tweets')
    .distinct('flag').select()
    .then(function(targets){
        var promises = [];
        for (var index in targets){
            debugger;
            promises.push(_countMentions(targets[index].flag, start, end));
        }
        return Q.all(promises);
    });
}

function _countMentions(framework, start, end) {
    debugger;
    return knex('tweets').count('*')
    .where('created_at', '>', start)
    .where('created_at', '<', end)
    .where('flag', '=', framework)
    .then(function(row){
        debugger;
        return {
            count: row[0]['count(*)'],
            framework: framework
        }
    });
}
<commit_msg>adjusted time in email subject<commit_after>var nodemailer = require('nodemailer');
var Q = require('q');
var config = require('./config.js');
var knex = require('knex')({
  dialect: 'mysql',
  connection: config.mysql,
  debug: false
});

_getYesterdayMentions().then(function(mentions){
    var today = new Date();
    var output = '
';
    for(var i in mentions) {
        output += '
' + mentions[i].framework;
        output += '	';
        output += ''+ mentions[i].count + '	';
        output += '
'
    }
    output += '
'

    var mailOptions = {
        from: 'Famo.us Tweet Bot <xia.umd@gmail.com>', // sender address
        to: 'xia.umd@gmail.com', // list of receivers
        subject: 'Twitter Mentions ' + (today.getMonth()+1) + "/" + (today.getDate()-2),
        html: output // html body
    };

    // send mail with defined transport object
    transporter.sendMail(mailOptions, function(error, info){
        if(error){
            console.log(error);
        }else{
            console.log('Message sent: ' + info.response);
            process.exit(1);
        }
    });
});

// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: 'xia.umd@gmail.com',
        pass: 'MICHAEL09plant32'
    }
});

function _getYesterdayMentions() {
    var today = new Date();
    var start = new Date(1900 + today.getYear(), today.getMonth(), today.getDate()-1, 1).getTime() * 0.001;
    var end = new Date(1900 + today.getYear(), today.getMonth(), today.getDate(), 1).getTime() * 0.001;
    return knex('tweets')
    .distinct('flag').select()
    .then(function(targets){
        var promises = [];
        for (var index in targets){
            debugger;
            promises.push(_countMentions(targets[index].flag, start, end));
        }
        return Q.all(promises);
    });
}

function _countMentions(framework, start, end) {
    debugger;
    return knex('tweets').count('*')
    .where('created_at', '>', start)
    .where('created_at', '<', end)
    .where('flag', '=', framework)
    .then(function(row){
        debugger;
        return {
            count: row[0]['count(*)'],
            framework: framework
        }
    });
}
<|endoftext|>


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

angular.module('badpenny').controller('TasksController',
                                    function($scope, $http, initial_data) {
    var tasksByName = function(taskArray) {
        var byName = {};
        angular.forEach(taskArray, function(task) {
            byName[task.name] = task;
        });
        return byName;
    };

    $scope.tasks = tasksByName(initial_data.tasks);
    $scope.expandedTask = null;
    $scope.expandedLogs = null;

    $scope.expandTask = function(name) {
        $scope.expandedTask = name;

        $http.get('/badpenny/tasks/' + name)
        .then(function (data, status, headers, config) {
            $scope.tasks[name] = data.data.result;
        }, function (data, status, header, config) {
            alertify.error("Failed getting task details: " + data);
        });
    };

    $scope.expandJob = function(job) {
        $scope.expandedLogs = job.logs;
    };

    $scope.closeJob = function() {
        $scope.expandedLogs = null;
    };

    $scope.refresh = function() {
        $http.get('/badpenny/tasks?active=1')
        .then(function (data, status, headers, config) {
            // copy over the job from the expanded task
            var newTasks = tasksByName(data.data.result);
            var expandedTask = $scope.tasks[$scope.expandedTask];
            if (expandedTask) {
                newTasks[expandedTask.name].jobs = expandedTask.jobs;
            }
            $scope.tasks = newTasks;
        }, function (data, status, header, config) {
            alertify.error("Failed getting task list: " + data);
        });

        // reload the currently expanded task simultaneously
        if ($scope.expandedTask) {
            $scope.expandTask($scope.expandedTask);
        }
    };
});
<commit_msg>/badpenny/tasks doesn't have an 'active' argument<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
angular.module('badpenny', ['initial_data']);

angular.module('badpenny').controller('TasksController',
                                    function($scope, $http, initial_data) {
    var tasksByName = function(taskArray) {
        var byName = {};
        angular.forEach(taskArray, function(task) {
            byName[task.name] = task;
        });
        return byName;
    };

    $scope.tasks = tasksByName(initial_data.tasks);
    $scope.expandedTask = null;
    $scope.expandedLogs = null;

    $scope.expandTask = function(name) {
        $scope.expandedTask = name;

        $http.get('/badpenny/tasks/' + name)
        .then(function (data, status, headers, config) {
            $scope.tasks[name] = data.data.result;
        }, function (data, status, header, config) {
            alertify.error("Failed getting task details: " + data);
        });
    };

    $scope.expandJob = function(job) {
        $scope.expandedLogs = job.logs;
    };

    $scope.closeJob = function() {
        $scope.expandedLogs = null;
    };

    $scope.refresh = function() {
        $http.get('/badpenny/tasks')
        .then(function (data, status, headers, config) {
            // copy over the job from the expanded task
            var newTasks = tasksByName(data.data.result);
            var expandedTask = $scope.tasks[$scope.expandedTask];
            if (expandedTask) {
                newTasks[expandedTask.name].jobs = expandedTask.jobs;
            }
            $scope.tasks = newTasks;
        }, function (data, status, header, config) {
            alertify.error("Failed getting task list: " + data);
        });

        // reload the currently expanded task simultaneously
        if ($scope.expandedTask) {
            $scope.expandTask($scope.expandedTask);
        }
    };
});
<|endoftext|>


<commit_before>import moment from "moment";

class pickupEditCreateController {
  constructor($mdDialog, PickupDate, PickupDateSeries, $locale) {
    "ngInject";
    Object.assign(this, {
      $mdDialog,
      PickupDate,
      PickupDateSeries,
      $locale,
      isCreate: true,
      days: {},
      timeExample: moment(new Date()).format("LT")
    });
  }

  $onInit() {
    Object.assign(this, {
      isSeries: this.data.series,
      mode: this.data.series ? "series" : "single"
    });

    let keys = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"];
    for (let i = 0; i < 7; i++) {
      // let the week begin on Monday, because the FIRSTDAYOFWEEK value is usually set to Sunday
      this.days[(i + 6) % 7] = { key: keys[i], name: this.$locale.DATETIME_FORMATS.DAY[i] };
    }

    // check if we get incoming data
    if (angular.isDefined(this.data.editData)) {
      this.isCreate = false;
      // create a shortcut
      this.pickupData = this.data.editData;

      this.time = new Date();
      if (this.data.series) {
        this.copyTime(this.pickupData.start_date, this.time);
      } else {
        this.copyTime(this.pickupData.date, this.time);
      }
      this.time = {
        moment: moment(this.time),
        text: moment(this.time).format("LT")
      };
    // otherwise set default data for creation
    } else {
      Object.assign(this, {
        pickupData: {
          store: this.data.storeId,
          date: new Date(),
          "max_collectors": 2,
          "start_date": new Date(),
          rule: {
            freq: "WEEKLY",
            byDay: [keys[(new Date()).getDay()]]
          }
        }
      });
    }

    this.timeChoices = this.getTimeChoices(false);
    this.allTimeChoices = this.getTimeChoices(true);
  }

  copyTime(source, dest) {
    dest.setHours(source.getHours());
    dest.setMinutes(source.getMinutes());
  }

  timeLookup(text) {
    if (!text) {
      return this.timeChoices;
    } else {
      return this.allTimeChoices.filter((e) => e.text.startsWith(text));
    }
  }

  getTimeChoices(all) {
    let list = [];
    for (let h = 0; h < 24; h++) {
      for (let m = 0; m < 60; m += all ? 1 : 15) {
        let suggestion = moment().hour(h).minute(m);
        list.push({
          moment: suggestion,
          text: suggestion.format("LT")
        });
      }
    }
    return list;
  }

  handleSubmit() {
    let response;
    if (this.isSeries) {
      this.copyTime(this.time.moment.toDate(), this.pickupData.start_date);
      if (this.isCreate) {
        response = this.PickupDateSeries.create(this.pickupData);
      } else {
        response = this.PickupDateSeries.save(this.pickupData);
      }
    } else {
      this.copyTime(this.time.moment.toDate(), this.pickupData.date);
      if (this.isCreate) {
        response = this.PickupDate.create(this.pickupData);
      } else {
        response = this.PickupDate.save(this.pickupData);
      }
    }
    return response.then((data) => {
      this.$mdDialog.hide(data);
    });
  }

  closePanel() {
    this.$mdDialog.cancel();
  }
}

export default pickupEditCreateController;
<commit_msg>refactor: split single and recurring data<commit_after>import moment from "moment";

class pickupEditCreateController {
  constructor($mdDialog, PickupDate, PickupDateSeries, $locale) {
    "ngInject";
    Object.assign(this, {
      $mdDialog,
      PickupDate,
      PickupDateSeries,
      $locale,
      isCreate: true,
      days: {},
      timeExample: moment(new Date()).format("LT")
    });
  }

  $onInit() {
    Object.assign(this, {
      isSeries: this.data.series,
      mode: this.data.series ? "series" : "single"
    });

    let keys = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"];
    for (let i = 0; i < 7; i++) {
      // let the week begin on Monday, because the FIRSTDAYOFWEEK value is usually set to Sunday
      this.days[(i + 6) % 7] = { key: keys[i], name: this.$locale.DATETIME_FORMATS.DAY[i] };
    }

    // check if we get incoming data
    if (angular.isDefined(this.data.editData)) {
      this.isCreate = false;

      // shared pickup data
      // note that we do partial updates on the server, so we don't need to copy *all* values
      this.pickupData = {
        id: this.data.editData.id,
        "max_collectors": this.data.editData.max_collectors,
        store: this.data.editData.store
      };

      this.time = new Date();
      // splitted pickup data and copy time to autocomplete input
      if (this.data.series) {
        this.seriesData = {
          "start_date": this.data.editData.start_date,
          rule: this.data.editData.rule
        };
        this.copyTime(this.seriesData.start_date, this.time);
      } else {
        this.singleData = {
          date: this.data.editData.date
        };
        this.copyTime(this.singleData.date, this.time);
      }
      this.time = {
        moment: moment(this.time),
        text: moment(this.time).format("LT")
      };
    // otherwise set default data for creation
    } else {
      Object.assign(this, {
        // shared data
        pickupData: {
          store: this.data.storeId,
          "max_collectors": 2
        },
        singleData: {
          date: new Date()
        },
        seriesData: {
          "start_date": new Date(),
          rule: {
            freq: "WEEKLY",
            byDay: [keys[(new Date()).getDay()]]
          }
        }
      });
    }
    this.timeChoices = this.getTimeChoices(false);
    this.allTimeChoices = this.getTimeChoices(true);
  }

  copyTime(source, dest) {
    dest.setHours(source.getHours());
    dest.setMinutes(source.getMinutes());
  }

  timeLookup(text) {
    if (!text) {
      return this.timeChoices;
    } else {
      return this.allTimeChoices.filter((e) => e.text.startsWith(text));
    }
  }

  getTimeChoices(all) {
    let list = [];
    for (let h = 0; h < 24; h++) {
      for (let m = 0; m < 60; m += all ? 1 : 15) {
        let suggestion = moment().hour(h).minute(m);
        list.push({
          moment: suggestion,
          text: suggestion.format("LT")
        });
      }
    }
    return list;
  }

  handleSubmit() {
    let response;
    if (this.isSeries) {
      this.copyTime(this.time.moment.toDate(), this.seriesData.start_date);
      let outgoing = angular.merge({}, this.pickupData, this.seriesData);
      if (this.isCreate) {
        response = this.PickupDateSeries.create(outgoing);
      } else {
        response = this.PickupDateSeries.save(outgoing);
      }
    } else {
      this.copyTime(this.time.moment.toDate(), this.singleData.date);
      let outgoing = angular.merge({}, this.pickupData, this.singleData);
      if (this.isCreate) {
        response = this.PickupDate.create(outgoing);
      } else {
        response = this.PickupDate.save(outgoing);
      }
    }
    return response.then((data) => {
      this.$mdDialog.hide(data);
    });
  }

  closePanel() {
    this.$mdDialog.cancel();
  }
}

export default pickupEditCreateController;
<|endoftext|>