<commit_before>/*
Language: Python
*/

hljs.LANGUAGES.python = {
  defaultMode: {
    lexems: [hljs.UNDERSCORE_IDENT_RE],
    illegal: '(</|->)',
    contains: ['comment', 'string', 'function', 'class', 'number', 'decorator'],
    keywords: {
      'keyword': {'and': 1, 'elif': 1, 'is': 1, 'global': 1, 'as': 1, 'in': 1, 'if': 1, 'from': 1, 'raise': 1, 'for': 1, 'except': 1, 'finally': 1, 'print': 1, 'import': 1, 'pass': 1, 'return': 1, 'exec': 1, 'else': 1, 'break': 1, 'not': 1, 'with': 1, 'class': 1, 'assert': 1, 'yield': 1, 'try': 1, 'while': 1, 'continue': 1, 'del': 1, 'or': 1, 'def': 1, 'lambda': 1, 'nonlocal': 10},
      'built_in': {'None': 1, 'True': 1, 'False': 1, 'Ellipsis': 1, 'NotImplemented': 1}
    }
  },
  modes: [
    {
      className: 'function',
      lexems: [hljs.UNDERSCORE_IDENT_RE],
      begin: '\\bdef ', end: ':',
      illegal: '$',
      keywords: {'def': 1},
      contains: ['title', 'params'],
      relevance: 10
    },
    {
      className: 'class',
      lexems: [hljs.UNDERSCORE_IDENT_RE],
      begin: '\\bclass ', end: ':',
      illegal: '[${]',
      keywords: {'class': 1},
      contains: ['title', 'params'],
      relevance: 10
    },
    {
      className: 'title',
      begin: hljs.UNDERSCORE_IDENT_RE, end: '^'
    },
    {
      className: 'params',
      begin: '\\(', end: '\\)',
      contains: ['string']
    },
    hljs.HASH_COMMENT_MODE,
    hljs.C_NUMBER_MODE,
    {
      className: 'string',
      begin: 'u?r?\'\'\'', end: '\'\'\'',
      relevance: 10
    },
    {
      className: 'string',
      begin: 'u?r?"""', end: '"""',
      relevance: 10
    },
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE,
    hljs.BACKSLASH_ESCAPE,
    {
      className: 'string',
      begin: '(u|r|ur)\'', end: '\'',
      contains: ['escape'],
      relevance: 10
    },
    {
      className: 'string',
      begin: '(u|r|ur)"', end: '"',
      contains: ['escape'],
      relevance: 10
    },
    {
      className: 'decorator',
      begin: '@', end: '$'
    }
  ]
};
<commit_msg>Added '?' as illegal symbol in Python<commit_after>/*
Language: Python
*/

hljs.LANGUAGES.python = {
  defaultMode: {
    lexems: [hljs.UNDERSCORE_IDENT_RE],
    illegal: '(</|->|\\?)',
    contains: ['comment', 'string', 'function', 'class', 'number', 'decorator'],
    keywords: {
      'keyword': {'and': 1, 'elif': 1, 'is': 1, 'global': 1, 'as': 1, 'in': 1, 'if': 1, 'from': 1, 'raise': 1, 'for': 1, 'except': 1, 'finally': 1, 'print': 1, 'import': 1, 'pass': 1, 'return': 1, 'exec': 1, 'else': 1, 'break': 1, 'not': 1, 'with': 1, 'class': 1, 'assert': 1, 'yield': 1, 'try': 1, 'while': 1, 'continue': 1, 'del': 1, 'or': 1, 'def': 1, 'lambda': 1, 'nonlocal': 10},
      'built_in': {'None': 1, 'True': 1, 'False': 1, 'Ellipsis': 1, 'NotImplemented': 1}
    }
  },
  modes: [
    {
      className: 'function',
      lexems: [hljs.UNDERSCORE_IDENT_RE],
      begin: '\\bdef ', end: ':',
      illegal: '$',
      keywords: {'def': 1},
      contains: ['title', 'params'],
      relevance: 10
    },
    {
      className: 'class',
      lexems: [hljs.UNDERSCORE_IDENT_RE],
      begin: '\\bclass ', end: ':',
      illegal: '[${]',
      keywords: {'class': 1},
      contains: ['title', 'params'],
      relevance: 10
    },
    {
      className: 'title',
      begin: hljs.UNDERSCORE_IDENT_RE, end: '^'
    },
    {
      className: 'params',
      begin: '\\(', end: '\\)',
      contains: ['string']
    },
    hljs.HASH_COMMENT_MODE,
    hljs.C_NUMBER_MODE,
    {
      className: 'string',
      begin: 'u?r?\'\'\'', end: '\'\'\'',
      relevance: 10
    },
    {
      className: 'string',
      begin: 'u?r?"""', end: '"""',
      relevance: 10
    },
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE,
    hljs.BACKSLASH_ESCAPE,
    {
      className: 'string',
      begin: '(u|r|ur)\'', end: '\'',
      contains: ['escape'],
      relevance: 10
    },
    {
      className: 'string',
      begin: '(u|r|ur)"', end: '"',
      contains: ['escape'],
      relevance: 10
    },
    {
      className: 'decorator',
      begin: '@', end: '$'
    }
  ]
};
<|endoftext|>


<commit_before>import _ from 'lodash'
import React, { Component } from 'react';
import { Line } from 'react-chartjs-2';
import { Button } from 'semantic-ui-react';

// Logic
import { getSNAPBenefits } from '../programs/federal/snap';
import { getHousingBenefit } from '../programs/massachusetts/housing';
import {
  formatAxis,
  formatTitle,
  formatLabel,
  stackedTitle
} from '../utils/charts/chartFunctions';

// Data
import { PROGRAM_CHART_VALUES } from '../utils/charts/PROGRAM_CHART_VALUES';

// Our Components
import { FormPartsContainer } from './formHelpers';

const SNAP_COLOR    = PROGRAM_CHART_VALUES.SNAP.color,
      SNAP_NAME     = PROGRAM_CHART_VALUES.SNAP.name,
      SECTION8_COLOR = PROGRAM_CHART_VALUES.section8.color,
      SECTION8_NAME  = PROGRAM_CHART_VALUES.section8.name,
      INCOME_COLOR   = PROGRAM_CHART_VALUES.income.color,
      INCOME_NAME    = PROGRAM_CHART_VALUES.income.name;

const MAX_X_MONTHLY = 100000/12;

const MULTIPLIERS = {
  'Weekly': 1/(4 + 1/3),
  'Monthly': 1,
  'Yearly': 12
};

// const income = props.client.future.earned * 12;

class verticalLinePlugin {

  constructor () {
    this.xRange = [];
    this.income = 0;
  }

  afterDatasetsDraw = ( chart ) => {
    const xRange = this.xRange,
          income = this.income;

    const i = xRange.findIndex(val => income < val);
    const positionBetweenTwoPoints = (income - xRange[i - 1]) / (xRange[i] - xRange[i - 1]);

    const data = chart.getDatasetMeta(0).data;
    const prevX = data[i - 1]._model.x;
    const currX = data[i]._model.x;
    const offset = Math.floor(positionBetweenTwoPoints * (currX - prevX) + prevX);

    const ctx = chart.chart.ctx;
    const scale = chart.scales['y-axis-0'];

    ctx.save();

    ctx.beginPath();
    ctx.strokeStyle = 'rgba(50, 50, 50, 0.5)';
    ctx.lineWidth = 2;
    ctx.setLineDash([5, 5]);
    ctx.moveTo(offset, scale.top);
    ctx.lineTo(offset, scale.bottom);
    ctx.stroke();

    ctx.restore();
  }
};

const GraphButton = function ({ id, activeID, onClick }) {
  return (
    <Button id={id} active={activeID === id} onClick={onClick}>
      {id}
    </Button>
  );
};  // End <GraphButton>

const GraphTimeButtons = function ({ activeID, onClick }) {
  return (
    <Button.Group basic className='graph-time-options'>
      <GraphButton id={'Weekly'} activeID={activeID} onClick={onClick}/>
      <GraphButton id={'Monthly'} activeID={activeID} onClick={onClick}/>
      <GraphButton id={'Yearly'} activeID={activeID} onClick={onClick}/>
    </Button.Group>
  );
};  // End <GraphTimeButtons>

const getFauxSNAP = function ( xRange, client, multiplier ) {
  /** Need a new object so client's data doesn't get changed. */
  var fakeClient = _.cloneDeep( client );
  var data = xRange.map( function ( income ) {
    fakeClient.future.earned = income / multiplier;  // Turn it back into monthly
    return getSNAPBenefits( fakeClient, 'future' ) * multiplier;
  });

  return data;
};  // End getFauxSNAP

const getFauxSec8 = function ( xRange, client, multiplier ) {
  /** Need a new object so client's data doesn't get changed. */
  var fakeClient = _.cloneDeep( client );

  fakeClient.current.contractRent = fakeClient.current.contractRent || 1000;
  fakeClient.current.earned       = 0;

  var data = xRange.map( function ( income ) {
    // New renting data
    fakeClient.future.earned  = income / multiplier;  // Turn it back into monthly
    var monthlySubsidy        = getHousingBenefit( fakeClient, 'future' );

    // Prep for next loop
    // Will use current values to calculate new values
    var newShare                  = fakeClient.current.contractRent - monthlySubsidy;
    fakeClient.current.rentShare  = newShare;
    fakeClient.current.earned     = fakeClient.future.earned;

    return monthlySubsidy * multiplier;
  });

  return data;
}

// ===============
// GRAPH DATA
// ===============
/* Note: default tooltip for chart.js 2.0+:
 * options: { tooltips: { callbacks: {
 *  label: function(tooltipItem, data) {
 *    return tooltipItem.yLabel;
 *  }
 * }}}
 */
class GrossGraph extends Component {

  constructor ( props ) {
    super( props );
    this.state = {
      verticalLine: new verticalLinePlugin()
    }
  }

  render () {
    const { client, multiplier } = this.props;

    // Adjust to time-interval, round to hundreds
    var max       = Math.ceil((MAX_X_MONTHLY * multiplier)/100) * 100,
        interval  = Math.ceil((max/100)/10) * 10;

    var xRange = _.range(0, max, interval);

    /** Need a new object so client's data doesn't get changed. */
    var income      = client.current.earned * multiplier,
        snapData    = getFauxSNAP( xRange, client, multiplier ),
        sec8Data    = getFauxSec8( xRange, client, multiplier ),
        incomeData  = xRange;

    // react-chartjs-2 keeps references to plugins, so we
    // have to mutate that reference
    this.state.verticalLine.xRange = xRange;
    this.state.verticalLine.income = income;

    var stackedAreaProps = {
      data: {
        labels: xRange,
        datasets: [
          {
            label: INCOME_NAME,
            backgroundColor: INCOME_COLOR,
            data: incomeData,
            fill: "origin"
          },
          {
            label: SNAP_NAME,
            backgroundColor: SNAP_COLOR,
            data: snapData
          },
          {
            label: SECTION8_NAME,
            backgroundColor: SECTION8_COLOR,
            data: sec8Data
          },
        ]  // end `datasets`
      },  // end `data`
      options: {
        title: {
          display: true,
          text: 'All Money Coming in as Income Changes'
        },  // end `title`
        elements: {
          line: { fill: '-1' },
          point: {
            radius: 0,
            hitRadius: 10,
            hoverRadius: 10
          }
        },  // end `elements`
        scales: {
          yAxes: [{
            stacked: true,
            scaleLabel: {
              display: true,
              labelString: 'Total Money Coming In ($)'
            },
            ticks: {
              beginAtZero: true,
              callback: formatAxis
            }
          }],  // end `yAxes`
          xAxes: [{
            stacked: true,
            scaleLabel: {
              display: true,
              labelString: 'Annual Income ($)'
            },
            ticks: {
              callback: formatAxis
            }
          }]  // end `xAxes`
        },  // end `scales`
        tooltips: {
          callbacks: {
            title: stackedTitle,
            label: formatLabel
          }
        }  // end `tooltips`
      },  // end `options`
      plugins: [this.state.verticalLine]
    };  // end `stackedAreaProps`

    return (
      <Line {...stackedAreaProps} />
    );
  }
};  // End <GrossGraph>

