<commit_before>//
// (C) Copyright 2016 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
// Written by M.Harada.
//

var request = require("request");

// Production keys
// Dont's keep the client id and secret at client side.
// Keep it at server side for 2-legged.

// To Do: set your key and secret.
var _baseUrl = "https://developer.api.autodesk.com/";
var _apiKey = "<your api key comes here>";
var _apiSecret = "<your api secret comes here>";

// Forge OAuth 2-legged for HQ
//
// For HQ, you need to use 2-legged Authentication
// authentication/v1/authenticate
// https://developer.autodesk.com/en/docs/oauth/v2/reference/http/authenticate-POST/
//

exports.authenticate= function (req, res) {
    var options = {
        method: 'POST',
        url: _baseUrl + 'authentication/v1/authenticate',
        headers: {
            'cache-control': 'no-cache',
            'content-type': 'application/x-www-form-urlencoded'
        },
        form: {
            client_id: _apiKey,
            client_secret: _apiSecret,
            grant_type: "client_credentials",
            scope: "data:read account:read account:write bucket:read"
        }
    };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);
        // console.log(body);

        var ticket = "";
        var jsonObj = JSON.parse(body);
        if (jsonObj) {
            token = jsonObj.access_token;
        }
        // Save ticket as a session data.
        req.session.token = token;

        // Send back the result
        res.send(body);
    });
}

// Company
//
// Get a list of companies
// hq/v1/accounts/:account_id/companies
// https://developer.autodesk.com/en/docs/bim360/v1/reference/http/companies-GET/
//

exports.company = function (req, res) {
    var body = req.body;
    var method = 'GET'; // body.method;
    var account_id = body.account_id;
    var url = _baseUrl + 'hq/v1/accounts/' + account_id + '/companies';

    var tokenHeader;
    if (req.session.token) {
        tokenHeader = 'Bearer ' + req.session.token;
    }

    var options = {
        method: method,
        url: url,
        headers: {
            'cache-control': 'no-cache',
            Authorization: tokenHeader
        },
    };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);
        console.log(body);
        res.send(body);
    });

}

// Company Data Update
//
// Update a part of company data, such as erp_id.
// hq/v1/accounts/:account_id/companies/:company_id
// https://developer.autodesk.com/en/docs/bim360/v1/reference/http/companies-:company_id-PATCH/
//

exports.companyUpdate = function (req, res) {
    var body = req.body;
    var method = 'PATCH'; // body.method;
    var account_id = body.account_id;
    var company_id = body.company_id;
    var url = _baseUrl + 'hq/v1/accounts/' + account_id + '/companies/' + company_id;
    var data = body.newData;

    var tokenHeader;
    if (req.session.token) {
        tokenHeader = 'Bearer ' + req.session.token;
    }

    var options = {
        method: method,
        url: url,
        headers: {
            'cache-control': 'no-cache',
            Authorization: tokenHeader,
            'Content-Type': 'application/json'
        },
        body: data
    };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);
        console.log(body);
        res.send(body);
    });

}
<commit_msg>minor clean ups<commit_after>//
// (C) Copyright 2016 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
// Written by M.Harada.
//

var request = require("request");

// Production keys
// Dont's keep the client id and secret at client side.
// Keep it at server side for 2-legged.

// To Do: set your key and secret.
var _baseUrl = "https://developer.api.autodesk.com/";
var _apiKey = "<your api key comes here>";
var _apiSecret = "<your api secret comes here>";

// Forge OAuth 2-legged for HQ
//
// For HQ, you need to use 2-legged Authentication
// authentication/v1/authenticate
// https://developer.autodesk.com/en/docs/oauth/v2/reference/http/authenticate-POST/
//

exports.authenticate= function (req, res) {
    var options = {
        method: 'POST',
        url: _baseUrl + 'authentication/v1/authenticate',
        headers: {
            'cache-control': 'no-cache',
            'content-type': 'application/x-www-form-urlencoded'
        },
        form: {
            client_id: _apiKey,
            client_secret: _apiSecret,
            grant_type: "client_credentials",
            scope: "data:read account:read account:write bucket:read"
        }
    };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);

        var ticket = "";
        var jsonObj = JSON.parse(body);
        if (jsonObj) {
            token = jsonObj.access_token;
        }
        // Save ticket as a session data.
        req.session.token = token;

        // Send back the result
        res.send(body);
    });
}

// Company
//
// Get a list of companies
// hq/v1/accounts/:account_id/companies
// https://developer.autodesk.com/en/docs/bim360/v1/reference/http/companies-GET/
//

exports.company = function (req, res) {
    var body = req.body;
    var method = 'GET';
    var account_id = body.account_id;
    var url = _baseUrl + 'hq/v1/accounts/' + account_id + '/companies';

    var tokenHeader;
    if (req.session.token) {
        tokenHeader = 'Bearer ' + req.session.token;
    }

    var options = {
        method: method,
        url: url,
        headers: {
            'cache-control': 'no-cache',
            Authorization: tokenHeader
        },
    };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);
        console.log(body);
        res.send(body);
    });

}

// Company Data Update
//
// Update a part of company data, such as erp_id.
// hq/v1/accounts/:account_id/companies/:company_id
// https://developer.autodesk.com/en/docs/bim360/v1/reference/http/companies-:company_id-PATCH/
//

exports.companyUpdate = function (req, res) {
    var body = req.body;
    var method = 'PATCH';
    var account_id = body.account_id;
    var company_id = body.company_id;
    var url = _baseUrl + 'hq/v1/accounts/' + account_id + '/companies/' + company_id;
    var data = body.newData;

    var tokenHeader;
    if (req.session.token) {
        tokenHeader = 'Bearer ' + req.session.token;
    }

    var options = {
        method: method,
        url: url,
        headers: {
            'cache-control': 'no-cache',
            Authorization: tokenHeader,
            'Content-Type': 'application/json'
        },
        body: data
    };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);
        console.log(body);
        res.send(body);
    });

}
<|endoftext|>


<commit_before>/**
 * Main application logic for Lumiere Meteor app.
 */

// Place hold some variables
var chroma;

// Persistant data stores
var Colors = new Meteor.Collection('colors');

// Allow a settings file to override defaults
Meteor.settings = _.extend({
  'name': 'Lumière',
  'phone': '+1 651 400 1501',
  'lights': 160
}, Meteor.settings);

// Shared objects across client and server.
// Meteor.lumiere.colors comes in from colors.js
Meteor.lumiere = Meteor.lumiere || {};

// Shared methods that should not be called async
Meteor.lumiere.fillColor = function(color) {
  var colors = [];
  var i;

  if (!_.isUndefined(color) && _.isObject(color)) {
    // Repeat colors
    for (i = 0; i < Meteor.settings.lights; i++) {
      colors.push(color.colors[i % color.colors.length]);
    }

    color.colors = colors;
  }
  return color;
};

// Client side only.  Multiple templates are used
// as Meteor ends up rerendering everything when
// one value is updated and can be very slow.
if (Meteor.isClient) {
  // Status allows for a simple icon to show if the client
  // is connected to the server
  Template.header.status = function() {
    return Meteor.status().status;
  };
  Template.header.name = Meteor.settings.name;

  // The current selection of lights
  Template.lights.current = function() {
    var recent = Colors.find({}, { sort: { timestamp: -1 }, limit: 1 }).fetch()[0];

    if (!_.isUndefined(recent)) {
      recent.input = recent.input.split(',').join(', ');
    }
    return Meteor.lumiere.fillColor(recent);
  };

  // About sections
  Template.about.phone = Meteor.settings.phone;
  Template.about.name = Meteor.settings.name;
  Template.nodes.name = Meteor.settings.name;

  // All those colors!
  Template.input.colorList = function() {
    return Meteor.lumiere.colors;
  };

  // Events handled in the input template.
  Template.input.events({
    // Submit new colors
    'submit .color-input-form': function(e) {
      e.preventDefault();
      var $form = $(e.currentTarget);

      Meteor.call('addColor', $form.find('#color-input-text').val(), function(error, response) {
        if (error) {
          throw new error;
        }
        else {
          $form.find('#color-input-text').val('');
        }
      });
    },
    // Add colors to input
    'click li.color-choice': function(e) {
      e.preventDefault();
      var $color = $(e.currentTarget);
      var $input = $('#color-input-text');
      var current = $input.val().split(',');
      var name = $color.data('name');
      current.push(name);

      current = _.filter(current, function(c) {
        return (!!c);
      });
      $input.val(current.join(','));
    }
  });
}

