<commit_before>/* @flow */

import React from 'react'
import ReactTable from 'sb-react-table'
import ResizableBox from 'react-resizable-box'
import { $range, severityNames, sortMessages, visitMessage, openExternally, getPathOfMessage } from '../helpers'
import type Delegate from './delegate'
import type { LinterMessage } from '../types'

export default class PanelComponent extends React.Component {
  props: {
    delegate: Delegate,
  };
  state: {
    messages: Array<LinterMessage>,
    visibility: boolean,
    tempHeight: ?number,
  };
  constructor(props: Object, context: ?Object) {
    super(props, context)
    this.state = {
      messages: this.props.delegate.filteredMessages,
      visibility: this.props.delegate.visibility,
      tempHeight: null,
    }
  }
  componentDidMount() {
    this.props.delegate.onDidChangeMessages((messages) => {
      this.setState({ messages })
    })
    this.props.delegate.onDidChangeVisibility((visibility) => {
      this.setState({ visibility })
    })
    this.props.delegate.onDidChangePanelConfig(() => {
      this.setState({ tempHeight: null })
    })
  }
  onClick = (e: MouseEvent, row: LinterMessage) => {
    if (process.platform === 'darwin' ? e.metaKey : e.ctrlKey) {
      if (e.shiftKey) {
        openExternally(row)
      } else {
        visitMessage(row, true)
      }
    } else {
      visitMessage(row)
    }
  }
  onResize = (direction: 'top', size: { width: number, height: number }) => {
    this.setState({ tempHeight: size.height })
  }
  onResizeStop = (direction: 'top', size: { width: number, height: number }) => {
    this.props.delegate.updatePanelHeight(size.height)
  }
  render() {
    const { delegate } = this.props
    const columns = [
      { key: 'severity', label: 'Severity', sortable: true },
      { key: 'linterName', label: 'Provider', sortable: true },
      { key: 'excerpt', label: 'Description' },
      { key: 'line', label: 'Line', sortable: true, onClick: this.onClick },
    ]
    if (delegate.panelRepresents === 'Entire Project') {
      columns.push({ key: 'file', label: 'File', sortable: true, onClick: this.onClick })
    }

    let height
    const customStyle: Object = { overflowY: 'scroll' }
    if (this.state.tempHeight) {
      height = this.state.tempHeight
    } else if (delegate.panelTakesMinimumHeight) {
      height = 'auto'
      customStyle.maxHeight = delegate.panelHeight
    } else {
      height = delegate.panelHeight
    }
    delegate.setPanelVisibility(this.state.visibility && (!delegate.panelTakesMinimumHeight || !!this.state.messages.length))

    return (
      <ResizableBox isResizable={{ top: true }} onResize={this.onResize} onResizeStop={this.onResizeStop} height={height} width="auto" customStyle={customStyle}>

          <ReactTable
            rows={this.state.messages}
            columns={columns}

            initialSort={[{ column: 'severity', type: 'desc' }, { column: 'file', type: 'asc' }, { column: 'line', type: 'asc' }]}
            sort={sortMessages}
            rowKey={i => i.key}

            renderHeaderColumn={i => i.label}
            renderBodyColumn={PanelComponent.renderRowColumn}

            style={{ width: '100%' }}
            className="linter"
          />

      </ResizableBox>
    )
  }
  static renderRowColumn(row: LinterMessage, column: string): string | Object {
    const range = $range(row)

    switch (column) {
      case 'file':
        return getPathOfMessage(row)
      case 'line':
        return range ? `${range.start.row + 1}:${range.start.column + 1}` : ''
      case 'excerpt':
        if (row.version === 1) {
          if (row.html) {
            return
          }
          return row.text || ''
        }
        return row.excerpt
      case 'severity':
        return severityNames[row.severity]
      default:
        return row[column]
    }
  }
}
<commit_msg>:new: Make description in panel clickable<commit_after>/* @flow */

import React from 'react'
import ReactTable from 'sb-react-table'
import ResizableBox from 'react-resizable-box'
import { $range, severityNames, sortMessages, visitMessage, openExternally, getPathOfMessage } from '../helpers'
import type Delegate from './delegate'
import type { LinterMessage } from '../types'