class BenefitGraph extends Component {

  constructor ( props ) {
    super( props );
    this.state = {
      verticalLine: new verticalLinePlugin()
    }
  }

  render () {
    const { client, multiplier } = this.props;

    // Adjust to time-interval, round to hundreds
    var max       = Math.ceil((MAX_X_MONTHLY * multiplier)/100) * 100,
        interval  = Math.ceil((max/100)/10) * 10;

    var xRange = _.range(0, max, interval);

    var income    = client.current.earned * multiplier,
        snapData  = getFauxSNAP( xRange, client, multiplier ),
        sec8Data  = getFauxSec8( xRange, client, multiplier );

    // react-chartjs-2 keeps references to plugins, so we
    // have to mutate that reference
    this.state.verticalLine.xRange = xRange;
    this.state.verticalLine.income = income;

    var lineProps = {
      data: {
        labels: xRange,
        datasets: [
          {
            label: SNAP_NAME,
            borderColor: SNAP_COLOR,
            data: snapData,
            fill: false,
            lineTension: 0
          },
          {
            label: SECTION8_NAME,
            borderColor: SECTION8_COLOR,
            data: sec8Data,
            fill: false,
            lineTension: 0
          },
        ]
      },  // end `data`
      options: {
        title: {
          display: true,
            text: 'Individual Benefit Amounts for Household as Income Changes'
        },
        showLines: true,
        scales: {
          yAxes: [{
            scaleLabel: {
              display: true,
              labelString: 'Benefit Value ($)'
            },
            ticks: {
              beginAtZero: true,
              /* chart.js v2.7 requires a callback function */
              callback: formatAxis
            }
          }],  // end `yAxes`
          xAxes: [{
            scaleLabel: {
              display: true,
              labelString: 'Annual Income ($)'
            },
            ticks: {
              callback: formatAxis
            }
          }]  // end `xAxes`
        },  // end `scales`
        tooltips: {
          callbacks: {
            title: formatTitle,
            label: formatLabel
          }
        }  // end `tooltips`
      },  // end `options`
      plugins: [this.state.verticalLine]
    };  // end lineProps

    return (
      <Line {...lineProps} />
    );
  }

};  // End <BenefitGraph>

class GraphHolder extends Component {

  constructor ( props ) {
    super( props );
    this.state = { activeID: 'Yearly', multiplier: MULTIPLIERS[ 'Yearly' ] };
  }

  onClick = ( evnt ) => {
    var id = evnt.target.id;
    this.setState({ activeID: id, multiplier: MULTIPLIERS[ id ] });
  }

  render () {
    const { activeID, multiplier }  = this.state,
          { Graph, client }         = this.props;

    return (

        <Graph client={client} multiplier={multiplier} />
        <GraphTimeButtons activeID={activeID} onClick={this.onClick} />

    );
  };  // End render()

};  // End <GraphHolder>

const ResultsGraph = ({ client, previousStep, resetClient }) => {

  return (

      <FormPartsContainer
        title     = {'Graphs'}
        left      = {{ name: 'Go Back', func: previousStep }}
        right     = {{ name: 'Reset', func: resetClient }}
      >
        <GraphHolder client={client} Graph={BenefitGraph} />
        <GraphHolder client={client} Graph={GrossGraph} />
      </FormPartsContainer>

  )

};  // End Results()

export default ResultsGraph
<commit_msg>Hack to sneak around state change warning. Bad news.<commit_after>import _ from 'lodash'
import React, { Component } from 'react';
import { Line } from 'react-chartjs-2';
import { Button } from 'semantic-ui-react';

// Logic
import { getSNAPBenefits } from '../programs/federal/snap';
import { getHousingBenefit } from '../programs/massachusetts/housing';
import {
  formatAxis,
  formatTitle,
  formatLabel,
  stackedTitle
} from '../utils/charts/chartFunctions';

// Data
import { PROGRAM_CHART_VALUES } from '../utils/charts/PROGRAM_CHART_VALUES';

// Our Components
import { FormPartsContainer } from './formHelpers';

const SNAP_COLOR    = PROGRAM_CHART_VALUES.SNAP.color,
      SNAP_NAME     = PROGRAM_CHART_VALUES.SNAP.name,
      SECTION8_COLOR = PROGRAM_CHART_VALUES.section8.color,
      SECTION8_NAME  = PROGRAM_CHART_VALUES.section8.name,
      INCOME_COLOR   = PROGRAM_CHART_VALUES.income.color,
      INCOME_NAME    = PROGRAM_CHART_VALUES.income.name;

const MAX_X_MONTHLY = 100000/12;

const MULTIPLIERS = {
  'Weekly': 1/(4 + 1/3),
  'Monthly': 1,
  'Yearly': 12
};

// const income = props.client.future.earned * 12;

class verticalLinePlugin {

  constructor () {
    this.xRange = [];
    this.income = 0;
  }

  afterDatasetsDraw = ( chart ) => {
    const xRange = this.xRange,
          income = this.income;

    const i = xRange.findIndex(val => income < val);
    const positionBetweenTwoPoints = (income - xRange[i - 1]) / (xRange[i] - xRange[i - 1]);

    const data = chart.getDatasetMeta(0).data;
    const prevX = data[i - 1]._model.x;
    const currX = data[i]._model.x;
    const offset = Math.floor(positionBetweenTwoPoints * (currX - prevX) + prevX);

    const ctx = chart.chart.ctx;
    const scale = chart.scales['y-axis-0'];

    ctx.save();

    ctx.beginPath();
    ctx.strokeStyle = 'rgba(50, 50, 50, 0.5)';
    ctx.lineWidth = 2;
    ctx.setLineDash([5, 5]);
    ctx.moveTo(offset, scale.top);
    ctx.lineTo(offset, scale.bottom);
    ctx.stroke();

    ctx.restore();
  }
};

const GraphButton = function ({ id, activeID, onClick }) {
  return (
    <Button id={id} active={activeID === id} onClick={onClick}>
      {id}
    </Button>
  );
};  // End <GraphButton>

const GraphTimeButtons = function ({ activeID, onClick }) {
  return (
    <Button.Group basic className='graph-time-options'>
      <GraphButton id={'Weekly'} activeID={activeID} onClick={onClick}/>
      <GraphButton id={'Monthly'} activeID={activeID} onClick={onClick}/>
      <GraphButton id={'Yearly'} activeID={activeID} onClick={onClick}/>
    </Button.Group>
  );
};  // End <GraphTimeButtons>

const getFauxSNAP = function ( xRange, client, multiplier ) {
  /** Need a new object so client's data doesn't get changed. */
  var fakeClient = _.cloneDeep( client );
  var data = xRange.map( function ( income ) {
    fakeClient.future.earned = income / multiplier;  // Turn it back into monthly
    return getSNAPBenefits( fakeClient, 'future' ) * multiplier;
  });

  return data;
};  // End getFauxSNAP

const getFauxSec8 = function ( xRange, client, multiplier ) {
  /** Need a new object so client's data doesn't get changed. */
  var fakeClient = _.cloneDeep( client );

  fakeClient.current.contractRent = fakeClient.current.contractRent || 1000;
  fakeClient.current.earned       = 0;

  var data = xRange.map( function ( income ) {
    // New renting data
    fakeClient.future.earned  = income / multiplier;  // Turn it back into monthly
    var monthlySubsidy        = getHousingBenefit( fakeClient, 'future' );

    // Prep for next loop
    // Will use current values to calculate new values
    var newShare                  = fakeClient.current.contractRent - monthlySubsidy;
    fakeClient.current.rentShare  = newShare;
    fakeClient.current.earned     = fakeClient.future.earned;

    return monthlySubsidy * multiplier;
  });

  return data;
}

// ===============
// GRAPH DATA
// ===============
/* Note: default tooltip for chart.js 2.0+:
 * options: { tooltips: { callbacks: {
 *  label: function(tooltipItem, data) {
 *    return tooltipItem.yLabel;
 *  }
 * }}}
 */
class GrossGraph extends Component {

  constructor ( props ) {
    super( props );
    this.state = {
      verticalLine: new verticalLinePlugin()
    }
  }

  render () {
    const { client, multiplier } = this.props;

    // Adjust to time-interval, round to hundreds
    var max       = Math.ceil((MAX_X_MONTHLY * multiplier)/100) * 100,
        interval  = Math.ceil((max/100)/10) * 10;

    var xRange = _.range(0, max, interval);

    /** Need a new object so client's data doesn't get changed. */
    var income      = client.current.earned * multiplier,
        snapData    = getFauxSNAP( xRange, client, multiplier ),
        sec8Data    = getFauxSec8( xRange, client, multiplier ),
        incomeData  = xRange;

    // react-chartjs-2 keeps references to plugins, so we
    // have to mutate that reference
    var hack    = this.state.verticalLine;
    hack.xRange = xRange;
    hack.income = income;

    var stackedAreaProps = {
      data: {
        labels: xRange,
        datasets: [
          {
            label: INCOME_NAME,
            backgroundColor: INCOME_COLOR,
            data: incomeData,
            fill: "origin"
          },
          {
            label: SNAP_NAME,
            backgroundColor: SNAP_COLOR,
            data: snapData
          },
          {
            label: SECTION8_NAME,
            backgroundColor: SECTION8_COLOR,
            data: sec8Data
          },
        ]  // end `datasets`
      },  // end `data`
      options: {
        title: {
          display: true,
          text: 'All Money Coming in as Income Changes'
        },  // end `title`
        elements: {
          line: { fill: '-1' },
          point: {
            radius: 0,
            hitRadius: 10,
            hoverRadius: 10
          }
        },  // end `elements`
        scales: {
          yAxes: [{
            stacked: true,
            scaleLabel: {
              display: true,
              labelString: 'Total Money Coming In ($)'
            },
            ticks: {
              beginAtZero: true,
              callback: formatAxis
            }
          }],  // end `yAxes`
          xAxes: [{
            stacked: true,
            scaleLabel: {
              display: true,
              labelString: 'Annual Income ($)'
            },
            ticks: {
              callback: formatAxis
            }
          }]  // end `xAxes`
        },  // end `scales`
        tooltips: {
          callbacks: {
            title: stackedTitle,
            label: formatLabel
          }
        }  // end `tooltips`
      },  // end `options`
      plugins: [this.state.verticalLine]
    };  // end `stackedAreaProps`

    return (
      <Line {...stackedAreaProps} />
    );
  }
};  // End <GrossGraph>

class BenefitGraph extends Component {

  constructor ( props ) {
    super( props );
    this.state = {
      verticalLine: new verticalLinePlugin()
    }
  }

  render () {
    const { client, multiplier } = this.props;

    // Adjust to time-interval, round to hundreds
    var max       = Math.ceil((MAX_X_MONTHLY * multiplier)/100) * 100,
        interval  = Math.ceil((max/100)/10) * 10;

    var xRange = _.range(0, max, interval);

    var income    = client.current.earned * multiplier,
        snapData  = getFauxSNAP( xRange, client, multiplier ),
        sec8Data  = getFauxSec8( xRange, client, multiplier );

    // react-chartjs-2 keeps references to plugins, so we
    // have to mutate that reference
    var hack    = this.state.verticalLine;
    hack.xRange = xRange;
    hack.income = income;

    var lineProps = {
      data: {
        labels: xRange,
        datasets: [
          {
            label: SNAP_NAME,
            borderColor: SNAP_COLOR,
            data: snapData,
            fill: false,
            lineTension: 0
          },
          {
            label: SECTION8_NAME,
            borderColor: SECTION8_COLOR,
            data: sec8Data,
            fill: false,
            lineTension: 0
          },
        ]
      },  // end `data`
      options: {
        title: {
          display: true,
            text: 'Individual Benefit Amounts for Household as Income Changes'
        },
        showLines: true,
        scales: {
          yAxes: [{
            scaleLabel: {
              display: true,
              labelString: 'Benefit Value ($)'
            },
            ticks: {
              beginAtZero: true,
              /* chart.js v2.7 requires a callback function */
              callback: formatAxis
            }
          }],  // end `yAxes`
          xAxes: [{
            scaleLabel: {
              display: true,
              labelString: 'Annual Income ($)'
            },
            ticks: {
              callback: formatAxis
            }
          }]  // end `xAxes`
        },  // end `scales`
        tooltips: {
          callbacks: {
            title: formatTitle,
            label: formatLabel
          }
        }  // end `tooltips`
      },  // end `options`
      plugins: [this.state.verticalLine]
    };  // end lineProps

    return (
      <Line {...lineProps} />
    );
  }

};  // End <BenefitGraph>