// Server side only.  Saving and processing colors.  Mostly we are just adding
// some methods that can be shared with the client
if (Meteor.isServer) {
  // "npm" packages
  chroma = Meteor.npmRequire('chroma-js');

  // On startup, create methods
  Meteor.startup(function() {
    Meteor.methods({
      // Turn a string into a color
      findColor: function(input) {
        var names = _.pluck(Meteor.lumiere.colors, 'colorName');
        var color = chroma('red');
        var colors = [];
        var found;
        var r;

        // First see if Chroma can handle the input, if that fails
        // do a look up of custom colors, otherwise, just choose
        // one at random
        try {
          color = chroma(input);
          color = color.hex();
        }
        catch (e) {
          found = names.indexOf(input);

          if (found !== -1) {
            color = Meteor.lumiere.colors[found].colors;
          }
          else {
            r = (Math.floor(Math.random() * (_.size(Meteor.lumiere.colors))));
            color = _.values(Meteor.lumiere.colors)[r].colors;
          }
        }

        // Turn values into hex
        if (_.isString(color)) {
          color = chroma(color).hex();
        }
        else if (_.isArray(color)) {
          color.forEach(function(c) {
            colors.push(chroma(c).hex());
          });
          color = colors;
        }

        return color;
      },

      // Turn input into a set of colors
      makeColors: function(input) {
        var colors = [];
        var inputs = [];
        var found;

        _.each(input.trim().split(','), function(c) {
          c = c.trim().replace(/\W/g, '').toLowerCase();
          if (c.length > 0) {
            found = Meteor.call('findColor', c);
            if (_.isString(found)) {
              colors.push(found);
            }
            else if (_.isArray(found)) {
              found.forEach(function(f) {
                colors.push(f);
              });
            }

            inputs.push(c);
          }
        });

        return {
          input: inputs.join(','),
          colors: colors
        };
      },

      // Save colors to data-store
      saveColors: function(input, colors) {
        Colors.insert({
          timestamp: (new Date()).getTime(),
          input: input,
          colors: colors
        });
      },

      // Wrapper for make and save
      addColor: function(input) {
        var colors = Meteor.call('makeColors', input);

        if (colors.colors.length > 0) {
          Meteor.call('saveColors', colors.input, colors.colors);
        }
      }
    });
  });
}

// "API" routing

// Routing for text input.  Can test locally with something like:
// curl --data "Body=blue" -X POST http://localhost:3000/api/colors/twilio
Router.route('incoming-twilio', {
  path: '/api/colors/twilio',
  where: 'server',
  action: function() {
    // Example input from Twilio
    /*
    { AccountSid: 'XXXXXX',
    MessageSid: 'XXXXXX',
    Body: 'green',
    ToZip: '55045',
    ToCity: 'LINDSTROM',
    FromState: 'GA',
    ToState: 'MN',
    SmsSid: 'XXXXXXX',
    To: '+16514001501',
    ToCountry: 'US',
    FromCountry: 'US',
    SmsMessageSid: 'XXXXX',
    ApiVersion: '2010-04-01',
    FromCity: 'ATLANTA',
    SmsStatus: 'received',
    NumMedia: '0',
    From: '+177059XXXXX',
    FromZip: '30354' }
    */

    // Responses
    var responses = [
      'Thanks for your input; your color(s) should show up in a few seconds.',
      'Yay! More colors! Might take a moment to update those colors for you.',
      'Our robots are working hard to get those colors just right for you.',
      'Wait for it... Bam! Colors!'
    ];

    // Should return a TwiML document.
    // https://www.twilio.com/docs/api/twiml
    if (this.request.body && this.request.body.Body) {
      Meteor.call('addColor', this.request.body.Body);
    }

    // Return some TwiML
    this.response.writeHead(200, {
      'Content-Type': 'text/xml'
    });
    this.response.end('<?xml version="1.0" encoding="UTF-8" ?> <Response> <Sms> ' + _.sample(responses) + ' -' + Meteor.settings.name + '</Sms> </Response>\n');
  }
});

// Routing for color api output
Router.route('outgoing-colors', {
  path: '/api/colors',
  where: 'server',
  action: function() {
    var color = Colors.find({}, { sort: { timestamp: -1 }}).fetch()[0];

    this.response.writeHead(200, {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Document-ID': color._id
    });
    this.response.end(JSON.stringify(color) + '\n');
  }
});
<commit_msg>Adding different color formats for api.<commit_after>/**
 * Main application logic for Lumiere Meteor app.
 */

// Place hold some variables
var chroma;

// Persistant data stores
var Colors = new Meteor.Collection('colors');

// Allow a settings file to override defaults
Meteor.settings = _.extend({
  'name': 'Lumière',
  'phone': '+1 651 400 1501',
  'lights': 160
}, Meteor.settings);

// Shared objects across client and server.
// Meteor.lumiere.colors comes in from colors.js
Meteor.lumiere = Meteor.lumiere || {};

// Shared methods that should not be called async
Meteor.lumiere.fillColor = function(color) {
  var colors = [];
  var i;

  if (!_.isUndefined(color) && _.isObject(color)) {
    // Repeat colors
    for (i = 0; i < Meteor.settings.lights; i++) {
      colors.push(color.colors[i % color.colors.length]);
    }

    color.colors = colors;
  }
  return color;
};

// Client side only.  Multiple templates are used
// as Meteor ends up rerendering everything when
// one value is updated and can be very slow.
if (Meteor.isClient) {
  // Status allows for a simple icon to show if the client
  // is connected to the server
  Template.header.status = function() {
    return Meteor.status().status;
  };
  Template.header.name = Meteor.settings.name;

  // The current selection of lights
  Template.lights.current = function() {
    var recent = Colors.find({}, { sort: { timestamp: -1 }, limit: 1 }).fetch()[0];

    if (!_.isUndefined(recent)) {
      recent.input = recent.input.split(',').join(', ');
    }
    return Meteor.lumiere.fillColor(recent);
  };

  // About sections
  Template.about.phone = Meteor.settings.phone;
  Template.about.name = Meteor.settings.name;
  Template.nodes.name = Meteor.settings.name;

  // All those colors!
  Template.input.colorList = function() {
    return Meteor.lumiere.colors;
  };

  // Events handled in the input template.
  Template.input.events({
    // Submit new colors
    'submit .color-input-form': function(e) {
      e.preventDefault();
      var $form = $(e.currentTarget);

      Meteor.call('addColor', $form.find('#color-input-text').val(), function(error, response) {
        if (error) {
          throw new error;
        }
        else {
          $form.find('#color-input-text').val('');
        }
      });
    },
    // Add colors to input
    'click li.color-choice': function(e) {
      e.preventDefault();
      var $color = $(e.currentTarget);
      var $input = $('#color-input-text');
      var current = $input.val().split(',');
      var name = $color.data('name');
      current.push(name);

      current = _.filter(current, function(c) {
        return (!!c);
      });
      $input.val(current.join(','));
    }
  });
}

// Server side only.  Saving and processing colors.  Mostly we are just adding
// some methods that can be shared with the client
if (Meteor.isServer) {
  // "npm" packages
  chroma = Meteor.npmRequire('chroma-js');

  // On startup, create methods
  Meteor.startup(function() {
    Meteor.methods({
      // Turn a string into a color
      findColor: function(input) {
        var names = _.pluck(Meteor.lumiere.colors, 'colorName');
        var color = chroma('red');
        var colors = [];
        var found;
        var r;

        // First see if Chroma can handle the input, if that fails
        // do a look up of custom colors, otherwise, just choose
        // one at random
        try {
          color = chroma(input);
          color = color.hex();
        }
        catch (e) {
          found = names.indexOf(input);

          if (found !== -1) {
            color = Meteor.lumiere.colors[found].colors;
          }
          else {
            r = (Math.floor(Math.random() * (_.size(Meteor.lumiere.colors))));
            color = _.values(Meteor.lumiere.colors)[r].colors;
          }
        }

        // Turn values into hex
        if (_.isString(color)) {
          color = chroma(color).hex();
        }
        else if (_.isArray(color)) {
          color.forEach(function(c) {
            colors.push(chroma(c).hex());
          });
          color = colors;
        }

        return color;
      },

      // Turn input into a set of colors
      makeColors: function(input) {
        var colors = [];
        var inputs = [];
        var found;

        _.each(input.trim().split(','), function(c) {
          c = c.trim().replace(/\W/g, '').toLowerCase();
          if (c.length > 0) {
            found = Meteor.call('findColor', c);
            if (_.isString(found)) {
              colors.push(found);
            }
            else if (_.isArray(found)) {
              found.forEach(function(f) {
                colors.push(f);
              });
            }

            inputs.push(c);
          }
        });

        return {
          input: inputs.join(','),
          colors: colors
        };
      },

      // Save colors to data-store
      saveColors: function(input, colors) {
        Colors.insert({
          timestamp: (new Date()).getTime(),
          input: input,
          colors: colors
        });
      },

      // Wrapper for make and save
      addColor: function(input) {
        var colors = Meteor.call('makeColors', input);

        if (colors.colors.length > 0) {
          Meteor.call('saveColors', colors.input, colors.colors);
        }
      }
    });
  });
}

// "API" routing

