<commit_before>// A viewer is a WebGL canvas that lets the user view a mesh. The user can
// tumble it around by dragging the mouse.

/**
 * Converts RGB color value to 24 bit hex color value
 * Conversion formula:
 * - convert R, G, B into HEX
 * - return 24bit Number 0xRRGGBB
 */
function rgbTo24Bit (r, g, b){
  if (r.length) { b = r[2], g = r[1], r = r[0]; }
  if ('r' in r && 'g' in r && 'b' in r) {b = r.b, g = r.g, r = r.r;}
  var s = Number(0x1000000+Math.floor(r*255)*0x10000+Math.floor(g*255)*0x100+Math.floor(b*255));
  return s;
}

OpenJsCad.Viewer.ThreeEngine = function (containerEl, size, options) {
  // TODO: read from config

  this.perspective = 45; // in degrees

  this.options = options;
  this.size = size;

  // the element to contain the canvas
  this.containerEl = containerEl;

  this.createScene();
  this.createCamera();
  this.parseSizeParams();
  // createRenderer will also call render
  this.createRenderer(options.noWebGL);
  this.animate();
}

OpenJsCad.Viewer.ThreeEngine.prototype = {
  init: function() {

  },
  // adds axes too
  createScene: function() {
    var scene = new THREE.Scene();
    this.scene_ = scene;
    if (this.options.axes.draw) {
      this.drawAxes();
    }
    if (this.options.grid.draw) {
      this.drawGrid();
    }
  },
  createCamera: function() {
    var cameraAngle = this.options.camera.angle;
    var light = new THREE.PointLight();
    light.position.set(0, 0, 0);
    // aspect ration changes later - just a placeholder
    var camera = new THREE.PerspectiveCamera(this.perspective, 1/1, 0.01, 1000000);
    this.camera_ = camera;
    camera.add(light);
    camera.up.set(0, 0, 1);
    this.scene_.add(camera);
  },
  createControls: function(canvas) {
    // controls. just change this line (and script include) to other threejs controls if desired
    var controls = new THREE.OrbitControls(this.camera_, canvas);
    this.controls_ = controls;
    controls.noKeys = true;
    controls.zoomSpeed = 0.5;
    // controls.autoRotate = true;
    controls.autoRotateSpeed = 1;
    controls.addEventListener( 'change', this.render.bind(this));
  },
  webGLAvailable: function() {
    try {
      var canvas = document.createElement("canvas");
      return !!
        window.WebGLRenderingContext &&
        (canvas.getContext("webgl") ||
         canvas.getContext("experimental-webgl"));
    } catch(e) {
      return false;
    }
  },
  createRenderer: function(bool_noWebGL) {
    var Renderer = this.webGLAvailable() && !bool_noWebGL ?
        THREE.WebGLRenderer : THREE.CanvasRenderer;
    // we're creating new canvas on switching renderer, as same
    // canvas doesn't tolerate moving from webgl to canvasrenderer
    var renderer = new Renderer({precision: 'highp', antialias: true});
    this.renderer_ = renderer;

    if (this.canvas) {
      this.canvas.remove();
    }
    this.canvas = renderer.domElement;
    this.containerEl.appendChild(this.canvas);
    // this.scene_.fog = new THREE.FogExp2( 0xcccccc, 0.002 )

    var bgColor = this.options.background.color;

    var bgColor_ = new THREE.Color();
    bgColor_.setRGB.apply(bgColor_, [bgColor.r, bgColor.g, bgColor.b, bgColor.a || 1]);

    renderer.setClearColor(bgColor_);
    // renderer.setClearColor(scene.fog.color);
    // and add controls
    this.createControls(renderer.domElement, this.canvas);

    // if coming in from contextrestore, enable rendering here
    this.pauseRender_ = false;
    this.handleResize();
    // handling context lost
    var this_ = this;
    this.canvas.addEventListener("webglcontextlost", function(e) {
      e.preventDefault();
      this_.cancelAnimate();
    }, false);
    this.canvas.addEventListener("webglcontextrestored", function(e) {
      this_.createRenderer(true);
      this_.animate();
    }, false);
  },
  render: function() {
    if (!this.pauseRender_) {
      this.renderer_.render(this.scene_, this.camera_);
    }
  },
  animate: function() {
    // reduce fps? replace func with
    // setTimeout( function() {
    //     requestAnimationFrame(this.animate.bind(this));
    // }, 1000 / 40 ); // last num = fps
    this.requestID_ = requestAnimationFrame(this.animate.bind(this));
    this.controls_.update();
  },
  cancelAnimate: function() {
    this.pauseRender_ = true;
    cancelAnimationFrame(this.requestID_);
  },
  refreshRenderer: function(bool_noWebGL) {
    this.cancelAnimate();
    if (!bool_noWebGL) {
      // need to refresh scene objects except camera
      var objs = this.scene_.children.filter(function(ch) {
        return !(ch instanceof THREE.Camera);
      });
      this.scene_.remove.apply(this.scene_, objs);
      var newObjs = objs.map(function(obj) {
        obj.geometry = obj.geometry.clone();
        obj.material = obj.material.clone();
        return obj.clone();
      });
      this.scene_.add.apply(this.scene_, newObjs);
      this.applyDrawOptions();
    }
    this.createRenderer(bool_noWebGL);
    this.animate();
  },
  drawAxes: function(axLen) {
    var axes = this.options.axes;
    var size = (axes.size || this.options.grid.size)/2;

    function v(x,y,z){
      return new THREE.Vector3(x,y,z);
    }
    var origin = v(0, 0, 0);
    "x y z".split(" ").forEach(function(axis) {

      var linePos = new THREE.Geometry();
      linePos.vertices.push(origin, v(axis === "x" ? size : 0, axis === "y" ? size : 0, axis === "z" ? size : 0));
      this.scene_.add(new THREE.Line(
        linePos,
        new THREE.LineBasicMaterial({color: rgbTo24Bit(axes[axis].pos), opacity: axes[axis].pos.a, transparent: true, lineWidth: 1})
      ))
      var lineNeg = new THREE.Geometry();
      lineNeg.vertices.push(origin, v(axis === "x" ? -size : 0, axis === "y" ? -size : 0, axis === "z" ? -size : 0));
      this.scene_.add(new THREE.Line(
        lineNeg,
        new THREE.LineBasicMaterial({color: rgbTo24Bit(axes[axis].neg), opacity: axes[axis].neg.a, transparent: true, lineWidth: 1})
      ))
    }, this);
  },
  drawGrid: function () {
    var m = this.options.grid.m; // short cut
    var M = this.options.grid.M; // short cut
    var size = this.options.grid.size/2;
    var size = 100, step = 1;
    var g_m = new THREE.Geometry();
    var g_M = new THREE.Geometry();
    for ( var i = - size; i <= size; i += step ) {
      var g = i % 10 ? g_m : g_M;
      g.vertices.push( new THREE.Vector3( - size, i, 0 ) );
      g.vertices.push( new THREE.Vector3(   size, i, 0 ) );
      g.vertices.push( new THREE.Vector3( i, - size, 0 ) );
      g.vertices.push( new THREE.Vector3( i,   size, 0 ) );
    }
    var material_m = new THREE.LineBasicMaterial( { color: rgbTo24Bit(m.color), opacity: m.color.a, transparent: true } );
    var material_M = new THREE.LineBasicMaterial( { color: rgbTo24Bit(M.color), opacity: M.color.a, transparent: true } );
    var line_m = THREE.LineSegments ? new THREE.LineSegments( g_m, material_m ) : new THREE.Line( g_m, material_m, THREE.LinePieces );
    this.scene_.add( line_m );
    var line_M = THREE.LineSegments ? new THREE.LineSegments( g_M, material_M ) : new THREE.Line( g_M, material_M, THREE.LinePieces );
    this.scene_.add( line_M );
  },
  applyDrawOptions: function() {
    this.getUserMeshes('faces').forEach(function(faceMesh) {
      faceMesh.visible = !!this.options.solid.faces;
    }, this);
    this.getUserMeshes('lines').forEach(function(lineMesh) {
      lineMesh.visible = !!this.options.solid.lines;
    }, this);
    this.render();
  },
  setCsg: function(csg) {
    this.clear();

    // set resetZoom on first render
    var resetZoom = !this.resetZoom_;
    this.resetZoom_ = resetZoom;

    var faceColor = this.options.solid.faceColor;

    // default is opaque if not defined otherwise
    var defaultColor_ = [faceColor.r, faceColor.g, faceColor.b, faceColor.a || 1];

    var res = THREE.CSG.fromCSG(csg, defaultColor_, this.options.solid.overlay);
    var colorMeshes = [].concat(res.colorMesh)
    .map(function(mesh) {
      mesh.userData = {faces: true};
      return mesh;
    });
    var wireMesh = res.wireframe;
    wireMesh.userData = {lines: true};
    this.scene_.add.apply(this.scene_, colorMeshes);
    this.scene_.add(wireMesh);
    resetZoom && this.resetZoom(res.boundLen);
    this.applyDrawOptions();
  },
  clear: function() {
    this.scene_.remove.apply(this.scene_, this.getUserMeshes());
  },
  // gets the meshes created by setCsg
  getUserMeshes: function(str) {
    return this.scene_.children.filter(function(ch) {
      if (str) {
        return ch.userData[str];
      } else {
        return ch.userData.lines || ch.userData.faces;
      }
    });
  },
  resetZoom: function(r) {
    if (!r) {
      // empty object - any default zoom
      r = 10;
    }
    var d = r / Math.tan(this.perspective * Math.PI / 180);
    // play here for different start zoom
    this.camera_.position.set(d*2, d*2, d);
    this.camera_.zoom = 1;
    this.camera_.lookAt(this.scene_.position);
    this.camera_.updateProjectionMatrix();
  },
  handleResize: function() {
    var canvas = this.canvas;

    this.resizeCanvas (canvas);

    this.camera_.aspect = canvas.width/canvas.height;
    this.camera_.updateProjectionMatrix();
    // set canvas attributes (false => don't set css)
    this.renderer_.setSize(canvas.width, canvas.height, false);
    this.render();
  }
};

<commit_msg>fixed view refresh<commit_after>// A viewer is a WebGL canvas that lets the user view a mesh. The user can
// tumble it around by dragging the mouse.

/**
 * Converts RGB color value to 24 bit hex color value
 * Conversion formula:
 * - convert R, G, B into HEX
 * - return 24bit Number 0xRRGGBB
 */
function rgbTo24Bit (r, g, b){
  if (r.length) { b = r[2], g = r[1], r = r[0]; }
  if ('r' in r && 'g' in r && 'b' in r) {b = r.b, g = r.g, r = r.r;}
  var s = Number(0x1000000+Math.floor(r*255)*0x10000+Math.floor(g*255)*0x100+Math.floor(b*255));
  return s;
}