class GraphHolder extends Component {

  constructor ( props ) {
    super( props );
    this.state = { activeID: 'Yearly', multiplier: MULTIPLIERS[ 'Yearly' ] };
  }

  onClick = ( evnt ) => {
    var id = evnt.target.id;
    this.setState({ activeID: id, multiplier: MULTIPLIERS[ id ] });
  }

  render () {
    const { activeID, multiplier }  = this.state,
          { Graph, client }         = this.props;

    return (

        <Graph client={client} multiplier={multiplier} />
        <GraphTimeButtons activeID={activeID} onClick={this.onClick} />

    );
  };  // End render()

};  // End <GraphHolder>

const ResultsGraph = ({ client, previousStep, resetClient }) => {

  return (

      <FormPartsContainer
        title     = {'Graphs'}
        left      = {{ name: 'Go Back', func: previousStep }}
        right     = {{ name: 'Reset', func: resetClient }}
      >
        <GraphHolder client={client} Graph={BenefitGraph} />
        <GraphHolder client={client} Graph={GrossGraph} />
      </FormPartsContainer>

  )

};  // End Results()

export default ResultsGraph
<|endoftext|>


<commit_before>"use strict";

var App = require('../app'),
    views = require('./views'),
    coreUtils= require('../core/utils');

var ProjectsController = {
    projects: function() {
        App.rootView.footerRegion.show(
            new views.ProjectsView()
        );

        App.rootView.layerPickerRegion.empty();

        App.state.set('active_page', coreUtils.projectsPageTitle);
    },

    projectsCleanUp: function() {
        App.rootView.footerRegion.empty();
        App.showLayerPicker();
    }
};

module.exports = {
    ProjectsController: ProjectsController
};
<commit_msg>Remove search bar when project page is launched<commit_after>"use strict";

var App = require('../app'),
    views = require('./views'),
    coreUtils= require('../core/utils');

var ProjectsController = {
    projectsPrepare: function() {
        App.rootView.geocodeSearchRegion.empty();
    },

    projects: function() {
        App.rootView.footerRegion.show(
            new views.ProjectsView()
        );

        App.rootView.layerPickerRegion.empty();

        App.state.set('active_page', coreUtils.projectsPageTitle);
    },

    projectsCleanUp: function() {
        App.rootView.footerRegion.empty();
        App.showLayerPicker();
    }
};

module.exports = {
    ProjectsController: ProjectsController
};
<|endoftext|>


<commit_before>import BoardReducer from './BoardReducer.js';
import { ActionTypes } from '../../actions/Actions.js';

export default function GameStateReducer(gameState, action) {
  switch (action.type) {
    case ActionTypes.SetGameState: {
      return action.gameState;
    }
    case ActionTypes.ChooseResourceFromStack: {
      return { ...gameState, board: BoardReducer(gameState.board, action) };
    }
    default: return gameState;
  }
}
<commit_msg>Preventing user from selecting resources during other players' rounds.<commit_after>import BoardReducer from './BoardReducer.js';
import { ActionTypes } from '../../actions/Actions.js';

export default function GameStateReducer(gameState, action) {
  switch (action.type) {
    case ActionTypes.SetGameState: {
      return action.gameState;
    }
    case ActionTypes.ChooseResourceFromStack: {
      if (gameState.currentPlayerIndex === 0) {
        return {...gameState, board: BoardReducer(gameState.board, action)};
      } else {
        return gameState;
      }
    }
    default: return gameState;
  }
}
<|endoftext|>


<commit_before>/* global cozy */
import * as triggers from 'lib/triggers'

import CozyRealtime from 'cozy-realtime'

export const CONNECTION_STATUS = {
  ERRORED: 'errored',
  RUNNING: 'running',
  CONNECTED: 'connected'
}

const ACCOUNTS_DOCTYPE = 'io.cozy.accounts'
const JOBS_DOCTYPE = 'io.cozy.jobs'
const TRIGGERS_DOCTYPE = 'io.cozy.triggers'

const normalize = (dbObject, doctype) => {
  return {
    ...dbObject,
    ...dbObject.attributes,
    id: dbObject._id,
    _type: doctype || dbObject._type
  }
}

export default class CollectStore {
  constructor(context, client, options = {}) {
    this.client = client
    this.listener = null
    this.options = options

    this.categories = require('../config/categories')

    this.updateUnfinishedJob = this.updateUnfinishedJob.bind(this)
    this.onAccountCreated = this.onAccountCreated.bind(this)
    this.onAccountUpdated = this.onAccountUpdated.bind(this)
    this.onAccountDeleted = this.onAccountDeleted.bind(this)
    this.onTriggerCreated = this.onTriggerCreated.bind(this)
    this.onTriggerDeleted = this.onTriggerDeleted.bind(this)

    this.initializeRealtime()
  }

  initializeRealtime() {
    this.realtime = new CozyRealtime({ client: this.client })

    this.realtime.subscribe('created', JOBS_DOCTYPE, this.updateUnfinishedJob)
    this.realtime.subscribe('updated', JOBS_DOCTYPE, this.updateUnfinishedJob)

    this.realtime.subscribe('created', ACCOUNTS_DOCTYPE, this.onAccountCreated)
    this.realtime.subscribe('updated', ACCOUNTS_DOCTYPE, this.onAccountUpdated)
    this.realtime.subscribe('deleted', ACCOUNTS_DOCTYPE, this.onAccountDeleted)

    this.realtime.subscribe('created', TRIGGERS_DOCTYPE, this.onTriggerCreated)
    this.realtime.subscribe('deleted', TRIGGERS_DOCTYPE, this.onTriggerDeleted)
  }

  async onAccountCreated(account) {
    this.dispatch({
      type: 'RECEIVE_NEW_DOCUMENT',
      response: { data: [normalize(account, ACCOUNTS_DOCTYPE)] },
      updateCollections: ['accounts']
    })
  }

  async onAccountUpdated(account) {
    this.dispatch({
      type: 'RECEIVE_UPDATED_DOCUMENT',
      response: { data: [normalize(account, ACCOUNTS_DOCTYPE)] },
      updateCollections: ['accounts']
    })
  }

  async onAccountDeleted(account) {
    this.dispatch({
      type: 'RECEIVE_DELETED_DOCUMENT',
      response: { data: [normalize(account, ACCOUNTS_DOCTYPE)] },
      updateCollections: ['accounts']
    })
  }

  async onTriggerCreated(trigger) {
    this.dispatch({
      type: 'RECEIVE_NEW_DOCUMENT',
      response: { data: [normalize(trigger, TRIGGERS_DOCTYPE)] },
      updateCollections: ['triggers']
    })
  }

  async onTriggerUpdated(trigger) {
    this.dispatch({
      type: 'RECEIVE_UPDATED_DOCUMENT',
      response: { data: [normalize(trigger, TRIGGERS_DOCTYPE)] },
      updateCollections: ['triggers']
    })
  }

  async onTriggerDeleted(trigger) {
    this.dispatch({
      type: 'RECEIVE_DELETED_DOCUMENT',
      response: { data: [normalize(trigger, TRIGGERS_DOCTYPE)] },
      updateCollections: ['triggers']
    })
  }

  async updateUnfinishedJob(job) {
    const normalizedJob = normalize(job, JOBS_DOCTYPE)
    // TODO Filter by worker on the WebSocket when it will be available in the
    // stack
    const isKonnectorJob = normalizedJob.worker === 'konnector'
    const isDeletedAccountHookJob = !!normalizedJob.account_deleted
    if (!isKonnectorJob || isDeletedAccountHookJob) {
      return
    }

    this.dispatch({
      type: 'RECEIVE_NEW_DOCUMENT',
      response: { data: [normalizedJob] },
      updateCollections: ['jobs']
    })
    const trigger = await triggers.fetch(cozy.client, normalizedJob.trigger_id)
    this.onTriggerUpdated(trigger)
  }

  createIntentService(intent, window) {
    return cozy.client.intents.createService(intent, window)
  }
}
<commit_msg>fix: Revert this remove to keep intent working<commit_after>/* global cozy */
import * as triggers from 'lib/triggers'

import CozyRealtime from 'cozy-realtime'

export const CONNECTION_STATUS = {
  ERRORED: 'errored',
  RUNNING: 'running',
  CONNECTED: 'connected'
}

const ACCOUNTS_DOCTYPE = 'io.cozy.accounts'
const JOBS_DOCTYPE = 'io.cozy.jobs'
const TRIGGERS_DOCTYPE = 'io.cozy.triggers'

const normalize = (dbObject, doctype) => {
  return {
    ...dbObject,
    ...dbObject.attributes,
    id: dbObject._id,
    _type: doctype || dbObject._type
  }
}

export default class CollectStore {
  constructor(context, client, options = {}) {
    this.client = client
    this.listener = null
    this.options = options

    this.categories = require('../config/categories')

    this.updateUnfinishedJob = this.updateUnfinishedJob.bind(this)
    this.onAccountCreated = this.onAccountCreated.bind(this)
    this.onAccountUpdated = this.onAccountUpdated.bind(this)
    this.onAccountDeleted = this.onAccountDeleted.bind(this)
    this.onTriggerCreated = this.onTriggerCreated.bind(this)
    this.onTriggerDeleted = this.onTriggerDeleted.bind(this)

    this.initializeRealtime()
  }

  initializeRealtime() {
    this.realtime = new CozyRealtime({ client: this.client })

    this.realtime.subscribe('created', JOBS_DOCTYPE, this.updateUnfinishedJob)
    this.realtime.subscribe('updated', JOBS_DOCTYPE, this.updateUnfinishedJob)

    this.realtime.subscribe('created', ACCOUNTS_DOCTYPE, this.onAccountCreated)
    this.realtime.subscribe('updated', ACCOUNTS_DOCTYPE, this.onAccountUpdated)
    this.realtime.subscribe('deleted', ACCOUNTS_DOCTYPE, this.onAccountDeleted)

    this.realtime.subscribe('created', TRIGGERS_DOCTYPE, this.onTriggerCreated)
    this.realtime.subscribe('deleted', TRIGGERS_DOCTYPE, this.onTriggerDeleted)
  }

  async onAccountCreated(account) {
    this.dispatch({
      type: 'RECEIVE_NEW_DOCUMENT',
      response: { data: [normalize(account, ACCOUNTS_DOCTYPE)] },
      updateCollections: ['accounts']
    })
  }

  async onAccountUpdated(account) {
    this.dispatch({
      type: 'RECEIVE_UPDATED_DOCUMENT',
      response: { data: [normalize(account, ACCOUNTS_DOCTYPE)] },
      updateCollections: ['accounts']
    })
  }

  async onAccountDeleted(account) {
    this.dispatch({
      type: 'RECEIVE_DELETED_DOCUMENT',
      response: { data: [normalize(account, ACCOUNTS_DOCTYPE)] },
      updateCollections: ['accounts']
    })
  }

  async onTriggerCreated(trigger) {
    this.dispatch({
      type: 'RECEIVE_NEW_DOCUMENT',
      response: { data: [normalize(trigger, TRIGGERS_DOCTYPE)] },
      updateCollections: ['triggers']
    })
  }

  async onTriggerUpdated(trigger) {
    this.dispatch({
      type: 'RECEIVE_UPDATED_DOCUMENT',
      response: { data: [normalize(trigger, TRIGGERS_DOCTYPE)] },
      updateCollections: ['triggers']
    })
  }

  async onTriggerDeleted(trigger) {
    this.dispatch({
      type: 'RECEIVE_DELETED_DOCUMENT',
      response: { data: [normalize(trigger, TRIGGERS_DOCTYPE)] },
      updateCollections: ['triggers']
    })
  }