// Routing for text input.  Can test locally with something like:
// curl --data "Body=blue" -X POST http://localhost:3000/api/colors/twilio
Router.route('incoming-twilio', {
  path: '/api/colors/twilio',
  where: 'server',
  action: function() {
    // Example input from Twilio
    /*
    { AccountSid: 'XXXXXX',
    MessageSid: 'XXXXXX',
    Body: 'green',
    ToZip: '55045',
    ToCity: 'LINDSTROM',
    FromState: 'GA',
    ToState: 'MN',
    SmsSid: 'XXXXXXX',
    To: '+16514001501',
    ToCountry: 'US',
    FromCountry: 'US',
    SmsMessageSid: 'XXXXX',
    ApiVersion: '2010-04-01',
    FromCity: 'ATLANTA',
    SmsStatus: 'received',
    NumMedia: '0',
    From: '+177059XXXXX',
    FromZip: '30354' }
    */

    // Responses
    var responses = [
      'Thanks for your input; your color(s) should show up in a few seconds.',
      'Yay! More colors! Might take a moment to update those colors for you.',
      'Our robots are working hard to get those colors just right for you.',
      'Wait for it... Bam! Colors!'
    ];

    // Should return a TwiML document.
    // https://www.twilio.com/docs/api/twiml
    if (this.request.body && this.request.body.Body) {
      Meteor.call('addColor', this.request.body.Body);
    }

    // Return some TwiML
    this.response.writeHead(200, {
      'Content-Type': 'text/xml'
    });
    this.response.end('<?xml version="1.0" encoding="UTF-8" ?> <Response> <Sms> ' + _.sample(responses) + ' -' + Meteor.settings.name + '</Sms> </Response>\n');
  }
});

// Routing for color api output
Router.route('outgoing-colors', {
  path: '/api/colors',
  where: 'server',
  action: function() {
    var thisRoute = this;
    var color = Colors.find({}, { sort: { timestamp: -1 }}).fetch()[0];

    // Output rgb if wants
    if (_.isObject(this.params) && this.params.format) {
      color.colors = _.map(color.colors, function(c, ci) {
        var o = chroma(c);
        if (_.isFunction(o[thisRoute.params.format])) {
          return o[thisRoute.params.format]();
        }
        return c;
      });
    }

    this.response.writeHead(200, {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Document-ID': color._id
    });
    this.response.end(JSON.stringify(color) + '\n');
  }
});
<|endoftext|>


<commit_before>import React, { useState, useEffect } from 'react';
import { PropTypes as T } from 'prop-types';
import { connect } from 'react-redux';
import { useHistory, useLocation } from 'react-router-dom';
import qs from 'qs';
import moment from 'moment';

import { openDownloadModal } from '../../actions/action-creators';
import config from '../../config';
import { HeaderMessage } from '../../components/header';
import Header from '../../components/header';
import { parameterMax } from '../../utils/map-settings';

import DetailsCard from '../../components/dashboard/details-card';
import NearbyLocations from './nearby-locations';
import LatestMeasurementsCard from '../../components/dashboard/lastest-measurements-card';
import SourcesCard from '../../components/dashboard/sources-card';
import MeasureandsCard from '../../components/dashboard/measurands-card';
import TemporalCoverageCard from '../../components/dashboard/temporal-coverage-card';
import TimeSeriesCard from '../../components/dashboard/time-series-card';
import MapCard from '../../components/dashboard/map-card';
import DateSelector from '../../components/date-selector';

import { buildQS } from '../../utils/url';
import { NO_CITY } from '../../utils/constants';

const defaultState = {
  fetched: false,
  fetching: false,
  error: null,
  data: null,
};

function Location(props) {
  let history = useHistory();
  let location = useLocation();
  const { id } = props.match.params;

  const [dateRange, setDateRange] = useState(
    qs.parse(location.search, { ignoreQueryPrefix: true }).dateRange
  );

  useEffect(() => {
    let query = qs.parse(location.search, {
      ignoreQueryPrefix: true,
    });
    query.dateRange = dateRange;
    history.push(`${location.pathname}?${buildQS(query)}`);
  }, [dateRange]);

  const [{ fetched, fetching, error, data }, setState] = useState(defaultState);

  useEffect(() => {
    const fetchData = id => {
      setState(state => ({ ...state, fetching: true, error: null }));

      fetch(`${config.api}/locations/${encodeURIComponent(id)}`)
        .then(response => {
          if (response.status >= 400) {
            throw new Error('Bad response');
          }
          return response.json();
        })
        .then(
          json => {
            setState(state => ({
              ...state,
              fetched: true,
              fetching: false,
              data: json.results[0],
            }));
          },
          e => {
            console.log('e', e);
            setState(state => ({
              ...state,
              fetched: true,
              fetching: false,
              error: e,
            }));
          }
        );
    };

    fetchData(id);

    return () => {
      setState(defaultState);
    };
  }, [id]);

  if (!fetched && !fetching) {
    return null;
  }

  if (fetching) {
    return (
      <HeaderMessage>

Take a deep breath.

Location data is loading...

      </HeaderMessage>
    );
  }

  if (error || !data) {
    return (
      <HeaderMessage>

Uh oh, something went wrong.

            There was a problem getting the data. If you continue to have
            problems, please let us know.

              Send us an Email

      </HeaderMessage>
    );
  }

  function onDownloadClick() {
    props._openDownloadModal({
      country: data.country,
      area: data.city,
      location: data.location,
    });
  }
  const filteredParams = data.parameters.filter(p =>
    Object.keys(parameterMax).includes(p.parameterId.toString())
  );

  // Lifecycle stage of different sources.
  const lifecycle =
    data.sources && data.sources.map(s => s.lifecycle_stage).filter(Boolean);

  return (

      <Header
        tagline="Location"
        title={data.name}
        subtitle={`in ${data.city || NO_CITY}, ${data.country}`}
        action={{
          api: `${config.apiDocs}`,
          download: onDownloadClick,
          compare: `/compare/${encodeURIComponent(data.id)}`,
        }}
        sourceType={data.sensorType}
        isMobile={data.isMobile}
      />

        <DateSelector setDateRange={setDateRange} dateRange={dateRange} />

          <DetailsCard
            measurements={data.measurements}
            lifecycle={lifecycle}
            coords={{
              lat: data.coordinates.latitude,
              lng: data.coordinates.longitude,
            }}
            date={{
              start: data.firstUpdated,
              end: data.lastUpdated,
            }}
          />
          <LatestMeasurementsCard parameters={data.parameters} />
          <SourcesCard sources={data.sources} />
          <TimeSeriesCard
            locationId={data.id}
            parameters={data.parameters}
            xUnit="day"
            dateRange={dateRange}
            titleInfo={
              'The value of a pollutant over time during the specified window. While locations have varying time intervals over which they report, all time series charts show data at the same intervals. For one day or one month of data the hourly average is shown. For the project lifetime the daily averages are shown for the most recent week of data.'
            }
          />
          {data.isMobile && (
            <MapCard
              parameters={data.parameters}
              isMobile={data.isMobile}
              locationId={data.id}
              bbox={data.bounds}
              points={data.points}
              firstUpdated={data.firstUpdated}
              lastUpdated={data.lastUpdated}
            />
          )}
          <TemporalCoverageCard
            parameters={data.parameters}
            spatial="location"
            id={data.id}
            dateRange={dateRange}
            titleInfo={
              'The average number of measurements for each pollutant by hour, day, or month. In some views a window may be turned off if that view is not applicable to the selected time window.'
            }
          />
          <MeasureandsCard
            parameters={data.parameters}
            titleInfo={
              'The average of all values and total number of measurements for each pollutant during the chosen time window.'
            }
          />

        <NearbyLocations
          locationId={data.id}
          center={[data.coordinates.longitude, data.coordinates.latitude]}
          city={data.city}
          country={data.country}
          parameters={filteredParams}
          initialActiveParameter={filteredParams[0]}
        />

  );
}

Location.propTypes = {
  match: T.object,
  _openDownloadModal: T.func,
  sources: T.array,
  measurements: T.array,
  parameters: T.array,
};

// /////////////////////////////////////////////////////////////////// //
// Connect functions

function selector(state) {
  return {
    parameters: state.baseData.data.parameters,
    sources: state.baseData.data.sources,
    measurements: state.measurements,
    latestMeasurements: state.latestMeasurements,
  };
}

function dispatcher(dispatch) {
  return {
    _openDownloadModal: (...args) => dispatch(openDownloadModal(...args)),
  };
}

export default connect(selector, dispatcher)(Location);
<commit_msg>Fix lint<commit_after>import React, { useState, useEffect } from 'react';
import { PropTypes as T } from 'prop-types';
import { connect } from 'react-redux';
import { useHistory, useLocation } from 'react-router-dom';
import qs from 'qs';

import { openDownloadModal } from '../../actions/action-creators';
import config from '../../config';
import { HeaderMessage } from '../../components/header';
import Header from '../../components/header';
import { parameterMax } from '../../utils/map-settings';