OpenJsCad.Viewer.ThreeEngine = function (containerEl, size, options) {
  // TODO: read from config

  this.perspective = 45; // in degrees

  this.options = options;
  this.size = size;

  // the element to contain the canvas
  this.containerEl = containerEl;

  this.createScene();
  this.createCamera();
  this.parseSizeParams();
  // createRenderer will also call render
  this.createRenderer(options.noWebGL);
  this.animate();
}

OpenJsCad.Viewer.ThreeEngine.prototype = {
  init: function() {

  },
  // adds axes too
  createScene: function() {
    var scene = new THREE.Scene();
    this.scene_ = scene;
    if (this.options.axes.draw) {
      this.drawAxes();
    }
    if (this.options.grid.draw) {
      this.drawGrid();
    }
  },
  createCamera: function() {
    var cameraAngle = this.options.camera.angle;
    var light = new THREE.PointLight();
    light.position.set(0, 0, 0);
    // aspect ration changes later - just a placeholder
    var camera = new THREE.PerspectiveCamera(this.perspective, 1/1, 0.01, 1000000);
    this.camera_ = camera;
    camera.add(light);
    camera.up.set(0, 0, 1);
    this.scene_.add(camera);
  },
  createControls: function(canvas) {
    // controls. just change this line (and script include) to other threejs controls if desired
    var controls = new THREE.OrbitControls(this.camera_, canvas);
    this.controls_ = controls;
    controls.noKeys = true;
    controls.zoomSpeed = 0.5;
    // controls.autoRotate = true;
    controls.autoRotateSpeed = 1;
    controls.addEventListener( 'change', this.render.bind(this));
  },
  webGLAvailable: function() {
    try {
      var canvas = document.createElement("canvas");
      return !!
        window.WebGLRenderingContext &&
        (canvas.getContext("webgl") ||
         canvas.getContext("experimental-webgl"));
    } catch(e) {
      return false;
    }
  },
  createRenderer: function(bool_noWebGL) {
    var Renderer = this.webGLAvailable() && !bool_noWebGL ?
        THREE.WebGLRenderer : THREE.CanvasRenderer;
    // we're creating new canvas on switching renderer, as same
    // canvas doesn't tolerate moving from webgl to canvasrenderer
    var renderer = new Renderer({precision: 'highp', antialias: true});
    this.renderer_ = renderer;

    if (this.canvas) {
      this.canvas.remove();
    }
    this.canvas = renderer.domElement;
    this.containerEl.appendChild(this.canvas);
    // this.scene_.fog = new THREE.FogExp2( 0xcccccc, 0.002 )

    var bgColor = this.options.background.color;

    var bgColor_ = new THREE.Color();
    bgColor_.setRGB.apply(bgColor_, [bgColor.r, bgColor.g, bgColor.b, bgColor.a || 1]);

    renderer.setClearColor(bgColor_);
    // renderer.setClearColor(scene.fog.color);
    // and add controls
    this.createControls(renderer.domElement, this.canvas);

    // if coming in from contextrestore, enable rendering here
    this.pauseRender_ = false;
    this.handleResize();
    // handling context lost
    var this_ = this;
    this.canvas.addEventListener("webglcontextlost", function(e) {
      e.preventDefault();
      this_.cancelAnimate();
    }, false);
    this.canvas.addEventListener("webglcontextrestored", function(e) {
      this_.createRenderer(true);
      this_.animate();
    }, false);
  },
  render: function() {
    if (!this.pauseRender_) {
      this.renderer_.render(this.scene_, this.camera_);
    }
  },
  animate: function() {
    // reduce fps? replace func with
    // setTimeout( function() {
    //     requestAnimationFrame(this.animate.bind(this));
    // }, 1000 / 40 ); // last num = fps
    this.requestID_ = requestAnimationFrame(this.animate.bind(this));
    this.controls_.update();
  },
  cancelAnimate: function() {
    this.pauseRender_ = true;
    cancelAnimationFrame(this.requestID_);
  },
  refreshRenderer: function(bool_noWebGL) {
    this.cancelAnimate();
    if (!bool_noWebGL) {
      // need to refresh scene objects except camera
      var objs = this.scene_.children.filter(function(ch) {
        return !(ch instanceof THREE.Camera);
      });
      this.scene_.remove.apply(this.scene_, objs);
      var newObjs = objs.map(function(obj) {
        obj.geometry = obj.geometry.clone();
        obj.material = obj.material.clone();
        return obj.clone();
      });
      this.scene_.add.apply(this.scene_, newObjs);
      this.applyDrawOptions();
    }
    this.createRenderer(bool_noWebGL);
    this.animate();
  },
  drawAxes: function(axLen) {
    var axes = this.options.axes;
    var size = (axes.size || this.options.grid.size)/2;

    function v(x,y,z){
      return new THREE.Vector3(x,y,z);
    }
    var origin = v(0, 0, 0);
    "x y z".split(" ").forEach(function(axis) {

      var linePos = new THREE.Geometry();
      linePos.vertices.push(origin, v(axis === "x" ? size : 0, axis === "y" ? size : 0, axis === "z" ? size : 0));
      this.scene_.add(new THREE.Line(
        linePos,
        new THREE.LineBasicMaterial({color: rgbTo24Bit(axes[axis].pos), opacity: axes[axis].pos.a, transparent: true, lineWidth: 1})
      ))
      var lineNeg = new THREE.Geometry();
      lineNeg.vertices.push(origin, v(axis === "x" ? -size : 0, axis === "y" ? -size : 0, axis === "z" ? -size : 0));
      this.scene_.add(new THREE.Line(
        lineNeg,
        new THREE.LineBasicMaterial({color: rgbTo24Bit(axes[axis].neg), opacity: axes[axis].neg.a, transparent: true, lineWidth: 1})
      ))
    }, this);
  },
  drawGrid: function () {
    var m = this.options.grid.m; // short cut
    var M = this.options.grid.M; // short cut
    var size = this.options.grid.size/2;
    var size = 100, step = 1;
    var g_m = new THREE.Geometry();
    var g_M = new THREE.Geometry();
    for ( var i = - size; i <= size; i += step ) {
      var g = i % 10 ? g_m : g_M;
      g.vertices.push( new THREE.Vector3( - size, i, 0 ) );
      g.vertices.push( new THREE.Vector3(   size, i, 0 ) );
      g.vertices.push( new THREE.Vector3( i, - size, 0 ) );
      g.vertices.push( new THREE.Vector3( i,   size, 0 ) );
    }
    var material_m = new THREE.LineBasicMaterial( { color: rgbTo24Bit(m.color), opacity: m.color.a, transparent: true } );
    var material_M = new THREE.LineBasicMaterial( { color: rgbTo24Bit(M.color), opacity: M.color.a, transparent: true } );
    var line_m = THREE.LineSegments ? new THREE.LineSegments( g_m, material_m ) : new THREE.Line( g_m, material_m, THREE.LinePieces );
    this.scene_.add( line_m );
    var line_M = THREE.LineSegments ? new THREE.LineSegments( g_M, material_M ) : new THREE.Line( g_M, material_M, THREE.LinePieces );
    this.scene_.add( line_M );
  },
  applyDrawOptions: function() {
    this.getUserMeshes('faces').forEach(function(faceMesh) {
      faceMesh.visible = !!this.options.solid.faces;
    }, this);
    this.getUserMeshes('lines').forEach(function(lineMesh) {
      lineMesh.visible = !!this.options.solid.lines;
    }, this);
    this.render();
  },
  setCsg: function(csg) {
    this.clear();

    // set resetZoom on first render
    var resetZoom = this.resetZoom_ ? false : true;
    this.resetZoom_ = true;

    var faceColor = this.options.solid.faceColor;

    // default is opaque if not defined otherwise
    var defaultColor_ = [faceColor.r, faceColor.g, faceColor.b, faceColor.a || 1];

    var res = THREE.CSG.fromCSG(csg, defaultColor_, this.options.solid.overlay);
    var colorMeshes = [].concat(res.colorMesh)
    .map(function(mesh) {
      mesh.userData = {faces: true};
      return mesh;
    });
    var wireMesh = res.wireframe;
    wireMesh.userData = {lines: true};
    this.scene_.add.apply(this.scene_, colorMeshes);
    this.scene_.add(wireMesh);
    resetZoom && this.resetZoom(res.boundLen);
    this.applyDrawOptions();
  },
  clear: function() {
    this.scene_.remove.apply(this.scene_, this.getUserMeshes());
  },
  // gets the meshes created by setCsg
  getUserMeshes: function(str) {
    return this.scene_.children.filter(function(ch) {
      if (str) {
        return ch.userData[str];
      } else {
        return ch.userData.lines || ch.userData.faces;
      }
    });
  },
  resetZoom: function(r) {
    if (!r) {
      // empty object - any default zoom
      r = 10;
    }
    var d = r / Math.tan(this.perspective * Math.PI / 180);
    // play here for different start zoom
    this.camera_.position.set(d*2, d*2, d);
    this.camera_.zoom = 1;
    this.camera_.lookAt(this.scene_.position);
    this.camera_.updateProjectionMatrix();
  },
  handleResize: function() {
    var canvas = this.canvas;

    this.resizeCanvas (canvas);

    this.camera_.aspect = canvas.width/canvas.height;
    this.camera_.updateProjectionMatrix();
    // set canvas attributes (false => don't set css)
    this.renderer_.setSize(canvas.width, canvas.height, false);
    this.render();
  }
};

<|endoftext|>


<commit_before>angular.module('genome.directive', [])

.directive('dstTopNav', function() {

  return {
    controller: function($scope, $cookies, $rootScope, $location, SelfFactory) {
      $scope.user_first_name = $cookies.user_first_name;
      $scope.expand = false;

      $scope.onpoolpage = $location.$$path === '/pool' ? true : false;
      $scope.onselfpage = $location.$$path === '/self' ? true : false;

      $scope.getRelatives = function () {
        $scope.onpoolpage = true;
        $scope.onselfpage = false;
        if($location.$$path === '/self'){
          $rootScope.transitionToPool();
        }
        $location.path('/pool')
      };

      $scope.getSelf = function () {
        $rootScope.curPage = '/self'
        $scope.onselfpage = true;
        $scope.onpoolpage = false;
        $rootScope.removeMap();
        $location.path('/self');
      };
    },
    templateUrl: '../static/app/directives/dst_top_nav.html'
  };

});<commit_msg>Added in curpage element to top nav<commit_after>angular.module('genome.directive', [])

.directive('dstTopNav', function() {

  return {
    controller: function($scope, $cookies, $rootScope, $location, SelfFactory) {
      $scope.user_first_name = $cookies.user_first_name;
      $scope.expand = false;

      $scope.onpoolpage = $location.$$path === '/pool' ? true : false;
      $scope.onselfpage = $location.$$path === '/self' ? true : false;

      $scope.getRelatives = function () {
        $rootScope.curPage = '/pool';
        $scope.onpoolpage = true;
        $scope.onselfpage = false;
        if($location.$$path === '/self'){
          $rootScope.transitionToPool();
        }
        $location.path('/pool')
      };

      $scope.getSelf = function () {
        $rootScope.curPage = '/self';
        $scope.onselfpage = true;
        $scope.onpoolpage = false;
        $rootScope.removeMap();
        $location.path('/self');
      };
    },
    templateUrl: '../static/app/directives/dst_top_nav.html'
  };

});<|endoftext|>