export default class PanelComponent extends React.Component {
  props: {
    delegate: Delegate,
  };
  state: {
    messages: Array<LinterMessage>,
    visibility: boolean,
    tempHeight: ?number,
  };
  constructor(props: Object, context: ?Object) {
    super(props, context)
    this.state = {
      messages: this.props.delegate.filteredMessages,
      visibility: this.props.delegate.visibility,
      tempHeight: null,
    }
  }
  componentDidMount() {
    this.props.delegate.onDidChangeMessages((messages) => {
      this.setState({ messages })
    })
    this.props.delegate.onDidChangeVisibility((visibility) => {
      this.setState({ visibility })
    })
    this.props.delegate.onDidChangePanelConfig(() => {
      this.setState({ tempHeight: null })
    })
  }
  onClick = (e: MouseEvent, row: LinterMessage) => {
    if (process.platform === 'darwin' ? e.metaKey : e.ctrlKey) {
      if (e.shiftKey) {
        openExternally(row)
      } else {
        visitMessage(row, true)
      }
    } else {
      visitMessage(row)
    }
  }
  onResize = (direction: 'top', size: { width: number, height: number }) => {
    this.setState({ tempHeight: size.height })
  }
  onResizeStop = (direction: 'top', size: { width: number, height: number }) => {
    this.props.delegate.updatePanelHeight(size.height)
  }
  render() {
    const { delegate } = this.props
    const columns = [
      { key: 'severity', label: 'Severity', sortable: true },
      { key: 'linterName', label: 'Provider', sortable: true },
      { key: 'excerpt', label: 'Description', onClick: this.onClick },
      { key: 'line', label: 'Line', sortable: true, onClick: this.onClick },
    ]
    if (delegate.panelRepresents === 'Entire Project') {
      columns.push({ key: 'file', label: 'File', sortable: true, onClick: this.onClick })
    }

    let height
    const customStyle: Object = { overflowY: 'scroll' }
    if (this.state.tempHeight) {
      height = this.state.tempHeight
    } else if (delegate.panelTakesMinimumHeight) {
      height = 'auto'
      customStyle.maxHeight = delegate.panelHeight
    } else {
      height = delegate.panelHeight
    }
    delegate.setPanelVisibility(this.state.visibility && (!delegate.panelTakesMinimumHeight || !!this.state.messages.length))

    return (
      <ResizableBox isResizable={{ top: true }} onResize={this.onResize} onResizeStop={this.onResizeStop} height={height} width="auto" customStyle={customStyle}>

          <ReactTable
            rows={this.state.messages}
            columns={columns}

            initialSort={[{ column: 'severity', type: 'desc' }, { column: 'file', type: 'asc' }, { column: 'line', type: 'asc' }]}
            sort={sortMessages}
            rowKey={i => i.key}

            renderHeaderColumn={i => i.label}
            renderBodyColumn={PanelComponent.renderRowColumn}

            style={{ width: '100%' }}
            className="linter"
          />

      </ResizableBox>
    )
  }
  static renderRowColumn(row: LinterMessage, column: string): string | Object {
    const range = $range(row)

    switch (column) {
      case 'file':
        return getPathOfMessage(row)
      case 'line':
        return range ? `${range.start.row + 1}:${range.start.column + 1}` : ''
      case 'excerpt':
        if (row.version === 1) {
          if (row.html) {
            return
          }
          return row.text || ''
        }
        return row.excerpt
      case 'severity':
        return severityNames[row.severity]
      default:
        return row[column]
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

console.log('Welcome to Paradise');
<commit_msg>Add base REPL<commit_after>'use strict';

var repl = require('repl');

var server = repl.start({
    prompt: 'PARADISE> '
});
<|endoftext|>


<commit_before>
(function(){
  var Map = this.propublica.Map = function(data){
    this.data   = data;
  };

  Map.prototype.select = Map.prototype.filter = function(/* keys */){
    var args = [].slice.call(arguments);

    return new FeatureCollection(this.data).filter(args);
  };

  Map.prototype.all = function(){
    return new FeatureCollection(this.data);
  };

  var bounds = function(){
    this.min = [Infinity, Infinity];
    this.max = [-Infinity, -Infinity];
    this.each(function(geom){
      var min  = geom.min;
      var max  = geom.max;
      minMax(this.min, this.max, min, max);
    });
  };

  var minMax = function(min, max, omin, omax) {
    min[0] = Math.min(min[0], omin[0]);
    min[1] = Math.min(min[1], omin[1]);
    max[0] = Math.max(max[0], omax[0]);
    max[1] = Math.max(max[1], omax[1]);
  };

  var ctor = function(){};
  var inherits = function(child, parent){
    ctor.prototype  = parent.prototype;
    child.prototype = new ctor();
    child.prototype.constructor = child;
  };

  var Geom = function(data){
    this._data = data;
    this._parse();
    this._bounds();
  };
  Geom.prototype._bounds = function(){ bounds.call(this); };
  Geom.prototype.each = function(cb){
    _.each(this._data, _.bind(cb, this));
  };

  Geom.prototype.map = function(cb){
    return _.map(this._data, _.bind(cb, this));
  };

  Geom.prototype._parse = function(){
    this._data = this.map(function(data){ return new this.child(data); });
  };

  Geom.prototype.project = function(cb){
    this.each(function(it) { it.project(cb); });
  };

  Geom.prototype.asSVG = function(cb){
    return this.map(function(it){ return it.asSVG(cb); }).join(" ");
  };

  var toJSON = function(){
    return _.clone(this._raw);
  };

  Geom.prototype.toJSON = toJSON;

  var Point = function(data){
    this._raw  = data;
    this._data = data;
    this.max   = data;
    this.min   = data;
  };

  Point.prototype.project = function(cb){
    this._data = cb.call(this, this._data);
  };

  Point.prototype.asSVG = function(cb, prefix){
    prefix = prefix || 'L';
    var data = this._data;
    if(cb) data = cb(_.clone(this._data));
    return prefix + data[0] + ", " + data[1];
  };

  var LineString = function(data){
    this._raw = data;
    Geom.call(this, data);
  };
  inherits(LineString, Geom);
  LineString.prototype.child = Point;

  LineString.prototype.asSVG = function(cb){
    return this._data[0].asSVG(cb, 'M') + " " + Geom.prototype.asSVG.call(this, cb);
  };

  var Polygon = function(data){
    this._raw = data;
    Geom.call(this, data.coordinates);
  };
  inherits(Polygon, Geom);
  Polygon.prototype.child = LineString;

  Polygon.prototype.asSVG = function(cb){
    return Geom.prototype.asSVG.call(this, cb) + 'Z';
  };

  var MultiPolygon = function(data){
    this._raw = data;
    Geom.call(this, data.coordinates);
  };
  inherits(MultiPolygon, Geom);
  MultiPolygon.prototype.child = Polygon;

  var geom = function(data){
    switch(data.type){
      case 'Polygon':
        return new Polygon(data);
      case 'MultiPolygon':
        return new MultiPolygon(data);
    }
    throw new Error("Unknown Geometry Type");
  };

  var Feature = function(data){
    this._raw   = data;
    this._props = data.properties;
    this._geom  = geom(data.geometry);
    this._bounds();
  };
  Feature.prototype._bounds = function(){ bounds.call(this); };

  Feature.prototype.each = function(cb){
    cb.call(this, this._geom);
  };

  Feature.prototype.asSVG = function(cb){
    return this._geom.asSVG(cb);
  };

  Feature.prototype.get = function(prop){
    return this._props[prop];
  };

  Feature.prototype.has = function(values){
    if(!_.isArray(values)) values = [values];

    return _.intersection(_.values(this._props), values).length > 0;
  };
  Feature.prototype.toJSON = toJSON;

  var project = function(point, width, height, min, max){
    var lat = point[1];
    var lon = point[0];

    var scale = width / (max[0] - min[0]);
    // Todo fix fudge
    lat = height - ((lat - min[1]) * scale | 0);
    lon = ((lon - min[0]) * scale | 0);
    return [lon, lat];
  };

  var FeatureCollection = function(data){
    var features = data.features;
    this._raw = data;
    this._features = _.map(features, function(feature){ return new Feature(feature); });
    this._bounds();
    this._project = project;
  };

  FeatureCollection.prototype.toJSON = toJSON;

  FeatureCollection.prototype._bounds = function(){ bounds.call(this); };

  FeatureCollection.prototype.setBounds = function(bounds){
    this.min = bounds[0];
    this.max = bounds[1]
    return this;
  };

  FeatureCollection.prototype.getBounds = function(){
    return [this.min, this.max];
  };

  FeatureCollection.prototype.each = function(cb){
    _.each(this._features, _.bind(cb, this));
  };

  FeatureCollection.prototype.filter = function(args){
    var ret = {"type": "FeatureCollection", "features": []};

    _.each(this._features, function(feat){
      if(feat.has(args)) ret.features.push(feat.toJSON());
    });

    return new FeatureCollection(ret, this._proj);
  };

  FeatureCollection.prototype.toJSON = toJSON;

  FeatureCollection.prototype.asSVG = function(width, height, cb){
    var min = this.min;
    var max = this.max;
    var that = this;
    this.each(function(it){
      cb(it.asSVG(function(pt) { return that._project(pt, width, height, min, max); }), it);
    });
  };

  FeatureCollection.prototype.project = function(proj){
    this._project = proj;
  };

  propublica.map = function(data){ return new Map(data); };
}).call(this);
<commit_msg>fleshing out<commit_after>
(function(){
  var Map = this.Mapper = function(data){
    this.data = data;
  };

  Map.prototype.select = Map.prototype.filter = function(/* keys */){
    var args = [].slice.call(arguments);

    return new FeatureCollection(this.data).filter(args);
  };

  Map.prototype.all = function(){
    return new FeatureCollection(this.data);
  };

  var bounds = function(){
    this.min = [Infinity, Infinity];
    this.max = [-Infinity, -Infinity];
    this.each(function(geom){
      var min  = geom.min;
      var max  = geom.max;
      minMax(this.min, this.max, min, max);
    });
  };

  var minMax = function(min, max, omin, omax) {
    min[0] = Math.min(min[0], omin[0]);
    min[1] = Math.min(min[1], omin[1]);
    max[0] = Math.max(max[0], omax[0]);
    max[1] = Math.max(max[1], omax[1]);
  };

  var ctor = function(){};
  var inherits = function(child, parent){
    ctor.prototype  = parent.prototype;
    child.prototype = new ctor();
    child.prototype.constructor = child;
  };

  var Geom = function(data){
    this._data = data;
    this._parse();
    this._bounds();
  };
  Geom.prototype._bounds = function(){ bounds.call(this); };
  Geom.prototype.type = "Geometry";
  Geom.prototype.each = function(cb){
    _.each(this._data, _.bind(cb, this));
  };

  Geom.prototype.map = function(cb){
    return _.map(this._data, _.bind(cb, this));
  };

  Geom.prototype._parse = function(){
    this._data = this.map(function(data){ return new this.child(data); });
  };

  Geom.prototype.children = function(){
    return this._data;
  };

  Geom.prototype.project = function(cb){
    this.each(function(it) { it.project(cb); });
  };

  Geom.prototype.asSVG = function(cb){
    return this.map(function(it){ return it.asSVG(cb); }).join(" ");
  };

  Geom.prototype.is = function(type) {
    return type === this.type;
  };

  var toJSON = function(){
    return _.clone(this._raw);
  };

  Geom.prototype.toJSON = toJSON;

  var Point = function(data){
    this._raw  = data;
    this._data = data;
    this.max   = data;
    this.min   = data;
  };
  Point.prototype.type = "Point";
  Point.prototype.project = function(cb){
    this._data = cb.call(this, this._data);
  };

  Point.prototype.asSVG = function(cb, prefix){
    prefix = prefix || 'L';
    var data = this._data;
    if(cb) data = cb(_.clone(this._data));
    return prefix + data[0] + ", " + data[1];
  };

  Point.prototype.x = Point.prototype.lat = function() {
    return this._data[0];
  };

  Point.prototype.y = Point.prototype.lng = function() {
    return this._data[1];
  };

  Point.prototype.z = Point.prototype.height = function() {
    return this._data[2];
  };

  var LineString = function(data){
    this._raw = data;
    Geom.call(this, data.coordinates || data);
  };
  inherits(LineString, Geom);
  LineString.prototype.child = Point;
  LineString.prototype.type = "LineString";

  LineString.prototype.asSVG = function(cb){
    return this._data[0].asSVG(cb, 'M') + " " + Geom.prototype.asSVG.call(this, cb);
  };

  var Polygon = function(data){
    this._raw = data;
    Geom.call(this, data.coordinates);
  };
  inherits(Polygon, Geom);
  Polygon.prototype.child = LineString;
  Polygon.prototype.type = "Polygon";

  Polygon.prototype.asSVG = function(cb){
    return Geom.prototype.asSVG.call(this, cb) + 'Z';
  };

  var MultiPolygon = function(data){
    this._raw = data;
    Geom.call(this, data.coordinates);
  };
  inherits(MultiPolygon, Geom);
  MultiPolygon.prototype.child = Polygon;
  MultiPolygon.prototype.type = "MultiPolygon";

  var MultiLineString = function(data){
    this._raw = data;
    Geom.call(this, data.coordinates);
  };
  inherits(MultiLineString, Geom);
  MultiLineString.prototype.child = LineString;
  MultiLineString.prototype.type = "MultiLineString";

  var geom = function(data){
    switch(data.type){
      case 'Polygon':
        return new Polygon(data);
      case 'MultiPolygon':
        return new MultiPolygon(data);
      case 'LineString':
        return new LineString(data);
      case 'MultiLineString':
        return new MultiLineString(data);
    }
    throw new Error("Unknown Geometry Type");
  };

  var Feature = function(data){
    this._raw   = data;
    this._props = data.properties;
    this._geom  = geom(data.geometry);
    this._bounds();
  };
  Feature.prototype._bounds = function(){ bounds.call(this); };

  Feature.prototype.each = function(cb){
    cb.call(this, this._geom);
  };

  Feature.prototype.is = function(type) {
    return this._geom.type === type;
  };

  Feature.prototype.asSVG = function(cb){
    return this._geom.asSVG(cb);
  };

  Feature.prototype.geom = function(){
    return this._geom;
  };

  Feature.prototype.get = function(prop){
    return this._props[prop];
  };

  Feature.prototype.has = function(values){
    if(!_.isArray(values)) values = [values];

    return _.intersection(_.values(this._props), values).length > 0;
  };
  Feature.prototype.toJSON = toJSON;

  var project = function(point, width, height, min, max){
    var lat = point[1];
    var lon = point[0];

    var scale = width / (max[0] - min[0]);
    // Todo fix fudge
    lat = height - ((lat - min[1]) * scale | 0);
    lon = ((lon - min[0]) * scale | 0);
    return [lon, lat];
  };

  var FeatureCollection = function(data){
    var features = data.features;
    this._raw = data;
    this._features = _.map(features, function(feature){ return new Feature(feature); });
    this._bounds();
    this._project = project;
  };

  FeatureCollection.prototype.toJSON = toJSON;

  FeatureCollection.prototype._bounds = function(){ bounds.call(this); };

  FeatureCollection.prototype.setBounds = function(bounds){
    this.min = bounds[0];
    this.max = bounds[1];
    return this;
  };

  FeatureCollection.prototype.getBounds = function(){
    return [this.min, this.max];
  };

  FeatureCollection.prototype.each = function(cb){
    _.each(this._features, _.bind(cb, this));
  };

  FeatureCollection.prototype.filter = function(args){
    var ret = {"type": "FeatureCollection", "features": []};

    _.each(this._features, function(feat){
      if(feat.has(args)) ret.features.push(feat.toJSON());
    });

    return new FeatureCollection(ret, this._proj);
  };

  FeatureCollection.prototype.flatten = function(type) {
    var ret = {"type": "FeatureCollection", "features": []};
    var features = this._features;

    var walk = function(ret, features){
      _.each(features, function(feat) {
        console.log(feat)
        if(feat.is(type)) ret.features.push(feat.toJSON());
        walk(ret, feat);
      });
      return ret;
    };

    return new FeatureCollection(walk(ret, this));
  };

  FeatureCollection.prototype.toJSON = toJSON;

  FeatureCollection.prototype.asSVG = function(width, height, cb){
    var min = this.min;
    var max = this.max;
    var that = this;
    this.each(function(it){
      cb(it.asSVG(function(pt) { return that._project(pt, width, height, min, max); }), it);
    });
  };

  FeatureCollection.prototype.project = function(proj){
    this._project = proj;
  };

}).call(this);
<|endoftext|>


<commit_before>var greenColor = '#4fc14e';
var redColor = '#FF5454';
var yellowColor = '#FFAA54';
var blueColor = '#3498DB';

var redStatusImage = "https://rawgithub.com/ccux/airsense/master/Status-1.svg";
var yellowStatusImage = "https://rawgithub.com/ccux/airsense/master/Status-2.svg";
var blueStatusImage = "https://rawgithub.com/ccux/airsense/master/Status-3.svg";
var greenStatusImage = "https://rawgithub.com/ccux/airsense/master/Status-4.svg";

var redIndicator = "https://rawgithub.com/ccux/airsense/master/status-red.svg";
var yellowIndicator = "https://rawgithub.com/ccux/airsense/master/status-yellow.svg";
var blueIndicator = "https://rawgithub.com/ccux/airsense/master/status-blue.svg";
var greenIndicator = "https://rawgithub.com/ccux/airsense/master/status-green.svg";

var status = 0;

var numberOfRooms = 5;
var rooms = [];

var roomNames = ["Living Room",
                "Kitchen",
                "Bedroom",
                "Kids Room",
                "Room"];

var roomIcons = [
                "https://raw.githubusercontent.com/ccux/airsense/master/Living%20room%402x.png",
                "https://raw.githubusercontent.com/ccux/airsense/master/Kitchen%402x.png",
                "https://raw.githubusercontent.com/ccux/airsense/master/Bedroom%402x.png",
                "https://raw.githubusercontent.com/ccux/airsense/master/Children%20Room%402x.png",
                "https://raw.githubusercontent.com/ccux/airsense/master/Office%402x.png"];

function greenStatus () {
//Green status
    document.getElementById("Status-Back-Div").style.backgroundColor = greenColor;
    document.getElementById("Status-Image").src = greenStatusImage;
    document.getElementById("Status-Heading").innerHTML = "GREAT INDOOR CLIMATE";
    document.getElementById("Status-Heading").style.color = greenColor;
    document.getElementById("Status-Heading-Text").innerHTML = "Your home has a great overall indoor climate.";
}

function blueStatus () {
    document.getElementById("Status-Back-Div").style.backgroundColor = blueColor;
    document.getElementById("Status-Image").src = blueStatusImage;
    document.getElementById("Status-Heading").innerHTML = "HEALTHY INDOOR CLIMATE";
    document.getElementById("Status-Heading").style.color = blueColor;
    document.getElementById("Status-Heading-Text").innerHTML = "Your home could need ventilation in " + rooms[0].name + ", but otherwise there is a good overall indoor climate.";
}

function yellowStatus () {
    document.getElementById("Status-Back-Div").style.backgroundColor = yellowColor;
    document.getElementById("Status-Image").src = yellowStatusImage;
    document.getElementById("Status-Heading").innerHTML = "COULD BE IMPROVED";
    document.getElementById("Status-Heading").style.color = yellowColor;
    document.getElementById("Status-Heading-Text").innerHTML = "Your home needs ventilation in your " + rooms[0].name + ", and in " + rooms[1].name + ".";
}

function redStatus () {
    document.getElementById("Status-Back-Div").style.backgroundColor = redColor;
    document.getElementById("Status-Image").src = redStatusImage;
    document.getElementById("Status-Heading").innerHTML = "CRITICAL INDOOR CLIMATE";
    document.getElementById("Status-Heading").style.color = redColor;
    document.getElementById("Status-Heading-Text").innerHTML = "Your home needs ventilation in your " + rooms[0].name + ", and in " + rooms[1].name + ".";
}

//Create a new Room object
function Room() {
    this.name = "";
    this.sensorID = "";
    this.icon = "";
    this.temp = "";
    this.humidity = "";
    this.airqual = "";
    this.sensorDetected = false;
    //Create Room
    //var room = new Room;
}

//Create a random number between 2 parameter values
function randomize (min, max) {
    var result = (Math.floor((Math.random() * (max-min+1) + min)));
    return result;
}

//Create a random temperature between 2 values
function randomizeTemperature () {
    var min = 18;
    var max = 26;
    return (randomize(min, max));
}

//Create a random humidity between 2 values
function randomizeHumidity () {
    var min = 30;
    var max = 80;
    return (randomize(min, max));
}

//Create a random AirQuality between 2 values
function randomizeAirQual () {
    var min = 400;
    var max = 1600;
    return (randomize(min, max));
}

//Create a random Sensor ID
function sensorID()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 12; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

//Create the rooms and add the to the rooms array
function createRooms () {
for (var i = 0; i < numberOfRooms; i++) {
var myRoom = new Room;

if (i <= 3) {
    myRoom.icon = roomIcons[i];
    myRoom.name = roomNames[i];

}
else {
    myRoom.icon = roomIcons[4];
    myRoom.name = "" + roomNames[4] + " " + (i - 3);
}

    myRoom.sensorID = sensorID();
    myRoom.temp = randomizeTemperature();
    myRoom.humidity = randomizeHumidity();

  /*DEMO*/
  if (returnHumidityStatus(myRoom.humidity) > 2)
  {
  myRoom.humidity = randomizeHumidity();
  }

    myRoom.airqual = randomizeAirQual();

  /*DEMO*/
  if (returnAirQualStatus(myRoom.airqual) > 2)
  {
  myRoom.airqual = randomizeAirQual();
  }

    myRoom.sensorDetected = true;

//Add the room to the rooms array
rooms.push(myRoom);
//console.log(rooms);
}
//Sort room array based on
rooms.sort(function(a, b){return getRoomStatus(b)-getRoomStatus(a)});

//Print array
console.log("1 " + getRoomStatus(rooms[0]));
console.log("2 " + getRoomStatus(rooms[1]));
console.log("3 " + getRoomStatus(rooms[2]));
console.log("4 " + getRoomStatus(rooms[3]));
}

function getRoomStatus (room) {

    var midResult = 0;
    var hum = returnHumidityStatus(room.humidity);
    var air = returnAirQualStatus(room.airqual)
    midResult += hum + air;

    return midResult;
}

function calculateOverallStatus () {
//First calculate the individual status of each room based on the three factors
status = 0;

console.log("Status 0: " + status);

var midResult = 0;

for (var i = rooms.length - 1; i >= 0; i--) {

var hum = returnHumidityStatus(rooms[i].humidity);
var air = returnAirQualStatus(rooms[i].airqual)

console.log("Hum status: " + hum);
console.log("Air status: " + air);

midResult += hum + air;

console.log("Status " + i + " " + midResult);
}

status += midResult;

console.log("Status pre /: " + status);

status /= (rooms.length/* * 2*/);

console.log("Total status: " + status);

var color = "";

//If the status is 3 or above
if (status >= 3) {
    redStatus();
}
//Else If the status is above 2
else if (status > 2) {
  yellowStatus();

}
//Else If the status is above 1.5
else if (status >= 1.5) {
  blueStatus();

}
//Else If the status is lass or equal to 1.5
else if (status < 1.5) {
    greenStatus();
}
}

function returnHumidityStatus (value) {

var greenColorMin = 41;
var greenColorMax = 59;
var yellowColorMin = 0;
var yellowColorMax = 40;
var redColorMin = 60;
var redColorMax = 100;

if (value > redColorMin)
{
//console.log('RedColor ', value);
return 3;
}
else if (value > yellowColorMax && value < redColorMin) {
//console.log('GreenColor ', value);
return 0;
}
else {
//console.log('YellowColor ', value);
return 2;
}

}

function returnAirQualStatus (value) {

var greenColorMin = 0;
var greenColorMax = 999;
var yellowColorMin = 1000;
var yellowColorMax = 1299;
var redColorMin = 1300;
var redColorMax = 1600;

if (value > redColorMin)
{
//console.log('RedColor ', value);
return 3;
}
else if (value > greenColorMax && value < redColorMin) {
//console.log('YellowColor ', value);
return 2;
}
else {
//console.log('GreenColor ', value);
return 0;
}
}

function humidityColor (value) {
var colorStatus = returnHumidityStatus(value);

console.log('The Color Value is: ' + value + " - And the Color Status is " + colorStatus);

if (colorStatus >= 3)
{
//console.log('RedColor ', value);
return redColor;
}
else if (colorStatus === 0) {
//console.log('GreenColor ', value);
return greenColor;
}
else if (colorStatus === 2){
//console.log('YellowColor ', value);
return yellowColor;
}
else {
return greenColor;
}
}

function airQualColor (value) {
var colorStatus = returnAirQualStatus(value);
if (colorStatus >= 3)
{
//console.log('RedColor ', value);
return redColor;
}
else if (colorStatus === 0) {
//console.log('GreenColor ', value);
return greenColor;
}
else if (colorStatus === 2){
//console.log('YellowColor ', value);
return yellowColor;
}
else {
return greenColor;
}
}

function returnAirQualStatusImage (value) {
    if (value === redColor) {
        return redIndicator;
    }
    else if (value === yellowColor) {
        return yellowIndicator;
    }
    else {
        return greenIndicator;
    }
}

function setRoomDetailsOnDom () {

//Loop trough the rooms and set the corresponding values
for (var i = rooms.length - 1; i >= 0; i--) {

//Set the name
var roomTitle = document.getElementsByClassName('room-block-title')[i];
//console.log(roomTitle);
roomTitle.innerHTML = rooms[i].name.toUpperCase();

//Set the temperature
var temperature = document.getElementsByClassName('temperature-number')[i];
temperature.innerHTML = rooms[i].temp;

//Set Humidity color
var humidity = document.getElementsByClassName('room-block-humidity')[i];
humidity.innerHTML = rooms[i].humidity + "%";
var statusColor = humidityColor(rooms[i].humidity);
humidity.style.color = statusColor;
console.log("Color is: ", statusColor);
//console.log("TEST " + document.getElementsByClassName('room-block-humidity')[0]);

var roomIcon = document.getElementsByClassName('room-block-icon')[i];
roomIcon.src = rooms[i].icon;

var airQualIcon = document.getElementsByClassName('room-block-airquality-status-image')[i];
var airQualIconSrc = returnAirQualStatusImage(airQualColor(rooms[i].airqual))
airQualIcon.src = airQualIconSrc;
}
}

//Link parsing function
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

// ################################ RUN PROGRAM ##################################################
createRooms();
calculateOverallStatus();
setRoomDetailsOnDom();

//Save the RoomData locally
// Put the object into storage
localStorage.setItem('rooms', JSON.stringify(rooms));

//Set the links of the rooms to pass the romms to the Detail view
var roomDetailLinks = document.getElementsByClassName("room-detail-link");
for (var i = 0; rooms.length > i +1; i++) {
    roomDetailLinks[i].href += "?roomid=" + i;

     console.log("The new link is: ", roomDetailLinks[i].href);
}

var hasLoaded = getParameterByName("loaded");

if (hasLoaded != null) {

console.log("IThe status is loaded", getParameterByName("loaded"));
}
else {
console.log("Is the status lis not loaded");

}

$('document').ready(function(){
         // your code

   });
<commit_msg>Load rooms from memory if from detail<commit_after>var greenColor = '#4fc14e';
var redColor = '#FF5454';
var yellowColor = '#FFAA54';
var blueColor = '#3498DB';

var redStatusImage = "https://rawgithub.com/ccux/airsense/master/Status-1.svg";
var yellowStatusImage = "https://rawgithub.com/ccux/airsense/master/Status-2.svg";
var blueStatusImage = "https://rawgithub.com/ccux/airsense/master/Status-3.svg";
var greenStatusImage = "https://rawgithub.com/ccux/airsense/master/Status-4.svg";

var redIndicator = "https://rawgithub.com/ccux/airsense/master/status-red.svg";
var yellowIndicator = "https://rawgithub.com/ccux/airsense/master/status-yellow.svg";
var blueIndicator = "https://rawgithub.com/ccux/airsense/master/status-blue.svg";
var greenIndicator = "https://rawgithub.com/ccux/airsense/master/status-green.svg";

var status = 0;

var numberOfRooms = 5;
var rooms = [];

var roomNames = ["Living Room",
                "Kitchen",
                "Bedroom",
                "Kids Room",
                "Room"];

var roomIcons = [
                "https://raw.githubusercontent.com/ccux/airsense/master/Living%20room%402x.png",
                "https://raw.githubusercontent.com/ccux/airsense/master/Kitchen%402x.png",
                "https://raw.githubusercontent.com/ccux/airsense/master/Bedroom%402x.png",
                "https://raw.githubusercontent.com/ccux/airsense/master/Children%20Room%402x.png",
                "https://raw.githubusercontent.com/ccux/airsense/master/Office%402x.png"];

function greenStatus () {
//Green status
    document.getElementById("Status-Back-Div").style.backgroundColor = greenColor;
    document.getElementById("Status-Image").src = greenStatusImage;
    document.getElementById("Status-Heading").innerHTML = "GREAT INDOOR CLIMATE";
    document.getElementById("Status-Heading").style.color = greenColor;
    document.getElementById("Status-Heading-Text").innerHTML = "Your home has a great overall indoor climate.";
}

function blueStatus () {
    document.getElementById("Status-Back-Div").style.backgroundColor = blueColor;
    document.getElementById("Status-Image").src = blueStatusImage;
    document.getElementById("Status-Heading").innerHTML = "HEALTHY INDOOR CLIMATE";
    document.getElementById("Status-Heading").style.color = blueColor;
    document.getElementById("Status-Heading-Text").innerHTML = "Your home could need ventilation in " + rooms[0].name + ", but otherwise there is a good overall indoor climate.";
}

function yellowStatus () {
    document.getElementById("Status-Back-Div").style.backgroundColor = yellowColor;
    document.getElementById("Status-Image").src = yellowStatusImage;
    document.getElementById("Status-Heading").innerHTML = "COULD BE IMPROVED";
    document.getElementById("Status-Heading").style.color = yellowColor;
    document.getElementById("Status-Heading-Text").innerHTML = "Your home needs ventilation in your " + rooms[0].name + ", and in " + rooms[1].name + ".";
}

function redStatus () {
    document.getElementById("Status-Back-Div").style.backgroundColor = redColor;
    document.getElementById("Status-Image").src = redStatusImage;
    document.getElementById("Status-Heading").innerHTML = "CRITICAL INDOOR CLIMATE";
    document.getElementById("Status-Heading").style.color = redColor;
    document.getElementById("Status-Heading-Text").innerHTML = "Your home needs ventilation in your " + rooms[0].name + ", and in " + rooms[1].name + ".";
}

//Create a new Room object
function Room() {
    this.name = "";
    this.sensorID = "";
    this.icon = "";
    this.temp = "";
    this.humidity = "";
    this.airqual = "";
    this.sensorDetected = false;
    //Create Room
    //var room = new Room;
}

//Create a random number between 2 parameter values
function randomize (min, max) {
    var result = (Math.floor((Math.random() * (max-min+1) + min)));
    return result;
}

//Create a random temperature between 2 values
function randomizeTemperature () {
    var min = 18;
    var max = 26;
    return (randomize(min, max));
}

//Create a random humidity between 2 values
function randomizeHumidity () {
    var min = 30;
    var max = 80;
    return (randomize(min, max));
}

//Create a random AirQuality between 2 values
function randomizeAirQual () {
    var min = 400;
    var max = 1600;
    return (randomize(min, max));
}

//Create a random Sensor ID
function sensorID()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 12; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

//Create the rooms and add the to the rooms array
function createRooms () {
for (var i = 0; i < numberOfRooms; i++) {
var myRoom = new Room;

if (i <= 3) {
    myRoom.icon = roomIcons[i];
    myRoom.name = roomNames[i];

}
else {
    myRoom.icon = roomIcons[4];
    myRoom.name = "" + roomNames[4] + " " + (i - 3);
}

    myRoom.sensorID = sensorID();
    myRoom.temp = randomizeTemperature();
    myRoom.humidity = randomizeHumidity();

  /*DEMO*/
  if (returnHumidityStatus(myRoom.humidity) > 2)
  {
  myRoom.humidity = randomizeHumidity();
  }

    myRoom.airqual = randomizeAirQual();

  /*DEMO*/
  if (returnAirQualStatus(myRoom.airqual) > 2)
  {
  myRoom.airqual = randomizeAirQual();
  }

    myRoom.sensorDetected = true;

//Add the room to the rooms array
rooms.push(myRoom);
//console.log(rooms);
}
//Sort room array based on
rooms.sort(function(a, b){return getRoomStatus(b)-getRoomStatus(a)});

//Print array
console.log("1 " + getRoomStatus(rooms[0]));
console.log("2 " + getRoomStatus(rooms[1]));
console.log("3 " + getRoomStatus(rooms[2]));
console.log("4 " + getRoomStatus(rooms[3]));
}

function getRoomStatus (room) {

    var midResult = 0;
    var hum = returnHumidityStatus(room.humidity);
    var air = returnAirQualStatus(room.airqual)
    midResult += hum + air;

    return midResult;
}

function calculateOverallStatus () {
//First calculate the individual status of each room based on the three factors
status = 0;

console.log("Status 0: " + status);

var midResult = 0;

for (var i = rooms.length - 1; i >= 0; i--) {

var hum = returnHumidityStatus(rooms[i].humidity);
var air = returnAirQualStatus(rooms[i].airqual)

console.log("Hum status: " + hum);
console.log("Air status: " + air);

midResult += hum + air;

console.log("Status " + i + " " + midResult);
}

status += midResult;

console.log("Status pre /: " + status);

status /= (rooms.length/* * 2*/);

console.log("Total status: " + status);

var color = "";

//If the status is 3 or above
if (status >= 3) {
    redStatus();
}
//Else If the status is above 2
else if (status > 2) {
  yellowStatus();

}
//Else If the status is above 1.5
else if (status >= 1.5) {
  blueStatus();

}
//Else If the status is lass or equal to 1.5
else if (status < 1.5) {
    greenStatus();
}
}

function returnHumidityStatus (value) {

var greenColorMin = 41;
var greenColorMax = 59;
var yellowColorMin = 0;
var yellowColorMax = 40;
var redColorMin = 60;
var redColorMax = 100;

if (value > redColorMin)
{
//console.log('RedColor ', value);
return 3;
}
else if (value > yellowColorMax && value < redColorMin) {
//console.log('GreenColor ', value);
return 0;
}
else {
//console.log('YellowColor ', value);
return 2;
}

}

function returnAirQualStatus (value) {

var greenColorMin = 0;
var greenColorMax = 999;
var yellowColorMin = 1000;
var yellowColorMax = 1299;
var redColorMin = 1300;
var redColorMax = 1600;

if (value > redColorMin)
{
//console.log('RedColor ', value);
return 3;
}
else if (value > greenColorMax && value < redColorMin) {
//console.log('YellowColor ', value);
return 2;
}
else {
//console.log('GreenColor ', value);
return 0;
}
}

function humidityColor (value) {
var colorStatus = returnHumidityStatus(value);

console.log('The Color Value is: ' + value + " - And the Color Status is " + colorStatus);

if (colorStatus >= 3)
{
//console.log('RedColor ', value);
return redColor;
}
else if (colorStatus === 0) {
//console.log('GreenColor ', value);
return greenColor;
}
else if (colorStatus === 2){
//console.log('YellowColor ', value);
return yellowColor;
}
else {
return greenColor;
}
}

function airQualColor (value) {
var colorStatus = returnAirQualStatus(value);
if (colorStatus >= 3)
{
//console.log('RedColor ', value);
return redColor;
}
else if (colorStatus === 0) {
//console.log('GreenColor ', value);
return greenColor;
}
else if (colorStatus === 2){
//console.log('YellowColor ', value);
return yellowColor;
}
else {
return greenColor;
}
}

function returnAirQualStatusImage (value) {
    if (value === redColor) {
        return redIndicator;
    }
    else if (value === yellowColor) {
        return yellowIndicator;
    }
    else {
        return greenIndicator;
    }
}

function setRoomDetailsOnDom () {

//Loop trough the rooms and set the corresponding values
for (var i = rooms.length - 1; i >= 0; i--) {

//Set the name
var roomTitle = document.getElementsByClassName('room-block-title')[i];
//console.log(roomTitle);
roomTitle.innerHTML = rooms[i].name.toUpperCase();

//Set the temperature
var temperature = document.getElementsByClassName('temperature-number')[i];
temperature.innerHTML = rooms[i].temp;

//Set Humidity color
var humidity = document.getElementsByClassName('room-block-humidity')[i];
humidity.innerHTML = rooms[i].humidity + "%";
var statusColor = humidityColor(rooms[i].humidity);
humidity.style.color = statusColor;
console.log("Color is: ", statusColor);
//console.log("TEST " + document.getElementsByClassName('room-block-humidity')[0]);

var roomIcon = document.getElementsByClassName('room-block-icon')[i];
roomIcon.src = rooms[i].icon;

var airQualIcon = document.getElementsByClassName('room-block-airquality-status-image')[i];
var airQualIconSrc = returnAirQualStatusImage(airQualColor(rooms[i].airqual))
airQualIcon.src = airQualIconSrc;
}
}

//Link parsing function
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

// ################################ RUN PROGRAM ##################################################

//Save the RoomData locally
// Put the object into storage
localStorage.setItem('rooms', JSON.stringify(rooms));

//Set the links of the rooms to pass the romms to the Detail view
var roomDetailLinks = document.getElementsByClassName("room-detail-link");
for (var i = 0; rooms.length > i +1; i++) {
    roomDetailLinks[i].href += "?roomid=" + i;

     console.log("The new link is: ", roomDetailLinks[i].href);
}

var hasLoaded = getParameterByName("loaded");

if (hasLoaded != null) {

console.log("The status is already here", getParameterByName("loaded"));

rooms = JSON.parse(localStorage.getItem("rooms"));

}
else {
console.log("The main status has not been loaded");

createRooms();

}

calculateOverallStatus();
setRoomDetailsOnDom();

$('document').ready(function(){
         // your code

   });

<|endoftext|>


<commit_before>// patches
window.performance = window.performance || {};
performance.now = (function() {
    return performance.now       ||
        performance.mozNow    ||
        performance.msNow     ||
        performance.oNow      ||
        performance.webkitNow ||
        Date.now  /*none found - fallback to browser default */
})();

// patches END

var libsw = new LibSpaceWalk();

var path = null;
var trailPath = null;

var ratio = 0;

var data = [];
data.push([]);
currentData = data[0];
var dataCount = 0;
var maxElements = 500;
var latestData = [];
var currentLevel = 0;

var current = null;
var last = null;
var svg;
var counter = null;

var group = null;
var youAreHere = null;
var grid = null;
var gridH = null;
var gridV = null;

var mapGroup = null;
var currentTile = {
	x: 0,
	y: 0,
	width: 0,
	height: 0
}
var mapTileRequested = false;

var bounds = {
	xMin: Number.MAX_VALUE,
	xMax: -Number.MAX_VALUE,
	yMin: Number.MAX_VALUE,
	yMax: -Number.MAX_VALUE,

	width: function() {
		return this.xMax - this.xMin;
	},

	height: function() {
		return this.yMax - this.yMin;
	},

	centerX: function() {
		return (this.xMin + this.xMax) / 2.0;
	},

	centerY: function() {
		return (this.yMin + this.yMax) / 2.0;
	}
}

var updateBounds = function(position, bounds) {
	bounds.xMax = Math.max(bounds.xMax, position.x);
	bounds.xMin = Math.min(bounds.xMin, position.x);
	bounds.yMax = Math.max(bounds.yMax, position.z);
	bounds.yMin = Math.min(bounds.yMin, position.z);

	if (!mapTileRequested && ((bounds.width() * 2) > currentTile.width ||
			(bounds.height() * 2) > currentTile.height)) {
		// request new tile
		// compute bounds of canvas in world coords
		requestMapTile({
			x: bounds.xMin - ((bounds.width() * 0.5) + 5),
			y: bounds.yMin - ((bounds.height() * 0.5) + 5),
			width: bounds.width() + ((bounds.width() * 1.5) + 10),
			height: bounds.height() + ((bounds.height() * 1.5) + 10)
		});

		// mapTileRequested = true;
	}
}

var mapTile = function(json) {
	console.log(json);

	mapGroup.selectAll('image').remove();
	mapGroup.append('image')
		.attr('x', json.x)
		.attr('y', -(json.y + json.height))
		.attr('width', json.width)
		.attr('height', json.height)
		.attr('xlink:href', 'data:' + json.type + ', ' + json.data);

	mapTileRequested = false;
	currentTile = json;

	// debug output
	d3.select('#image img').remove();
	d3.select('#image').append('img')
		.attr('src', 'data:' + json.type + ', ' + json.data);
}

libsw.onMessage = function(message) {
	var sample = message;

	if (sample.type === "mapTile") {
		mapTile(sample.payload);
		return;
	} else if (sample.type === "position") {

		data[0].push(sample.payload);
		latestData.push(sample.payload);

		if ((latestData.length - 2) > dataCount % Math.pow(2, currentLevel)) {
			var last = latestData[latestData.length - 1];
			latestData.length = 0;
			latestData.push(last);
			latestData.push(sample.payload);
		}

		for (var i = 1; i < data.length; i++) {
			if (dataCount % (Math.pow(2, i)) === 0) {
				data[i].push(sample.payload);
			}
		}

		if (data[data.length-1].length > maxElements) {
			currentLevel++;
			data.push([]);
			for (var i = 0; i < data[data.length-2].length; i += 2) {
				data[data.length-1].push(data[data.length-2][i]);
			}
			currentData = data[data.length-1];
			path.datum(currentData);
		}

		dataCount++;

		updateBounds(sample.payload, bounds);

		last = current;
		current = sample;

		update();
		makeGrid(bounds);

		counter.hit();
		counter.print();
	}
};

 var drawPath = function(selection) {
	selection
		.attr('vector-effect', 'inherit')
		.attr('d', d3.svg.line()
			.x(function(d) {return d.x})
			.y(function(d) {return -d.z})
			.interpolate('linear'));
}

var update = function() {

	if (!path) {
		path = group.append('path')
		.datum(currentData)
		.call(drawPath);
	}

	if (!trailPath) {
		trailPath = group.append('path')
		.datum(latestData)
		.call(drawPath);
	}

	path.call(drawPath);
	trailPath.call(drawPath);

	youAreHere.attr('cx', current.x)
		.attr('cy', current.z);

	updateGroup(bounds);
}

var updateGroup = function(bounds) {
	var scale = Math.min(svg.width / bounds.width(), svg.height / bounds.height()) * 0.9;

	group
		// .transition()
		.attr('transform', 'translate(' + (-bounds.centerX() * scale + svg.width / 2) + ' '+
			(bounds.centerY() * scale + svg.height / 2) + ') scale(' + scale + ')');
}

var makeGrid = function(bounds) {

	var size = 3;
	var logStep = Math.pow(size, Math.floor(Math.log(Math.max(bounds.width(), bounds.height())) / Math.log(size)));
	// console.log(logStep);

	var count = Math.ceil(bounds.width() / logStep);
	// console.log(count);

	var anchorV = Math.floor((bounds.xMin - (bounds.width())) / logStep) * logStep;

	var dataV = [];
	for (var i = 0; i < count * 10; i++) {
		dataV.push(anchorV + logStep * i);
	}

	var foo = gridV.selectAll('line').data(dataV);
	foo
		.attr('x1', function(d) {return d;})
		.attr('x2', function(d) {return d;})
		.attr('y1', bounds.yMin - 10 * bounds.height())
		.attr('y2', bounds.yMax + 10 * bounds.height())
		.attr('vector-effect', 'inherit')

	foo.enter()
		.append('line')
			.attr('x1', function(d) {return d;})
			.attr('x2', function(d) {return d;})
			.attr('y1', bounds.yMin - 10 * bounds.height())
			.attr('y2', bounds.yMax + 10 * bounds.height())
			.attr('vector-effect', 'inherit');
	foo.exit()
		.remove();

	var anchorH = Math.floor((bounds.yMax - (bounds.height())) / logStep) * logStep;

	var dataH = [];
	for (var i = 0; i < count * 4; i++) {
		dataH.push(anchorH + logStep * i);
	}

	foo = gridH.selectAll('line').data(dataH);
	foo
		.attr('x1', bounds.xMin - 10 * bounds.width())
		.attr('x2', bounds.xMax + 10 * bounds.width())
		.attr('y1', function(d) {return d;})
		.attr('y2', function(d) {return d;})
		.attr('vector-effect', 'inherit');

	foo.enter()
		.append('line')
		.attr('x1', bounds.xMin - 10 * bounds.width())
		.attr('x2', bounds.xMax + 10 * bounds.width())
		.attr('y1', function(d) {return d;})
		.attr('y2', function(d) {return d;})
		.attr('vector-effect', 'inherit');

	foo.exit()
		.remove();
}

window.onload = function() {

	console.log('------- onload mapper --------');

	var Counter = function() {
		var count = 0;
		var start = performance.now();

		var totalSpan = document.getElementById('total');
		var rateSpan = document.getElementById('rate');

		this.print = function() {
			totalSpan.innerHTML = count;
			rateSpan.innerHTML = (count / ((performance.now() - start) / 1000)).toFixed(3);
		}

		this.hit = function() {
			count++;
		}
	}

	counter = new Counter();

	rx = d3.select('#rx');
	rx.attr('class', 'off');

	svg = d3.select('#map');
	svg.width = svg[0][0].clientWidth;
	svg.height = svg[0][0].clientHeight;
	ratio = svg.width / svg.height;

	var domSVG = document.getElementById('map');

	var mouseDown = false;
	document.onmousemove = function(event) {
		if (mouseDown) {
			// console.log('dragging')
			// console.log(event.clientX);
		}
	}

	domSVG.onmousedown = function() {
		mouseDown = true;
	}

	document.onmouseup = function(event) {
		mouseDown = false;
	}

	group = svg.append('g');
	group.attr('vector-effect', 'non-scaling-stroke');
	mapGroup = group.append('g');

	youAreHere = group.append('circle')
		.attr('cx', '0')
		.attr('cy', '0')
		.attr('r', '4');

	grid = group.append('g').attr('id', 'grid');
	gridV = grid.append('g').attr('vector-effect', 'non-scaling-stroke');;
	gridH = grid.append('g').attr('vector-effect', 'non-scaling-stroke');;

	grid.attr('vector-effect', 'non-scaling-stroke');

	console.log('------- /onload mapper --------');
}

var requestMapTile = function(rect) {
	var message = {
		type: 'message',
		payload: {
			type: 'mapTileRequest',
			payload: rect
		}
	}
	libsw.postMessage(message);
}
<commit_msg>updated to latest protocol version<commit_after>// patches
window.performance = window.performance || {};
performance.now = (function() {
    return performance.now       ||
        performance.mozNow    ||
        performance.msNow     ||
        performance.oNow      ||
        performance.webkitNow ||
        Date.now  /*none found - fallback to browser default */
})();

// patches END

var libsw = new LibSpaceWalk();

var path = null;
var trailPath = null;

var ratio = 0;

var data = [];
data.push([]);
currentData = data[0];
var dataCount = 0;
var maxElements = 500;
var latestData = [];
var currentLevel = 0;

var current = null;
var last = null;
var svg;
var counter = null;

var group = null;
var youAreHere = null;
var grid = null;
var gridH = null;
var gridV = null;

var mapGroup = null;
var currentTile = {
	x: 0,
	y: 0,
	width: 0,
	height: 0
}
var mapTileRequested = false;

var bounds = {
	xMin: Number.MAX_VALUE,
	xMax: -Number.MAX_VALUE,
	yMin: Number.MAX_VALUE,
	yMax: -Number.MAX_VALUE,

	width: function() {
		return this.xMax - this.xMin;
	},

	height: function() {
		return this.yMax - this.yMin;
	},

	centerX: function() {
		return (this.xMin + this.xMax) / 2.0;
	},

	centerY: function() {
		return (this.yMin + this.yMax) / 2.0;
	}
}

var updateBounds = function(position, bounds) {
	bounds.xMax = Math.max(bounds.xMax, position.x);
	bounds.xMin = Math.min(bounds.xMin, position.x);
	bounds.yMax = Math.max(bounds.yMax, position.z);
	bounds.yMin = Math.min(bounds.yMin, position.z);

	if (!mapTileRequested && ((bounds.width() * 2) > currentTile.width ||
			(bounds.height() * 2) > currentTile.height)) {
		// request new tile
		// compute bounds of canvas in world coords
		requestMapTile({
			x: bounds.xMin - ((bounds.width() * 0.5) + 5),
			y: bounds.yMin - ((bounds.height() * 0.5) + 5),
			width: bounds.width() + ((bounds.width() * 1.5) + 10),
			height: bounds.height() + ((bounds.height() * 1.5) + 10)
		});

		// mapTileRequested = true;
	}
}

var mapTile = function(json) {
	console.log(json);

	mapGroup.selectAll('image').remove();
	mapGroup.append('image')
		.attr('x', json.x)
		.attr('y', -(json.y + json.height))
		.attr('width', json.width)
		.attr('height', json.height)
		.attr('xlink:href', 'data:' + json.mime + ';' + json.encoding + ', ' + json.data);

	mapTileRequested = false;
	currentTile = json;

	// debug output
	d3.select('#image img').remove();
	d3.select('#image').append('img')
		.attr('src', 'data:' + json.mime + ';' + json.encoding + ', ' + json.data);
}

libsw.onMessage = function(message) {
	var sample = message;

	if (sample.type === "ext.simpleTelemetry.mapTileData") {
		mapTile(sample.payload);
		return;
	} else if (sample.type === "ext.simpleTelemetry.location") {

		data[0].push(sample.payload);
		latestData.push(sample.payload);

		if ((latestData.length - 2) > dataCount % Math.pow(2, currentLevel)) {
			var last = latestData[latestData.length - 1];
			latestData.length = 0;
			latestData.push(last);
			latestData.push(sample.payload);
		}

		for (var i = 1; i < data.length; i++) {
			if (dataCount % (Math.pow(2, i)) === 0) {
				data[i].push(sample.payload);
			}
		}

		if (data[data.length-1].length > maxElements) {
			currentLevel++;
			data.push([]);
			for (var i = 0; i < data[data.length-2].length; i += 2) {
				data[data.length-1].push(data[data.length-2][i]);
			}
			currentData = data[data.length-1];
			path.datum(currentData);
		}

		dataCount++;

		updateBounds(sample.payload, bounds);

		last = current;
		current = sample;

		update();
		makeGrid(bounds);

		counter.hit();
		counter.print();
	}
};

 var drawPath = function(selection) {
	selection
		.attr('vector-effect', 'inherit')
		.attr('d', d3.svg.line()
			.x(function(d) {return d.x})
			.y(function(d) {return -d.z})
			.interpolate('linear'));
}

var update = function() {

	if (!path) {
		path = group.append('path')
		.datum(currentData)
		.call(drawPath);
	}

	if (!trailPath) {
		trailPath = group.append('path')
		.datum(latestData)
		.call(drawPath);
	}

	path.call(drawPath);
	trailPath.call(drawPath);

	youAreHere.attr('cx', current.x)
		.attr('cy', current.z);

	updateGroup(bounds);
}

var updateGroup = function(bounds) {
	var scale = Math.min(svg.width / bounds.width(), svg.height / bounds.height()) * 0.9;

	group
		// .transition()
		.attr('transform', 'translate(' + (-bounds.centerX() * scale + svg.width / 2) + ' '+
			(bounds.centerY() * scale + svg.height / 2) + ') scale(' + scale + ')');
}

var makeGrid = function(bounds) {

	var size = 3;
	var logStep = Math.pow(size, Math.floor(Math.log(Math.max(bounds.width(), bounds.height())) / Math.log(size)));
	// console.log(logStep);

	var count = Math.ceil(bounds.width() / logStep);
	// console.log(count);

	var anchorV = Math.floor((bounds.xMin - (bounds.width())) / logStep) * logStep;

	var dataV = [];
	for (var i = 0; i < count * 10; i++) {
		dataV.push(anchorV + logStep * i);
	}

	var foo = gridV.selectAll('line').data(dataV);
	foo
		.attr('x1', function(d) {return d;})
		.attr('x2', function(d) {return d;})
		.attr('y1', bounds.yMin - 10 * bounds.height())
		.attr('y2', bounds.yMax + 10 * bounds.height())
		.attr('vector-effect', 'inherit')

	foo.enter()
		.append('line')
			.attr('x1', function(d) {return d;})
			.attr('x2', function(d) {return d;})
			.attr('y1', bounds.yMin - 10 * bounds.height())
			.attr('y2', bounds.yMax + 10 * bounds.height())
			.attr('vector-effect', 'inherit');
	foo.exit()
		.remove();

	var anchorH = Math.floor((bounds.yMax - (bounds.height())) / logStep) * logStep;

	var dataH = [];
	for (var i = 0; i < count * 4; i++) {
		dataH.push(anchorH + logStep * i);
	}

	foo = gridH.selectAll('line').data(dataH);
	foo
		.attr('x1', bounds.xMin - 10 * bounds.width())
		.attr('x2', bounds.xMax + 10 * bounds.width())
		.attr('y1', function(d) {return d;})
		.attr('y2', function(d) {return d;})
		.attr('vector-effect', 'inherit');

	foo.enter()
		.append('line')
		.attr('x1', bounds.xMin - 10 * bounds.width())
		.attr('x2', bounds.xMax + 10 * bounds.width())
		.attr('y1', function(d) {return d;})
		.attr('y2', function(d) {return d;})
		.attr('vector-effect', 'inherit');

	foo.exit()
		.remove();
}

window.onload = function() {

	console.log('------- onload mapper --------');

	var Counter = function() {
		var count = 0;
		var start = performance.now();

		var totalSpan = document.getElementById('total');
		var rateSpan = document.getElementById('rate');

		this.print = function() {
			totalSpan.innerHTML = count;
			rateSpan.innerHTML = (count / ((performance.now() - start) / 1000)).toFixed(3);
		}

		this.hit = function() {
			count++;
		}
	}

	counter = new Counter();

	rx = d3.select('#rx');
	rx.attr('class', 'off');

	svg = d3.select('#map');
	svg.width = svg[0][0].clientWidth;
	svg.height = svg[0][0].clientHeight;
	ratio = svg.width / svg.height;

	var domSVG = document.getElementById('map');

	var mouseDown = false;
	document.onmousemove = function(event) {
		if (mouseDown) {
			// console.log('dragging')
			// console.log(event.clientX);
		}
	}

	domSVG.onmousedown = function() {
		mouseDown = true;
	}

	document.onmouseup = function(event) {
		mouseDown = false;
	}

	group = svg.append('g');
	group.attr('vector-effect', 'non-scaling-stroke');
	mapGroup = group.append('g');

	youAreHere = group.append('circle')
		.attr('cx', '0')
		.attr('cy', '0')
		.attr('r', '4');

	grid = group.append('g').attr('id', 'grid');
	gridV = grid.append('g').attr('vector-effect', 'non-scaling-stroke');;
	gridH = grid.append('g').attr('vector-effect', 'non-scaling-stroke');;

	grid.attr('vector-effect', 'non-scaling-stroke');

	console.log('------- /onload mapper --------');
}

var requestMapTile = function(rect) {
	var message = {
		type: 'ext.simpleTelemetry.mapTileRequest',
		payload: rect
	}
	libsw.postMessage(message);
}
<|endoftext|>


<commit_before>const path = require('path')

// Private: re-join the segments split from an absolute path to form another absolute path.
function absolute (...parts) {
  const candidate = path.join(...parts)
  return path.isAbsolute(candidate) ? candidate : path.join(path.sep, candidate)
}

module.exports = {absolute}
<commit_msg>Handle win32 drive letters when reconstituting paths<commit_after>const path = require('path')

// Private: re-join the segments split from an absolute path to form another absolute path.
function absolute (...parts) {
  let candidate = parts.length !== 1 ? path.join(parts) : parts[0]
  if (process.platform === 'win32' && /^[A-Z]:$/.test(candidate)) candidate += '\\'
  return path.isAbsolute(candidate) ? candidate : path.join(path.sep, candidate)
}

module.exports = {absolute}
<|endoftext|>


<commit_before>// Copyright (c) 2014, Joyent, Inc. All rights reserved.

var bunyan = require('bunyan');
var dashdash = require('dashdash');
var http = require('http');
var path = require('path');

var Redis = require('../redis.js');
var ChangeLogReader = require('./change_log_reader.js');
var Transform = require('./transform.js');

var options = [
    {
        names: ['help', 'h'],
        type: 'bool',
        help: 'Print this help and exit.'
    },
    {
        names: ['config', 'c'],
        type: 'string',
        env: 'MAHI_CONFIG',
        helpArg: 'PATH',
        default: path.resolve(__dirname, '../../etc/mahi.json'),
        help: 'configuration file with ufds and redis config settings'
    },
    {
        names: ['aperture'],
        type: 'string',
        env: 'MAHI_APERTURE_PATH',
        helpArg: 'PATH',
        default: path.resolve(__dirname, '../../etc/aperture.json'),
        help: 'configuration file for aperture'
    },
    {
        names: ['ufds-url'],
        type: 'string',
        env: 'MAHI_UFDS_URL',
        helpArg: 'URL',
        help: 'ufds url (overrides config)'
    },
    {
        names: ['redis-host'],
        type: 'string',
        env: 'MAHI_REDIS_HOST',
        helpArg: 'HOST',
        help: 'redis host (overrides config)'
    },
    {
        names: ['redis-port'],
        type: 'number',
        env: 'MAHI_REDIS_PORT',
        helpArg: 'PORT',
        help: 'redis port (overrides config)'
    }
];

function main() {
    var parser = dashdash.createParser({options: options});
    var opts;
    try {
        opts = parser.parse(process.argv);
    } catch (e) {
        console.error('error: %s', e.message);
        process.exit(1);
    }

    if (opts.help) {
        var help = parser.help().trimRight();
        console.log('usage: \n' + help);
        process.exit(0);
    }

    var config = require(path.resolve(opts.config));
    var apertureConfig = require(path.resolve(opts.aperture));
    var ufdsConfig = config.ufds;
    var redisConfig = config.redis;
    var replicatorConfig = config.replicator || {};

    var log = bunyan.createLogger({
        name: 'authcache-replicator',
        level: process.env.LOG_LEVEL || 'info'
    });

    ufdsConfig.url = opts['ufds-url'] || ufdsConfig.url;
    redisConfig.host = opts['redis-host'] || redisConfig.host;
    redisConfig.port = opts['redis-port'] || redisConfig.port;

    redisConfig.log = log;
    Redis.createClient(redisConfig, function (err, redis) {
        if (err) {
            log.fatal({err: err}, 'error creating redis client');
            process.exit(1);
        }

        http.createServer(function (request, response) {
            redis.ping(function (err) {
                if (err) {
                    response.writeHead(503, 'Redis Unavailable');
                    response.end();
                    return;
                }
                redis.get('virginv2', function (err, res) {
                    if (err) {
                        response.writeHead(503, 'Redis Error');
                        response.end();
                        return;
                    }
                    if (res !== null) {
                        response.writeHead(503, 'Not Caught Up');
                        response.end();
                        return;
                    }
                    response.writeHead(204);
                    response.end();
                });
            });
        }).listen(replicatorConfig.pingPort || 80);

        redis.get('changenumberv2', function (err, changenumber) {
            if (err) {
                log.fatal({err: err}, 'error getting changenumber from redis');
                process.exit(1);
            }

            redis.set('virginv2', 'true', function (err) {
                if (err) {
                    log.fatal({err: err}, 'error setting virgin flag');
                    process.exit(1);
                }

                changenumber = parseInt(changenumber, 10);

                var reader = new ChangeLogReader({
                    log: log,
                    ufds: ufdsConfig,
                    changenumber: changenumber || 0
                });

                var transform = new Transform({
                    log: log,
                    redis: redis,
                    typeTable: apertureConfig.typeTable
                });

                reader.once('fresh', function onFresh() {
                    redis.del('virginv2', function delVirgin(err) {
                        if (err) {
                            log.error({err: err}, 'error removing virgin flag');
                            return;
                        }
                        log.info('virgin flag removed');
                    });
                });

                reader.pipe(transform);
            });
        });
    });
}

if (require.main === module) {
    main();
}
<commit_msg>MANTA-2100 use shared aperture config<commit_after>// Copyright (c) 2014, Joyent, Inc. All rights reserved.

var apertureConfig = require('aperture-config').config;
var bunyan = require('bunyan');
var dashdash = require('dashdash');
var http = require('http');
var path = require('path');

var Redis = require('../redis.js');
var ChangeLogReader = require('./change_log_reader.js');
var Transform = require('./transform.js');

var options = [
    {
        names: ['help', 'h'],
        type: 'bool',
        help: 'Print this help and exit.'
    },
    {
        names: ['config', 'c'],
        type: 'string',
        env: 'MAHI_CONFIG',
        helpArg: 'PATH',
        default: path.resolve(__dirname, '../../etc/mahi.json'),
        help: 'configuration file with ufds and redis config settings'
    },
    {
        names: ['aperture'],
        type: 'string',
        env: 'MAHI_APERTURE_PATH',
        helpArg: 'PATH',
        help: 'configuration file for aperture'
    },
    {
        names: ['ufds-url'],
        type: 'string',
        env: 'MAHI_UFDS_URL',
        helpArg: 'URL',
        help: 'ufds url (overrides config)'
    },
    {
        names: ['redis-host'],
        type: 'string',
        env: 'MAHI_REDIS_HOST',
        helpArg: 'HOST',
        help: 'redis host (overrides config)'
    },
    {
        names: ['redis-port'],
        type: 'number',
        env: 'MAHI_REDIS_PORT',
        helpArg: 'PORT',
        help: 'redis port (overrides config)'
    }
];

function main() {
    var parser = dashdash.createParser({options: options});
    var opts;
    try {
        opts = parser.parse(process.argv);
    } catch (e) {
        console.error('error: %s', e.message);
        process.exit(1);
    }

    if (opts.help) {
        var help = parser.help().trimRight();
        console.log('usage: \n' + help);
        process.exit(0);
    }

    var config = require(path.resolve(opts.config));
    var typeTable = opts.aperture ?
        require(path.resolve(opts.aperture)).typeTable :
        apertureConfig.typeTable;
    var ufdsConfig = config.ufds;
    var redisConfig = config.redis;
    var replicatorConfig = config.replicator || {};

    var log = bunyan.createLogger({
        name: 'authcache-replicator',
        level: process.env.LOG_LEVEL || 'info'
    });

    ufdsConfig.url = opts['ufds-url'] || ufdsConfig.url;
    redisConfig.host = opts['redis-host'] || redisConfig.host;
    redisConfig.port = opts['redis-port'] || redisConfig.port;

    redisConfig.log = log;
    Redis.createClient(redisConfig, function (err, redis) {
        if (err) {
            log.fatal({err: err}, 'error creating redis client');
            process.exit(1);
        }

        http.createServer(function (request, response) {
            redis.ping(function (err) {
                if (err) {
                    response.writeHead(503, 'Redis Unavailable');
                    response.end();
                    return;
                }
                redis.get('virginv2', function (err, res) {
                    if (err) {
                        response.writeHead(503, 'Redis Error');
                        response.end();
                        return;
                    }
                    if (res !== null) {
                        response.writeHead(503, 'Not Caught Up');
                        response.end();
                        return;
                    }
                    response.writeHead(204);
                    response.end();
                });
            });
        }).listen(replicatorConfig.pingPort || 80);

        redis.get('changenumberv2', function (err, changenumber) {
            if (err) {
                log.fatal({err: err}, 'error getting changenumber from redis');
                process.exit(1);
            }

            redis.set('virginv2', 'true', function (err) {
                if (err) {
                    log.fatal({err: err}, 'error setting virgin flag');
                    process.exit(1);
                }

                changenumber = parseInt(changenumber, 10);

                var reader = new ChangeLogReader({
                    log: log,
                    ufds: ufdsConfig,
                    changenumber: changenumber || 0
                });

                var transform = new Transform({
                    log: log,
                    redis: redis,
                    typeTable: typeTable
                });

                reader.once('fresh', function onFresh() {
                    redis.del('virginv2', function delVirgin(err) {
                        if (err) {
                            log.error({err: err}, 'error removing virgin flag');
                            return;
                        }
                        log.info('virgin flag removed');
                    });
                });

                reader.pipe(transform);
            });
        });
    });
}

if (require.main === module) {
    main();
}
<|endoftext|>


<commit_before>const blessed = require('blessed'),
      contrib = require('blessed-contrib'),
      auto = true;

function renderScreen(screen, stream, screenName, user) {
    screen = new blessed.screen({
        autoPadding: true,
        smartCSR: true,
        program: new blessed.program({
            input: stream,
            output: stream
        }),
        dockBorders: true,
        terminal: term || 'ansi'
    });

    // add common screen components
    var bottomBarMenu = blessed.listbar({
        parent: screen,
        bottom: 0,
        height: auto ? 'shrink' : 3,
        width: '100%',
        mouse: true,
        keys: true,
        autoCommandKeys: true,
        vi: true,
        style: {
            bg: 'magenta',
            item: {
                bg: 'red',
                hover: {
                    bg: 'blue'
                }
            },
            selected: {
                bg: 'blue'
            }
        },
        commands: {
            'Welcome': function() {
                screen.render();
            },
            'Account Info': function() {
                screen.render();
            },
            'Select Server': function() {
                screen.render();
            },
            'Confirm': function() {
                screen.render();
            },
            'Guide': function() {
                screen.render();
            }
        }
    });

    var topBar = blessed.box({
        top: '0',
        width: '100%',
        height: 'shrink',
        valign: 'middle',
        content: '{bold} Welcome to #! {/bold} - Sign Up',
        tags: true,
        style: {
            fg: 'white',
            bg: 'magenta'
        }
    });

    require('./screens/'+ screenName + '.js')(screen, stream, user);

    screen.key(['escape', 'q', 'C-c'], function(ch, key) {
        screen.destroy();
        stream.end();
    });

    screen.append(topBar);
    screen.render();
}

module.exports = renderScreen;
<commit_msg>added placeholder screens and wired up the controls<commit_after>const blessed = require('blessed'),
      contrib = require('blessed-contrib'),
      auto = true;

function renderScreen(screen, stream, screenName, user) {
    screen = new blessed.screen({
        autoPadding: true,
        smartCSR: true,
        program: new blessed.program({
            input: stream,
            output: stream
        }),
        dockBorders: true,
        terminal: term || 'ansi'
    });

    // add common screen components
    var bottomBarMenu = blessed.listbar({
        parent: screen,
        bottom: 0,
        height: auto ? 'shrink' : 3,
        width: '100%',
        mouse: true,
        keys: true,
        autoCommandKeys: true,
        vi: true,
        style: {
            bg: 'magenta',
            item: {
                bg: 'red',
                hover: {
                    bg: 'blue'
                }
            },
            selected: {
                bg: 'blue'
            }
        },
        commands: {
            'Welcome': function() {
                screen.destroy();
                renderScreen(screen, stream, 'welcome', user)
                screen.render()
            },
            'Account Info': function() {
                screen.destroy();
                renderScreen(screen, stream, 'account-info', user)
                screen.render();
            },
            'Select Server': function() {
                screen.destroy();
                renderScreen(screen, stream, 'server-select', user)
                screen.render();
            },
            'Confirm': function() {
                screen.destroy();
                renderScreen(screen, stream, 'account-review', user)
                screen.render();
            },
            'Guide': function() {
                screen.destroy();
                renderScreen(screen, stream, 'post-signup', user)
                screen.render();
            }
        }
    });

    var topBar = blessed.box({
        top: '0',
        width: '100%',
        height: 'shrink',
        valign: 'middle',
        content: '{bold} Welcome to #! {/bold} - Sign Up',
        tags: true,
        style: {
            fg: 'white',
            bg: 'magenta'
        }
    });

    require('./screens/'+ screenName + '.js')(screen, stream, user);

    screen.key(['escape', 'q', 'C-c'], function(ch, key) {
        screen.destroy();
        stream.end();
    });

    screen.append(topBar);
    screen.render();
}

module.exports = renderScreen;
<|endoftext|>


<commit_before>/*!
 * Stylus - Selector Parser
 * Copyright (c) Automattic <developer.wordpress.com>
 * MIT Licensed
 */

var COMBINATORS = ['>', '+', '~'];

/**
 * Initialize a new `SelectorParser`
 * with the given `str` and selectors `stack`.
 *
 * @param {String} str
 * @param {Array} stack
 * @param {Array} parts
 * @api private
 */

var SelectorParser = module.exports = function SelectorParser(str, stack, parts) {
  this.str = str;
  this.stack = stack || [];
  this.parts = parts || [];
  this.pos = 0;
  this.level = 2;
  this.nested = true;
  this.ignore = false;
};

/**
 * Consume the given `len` and move current position.
 *
 * @param {Number} len
 * @api private
 */

SelectorParser.prototype.skip = function(len) {
  this.str = this.str.substr(len);
  this.pos += len;
};

/**
 * Consume spaces.
 */

SelectorParser.prototype.skipSpaces = function() {
  while (' ' == this.str[0]) this.skip(1);
};

/**
 * Fetch next token.
 *
 * @return {String}
 * @api private
 */

SelectorParser.prototype.advance = function() {
  return this.root()
    || this.relative()
    || this.initial()
    || this.escaped()
    || this.parent()
    || this.partial()
    || this.char();
};

/**
 * '/'
 */

SelectorParser.prototype.root = function() {
  if (!this.pos && '/' == this.str[0]
    && 'deep' != this.str.slice(1, 5)) {
    this.nested = false;
    this.skip(1);
  }
};

/**
 * '../'
 */

SelectorParser.prototype.relative = function(multi) {
  if ((!this.pos || multi) && '../' == this.str.slice(0, 3)) {
    this.nested = false;
    this.skip(3);
    while (this.relative(true)) this.level++;
    if (!this.raw) {
      var ret = this.stack[this.stack.length - this.level];
      if (ret) {
        return ret;
      } else {
        this.ignore = true;
      }
    }
  }
};

/**
 * '~/'
 */

SelectorParser.prototype.initial = function() {
  if (!this.pos && '~' == this.str[0] && '/' == this.str[1]) {
    this.nested = false;
    this.skip(2);
    return this.stack[0];
  }
};

/**
 * '\' ('&' | '^')
 */

SelectorParser.prototype.escaped = function() {
  if ('\\' == this.str[0]) {
    var char = this.str[1];
    if ('&' == char || '^' == char) {
      this.skip(2);
      return char;
    }
  }
};

/**
 * '&'
 */

SelectorParser.prototype.parent = function() {
  if ('&' == this.str[0]) {
    this.nested = false;

    if (!this.pos && (!this.stack.length || this.raw)) {
      var i = 0;
      while (' ' == this.str[++i]) ;
      if (~COMBINATORS.indexOf(this.str[i])) {
        this.skip(i + 1);
        return;
      }
    }

    this.skip(1);
    if (!this.raw)
      return this.stack[this.stack.length - 1];
  }
};

/**
 * '^[' range ']'
 */

SelectorParser.prototype.partial = function() {
  if ('^' == this.str[0] && '[' == this.str[1]) {
    this.skip(2);
    this.skipSpaces();
    var ret = this.range();
    this.skipSpaces();
    if (']' != this.str[0]) return '^[';
    this.nested = false;
    this.skip(1);
    if (ret) {
      return ret;
    } else {
      this.ignore = true;
    }
  }
};

/**
 * '-'? 0-9+
 */

SelectorParser.prototype.number = function() {
  var i =  0, ret = '';
  if ('-' == this.str[i])
    ret += this.str[i++];

  while (this.str.charCodeAt(i) >= 48
    && this.str.charCodeAt(i) <= 57)
    ret += this.str[i++];

  if (ret) {
    this.skip(i);
    return Number(ret);
  }
};

/**
 * number ('..' number)?
 */

SelectorParser.prototype.range = function() {
  var start = this.number()
    , parsed
    , ret;

  if ('..' == this.str.slice(0, 2)) {
    this.skip(2);
    var end = this.number()
      , len = this.parts.length;

    if (start < 0) start = len + start - 1;
    if (end < 0) end = len + end - 1;

    if (start > end) {
      var tmp = start;
      start = end;
      end = tmp;
    }

    if (end < len - 1) {
      parsed = this.parts.slice(start, end + 1).map(function(part) {
        var selector = new SelectorParser(part, this.stack, this.parts);
        selector.raw = true;
        return selector.parse();
      }, this);

      ret = parsed.map(function(selector) {
        return selector.val.trim();
      }).join(parsed.every(function(selector) {
        return selector.nested;
      }) ? ' ' : '');
    }
  } else {
    ret = this.stack[
      start < 0 ? this.stack.length + start - 1 : start
    ];
  }

  if (ret) {
    return ret;
  } else {
    this.ignore = true;
  }
};

/**
 * .+
 */

SelectorParser.prototype.char = function() {
  var char = this.str[0];
  this.skip(1);
  return char;
};

/**
 * Parses the selector.
 *
 * @return {Object}
 * @api private
 */

SelectorParser.prototype.parse = function() {
  var val = '';
  while (this.str.length) {
    val += this.advance() || '';
    if (this.ignore) {
      val = '';
      break;
    }
  }
  return { val: val.trimRight(), nested: this.nested };
};
<commit_msg>Undesired spaces with partial reference selector using ranges. Fixes #2133<commit_after>/*!
 * Stylus - Selector Parser
 * Copyright (c) Automattic <developer.wordpress.com>
 * MIT Licensed
 */

var COMBINATORS = ['>', '+', '~'];

/**
 * Initialize a new `SelectorParser`
 * with the given `str` and selectors `stack`.
 *
 * @param {String} str
 * @param {Array} stack
 * @param {Array} parts
 * @api private
 */

var SelectorParser = module.exports = function SelectorParser(str, stack, parts) {
  this.str = str;
  this.stack = stack || [];
  this.parts = parts || [];
  this.pos = 0;
  this.level = 2;
  this.nested = true;
  this.ignore = false;
};

/**
 * Consume the given `len` and move current position.
 *
 * @param {Number} len
 * @api private
 */

SelectorParser.prototype.skip = function(len) {
  this.str = this.str.substr(len);
  this.pos += len;
};

/**
 * Consume spaces.
 */

SelectorParser.prototype.skipSpaces = function() {
  while (' ' == this.str[0]) this.skip(1);
};

/**
 * Fetch next token.
 *
 * @return {String}
 * @api private
 */

SelectorParser.prototype.advance = function() {
  return this.root()
    || this.relative()
    || this.initial()
    || this.escaped()
    || this.parent()
    || this.partial()
    || this.char();
};

/**
 * '/'
 */

SelectorParser.prototype.root = function() {
  if (!this.pos && '/' == this.str[0]
    && 'deep' != this.str.slice(1, 5)) {
    this.nested = false;
    this.skip(1);
  }
};

/**
 * '../'
 */

SelectorParser.prototype.relative = function(multi) {
  if ((!this.pos || multi) && '../' == this.str.slice(0, 3)) {
    this.nested = false;
    this.skip(3);
    while (this.relative(true)) this.level++;
    if (!this.raw) {
      var ret = this.stack[this.stack.length - this.level];
      if (ret) {
        return ret;
      } else {
        this.ignore = true;
      }
    }
  }
};

/**
 * '~/'
 */

SelectorParser.prototype.initial = function() {
  if (!this.pos && '~' == this.str[0] && '/' == this.str[1]) {
    this.nested = false;
    this.skip(2);
    return this.stack[0];
  }
};

/**
 * '\' ('&' | '^')
 */

SelectorParser.prototype.escaped = function() {
  if ('\\' == this.str[0]) {
    var char = this.str[1];
    if ('&' == char || '^' == char) {
      this.skip(2);
      return char;
    }
  }
};

/**
 * '&'
 */

SelectorParser.prototype.parent = function() {
  if ('&' == this.str[0]) {
    this.nested = false;

    if (!this.pos && (!this.stack.length || this.raw)) {
      var i = 0;
      while (' ' == this.str[++i]) ;
      if (~COMBINATORS.indexOf(this.str[i])) {
        this.skip(i + 1);
        return;
      }
    }

    this.skip(1);
    if (!this.raw)
      return this.stack[this.stack.length - 1];
  }
};

/**
 * '^[' range ']'
 */

SelectorParser.prototype.partial = function() {
  if ('^' == this.str[0] && '[' == this.str[1]) {
    this.skip(2);
    this.skipSpaces();
    var ret = this.range();
    this.skipSpaces();
    if (']' != this.str[0]) return '^[';
    this.nested = false;
    this.skip(1);
    if (ret) {
      return ret;
    } else {
      this.ignore = true;
    }
  }
};

/**
 * '-'? 0-9+
 */

SelectorParser.prototype.number = function() {
  var i =  0, ret = '';
  if ('-' == this.str[i])
    ret += this.str[i++];

  while (this.str.charCodeAt(i) >= 48
    && this.str.charCodeAt(i) <= 57)
    ret += this.str[i++];

  if (ret) {
    this.skip(i);
    return Number(ret);
  }
};

/**
 * number ('..' number)?
 */

SelectorParser.prototype.range = function() {
  var start = this.number()
    , ret;

  if ('..' == this.str.slice(0, 2)) {
    this.skip(2);
    var end = this.number()
      , len = this.parts.length;

    if (start < 0) start = len + start - 1;
    if (end < 0) end = len + end - 1;

    if (start > end) {
      var tmp = start;
      start = end;
      end = tmp;
    }

    if (end < len - 1) {
      ret = this.parts.slice(start, end + 1).map(function(part) {
        var selector = new SelectorParser(part, this.stack, this.parts);
        selector.raw = true;
        return selector.parse();
      }, this).map(function(selector) {
        return (selector.nested ? ' ' : '') + selector.val;
      }).join('').trim();
    }
  } else {
    ret = this.stack[
      start < 0 ? this.stack.length + start - 1 : start
    ];
  }

  if (ret) {
    return ret;
  } else {
    this.ignore = true;
  }
};

/**
 * .+
 */

SelectorParser.prototype.char = function() {
  var char = this.str[0];
  this.skip(1);
  return char;
};

/**
 * Parses the selector.
 *
 * @return {Object}
 * @api private
 */

SelectorParser.prototype.parse = function() {
  var val = '';
  while (this.str.length) {
    val += this.advance() || '';
    if (this.ignore) {
      val = '';
      break;
    }
  }
  return { val: val.trimRight(), nested: this.nested };
};
<|endoftext|>


<commit_before>var Utils = require("./utils")
var Query = module.exports = function(client, callee, options) {
  this.client = client
  this.callee = callee
  this.options = options || {}
  this.bindClientFunction = function(err) { self.onFailure(err) }
}
Utils.addEventEmitter(Query)

Query.prototype.run = function(query) {
  var self = this
  this.sql = query

  this.bindClient()

  if(this.options.logging)
    console.log('Executing: ' + this.sql)

  this.client.query(this.sql, function(err, results, fields) {
    err ? self.onFailure(err) : self.onSuccess(self.sql, results, fields)
  }).setMaxListeners(100)

  return this
}

Query.prototype.bindClient = function() {
  this.client.on('error', this.bindClientFunction)
}

Query.prototype.unbindClient = function() {
  this.client.removeListener('error', this.bindClientFunction)
}

Query.prototype.onSuccess = function(query, results, fields) {
  var result = this.callee
    , self   = this

  // add the inserted row id to the instance
  if (this.callee && (query.indexOf('INSERT INTO') == 0) && (results.hasOwnProperty('insertId')))
    this.callee[this.callee.definition.autoIncrementField] = results.insertId

  // transform results into real model instances
  // return the first real model instance if options.plain is set (e.g. Model.find)
  if (query.indexOf('SELECT') == 0) {
    result = results.map(function(result) { return self.callee.build(result, {isNewRecord: false}) })

    if(this.options.plain)
      result = (result.length == 0) ? null : result[0]
  }

  this.unbindClient()
  this.emit('success', result)
}

Query.prototype.onFailure = function(err) {
  this.unbindClient()
  this.emit('failure', err, this.callee)
}<commit_msg>fixed reference in client failure catch<commit_after>var Utils = require("./utils")
var Query = module.exports = function(client, callee, options) {
  var self = this

  this.client = client
  this.callee = callee
  this.options = options || {}
  this.bindClientFunction = function(err) { self.onFailure(err) }
}
Utils.addEventEmitter(Query)

Query.prototype.run = function(query) {
  var self = this
  this.sql = query

  this.bindClient()

  if(this.options.logging)
    console.log('Executing: ' + this.sql)

  this.client.query(this.sql, function(err, results, fields) {
    err ? self.onFailure(err) : self.onSuccess(self.sql, results, fields)
  }).setMaxListeners(100)

  return this
}

Query.prototype.bindClient = function() {
  this.client.on('error', this.bindClientFunction)
}

Query.prototype.unbindClient = function() {
  this.client.removeListener('error', this.bindClientFunction)
}

Query.prototype.onSuccess = function(query, results, fields) {
  var result = this.callee
    , self   = this

  // add the inserted row id to the instance
  if (this.callee && (query.indexOf('INSERT INTO') == 0) && (results.hasOwnProperty('insertId')))
    this.callee[this.callee.definition.autoIncrementField] = results.insertId

  // transform results into real model instances
  // return the first real model instance if options.plain is set (e.g. Model.find)
  if (query.indexOf('SELECT') == 0) {
    result = results.map(function(result) { return self.callee.build(result, {isNewRecord: false}) })

    if(this.options.plain)
      result = (result.length == 0) ? null : result[0]
  }

  this.unbindClient()
  this.emit('success', result)
}

Query.prototype.onFailure = function(err) {
  this.unbindClient()
  this.emit('failure', err, this.callee)
}<|endoftext|>


<commit_before>var fs = require('fs');

/* varible contain all watched file names
 * {name: true}
 */
var FileNames           = {},
    NamesList_s         = '';

/* function thet use for crossplatform
 * access to fs.watch or fs.watchFile function
 */
var fs_watch            = null;
var on_fs_watch         = null;
var firstFileRead_b     = true;
var Manifest = '';

setWatachFunctions();

exports.createManifest = function(){
    var lAllNames = cloudRequire(process.cwd() + '/hashes');
    if(lAllNames)
        for(var lName in lAllNames){
            if(lName.indexOf('min') > 0)
                lName = './min/' + lName;
            exports.watch(lName);
        }
    processManifest();
};

exports.watch = function(pFileName){
    console.log(pFileName + ' is watched');

    if(!FileNames[pFileName] &&
        pFileName !== './cloudcmd.appcache'){
        try{
            fs_watch(pFileName, on_fs_watch(pFileName));
        }catch(pError){}

        NamesList_s += pFileName + '\n';
        FileNames[pFileName] = true;
    }
    else if(firstFileRead_b){
        processManifest();
        firstFileRead_b = false;
    }
};

function setWatachFunctions(){
    if(process.platform === 'win32'){
        /* good on windows  */
        fs_watch    = fs.watch;
        on_fs_watch = onWatch;
    }
    else{
        /* good on linux    */
        fs_watch    = fs.watchFile;
        on_fs_watch = onWatchFile;
    }

}

function onWatch (pFileName){
    return function(pEvent, pFileName){
        console.log(pEvent);
        console.log('file ' + pFileName + ' is changed');
        processManifest();
    };
}

function onWatchFile(pFileName){
    return function(pCurr, pPrev){
        console.log(pCurr);
        if(pCurr.mtime !== pPrev.mtime){
            console.log('file ' + pFileName + ' is changed');
            processManifest();
        }
    };
}

function processManifest(){
    Manifest = 'CACHE MANIFEST\n'   +
        '#' + new Date()   + '\n'   +
        'CACHE:\n'                  +
        NamesList_s                 +
        'NETWORK:\n'                +
        '*';

    console.log(Manifest);
        fs.writeFile('cloudcmd.appcache', Manifest, function(){
            console.log('cloudcmd.appcache refreshed');
        });
}

/* function do safe require of needed module */
function cloudRequire(pModule){
  try{
      return require(pModule);
  }
  catch(pError){
      return false;
  }
}<commit_msg>minor changes<commit_after>var fs = require('fs');

/* varible contain all watched file names
 * {name: true}
 */
var FileNames           = {},
    NamesList_s         = '';

/* function thet use for crossplatform
 * access to fs.watch or fs.watchFile function
 */
var fs_watch            = null;
var on_fs_watch         = null;
var firstFileRead_b     = true;
var Manifest = '';

setWatachFunctions();

exports.createManifest = function(){
    var lAllNames = cloudRequire(process.cwd() + '/hashes');
    if(lAllNames)
        for(var lName in lAllNames){
            if(lName.indexOf('min') > 0)
                lName = './min/' + lName;
            exports.watch(lName);
        }
    processManifest();
};

exports.watch = function(pFileName){
    console.log(pFileName + ' is watched');

    if(!FileNames[pFileName] &&
        pFileName !== './cloudcmd.appcache'){
        try{
            fs_watch(pFileName, on_fs_watch(pFileName));
        }catch(pError){}

        NamesList_s += pFileName + '\n';
        FileNames[pFileName] = true;
    }
    else if(firstFileRead_b){
        processManifest();
        firstFileRead_b = false;
    }
};

function setWatachFunctions(){
    if(process.platform === 'win32'){
        /* good on windows  */
        fs_watch    = fs.watch;
        on_fs_watch = onWatch;
    }
    else{
        /* good on linux    */
        fs_watch    = fs.watchFile;
        on_fs_watch = onWatchFile;
    }

}

function onWatch (pFileName){
    return function(pEvent, pFileName){
        console.log(pEvent);
        console.log('file ' + pFileName + ' is changed');
        processManifest();
    };
}

function onWatchFile(pFileName){
    return function(pCurr, pPrev){
        if(pCurr.mtime !== pPrev.mtime){
            console.log('file ' + pFileName + ' is changed');
            processManifest();
        }
    };
}

function processManifest(){
    Manifest = 'CACHE MANIFEST\n'   +
        '#' + new Date()   + '\n'   +
        'CACHE:\n'                  +
        NamesList_s                 +
        'NETWORK:\n'                +
        '*';

    fs.writeFile('cloudcmd.appcache', Manifest, function(){
        console.log('cloudcmd.appcache refreshed');
    });
}

/* function do safe require of needed module */
function cloudRequire(pModule){
  try{
      return require(pModule);
  }
  catch(pError){
      return false;
  }
}<|endoftext|>


<commit_before>class GameMode {
  get engineOptions() {
    return {
      stepper: 'panelLeagueVs',
      width: 6,
      height: 12,
      flashTime: 40,
      floatTime: 10,
      swapTime: 3,
      garbageFlashTime: 2,
      blockTypes: [
        'red',
        'green',
        'blue',
        'yellow',
        'violet',
        'navy',
      ],
    };
  }

  get name() {
    return 'panel-league-duel';
  }

  get maximumPlayerCount() {
    return 2;
  }

  shouldStep(game) {
    return true;
  }

  shouldSendClock(game) {
    return (game.engine.time % 10 === 0);
  }

  shouldStartGame(game) {
    return game.playerCount === this.maximumPlayerCount;
  }

  shouldStopGame(game) {
    return !game.playerCount;
  }
}

class SandboxMode extends GameMode {
  get engineOptions() {
    return {
      stepper: 'panelLeagueScoring',
      width: 12,
      height: 12,
      flashTime: 40,
      floatTime: 10,
      swapTime: 3,
      blockTypes: [
        'red',
        'green',
        'blue',
        'yellow',
        'violet',
        'navy',
      ],
    };
  }

  get name() {
    return 'panel-league-sandbox';
  }

  get maximumPlayerCount() {
    return Number.MAX_VALUE;
  }

  shouldStartGame() {
    return true;
  }

  shouldStopGame() {
    return false;
  }
}

const gameModeFactory = ((name) => {
  switch (name) {
    case 'panel-league-duel':
      return new GameMode();
    case 'panel-league-sandbox':
      return new SandboxMode();
    default:
      throw new Error(`Unrecognized game mode: ${name}`);
  }
});

module.exports = gameModeFactory;
<commit_msg>Add Puyo to server game modes<commit_after>class GameMode {
  get engineOptions() {
    return {
      stepper: 'panelLeagueVs',
      width: 6,
      height: 12,
      flashTime: 40,
      floatTime: 10,
      swapTime: 3,
      garbageFlashTime: 2,
      blockTypes: [
        'red',
        'green',
        'blue',
        'yellow',
        'violet',
        'navy',
      ],
    };
  }

  get name() {
    return 'panel-league-duel';
  }

  get maximumPlayerCount() {
    return 2;
  }

  shouldStep(game) {
    return true;
  }

  shouldSendClock(game) {
    return (game.engine.time % 10 === 0);
  }

  shouldStartGame(game) {
    return game.playerCount === this.maximumPlayerCount;
  }

  shouldStopGame(game) {
    return !game.playerCount;
  }
}

class SandboxMode extends GameMode {
  get engineOptions() {
    return {
      stepper: 'panelLeagueScoring',
      width: 12,
      height: 12,
      flashTime: 40,
      floatTime: 10,
      swapTime: 3,
      blockTypes: [
        'red',
        'green',
        'blue',
        'yellow',
        'violet',
        'navy',
      ],
    };
  }

  get name() {
    return 'panel-league-sandbox';
  }

  get maximumPlayerCount() {
    return Number.MAX_VALUE;
  }

  shouldStartGame() {
    return true;
  }

  shouldStopGame() {
    return false;
  }
}

class PuyoEndlessMode extends GameMode {
  get engineOptions() {
    return { stepper: 'puyo:endless' };
  }

  get name() {
    return 'puyo:endless';
  }

  get maximumPlayerCount() {
    return 1;
  }

  shouldStep(game) {
    return game.engine.callStepper('canStep');
  }

  shouldSendClock() {
    return true;
  }
}

class PuyoDuelMode extends GameMode {
  get engineOptions() {
    return { stepper: 'puyo:duel' };
  }

  get name() {
    return 'puyo:duel';
  }

  get maximumPlayerCount() {
    return 2;
  }

  shouldStep(game) {
    return game.engine.callStepper('canStep');
  }

  shouldSendClock() {
    return true;
  }
}

const gameModeFactory = ((name) => {
  switch (name) {
    case 'panel-league-duel':
      return new GameMode();
    case 'panel-league-sandbox':
      return new SandboxMode();
    case 'puyo:endless':
      return new PuyoEndlessMode();
    case 'puyo:duel':
      return new PuyoDuelMode();
    default:
      throw new Error(`Unrecognized game mode: ${name}`);
  }
});

module.exports = gameModeFactory;
<|endoftext|>


<commit_before>function ServiceLocator() {
  this.instances = {};
  this.serviceRegistrars = {};
}

ServiceLocator.prototype.get = function(name) {
  if (this.instances[name]) {
    return this.instances[name];
  }
  if (this.serviceRegistrars[name]) {
    return this.instances[name] = this.serviceRegistrars[name]();
  }
  throw new Error('Service `' + name + '` not found');
};

ServiceLocator.prototype.register = function(name, service) {
  if (service instanceof Function) {
    this.serviceRegistrars[name] = service;
  } else {
    this.instances[name] = service;
  }
};

ServiceLocator.prototype.reset = function() {
  this.serviceRegistrars = {};
  this.instances = {};
};

module.exports = new ServiceLocator();
<commit_msg>remove duplication<commit_after>function ServiceLocator() {
  this.reset();
}

ServiceLocator.prototype.get = function(name) {
  if (this.instances[name]) {
    return this.instances[name];
  }
  if (this.serviceRegistrars[name]) {
    return this.instances[name] = this.serviceRegistrars[name]();
  }
  throw new Error('Service `' + name + '` not found');
};

ServiceLocator.prototype.register = function(name, service) {
  if (service instanceof Function) {
    this.serviceRegistrars[name] = service;
  } else {
    this.instances[name] = service;
  }
};

ServiceLocator.prototype.reset = function() {
  this.serviceRegistrars = {};
  this.instances = {};
};

module.exports = new ServiceLocator();
<|endoftext|>