import DetailsCard from '../../components/dashboard/details-card';
import NearbyLocations from './nearby-locations';
import LatestMeasurementsCard from '../../components/dashboard/lastest-measurements-card';
import SourcesCard from '../../components/dashboard/sources-card';
import MeasureandsCard from '../../components/dashboard/measurands-card';
import TemporalCoverageCard from '../../components/dashboard/temporal-coverage-card';
import TimeSeriesCard from '../../components/dashboard/time-series-card';
import MapCard from '../../components/dashboard/map-card';
import DateSelector from '../../components/date-selector';

import { buildQS } from '../../utils/url';
import { NO_CITY } from '../../utils/constants';

const defaultState = {
  fetched: false,
  fetching: false,
  error: null,
  data: null,
};

function Location(props) {
  let history = useHistory();
  let location = useLocation();
  const { id } = props.match.params;

  const [dateRange, setDateRange] = useState(
    qs.parse(location.search, { ignoreQueryPrefix: true }).dateRange
  );

  useEffect(() => {
    let query = qs.parse(location.search, {
      ignoreQueryPrefix: true,
    });
    query.dateRange = dateRange;
    history.push(`${location.pathname}?${buildQS(query)}`);
  }, [dateRange]);

  const [{ fetched, fetching, error, data }, setState] = useState(defaultState);

  useEffect(() => {
    const fetchData = id => {
      setState(state => ({ ...state, fetching: true, error: null }));

      fetch(`${config.api}/locations/${encodeURIComponent(id)}`)
        .then(response => {
          if (response.status >= 400) {
            throw new Error('Bad response');
          }
          return response.json();
        })
        .then(
          json => {
            setState(state => ({
              ...state,
              fetched: true,
              fetching: false,
              data: json.results[0],
            }));
          },
          e => {
            console.log('e', e);
            setState(state => ({
              ...state,
              fetched: true,
              fetching: false,
              error: e,
            }));
          }
        );
    };

    fetchData(id);

    return () => {
      setState(defaultState);
    };
  }, [id]);

  if (!fetched && !fetching) {
    return null;
  }

  if (fetching) {
    return (
      <HeaderMessage>

Take a deep breath.

Location data is loading...

      </HeaderMessage>
    );
  }

  if (error || !data) {
    return (
      <HeaderMessage>

Uh oh, something went wrong.

            There was a problem getting the data. If you continue to have
            problems, please let us know.

              Send us an Email

      </HeaderMessage>
    );
  }

  function onDownloadClick() {
    props._openDownloadModal({
      country: data.country,
      area: data.city,
      location: data.location,
    });
  }
  const filteredParams = data.parameters.filter(p =>
    Object.keys(parameterMax).includes(p.parameterId.toString())
  );

  // Lifecycle stage of different sources.
  const lifecycle =
    data.sources && data.sources.map(s => s.lifecycle_stage).filter(Boolean);

  return (

      <Header
        tagline="Location"
        title={data.name}
        subtitle={`in ${data.city || NO_CITY}, ${data.country}`}
        action={{
          api: `${config.apiDocs}`,
          download: onDownloadClick,
          compare: `/compare/${encodeURIComponent(data.id)}`,
        }}
        sourceType={data.sensorType}
        isMobile={data.isMobile}
      />

        <DateSelector setDateRange={setDateRange} dateRange={dateRange} />

          <DetailsCard
            measurements={data.measurements}
            lifecycle={lifecycle}
            coords={{
              lat: data.coordinates.latitude,
              lng: data.coordinates.longitude,
            }}
            date={{
              start: data.firstUpdated,
              end: data.lastUpdated,
            }}
          />
          <LatestMeasurementsCard parameters={data.parameters} />
          <SourcesCard sources={data.sources} />
          <TimeSeriesCard
            locationId={data.id}
            parameters={data.parameters}
            xUnit="day"
            dateRange={dateRange}
            titleInfo={
              'The value of a pollutant over time during the specified window. While locations have varying time intervals over which they report, all time series charts show data at the same intervals. For one day or one month of data the hourly average is shown. For the project lifetime the daily averages are shown for the most recent week of data.'
            }
          />
          {data.isMobile && (
            <MapCard
              parameters={data.parameters}
              isMobile={data.isMobile}
              locationId={data.id}
              bbox={data.bounds}
              points={data.points}
              firstUpdated={data.firstUpdated}
              lastUpdated={data.lastUpdated}
            />
          )}
          <TemporalCoverageCard
            parameters={data.parameters}
            spatial="location"
            id={data.id}
            dateRange={dateRange}
            titleInfo={
              'The average number of measurements for each pollutant by hour, day, or month. In some views a window may be turned off if that view is not applicable to the selected time window.'
            }
          />
          <MeasureandsCard
            parameters={data.parameters}
            titleInfo={
              'The average of all values and total number of measurements for each pollutant during the chosen time window.'
            }
          />

        <NearbyLocations
          locationId={data.id}
          center={[data.coordinates.longitude, data.coordinates.latitude]}
          city={data.city}
          country={data.country}
          parameters={filteredParams}
          initialActiveParameter={filteredParams[0]}
        />

  );
}

Location.propTypes = {
  match: T.object,
  _openDownloadModal: T.func,
  sources: T.array,
  measurements: T.array,
  parameters: T.array,
};

// /////////////////////////////////////////////////////////////////// //
// Connect functions

function selector(state) {
  return {
    parameters: state.baseData.data.parameters,
    sources: state.baseData.data.sources,
    measurements: state.measurements,
    latestMeasurements: state.latestMeasurements,
  };
}

function dispatcher(dispatch) {
  return {
    _openDownloadModal: (...args) => dispatch(openDownloadModal(...args)),
  };
}

export default connect(selector, dispatcher)(Location);
<|endoftext|>


<commit_before>if (typeof Leona === 'undefined') {
  var Leona = {};
}

(function() {
  function executeCallback(callback) {
    if (callback) {
      callback();
    }
  }

  var Condition = function(tester) {
    this.tester = tester;
  };

  Condition.prototype.met = function() {
    return (!!this.tester()) === true;
  };

  var Task = function(name, type, exec, options) {
    var self = this;
    self.name = name;
    self.type = type;
    self.exec = exec;
    self.opts = options;
    self.conditions = [];
    self.running = false;
    self.time = new Date().getTime();
    if (self.opts) {
      if (self.opts.delay) {
        self.conditions.push(new Condition(function() {
          return (new Date()).getTime() >= self.time + self.opts.delay;
        }));
      }
      if (self.opts.condition) {
        self.conditions.push(new Condition(self.opts.condition));
      }
      if (self.opts.renew) {
        self.renew = self.opts.renew;
      }
    }
  };

  Task.create = function(settings) {
    return new Task(
        settings.name || 'Anonymous Task',
        settings.type || Task.Types.Simple,
        settings.func,
        settings.opts);
  }

  Task.prototype.isReadyToRun = function() {
    var self = this;
    return self.conditions.every(function(condition) {
      return condition.met();
    });
  };

  Task.prototype.shouldRenew = function() {
    var self = this;
    if (self.renew === true) {
      return true;
    }
    if (typeof self.renew === 'function') {
      return (!!self.renew()) === true;
    }
    return false;
  }

  Task.prototype.start = function(refresh) {
    var self = this;
    if (self.running) {
      return;
    }
    self.time = new Date().getTime();
    scheduler.addTask(self);
  };

  Task.prototype.run = function(callback) {
    var self = this;
    self.running = true;

    function finishExecution() {
      self.running = false;
      executeCallback(callback);
    }

    setTimeout(function() {
      if (self.opts.async || self.opts.isAsyncExec) {
        self.exec(finishExecution);
      } else {
        self.exec();
        finishExecution();
      }
    });
  };

  Task.Types = {
    'Simple': {
      'name': 'Simple',
      'qps': 1000
    },
    'Ui': {
      'name': 'Ui',
      'qps': 7
    },
    'Network': {
      'name': 'Network',
      'qps': 4
    }
  };

  Task.Pool = function(options) {
    var self = this;
    self.qps = 0;
    self.qpsLimit = options.qps || 1000;
    self.tasks = [];
    self.worker = null;
  };

  Task.Pool.prototype.start = function() {
    var self = this;
    if (self.worker) {
      return;
    }
    self.worker = setInterval(function() {
      if (self.qps >= self.qpsLimit) {
        return;
      }
      var task = self.fetchReadyTask();
      if (task) {
        ++self.qps;
        task.run(function() {
          setTimeout(function() {
            --self.qps;
            if (task.shouldRenew()) {
              task.start();
            }
          }, 1000);
        });
      }
      if (self.done()) {
        clearInterval(self.worker);
        self.worker = null;
      }
    }, 100);
  };

  Task.Pool.prototype.add = function(task) {
    var self = this;
    self.tasks.push(task);
    self.start();
  };

  Task.Pool.prototype.fetchReadyTask = function() {
    var self = this;
    var taskCount = self.tasks.length;
    var task = null;
    for (var i = 0; i < taskCount; ++i) {
      if (self.tasks[i].isReadyToRun()) {
        task = self.tasks[i];
        self.tasks.splice(i, 1);
        break;
      }
    }
    return task;
  };

  Task.Pool.prototype.done = function() {
    return this.tasks.length === 0;
  };

  Task.Scheduler = function(options) {
    var self = this;
    self.pools = {};
  };

  Task.Scheduler.prototype.addTask = function(task) {
    var self = this;

    if (!self.pools[task.type.name]) {
      var newPool = new Task.Pool(task.type);
      self.pools[task.type.name] = newPool;
    }
    self.pools[task.type.name].add(task);
  };

  var scheduler = new Task.Scheduler();

  Leona.scheduler = scheduler;
  Leona.Task = Task;
})();<commit_msg>immediate restart<commit_after>if (typeof Leona === 'undefined') {
  var Leona = {};
}