<commit_before>'use babel';

import fs from 'fs';
import path from 'path';
import os from 'os';
import { exec } from 'child_process';
import voucher from 'voucher';
import { EventEmitter } from 'events';
import hasbin from 'hasbin'

export const config = {
  jobs: {
    title: 'Simultaneous jobs',
    description: 'Limits how many jobs make will run simultaneously. Defaults to number of processors. Set to 1 for default behavior of make.',
    type: 'number',
    default: os.cpus().length,
    minimum: 1,
    maximum: os.cpus().length,
    order: 1
  },
  useMake: {
    title: 'Target extraction with make',
    description: 'Use `make` to extract targets. This may yield unwanted targets, or take a long time and a lot of resource.',
    type: 'boolean',
    default: false,
    order: 2
  },
  useBear: {
    title: 'Bear integration',
    description: 'If present, use `bear` to generate compile_commands.json',
    type: 'boolean',
    default: true,
    order: 3
  }
};

export function provideBuilder() {
  const gccErrorMatch = '(?<file>([A-Za-z]:[\\/])?[^:\\n]+):(?<line>\\d+):(?<col>\\d+):\\s*(fatal error|error):\\s*(?<message>.+)';
  const ocamlErrorMatch = '(?<file>[\\/0-9a-zA-Z\\._\\-]+)", line (?<line>\\d+), characters (?<col>\\d+)-(?<col_end>\\d+):\\n(?<message>.+)';
  const golangErrorMatch = '(?<file>([A-Za-z]:[\\/])?[^:\\n]+):(?<line>\\d+):\\s*(?<message>.*error.+)';
  const errorMatch = [
    gccErrorMatch, ocamlErrorMatch, golangErrorMatch
  ];

  const gccWarningMatch = '(?<file>([A-Za-z]:[\\/])?[^:\\n]+):(?<line>\\d+):(?<col>\\d+):\\s*(warning):\\s*(?<message>.+)';
  const warningMatch = [
    gccWarningMatch
  ];

  return class MakeBuildProvider extends EventEmitter {
    constructor(cwd) {
      super();
      this.cwd = cwd;
      atom.config.observe('build-make.jobs', () => this.emit('refresh'));
      atom.config.observe('build-make.useMake', () => this.emit('refresh'));
      atom.config.observe('build-make.useBear', () => this.emit('refresh'));
    }

    getNiceName() {
      return 'GNU Make';
    }

    isEligible() {
      this.files = [ 'Makefile', 'GNUmakefile', 'makefile' ]
        .map(f => path.join(this.cwd, f))
        .filter(fs.existsSync);
      return this.files.length > 0;
    }

    settings() {
      const buildexec = atom.config.get('build-make.useBear') && hasbin.sync('bear') ? 'bear' : 'make';

      const args = atom.config.get('build-make.useBear') && hasbin.sync('bear') ? [`make`, `-j${atom.config.get('build-make.jobs')}`] : [`-j${atom.config.get('build-make.jobs')}`];

      const defaultTarget = {
        exec: buildexec,
        name: 'GNU Make: default (no target)',
        args: args,
        sh: false,
        errorMatch: errorMatch,
        warningMatch: warningMatch
      };

      const promise = atom.config.get('build-make.useMake') ?
        voucher(exec, 'make -prRn', { cwd: this.cwd }) :
        voucher(fs.readFile, this.files[0]); // Only take the first file

      return promise.then(output => {
        return [ defaultTarget ].concat(output.toString('utf8')
          .split(/[\r\n]{1,2}/)
          .filter(line => /^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/.test(line))
          .map(targetLine => targetLine.split(':').shift())
          .filter( (elem, pos, array) => (array.indexOf(elem) === pos) )
          .map(target => ({
            exec: buildexec,
            args: args.concat([ target ]),
            name: `GNU Make: ${target}`,
            sh: false,
            errorMatch: errorMatch,
            warningMatch: warningMatch
          })));
      }).catch(e => [ defaultTarget ]);
    }
  };
}
<commit_msg>Bear integration is a target<commit_after>'use babel';

import fs from 'fs';
import path from 'path';
import os from 'os';
import { exec } from 'child_process';
import voucher from 'voucher';
import { EventEmitter } from 'events';
import hasbin from 'hasbin'

export const config = {
  jobs: {
    title: 'Simultaneous jobs',
    description: 'Limits how many jobs make will run simultaneously. Defaults to number of processors. Set to 1 for default behavior of make.',
    type: 'number',
    default: os.cpus().length,
    minimum: 1,
    maximum: os.cpus().length,
    order: 1
  },
  useMake: {
    title: 'Target extraction with make',
    description: 'Use `make` to extract targets. This may yield unwanted targets, or take a long time and a lot of resource.',
    type: 'boolean',
    default: false,
    order: 2
  },
  useBear: {
    title: 'Bear integration',
    description: 'If present, add `bear` target to generate compile_commands.json',
    type: 'boolean',
    default: true,
    order: 3
  }
};

export function provideBuilder() {
  const gccErrorMatch = '(?<file>([A-Za-z]:[\\/])?[^:\\n]+):(?<line>\\d+):(?<col>\\d+):\\s*(fatal error|error):\\s*(?<message>.+)';
  const ocamlErrorMatch = '(?<file>[\\/0-9a-zA-Z\\._\\-]+)", line (?<line>\\d+), characters (?<col>\\d+)-(?<col_end>\\d+):\\n(?<message>.+)';
  const golangErrorMatch = '(?<file>([A-Za-z]:[\\/])?[^:\\n]+):(?<line>\\d+):\\s*(?<message>.*error.+)';
  const errorMatch = [
    gccErrorMatch, ocamlErrorMatch, golangErrorMatch
  ];

  const gccWarningMatch = '(?<file>([A-Za-z]:[\\/])?[^:\\n]+):(?<line>\\d+):(?<col>\\d+):\\s*(warning):\\s*(?<message>.+)';
  const warningMatch = [
    gccWarningMatch
  ];

  return class MakeBuildProvider extends EventEmitter {
    constructor(cwd) {
      super();
      this.cwd = cwd;
      atom.config.observe('build-make.jobs', () => this.emit('refresh'));
      atom.config.observe('build-make.useMake', () => this.emit('refresh'));
      atom.config.observe('build-make.useBear', () => this.emit('refresh'));
    }

    getNiceName() {
      return 'GNU Make';
    }

    isEligible() {
      this.files = [ 'Makefile', 'GNUmakefile', 'makefile' ]
        .map(f => path.join(this.cwd, f))
        .filter(fs.existsSync);
      return this.files.length > 0;
    }

    settings() {
      const args = [`-j${atom.config.get('build-make.jobs')}`];

      const defaultTarget = {
        exec: 'make',
        name: 'GNU Make: default (no target)',
        args: args,
        sh: false,
        errorMatch: errorMatch,
        warningMatch: warningMatch
      };

      const promise = atom.config.get('build-make.useMake') ?
        voucher(exec, 'make -prRn', { cwd: this.cwd }) :
        voucher(fs.readFile, this.files[0]); // Only take the first file

      return promise.then(output => {
        const returntargets = [ defaultTarget ].concat(output.toString('utf8')
          .split(/[\r\n]{1,2}/)
          .filter(line => /^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/.test(line))
          .map(targetLine => targetLine.split(':').shift())
          .filter( (elem, pos, array) => (array.indexOf(elem) === pos) )
          .map(target => ({
            exec: 'make',
            args: args.concat([ target ]),
            name: `GNU Make: ${target}`,
            sh: false,
            errorMatch: errorMatch,
            warningMatch: warningMatch
          })));

          if (atom.config.get('build-make.useBear') && hasbin.sync('bear')) {
            return returntargets.concat({
              exec: `make clean && bear make -j${atom.config.get('build-make.jobs')}`,
              name: 'GNU Make: generate compile_commands.json (with bear)',
              args: [],
              sh: true,
              errorMatch: errorMatch,
              warningMatch: warningMatch
            });
          } else {
            return returntargets;
          }
      }).catch(e => [ defaultTarget ]);
    }
  };
}
<|endoftext|>


<commit_before>// @flow
import React from "react"
import Card from "@material-ui/core/Card"
import CardContent from "@material-ui/core/CardContent"
import Button from "@material-ui/core/Button"
import Grid from "@material-ui/core/Grid"

import SpinnerButton from "./SpinnerButton"
import { FETCH_PROCESSING } from "../actions"
import type { Course, CourseRun } from "../flow/programTypes"
import type { CoursePrice } from "../flow/dashboardTypes"
import { formatPrice } from "../util/util"

class OrderSummary extends React.Component {
  props: {
    course: Course,
    courseRun: CourseRun,
    coursePrice: CoursePrice,
    finalPrice: ?number,
    discount: ?number,
    couponCode: ?string,
    checkout: Function,
    checkoutStatus?: string
  }

  getCoursePrice(): string {
    const { coursePrice } = this.props
    return formatPrice(coursePrice.price)
  }

  getFinalPrice(): string {
    const { finalPrice } = this.props
    return formatPrice(finalPrice)
  }

  getDiscountAmount(): string {
    const { discount } = this.props
    return `-${formatPrice(discount)}`
  }

  getExplanationText(): React$Element<*> {
    const { finalPrice, coursePrice } = this.props
    let text
    const price =
      finalPrice !== undefined && finalPrice !== null
        ? finalPrice
        : coursePrice.price
    if (price > 0) {
      text =
        "Clicking continue will take you to an external website, where you " +
        "can complete the transaction with a credit or debit card."
    } else {
      text =
        "Because there is no cost to enroll in this course, when you click the button below" +
        " you will skip the normal payment process and be enrolled in the course immediately."
    }
    return
{text}

  }

  showAmount(description: string, amount: string): Array<React$Element<*>> {
    return [
      <Grid item xs={8} className="description" key={description}>
        {description}
      </Grid>,
      <Grid item xs={2} key={`${description}-amount`} className="align-right">
        {amount}
      </Grid>
    ]
  }