  async updateUnfinishedJob(job) {
    const normalizedJob = normalize(job, JOBS_DOCTYPE)
    // TODO Filter by worker on the WebSocket when it will be available in the
    // stack
    const isKonnectorJob = normalizedJob.worker === 'konnector'
    const isDeletedAccountHookJob = !!normalizedJob.account_deleted
    if (!isKonnectorJob || isDeletedAccountHookJob) {
      return
    }

    this.dispatch({
      type: 'RECEIVE_NEW_DOCUMENT',
      response: { data: [normalizedJob] },
      updateCollections: ['jobs']
    })
    const trigger = await triggers.fetch(cozy.client, normalizedJob.trigger_id)
    this.onTriggerUpdated(trigger)
  }

  createIntentService(intent, window) {
    return cozy.client.intents.createService(intent, window)
  }

  // Get the drive and banks application url using the list of application
  fetchUrls() {
    return cozy.client
      .fetchJSON('GET', '/apps/')
      .then(body => {
        body.forEach(item => {
          if (!item.attributes || !item.attributes.slug || !item.links) return
          switch (item.attributes.slug) {
            case 'banks':
              this.banksUrl = `${item.links.related}`
              break
            default:
              break
          }
        })
      })
      .catch(err => {
        // eslint-disable-next-line no-console
        console.warn(err.message)
        return false
      })
  }
}
<|endoftext|>


<commit_before>
class PolymerUtils {

    static isUndefined(obj) {
        return typeof obj === "undefined";
    }

    static isNotUndefined(obj) {
        return typeof obj !== "undefined";
    }

    static isUndefinedOrNull(obj) {
        return typeof obj === "undefined" || obj === null;
    }

    static getElementById(id) {
        return document.getElementById(id);
    }

    static getElementsByClassName(className, root) {
        if (PolymerUtils.isUndefined(root)) {
            document.getElementsByClassName(className);
        } else {
            root.getElementsByClassName(className);
        }
    }

    static querySelector(selectors) {
        return document.querySelector(selectors);
    }

    static querySelectorAll(selectors) {
        return document.querySelectorAll(selectors);
    }

    static show(id) {
        PolymerUtils.addStyle(id, display, "inline");
    }

    static hide(id) {
        PolymerUtils.addStyle(id, display, "none");
    }

    static addClass(id, className) {
        if (PolymerUtils.isUndefinedOrNull(id)) {
            let el;
            if (id.startsWith(".")) {
                // If starts with a dot then is a class, we use querySelector
                el = PolymerUtils.querySelector(id);
            } else {
                // It is an ID
                el = PolymerUtils.getElementById(id);
            }

            if (PolymerUtils.isUndefinedOrNull(el)) {
                el.classList.add(className);
            }
        }
    }

    static removeClass(id, className) {
        if (PolymerUtils.isUndefinedOrNull(id)) {
            let el;
            if (id.startsWith(".")) {
                // If starts with a dot then is a class, we use querySelector
                el = PolymerUtils.querySelector(id);
            } else {
                // It is an ID
                el = PolymerUtils.getElementById(id);
            }

            if (PolymerUtils.isUndefinedOrNull(el)) {
                el.classList.remove(className);
            }
        }
    }

    static addStyle(id, key, value) {
        if (PolymerUtils.isUndefinedOrNull(key)) {
            let el = this.getElementById(id);
            if (PolymerUtils.isUndefinedOrNull(el)) {
                el.style[key] = value;
            }
        }
    }

    static removeStyle(id, key) {
        let el = PolymerUtils.getElementById(id);
        if (PolymerUtils.isUndefinedOrNull(el)) {
            delete el.style[key];
        }
    }

    static setAttribute(id, key, value) {
        if (PolymerUtils.isUndefinedOrNull(key)) {
            let el = PolymerUtils.getElementById(id);
            if (PolymerUtils.isUndefinedOrNull(el)) {
                el.setAttribute(key, value);
            }
        }
    }

    static removeAttribute(id, key) {
        if (PolymerUtils.isUndefinedOrNull(key)) {
            let el = PolymerUtils.getElementById(id);
            if (PolymerUtils.isUndefinedOrNull(el)) {
                el.removeAttribute(key);
            }
        }
    }

}<commit_msg>lib: add some convenience functions to PolymerUtils<commit_after>
class PolymerUtils {

    static isUndefined(obj) {
        return typeof obj === "undefined";
    }

    static isNotUndefined(obj) {
        return typeof obj !== "undefined";
    }

    static isNull(obj) {
        return obj === null;
    }

    static isNotNull(obj) {
        return obj !== null;
    }

    static isUndefinedOrNull(obj) {
        return typeof obj === "undefined" || obj === null;
    }

    static isNotUndefinedOrNull(obj) {
        return typeof obj !== "undefined" && obj !== null;
    }

    static getElementById(id) {
        return document.getElementById(id);
    }

    static getElementsByClassName(className, root) {
        if (PolymerUtils.isUndefined(root)) {
            document.getElementsByClassName(className);
        } else {
            root.getElementsByClassName(className);
        }
    }

    static querySelector(selectors) {
        return document.querySelector(selectors);
    }

    static querySelectorAll(selectors) {
        return document.querySelectorAll(selectors);
    }

    static show(id) {
        PolymerUtils.addStyle(id, display, "inline");
    }

    static hide(id) {
        PolymerUtils.addStyle(id, display, "none");
    }

    static addClass(id, className) {
        if (PolymerUtils.isUndefinedOrNull(id)) {
            let el;
            if (id.startsWith(".")) {
                // If starts with a dot then is a class, we use querySelector
                el = PolymerUtils.querySelector(id);
            } else {
                // It is an ID
                el = PolymerUtils.getElementById(id);
            }

            if (PolymerUtils.isUndefinedOrNull(el)) {
                el.classList.add(className);
            }
        }
    }

    static removeClass(id, className) {
        if (PolymerUtils.isUndefinedOrNull(id)) {
            let el;
            if (id.startsWith(".")) {
                // If starts with a dot then is a class, we use querySelector
                el = PolymerUtils.querySelector(id);
            } else {
                // It is an ID
                el = PolymerUtils.getElementById(id);
            }

            if (PolymerUtils.isUndefinedOrNull(el)) {
                el.classList.remove(className);
            }
        }
    }

    static addStyle(id, key, value) {
        if (PolymerUtils.isUndefinedOrNull(key)) {
            let el = this.getElementById(id);
            if (PolymerUtils.isUndefinedOrNull(el)) {
                el.style[key] = value;
            }
        }
    }

    static removeStyle(id, key) {
        let el = PolymerUtils.getElementById(id);
        if (PolymerUtils.isUndefinedOrNull(el)) {
            delete el.style[key];
        }
    }

    static setAttribute(id, key, value) {
        if (PolymerUtils.isUndefinedOrNull(key)) {
            let el = PolymerUtils.getElementById(id);
            if (PolymerUtils.isUndefinedOrNull(el)) {
                el.setAttribute(key, value);
            }
        }
    }

    static removeAttribute(id, key) {
        if (PolymerUtils.isUndefinedOrNull(key)) {
            let el = PolymerUtils.getElementById(id);
            if (PolymerUtils.isUndefinedOrNull(el)) {
                el.removeAttribute(key);
            }
        }
    }

}<|endoftext|>


<commit_before>var clock = new THREE.Clock();

/* Setup three.js WebGL renderer */
var renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColor(new THREE.Color(0x000, 1.0));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMapEnabled = true;

/* Append the canvas element created by the renderer to document body element. */
document.body.appendChild( renderer.domElement );

/* Create a three.js scene */
var scene = new THREE.Scene();

/* Create a three.js camera */
var camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
// Position and point the camera to the center of the scene
camera.position.set(0, 70, 75);
//camera.rotate.y = 90 * Math.PI / 180;
camera.lookAt(new THREE.Vector3(0, 0, 0));

/* Apply VR headset positional data to camera. */
var controls = new THREE.VRControls( camera );

/* Apply VR stereo rendering to renderer */
var effect = new THREE.VREffect( renderer );
effect.setSize( window.innerWidth, window.innerHeight );

/* Raycaster */
var raycaster = new THREE.Raycaster();

/* Apply first person controls to the camera */
var camControls = new THREE.FirstPersonControls(camera);
camControls.lookSpeed = 0.4;
camControls.movementSpeed = 20;
camControls.noFly = true;
camControls.lookVertical = true;
camControls.constrainVertical = true;
camControls.verticalMin = 1.0;
camControls.verticalMax = 2.0;
camControls.lon = -150;
camControls.lat = 120;

// 3D area dimension variables
var roomHeight = 150;
var roomWidth = 275;
var roomLength = 275;
var wallThickness = 2;
var cornerWidth = roomWidth/8;

/* Lighting */

var spotLights = [ 	[ roomWidth*0.8, roomHeight, roomLength/2*0.8, 1 ],
					[ -roomWidth*0.8, roomHeight, roomLength/2*0.8, 1 ],
					[ roomWidth*0.8, roomHeight, -roomLength/2*0.8, 1 ],
					[ -roomWidth*0.8, roomHeight, -roomLength/2*0.8, 1 ]
					[ 0, 0, 0, 1 ]
				];

spotLights.forEach(function(light) {
    var sl = new THREE.SpotLight(0xffffff);
    sl.position.set(light[0], light[1], light[2]);
	sl.intensity = light[3];
	scene.add(sl);
});

// var ambientLight = new THREE.AmbientLight(0x383838);
// scene.add(ambientLight);

// Add axis (Dev Only)
// scene.add(new THREE.AxisHelper(150));

/* Create 3d objects */

var assignChildrenName = function(obj, name) {

	if (obj.type == "Mesh") {
		// we just need to change this..
		obj.name = name;
		return;
	}

	if (obj.children) {
		for (objIndex = 0; objIndex < obj.children.length; objIndex++) {
			// this will be the object3d
			obj3d = obj.children[objIndex];
			assignChildrenName(obj3d, name);
		}
	}
};

// Materials & Texture
var floorTexture = THREE.ImageUtils.loadTexture( "images/tile.jpg" );
floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.repeat.set( 5, 5 );

var ceilTexture = THREE.ImageUtils.loadTexture( "images/ceil3.jpg" );
ceilTexture.wrapS = ceilTexture.wrapT = THREE.RepeatWrapping;
ceilTexture.repeat.set( 3, 10 );

var matWall = new THREE.MeshPhongMaterial({color: 0xffffff});
var matFloor = new THREE.MeshBasicMaterial( { map: floorTexture, side: THREE.DoubleSide } );
var matCeiling = new THREE.MeshBasicMaterial( { map: ceilTexture, side: THREE.DoubleSide } );

// Geometries
var geoFaceWall = new THREE.BoxGeometry(roomWidth, roomHeight, wallThickness);
var geoSideWall = new THREE.BoxGeometry(wallThickness, roomHeight, roomLength);
var geoFloor = new THREE.BoxGeometry(roomWidth, wallThickness, roomLength);
var geoCorner = new THREE.BoxGeometry(cornerWidth, roomHeight, cornerWidth);
var geoWallExt = new THREE.BoxGeometry(roomWidth/30, roomHeight, roomLength*0.4);

// Environment Objects 	< name : [ geometry, material, Px, Py, Pz ] >
var components = {
	wallS : 		[ geoFaceWall, matWall, 0, roomHeight/2, -roomLength/2 - wallThickness/2 ],
	wallE : 		[ geoSideWall, matWall, -roomWidth/2 - wallThickness/2, roomHeight/2, 0 ],
	wallW : 		[ geoSideWall, matWall, roomWidth/2 + wallThickness/2, roomHeight/2, 0 ],
	wallN : 		[ geoFaceWall, matWall, 0, roomHeight/2, roomLength/2 + wallThickness/2 ],
	floor : 		[ geoFloor, matFloor,	0, wallThickness/2, 0 ],
	celing : 		[ geoFloor, matCeiling,	0, roomHeight + wallThickness/2, 0 ],
	cornerBlock : 	[ geoCorner, matWall,	-roomWidth/2 + cornerWidth/2, roomHeight/2, -roomLength/2 + cornerWidth/2 ],
	wallExt : 		[ geoWallExt, matWall,	-roomWidth/2 + roomWidth/30/2, roomHeight/2, roomLength/2 - (roomLength*0.4)/2 ],
};