(function() {
  function executeCallback(callback) {
    if (callback) {
      callback();
    }
  }

  var Condition = function(tester) {
    this.tester = tester;
  };

  Condition.prototype.met = function() {
    return (!!this.tester()) === true;
  };

  var Task = function(name, type, exec, options) {
    var self = this;
    self.name = name;
    self.type = type;
    self.exec = exec;
    self.opts = options;
    self.conditions = [];
    self.running = false;
    self.time = new Date().getTime();
    if (self.opts) {
      if (self.opts.delay) {
        self.conditions.push(new Condition(function() {
          return (new Date()).getTime() >= self.time + self.opts.delay;
        }));
      }
      if (self.opts.condition) {
        self.conditions.push(new Condition(self.opts.condition));
      }
      if (self.opts.renew) {
        self.renew = self.opts.renew;
      }
    }
  };

  Task.create = function(settings) {
    return new Task(
        settings.name || 'Anonymous Task',
        settings.type || Task.Types.Simple,
        settings.func,
        settings.opts);
  }

  Task.prototype.isReadyToRun = function() {
    var self = this;
    return self.conditions.every(function(condition) {
      return condition.met();
    });
  };

  Task.prototype.shouldRenew = function() {
    var self = this;
    if (self.renew === true) {
      return true;
    }
    if (typeof self.renew === 'function') {
      return (!!self.renew()) === true;
    }
    return false;
  }

  Task.prototype.start = function(refresh) {
    var self = this;
    if (self.running) {
      return;
    }
    self.time = new Date().getTime();
    scheduler.addTask(self);
  };

  Task.prototype.run = function(callback) {
    var self = this;
    self.running = true;

    function finishExecution() {
      self.running = false;
      executeCallback(callback);
    }

    setTimeout(function() {
      if (self.opts.async || self.opts.isAsyncExec) {
        self.exec(finishExecution);
      } else {
        self.exec();
        finishExecution();
      }
    });
  };

  Task.Types = {
    'Simple': {
      'name': 'Simple',
      'qps': 1000
    },
    'Ui': {
      'name': 'Ui',
      'qps': 7
    },
    'Network': {
      'name': 'Network',
      'qps': 4
    }
  };

  Task.Pool = function(options) {
    var self = this;
    self.qps = 0;
    self.qpsLimit = options.qps || 1000;
    self.tasks = [];
    self.worker = null;
  };

  Task.Pool.prototype.start = function() {
    var self = this;
    if (self.worker) {
      return;
    }
    self.worker = setInterval(function() {
      if (self.qps >= self.qpsLimit) {
        return;
      }
      var task = self.fetchReadyTask();
      if (task) {
        ++self.qps;
        task.run(function() {
          setTimeout(function() {
            --self.qps;
          }, 1000);
          if (task.shouldRenew()) {
            setTimeout(function() {
              task.start();
            });
          }
        });
      }
      if (self.done()) {
        clearInterval(self.worker);
        self.worker = null;
      }
    }, 100);
  };

  Task.Pool.prototype.add = function(task) {
    var self = this;
    self.tasks.push(task);
    self.start();
  };

  Task.Pool.prototype.fetchReadyTask = function() {
    var self = this;
    var taskCount = self.tasks.length;
    var task = null;
    for (var i = 0; i < taskCount; ++i) {
      if (self.tasks[i].isReadyToRun()) {
        task = self.tasks[i];
        self.tasks.splice(i, 1);
        break;
      }
    }
    return task;
  };

  Task.Pool.prototype.done = function() {
    return this.tasks.length === 0;
  };

  Task.Scheduler = function(options) {
    var self = this;
    self.pools = {};
  };

  Task.Scheduler.prototype.addTask = function(task) {
    var self = this;

    if (!self.pools[task.type.name]) {
      var newPool = new Task.Pool(task.type);
      self.pools[task.type.name] = newPool;
    }
    self.pools[task.type.name].add(task);
  };

  var scheduler = new Task.Scheduler();

  Leona.scheduler = scheduler;
  Leona.Task = Task;
})();<|endoftext|>


<commit_before>import moment from 'moment';
import Component from '@ember/component';
import { run } from '@ember/runloop';

export default Component.extend({
  didInsertElement() {
    var self = this;
    this.interval = setInterval(function(){ run(self, 'tick'); }, 1000);
    this.tick();
  },

  willDestroyElement(){
    clearInterval(this.interval);
    this._super();
  },

  tick: function(now) {
    if (!now) {
      now = moment();
    }
    this.setProperties({
      now: now,
      hours: now.format('hh'),
      minutes: now.format('mm'),
      seconds: now.format('ss')
    });
  },

  actions: {
    forceTick: function() {
      clearInterval(this.interval);
      this.tick(this.get('now').add({hours: 1, minutes: 1, seconds: 1}));
    }
  }

});
<commit_msg>avoid mutation in didInsertElement<commit_after>import moment from 'moment';
import Component from '@ember/component';
import { run } from '@ember/runloop';

export default Component.extend({
  init() {
    this._super();
    this.tick();
  },

  didInsertElement() {
    var self = this;
    this.interval = setInterval(function(){ run(self, 'tick'); }, 1000);
  },

  willDestroyElement(){
    clearInterval(this.interval);
    this._super();
  },

  tick: function(now) {
    if (!now) {
      now = moment();
    }
    this.setProperties({
      now: now,
      hours: now.format('hh'),
      minutes: now.format('mm'),
      seconds: now.format('ss')
    });
  },

  actions: {
    forceTick: function() {
      clearInterval(this.interval);
      this.tick(this.get('now').add({hours: 1, minutes: 1, seconds: 1}));
    }
  }

});
<|endoftext|>


<commit_before>(function() {
    // Create the connector object
    var myConnector = tableau.makeConnector();

    // Define the schema
    myConnector.getSchema = function(schemaCallback) {
        var cols = [
		{ id : "npc",  alias : "Npc", dataType : tableau.dataTypeEnum.string }
		];

        var tableSchema = {
            id: "riversideCrime",
            alias: "Riverside Crime JSON entries",
            columns: cols
        };

        schemaCallback([tableSchema]);
    };

    // Download the data
    myConnector.getData = function(table, doneCallback) {
        $.getJSON("https://riversideca.gov/transparency/data/dataset/json/27", function(resp) {
            var feat = resp.features,
                tableData = [];

            // Iterate over the JSON object
            for (var i = 0, len = feat.length; i < len; i++) {
                tableData.push({

                    "npc": feat[i]..npc,

                });
            }

            table.appendRows(tableData);
            doneCallback();
        });
    };

    tableau.registerConnector(myConnector);

    // Create event listeners for when the user submits the form
    $(document).ready(function() {
        $("#submitButton").click(function() {
            tableau.connectionName = "Riverside Crime Report"; // This will be the data source name in Tableau
            tableau.submit(); // This sends the connector object to Tableau
        });
    });
})();
<commit_msg>Update RivCrimeReport.js<commit_after>(function() {
    // Create the connector object
    var myConnector = tableau.makeConnector();

    // Define the schema
    myConnector.getSchema = function(schemaCallback) {
        var cols = [
		{ id : "npc",  alias : "Npc", dataType : tableau.dataTypeEnum.string }
		];

        var tableSchema = {
            id: "riversideCrime",
            alias: "Riverside Crime JSON entries",
            columns: cols
        };

        schemaCallback([tableSchema]);
    };

    // Download the data
    myConnector.getData = function(table, doneCallback) {
        $.getJSON("https://riversideca.gov/transparency/data/dataset/json/27", function(resp) {
            var feat = resp.features,
                tableData = [];

            // Iterate over the JSON object
            for (var i = 0, len = feat.length; i < len; i++) {
                tableData.push({

                    "npc": feat[i].npc,

                });
            }

            table.appendRows(tableData);
            doneCallback();
        });
    };

    tableau.registerConnector(myConnector);

    // Create event listeners for when the user submits the form
    $(document).ready(function() {
        $("#submitButton").click(function() {
            tableau.connectionName = "Riverside Crime Report"; // This will be the data source name in Tableau
            tableau.submit(); // This sends the connector object to Tableau
        });
    });
})();
<|endoftext|>


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

const libraryName = 'Reactstrap';