  render() {
    const {
      course,
      courseRun,
      checkout,
      checkoutStatus,
      couponCode,
      discount
    } = this.props
    let discountInfo

    if (discount) {
      const message = couponCode
        ? `Discount from coupon ${couponCode}`
        : "Discount from coupon"
      discountInfo = [
        this.showAmount(message, this.getDiscountAmount()),
        <Grid item xs={10} className="division-line" key="division" />,
        this.showAmount("Total", this.getFinalPrice())
      ]
    }

    return (

        <Card shadow={1} className="card">
          <CardContent>

              You are about to pay for {course.title}

              <Grid container className="summary-box">
                {this.showAmount("Cost of course", this.getCoursePrice())}
                {discountInfo}
              </Grid>

            {this.getExplanationText()}
          </CardContent>
        </Card>

          By clicking below, you agree to the{" "}

            MITx MicroMasters Terms of Service.

        <SpinnerButton
          className="mdl-button next continue-payment"
          component={Button}
          spinning={checkoutStatus === FETCH_PROCESSING}
          onClick={() => checkout(courseRun.course_id)}
        >
          Continue
        </SpinnerButton>

    )
  }
}

export default OrderSummary
<commit_msg>Show an error message on checkout request failure (#4827)<commit_after>// @flow
import React from "react"
import Card from "@material-ui/core/Card"
import CardContent from "@material-ui/core/CardContent"
import Button from "@material-ui/core/Button"
import Grid from "@material-ui/core/Grid"

import SpinnerButton from "./SpinnerButton"
import { FETCH_PROCESSING, FETCH_FAILURE } from "../actions"
import type { Course, CourseRun } from "../flow/programTypes"
import type { CoursePrice } from "../flow/dashboardTypes"
import { formatPrice } from "../util/util"
import Alert from "react-bootstrap/lib/Alert"

class OrderSummary extends React.Component {
  props: {
    course: Course,
    courseRun: CourseRun,
    coursePrice: CoursePrice,
    finalPrice: ?number,
    discount: ?number,
    couponCode: ?string,
    checkout: Function,
    checkoutStatus?: string
  }

  getCoursePrice(): string {
    const { coursePrice } = this.props
    return formatPrice(coursePrice.price)
  }

  getFinalPrice(): string {
    const { finalPrice } = this.props
    return formatPrice(finalPrice)
  }

  getDiscountAmount(): string {
    const { discount } = this.props
    return `-${formatPrice(discount)}`
  }

  getExplanationText(): React$Element<*> {
    const { finalPrice, coursePrice } = this.props
    let text
    const price =
      finalPrice !== undefined && finalPrice !== null
        ? finalPrice
        : coursePrice.price
    if (price > 0) {
      text =
        "Clicking continue will take you to an external website, where you " +
        "can complete the transaction with a credit or debit card."
    } else {
      text =
        "Because there is no cost to enroll in this course, when you click the button below" +
        " you will skip the normal payment process and be enrolled in the course immediately."
    }
    return
{text}

  }

  showAmount(description: string, amount: string): Array<React$Element<*>> {
    return [
      <Grid item xs={8} className="description" key={description}>
        {description}
      </Grid>,
      <Grid item xs={2} key={`${description}-amount`} className="align-right">
        {amount}
      </Grid>
    ]
  }

  checkAndShowCheckoutError(status?: string) {
    if (status === FETCH_FAILURE) {
      return (

          <Alert bsStyle="danger">

              Something went wrong. Please{" "}

                contact customer support.

          </Alert>

      )
    }
    return null
  }

  render() {
    const {
      course,
      courseRun,
      checkout,
      checkoutStatus,
      couponCode,
      discount
    } = this.props
    let discountInfo

    if (discount) {
      const message = couponCode
        ? `Discount from coupon ${couponCode}`
        : "Discount from coupon"
      discountInfo = [
        this.showAmount(message, this.getDiscountAmount()),
        <Grid item xs={10} className="division-line" key="division" />,
        this.showAmount("Total", this.getFinalPrice())
      ]
    }

    return (

        <Card shadow={1} className="card">
          <CardContent>

              You are about to pay for {course.title}

              <Grid container className="summary-box">
                {this.showAmount("Cost of course", this.getCoursePrice())}
                {discountInfo}
              </Grid>

            {this.getExplanationText()}
          </CardContent>
        </Card>

          By clicking below, you agree to the{" "}

            MITx MicroMasters Terms of Service.

        <SpinnerButton
          className="mdl-button next continue-payment"
          component={Button}
          spinning={checkoutStatus === FETCH_PROCESSING}
          onClick={() => checkout(courseRun.course_id)}
        >
          Continue
        </SpinnerButton>
        {this.checkAndShowCheckoutError(checkoutStatus)}

    )
  }
}

export default OrderSummary
<|endoftext|>


<commit_before>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2010-2012 Zynga Inc.
--------------------------------------------------------------------------------------------------
  Based on the work of ES5 Shim
  MIT License, Copyright (c) 2009, 280 North Inc. http://280north.com/
  http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
==================================================================================================
*/

(function()
{
	// Fix for IE bug with enumerables
	var hasDontEnumBug = true;
	for (var key in {"toString": null}) {
		hasDontEnumBug = false;
	}

	if (hasDontEnumBug)
	{
		var dontEnums = "toString,toLocaleString,valueOf,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,constructor".split(",");
		var dontEnumsLength = dontEnums.length;
	}

	/**
	 * Adds missing ES5 `Object.keys` to the Object constructor when not implemented natively by the browser engine.
	 * Also adds a custom extension `Object.empty` to quickly check whether an object is empty (no keys).
	 */
	core.Main.addStatics("Object",
	{
		/**
		 * {Array} Returns an array of all own enumerable properties found upon a given @object {Object},
		 * in the same order as that provided by a for-in loop
		 *
		 * See also:
		 *
		 * - ES5 15.2.3.14
		 * - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys
		 */
		keys : function(object)
		{
			var keys = [];
			for (var name in object)
			{
				if (Object.hasOwnProperty(object, name)) {
					keys.push(name);
				}
			}

			if (hasDontEnumBug)
			{
				for (var i=0; i<dontEnumsLength; i++)
				{
					var dontEnum = dontEnums[i];
					if (Object.hasOwnProperty(object, dontEnum)) {
						keys.push(dontEnum);
					}
				}
			}

			return keys;
		}

	}, true);

})();<commit_msg>Fix Object.keys() for Internet Explorer 8<commit_after>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2010-2012 Zynga Inc.
--------------------------------------------------------------------------------------------------
  Based on the work of ES5 Shim
  MIT License, Copyright (c) 2009, 280 North Inc. http://280north.com/
  http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
==================================================================================================
*/

(function()
{
	// Fix for IE bug with enumerables
	var hasDontEnumBug = true;
	for (var key in {"toString": null}) {
		hasDontEnumBug = false;
	}

	if (hasDontEnumBug)
	{
		var dontEnums = "toString,toLocaleString,valueOf,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,constructor".split(",");
		var dontEnumsLength = dontEnums.length;
	}

	/**
	 * Adds missing ES5 `Object.keys` to the Object constructor when not implemented natively by the browser engine.
	 * Also adds a custom extension `Object.empty` to quickly check whether an object is empty (no keys).
	 */
	core.Main.addStatics("Object",
	{
		/**
		 * {Array} Returns an array of all own enumerable properties found upon a given @object {Object},
		 * in the same order as that provided by a for-in loop
		 *
		 * See also:
		 *
		 * - ES5 15.2.3.14
		 * - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys
		 */
		keys : function(object)
		{
			var keys = [];
			for (var name in object)
			{
				if (Object.prototype.hasOwnProperty.call(object, name)) {
					keys.push(name);
				}
			}

			if (hasDontEnumBug)
			{
				for (var i=0; i<dontEnumsLength; i++)
				{
					var dontEnum = dontEnums[i];
					if (Object.prototype.hasOwnProperty.call(object, dontEnum)) {
						keys.push(dontEnum);
					}
				}
			}

			return keys;
		}

	}, true);

})();<|endoftext|>


<commit_before>'use strict';

function Point(x, y) {
  if (!(this instanceof Point)) {
    return new Point(x, y);
  }

  this.x = x;
  this.y = y;

  this.add = function (point) {
    return new Point(this.x + point.x, this.y + point.y);
  };

  this.sub = function (point) {
    return new Point(this.x - point.x, this.y - point.y);
  };

  this.mul = function (value) {
    return new Point(this.x * value, this.y * value);
  };

  this.div = function (value) {
    return new Point(this.x / value, this.y / value);
  };

  this.dist = function () {
    return Math.sqrt(this.x*this.x + this.y*this.y);
  };

  this.sqr = function () {
    return this.x*this.x + this.y*this.y;
  };
}

// converts cubic bezier to quad
function toQuad(p1, c1, c2, p2) {
  // Quad control point is (3*c2 - p2 + 3*c1 - p1)/4
  return [p1, c2.mul(3).sub(p2).add(c1.mul(3)).sub(p1).div(4), p2];
}

/*
 * Aproximates cubic curve to 2 quad curves. Returns array of quad curves
 *
 * 1. Split cubic bezier-> 2 cubic beziers, by midpoint
 * 2. Replace each cubic bezier with quad bezier
 *
 * This is a simplified approach. It can be improved by adaptive splitting,
 * but in real life that's not needed.
 *
 * (!) We could use more slices, but FONT SIZE DOES MATTER !!!
 */
function bezierCubicToQuad(p1, c1, c2, p2) {

  // check first, if we can aproximate with quad directly
  // |p2 - 3*c2 + 3*c1 - p1|/2 should be small (zero in ideal)
  // http://www.caffeineowl.com/graphics/2d/vectorial/cubic2quad01.html
  var cpDistance = p2.sub(c2.mul(3)).add(c1.mul(3)).sub(p1).dist()/2;

  if (cpDistance <= 3) {
    return [ toQuad(p1, c1, c2, p2) ];
  }

  // Split to 2 qubic beziers
  // https://www.atalasoft.com/blogs/stevehawley/may-2013/how-to-split-a-cubic-bezier-curve
  // http://www.timotheegroleau.com/Flash/articles/cubic_bezier/bezier_lib.as

  // midpoints of qubic bezier
  // (p2 + 3*c2 + 3*c1 + p1)/8
  var mp = p2.add(c2.mul(3)).add(c1.mul(3)).add(p1).div(8);

  var q1 = toQuad(p1, p1.add(c1).div(2), p1.add(c2).add(c1.mul(2)).div(4), mp);
  var q2 = toQuad(mp, p2.add(c1).add(c2.mul(2)).div(4), p2.add(c2).div(2), p2);

  // now replace each half with quad curve
  return [ q1, q2 ];

}

/*
 * Check if 3 points are in line, and second in the midle.
 * Used to replace quad curves with lines or join lines
 *
 */
function isInLine(p1, m, p2, accuracy) {
  var a = p1.sub(m).sqr();
  var b = p2.sub(m).sqr();
  var c = p1.sub(p2).sqr();

  // control point not between anchors
  if ((a > (b+c)) || (b > (a+c))) {
    return false;
  }

  // count siatance between m and [p1,p2]
  a = Math.sqrt(a);
  b = Math.sqrt(b);
  c = Math.sqrt(c);

  var p = (a + b + c) / 2;
  var s = Math.sqrt((p - a) * (p - b) * (p - c) * p);
  var distance = s * 2 / c;

  return distance < accuracy ? true : false;
}

module.exports.Point = Point;
module.exports.bezierCubicToQuad = bezierCubicToQuad;
module.exports.isInLine = isInLine;
<commit_msg>Simplified distance calculation (use vector scalar multiplication instead of geron formula)<commit_after>'use strict';

function Point(x, y) {
  if (!(this instanceof Point)) {
    return new Point(x, y);
  }

  this.x = x;
  this.y = y;

  this.add = function (point) {
    return new Point(this.x + point.x, this.y + point.y);
  };

  this.sub = function (point) {
    return new Point(this.x - point.x, this.y - point.y);
  };

  this.mul = function (value) {
    return new Point(this.x * value, this.y * value);
  };

  this.div = function (value) {
    return new Point(this.x / value, this.y / value);
  };

  this.dist = function () {
    return Math.sqrt(this.x*this.x + this.y*this.y);
  };

  this.sqr = function () {
    return this.x*this.x + this.y*this.y;
  };
}

// converts cubic bezier to quad
function toQuad(p1, c1, c2, p2) {
  // Quad control point is (3*c2 - p2 + 3*c1 - p1)/4
  return [p1, c2.mul(3).sub(p2).add(c1.mul(3)).sub(p1).div(4), p2];
}

/*
 * Aproximates cubic curve to 2 quad curves. Returns array of quad curves
 *
 * 1. Split cubic bezier-> 2 cubic beziers, by midpoint
 * 2. Replace each cubic bezier with quad bezier
 *
 * This is a simplified approach. It can be improved by adaptive splitting,
 * but in real life that's not needed.
 *
 * (!) We could use more slices, but FONT SIZE DOES MATTER !!!
 */
function bezierCubicToQuad(p1, c1, c2, p2) {

  // check first, if we can aproximate with quad directly
  // |p2 - 3*c2 + 3*c1 - p1|/2 should be small (zero in ideal)
  // http://www.caffeineowl.com/graphics/2d/vectorial/cubic2quad01.html
  var cpDistance = p2.sub(c2.mul(3)).add(c1.mul(3)).sub(p1).dist()/2;

  if (cpDistance <= 3) {
    return [ toQuad(p1, c1, c2, p2) ];
  }

  // Split to 2 qubic beziers
  // https://www.atalasoft.com/blogs/stevehawley/may-2013/how-to-split-a-cubic-bezier-curve
  // http://www.timotheegroleau.com/Flash/articles/cubic_bezier/bezier_lib.as

  // midpoints of qubic bezier
  // (p2 + 3*c2 + 3*c1 + p1)/8
  var mp = p2.add(c2.mul(3)).add(c1.mul(3)).add(p1).div(8);

  var q1 = toQuad(p1, p1.add(c1).div(2), p1.add(c2).add(c1.mul(2)).div(4), mp);
  var q2 = toQuad(mp, p2.add(c1).add(c2.mul(2)).div(4), p2.add(c2).div(2), p2);

  // now replace each half with quad curve
  return [ q1, q2 ];

}

/*
 * Check if 3 points are in line, and second in the midle.
 * Used to replace quad curves with lines or join lines
 *
 */
function isInLine(p1, m, p2, accuracy) {
  var a = p1.sub(m).sqr();
  var b = p2.sub(m).sqr();
  var c = p1.sub(p2).sqr();

  // control point not between anchors
  if ((a > (b+c)) || (b > (a+c))) {
    return false;
  }

  // count distance via scalar multiplication
  var distance = Math.sqrt(Math.pow((p1.x - m.x)*(p2.y - m.y) - (p2.x - m.x)*(p1.y - m.y), 2) / c);

  return distance < accuracy ? true : false;
}

module.exports.Point = Point;
module.exports.bezierCubicToQuad = bezierCubicToQuad;
module.exports.isInLine = isInLine;
<|endoftext|>


<commit_before>({
  init : function(){
    var self = this;
    $(function() {
      self.bindClick();
      self.bindWait();
    });
  },

  bindClick: function() {
    var self = this;
    $("#nhk").click(function(){
      self.callApi();
    });
  },

  bindWait: function() {
    var self = this;
    setInterval(function(){ self.callApi() }, 1000 * 60 * 60);
  },

  callApi: function() {
    var self = this;
    var url = "http://api.nhk.or.jp/v1/pg/now/130/g1.json";
    var api_key = localStorage["api_key"];
    $.ajax ({
      type: "GET",
      url : url + "?key=" +api_key,
      success: function(msg) {
        self.sendNotification(msg);
      },
      failure: function() {
        console.log("Fairure");
      }
    });
  },

  sendNotification: function(msg){
    var title = msg.nowonair_list.g1.present.title;
    var icon = msg.nowonair_list.g1.present.service.logo_s.url;
    var message = msg.nowonair_list.g1.present.subtitle;
    window.webkitNotifications.createNotification(icon, title, message);
    if ( webkitNotifications.checkPermission() == 0 ) {
      var popup = webkitNotifications.createNotification(icon, title, message);
      popup.ondisplay = function(){
        setTimeout(function(){
          popup.cancel();
        }, 5000);
      };
      popup.show();
    } else {
      webkitNotifications.requestPermission();
    }
  }
}).init();
<commit_msg>Fix notice mode<commit_after>({

  base_url_now : 'http://api.nhk.or.jp/v1/pg/now',
  base_url_list : 'http://api.nhk.or.jp/v1/pg/list',
  area : '130', //Tokyo
  service : 'g1',
  program: [],

  init : function(){
    var self = this;
    $(function() {
      self.getNowOnair();
      self.getNHKprogram();
      self.pollingProgram();
    });
  },

  pollingProgram: function() {
    var self = this;
    setInterval(function(){ self.noticeProgram(); }, 1000 * 60);
  },

  getNowOnair: function() {
    var self = this;
    var url_now = this.base_url_now + "/" + this.area + "/" + this.service + ".json";
    $("#nhk").click(function(){
      self.callApi(url_now);
    });
  },

  getNHKprogram: function() {
    var self = this;
    var today = self.getToday();
    var list_url = this.base_url_list + "/" + this.area + "/" + this.service + "/" + today + ".json";
    var program = self.callApi(list_url);
  },

  saveNHKprogram: function(program) {
    var program_array = program.list.g1;
    for (var i = 0 ; i < program_array.length; i++) {
      this.program[i] = {};
      this.program[i]["title"] = program_array[i].title;
      this.program[i]["subtitle"] = program_array[i].subtitle;
      this.program[i]["icon"] = program_array[i].service.logo_m.url;
      this.program[i]["start_time"] = Date.parse(program_array[i].start_time);
    }
  },

  noticeProgram: function() {
    var self = this;
    var now = new Date();
    for (var i = 0 ; i < this.program.length; i++) {
      var diff = Math.abs(now - this.program[i]["start_time"]);
      console.log(diff);
      if (diff <= 1000 * 60) {
      self.sendNotification(this.program[i]["icon"], this.program[i]["title"], this.program[i]["subtitle"]);
      }
    }
  },

  getToday: function() {
    var self = this;
    var date = new Date();
    var hour = date.getHours();
    if (hour < 4) {
      date.setDate(date.getDate()-1);
    }
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHour;
    month = ('0' + month).slice(-2);
    day = ('0' + day).slice(-2);
    return year + "-" + month + "-" + day;
  },

  callApi: function(api_url) {
    var self = this;
    var api_key = localStorage["api_key"];
    var url = api_url + "?key=" + api_key;
    $.ajax ({
      type: "GET",
      url : url.replace(/\s+/g, ""),
      datatype: 'json',
      success: function(msg) {
       for(var key in msg) {
         if (key == "list") {
           self.saveNHKprogram(msg);
         } else if (key == "nowonair_list") {
           var title = msg.nowonair_list.g1.present.title;
           var icon = msg.nowonair_list.g1.present.service.logo_s.url;
           var subtitle = msg.nowonair_list.g1.present.subtitle;
           self.sendNotification(icon, title, subtitle);
         }
       }
      },
      failure: function() {
        console.log("Fairure");
      }
    });
  },

  sendNotification: function(icon, title, subtitle) {
    window.webkitNotifications.createNotification(icon, title, subtitle);
    if ( webkitNotifications.checkPermission() == 0 ) {
      var popup = webkitNotifications.createNotification(icon, title, subtitle);
      popup.ondisplay = function(){
        setTimeout(function(){
          popup.cancel();
        }, 5000);
      };
      popup.show();
    } else {
      webkitNotifications.requestPermission();
    }
  }
}).init();
<|endoftext|>


<commit_before>import {ColumnView} from '../scene/view';
import {DataColumnModel} from './data.column.model';
import {TemplatePath} from '../template';

TemplatePath.register('date-cell', (template, column) => {
	return {
		model: template.for,
		resource: column.key
	};
});

TemplatePath.register('date-cell-edit', (template, column) => {
	return {
		model: 'edit',
		resource: column.key
	};
});

export class DateColumnModel extends DataColumnModel {
	constructor() {
		super('date');

		this.format = 'MM/DD/YYYY';
	}
}

export class DateColumn extends ColumnView {
	constructor(model) {
		super(model);
	}

	static model(model) {
		return model ? DateColumn.assign(model) : new DateColumnModel();
	}
}<commit_msg>date format fix<commit_after>import {ColumnView} from '../scene/view';
import {DataColumnModel} from './data.column.model';
import {TemplatePath} from '../template';

TemplatePath.register('date-cell', (template, column) => {
	return {
		model: template.for,
		resource: column.key
	};
});

TemplatePath.register('date-cell-edit', (template, column) => {
	return {
		model: 'edit',
		resource: column.key
	};
});

export class DateColumnModel extends DataColumnModel {
	constructor() {
		super('date');

		this.format = 'MM/dd/yyyy';
	}
}

export class DateColumn extends ColumnView {
	constructor(model) {
		super(model);
	}

	static model(model) {
		return model ? DateColumn.assign(model) : new DateColumnModel();
	}
}<|endoftext|>


<commit_before>// vim: ts=4 sw=4 et :
class Menu {
    constructor(choices) {
        this.choices = choices; // save menu options
        this.selected = 0;
        this.unselected_pics = this.choices.map(name => makeImage(`img/menu_${name}.png`))
        this.selected_pics = this.choices.map(name => makeImage(`img/menu_${name}_sel.png`))
        this.dudes_img = makeImage("img/p2.png")
    }
    update(dt, delta) {
        if (app.keys.is_new_press("ENTER")) {
            console.log(this.selected);

            if (this.selected == 0) app.menus[0].restart();
        }
        if (app.keys.is_new_press('DOWN')) {
            if (this.selected < this.choices.length - 1) {
                this.selected = this.selected + 1;
            }
        } else if (app.keys.is_new_press("UP")) {
            if (this.selected > 0) {
                this.selected = this.selected - 1;
            }
        } else if (app.keys.is_new_press("RIGHT") && this.selected == 1) {
            if (app.config.DUDES < 10) app.config.DUDES += 1;
        } else if (app.keys.is_new_press("LEFT") && this.selected == 1) {
            if (app.config.DUDES > 1) app.config.DUDES -= 1;
        }
    }
    draw(dt, delta) {
        var i = 0,
            x = 100,
            y = 100,
            factor = 0;
        for (i = 0; i < this.choices.length; i++) {
            if (this.selected == i) {
                factor = Math.max(0.15, Math.abs(Math.sin((dt / 725) % Math.PI)))
                app.display.context.globalAlpha = 1 - factor;
                app.display.context.drawImage(this.unselected_pics[i], x, y);
                app.display.context.globalAlpha = factor;
                app.display.context.drawImage(this.selected_pics[i], x, y);
                app.display.context.globalAlpha = 1.0;
            } else {
                app.display.context.drawImage(this.unselected_pics[i], x, y);
            }
            y += 125;
        }
        y = 250;
        x = 500;
        for (i = 0; i < app.config.DUDES; i++) {
            app.display.context.drawImage(this.dudes_img, x, y);
            x += 50;
        }
    }
}
class MainMenu extends Menu {
    constructor() {
        super(["NewGame", "Enemies"]);
    }
    update(dt, delta) {
        super.update(dt, delta)
        if (app.keys.is_new_press("ESC")) {
            app.pop_menu();
        }
    }
    draw(dt, delta) {
        // add a semi transparent background
        app.display.context.fillStyle = "rgba(100, 120, 150, 0.4)";
        app.display.context.fillRect(0, 0, app.display.width, app.display.height);
        app.display.context.fillStyle = "white";
        super.draw(dt, delta)
    }
}
<commit_msg>move specific code out of Menu<commit_after>// vim: ts=4 sw=4 et :
class Menu {
    constructor(choices) {
        this.choices = choices; // save menu options
        this.selected = 0;
        this.unselected_pics = this.choices.map(name => makeImage(`img/menu_${name}.png`))
        this.selected_pics = this.choices.map(name => makeImage(`img/menu_${name}_sel.png`))
        this.dudes_img = makeImage("img/p2.png")
    }
    update(dt, delta) {
        for (let sp_key of ['ENTER', 'LEFT', 'RIGHT']) {
            if (app.keys.is_new_press(sp_key)) {
                let ev_name = `${this.choices[this.selected]}_${sp_key}`
                if (this[ev_name])
                    this[ev_name]()
            }
            if (app.keys.is_new_press('DOWN')) {
                if (this.selected < this.choices.length - 1) {
                    this.selected = this.selected + 1;
                }
            } else if (app.keys.is_new_press("UP")) {
                if (this.selected > 0) {
                    this.selected = this.selected - 1;
                }
            }
        }
    }
    draw(dt, delta) {
        var i = 0,
            x = 100,
            y = 100,
            factor = 0;
        for (i = 0; i < this.choices.length; i++) {
            if (this.selected == i) {
                factor = Math.max(0.15, Math.abs(Math.sin((dt / 725) % Math.PI)))
                app.display.context.globalAlpha = 1 - factor;
                app.display.context.drawImage(this.unselected_pics[i], x, y);
                app.display.context.globalAlpha = factor;
                app.display.context.drawImage(this.selected_pics[i], x, y);
                app.display.context.globalAlpha = 1.0;
            } else {
                app.display.context.drawImage(this.unselected_pics[i], x, y);
            }
            y += 125;
        }
        y = 250;
        x = 500;
        for (i = 0; i < app.config.DUDES; i++) {
            app.display.context.drawImage(this.dudes_img, x, y);
            x += 50;
        }
    }
}
class MainMenu extends Menu {
    constructor() {
        super(["NewGame", "Enemies"]);
    }
    NewGame_ENTER() {
        app.menus[0].restart();
    }
    Enemies_RIGHT() {
        if (app.config.DUDES < 10) app.config.DUDES += 1;
    }
    Enemies_LEFT() {
        if (app.config.DUDES > 1) app.config.DUDES -= 1;
    }
    update(dt, delta) {
        super.update(dt, delta);
        if (app.keys.is_new_press("ESC")) {
            app.pop_menu();
        }
    }
    draw(dt, delta) {
        // add a semi transparent background
        app.display.context.fillStyle = "rgba(100, 120, 150, 0.4)";
        app.display.context.fillRect(0, 0, app.display.width, app.display.height);
        app.display.context.fillStyle = "white";
        super.draw(dt, delta);
    }
}
<|endoftext|>


<commit_before>/** @flow */

var Colors = require('./Colors');
var LineClamp = require('./LineClamp');
var React = require('react/addons');
var RelativeDate = require('./RelativeDate');
var _ = require('lodash');
var sx = require('./styleSet');

var PureRenderMixin = React.addons.PureRenderMixin;
var PropTypes = React.PropTypes;

var BlockMessageList = React.createClass({
  propTypes: {
    messages: PropTypes.array.isRequired,

    labels: PropTypes.array,
    selectedMessageID: PropTypes.string,
  },

  mixins: [PureRenderMixin],

  _onMessageClick(index: number, message: string) {
    this.props.onMessageSelected(message);
  },

  render(): any {
    return (

        {this.props.messages.map((msg, index) => (
          <BlockMessageListItem
            index={index}
            isSelected={msg.id === this.props.selectedMessageID}
            key={index}
            labels={this.props.labels && _.indexBy(this.props.labels, 'id')}
            message={msg}
            onClick={this._onMessageClick}
          />
        ))}

    );
  }
});

var BlockMessageListItem = React.createClass({
  propTypes: {
    index: PropTypes.number.isRequired,
    isSelected: PropTypes.bool.isRequired,
    message: PropTypes.object.isRequired,
    onClick: PropTypes.func.isRequired,

    labels: PropTypes.object,
  },

  mixins: [PureRenderMixin],

  _onClick() {
    this.props.onClick(this.props.index, this.props.message);
  },

  render(): any {
    var msg = this.props.message;
    return (

              {msg.isStarred ? (
                {'\u2605'}
              ) : null}
              {msg.from.name || msg.from.email}

            <RelativeDate
              style={styles.item.date}
              date={msg.date}
            />

          <LineClamp style={styles.item.text} lines={2}>
            {this.props.labels && msg.labelIDs.filter(labelID =>
              this.props.labels[labelID].type === 'user'
            ).map(labelID =>

                {this.props.labels ? this.props.labels[labelID].name : labelID}

            )}

              {msg.subject}{' '}

              {_.unescape(msg.snippet)}…

          </LineClamp>

    );
  }
});

var styles = {
  list: {
    root: {
      cursor: 'pointer',
      userSelect: 'none',
    }
  },

  item: {
    root: {
      lineHeight: 1.6,
      margin: '0 8px 8px 8px',
    },

    rootFirst: {
      borderTop: 'none',
    },

    inner: {
      borderRadius: '8px',
      padding: '8px 12px 12px 12px',
    },

    innerIsUnread: {
      background: Colors.accent.lighten(40),
    },

    innerIsSelected: {
      background: Colors.accent,
      color: 'white',
    },

    top: {
      display: 'flex',
    },

    date: {
      flex: 1,
      fontSize: '14px',
      opacity: 0.5,
      textAlign: 'right',
    },

    text: {
      fontSize: '14px',
    },

    label: {
      background: Colors.accent,
      borderRadius: '4px',
      color: 'white',
      display: 'inline-block',
      marginRight: '4px',
      padding: '0 4px',
    },

    sender: {
      color: Colors.accent,
      fontWeight: 'bold',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      whiteSpace: 'nowrap',
    },

    senderIsSelected: {
      color: 'white',
    },

    snippet: {
      opacity: 0.5,
    },

    star: {
      color: 'yellow',
      marginRight: '4px',
      textShadow: `
        -1px -1px 0 #999,
        1px -1px 0 #999,
        -1px 1px 0 #999,
        1px 1px 0 #999,
        -1px 0 0 #999,
        1px 0 0 #999,
        0 1px 0 #999,
        0 -1px 0 #999
      `,
    },
  },
};

module.exports = BlockMessageList;
<commit_msg>Fix message date style<commit_after>/** @flow */

var Colors = require('./Colors');
var LineClamp = require('./LineClamp');
var React = require('react/addons');
var RelativeDate = require('./RelativeDate');
var _ = require('lodash');
var sx = require('./styleSet');

var PureRenderMixin = React.addons.PureRenderMixin;
var PropTypes = React.PropTypes;

var BlockMessageList = React.createClass({
  propTypes: {
    messages: PropTypes.array.isRequired,

    labels: PropTypes.array,
    selectedMessageID: PropTypes.string,
  },

  mixins: [PureRenderMixin],

  _onMessageClick(index: number, message: string) {
    this.props.onMessageSelected(message);
  },

  render(): any {
    return (

        {this.props.messages.map((msg, index) => (
          <BlockMessageListItem
            index={index}
            isSelected={msg.id === this.props.selectedMessageID}
            key={index}
            labels={this.props.labels && _.indexBy(this.props.labels, 'id')}
            message={msg}
            onClick={this._onMessageClick}
          />
        ))}

    );
  }
});

var BlockMessageListItem = React.createClass({
  propTypes: {
    index: PropTypes.number.isRequired,
    isSelected: PropTypes.bool.isRequired,
    message: PropTypes.object.isRequired,
    onClick: PropTypes.func.isRequired,

    labels: PropTypes.object,
  },

  mixins: [PureRenderMixin],

  _onClick() {
    this.props.onClick(this.props.index, this.props.message);
  },

  render(): any {
    var msg = this.props.message;
    return (

              {msg.isStarred ? (
                {'\u2605'}
              ) : null}
              {msg.from.name || msg.from.email}

            <RelativeDate
              style={styles.item.date}
              date={msg.date}
            />

          <LineClamp style={styles.item.text} lines={2}>
            {this.props.labels && msg.labelIDs.filter(labelID =>
              this.props.labels[labelID].type === 'user'
            ).map(labelID =>

                {this.props.labels ? this.props.labels[labelID].name : labelID}

            )}

              {msg.subject}{' '}

              {_.unescape(msg.snippet)}…

          </LineClamp>

    );
  }
});

var styles = {
  list: {
    root: {
      cursor: 'pointer',
      userSelect: 'none',
    }
  },

  item: {
    root: {
      lineHeight: 1.6,
      margin: '0 8px 8px 8px',
    },

    rootFirst: {
      borderTop: 'none',
    },

    inner: {
      borderRadius: '8px',
      padding: '8px 12px 12px 12px',
    },

    innerIsUnread: {
      background: Colors.accent.lighten(40),
    },

    innerIsSelected: {
      background: Colors.accent,
      color: 'white',
    },

    top: {
      display: 'flex',
    },

    date: {
      flex: 1,
      fontSize: '14px',
      opacity: 0.5,
      textAlign: 'right',
    },

    text: {
      fontSize: '14px',
    },

    label: {
      background: Colors.accent,
      borderRadius: '4px',
      color: 'white',
      display: 'inline-block',
      marginRight: '4px',
      padding: '0 4px',
    },

    sender: {
      color: Colors.accent,
      fontWeight: 'bold',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      whiteSpace: 'nowrap',
    },

    senderIsSelected: {
      color: 'white',
    },

    snippet: {
      opacity: 0.5,
    },

    star: {
      color: 'yellow',
      marginRight: '4px',
      textShadow: `
        -1px -1px 0 #999,
        1px -1px 0 #999,
        -1px 1px 0 #999,
        1px 1px 0 #999,
        -1px 0 0 #999,
        1px 0 0 #999,
        0 1px 0 #999,
        0 -1px 0 #999
      `,
    },
  },
};

module.exports = BlockMessageList;
<|endoftext|>


<commit_before>define([], function() {

  var tiles = {
    // My mapbox tiles
    mapboxNIF: L.tileLayer(
      'http://{s}.tiles.mapbox.com/v3/{user}.{map}/{z}/{x}/{y}.png',
      {
        user: 'nakeditchyfeet',
        map: 'ibm368a5',
        attribution: '© Mapbox © OpenStreetMap'
      }
    ),
    mapboxLeigh: L.tileLayer(
      'http://{s}.tiles.mapbox.com/v3/{user}.{map}/{z}/{x}/{y}.png',
      {
        user: 'nakeditchyfeet',
        map: 'iff212lb',
        attribution: '© Mapbox © OpenStreetMap'
      }
    ),
    // Thunderforest.Landscape (from http://leaflet-extras.github.io/leaflet-providers/preview/index.html)
    thunderforestLandscape: L.tileLayer('http://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png', {
      attribution: '© OpenCycleMap, © OpenStreetMap contributors, CC-BY-SA'
    }),
    thunderforestOutdoors: L.tileLayer('http://{s}.tile.thunderforest.com/outdoors/{z}/{x}/{y}.png', {
      attribution: '© OpenCycleMap, © OpenStreetMap contributors, CC-BY-SA'
    }),
    // Stamen.Watercolor (from http://leaflet-extras.github.io/leaflet-providers/preview/index.html)
    stamenWatercolor: L.tileLayer('http://{s}.tile.stamen.com/watercolor/{z}/{x}/{y}.jpg', {
      attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap contributors, CC-BY-SA',
      subdomains: 'abcd',
      minZoom: 3,
      maxZoom: 16
    }),
    // Esri.WorldPhysical (from http://leaflet-extras.github.io/leaflet-providers/preview/index.html)
    esriWorldPhysical: L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Physical_Map/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles © Esri — Source: US National Park Service',
      maxZoom: 8
    }),
    esriWorldTopoMap: L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ, TomTom, Intermap, iPC, USGS, FAO, NPS, NRCAN, GeoBase, Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri China (Hong Kong), and the GIS User Community'
    }),
    esriWorldImagery: L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
    }),
    esriOceanBasemap: L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles © Esri — Sources: GEBCO, NOAA, CHS, OSU, UNH, CSUMB, National Geographic, DeLorme, NAVTEQ, and Esri',
      maxZoom: 13
    }),
    esriNatGeo: L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles © Esri — National Geographic, Esri, DeLorme, NAVTEQ, UNEP-WCMC, USGS, NASA, ESA, METI, NRCAN, GEBCO, NOAA, iPC',
      maxZoom: 16
    }),
    acetateTerrain: L.tileLayer('http://a{s}.acetate.geoiq.com/tiles/terrain/{z}/{x}/{y}.png', {
      attribution: '©2012 Esri & Stamen, Data from OSM and Natural Earth',
      subdomains: '0123',
      minZoom: 2,
      maxZoom: 18
    }),
    acetateAll: L.tileLayer('http://a{s}.acetate.geoiq.com/tiles/acetate-hillshading/{z}/{x}/{y}.png', {
      attribution: '©2012 Esri & Stamen, Data from OSM and Natural Earth',
      subdomains: '0123',
      minZoom: 2,
      maxZoom: 18
    }),
    openStreetMapHot: L.tileLayer('http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
      attribution: '© OpenStreetMap contributors, CC-BY-SA, Tiles courtesy of Humanitarian OpenStreetMap Team'
    })
  };

  // return tiles.mapboxNIF;
  // return tiles.thunderforestLandscape;
  // return tiles.thunderforestOutdoors;
  // return tiles.stamenWatercolor;
  // return tiles.esriWorldPhysical;
  // return tiles.esriWorldTopoMap;
  // return tiles.esriWorldImagery;
  // return tiles.esriOceanBasemap;
  // return tiles.esriNatGeo;
  // return tiles.acetateTerrain;
  // return tiles.acetateAll;
  // return tiles.openStreetMapHot;
  return tiles.mapboxLeigh;

});<commit_msg>Switch to a tile set for the map which isn't broken.<commit_after>define([], function() {

  var tiles = {
    // My mapbox tiles
    mapboxNIF: L.tileLayer(
      'http://{s}.tiles.mapbox.com/v3/{user}.{map}/{z}/{x}/{y}.png',
      {
        user: 'nakeditchyfeet',
        map: 'ibm368a5',
        attribution: '© Mapbox © OpenStreetMap'
      }
    ),
    mapboxLeigh: L.tileLayer(
      'http://{s}.tiles.mapbox.com/v3/{user}.{map}/{z}/{x}/{y}.png',
      {
        user: 'nakeditchyfeet',
        map: 'iff212lb',
        attribution: '© Mapbox © OpenStreetMap'
      }
    ),
    // Thunderforest.Landscape (from http://leaflet-extras.github.io/leaflet-providers/preview/index.html)
    thunderforestLandscape: L.tileLayer('http://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png', {
      attribution: '© OpenCycleMap, © OpenStreetMap contributors, CC-BY-SA'
    }),
    thunderforestOutdoors: L.tileLayer('http://{s}.tile.thunderforest.com/outdoors/{z}/{x}/{y}.png', {
      attribution: '© OpenCycleMap, © OpenStreetMap contributors, CC-BY-SA'
    }),
    // Stamen.Watercolor (from http://leaflet-extras.github.io/leaflet-providers/preview/index.html)
    stamenWatercolor: L.tileLayer('http://{s}.tile.stamen.com/watercolor/{z}/{x}/{y}.jpg', {
      attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap contributors, CC-BY-SA',
      subdomains: 'abcd',
      minZoom: 3,
      maxZoom: 16
    }),
    // Esri.WorldPhysical (from http://leaflet-extras.github.io/leaflet-providers/preview/index.html)
    esriWorldPhysical: L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Physical_Map/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles © Esri — Source: US National Park Service',
      maxZoom: 8
    }),
    esriWorldTopoMap: L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ, TomTom, Intermap, iPC, USGS, FAO, NPS, NRCAN, GeoBase, Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri China (Hong Kong), and the GIS User Community'
    }),
    esriWorldImagery: L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
    }),
    esriOceanBasemap: L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles © Esri — Sources: GEBCO, NOAA, CHS, OSU, UNH, CSUMB, National Geographic, DeLorme, NAVTEQ, and Esri',
      maxZoom: 13
    }),
    esriNatGeo: L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles © Esri — National Geographic, Esri, DeLorme, NAVTEQ, UNEP-WCMC, USGS, NASA, ESA, METI, NRCAN, GEBCO, NOAA, iPC',
      maxZoom: 16
    }),
    acetateTerrain: L.tileLayer('http://a{s}.acetate.geoiq.com/tiles/terrain/{z}/{x}/{y}.png', {
      attribution: '©2012 Esri & Stamen, Data from OSM and Natural Earth',
      subdomains: '0123',
      minZoom: 2,
      maxZoom: 18
    }),
    acetateAll: L.tileLayer('http://a{s}.acetate.geoiq.com/tiles/acetate-hillshading/{z}/{x}/{y}.png', {
      attribution: '©2012 Esri & Stamen, Data from OSM and Natural Earth',
      subdomains: '0123',
      minZoom: 2,
      maxZoom: 18
    }),
    openStreetMapHot: L.tileLayer('http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
      attribution: '© OpenStreetMap contributors, CC-BY-SA, Tiles courtesy of Humanitarian OpenStreetMap Team'
    })
  };

  // return tiles.mapboxNIF;
  // return tiles.thunderforestLandscape;
  // return tiles.thunderforestOutdoors;
  // return tiles.stamenWatercolor;
  return tiles.esriWorldPhysical;
  // return tiles.esriWorldTopoMap;
  // return tiles.esriWorldImagery;
  // return tiles.esriOceanBasemap;
  // return tiles.esriNatGeo;
  // return tiles.acetateTerrain;
  // return tiles.acetateAll;
  // return tiles.openStreetMapHot;
  // return tiles.mapboxLeigh;

});
<|endoftext|>