for (var key in components) {
	// hasOwnProperty needed to prevent insert keys into the prototype object of dictionary
	if (components.hasOwnProperty(key)) {
		var newObject = new THREE.Mesh(components[key][0], components[key][1]);
		newObject.position.set(components[key][2], components[key][3], components[key][4]);
		newObject.name = key;

		assignChildrenName(newObject, key);
		scene.add(newObject);
	}
}

// TO DO: Need to add objects more modularly and without errors!

// Load Objects 	< filename : [ filename, scale, Px, Py, Pz ] >
var loadObjects = {
	'table1' : [ 'technicalTable1', 0.4, roomWidth/2 - 50, 36, roomLength/2 + 25 ],
	'table2' : [ 'technicalTable1', 0.4, -roomWidth/2 + 100, 36, roomLength/2 + 25 ]
};

var tableScale = 0.35;

var loader = new THREE.OBJMTLLoader();
loader.load( 'models/' + loadObjects['table1'][0] + '.obj', 'models/' + loadObjects['table1'][0] + '.mtl', function ( obj ) {

	obj.scale.set(tableScale, tableScale, tableScale);
	obj.position.x = roomWidth/2 - 50;
	obj.position.y = 36;
	obj.position.z = - roomLength/2 + 25;
	obj.name = "table";

	assignChildrenName(obj, "table");

	scene.add( obj );

}, onProgress, onError );

loader.load( 'models/technicalTable1.obj', 'models/technicalTable1.mtl', function ( obj ) {

	obj.scale.set(tableScale, tableScale, tableScale);
	obj.position.x = - roomWidth/2 + 100;
	obj.position.y = 36;
	obj.position.z = - roomLength/2 + 25;

	assignChildrenName(obj, "table");

	scene.add( obj );

}, onProgress, onError );

loader.load( 'models/technicalTable1.obj', 'models/technicalTable1.mtl', function ( obj ) {

	obj.scale.set(tableScale, tableScale, tableScale);
	obj.position.x = - roomWidth/2 + 80;
	obj.position.y = 36;
	obj.position.z = 50;
	obj.name = "table";

	assignChildrenName(obj, "table");

	scene.add( obj );

}, onProgress, onError );

loader.load( 'models/technicalTable1.obj', 'models/technicalTable1.mtl', function ( obj ) {

	obj.scale.set(tableScale, tableScale, tableScale);
	obj.position.x = roomWidth/2 - 50;
	obj.position.y = 36;
	obj.position.z = 50;
	obj.name = "table";

	assignChildrenName(obj, "table");

	scene.add( obj );

}, onProgress, onError );

loader.load( 'models/lockers.obj', 'models/lockers.mtl', function ( obj ) {

	obj.scale.set(0.70, 0.70, 0.70);
	obj.position.x = roomWidth/2 - 5;
	obj.position.y = 5;
	obj.position.z = -30;
	obj.rotation.y = 3*Math.PI/2;
	obj.name = "locker";

	assignChildrenName(obj, "locker");

	scene.add( obj );

}, onProgress, onError );

loader.load( 'models/lockers.obj', 'models/lockers.mtl', function ( obj ) {

	obj.scale.set(0.70, 0.70, 0.70);
	obj.position.x = roomWidth/2 - 5;
	obj.position.y = 37;
	obj.position.z = -30;
	obj.rotation.y = 3*Math.PI/2;
	obj.name = "locker";

	assignChildrenName(obj, "locker");

	scene.add( obj );

}, onProgress, onError );

loader.load( 'models/whiteBoard.obj', 'models/whiteBoard.mtl', function ( obj ) {

	obj.scale.set(0.40, 0.80, 0.60);
	obj.position.x = 0;
	obj.position.y = 0;
	obj.position.z = roomLength/2 - 15;
	obj.name = "whiteboard";

	assignChildrenName(obj, "whiteboard");

	scene.add( obj );
}, onProgress, onError );

loader.load( 'models/whiteBoard.obj', 'models/whiteBoard.mtl', function ( obj ) {

	obj.scale.set(0.40, 0.80, 0.60);
	obj.position.x = -80;
	obj.position.y = 0;
	obj.position.z = roomLength/2 - 15;
	obj.name = "whiteboard";

	assignChildrenName(obj, "whiteboard");

	scene.add( obj );

}, onProgress, onError );

var onProgress = function ( xhr ) {
	if ( xhr.lengthComputable ) {
		var percentComplete = xhr.loaded / xhr.total * 100;
		console.log( Math.round(percentComplete, 2) + '% downloaded' );
	}
};

var onError = function ( xhr ) {
};

function distance(v1, v2) {
	dx = v1.x - v2.x;
    // dy = v1.y - v2.y;
    dz = v1.z - v2.z;

    return Math.sqrt(dx*dx+dz*dz);
}

function checkBoundaries() {
	var plocal = new THREE.Vector3(0, 0, -1);
	var pWorld = plocal.applyMatrix4( camera.matrixWorld );
	var vec = pWorld.sub(camera.position).normalize();

	var pos = camera.position;

	var rays = [
		new THREE.Vector3(pos.x, pos.y - 30, pos.z),
		new THREE.Vector3(pos.x, pos.y, pos.z),
		new THREE.Vector3(pos.x, pos.y + 20, pos.z)
	];

	for (r = 0; r < rays.length; r++) {
		var ray = new THREE.Raycaster(rays[r], vec);
		var intersects = ray.intersectObjects( scene.children, true );

		for (z = 0; z < intersects.length; z++) {
    		if ((distance(camera.position, intersects[z].object.position) < 15) && intersects[z].object.name !== "floor") {
    			document.getElementById("info").style.display = "block";
    			document.getElementById("info").innerHTML = intersects[z].object.name;
    			return false;
    		}
    	}
	}

	document.getElementById("info").style.display = "none";
	return true;
}

/* Request animation frame loop function */
function render() {
	var delta = clock.getDelta();

	// camControls.moveForward = checkBoundaries();
	if (checkBoundaries()) {
		camControls.update(delta);
	}

	/*
	Update VR headset position and apply to camera.
	*/
	controls.update();

	/*
	Render the scene through the VREffect.
	*/
	effect.render( scene, camera );

	// Render without stero VR effect
	//renderer.render(scene, camera);

	requestAnimationFrame( render );
}

/* Kick off animation loop */
render();

/* Listen for double click event to enter full-screen VR mode */
document.body.addEventListener( 'dblclick', function() {
	effect.setFullScreen( true );
});

/* Listen for keyboard event and zero positional sensor on appropriate keypress. */
function onkey(event) {
	event.preventDefault();

	if (event.keyCode == 90) { // z
		controls.zeroSensor();

	} else if (event.keyCode == 80) { // p (pause)
		// Toggle camera look speed on/off
		(camControls.lookSpeed > 0.0) ? camControls.lookSpeed = 0.0 : camControls.lookSpeed = 0.4;
	}
};

window.addEventListener("keydown", onkey, true);

/* Handle window resizes */
function onWindowResize() {
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();

	effect.setSize( window.innerWidth, window.innerHeight );
}

window.addEventListener( 'resize', onWindowResize, false );<commit_msg>modularized adding objects to scene<commit_after>var clock = new THREE.Clock();

/* Setup three.js WebGL renderer */
var renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColor(new THREE.Color(0x000, 1.0));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMapEnabled = true;

/* Append the canvas element created by the renderer to document body element. */
document.body.appendChild( renderer.domElement );

/* Create a three.js scene */
var scene = new THREE.Scene();

/* Create a three.js camera */
var camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
// Position and point the camera to the center of the scene
camera.position.set(0, 70, 75);
//camera.rotate.y = 90 * Math.PI / 180;
camera.lookAt(new THREE.Vector3(0, 0, 0));

/* Apply VR headset positional data to camera. */
var controls = new THREE.VRControls( camera );

/* Apply VR stereo rendering to renderer */
var effect = new THREE.VREffect( renderer );
effect.setSize( window.innerWidth, window.innerHeight );

/* Raycaster */
var raycaster = new THREE.Raycaster();

/* Apply first person controls to the camera */
var camControls = new THREE.FirstPersonControls(camera);
camControls.lookSpeed = 0.4;
camControls.movementSpeed = 20;
camControls.noFly = true;
camControls.lookVertical = true;
camControls.constrainVertical = true;
camControls.verticalMin = 1.0;
camControls.verticalMax = 2.0;
camControls.lon = -150;
camControls.lat = 120;

// 3D area dimension variables
var roomHeight = 150;
var roomWidth = 275;
var roomLength = 275;
var wallThickness = 2;
var cornerWidth = roomWidth/8;

/* Lighting */

var spotLights = [ 	[ roomWidth*0.8, roomHeight, roomLength/2*0.8, 1 ],
					[ -roomWidth*0.8, roomHeight, roomLength/2*0.8, 1 ],
					[ roomWidth*0.8, roomHeight, -roomLength/2*0.8, 1 ],
					[ -roomWidth*0.8, roomHeight, -roomLength/2*0.8, 1 ]
					[ 0, 0, 0, 1 ]
				];

spotLights.forEach(function(light) {
    var sl = new THREE.SpotLight(0xffffff);
    sl.position.set(light[0], light[1], light[2]);
	sl.intensity = light[3];
	scene.add(sl);
});

// var ambientLight = new THREE.AmbientLight(0x383838);
// scene.add(ambientLight);

// Add axis (Dev Only)
// scene.add(new THREE.AxisHelper(150));

/* Create 3d objects */

var assignChildrenName = function(obj, name) {

	if (obj.type == "Mesh") {
		// we just need to change this..
		obj.name = name;
		return;
	}

	if (obj.children) {
		for (objIndex = 0; objIndex < obj.children.length; objIndex++) {
			// this will be the object3d
			obj3d = obj.children[objIndex];
			assignChildrenName(obj3d, name);
		}
	}
};

// Materials & Texture
var floorTexture = THREE.ImageUtils.loadTexture( "images/tile.jpg" );
floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.repeat.set( 5, 5 );

var ceilTexture = THREE.ImageUtils.loadTexture( "images/ceil3.jpg" );
ceilTexture.wrapS = ceilTexture.wrapT = THREE.RepeatWrapping;
ceilTexture.repeat.set( 3, 10 );

var matWall = new THREE.MeshPhongMaterial({color: 0xffffff});
var matFloor = new THREE.MeshBasicMaterial( { map: floorTexture, side: THREE.DoubleSide } );
var matCeiling = new THREE.MeshBasicMaterial( { map: ceilTexture, side: THREE.DoubleSide } );

// Geometries
var geoFaceWall = new THREE.BoxGeometry(roomWidth, roomHeight, wallThickness);
var geoSideWall = new THREE.BoxGeometry(wallThickness, roomHeight, roomLength);
var geoFloor = new THREE.BoxGeometry(roomWidth, wallThickness, roomLength);
var geoCorner = new THREE.BoxGeometry(cornerWidth, roomHeight, cornerWidth);
var geoWallExt = new THREE.BoxGeometry(roomWidth/30, roomHeight, roomLength*0.4);

// Environment Objects 	< name : [ geometry, material, Px, Py, Pz ] >
var components = {
	wallS : 		[ geoFaceWall, matWall, 0, roomHeight/2, -roomLength/2 - wallThickness/2 ],
	wallE : 		[ geoSideWall, matWall, -roomWidth/2 - wallThickness/2, roomHeight/2, 0 ],
	wallW : 		[ geoSideWall, matWall, roomWidth/2 + wallThickness/2, roomHeight/2, 0 ],
	wallN : 		[ geoFaceWall, matWall, 0, roomHeight/2, roomLength/2 + wallThickness/2 ],
	floor : 		[ geoFloor, matFloor,	0, wallThickness/2, 0 ],
	celing : 		[ geoFloor, matCeiling,	0, roomHeight + wallThickness/2, 0 ],
	cornerBlock : 	[ geoCorner, matWall,	-roomWidth/2 + cornerWidth/2, roomHeight/2, -roomLength/2 + cornerWidth/2 ],
	wallExt : 		[ geoWallExt, matWall,	-roomWidth/2 + roomWidth/30/2, roomHeight/2, roomLength/2 - (roomLength*0.4)/2 ],
};