module.exports = function (env) {
  let outputFile;
  const plugins = [
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(env)
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin()
  ];

  if (env === 'production') {
    plugins.push(new webpack.optimize.UglifyJsPlugin(
      {
        minimize: true,
        compress: {
          warnings: false
        },
        mangle: true
      }
    ));
    outputFile = libraryName.toLowerCase() + '.min.js';
  } else {
    outputFile = libraryName.toLowerCase() + '.js';
  }

  const config = {
    devtool: 'source-map',
    entry: [__dirname + '/src/index.js'],
    output: {
      path: __dirname + '/dist',
      filename: outputFile,
      library: libraryName,
      libraryTarget: 'umd',
      umdNamedDefine: true
    },
    externals: [
      {
        react: {
          root: 'React',
          commonjs2: 'react',
          commonjs: 'react',
          amd: 'react'
        }
      },
      {
        'react-dom': {
          root: 'ReactDOM',
          commonjs2: 'react-dom',
          commonjs: 'react-dom',
          amd: 'react-dom'
        }
      },
      {
        'react-addons-css-transition-group': {
          commonjs: 'react-addons-css-transition-group',
          commonjs2: 'react-addons-css-transition-group',
          amd: 'react-addons-css-transition-group',
          root: ['React', 'addons', 'CSSTransitionGroup']
        }
      }
    ],
    module: {
      loaders: [
        {
          test: /\.(json)$/,
          loaders: [
            'json-loader?cacheDirectory'
          ]
        },
        {
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          loaders: [
            'babel-loader?cacheDirectory'
          ]
        },
      ]
    },
    resolve: {
      alias: {
        reactstrap: 'src/index'
      },
      extensions: ['', '.js', '.jsx', '.json'],
      root: [
        path.resolve('./src')
      ]
    },
    plugins: plugins
  };

  return config;
};
<commit_msg>build(react-addons-transition-group): update externals (#38)<commit_after>const path = require('path');
const webpack = require('webpack');

const libraryName = 'Reactstrap';

module.exports = function (env) {
  let outputFile;
  const plugins = [
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(env)
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin()
  ];

  if (env === 'production') {
    plugins.push(new webpack.optimize.UglifyJsPlugin(
      {
        minimize: true,
        compress: {
          warnings: false
        },
        mangle: true
      }
    ));
    outputFile = libraryName.toLowerCase() + '.min.js';
  } else {
    outputFile = libraryName.toLowerCase() + '.js';
  }

  const config = {
    devtool: 'source-map',
    entry: [__dirname + '/src/index.js'],
    output: {
      path: __dirname + '/dist',
      filename: outputFile,
      library: libraryName,
      libraryTarget: 'umd',
      umdNamedDefine: true
    },
    externals: [
      {
        react: {
          root: 'React',
          commonjs2: 'react',
          commonjs: 'react',
          amd: 'react'
        }
      },
      {
        'react-dom': {
          root: 'ReactDOM',
          commonjs2: 'react-dom',
          commonjs: 'react-dom',
          amd: 'react-dom'
        }
      },
      {
        'react-addons-transition-group': {
          commonjs: 'react-addons-transition-group',
          commonjs2: 'react-addons-transition-group',
          amd: 'react-addons-transition-group',
          root: ['React', 'addons', 'TransitionGroup']
        }
      }
    ],
    module: {
      loaders: [
        {
          test: /\.(json)$/,
          loaders: [
            'json-loader?cacheDirectory'
          ]
        },
        {
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          loaders: [
            'babel-loader?cacheDirectory'
          ]
        },
      ]
    },
    resolve: {
      alias: {
        reactstrap: 'src/index'
      },
      extensions: ['', '.js', '.jsx', '.json'],
      root: [
        path.resolve('./src')
      ]
    },
    plugins: plugins
  };

  return config;
};
<|endoftext|>


<commit_before>/**
 * Base webpack config used across other specific configs
 */

import _ from 'lodash';
import path from 'path';
import { dependencies as externals } from './app/package.json';
import { optionalDependencies as additionalExternals } from './app/package.json';

export default {
  module: {
    rules: [{
      test: /\.jsx?$/,
      use: [{
        loader: 'babel-loader'
      }],
      exclude: /node_modules/
    }]
  },

  output: {
    path: path.join(__dirname, 'app'),
    filename: 'bundle.js',

    // https://github.com/webpack/webpack/issues/1114
    libraryTarget: 'commonjs2'
  },

  /**
   * Determine the array of extensions that should be used to resolve modules.
   */
  resolve: {
    extensions: ['.js', '.jsx', '.json'],
    mainFields: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'],
    alias: {
      superagent: 'superagent/lib/client.js',
      emitter: 'component-emitter',
      reduce  : 'reduce-component'
    }
  },
  resolveLoader: { },

  plugins: [],

  externals: _.keys(_.merge({}, externals, additionalExternals) || {})
};
<commit_msg>don't exclude open dependency from babel-loader, as it contains ES6 spread operator<commit_after>/**
 * Base webpack config used across other specific configs
 */

import _ from 'lodash';
import path from 'path';
import { dependencies as externals } from './app/package.json';
import { optionalDependencies as additionalExternals } from './app/package.json';

export default {
  module: {
    rules: [{
      test: /\.jsx?$/,
      use: [{
        loader: 'babel-loader'
      }],
      exclude: /node_modules\/(?!open)/
    }]
  },

  output: {
    path: path.join(__dirname, 'app'),
    filename: 'bundle.js',

    // https://github.com/webpack/webpack/issues/1114
    libraryTarget: 'commonjs2'
  },

  /**
   * Determine the array of extensions that should be used to resolve modules.
   */
  resolve: {
    extensions: ['.js', '.jsx', '.json'],
    mainFields: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'],
    alias: {
      superagent: 'superagent/lib/client.js',
      emitter: 'component-emitter',
      reduce  : 'reduce-component'
    }
  },
  resolveLoader: { },

  plugins: [],

  externals: _.keys(_.merge({}, externals, additionalExternals) || {})
};
<|endoftext|>


<commit_before>/**
 * Base webpack config used across other specific configs
 */

import path from 'path';
import validate from 'webpack-validator';
import {
  dependencies as externals
} from './app/package.json';

export default validate({
  module: {
    loaders: [{
      test: /\.jsx?$/,
      loaders: ['babel-loader'],
      exclude: /node_modules/
    }, {
      test: /\.json$/,
      loader: 'json-loader'
    },
    {
      test: /\.(?:ico|gif|png|jpg|jpeg|svg|webp)$/,
      loader: 'url-loader'
    }]
  },

  output: {
    path: path.join(__dirname, 'app'),
    filename: 'bundle.js',

    // https://github.com/webpack/webpack/issues/1114
    libraryTarget: 'commonjs2'
  },

  // https://webpack.github.io/docs/configuration.html#resolve
  resolve: {
    extensions: ['', '.js', '.jsx', '.json'],
    packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main']
  },

  plugins: [],

  externals: Object.keys(externals || {})
});
<commit_msg>Removed svg from webpack.config.base.js<commit_after>/**
 * Base webpack config used across other specific configs
 */

import path from 'path';
import validate from 'webpack-validator';
import {
  dependencies as externals
} from './app/package.json';

export default validate({
  module: {
    loaders: [{
      test: /\.jsx?$/,
      loaders: ['babel-loader'],
      exclude: /node_modules/
    }, {
      test: /\.json$/,
      loader: 'json-loader'
    },
    {
      test: /\.(?:ico|gif|png|jpg|jpeg|webp)$/,
      loader: 'url-loader'
    }]
  },

  output: {
    path: path.join(__dirname, 'app'),
    filename: 'bundle.js',

    // https://github.com/webpack/webpack/issues/1114
    libraryTarget: 'commonjs2'
  },

  // https://webpack.github.io/docs/configuration.html#resolve
  resolve: {
    extensions: ['', '.js', '.jsx', '.json'],
    packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main']
  },

  plugins: [],

  externals: Object.keys(externals || {})
});
<|endoftext|>


<commit_before>/* eslint no-var: 0 */
var nib = require('nib');
var path = require('path');
var webpack = require('webpack');

module.exports = {
    cache: true,
    target: 'web',
    entry: {
        app: [
            path.resolve(__dirname, 'src/web/index.jsx')
        ],
        vendor: [
            'async',
            'classnames',
            'gcode-interpreter',
            'gcode-parser',
            'i18next',
            'jsuri',
            'lodash',
            'moment',
            'pubsub-js',
            'rc-slider',
            'rc-switch',
            'react',
            'react-dom',
            'react-addons-update',
            'react-bootstrap',
            'react-datagrid',
            'react-dom',
            'react-datagrid',
            'react-dropzone',
            'react-infinite',
            'react-router',
            'react-select',
            'react-sortablejs',
            'sha1',
            'sortablejs',
            'stacktrace-js',
            'three'
        ]
    },
    output: {
        path: path.join(__dirname, 'dist', 'web'),
        filename: '[name].js'
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js')
    ],
    module: {
        preLoaders: [
            // http://survivejs.com/webpack_react/linting_in_webpack/
            {
                test: /\.jsx?$/,
                loaders: ['eslint'],
                exclude: /node_modules/
            },
            {
                test: /\.styl$/,
                loader: 'stylint'
            }
        ],
        loaders: [
            {
                test: /\.json$/,
                loader: 'json'
            },
            {
                test: /\.jsx?$/,
                loader: 'babel',
                exclude: /(node_modules|bower_components)/,
                query: {
                    env: {
                        development: {
                            presets: ['react-hmre']
                        }
                    },
                    presets: ['es2015', 'stage-0', 'react'],
                    plugins: [
                        'transform-decorators-legacy'
                    ]
                }
            },
            {
                test: /\.styl$/,
                loader: 'style!css!stylus'
            },
            {
                test: /\.css$/,
                loader: 'style!css'
            },
            {
                test: /\.(png|jpg)$/,
                loader: 'url',
                query: {
                    limit: 8192
                }
            },
            {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'url',
                query: {
                    limit: 10000,
                    mimetype: 'application/font-woff'
                }
            },
            {
                test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'file'
            }
        ]
    },
    stylus: {
        // nib - CSS3 extensions for Stylus
        use: [nib()],
        // no need to have a '@import "nib"' in the stylesheet
        import: ['~nib/lib/nib/index.styl']
    },
    resolve: {
        alias: {},
        extensions: ['', '.js', '.jsx', '.styl']
    },
    node: {
        fs: 'empty'
    }
};
<commit_msg>Update vendor bundle dependencies<commit_after>/* eslint no-var: 0 */
var nib = require('nib');
var path = require('path');
var webpack = require('webpack');

module.exports = {
    cache: true,
    target: 'web',
    entry: {
        app: [
            path.resolve(__dirname, 'src/web/index.jsx')
        ],
        vendor: [
            'async',
            'classnames',
            'colornames',
            'gcode-interpreter',
            'gcode-parser',
            'gcode-toolpath',
            'i18next',
            'jsuri',
            'lodash',
            'moment',
            'mousetrap',
            'pubsub-js',
            'rc-slider',
            'rc-switch',
            'react',
            'react-dom',
            'react-addons-shallow-compare',
            'react-addons-update',
            'react-bootstrap',
            'react-dom',
            'react-dropzone',
            'react-infinite',
            'react-router',
            'react-select',
            'react-sortablejs',
            'react-virtualized',
            'sha1',
            'sortablejs',
            'stacktrace-js',
            'superagent',
            'three'
        ]
    },
    output: {
        path: path.join(__dirname, 'dist', 'web'),
        filename: '[name].js'
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js')
    ],
    module: {
        preLoaders: [
            // http://survivejs.com/webpack_react/linting_in_webpack/
            {
                test: /\.jsx?$/,
                loaders: ['eslint'],
                exclude: /node_modules/
            },
            {
                test: /\.styl$/,
                loader: 'stylint'
            }
        ],
        loaders: [
            {
                test: /\.json$/,
                loader: 'json'
            },
            {
                test: /\.jsx?$/,
                loader: 'babel',
                exclude: /(node_modules|bower_components)/,
                query: {
                    env: {
                        development: {
                            presets: ['react-hmre']
                        }
                    },
                    presets: ['es2015', 'stage-0', 'react'],
                    plugins: [
                        'transform-decorators-legacy'
                    ]
                }
            },
            {
                test: /\.styl$/,
                loader: 'style!css!stylus'
            },
            {
                test: /\.css$/,
                loader: 'style!css'
            },
            {
                test: /\.(png|jpg)$/,
                loader: 'url',
                query: {
                    limit: 8192
                }
            },
            {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'url',
                query: {
                    limit: 10000,
                    mimetype: 'application/font-woff'
                }
            },
            {
                test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'file'
            }
        ]
    },
    stylus: {
        // nib - CSS3 extensions for Stylus
        use: [nib()],
        // no need to have a '@import "nib"' in the stylesheet
        import: ['~nib/lib/nib/index.styl']
    },
    resolve: {
        alias: {},
        extensions: ['', '.js', '.jsx', '.styl']
    },
    node: {
        fs: 'empty'
    }
};
<|endoftext|>


<commit_before>const path = require('path');
const webpackMerge = require('webpack-merge');
const autoprefixer = require('autoprefixer');
const webpackCommon = require('./common.config');

// webpack plugins
const HtmlWebpackPlugin = require('html-webpack-plugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');

module.exports = webpackMerge(webpackCommon, {

  bail: true,

  devtool: 'source-map',

  output: {

    path: path.resolve(__dirname, '../dist'),

    filename: '[name]-[hash].min.js',

    sourceMapFilename: '[name]-[hash].map',

    chunkFilename: '[id]-[chunkhash].js'

  },

  module: {

    rules: [
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            {
              loader: 'css-loader',
              options: {
                modules: true,
                minimize: true,
                sourceMap: true,
                importLoaders: 2,
                localIdentName: '[name]__[local]'
              }
            },
            {
              loader: 'postcss-loader',
              options: {
                config: {
                  path: path.resolve(__dirname, 'postcss.config.js')
                },
                sourceMap: true
              }
            },
            {
              loader: 'sass-loader',
              options: {
                outputStyle: 'expanded',
                sourceMap: true,
                sourceMapContents: true
              }
            }
          ]
        })
      }
    ]

  },

  plugins: [
    new HtmlWebpackPlugin({
      inject: true,
      template: path.resolve(__dirname, '../static/index.html'),
      favicon: path.resolve(__dirname, '../static/favicon.ico'),
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true
      }
    }),
    new CleanWebpackPlugin(['dist'], {
      root: path.resolve(__dirname, '..'),
      exclude: '.gitignore'
    }),
    new DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new ExtractTextPlugin('[name]-[chunkhash].min.css'),
    new UglifyJsPlugin({
      compressor: {
        screw_ie8: true,
        warnings: false
      },
      mangle: {
        screw_ie8: true
      },
      output: {
        comments: false,
        screw_ie8: true
      },
      sourceMap: true
    }),
    new LoaderOptionsPlugin({
      options: {
        context: '/',
        sassLoader: {
          includePaths: [path.resolve(__dirname, '../src')]
        }
      }
    })
  ]

});
<commit_msg>webpack: copy static to dist when build<commit_after>const path = require('path');
const webpackMerge = require('webpack-merge');
const autoprefixer = require('autoprefixer');
const webpackCommon = require('./common.config');