<commit_before>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import Box from 'grommet/components/Box';
import Responsive from 'grommet/utils/Responsive';
import IndexPropTypes from '../utils/PropTypes';
import IndexTable from './Table';
import IndexTiles from './Tiles';
import IndexList from './List';
import IndexHeader from './Header';
import Intl from 'grommet/utils/Intl';

const CLASS_ROOT = 'index';

const VIEW_COMPONENT = {
  list: IndexList,
  tiles: IndexTiles,
  table: IndexTable
};

export default class Index extends Component {

  constructor () {
    super();
    this._onResponsive = this._onResponsive.bind(this);
    this.state = { responsiveSize: 'medium' };
  }

  componentDidMount () {
    this._responsive = Responsive.start(this._onResponsive);
  }

  componentWillUnmount () {
    this._responsive.stop();
  }

  _onResponsive (small) {
    this.setState({ responsiveSize: (small ? 'small' : 'medium') });
  }

  render () {
    const { result, notifications } = this.props;
    let { data } = this.props;

    if (result) {
      console.warn('\'result\' prop has been renamed to \'data.\'' +
        ' Support for \'result\' will be removed in a future release.');
      data = result;
    }

    var classes = [CLASS_ROOT];
    if (this.props.className) {
      classes.push(this.props.className);
    }

    let error;
    if (data && data.error) {
      error = (
        <div className={`${CLASS_ROOT}__error`}>
          {result.error}

      );
    }

    let empty;
    if (data) {
      let emptyMessage;
      let addControl;
      if (data.unfilteredTotal === 0) {
        emptyMessage = this.props.emptyMessage;
        if (this.props.emptyAddControl) {
          addControl = this.props.emptyAddControl;
        } else {
          addControl = this.props.addControl;
        }
      } else if (data.total === 0) {
        emptyMessage = Intl.getMessage(this.context.intl, 'No matches');
      }
      if (emptyMessage) {
        empty = (
          <Box className={`${CLASS_ROOT}__empty`}
            pad={{horizontal: 'medium', vertical: 'large', between: 'medium'}}
            justify="center" align="center">
            {emptyMessage}
            {addControl}
          </Box>
        );
      }
    }

    let view = this.props.view;
    let itemComponent = this.props.itemComponent;
    if (typeof view === 'object') {
      view = view[this.state.responsiveSize];
    }
    if (typeof itemComponent === 'object') {
      itemComponent = itemComponent[this.state.responsiveSize];
    }
    const ViewComponent = VIEW_COMPONENT[view];

    return (

        <div className={`${CLASS_ROOT}__container`}>
          <IndexHeader className={`${CLASS_ROOT}__header`}
            label={this.props.label}
            attributes={this.props.attributes}
            filterDirection={this.props.filterDirection}
            filter={this.props.filter} onFilter={this.props.onFilter}
            query={this.props.query} onQuery={this.props.onQuery}
            sort={this.props.sort} onSort={this.props.onSort}
            data={data}
            fixed={this.props.fixed}
            addControl={this.props.addControl}
            navControl={this.props.navControl} />
          {error}
          {notifications}
          <div ref="items" className={`${CLASS_ROOT}__items`}>
            <ViewComponent
              actions={this.props.actions}
              attributes={this.props.attributes}
              fill={this.props.fill}
              flush={this.props.flush}
              itemComponent={itemComponent}
              data={data}
              sections={this.props.sections}
              selection={this.props.selection}
              size={this.props.size}
              sort={this.props.sort}
              onSelect={this.props.onSelect}
              onMore={this.props.onMore} />
            {empty}

    );
  }

}