for (var key in components) {
	// hasOwnProperty needed to prevent insert keys into the prototype object of dictionary
	if (components.hasOwnProperty(key)) {
		var newObject = new THREE.Mesh(components[key][0], components[key][1]);
		newObject.position.set(components[key][2], components[key][3], components[key][4]);
		newObject.name = key;

		assignChildrenName(newObject, key);
		scene.add(newObject);
	}
}

// Loader to load .obj and .mtl
var loader = new THREE.OBJMTLLoader();

// Object vars
var tblScale = 0.35;
var lockerScale = 0.70;

// Load Objects 	< name : [ filename, Sx, Sy, Sz, Px, Py, Pz, Rx, Ry, Rz ] >
var lo = {
	'table1' : [ 'models/technicalTable1', tblScale, tblScale, tblScale, roomWidth/2 - 50, 36, - roomLength/2 + 25, null, null, null ],
	'table2' : [ 'models/technicalTable1', tblScale, tblScale, tblScale, -roomWidth/2 + 100, 36, - roomLength/2 + 25, null, null, null ],
	'table3' : [ 'models/technicalTable1', tblScale, tblScale, tblScale, -roomWidth/2 + 80, 36, 50, null, null, null ],
	'table4' : [ 'models/technicalTable1', tblScale, tblScale, tblScale, roomWidth/2 - 50, 36, 50, null, null, null ],
	'lockers1' : [ 'models/lockers', lockerScale, lockerScale, lockerScale, roomWidth/2 - 5, 5, -30, null, 3*Math.PI/2, null ],
	'lockers2' : [ 'models/lockers', lockerScale, lockerScale, lockerScale, roomWidth/2 - 5, 37, -30, null, 3*Math.PI/2, null ],
	'whiteBoard1' : [ 'models/whiteBoard', 0.40, 0.80, 0.60, 0, 0, roomLength/2 - 15, null, null, null ],
	'whiteBoard2' : [ 'models/whiteBoard', 0.40, 0.80, 0.60, -80, 0, roomLength/2 - 15, null, null, null ]
};

var addObjects = function(lo) {
	for (var key in lo) {
		loader.load( lo[key][0] + '.obj', lo[key][0] + '.mtl', function ( obj ) {
			console.log(this.key);

			obj.scale.set(lo[this.key][1], lo[this.key][2], lo[this.key][3]);
			obj.position.set(lo[this.key][4], lo[this.key][5], lo[this.key][6]);

			if (lo[this.key][7]) obj.rotation.x = lo[this.key][7];
			if (lo[this.key][8]) obj.rotation.y = lo[this.key][8];
			if (lo[this.key][9]) obj.rotation.z = lo[this.key][9];

			obj.name = this.key;
			assignChildrenName(obj, this.key);
			scene.add(obj);

		}.bind({key: key}));

	}
};
addObjects(lo)

function distance(v1, v2) {
	dx = v1.x - v2.x;
    // dy = v1.y - v2.y;
    dz = v1.z - v2.z;

    return Math.sqrt(dx*dx+dz*dz);
}

function checkBoundaries() {
	var plocal = new THREE.Vector3(0, 0, -1);
	var pWorld = plocal.applyMatrix4( camera.matrixWorld );
	var vec = pWorld.sub(camera.position).normalize();

	var pos = camera.position;

	var rays = [
		new THREE.Vector3(pos.x, pos.y - 30, pos.z),
		new THREE.Vector3(pos.x, pos.y, pos.z),
		new THREE.Vector3(pos.x, pos.y + 20, pos.z)
	];

	for (r = 0; r < rays.length; r++) {
		var ray = new THREE.Raycaster(rays[r], vec);
		var intersects = ray.intersectObjects( scene.children, true );

		for (z = 0; z < intersects.length; z++) {
    		if ((distance(camera.position, intersects[z].object.position) < 15) && intersects[z].object.name !== "floor") {
    			document.getElementById("info").style.display = "block";
    			document.getElementById("info").innerHTML = intersects[z].object.name;
    			return false;
    		}
    	}
	}

	document.getElementById("info").style.display = "none";
	return true;
}

/* Request animation frame loop function */
function render() {
	var delta = clock.getDelta();

	// camControls.moveForward = checkBoundaries();
	if (checkBoundaries()) {
		camControls.update(delta);
	}

	/*
	Update VR headset position and apply to camera.
	*/
	controls.update();

	/*
	Render the scene through the VREffect.
	*/
	//effect.render( scene, camera );

	// Render without stero VR effect
	renderer.render(scene, camera);

	requestAnimationFrame( render );
}

/* Kick off animation loop */
render();

/* Listen for double click event to enter full-screen VR mode */
document.body.addEventListener( 'dblclick', function() {
	effect.setFullScreen( true );
});

/* Listen for keyboard event and zero positional sensor on appropriate keypress. */
function onkey(event) {
	event.preventDefault();

	if (event.keyCode == 90) { // z
		controls.zeroSensor();

	} else if (event.keyCode == 80) { // p (pause)
		// Toggle camera look speed on/off
		(camControls.lookSpeed > 0.0) ? camControls.lookSpeed = 0.0 : camControls.lookSpeed = 0.4;
	}
};

window.addEventListener("keydown", onkey, true);

/* Handle window resizes */
function onWindowResize() {
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();

	effect.setSize( window.innerWidth, window.innerHeight );
}

window.addEventListener( 'resize', onWindowResize, false );<|endoftext|>


<commit_before>var path = require('path'),
    fs = require('fs'),
    exec = require('child_process').exec,
    argv = require('minimist')(process.argv.slice(2)),
    gulp = require('gulp'),
    gutil = require('gulp-util');

var create = function(generatorPath, options) {
  if (argv._.length < 2) {
    gutil.log("Error: See 'em new --help'.");
    process.exit(0);
  }
  // checking the url prefix
  var re = /^http(?:s)?:\/\//,
      userInputPath = options.path,
      // check for remote URL path
      remoteUrl = ( userInputPath ) ? ( re.test(userInputPath) ) ? userInputPath : ('http://' + userInputPath) : undefined;

  // get the full path to the core of application. ( Server && Client )
  var skeletonsCorePath = getSkeletonsCorePath(),
      // get the full path to the ember application or take the generator from github or an URL
      // skeletonsAppPath = ( userInputPath ) ? remoteUrl : getSkeletonsAppPath();
      skeletonsAppPath = getSkeletonsAppPath();

  if (fs.existsSync(generatorPath)) {
    gutil.log('[-log]', 'Folder (', generatorPath, ') has existed in this directory!' );
    process.exit(0);
  } else {
    // Create a new directory name what user passed in
    fs.mkdirSync(generatorPath);
  }

  var currentAppPath = path.resolve(generatorPath);
  // Setup gulp task, copy the source files into the newly create folder
  setupTask (skeletonsCorePath, skeletonsAppPath, currentAppPath);
  // Trigger the generator task
  gulp.start('generator');
};

module.exports = create;

function setupTask (coreSrcPath, appSrcPath, dest) {
  gutil.log('[-log]', 'Starting to generate application at ', dest );
  var coreSrc = [ coreSrcPath + '/**', coreSrcPath + '/**/.*' ],
      appSrc = [ appSrcPath + '/**' ];

  return gulp.task('generator', function (callback) {
      gulp.src(coreSrc)
          .on('end', function() {
              gutil.log('[-log]', 'You new application Server is ready');
          })
          .pipe(gulp.dest(dest));

      gulp.src(appSrc)
          .on('end', function() {
              gutil.log('[-log]', 'New Ember application is ready');
              installNpm( dest, callback );
          })
          .pipe(gulp.dest(dest+'/client/app'));
  });
}

function installNpm (rootPath, callback) {
    rootPath = rootPath || process.cwd();
    gutil.log('[-log]', 'NPM is installing packages...');
    process.chdir(rootPath);
    return exec('npm install', function(error, stdout, stderr) {
      var log;
      //process.chdir(rootPath);
      if (error !== null) {
        log = stderr.toString();
        gutil.log('[-log]', log);
        return callback(log);
      }
      installBower(rootPath, callback);
    });
}

function installBower (rootPath, callback) {
  rootPath = rootPath || process.cwd();
  gutil.log('[-log]', 'Bower is installing javascript packages...');
  process.chdir(rootPath);
  return exec('bower install', function(error, stdout, stderr) {
    var log;
    //process.chdir(rootPath);
    if (error !== null) {
      log = stderr.toString();
      gutil.log('[-log]', log);
      return callback(log);
    }
    gitInit(rootPath, callback);
  });
}

function gitInit(rootPath, callback) {
    gutil.log('[-log]', 'Be Patient, em-cli is doing REALLY hard to initialize your repo ...' );

    rootPath = rootPath || process.cwd();
    process.chdir(rootPath);
    var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        today = new Date(),
        todayDate = today.getDate(),
        todayMonth = month[today.getMonth()],
        todayYear = today.getFullYear(),
        init = 'git init && git add . && git commit -m "Initial Commit @ ' + todayMonth + ' ' + todayDate + ', ' + todayYear + '"';
    return exec(init, function(error, stdout, stderr) {
        var log;
        if (error !== null) {
          log = stderr.toString();
          gutil.log('[-log]', log);
          return callback(log);
        }
        gutil.log('[-log]', 'Initialized a new git repo & did first commit' );
        callback();
    });
}

function getSkeletonsCorePath () {
  var skeletonsCorePath = pathResolver('skeletons/core');
  return skeletonsCorePath;
}

function getSkeletonsAppPath () {
  var skeletonsAppPath = pathResolver('skeletons/app');
  return skeletonsAppPath;
}

function pathResolver (relativePath) {
  return path.resolve(__dirname, '..', relativePath);
}

// function rmGItRepo(cb) {
//     gutil.log('\n[-log]', gutil.colors.magenta('Removing .git/* ...') );
//     shell.rm('-rf', path.join(__dirname, '..', '..', '.git'));
//     shell.cd(_root);
//     gutil.log('\n[-log]', gutil.colors.magenta('Be Patient, Gulp is doing REALLY hard to initialize your repo ...') );

//     var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
//         today = new Date(),
//         todayDate = today.getDate(),
//         todayMonth = month[today.getMonth()],
//         todayYear = today.getFullYear(),
//         init = 'git init && git add . && git commit -m "Initial Commit @ ' + todayMonth + ' ' + todayDate + ', ' + todayYear + '"';

//     shell.exec(init, function() {
//         gutil.log('\n[-log]', gutil.colors.green('6th - Initialized a new git repo & did first commit') );
//         gutil.log('\n[-log]', gutil.colors.green('Finished! Your Mobile App Development is ready to go! Hooray!'), '\n[gulp]');
//         cb();
//     });
// }

// function keepingGitRepo(skipPrompt, cb) {
//     // Kick off the command line prompt to accept user input
//     // when first time user kick off `gulp setup --bane appName` with a flag,
//     // by default, we want to kill the repo, start from a fresh point. Remove .git folder
//     // when no flag passed, it will launch the prompt for user to choose
//     if (skipPrompt) {
//         rmGItRepo(cb);
//     } else {
//         prompt.start();

//         var schema = [{
//             description: 'Do you want to init a new repo? [Warning: it will remove your current repo!] (Y or N)',
//             type: 'string',
//             default: 'Y',
//             required: true
//         }];

//         prompt.get(schema, function(err, userInput) {
//             if (err) {
//                 gutil.log('\n[-log]', gutil.colors.red('Cannot run the final task of initializing a git repo!') );
//                 cb();
//             }

//             var result = userInput.question;

//             if (result === 'Y' || result === 'y' || result === 'yes' || result === 'Yes') {
//                 rmGItRepo(cb);
//             } else {
//                 gutil.log('\n[-log]', gutil.colors.cyan('Do not forget to manage your repo! RUN git status && git log !') );
//                 gutil.log('\n[-log]', gutil.colors.green('Finished! Your Mobile App Development is ready to go! Hooray!'), '\n[gulp]');
//                 cb();
//             }
//         });
//     }
// }

// function setupStep(appName, skipPrompt, cb) {

//     // STEP 1
//     // Override config.json  apllicationName value to sencha app variable name
//     gulp.src( _configs.configJsonSrc )
//         .pipe(replace(/"applicationName"(\s+)?:(\s+)?"(\w+)?"/, '"applicationName": "' + appName + '"'))
//         .pipe(gulp.dest( _root ));
//     gutil.log('\n[-log]', 'config.json has updated', gutil.colors.cyan('applicationName: ' + appName));