// webpack plugins
const HtmlWebpackPlugin = require('html-webpack-plugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');

module.exports = webpackMerge(webpackCommon, {

  bail: true,

  devtool: 'source-map',

  output: {

    path: path.resolve(__dirname, '../dist'),

    filename: '[name]-[hash].min.js',

    sourceMapFilename: '[name]-[hash].map',

    chunkFilename: '[id]-[chunkhash].js'

  },

  module: {

    rules: [
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            {
              loader: 'css-loader',
              options: {
                modules: true,
                minimize: true,
                sourceMap: true,
                importLoaders: 2,
                localIdentName: '[name]__[local]'
              }
            },
            {
              loader: 'postcss-loader',
              options: {
                config: {
                  path: path.resolve(__dirname, 'postcss.config.js')
                },
                sourceMap: true
              }
            },
            {
              loader: 'sass-loader',
              options: {
                outputStyle: 'expanded',
                sourceMap: true,
                sourceMapContents: true
              }
            }
          ]
        })
      }
    ]

  },

  plugins: [
    new HtmlWebpackPlugin({
      inject: true,
      template: path.resolve(__dirname, '../static/index.html'),
      favicon: path.resolve(__dirname, '../static/favicon.ico'),
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true
      }
    }),
    new CopyWebpackPlugin([
      {from: path.resolve(__dirname, '../static')}
    ], {
      ignore: ['index.html', 'favicon.ico']
    }),
    new CleanWebpackPlugin(['dist'], {
      root: path.resolve(__dirname, '..'),
      exclude: '.gitignore'
    }),
    new DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new ExtractTextPlugin('[name]-[chunkhash].min.css'),
    new UglifyJsPlugin({
      compressor: {
        screw_ie8: true,
        warnings: false
      },
      mangle: {
        screw_ie8: true
      },
      output: {
        comments: false,
        screw_ie8: true
      },
      sourceMap: true
    }),
    new LoaderOptionsPlugin({
      options: {
        context: '/',
        sassLoader: {
          includePaths: [path.resolve(__dirname, '../src')]
        }
      }
    })
  ]

});
<|endoftext|>