Index.propTypes = {
  actions: PropTypes.element,
  addControl: PropTypes.node,
  attributes: IndexPropTypes.attributes,
  data: IndexPropTypes.data,
  emptyMessage: PropTypes.string,
  emptyAddControl: PropTypes.node,
  fill: PropTypes.bool, // for Tiles
  filter: PropTypes.object, // { name: [value, ...] }
  filterDirection: PropTypes.oneOf(['row', 'column']),
  fixed: PropTypes.bool,
  flush: PropTypes.bool, // for Tiles
  itemComponent: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.shape({
      medium: PropTypes.func,
      small: PropTypes.func
    })
  ]),
  label: PropTypes.string,
  navControl: PropTypes.node,
  notifications: PropTypes.node,
  onFilter: PropTypes.func, // (filter)
  onMore: PropTypes.func,
  onQuery: PropTypes.func, // (query)
  onSelect: PropTypes.func,
  onSort: PropTypes.func, // (sort)
  query: PropTypes.object, // Query
  selection: PropTypes.oneOfType([
    PropTypes.string, // uri
    PropTypes.arrayOf(PropTypes.string)
  ]),
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  sort: PropTypes.string,
  view: PropTypes.oneOfType([
    PropTypes.oneOf(["table", "tiles", "list"]),
    PropTypes.shape({
      medium: PropTypes.oneOf(["table", "tiles", "list"]),
      small: PropTypes.oneOf(["table", "tiles", "list"])
    })
  ])
};