//     // STEP 2
//     // override  base.jade  sencha app variable name
//     gulp.src( _configs.baseViewSrc )
//         .pipe(replace(/.*/, 'include ../../' + appName + '/index.html'))
//         .pipe(gulp.dest( _configs.baseViewDest ));
//     gutil.log('\n[-log]', 'Setup the include path at', gutil.colors.cyan('server/views/base.jade'));

//     // STEP 3
//     // override app.js  sencha app variable
//     gulp.src( _configs.appJsSrc )
//         .pipe(replace(/senchaAppName\s=\s+\'(\w+)?\'/, 'senchaAppName = \'' + appName + '\''))
//         .pipe(gulp.dest( _configs._server ));
//     gutil.log('\n[-log]', '3rd - Setup the setup', gutil.colors.cyan('server/app.js'), 'sencha appName to', gutil.colors.cyan(appName) );

//     // STEP 4
//     // Create a sample README.md file about this repo
//     var readmeContent = '# ' + appName + '\n\n> Your application description goes here.\n\n\n## Getting started' +
// 			'\n\nWrite your getting startted guide here.\n\n\n## License\n\nMIT License • © [Matt Ma](http://mattmadesign.com)';
//     gulp.src( _configs.readmeSrc )
//         .pipe(replace(/[\s\S]*/gm, ''))
//         .pipe(replace(/[\s\S]*/, readmeContent ))
//         .pipe(gulp.dest(_root));
//     gutil.log('\n[-log]', 'Generate a sample', gutil.colors.cyan('README.md'), ', please, write your own instead!');

//     // STEP 5
//     // Override Compass config.rb in project root with the appName value
//     gulp.src(_configs.configRbSrc )
//         .pipe(replace(/curDir,(?:\s+)?'\s*(.*?)\s*'/, 'curDir, \'' + appName +'\'' ))
//         .on('end', function() {
//             gutil.log('\n[-log]', gutil.colors.cyan('config.rb'), ' is ready to use for your sass compiler task', '\n[gulp]' );
//             // STEP 6
//             // Pass cb to clean current .git repo or remain the old git
//             // Remove the project .git folder and init a new git
//             keepingGitRepo(skipPrompt, cb);
//         })
//         .pipe(gulp.dest(_root));
// }

<commit_msg>remove the comment out lines<commit_after>var path = require('path'),
    fs = require('fs'),
    exec = require('child_process').exec,
    argv = require('minimist')(process.argv.slice(2)),
    gulp = require('gulp'),
    gutil = require('gulp-util');

var create = function(generatorPath, options) {
  if (argv._.length < 2) {
    gutil.log("Error: See 'em new --help'.");
    process.exit(0);
  }
  // checking the url prefix
  var re = /^http(?:s)?:\/\//,
      userInputPath = options.path,
      // check for remote URL path
      remoteUrl = ( userInputPath ) ? ( re.test(userInputPath) ) ? userInputPath : ('http://' + userInputPath) : undefined;

  // get the full path to the core of application. ( Server && Client )
  var skeletonsCorePath = getSkeletonsCorePath(),
      // get the full path to the ember application or take the generator from github or an URL
      // skeletonsAppPath = ( userInputPath ) ? remoteUrl : getSkeletonsAppPath();
      skeletonsAppPath = getSkeletonsAppPath();

  if (fs.existsSync(generatorPath)) {
    gutil.log('[-log]', 'Folder (', generatorPath, ') has existed in this directory!' );
    process.exit(0);
  } else {
    // Create a new directory name what user passed in
    fs.mkdirSync(generatorPath);
  }

  var currentAppPath = path.resolve(generatorPath);
  // Setup gulp task, copy the source files into the newly create folder
  setupTask (skeletonsCorePath, skeletonsAppPath, currentAppPath);
  // Trigger the generator task
  gulp.start('generator');
};

module.exports = create;

function setupTask (coreSrcPath, appSrcPath, dest) {
  gutil.log('[-log]', 'Starting to generate application at ', dest );
  var coreSrc = [ coreSrcPath + '/**', coreSrcPath + '/**/.*' ],
      appSrc = [ appSrcPath + '/**' ];

  return gulp.task('generator', function (callback) {
      gulp.src(coreSrc)
          .on('end', function() {
              gutil.log('[-log]', 'You new application Server is ready');
          })
          .pipe(gulp.dest(dest));

      gulp.src(appSrc)
          .on('end', function() {
              gutil.log('[-log]', 'New Ember application is ready');
              installNpm( dest, callback );
          })
          .pipe(gulp.dest(dest+'/client/app'));
  });
}

function installNpm (rootPath, callback) {
    rootPath = rootPath || process.cwd();
    gutil.log('[-log]', 'NPM is installing packages...');
    process.chdir(rootPath);
    return exec('npm install', function(error, stdout, stderr) {
      var log;
      //process.chdir(rootPath);
      if (error !== null) {
        log = stderr.toString();
        gutil.log('[-log]', log);
        return callback(log);
      }
      installBower(rootPath, callback);
    });
}

function installBower (rootPath, callback) {
  rootPath = rootPath || process.cwd();
  gutil.log('[-log]', 'Bower is installing javascript packages...');
  process.chdir(rootPath);
  return exec('bower install', function(error, stdout, stderr) {
    var log;
    //process.chdir(rootPath);
    if (error !== null) {
      log = stderr.toString();
      gutil.log('[-log]', log);
      return callback(log);
    }
    gitInit(rootPath, callback);
  });
}

function gitInit(rootPath, callback) {
    gutil.log('[-log]', 'Be Patient, em-cli is doing REALLY hard to initialize your repo ...' );

    rootPath = rootPath || process.cwd();
    process.chdir(rootPath);
    var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        today = new Date(),
        todayDate = today.getDate(),
        todayMonth = month[today.getMonth()],
        todayYear = today.getFullYear(),
        init = 'git init && git add . && git commit -m "Initial Commit @ ' + todayMonth + ' ' + todayDate + ', ' + todayYear + '"';
    return exec(init, function(error, stdout, stderr) {
        var log;
        if (error !== null) {
          log = stderr.toString();
          gutil.log('[-log]', log);
          return callback(log);
        }
        gutil.log('[-log]', 'Initialized a new git repo & did first commit' );
        callback();
    });
}

function getSkeletonsCorePath () {
  var skeletonsCorePath = pathResolver('skeletons/core');
  return skeletonsCorePath;
}

function getSkeletonsAppPath () {
  var skeletonsAppPath = pathResolver('skeletons/app');
  return skeletonsAppPath;
}

function pathResolver (relativePath) {
  return path.resolve(__dirname, '..', relativePath);
}
<|endoftext|>


<commit_before>var ModeHandler = function(mode, DrawContext) {

  var handlers = {
    drag: [],
    click: [],
    mousemove: [],
    mousedown: [],
    mouseup: [],
    keydown: [],
    keyup: [],
    trash: []
  };

  var ctx = {
    on: function(event, selector, fn) {
      if (handlers[event] === undefined) {
        throw new Error(`Invalid event type: ${event}`);
      }
      handlers[event].push({
        selector: selector,
        fn: fn
      });
    },
    off: function(event, selector, fn) {
      handlers[event] = handlers[event].filter(handler => {
        return handler.selector !== selector || handler.fn !== fn;
      });
    },
    fire: function(event, payload) {
      var modename = DrawContext.events.currentModeName();
      DrawContext.map.fire(`draw.${modename}.${event}`, payload);
    },
    render: function(id) {
      DrawContext.store.featureChanged(id);
    }
  };

  var delegate = function (eventName, event) {
    var handles = handlers[eventName];
    var iHandle = handles.length;
    while (iHandle--) {
      var handle = handles[iHandle];
      if (handle.selector(event)) {
        handle.fn.call(ctx, event);
        DrawContext.store.render();
        break;
      }
    }
    DrawContext.ui.fireClassUpdate();
  };

  mode.start.call(ctx);

  return {
    render: mode.render || function(geojson) {return geojson; },
    stop: function() {
      DrawContext.store.clearSelected();
      if (mode.stop) mode.stop();
    },
    drag: function(event) {
      delegate('drag', event);
    },
    click: function(event) {
      delegate('click', event);
    },
    mousemove: function(event) {
      delegate('mousemove', event);
    },
    mousedown: function(event) {
      delegate('mousedown', event);
    },
    mouseup: function(event) {
      delegate('mouseup', event);
    },
    keydown: function(event) {
      delegate('keydown', event);
    },
    keyup: function(event) {
      delegate('keyup', event);
    },
    trash: function(event) {
      delegate('trash', event);
    }
  };
};

module.exports = ModeHandler;
<commit_msg>handle deselect after we stop mode<commit_after>var ModeHandler = function(mode, DrawContext) {

  var handlers = {
    drag: [],
    click: [],
    mousemove: [],
    mousedown: [],
    mouseup: [],
    keydown: [],
    keyup: [],
    trash: []
  };

  var ctx = {
    on: function(event, selector, fn) {
      if (handlers[event] === undefined) {
        throw new Error(`Invalid event type: ${event}`);
      }
      handlers[event].push({
        selector: selector,
        fn: fn
      });
    },
    off: function(event, selector, fn) {
      handlers[event] = handlers[event].filter(handler => {
        return handler.selector !== selector || handler.fn !== fn;
      });
    },
    fire: function(event, payload) {
      var modename = DrawContext.events.currentModeName();
      DrawContext.map.fire(`draw.${modename}.${event}`, payload);
    },
    render: function(id) {
      DrawContext.store.featureChanged(id);
    }
  };

  var delegate = function (eventName, event) {
    var handles = handlers[eventName];
    var iHandle = handles.length;
    while (iHandle--) {
      var handle = handles[iHandle];
      if (handle.selector(event)) {
        handle.fn.call(ctx, event);
        DrawContext.store.render();
        break;
      }
    }
    DrawContext.ui.fireClassUpdate();
  };

  mode.start.call(ctx);

  return {
    render: mode.render || function(geojson) {return geojson; },
    stop: function() {
      if (mode.stop) mode.stop();
      DrawContext.store.clearSelected();
    },
    drag: function(event) {
      delegate('drag', event);
    },
    click: function(event) {
      delegate('click', event);
    },
    mousemove: function(event) {
      delegate('mousemove', event);
    },
    mousedown: function(event) {
      delegate('mousedown', event);
    },
    mouseup: function(event) {
      delegate('mouseup', event);
    },
    keydown: function(event) {
      delegate('keydown', event);
    },
    keyup: function(event) {
      delegate('keyup', event);
    },
    trash: function(event) {
      delegate('trash', event);
    }
  };
};

module.exports = ModeHandler;
<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
    fs = require('fs'),
    exec = require('child_process').exec,
    argv = require('minimist')(process.argv.slice(2)),
    tildify = require('tildify'),
    gulp = require('gulp'),
    gutil = require('gulp-util');

// installer plugins to handle the npm and bower packages installation
function installer ( rootPath, command, description, nextStepFn, callback ) {
  rootPath = rootPath || process.cwd();
  gutil.log(gutil.colors.gray('[-log:]'), description);
  process.chdir(rootPath);
  return exec(command, function(error, stdout, stderr) {
    //process.chdir(rootPath);
    if (error !== null) {
      var log = stderr.toString();
      gutil.log( gutil.colors.red('[-Error:] ' + log) );
      if (command === 'npm install') {
        gutil.log( gutil.colors.red('[-Error:] npm install failed dramatically.') );
        gutil.log(
          gutil.colors.red('[-Error:] Need to manually do \'npm install\' and \'bower install\' ')
        );
        gutil.log(
          gutil.colors.red('[-Error:] Before the project is fully ready for development')
        );
      } else if (command === 'bower install') {
        gutil.log( gutil.colors.red('[-Error:] bower install failed dramatically.') );
        gutil.log( gutil.colors.red('[-Error:] Need to manually do \'bower install\'') );
        gutil.log(
          gutil.colors.red('[-Error:] Before the project is fully ready for development')
        );
      } else {
        gutil.log(
          gutil.colors.red('[-Error:] initialize git repository failed dramatically.')
        );
        gutil.log( gutil.colors.red('[-Error:] Need to manually do') );
        gutil.log( gutil.colors.red('[-Error:] \'git init && git add . && git commit -m\'') );
      }
      return callback(log);
    }
    nextStepFn(rootPath, callback);
  });
}