<commit_before>// Webpack config for creating the production bundle.
var path = require('path');
var webpack = require('webpack');
var CleanPlugin = require('clean-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var strip = require('strip-loader');

var projectRootPath = path.resolve(__dirname, '../');
var assetsPath = path.resolve(projectRootPath, './static/dist');

// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'));

module.exports = {
  devtool: 'source-map',
  context: path.resolve(__dirname, '..'),
  entry: {
    'main': [
      'bootstrap-sass!./src/theme/bootstrap.config.prod.js',
      'font-awesome-webpack!./src/theme/font-awesome.config.prod.js',
      './src/client.js'
    ],
    assets: './src/assets.js'
  },
  output: {
    path: assetsPath,
    filename: '[name]-[chunkhash].js',
    chunkFilename: '[name]-[chunkhash].js',
    publicPath: 'https://some-game.s3-us-west-2.amazonaws.com/'
  },
  module: {
    loaders: [
      { test: /\.typeface\.js$/, loader: "file" },
      { test: /\.jsx?$/, exclude: /node_modules|\.typeface\.js$/, loaders: [strip.loader('debug'), 'babel']},
      { test: /models.+\.json$/, loader: "file" },
      { test: /\.json$/, exclude: /models.+\.json$/, loader: "json-loader" },
      { test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap=true&sourceMapContents=true') },
      { test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true') },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
      { test: /\.(obj|dae)$/, loader: "file" },
      { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=200' }
    ]
  },
  progress: true,
  resolve: {
    modulesDirectories: [
      'src',
      'assets',
      'node_modules'
    ],
    extensions: ['', '.json', '.js', '.jsx']
  },
  plugins: [
    new CleanPlugin([assetsPath], { root: projectRootPath }),

    // css files from the extract-text-plugin loader
    new ExtractTextPlugin('[name]-[chunkhash].css', {allChunks: true}),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      },

      __CLIENT__: true,
      __SERVER__: false,
      __DEVELOPMENT__: false,
      __DEVTOOLS__: false
    }),

    // ignore dev config
    new webpack.IgnorePlugin(/\.\/dev/, /\/config$/),

    // optimizations
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),

    webpackIsomorphicToolsPlugin
  ]
};
<commit_msg>no ass<commit_after>// Webpack config for creating the production bundle.
var path = require('path');
var webpack = require('webpack');
var CleanPlugin = require('clean-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var strip = require('strip-loader');

var projectRootPath = path.resolve(__dirname, '../');
var assetsPath = path.resolve(projectRootPath, './static/dist');

// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'));

module.exports = {
  devtool: 'source-map',
  context: path.resolve(__dirname, '..'),
  entry: {
    'main': [
      'bootstrap-sass!./src/theme/bootstrap.config.prod.js',
      'font-awesome-webpack!./src/theme/font-awesome.config.prod.js',
      './src/client.js'
    ]
  },
  output: {
    path: assetsPath,
    filename: '[name]-[chunkhash].js',
    chunkFilename: '[name]-[chunkhash].js',
    publicPath: 'https://some-game.s3-us-west-2.amazonaws.com/'
  },
  module: {
    loaders: [
      { test: /\.typeface\.js$/, loader: "file" },
      { test: /\.jsx?$/, exclude: /node_modules|\.typeface\.js$/, loaders: [strip.loader('debug'), 'babel']},
      { test: /models.+\.json$/, loader: "file" },
      { test: /\.json$/, exclude: /models.+\.json$/, loader: "json-loader" },
      { test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap=true&sourceMapContents=true') },
      { test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true') },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
      { test: /\.(obj|dae)$/, loader: "file" },
      { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=200' }
    ]
  },
  progress: true,
  resolve: {
    modulesDirectories: [
      'src',
      'assets',
      'node_modules'
    ],
    extensions: ['', '.json', '.js', '.jsx']
  },
  plugins: [
    new CleanPlugin([assetsPath], { root: projectRootPath }),

    // css files from the extract-text-plugin loader
    new ExtractTextPlugin('[name]-[chunkhash].css', {allChunks: true}),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      },

      __CLIENT__: true,
      __SERVER__: false,
      __DEVELOPMENT__: false,
      __DEVTOOLS__: false
    }),

    // ignore dev config
    new webpack.IgnorePlugin(/\.\/dev/, /\/config$/),

    // optimizations
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),

    webpackIsomorphicToolsPlugin
  ]
};
<|endoftext|>


<commit_before>let webpack = require('webpack');
let path = require('path');
let StatsWriterPlugin = require('webpack-stats-plugin').StatsWriterPlugin;
let Visualizer = require('webpack-visualizer-plugin');
let ExtractTextPlugin = require('extract-text-webpack-plugin');

let webpackConfig = {
    resolve: {
        extensions: ['.js']
    },
    entry: {
        main: [
            './client.js'
        ],
        vendor: [
            'react', 'react-dom', 'react-hotkeys', 'react-list', 'react-responsive', 'react-custom-scrollbars', 'react-resize-aware', 'async', 'immutable', 'classnames', 'fluxible', 'fluxible-addons-react', 'fluxible-plugin-fetchr', 'fluxible-router', 'react-google-recaptcha', 'identicons-react', 'iso-639-1', 'lodash', 'cheerio', 'react-dnd', 'react-dnd-html5-backend', 'striptags', 'js-sha512', 'debug', 'md5', 'js-cookie', 'cookie', 'fumble', 'crypt'
        ]
    },
    output: {
        path: path.resolve('./build/js'),
        publicPath: '/public/js/',
        filename: '[name].js'
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules\/(?!identicons)/ ,
                loader: 'babel-loader',
                options: {
                    presets: [
                        ['es2015', { modules: false }]
                    ]
                }
            },
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: 'css-loader',
                    publicPath: '/public/css/'
                })
            },
            // Getting URLs for font files otherwise we get encoding errors in css-loader
            { test   : /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/, loader: 'url-loader?limit=100000'}
        ]
    },
    node: {
        setImmediate: false
    },
    plugins: [
        // css files from the extract-text-plugin loader
        new ExtractTextPlugin({
            filename: '../css/vendor.bundle.css',
            disable: false,
            allChunks: true
        }),

        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('production'),
                // Mainly used to require CSS files with webpack, which can happen only on browser
                // Used as `if (process.env.BROWSER)...`
                BROWSER: JSON.stringify(true),
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            compress: {
                warnings: false
            }
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks: Infinity,
            filename: '[name].bundle.js'
        }),
        // Write out stats file to build directory.
        new StatsWriterPlugin({
            filename: 'webpack.stats.json', // Default
            fields: null,
            transform: function (data) {
                return JSON.stringify(data, null, 2);
            }
        }),
        new Visualizer()
    ],
    devtool: 'source-map'
};

module.exports = webpackConfig;
<commit_msg>SWIK-1123 removing ExtractStylePlugin until we can figure a better way to exclude theme CSS<commit_after>let webpack = require('webpack');
let path = require('path');
let StatsWriterPlugin = require('webpack-stats-plugin').StatsWriterPlugin;
let Visualizer = require('webpack-visualizer-plugin');
let ExtractTextPlugin = require('extract-text-webpack-plugin');

let webpackConfig = {
    resolve: {
        extensions: ['.js']
    },
    entry: {
        main: [
            './client.js'
        ],
        vendor: [
            'react', 'react-dom', 'react-hotkeys', 'react-list', 'react-responsive', 'react-custom-scrollbars', 'react-resize-aware', 'async', 'immutable', 'classnames', 'fluxible', 'fluxible-addons-react', 'fluxible-plugin-fetchr', 'fluxible-router', 'react-google-recaptcha', 'identicons-react', 'iso-639-1', 'lodash', 'cheerio', 'react-dnd', 'react-dnd-html5-backend', 'striptags', 'js-sha512', 'debug', 'md5', 'js-cookie', 'cookie', 'fumble', 'crypt'
        ]
    },
    output: {
        path: path.resolve('./build/js'),
        publicPath: '/public/js/',
        filename: '[name].js'
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules\/(?!identicons)/ ,
                loader: 'babel-loader',
                options: {
                    presets: [
                        ['es2015', { modules: false }]
                    ]
                }
            },
            // {
            //     test: /\.css$/,
            //     loader: ExtractTextPlugin.extract({
            //         fallback: 'style-loader',
            //         use: 'css-loader',
            //         publicPath: '/public/css/'
            //     })
            // },
            { test: /\.css$/,
                use: [
                    {
                        loader: 'style-loader'
                    },
                    {
                        loader: 'css-loader'
                    }
                ]
            },
            // Getting URLs for font files otherwise we get encoding errors in css-loader
            { test   : /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/, loader: 'url-loader?limit=100000'}
        ]
    },
    node: {
        setImmediate: false
    },
    plugins: [
        // css files from the extract-text-plugin loader
        // new ExtractTextPlugin({
        //     filename: '../css/vendor.bundle.css',
        //     disable: false,
        //     allChunks: true
        // }),

        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('production'),
                // Mainly used to require CSS files with webpack, which can happen only on browser
                // Used as `if (process.env.BROWSER)...`
                BROWSER: JSON.stringify(true),
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            compress: {
                warnings: false
            }
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks: Infinity,
            filename: '[name].bundle.js'
        }),
        // Write out stats file to build directory.
        new StatsWriterPlugin({
            filename: 'webpack.stats.json', // Default
            fields: null,
            transform: function (data) {
                return JSON.stringify(data, null, 2);
            }
        }),
        new Visualizer()
    ],
    devtool: 'source-map'
};

module.exports = webpackConfig;
<|endoftext|>