Index.defaultProps = {
  attributes: [{name: 'name', label: 'Name', index: 0}],
  filterDirection: 'column',
  fixed: true,
  flush: true,
  view: "tiles"
};

Index.contextTypes = {
  intl: PropTypes.object
};
<commit_msg>allow any node in emptyMessage prop<commit_after>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import Box from 'grommet/components/Box';
import Responsive from 'grommet/utils/Responsive';
import IndexPropTypes from '../utils/PropTypes';
import IndexTable from './Table';
import IndexTiles from './Tiles';
import IndexList from './List';
import IndexHeader from './Header';
import Intl from 'grommet/utils/Intl';

const CLASS_ROOT = 'index';

const VIEW_COMPONENT = {
  list: IndexList,
  tiles: IndexTiles,
  table: IndexTable
};

export default class Index extends Component {

  constructor () {
    super();
    this._onResponsive = this._onResponsive.bind(this);
    this.state = { responsiveSize: 'medium' };
  }

  componentDidMount () {
    this._responsive = Responsive.start(this._onResponsive);
  }

  componentWillUnmount () {
    this._responsive.stop();
  }

  _onResponsive (small) {
    this.setState({ responsiveSize: (small ? 'small' : 'medium') });
  }

  render () {
    const { result, notifications } = this.props;
    let { data } = this.props;

    if (result) {
      console.warn('\'result\' prop has been renamed to \'data.\'' +
        ' Support for \'result\' will be removed in a future release.');
      data = result;
    }

    var classes = [CLASS_ROOT];
    if (this.props.className) {
      classes.push(this.props.className);
    }

    let error;
    if (data && data.error) {
      error = (
        <div className={`${CLASS_ROOT}__error`}>
          {result.error}

      );
    }

    let empty;
    if (data) {
      let emptyMessage;
      let addControl;
      if (data.unfilteredTotal === 0) {
        emptyMessage = this.props.emptyMessage;
        if (this.props.emptyAddControl) {
          addControl = this.props.emptyAddControl;
        } else {
          addControl = this.props.addControl;
        }
      } else if (data.total === 0) {
        emptyMessage = Intl.getMessage(this.context.intl, 'No matches');
      }
      if (emptyMessage) {
        empty = (
          <Box className={`${CLASS_ROOT}__empty`}
            pad={{horizontal: 'medium', vertical: 'large', between: 'medium'}}
            justify="center" align="center">
            {emptyMessage}
            {addControl}
          </Box>
        );
      }
    }

    let view = this.props.view;
    let itemComponent = this.props.itemComponent;
    if (typeof view === 'object') {
      view = view[this.state.responsiveSize];
    }
    if (typeof itemComponent === 'object') {
      itemComponent = itemComponent[this.state.responsiveSize];
    }
    const ViewComponent = VIEW_COMPONENT[view];

    return (

        <div className={`${CLASS_ROOT}__container`}>
          <IndexHeader className={`${CLASS_ROOT}__header`}
            label={this.props.label}
            attributes={this.props.attributes}
            filterDirection={this.props.filterDirection}
            filter={this.props.filter} onFilter={this.props.onFilter}
            query={this.props.query} onQuery={this.props.onQuery}
            sort={this.props.sort} onSort={this.props.onSort}
            data={data}
            fixed={this.props.fixed}
            addControl={this.props.addControl}
            navControl={this.props.navControl} />
          {error}
          {notifications}
          <div ref="items" className={`${CLASS_ROOT}__items`}>
            <ViewComponent
              actions={this.props.actions}
              attributes={this.props.attributes}
              fill={this.props.fill}
              flush={this.props.flush}
              itemComponent={itemComponent}
              data={data}
              sections={this.props.sections}
              selection={this.props.selection}
              size={this.props.size}
              sort={this.props.sort}
              onSelect={this.props.onSelect}
              onMore={this.props.onMore} />
            {empty}

    );
  }

}