function gitInit(rootPath, callback) {
  gutil.log(
    gutil.colors.gray('[-log:]'),
    gutil.colors.cyan('em-cli'),
    'is doing REALLY hard to initialize your repo ...'
  );

  rootPath = rootPath || process.cwd();
  process.chdir(rootPath);
  var month = [
    'Jan', 'Feb', 'Mar',
    'Apr', 'May', 'Jun',
    'Jul', 'Aug', 'Sep',
    'Oct', 'Nov', 'Dec'
  ],
    today = new Date(),
    todayDate = today.getDate(),
    todayMonth = month[today.getMonth()],
    todayYear = today.getFullYear(),
    command = 'git init && git add . && git commit -m \'Initial Commit @ ' +
              todayMonth + ' ' + todayDate + ', ' + todayYear + '\'';

  return exec(command, function(error, stdout, stderr) {
      if (error !== null) {
        var log = stderr.toString();
        gutil.log( gutil.colors.red('[-Error:] ' + log) );
        return callback(log);
      }
      gutil.log(
         gutil.colors.green('[-done:] Initialized a new git repo and did a first commit')
      );
      gutil.log(
        gutil.colors.bold('[-copy:] =>'),
        gutil.colors.cyan('cd ' + argv._[1]),
        gutil.colors.gray('# navigate to the newly created application')
      );
      callback();
    });
}

function installBower (rootPath, callback) {
  installer (
    rootPath,
    'bower install',
    'Bower is installing javascript packages...',
    gitInit,
    callback
  );
}

function installNpm (rootPath, callback) {
  installer (
    rootPath,
    'npm install',
    'NPM is installing node packages...',
    installBower,
    callback
  );
}

function setupTask (coreSrcPath, appSrcPath, dest, isRunningTest) {
  gutil.log(
    gutil.colors.gray('[-log:]'),
    'Starting to generate an application at',
    gutil.colors.cyan( tildify(dest) )
  );

  var coreSrc = [ coreSrcPath + '/**', coreSrcPath + '/**/.*' ],
      appSrc = [ appSrcPath + '/**' ];

  return gulp.task('generator', function (callback) {
      gulp.src(coreSrc)
        .on('end', function() {
          gutil.log(
            gutil.colors.green('[-done:] A new'),
            gutil.colors.cyan('Node.js'),
            gutil.colors.green('web server have been successfully created!') );
        })
        .pipe(gulp.dest(dest));

      gulp.src(appSrc)
        .on('end', function() {
          gutil.log(
            gutil.colors.green('[-done:] A new'),
            gutil.colors.cyan('Ember.js'),
            gutil.colors.green('mvc application have been successfully created!')
          );
          if( !isRunningTest ) {
            installNpm( dest, callback );
          } else {
            callback();
          }
        })
        .pipe(gulp.dest(dest+'/client/app'));
    });
}

function pathResolver (relativePath) {
  return path.resolve(__dirname, '..', relativePath);
}

function getSkeletonsCorePath () {
  var skeletonsCorePath = pathResolver('skeletons/core');
  return skeletonsCorePath;
}

function getSkeletonsAppPath () {
  var skeletonsAppPath = pathResolver('skeletons/app');
  return skeletonsAppPath;
}

var create = function(generatorPath, options) {
  if (argv._.length < 2) {
    gutil.log(gutil.colors.red('[-Error:] Missing directory name.'), 'ex: em new my-app');
    gutil.log(gutil.colors.red('[-Error:]'), 'See \'em new --help\'');
    process.exit(0);
  }

  // check for the mode, is running test or not
  var isRunningTest = options.test || false;

  // @TODO: implment so that user could pass in a git url for installing app
//  checking the url prefix
//   var re = /^http(?:s)?:\/\//,
//       userInputPath = options.path;

  //  check for remote URL path
//       remoteUrl = ( userInputPath ) ?
//                       ( re.test(userInputPath) ) ?
//                         userInputPath : ('http://' + userInputPath) : undefined;

  // get the full path to the core of application. ( Server && Client )
  var skeletonsCorePath = getSkeletonsCorePath(),
      // get the full path to the ember application or take the generator from github or an URL
      // skeletonsAppPath = ( userInputPath ) ? remoteUrl : getSkeletonsAppPath();
      skeletonsAppPath = getSkeletonsAppPath();

  if (fs.existsSync(generatorPath)) {
    gutil.log(
      gutil.colors.red('[-Error:]'), 'The folder name',
      gutil.colors.red(generatorPath), 'has existed in this directory tree!'
    );
    process.exit(0);
  } else {
    // Create a new directory name what user passed in
    fs.mkdirSync(generatorPath);
  }

  var currentAppPath = path.resolve(generatorPath);
  // Setup gulp task, copy the source files into the newly create folder
  setupTask (skeletonsCorePath, skeletonsAppPath, currentAppPath, isRunningTest);
  // Trigger the generator task
  gulp.start('generator');
};

module.exports = create;
<commit_msg>update the informational info when user install the packages<commit_after>'use strict';

var path = require('path'),
    fs = require('fs'),
    exec = require('child_process').exec,
    argv = require('minimist')(process.argv.slice(2)),
    tildify = require('tildify'),
    gulp = require('gulp'),
    gutil = require('gulp-util');

// installer plugins to handle the npm and bower packages installation
function installer ( rootPath, command, description, nextStepFn, callback ) {
  rootPath = rootPath || process.cwd();
  gutil.log(gutil.colors.gray('[-log:]'), description);
  process.chdir(rootPath);
  return exec(command, function(error, stdout, stderr) {
    //process.chdir(rootPath);
    if (error !== null) {
      var log = stderr.toString();
      gutil.log( gutil.colors.red('[-Error:] ' + log) );
      if (command === 'npm install') {
        gutil.log( gutil.colors.red('[-Error:] npm install failed dramatically.') );
        gutil.log(
          gutil.colors.red('[-Error:] Need to manually do \'npm install\' and \'bower install\' ')
        );
        gutil.log(
          gutil.colors.red('[-Error:] Before the project is fully ready for development')
        );
      } else if (command === 'bower install') {
        gutil.log( gutil.colors.red('[-Error:] bower install failed dramatically.') );
        gutil.log( gutil.colors.red('[-Error:] Need to manually do \'bower install\'') );
        gutil.log(
          gutil.colors.red('[-Error:] Before the project is fully ready for development')
        );
      } else {
        gutil.log(
          gutil.colors.red('[-Error:] initialize git repository failed dramatically.')
        );
        gutil.log( gutil.colors.red('[-Error:] Need to manually do') );
        gutil.log( gutil.colors.red('[-Error:] \'git init && git add . && git commit -m\'') );
      }
      return callback(log);
    }
    nextStepFn(rootPath, callback);
  });
}

function gitInit(rootPath, callback) {
  gutil.log(
    gutil.colors.gray('[-log:]'),
    gutil.colors.cyan('em-cli'),
    'is doing REALLY hard to initialize your repo ...'
  );

  rootPath = rootPath || process.cwd();
  process.chdir(rootPath);
  var month = [
    'Jan', 'Feb', 'Mar',
    'Apr', 'May', 'Jun',
    'Jul', 'Aug', 'Sep',
    'Oct', 'Nov', 'Dec'
  ],
    today = new Date(),
    todayDate = today.getDate(),
    todayMonth = month[today.getMonth()],
    todayYear = today.getFullYear(),
    command = 'git init && git add . && git commit -m \'Initial Commit @ ' +
              todayMonth + ' ' + todayDate + ', ' + todayYear + '\'';

  return exec(command, function(error, stdout, stderr) {
      if (error !== null) {
        var log = stderr.toString();
        gutil.log( gutil.colors.red('[-Error:] ' + log) );
        return callback(log);
      }
      gutil.log(
         gutil.colors.green('[-done:] Initialized a new git repo and did a first commit')
      );
      gutil.log(
        gutil.colors.bold('[-copy:] =>'),
        gutil.colors.cyan('cd ' + argv._[1]),
        gutil.colors.gray('# navigate to the newly created application')
      );
      gutil.log(
        gutil.colors.bold('[-copy:] =>'),
        gutil.colors.cyan('em serve'),
        gutil.colors.gray(' # kick start the server, open project in favorite browser,'),
        gutil.colors.gray('auto watch file changes and rebuild the project')
      );
      callback();
    });
}

function installBower (rootPath, callback) {
  installer (
    rootPath,
    'bower install',
    'Bower is installing javascript packages...',
    gitInit,
    callback
  );
}

function installNpm (rootPath, callback) {
  installer (
    rootPath,
    'npm install',
    'NPM is installing node packages...',
    installBower,
    callback
  );
}

function setupTask (coreSrcPath, appSrcPath, dest, isRunningTest) {
  gutil.log(
    gutil.colors.gray('[-log:]'),
    'Starting to generate an application at',
    gutil.colors.cyan( tildify(dest) )
  );

  var coreSrc = [ coreSrcPath + '/**', coreSrcPath + '/**/.*' ],
      appSrc = [ appSrcPath + '/**' ];

  return gulp.task('generator', function (callback) {
      gulp.src(coreSrc)
        .on('end', function() {
          gutil.log(
            gutil.colors.green('[-done:] A new'),
            gutil.colors.cyan('Node.js'),
            gutil.colors.green('web server have been successfully created!')
          );
          gutil.log(
            gutil.colors.magenta('Be patient, fetching packages from internet ...')
          );
        })
        .pipe(gulp.dest(dest));

      gulp.src(appSrc)
        .on('end', function() {
          gutil.log(
            gutil.colors.green('[-done:] A new'),
            gutil.colors.cyan('Ember.js'),
            gutil.colors.green('mvc application have been successfully created!')
          );
          if( !isRunningTest ) {
            installNpm( dest, callback );
          } else {
            callback();
          }
        })
        .pipe(gulp.dest(dest+'/client/app'));
    });
}

function pathResolver (relativePath) {
  return path.resolve(__dirname, '..', relativePath);
}

function getSkeletonsCorePath () {
  var skeletonsCorePath = pathResolver('skeletons/core');
  return skeletonsCorePath;
}

function getSkeletonsAppPath () {
  var skeletonsAppPath = pathResolver('skeletons/app');
  return skeletonsAppPath;
}

var create = function(generatorPath, options) {
  if (argv._.length < 2) {
    gutil.log(gutil.colors.red('[-Error:] Missing directory name.'), 'ex: em new my-app');
    gutil.log(gutil.colors.red('[-Error:]'), 'See \'em new --help\'');
    process.exit(0);
  }

  // check for the mode, is running test or not
  var isRunningTest = options.test || false;

  // @TODO: implment so that user could pass in a git url for installing app
//  checking the url prefix
//   var re = /^http(?:s)?:\/\//,
//       userInputPath = options.path;

  //  check for remote URL path
//       remoteUrl = ( userInputPath ) ?
//                       ( re.test(userInputPath) ) ?
//                         userInputPath : ('http://' + userInputPath) : undefined;

  // get the full path to the core of application. ( Server && Client )
  var skeletonsCorePath = getSkeletonsCorePath(),
      // get the full path to the ember application or take the generator from github or an URL
      // skeletonsAppPath = ( userInputPath ) ? remoteUrl : getSkeletonsAppPath();
      skeletonsAppPath = getSkeletonsAppPath();

  if (fs.existsSync(generatorPath)) {
    gutil.log(
      gutil.colors.red('[-Error:]'), 'The folder name',
      gutil.colors.red(generatorPath), 'has existed in this directory tree!'
    );
    process.exit(0);
  } else {
    // Create a new directory name what user passed in
    fs.mkdirSync(generatorPath);
  }

  var currentAppPath = path.resolve(generatorPath);
  // Setup gulp task, copy the source files into the newly create folder
  setupTask (skeletonsCorePath, skeletonsAppPath, currentAppPath, isRunningTest);
  // Trigger the generator task
  gulp.start('generator');
};

module.exports = create;
<|endoftext|>