Index.propTypes = {
  actions: PropTypes.element,
  addControl: PropTypes.node,
  attributes: IndexPropTypes.attributes,
  data: IndexPropTypes.data,
  emptyMessage: PropTypes.node,
  emptyAddControl: PropTypes.node,
  fill: PropTypes.bool, // for Tiles
  filter: PropTypes.object, // { name: [value, ...] }
  filterDirection: PropTypes.oneOf(['row', 'column']),
  fixed: PropTypes.bool,
  flush: PropTypes.bool, // for Tiles
  itemComponent: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.shape({
      medium: PropTypes.func,
      small: PropTypes.func
    })
  ]),
  label: PropTypes.string,
  navControl: PropTypes.node,
  notifications: PropTypes.node,
  onFilter: PropTypes.func, // (filter)
  onMore: PropTypes.func,
  onQuery: PropTypes.func, // (query)
  onSelect: PropTypes.func,
  onSort: PropTypes.func, // (sort)
  query: PropTypes.object, // Query
  selection: PropTypes.oneOfType([
    PropTypes.string, // uri
    PropTypes.arrayOf(PropTypes.string)
  ]),
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  sort: PropTypes.string,
  view: PropTypes.oneOfType([
    PropTypes.oneOf(["table", "tiles", "list"]),
    PropTypes.shape({
      medium: PropTypes.oneOf(["table", "tiles", "list"]),
      small: PropTypes.oneOf(["table", "tiles", "list"])
    })
  ])
};

Index.defaultProps = {
  attributes: [{name: 'name', label: 'Name', index: 0}],
  filterDirection: 'column',
  fixed: true,
  flush: true,
  view: "tiles"
};

Index.contextTypes = {
  intl: PropTypes.object
};
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name Pear2Pear.controller:ChatCtrl
 * @description
 * # Chat Ctrl
 * Show Chat for a given project
 */

angular.module('Pear2Pear')
  .config(['$routeProvider', function($routeProvider) {
    $routeProvider
      .when('/projects/:id/chat', {
        templateUrl: 'chat/show.html',
        controller: 'ChatCtrl'
      });
  }])
  .controller('ChatCtrl', ['pear', '$scope', '$rootScope', '$route', function(pear, $scope, $rootScope, $route){

    $scope.id = $route.current.params.id;
    $scope.userId = $rootScope.userId;

    $scope.chat = {_new : ''};

    pear.onLoad(function(){
        $scope.project = pear.projects.find($scope.id);
        $scope.projects = pear.projects.all();
    });

    $scope.send = function(){
      pear.addChatMessage($scope.id, $scope.chat._new, $scope.userId);
    };

    // Should use activeLinks, but https://github.com/mcasimir/mobile-angular-ui/issues/262
    $scope.nav = function(id) {
      return id === 'chat' ? 'active' : '';
    };
  }]);
<commit_msg>uses login name for coloring messages. Easy now to work on #7<commit_after>'use strict';

/**
 * @ngdoc function
 * @name Pear2Pear.controller:ChatCtrl
 * @description
 * # Chat Ctrl
 * Show Chat for a given project
 */

angular.module('Pear2Pear')
  .config(['$routeProvider', function($routeProvider) {
    $routeProvider
      .when('/projects/:id/chat', {
        templateUrl: 'chat/show.html',
        controller: 'ChatCtrl'
      });
  }])
  .controller('ChatCtrl', ['pear', '$scope', '$rootScope', '$route', function(pear, $scope, $rootScope, $route){

    $scope.id = $route.current.params.id;
    $scope.userId = $rootScope.userId;
    $scope.chat = {_new : ''};

    pear.onLoad(function(){
        $scope.project = pear.projects.find($scope.id);
        $scope.projects = pear.projects.all();
    });

    $scope.send = function(){
      pear.addChatMessage($scope.id, $scope.chat._new, $scope.userId);
    };

    // Should use activeLinks, but https://github.com/mcasimir/mobile-angular-ui/issues/262
    $scope.nav = function(id) {
      return id === 'chat' ? 'active' : '';
    };
  }]);
<|endoftext|>