<commit_before>require('whatwg-fetch');

var $ = require('jquery');
var _ = require('underscore');
var ConfigModel = require('./data/config-model');
var LayerStyleCollection = require('./embed/style-collection');
var MetricsTracker = require('./components/metrics/metrics-tracker');
var deepInsights = require('../deep-insights/index');
var EmbedIntegrations = require('./embed/embed-integrations');
var URLStateHelper = require('../deep-insights/api/url-helper.js');
var EmbedView = require('./embed/embed-view');

var vizJSON = window.vizJSON;
var authTokens = window.authTokens;
var mapzenApiKey = window.mapzenApiKey;
var stateJSON = window.stateJSON;
var layersData = window.layersData;
var baseURL = window.baseURL;
var anyLayerWithLegends = vizJSON.layers.some(layer => layer.legends && layer.legends.length);

var configModel = new ConfigModel({ base_url: baseURL });

var layerStyleCollection = new LayerStyleCollection();
layerStyleCollection.resetByLayersData(layersData);

var embedView = new EmbedView({
  title: vizJSON.title,
  showMenu: vizJSON.options.dashboard_menu,
  showLegends: vizJSON.options.legends && anyLayerWithLegends
});

MetricsTracker.init({
  visId: vizJSON.id,
  configModel: configModel
});

$('#dashboard').prepend(embedView.render().$el);

var cartoLogoOption = _.findWhere(vizJSON.overlays, {type: 'logo'});
var dashboardOpts = {
  no_cdn: false,
  cartodb_logo: cartoLogoOption !== undefined,
  renderMenu: vizJSON.options.dashboard_menu,
  share_urls: true,
  authToken: authTokens,
  layerSelectorEnabled: true,
  mapzenApiKey: mapzenApiKey
};

var stateFromURL = URLStateHelper.getStateFromCurrentURL();
if (stateFromURL && !_.isEmpty(stateFromURL)) {
  _.extend(dashboardOpts, {
    state: stateFromURL
  });
} else if (stateJSON && stateJSON !== '{}') {
  _.extend(dashboardOpts, {
    state: stateJSON
  });
}

deepInsights.createDashboard('.js-embed-map', vizJSON, dashboardOpts, function (error, dashboard) {
  if (error) {
    console.error('Dashboard has some errors:', error);
  }

  var map = dashboard.getMap().map;
  var scrollwheel = vizJSON.options.scrollwheel;
  var method = scrollwheel ? 'enableScrollWheel' : 'disableScrollWheel';
  map && map[method] && map[method]();

  var embedIntegrations = new EmbedIntegrations({
    deepInsightsDashboard: dashboard,
    layerStyleCollection: layerStyleCollection
  });

  window.embedIntegrations = embedIntegrations;
});

window.layerStyleCollection = layerStyleCollection;
<commit_msg>Don't use arrow functions<commit_after>require('whatwg-fetch');

var $ = require('jquery');
var _ = require('underscore');
var ConfigModel = require('./data/config-model');
var LayerStyleCollection = require('./embed/style-collection');
var MetricsTracker = require('./components/metrics/metrics-tracker');
var deepInsights = require('../deep-insights/index');
var EmbedIntegrations = require('./embed/embed-integrations');
var URLStateHelper = require('../deep-insights/api/url-helper.js');
var EmbedView = require('./embed/embed-view');

var vizJSON = window.vizJSON;
var authTokens = window.authTokens;
var mapzenApiKey = window.mapzenApiKey;
var stateJSON = window.stateJSON;
var layersData = window.layersData;
var baseURL = window.baseURL;
var anyLayerWithLegends = vizJSON.layers.some(function (layer) {
  return layer.legends && layer.legends.length;
});

var configModel = new ConfigModel({ base_url: baseURL });

var layerStyleCollection = new LayerStyleCollection();
layerStyleCollection.resetByLayersData(layersData);

var embedView = new EmbedView({
  title: vizJSON.title,
  showMenu: vizJSON.options.dashboard_menu,
  showLegends: vizJSON.options.legends && anyLayerWithLegends
});

MetricsTracker.init({
  visId: vizJSON.id,
  configModel: configModel
});

$('#dashboard').prepend(embedView.render().$el);

var cartoLogoOption = _.findWhere(vizJSON.overlays, {type: 'logo'});
var dashboardOpts = {
  no_cdn: false,
  cartodb_logo: cartoLogoOption !== undefined,
  renderMenu: vizJSON.options.dashboard_menu,
  share_urls: true,
  authToken: authTokens,
  layerSelectorEnabled: true,
  mapzenApiKey: mapzenApiKey
};

var stateFromURL = URLStateHelper.getStateFromCurrentURL();
if (stateFromURL && !_.isEmpty(stateFromURL)) {
  _.extend(dashboardOpts, {
    state: stateFromURL
  });
} else if (stateJSON && stateJSON !== '{}') {
  _.extend(dashboardOpts, {
    state: stateJSON
  });
}

deepInsights.createDashboard('.js-embed-map', vizJSON, dashboardOpts, function (error, dashboard) {
  if (error) {
    console.error('Dashboard has some errors:', error);
  }

  var map = dashboard.getMap().map;
  var scrollwheel = vizJSON.options.scrollwheel;
  var method = scrollwheel ? 'enableScrollWheel' : 'disableScrollWheel';
  map && map[method] && map[method]();

  var embedIntegrations = new EmbedIntegrations({
    deepInsightsDashboard: dashboard,
    layerStyleCollection: layerStyleCollection
  });

  window.embedIntegrations = embedIntegrations;
});

window.layerStyleCollection = layerStyleCollection;
<|endoftext|>


<commit_before>var express = require('express');
var DataStore = require('./regard-data-store.js');

var router = express.Router();
var dataStore = new DataStore('regard', 'website');

router.get('/userevents/:id', function (req, res, next) {
  var id = req.params.id;

  dataStore.getEventsForUser(id).then(function (events) {
    res.json({
      userevents: [{
        _id: id,
        events: JSON.parse(events)
      }]
    });
  });
});

router.post('/userevents/:id/delete-data', function (req, res, next) {
  var id = req.params.id;

  dataStore.deleteData(id).then(function () {
    res.send(200);
  }, next);
});

module.exports = router;<commit_msg>Add error handling to user events<commit_after>var express = require('express');
var DataStore = require('./regard-data-store.js');

var router = express.Router();
var dataStore = new DataStore('regard', 'website');

router.get('/userevents/:id', function (req, res, next) {
  var id = req.params.id;

  dataStore.getEventsForUser(id).then(function (events) {
    res.json({
      userevents: [{
        _id: id,
        events: JSON.parse(events)
      }]
    });
  }, next);
});

router.post('/userevents/:id/delete-data', function (req, res, next) {
  var id = req.params.id;

  dataStore.deleteData(id).then(function () {
    res.send(200);
  }, next);
});

module.exports = router;<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'

import TriMetLegIcon from '@opentripplanner/icons/lib/trimet-leg-icon'

// TODO: add the custom icons hook found in print-layout.

export default class ItinerarySummary extends Component {
  static propTypes = {
    itinerary: PropTypes.object
  }

  render () {
    const { itinerary } = this.props

    const blocks = []
    itinerary.legs.forEach((leg, i) => {
      // Skip mid-itinerary walk transfer legs
      if (
        i > 0 &&
        i < itinerary.legs.length - 1 &&
        !leg.transitLeg &&
        itinerary.legs[i - 1].transitLeg &&
        itinerary.legs[i + 1].transitLeg) {
        return null
      }

      // Add the mode icon
      blocks.push(

          <TriMetLegIcon leg={leg} />

      )

      // If a transit leg, add the name (preferably short; long if needed)
      if (leg.transitLeg) {
        blocks.push(

              {leg.routeShortName || leg.routeLongName}

        )
      }

      // If not the last leg, add a '►'
      if (i < itinerary.legs.length - 1) {
        blocks.push(

►

        )
      }
    })

    return
{blocks}

  }
}
<commit_msg>style(Organize imports per PR comments.):<commit_after>import TriMetLegIcon from '@opentripplanner/icons/lib/trimet-leg-icon'
import PropTypes from 'prop-types'
import React, { Component } from 'react'

// TODO: add the custom icons hook found in print-layout.

export default class ItinerarySummary extends Component {
  static propTypes = {
    itinerary: PropTypes.object
  }

  render () {
    const { itinerary } = this.props

    const blocks = []
    itinerary.legs.forEach((leg, i) => {
      // Skip mid-itinerary walk transfer legs
      if (
        i > 0 &&
        i < itinerary.legs.length - 1 &&
        !leg.transitLeg &&
        itinerary.legs[i - 1].transitLeg &&
        itinerary.legs[i + 1].transitLeg) {
        return null
      }

      // Add the mode icon
      blocks.push(

          <TriMetLegIcon leg={leg} />

      )

      // If a transit leg, add the name (preferably short; long if needed)
      if (leg.transitLeg) {
        blocks.push(

              {leg.routeShortName || leg.routeLongName}

        )
      }

      // If not the last leg, add a '►'
      if (i < itinerary.legs.length - 1) {
        blocks.push(

►

        )
      }
    })

    return
{blocks}

  }
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { Autobind } from 'es-decorators';
import debounce from 'lodash/debounce';
import isEqual from 'lodash/isEqual';
import MediaQuery from 'react-responsive';
import 'isomorphic-fetch';
import ReactDOM from 'react-dom';
import DropdownTreeSelect from 'react-dropdown-tree-select';

// Redux
import withRedux from 'next-redux-wrapper';
import { initStore } from 'store';
import {
  toggleLayerGroupVisibility,
  toggleLayerGroup,
  setLayerGroupsOrder,
  setLayerGroupActiveLayer,
  setLayerGroups,
  getDatasets,
  setDatasetsPage,
  setDatasetsSearchFilter,
  setDatasetsTopicsFilter,
  setDatasetsGeographiesFilter,
  setDatasetsDataTypeFilter,
  setDatasetsFilteredByConcepts
} from 'redactions/explore';
import { redirectTo } from 'redactions/common';
import { toggleModal, setModalOptions } from 'redactions/modal';

// Selectors
import getpaginatedDatasets from 'selectors/explore/datasetsPaginatedExplore';
import getFilteredDatasets from 'selectors/explore/filterDatasets';
import getLayerGroups from 'selectors/explore/layersExplore';

// Components
import Sidebar from 'components/app/layout/Sidebar';
import DatasetListHeader from 'components/app/explore/DatasetListHeader';
import DatasetList from 'components/app/explore/DatasetList';
import Paginator from 'components/ui/Paginator';
import Map from 'components/vis/Map';
import ShareModalExplore from 'components/modal/ShareModalExplore';
import Legend from 'components/ui/Legend';
import Spinner from 'components/ui/Spinner';
import Icon from 'components/ui/Icon';
import SearchInput from 'components/ui/SearchInput';

// Layout
import Page from 'components/app/layout/Page';
import Layout from 'components/app/layout/Layout';

// Utils
import LayerManager from 'utils/layers/LayerManager';

// Services
import DatasetService from 'services/DatasetService';

const mapConfig = {
  zoom: 3,
  latLng: {
    lat: 0,
    lng: 0
  }
};

class Explore extends Page {
  constructor(props) {
    super(props);

    this.state = {
      topicsTree: null,
      geographiesTree: null,
      dataTypesTree: null
    };

    // Services
    this.datasetService = new DatasetService(null, { apiURL: process.env.WRI_API_URL });

    // BINDINGS
    this.handleFilterDatasetsSearch = debounce(this.handleFilterDatasetsSearch.bind(this), 500);
  }

  componentWillMount() {
    const query = this.props.url.query;
    if (query.page) {
      this.props.setDatasetsPage(+query.page);
    }

    if (query.layers) {
      try {
        const layerGroups = JSON.parse(decodeURIComponent(query.layers));
        this.props.setLayerGroups(layerGroups);
      } catch (e) {
        this.props.setLayerGroups([]);
      }
    }

    if (query.search) {
      this.props.setDatasetsSearchFilter({ value: query.search, key: 'name' });
    }

    if (query.topics) {
      this.props.setDatasetsTopicsFilter(JSON.parse(query.topics));
    }

    if (query.geographies) {
      this.props.setDatasetsGeographiesFilter(JSON.parse(query.geographies));
    }

    if (query.dataType) {
      this.props.setDatasetsDataTypeFilter(JSON.parse(query.dataType));
    }

    this.props.getDatasets();
  }

  componentDidMount() {
    this.loadKnowledgeGraph();
  }

  componentWillReceiveProps(nextProps) {
    const oldFilters = this.props.explore.filters;
    const { topics, geographies, dataType } = oldFilters;
    const newFilters = nextProps.explore.filters;

    const conceptsUpdated = topics !== newFilters.topics ||
      geographies !== newFilters.geographies ||
      dataType !== newFilters.dataType;

    const newFiltersHaveData = (newFilters.topics && newFilters.topics.length > 0) ||
      (newFilters.dataType && newFilters.dataType.length > 0) ||
      (newFilters.geographies && newFilters.geographies.length > 0);

    if (conceptsUpdated && newFiltersHaveData) {
      this.datasetService.searchDatasetsByConcepts(
        newFilters.topics, newFilters.geographies, newFilters.dataType)
        .then((datasetList) => {
          this.props.setDatasetsFilteredByConcepts(datasetList);
        });
    } else if (conceptsUpdated && !newFiltersHaveData) {
      this.props.setDatasetsFilteredByConcepts(null);
    }

    // this.setState({
    //   vocabularies: nextProps.explore.vocabularies.list
    // });
  }

  shouldComponentUpdate(nextProps, nextState) {
    return !isEqual(nextProps.explore, this.props.explore)
      || !isEqual(nextState, this.state);
  }

  loadKnowledgeGraph() {
    const query = this.props.url.query;
    const { topics, dataType, geographies } = query;

    // Topics selector
    fetch(new Request('/static/data/TopicsTreeLite.json'))
      .then(response => response.json())
      .then((response) => {
        const data = response;
        this.setState({ topicsTree: data });
        const element = document.getElementsByClassName('topics-selector')[0];

        const onChange = (currentNode, selectedNodes) => {
          const topicsVal = selectedNodes.map(val => val.value);
          this.props.setDatasetsTopicsFilter(topicsVal);
        };

        if (topics) {
          data.forEach(child => this.selectElementsFromTree(child, topics));
        }

        ReactDOM.render(
          <DropdownTreeSelect
            placeholderText="Topics"
            data={data}
            onChange={onChange}
          />,
          element);
      });

    // Data types selector
    fetch(new Request('/static/data/DataTypesTreeLite.json'))
      .then(response => response.json())
      .then((response) => {
        const data = response;
        this.setState({ dataTypesTree: data });
        const element = document.getElementsByClassName('data-types-selector')[0];

        const onChange = (currentNode, selectedNodes) => {
          const dataTypesVal = selectedNodes.map(val => val.value);
          this.props.setDatasetsDataTypeFilter(dataTypesVal);
        };

        if (dataType) {
          console.log('dataType', dataType);
          data.forEach(child => this.selectElementsFromTree(child, dataType));
        }

        ReactDOM.render(
          <DropdownTreeSelect
            data={response}
            placeholderText="Data types"
            onChange={onChange}
          />,
          element);
      });

    // Data types selector
    fetch(new Request('/static/data/GeographiesTreeLite.json'))
      .then(response => response.json())
      .then((response) => {
        const data = response;
        this.setState({ geographiesTree: data });
        const element = document.getElementsByClassName('geographies-selector')[0];

        const onChange = (currentNode, selectedNodes) => {
          const geographiesVal = selectedNodes.map(val => val.value);
          this.props.setDatasetsGeographiesFilter(geographiesVal);
        };

        if (dataType) {
          data.forEach(child => this.selectElementsFromTree(child, geographies));
        }

        ReactDOM.render(
          <DropdownTreeSelect
            data={response}
            placeholderText="Geographies"
            onChange={onChange}
          />,
          element);
      });
  }

  selectElementsFromTree(tree, elements) {
    if (elements.includes(tree.value)) {
      tree.checked = true;
    }
    if (tree.children) {
      tree.children.forEach(val => this.selectElementsFromTree(val, elements));
    }
  }

  @Autobind
  handleRedirect(item) {
    if (item && item.value) {
      this.props.redirectTo(`explore/${item.value}`);
    }
  }

  handleFilterDatasetsSearch(value) {
    const filter = { value: value || '', key: 'name' };
    this.props.setDatasetsSearchFilter(filter);

    // We move the user to the first page
    this.props.setDatasetsPage(1);
  }

  handleShareModal() {
    const options = {
      children: ShareModalExplore,
      childrenProps: {
        url: window.location.href,
        layerGroups: this.props.rawLayerGroups,
        toggleModal: this.props.toggleModal
      }
    };
    this.props.toggleModal(true);
    this.props.setModalOptions(options);
  }

  /**
   * Event handler executed when the user toggles the visibility
   * of a layer group in the legend
   * @param {LayerGroup} layerGroup
   */
  @Autobind
  onToggleLayerGroupVisibility(layerGroup) {
    this.props.toggleLayerGroupVisibility(layerGroup.dataset, !layerGroup.visible);
  }

  /**
   * Event handler executed when the user removes a layer
   * group from the map
   * @param {LayerGroup} layerGroup
   */
  @Autobind
  onRemoveLayerGroup(layerGroup) {
    this.props.removeLayerGroup(layerGroup.dataset);
  }

  /**
   * Event handler executed when the user re-orders the
   * layer groups
   * @param {string[]} datasets - List of datasets IDs
   */
  @Autobind
  onSetLayerGroupsOrder(datasets) {
    this.props.setLayerGroupsOrder(datasets);
  }

  /**
   * Event handler executed when the user change the active
   * layer of a layer group
   * @param {string} dataset - Dataset ID
   * @param {string} layer - Layer ID
   */
  @Autobind
  onSetLayerGroupActiveLayer(dataset, layer) {
    this.props.setLayerGroupActiveLayer(dataset, layer);
  }

  /**
   * Return the current value of the vocabulary filter
   * @returns {string}
   */
  getCurrentVocabularyFilter() {
    const filters = this.props.explore.filters;
    if (!filters.length) return null;

    const filter = filters.find(f => f.key === 'vocabulary');

    return filter && filter.value;
  }

  /**
   * Return the current search made on the name of the
   * datasets
   * @returns {string}
   */
  getCurrentNameFilter() {
    const filters = this.props.explore.filters;
    if (!filters.length) return null;

    const filter = filters.find(f => f.key === 'name');

    return filter && filter.value;
  }

  render() {
    const { explore, paginatedDatasets } = this.props;
    const { search } = explore.filters;

    return (
      <Layout
        title="Explore"
        description="Explore description"
        url={this.props.url}
        user={this.props.user}
      >

            <Sidebar>

Explore

                <SearchInput
                  onSearch={this.handleFilterDatasetsSearch}
                  input={{
                    value: search && search.value,
                    placeholder: 'Search dataset'
                  }}
                />

              <DatasetListHeader
                list={explore.datasets.list}
                mode={explore.datasets.mode}
              />
              <Spinner
                isLoading={explore.datasets.loading}
                className="-light"
              />

                  <DatasetList
                    list={paginatedDatasets}
                    mode={explore.datasets.mode}
                    showActions
                  />

              <Paginator
                options={{
                  page: explore.datasets.page,
                  limit: explore.datasets.limit,
                  size: explore.datasets.list.length
                }}
                onChange={(page) => {
                  this.props.setDatasetsPage(page);
                  // Scroll to the top of the list
                  document.getElementsByClassName('sidebar-content')[0].scrollTop = 0;
                }}
              />
            </Sidebar>
            <MediaQuery minDeviceWidth={720} values={{ deviceWidth: 720 }}>

                <Map
                  LayerManager={LayerManager}
                  mapConfig={mapConfig}
                  layerGroups={this.props.layerGroups}
                />

                <button className="share-button" onClick={() => this.handleShareModal()}>
                  <Icon name="icon-share" className="-small" />
                </button>

                {this.props.layerGroups && this.props.layerGroups.length &&
                  <Legend
                    layerGroups={this.props.layerGroups}
                    className={{ color: '-dark' }}
                    toggleLayerGroupVisibility={this.onToggleLayerGroupVisibility}
                    setLayerGroupsOrder={this.onSetLayerGroupsOrder}
                    removeLayerGroup={this.onRemoveLayerGroup}
                    setLayerGroupActiveLayer={this.onSetLayerGroupActiveLayer}
                  />
                }

            </MediaQuery>

      </Layout>
    );
  }
}

Explore.propTypes = {
  // ROUTER
  url: PropTypes.object,

  // STORE
  explore: PropTypes.object,
  paginatedDatasets: PropTypes.array,
  layerGroups: PropTypes.array,
  toggledDataset: PropTypes.string,

  // ACTIONS

  getDatasets: PropTypes.func,
  setDatasetsPage: PropTypes.func,
  redirectTo: PropTypes.func,
  setDatasetsFilters: PropTypes.func,
  toggleModal: PropTypes.func,
  setModalOptions: PropTypes.func,

  // Toggle the visibility of a layer group based on the layer passed as argument
  toggleLayerGroupVisibility: PropTypes.func.isRequired,
  // Remove the layer group
  removeLayerGroup: PropTypes.func.isRequired,
  // Set the active layer of a layer group
  setLayerGroupActiveLayer: PropTypes.func.isRequired,
  // Set the layer groups
  setLayerGroups: PropTypes.func.isRequired
};

const mapStateToProps = (state) => {
  const filters = state.explore.filters;
  const datasets = (filters.search || filters.topcis || filters.geographies || filters.dataType)
    ? Object.assign({}, state.explore.datasets, { list: getFilteredDatasets(state) })
    : state.explore.datasets;

  const explore = Object.assign({}, state.explore, { datasets });

  return {
    explore,
    paginatedDatasets: getpaginatedDatasets(explore),
    allDatasets: state.explore.datasets.list,
    layerGroups: getLayerGroups(state),
    rawLayerGroups: state.explore.layers
  };
};

const mapDispatchToProps = dispatch => ({
  getDatasets: () => { dispatch(getDatasets()); },
  setDatasetsSearchFilter: search => dispatch(setDatasetsSearchFilter(search)),
  setDatasetsTopicsFilter: topics => dispatch(setDatasetsTopicsFilter(topics)),
  setDatasetsDataTypeFilter: dataType => dispatch(setDatasetsDataTypeFilter(dataType)),
  setDatasetsGeographiesFilter: geographies => dispatch(setDatasetsGeographiesFilter(geographies)),
  setDatasetsFilteredByConcepts: datasetList =>
    dispatch(setDatasetsFilteredByConcepts(datasetList)),
  redirectTo: (url) => { dispatch(redirectTo(url)); },
  toggleModal: (open, options) => dispatch(toggleModal(open, options)),
  setModalOptions: (options) => { dispatch(setModalOptions(options)); },
  setDatasetsPage: page => dispatch(setDatasetsPage(page)),
  toggleLayerGroupVisibility: (dataset, visible) => {
    dispatch(toggleLayerGroupVisibility(dataset, visible));
  },
  removeLayerGroup: dataset => dispatch(toggleLayerGroup(dataset, false)),
  setLayerGroupsOrder: datasets => dispatch(setLayerGroupsOrder(datasets)),
  setLayerGroupActiveLayer: (dataset, layer) => dispatch(setLayerGroupActiveLayer(dataset, layer)),
  setLayerGroups: layerGroups => dispatch(setLayerGroups(layerGroups))
});

export default withRedux(initStore, mapStateToProps, mapDispatchToProps)(Explore);
<commit_msg>remove log code<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { Autobind } from 'es-decorators';
import debounce from 'lodash/debounce';
import isEqual from 'lodash/isEqual';
import MediaQuery from 'react-responsive';
import 'isomorphic-fetch';
import ReactDOM from 'react-dom';
import DropdownTreeSelect from 'react-dropdown-tree-select';

// Redux
import withRedux from 'next-redux-wrapper';
import { initStore } from 'store';
import {
  toggleLayerGroupVisibility,
  toggleLayerGroup,
  setLayerGroupsOrder,
  setLayerGroupActiveLayer,
  setLayerGroups,
  getDatasets,
  setDatasetsPage,
  setDatasetsSearchFilter,
  setDatasetsTopicsFilter,
  setDatasetsGeographiesFilter,
  setDatasetsDataTypeFilter,
  setDatasetsFilteredByConcepts
} from 'redactions/explore';
import { redirectTo } from 'redactions/common';
import { toggleModal, setModalOptions } from 'redactions/modal';

// Selectors
import getpaginatedDatasets from 'selectors/explore/datasetsPaginatedExplore';
import getFilteredDatasets from 'selectors/explore/filterDatasets';
import getLayerGroups from 'selectors/explore/layersExplore';

// Components
import Sidebar from 'components/app/layout/Sidebar';
import DatasetListHeader from 'components/app/explore/DatasetListHeader';
import DatasetList from 'components/app/explore/DatasetList';
import Paginator from 'components/ui/Paginator';
import Map from 'components/vis/Map';
import ShareModalExplore from 'components/modal/ShareModalExplore';
import Legend from 'components/ui/Legend';
import Spinner from 'components/ui/Spinner';
import Icon from 'components/ui/Icon';
import SearchInput from 'components/ui/SearchInput';

// Layout
import Page from 'components/app/layout/Page';
import Layout from 'components/app/layout/Layout';

// Utils
import LayerManager from 'utils/layers/LayerManager';

// Services
import DatasetService from 'services/DatasetService';

const mapConfig = {
  zoom: 3,
  latLng: {
    lat: 0,
    lng: 0
  }
};

class Explore extends Page {
  constructor(props) {
    super(props);

    this.state = {
      topicsTree: null,
      geographiesTree: null,
      dataTypesTree: null
    };

    // Services
    this.datasetService = new DatasetService(null, { apiURL: process.env.WRI_API_URL });

    // BINDINGS
    this.handleFilterDatasetsSearch = debounce(this.handleFilterDatasetsSearch.bind(this), 500);
  }

  componentWillMount() {
    const query = this.props.url.query;
    if (query.page) {
      this.props.setDatasetsPage(+query.page);
    }

    if (query.layers) {
      try {
        const layerGroups = JSON.parse(decodeURIComponent(query.layers));
        this.props.setLayerGroups(layerGroups);
      } catch (e) {
        this.props.setLayerGroups([]);
      }
    }

    if (query.search) {
      this.props.setDatasetsSearchFilter({ value: query.search, key: 'name' });
    }

    if (query.topics) {
      this.props.setDatasetsTopicsFilter(JSON.parse(query.topics));
    }

    if (query.geographies) {
      this.props.setDatasetsGeographiesFilter(JSON.parse(query.geographies));
    }

    if (query.dataType) {
      this.props.setDatasetsDataTypeFilter(JSON.parse(query.dataType));
    }

    this.props.getDatasets();
  }

  componentDidMount() {
    this.loadKnowledgeGraph();
  }

  componentWillReceiveProps(nextProps) {
    const oldFilters = this.props.explore.filters;
    const { topics, geographies, dataType } = oldFilters;
    const newFilters = nextProps.explore.filters;

    const conceptsUpdated = topics !== newFilters.topics ||
      geographies !== newFilters.geographies ||
      dataType !== newFilters.dataType;

    const newFiltersHaveData = (newFilters.topics && newFilters.topics.length > 0) ||
      (newFilters.dataType && newFilters.dataType.length > 0) ||
      (newFilters.geographies && newFilters.geographies.length > 0);

    if (conceptsUpdated && newFiltersHaveData) {
      this.datasetService.searchDatasetsByConcepts(
        newFilters.topics, newFilters.geographies, newFilters.dataType)
        .then((datasetList) => {
          this.props.setDatasetsFilteredByConcepts(datasetList);
        });
    } else if (conceptsUpdated && !newFiltersHaveData) {
      this.props.setDatasetsFilteredByConcepts(null);
    }

    // this.setState({
    //   vocabularies: nextProps.explore.vocabularies.list
    // });
  }

  shouldComponentUpdate(nextProps, nextState) {
    return !isEqual(nextProps.explore, this.props.explore)
      || !isEqual(nextState, this.state);
  }

  loadKnowledgeGraph() {
    const query = this.props.url.query;
    const { topics, dataType, geographies } = query;

    // Topics selector
    fetch(new Request('/static/data/TopicsTreeLite.json'))
      .then(response => response.json())
      .then((response) => {
        const data = response;
        this.setState({ topicsTree: data });
        const element = document.getElementsByClassName('topics-selector')[0];

        const onChange = (currentNode, selectedNodes) => {
          const topicsVal = selectedNodes.map(val => val.value);
          this.props.setDatasetsTopicsFilter(topicsVal);
        };

        if (topics) {
          data.forEach(child => this.selectElementsFromTree(child, topics));
        }

        ReactDOM.render(
          <DropdownTreeSelect
            placeholderText="Topics"
            data={data}
            onChange={onChange}
          />,
          element);
      });

    // Data types selector
    fetch(new Request('/static/data/DataTypesTreeLite.json'))
      .then(response => response.json())
      .then((response) => {
        const data = response;
        this.setState({ dataTypesTree: data });
        const element = document.getElementsByClassName('data-types-selector')[0];

        const onChange = (currentNode, selectedNodes) => {
          const dataTypesVal = selectedNodes.map(val => val.value);
          this.props.setDatasetsDataTypeFilter(dataTypesVal);
        };

        if (dataType) {
          data.forEach(child => this.selectElementsFromTree(child, dataType));
        }

        ReactDOM.render(
          <DropdownTreeSelect
            data={response}
            placeholderText="Data types"
            onChange={onChange}
          />,
          element);
      });

    // Data types selector
    fetch(new Request('/static/data/GeographiesTreeLite.json'))
      .then(response => response.json())
      .then((response) => {
        const data = response;
        this.setState({ geographiesTree: data });
        const element = document.getElementsByClassName('geographies-selector')[0];

        const onChange = (currentNode, selectedNodes) => {
          const geographiesVal = selectedNodes.map(val => val.value);
          this.props.setDatasetsGeographiesFilter(geographiesVal);
        };

        if (dataType) {
          data.forEach(child => this.selectElementsFromTree(child, geographies));
        }

        ReactDOM.render(
          <DropdownTreeSelect
            data={response}
            placeholderText="Geographies"
            onChange={onChange}
          />,
          element);
      });
  }

  selectElementsFromTree(tree, elements) {
    if (elements.includes(tree.value)) {
      tree.checked = true;
    }
    if (tree.children) {
      tree.children.forEach(val => this.selectElementsFromTree(val, elements));
    }
  }

  @Autobind
  handleRedirect(item) {
    if (item && item.value) {
      this.props.redirectTo(`explore/${item.value}`);
    }
  }

  handleFilterDatasetsSearch(value) {
    const filter = { value: value || '', key: 'name' };
    this.props.setDatasetsSearchFilter(filter);

    // We move the user to the first page
    this.props.setDatasetsPage(1);
  }

  handleShareModal() {
    const options = {
      children: ShareModalExplore,
      childrenProps: {
        url: window.location.href,
        layerGroups: this.props.rawLayerGroups,
        toggleModal: this.props.toggleModal
      }
    };
    this.props.toggleModal(true);
    this.props.setModalOptions(options);
  }

  /**
   * Event handler executed when the user toggles the visibility
   * of a layer group in the legend
   * @param {LayerGroup} layerGroup
   */
  @Autobind
  onToggleLayerGroupVisibility(layerGroup) {
    this.props.toggleLayerGroupVisibility(layerGroup.dataset, !layerGroup.visible);
  }

  /**
   * Event handler executed when the user removes a layer
   * group from the map
   * @param {LayerGroup} layerGroup
   */
  @Autobind
  onRemoveLayerGroup(layerGroup) {
    this.props.removeLayerGroup(layerGroup.dataset);
  }

  /**
   * Event handler executed when the user re-orders the
   * layer groups
   * @param {string[]} datasets - List of datasets IDs
   */
  @Autobind
  onSetLayerGroupsOrder(datasets) {
    this.props.setLayerGroupsOrder(datasets);
  }

  /**
   * Event handler executed when the user change the active
   * layer of a layer group
   * @param {string} dataset - Dataset ID
   * @param {string} layer - Layer ID
   */
  @Autobind
  onSetLayerGroupActiveLayer(dataset, layer) {
    this.props.setLayerGroupActiveLayer(dataset, layer);
  }

  /**
   * Return the current value of the vocabulary filter
   * @returns {string}
   */
  getCurrentVocabularyFilter() {
    const filters = this.props.explore.filters;
    if (!filters.length) return null;

    const filter = filters.find(f => f.key === 'vocabulary');

    return filter && filter.value;
  }

  /**
   * Return the current search made on the name of the
   * datasets
   * @returns {string}
   */
  getCurrentNameFilter() {
    const filters = this.props.explore.filters;
    if (!filters.length) return null;

    const filter = filters.find(f => f.key === 'name');

    return filter && filter.value;
  }

  render() {
    const { explore, paginatedDatasets } = this.props;
    const { search } = explore.filters;

    return (
      <Layout
        title="Explore"
        description="Explore description"
        url={this.props.url}
        user={this.props.user}
      >

            <Sidebar>

Explore

                <SearchInput
                  onSearch={this.handleFilterDatasetsSearch}
                  input={{
                    value: search && search.value,
                    placeholder: 'Search dataset'
                  }}
                />

              <DatasetListHeader
                list={explore.datasets.list}
                mode={explore.datasets.mode}
              />
              <Spinner
                isLoading={explore.datasets.loading}
                className="-light"
              />

                  <DatasetList
                    list={paginatedDatasets}
                    mode={explore.datasets.mode}
                    showActions
                  />

              <Paginator
                options={{
                  page: explore.datasets.page,
                  limit: explore.datasets.limit,
                  size: explore.datasets.list.length
                }}
                onChange={(page) => {
                  this.props.setDatasetsPage(page);
                  // Scroll to the top of the list
                  document.getElementsByClassName('sidebar-content')[0].scrollTop = 0;
                }}
              />
            </Sidebar>
            <MediaQuery minDeviceWidth={720} values={{ deviceWidth: 720 }}>

                <Map
                  LayerManager={LayerManager}
                  mapConfig={mapConfig}
                  layerGroups={this.props.layerGroups}
                />

                <button className="share-button" onClick={() => this.handleShareModal()}>
                  <Icon name="icon-share" className="-small" />
                </button>

                {this.props.layerGroups && this.props.layerGroups.length &&
                  <Legend
                    layerGroups={this.props.layerGroups}
                    className={{ color: '-dark' }}
                    toggleLayerGroupVisibility={this.onToggleLayerGroupVisibility}
                    setLayerGroupsOrder={this.onSetLayerGroupsOrder}
                    removeLayerGroup={this.onRemoveLayerGroup}
                    setLayerGroupActiveLayer={this.onSetLayerGroupActiveLayer}
                  />
                }

            </MediaQuery>

      </Layout>
    );
  }
}

Explore.propTypes = {
  // ROUTER
  url: PropTypes.object,

  // STORE
  explore: PropTypes.object,
  paginatedDatasets: PropTypes.array,
  layerGroups: PropTypes.array,
  toggledDataset: PropTypes.string,

  // ACTIONS

  getDatasets: PropTypes.func,
  setDatasetsPage: PropTypes.func,
  redirectTo: PropTypes.func,
  setDatasetsFilters: PropTypes.func,
  toggleModal: PropTypes.func,
  setModalOptions: PropTypes.func,

  // Toggle the visibility of a layer group based on the layer passed as argument
  toggleLayerGroupVisibility: PropTypes.func.isRequired,
  // Remove the layer group
  removeLayerGroup: PropTypes.func.isRequired,
  // Set the active layer of a layer group
  setLayerGroupActiveLayer: PropTypes.func.isRequired,
  // Set the layer groups
  setLayerGroups: PropTypes.func.isRequired
};

const mapStateToProps = (state) => {
  const filters = state.explore.filters;
  const datasets = (filters.search || filters.topcis || filters.geographies || filters.dataType)
    ? Object.assign({}, state.explore.datasets, { list: getFilteredDatasets(state) })
    : state.explore.datasets;

  const explore = Object.assign({}, state.explore, { datasets });

  return {
    explore,
    paginatedDatasets: getpaginatedDatasets(explore),
    allDatasets: state.explore.datasets.list,
    layerGroups: getLayerGroups(state),
    rawLayerGroups: state.explore.layers
  };
};

const mapDispatchToProps = dispatch => ({
  getDatasets: () => { dispatch(getDatasets()); },
  setDatasetsSearchFilter: search => dispatch(setDatasetsSearchFilter(search)),
  setDatasetsTopicsFilter: topics => dispatch(setDatasetsTopicsFilter(topics)),
  setDatasetsDataTypeFilter: dataType => dispatch(setDatasetsDataTypeFilter(dataType)),
  setDatasetsGeographiesFilter: geographies => dispatch(setDatasetsGeographiesFilter(geographies)),
  setDatasetsFilteredByConcepts: datasetList =>
    dispatch(setDatasetsFilteredByConcepts(datasetList)),
  redirectTo: (url) => { dispatch(redirectTo(url)); },
  toggleModal: (open, options) => dispatch(toggleModal(open, options)),
  setModalOptions: (options) => { dispatch(setModalOptions(options)); },
  setDatasetsPage: page => dispatch(setDatasetsPage(page)),
  toggleLayerGroupVisibility: (dataset, visible) => {
    dispatch(toggleLayerGroupVisibility(dataset, visible));
  },
  removeLayerGroup: dataset => dispatch(toggleLayerGroup(dataset, false)),
  setLayerGroupsOrder: datasets => dispatch(setLayerGroupsOrder(datasets)),
  setLayerGroupActiveLayer: (dataset, layer) => dispatch(setLayerGroupActiveLayer(dataset, layer)),
  setLayerGroups: layerGroups => dispatch(setLayerGroups(layerGroups))
});

export default withRedux(initStore, mapStateToProps, mapDispatchToProps)(Explore);
<|endoftext|>


<commit_before>const Issue = require('../../utils').issues.Issue

/**
 * Checks status column in a electroencephalography _channels.tsv file to
 * ensure its values are only * 'good', 'bad', or 'n/a'
 */
const checkStatusCol = function(rows, file, issues) {
  const header = rows[0]
  const statusColumn = header.indexOf('status')
  if (statusColumn !== -1) {
    for (let i = 1; i < rows.length; i++) {
      const line = rows[i]
      const status = line[statusColumn]
      if (status !== 'good' && status !== 'bad' && status != 'n/a') {
        issues.push(
          new Issue({
            file: file,
            evidence: line,
            line: i + 1,
            reason:
              'the status column values should either be good, bad, or n/a',
            code: 125,
          }),
        )
      }
    }
  }
  return
}

export default checkStatusCol
<commit_msg>try adding param values to checkStatusCol dock string.<commit_after>const Issue = require('../../utils').issues.Issue

/**
 * Checks status column in a electroencephalography _channels.tsv file to
 * ensure its values are only * 'good', 'bad', or 'n/a'
 * @param {string[]} rows - Each row of a tsv file to be checked.
 * @param file - File of rows being checked, used for error message if
 *     problem is found.
 * @param {Object[]} issues - Array of issue objects to add to if problem is
 *     found.
 */
const checkStatusCol = function(rows, file, issues) {
  const header = rows[0]
  const statusColumn = header.indexOf('status')
  if (statusColumn !== -1) {
    for (let i = 1; i < rows.length; i++) {
      const line = rows[i]
      const status = line[statusColumn]
      if (status !== 'good' && status !== 'bad' && status != 'n/a') {
        issues.push(
          new Issue({
            file: file,
            evidence: line,
            line: i + 1,
            reason:
              'the status column values should either be good, bad, or n/a',
            code: 125,
          }),
        )
      }
    }
  }
  return
}

export default checkStatusCol
<|endoftext|>


<commit_before>(function () {
  var codes = [
    38, // up
    38, // up
    40, // down
    40, // down
    37, // left
    39, // right
    37, // left
    39, // right
    66, // b
    65  // a
  ];

  kamo.Stream.fromEventHandlerSetter(window, 'onkeyup').map(function (message) {
    return message.keyCode;
  }).scan([], function (messages, message) {
    messages.push(message);
    return messages.slice(-codes.length);
  }).filter(function (message) {
    return JSON.stringify(message) == JSON.stringify(codes);
  }).subscribe(function (message) {
    alert('Conguraturation!');
  });
})();
<commit_msg>Refactor the KonamiCode example JS code by using early added method<commit_after>(function () {
  var codes = [
    38, // up
    38, // up
    40, // down
    40, // down
    37, // left
    39, // right
    37, // left
    39, // right
    66, // b
    65  // a
  ];

  kamo.Stream.fromEventHandlerSetter(window, 'onkeyup').map(function (message) {
    return message.keyCode;
  }).windowWithCount(codes.length).filter(function (message) {
    console.log(message);
    return JSON.stringify(message) == JSON.stringify(codes);
  }).subscribe(function (message) {
    alert('Conguraturation!');
  });
})();
<|endoftext|>


<commit_before>// Apache 2.0 J Chris Anderson 2011
$(document).ready(function() {
  $("#query").val('');

  // The db
  var path = unescape(document.location.pathname).split('/'),
  design = path[3],
  db = $.couch.db(path[1]);

  db.info({
    success: function(data){
      $("#sidebar-placeholder").html($.mustache($("#sidebar-mustache").html(),{
        num: data.doc_count
      }));
    }
  });

  // display nice human readable size
  function bytesToSize(bytes) {
    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    var posttxt = 0;
    if (bytes == 0) return 'n/a';
      while( bytes >= 1024 ) {
        posttxt++;
        bytes = bytes / 1024;
      }
      return bytes.toFixed(2) + " " + sizes[posttxt];
  }

  //search
  function search() {
    if ($("#query").val() == ""){return;}
    var terms = $("#query").val().toLowerCase().split(' '); // simple for the moment
    first_fetch_from_db(terms);
  }

  // fetch the number of ids from the db
  function first_fetch_from_db(terms) {
    db.list(design + "/regexp_check", "search_index_with_name",
            // couchdb's list options
            {
              data: JSON.stringify({"q": terms}),
              keys: terms,
              reduce: false
            },
            // ajaxOptions
            {
              success: function(data) {

                var total_num = data.length;

                // display the number of ids
                var them = $.mustache($("#result-header-mustache").html(), {
                  num: total_num
                });
                $("#result-header").html(them);

                // pagination will start at the beginning of the results
                display_page(1, [], Math.floor(total_num/10),terms);
              }
            }
           );
  };

  // setup and display paginated keys for a page
  // @page is the number of the page we want to display
  // @page_index_arg is an array
  function display_page(page, page_index_arg, num_page, terms){

    // use a clean copy.
    var page_index = page_index_arg.slice();

    // if fetching from the first page, chances are that page_index is
    // empty. If there already is something in page_index[1], we can
    // safely remove it, instead of checking it entirely
    if (page === 1){page_index[1] = ""};

    db.list(design + "/regexp_check", "search_index_with_name",
            {
              data: JSON.stringify({"q": terms}),
              keys: terms,
              reduce: false,
              limit: 11,
              startkey_docid: page_index[page],
            },
            {
              success: function(data) {

                var next_exists = true,
                prev_exists = true;

                if (data.length < 11){ // last page
                  next_exists = false;
                } else if(page_index.indexOf(data[10]) == -1){ // didn't click on "prev"
                  page_index.push(data[10]); // careful ! 11th element is at 10
                }
                var prev_exists = page != 1;

                // display the prev/next footer
                $("#result-footer").html($.mustache($("#result-footer-mustache").html(),{
                  next: (function(){return next_exists == true}),
                  page: page,
                  num_page: num_page,
                  prev: (function(){return prev_exists == true})
                }));

                // bind the clicks
                if (next_exists){
                  $("a[href=#next]").click(function(){
                    display_page(page + 1, page_index, num_page, terms);
                  });
                }
                if (prev_exists){
                  $("a[href=#prev]").click(function(){
                    display_page(page - 1, page_index, num_page, terms)});
                }

                // finally, display the goods
                fetch_and_display(data.slice(0,10), terms);

              }
            }
           );
  }

  // really fetch docs and display them
  function fetch_and_display(ids,terms){
    db.allDocs({
      keys: ids,
      include_docs: true,
      success: function(data){
        var them = $.mustache($("#result-body-mustache").html(), {
          items : data.rows.map(function(r) {

            // highlight the name
            var highlighted_name = terms.reduce(function(accu,cur){
              var re = new RegExp(cur,'ig');
              return accu.replace(re , function(str){
                return '' + str + ''
              });
            },r.doc.name);

            // return the fill-in values
            return {
              "size" : bytesToSize(r.doc.size),
              "name" : highlighted_name,
              "tpb_url" : r.doc.tpb_url,
              "hash" : r.doc.hash
            };
          })
        });
        $("#result-body").html(them);
      }
    });
  }

  $("#search-button").click(search);
  $("#query").keyup(function(event){
    if (event.which == 13) {
      search();
    }
  });

});
<commit_msg>Fetch all the ids; we are not limited to 11<commit_after>// Apache 2.0 J Chris Anderson 2011
$(document).ready(function() {
  $("#query").val('');

  // The db
  var path = unescape(document.location.pathname).split('/'),
  design = path[3],
  db = $.couch.db(path[1]);

  db.info({
    success: function(data){
      $("#sidebar-placeholder").html($.mustache($("#sidebar-mustache").html(),{
        num: data.doc_count
      }));
    }
  });

  // display nice human readable size
  function bytesToSize(bytes) {
    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    var posttxt = 0;
    if (bytes == 0) return 'n/a';
      while( bytes >= 1024 ) {
        posttxt++;
        bytes = bytes / 1024;
      }
      return bytes.toFixed(2) + " " + sizes[posttxt];
  }

  //search
  function search() {
    if ($("#query").val() == ""){return;}
    var terms = $("#query").val().toLowerCase().split(' '); // simple for the moment
    first_fetch_from_db(terms);
  }

  // fetch the number of ids from the db
  function first_fetch_from_db(terms) {
    db.list(design + "/regexp_check", "search_index_with_name",
            // couchdb's list options
            {
              data: JSON.stringify({"q": terms}),
              keys: terms,
              reduce: false
            },
            // ajaxOptions
            {
              success: function(data) {

                var total_num = data.length;

                // display the number of ids
                var them = $.mustache($("#result-header-mustache").html(), {
                  num: total_num
                });
                $("#result-header").html(them);

                // pagination will start at the beginning of the results
                display_page(1, [], Math.floor(total_num/10),terms);
              }
            }
           );
  };

  // setup and display paginated keys for a page
  // @page is the number of the page we want to display
  // @page_index_arg is an array
  function display_page(page, page_index_arg, num_page, terms){

    // use a clean copy.
    var page_index = page_index_arg.slice();

    // if fetching from the first page, chances are that page_index is
    // empty. If there already is something in page_index[1], we can
    // safely remove it, instead of checking it entirely
    if (page === 1){page_index[1] = ""};

    db.list(design + "/regexp_check", "search_index_with_name",
            {
              data: JSON.stringify({"q": terms}),
              keys: terms,
              reduce: false,
              startkey_docid: page_index[page],
            },
            {
              success: function(data) {

                var next_exists = true,
                prev_exists = true;

                if (data.length < 11){ // last page
                  next_exists = false;
                } else if(page_index.indexOf(data[10]) == -1){ // didn't click on "prev"
                  page_index.push(data[10]); // careful ! 11th element is at 10
                }
                var prev_exists = page != 1;

                // display the prev/next footer
                $("#result-footer").html($.mustache($("#result-footer-mustache").html(),{
                  next: (function(){return next_exists == true}),
                  page: page,
                  num_page: num_page,
                  prev: (function(){return prev_exists == true})
                }));

                // bind the clicks
                if (next_exists){
                  $("a[href=#next]").click(function(){
                    display_page(page + 1, page_index, num_page, terms);
                  });
                }
                if (prev_exists){
                  $("a[href=#prev]").click(function(){
                    display_page(page - 1, page_index, num_page, terms)});
                }

                // finally, display the goods
                fetch_and_display(data.slice(0,10), terms);

              }
            }
           );
  }

  // really fetch docs and display them
  function fetch_and_display(ids,terms){
    db.allDocs({
      keys: ids,
      include_docs: true,
      success: function(data){
        var them = $.mustache($("#result-body-mustache").html(), {
          items : data.rows.map(function(r) {

            // highlight the name
            var highlighted_name = terms.reduce(function(accu,cur){
              var re = new RegExp(cur,'ig');
              return accu.replace(re , function(str){
                return '' + str + ''
              });
            },r.doc.name);

            // return the fill-in values
            return {
              "size" : bytesToSize(r.doc.size),
              "name" : highlighted_name,
              "tpb_url" : r.doc.tpb_url,
              "hash" : r.doc.hash
            };
          })
        });
        $("#result-body").html(them);
      }
    });
  }

  $("#search-button").click(search);
  $("#query").keyup(function(event){
    if (event.which == 13) {
      search();
    }
  });

});
<|endoftext|>


<commit_before>// on click get map's coordinates
map.on('click', function(e) {
   $('#myModal').modal('show');
});
<commit_msg>minor<commit_after>$(function() {
	// on click get map's coordinates
	var lat;
	var lng;
	var file;

	map.on('click', function(e) {
	   $('#myModal').modal('show');
	   lat = e.latlng.lat;
	   lng = e.latlng.lng;
	});

	// Set an event listener on the Choose File field.
	$('#fileselect').bind("change", function(e) {
	  var files = e.target.files || e.dataTransfer.files;
	  // Our file var now holds the selected file
	  file = files[0];
	});

	// This function is called when the user clicks on Upload to Parse. It will create the REST API request to upload this image to Parse.
	$('#uploadButton').click(function() {
		if (file == null) {
			alert('NO FILE');
			return;
		}
		else {
			alert('Continues');
		}

		var post = Parse.Object.extend("Post");
		var geoPoint = new Parse.GeoPoint(lat, lng);
		var parseFile = new Parse.File("file", file);
		post.set("caption", document.getElementById("message-text").value);
		post.set("file", parseFile);
		post.set("geoPoint", geoPoint);
		//post.set("userID", currentUserID);

		post.save(null, {
			success: function(POST) {
				// Execute any logic that should take place after the object is saved.
				alert('New object created with objectId: ' + POST.id);
				$('#myModal').modal('hide');
		  	},
		  	error: function(POST, error) {
		   		// Execute any logic that should take place if the save fails.
		    	// error is a Parse.Error with an error code and message.
		    	alert('Failed to create new object, with error code: ' + error.message);
		  	}
		});
	});
});

<|endoftext|>


<commit_before>import { Posts } from '/posts/collection';

Template.postItem.onRendered(function () {
  // Get reference to template instance
  const instance = this;

  // Get Post ID from template instance
  const postId = instance.data.post._id;

  // Get reference to post DOM element
  const postElement = instance.$(`#${postId}`);

  // Render OEmbed content
  postElement.oembed();
});

Template.postItem.helpers({
  userIsPostOwner: function () {
    const instance = Template.instance();

    // Get Post ID from template instance
    const postOwnerId = instance.data.post.userId;
    const loggedUser = Meteor.userId();
    return postOwnerId === loggedUser;
  },
})

Template.postItem.events({
  'click .delete'() {
    if (confirm("Do you really want delete this post?")) {
      const instance = Template.instance();
      const postId = instance.data.post._id;
      Posts.remove(postId);
    }
  },
  'click .edit'(event, template) {
    const post = template.data.post;
    Modal.show("postsForm", {
      postItem: post,
      pageHeader: "Edit post item"
    });
  }
});
<commit_msg>Moved button helpers from all posts to owner's posts<commit_after>import { Posts } from '/posts/collection';

Template.postItem.onRendered(function () {
  // Get reference to template instance
  const instance = this;

  // Get Post ID from template instance
  const postId = instance.data.post._id;

  // Get reference to post DOM element
  const postElement = instance.$(`#${postId}`);

  // Render OEmbed content
  postElement.oembed();
});

Template.myPostItem.onRendered(function () {
  // Get reference to template instance
  const instance = this;

  // Get Post ID from template instance
  const postId = instance.data.post._id;

  // Get reference to post DOM element
  const postElement = instance.$(`#${postId}`);

  // Render OEmbed content
  postElement.oembed();
});

Template.myPostItem.helpers({
  userIsPostOwner: function () {
    const instance = Template.instance();

    // Get Post ID from template instance
    const postOwnerId = instance.data.post.userId;
    const loggedUser = Meteor.userId();
    return postOwnerId === loggedUser;
  },
})

Template.myPostItem.events({
  'click .delete'() {
    if (confirm("Do you really want delete this post?")) {
      const instance = Template.instance();
      const postId = instance.data.post._id;
      Posts.remove(postId);
    }
  },
  'click .edit'(event, template) {
    const post = template.data.post;
    Modal.show("postsForm", {
      postItem: post,
      pageHeader: "Edit post item"
    });
  }
});
<|endoftext|>


<commit_before>require('colors-browserify')
var Hub = require('../../lib')
var http = require('http')
var JSONStream = require('JSONStream')
var hub = new Hub({ //eslint-disable-line
  adapter: {
    inject: require('../../lib/protocol/websocket'),
    id: 'mtv',
    websocket: {
      server: 3031,
      val: 'ws://localhost:3032'
    }
  },
  levelup: 'mtv'
  // datafromjson: false
})

hub.levelready.is(true, function () {
  if (!hub.datafromjson || hub.datafromjson.val !== true) {
    console.log('start loading!'.magenta)
    http.request({
      host:  'scraper.dev.vigour.io', //'scraper-de-staging.dev.vigour.io',
      path: '/new.json',
      port: 80,
      method: 'get',
      headers: {
        accepts: '*/*'
      }
    }, function (res) {
      res.pipe(JSONStream.parse('mtvData.*.*'))
      .on('data', function (data) {
        console.log('CHUNK!'.magenta)
        // make this atomic wat to heavy
        hub.set(data)
      })
      .on('end', function () {
        hub.setKey('datafromjson', true)
      })
    }).end()
  }
})
<commit_msg>show chunks<commit_after>require('colors-browserify')
var Hub = require('../../lib')
var http = require('http')
var JSONStream = require('JSONStream')
var hub = new Hub({ //eslint-disable-line
  adapter: {
    inject: require('../../lib/protocol/websocket'),
    id: 'mtv',
    websocket: {
      server: 3031,
      val: 'ws://localhost:3032'
    }
  },
  shows: {},
  levelup: 'mtv'
  // datafromjson: false
})

hub.levelready.is(true, function () {
  if (!hub.datafromjson || hub.datafromjson.val !== true) {
    console.log('start loading!'.magenta)
    http.request({
      host: 'scraper.dev.vigour.io',
      path: '/new.json',
      port: 80,
      method: 'get',
      headers: {
        accepts: '*/*'
      }
    }, function (res) {
      res.pipe(JSONStream.parse('mtvData.*.*.shows.*'))
      .on('data', function (data) {
        if (data.id) {
          hub.shows.setKey(data.id , data)
        }
      })
      .on('end', function () {
        hub.setKey('datafromjson', true)
        console.log('LOADED!'.magenta)
      })
    }).end()
  }
})
<|endoftext|>


<commit_before>/**
 * Copyright 2016 Dave Thwaites
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

module.exports = function(RED) {
    "use strict";
    var util = require("util");
    var spawn = require('child_process').spawn;
    var fs = require('fs');

    var gpioCommand = __dirname+'/ener314';

    if (!fs.existsSync("/dev/ttyAMA0")) { // unlikely if not on a Pi
        util.log("Info : Ignoring Raspberry Pi specific node (rpi-ener314).");
        throw "Info : Ignoring Raspberry Pi specific node (rpi-ener314).";
    }

    if (!fs.existsSync("/usr/share/doc/python-rpi.gpio")) {
        util.log("[rpi-ener314] Warning : Can't find RPi.GPIO python library.");
        throw "Warning : Can't find RPi.GPIO python library.";
    }

    if ( !(1 & parseInt ((fs.statSync(gpioCommand).mode & parseInt ("777", 8)).toString (8)[0]) )) {
        util.log("[rpi-ener314] Error : "+gpioCommand+" needs to be executable.");
        throw "Error : ever314.py needs to be executable.";
    }

/*
    function PibrellaIn(n) {
        RED.nodes.createNode(this,n);
        this.buttonState = -1;
        this.pin = pintable[n.pin];
        this.read = n.read || false;
        if (this.read) { this.buttonState = -2; }
        var node = this;
        if (!pinsInUse.hasOwnProperty(this.pin)) {
            pinsInUse[this.pin] = "tri";
        }
        else {
            if ((pinsInUse[this.pin] !== "tri")||(pinsInUse[this.pin] === "pwm")) {
                node.error("GPIO pin "+this.pin+" already set as "+pinTypes[pinsInUse[this.pin]]);
            }
        }

        if (node.pin !== undefined) {
            node.child = spawn(gpioCommand, ["in",node.pin]);
            node.running = true;
            node.status({fill:"green",shape:"dot",text:"OK"});

            node.child.stdout.on('data', function (data) {
                data = data.toString().trim();
                if (data.length > 0) {
                    if (node.buttonState !== -1) {
                        node.send({ topic:"pibrella/"+tablepin[node.pin], payload:Number(data) });
                    }
                    node.buttonState = data;
                    node.status({fill:"green",shape:"dot",text:data});
                    if (RED.settings.verbose) { node.log("out: "+data+" :"); }
                }
            });

            node.child.stderr.on('data', function (data) {
                if (RED.settings.verbose) { node.log("err: "+data+" :"); }
            });

            node.child.on('close', function (code) {
                if (RED.settings.verbose) { node.log("ret: "+code+" :"); }
                node.child = null;
                node.running = false;
                node.status({fill:"red",shape:"circle",text:""});
            });

            node.child.on('error', function (err) {
                if (err.errno === "ENOENT") { node.warn('Command not found'); }
                else if (err.errno === "EACCES") { node.warn('Command not executable'); }
                else { node.log('error: ' + err); }
            });

        }
        else {
            node.error("Invalid GPIO pin: "+node.pin);
        }

        node.on("close", function() {
            if (node.child != null) {
                node.child.stdin.write(" close "+node.pin);
                node.child.kill('SIGKILL');
            }
            node.status({fill:"red",shape:"circle",text:""});
            delete pinsInUse[node.pin];
            if (RED.settings.verbose) { node.log("end"); }
        });
    }
    RED.nodes.registerType("rpi-pibrella in",PibrellaIn);
*/

    function ener002(n) {
        RED.nodes.createNode(this,n);
        this.pimote = RED.nodes.getNode(n.pimote);
        this.socket = n.socket;
        this.set = n.set || false;
        this.state = n.state || 0;
        var node = this;

        if (this.pimote) {
            // Pi-mote node configured! :-)
        } else {
            // No Pi-mote node configured...
        }

        function inputlistener(msg) {
            if (msg.payload === "true") { msg.payload = true; }
            if (msg.payload === "false") { msg.payload = false; }
            var out = msg.payload.toString().trim().toLowerCase();
            if (out == "on" || out == "off") {
                out = "O"+out.substring(1);
                if (RED.settings.verbose) { node.log("inp: "+msg.payload); }
                if (node.child !== null) {
                    node.child.stdin.write(this.socket+" "+out+"\n");
                    node.status({fill:"green", shape:"ring", text:out});
                } else {
                    node.warn("Command not running");
                    node.status({fill:"red", shape:"circle", text:"Not Running"});
                }
            }
            else { node.warn("Invalid input: "+out); }
        }

        if (node.socket !== undefined) {
            node.child = spawn(gpioCommand, []);
            if (node.set) {
                node.child.stdin.write(node.socket+" "+node.state+"\n");
                node.status({fill:"green",shape:"ring",text:node.state});
            } else {
                node.status({fill:"green",shape:"ring",text:"OK"});
            }
            node.running = true;

            node.on("input", inputlistener);

            node.child.stdout.on('data', function (data) {
                if (RED.settings.verbose) { node.log("out: "+data+" :"); }
                if (data.toString().trim() == "Starting background thread...") { node.status({fill:"green",shape:"dot",text:"OK"}); }
            });

            node.child.stderr.on('data', function (data) {
                if (RED.settings.verbose) { node.log("err: "+data+" :"); }
            });

            node.child.on('close', function (code) {
                if (RED.settings.verbose) { node.log("ret: "+code+" :"); }
                node.child = null;
                node.running = false;
                node.status({fill:"red", shape:"ring", text:"Closed"});
            });

            node.child.on('error', function (err) {
                if (err.errno === "ENOENT") { node.warn('Command not found'); }
                else if (err.errno === "EACCES") { node.warn('Command not executable'); }
                else { node.log('error: ' + err); }
            });

        } else {
            node.error("Invalid ENER314 socket: "+node.socket);
        }

        node.on("close", function() {
            if (node.child != null) {
                node.child.stdin.write("exit");
                node.child.kill('SIGKILL');
            }
            node.status({fill:"red", shape:"circle", text:"Closed"});
            if (RED.settings.verbose) { node.log("end"); }
        });

    }
    RED.nodes.registerType("ener002",ener002);

    function pimote(n) {
        RED.nodes.createNode(this,n);
        this.board = n.board;
        this.defaultpins = n.defaultpins || false;
        this.d0 = n.d0 || 0;
        this.d1 = n.d1 || 0;
        this.d2 = n.d2 || 0;
        this.d3 = n.d3 || 0;
        this.modsel = n.modsel || 0;
        this.enable = n.enable || 0;
        var node = this;
        if (RED.settings.verbose) {
            node.log("board type: "+this.board+" :");
            node.log("use default pins: "+this.defaultpins+" :");
            node.log("node name: "+n.name+" :");
        }

/*
        if (node.socket !== undefined) {
            node.child = spawn(gpioCommand, []);
            if (node.set) {
                node.child.stdin.write(node.socket+" "+node.state+"\n");
                node.status({fill:"green",shape:"ring",text:node.state});
            } else {
                node.status({fill:"green",shape:"ring",text:"OK"});
            }
            node.running = true;

            node.on("input", inputlistener);

            node.child.stdout.on('data', function (data) {
                if (RED.settings.verbose) { node.log("out: "+data+" :"); }
                if (data.toString().trim() == "Starting background thread...") { node.status({fill:"green",shape:"dot",text:"OK"}); }
            });

            node.child.stderr.on('data', function (data) {
                if (RED.settings.verbose) { node.log("err: "+data+" :"); }
            });

            node.child.on('close', function (code) {
                if (RED.settings.verbose) { node.log("ret: "+code+" :"); }
                node.child = null;
                node.running = false;
                node.status({fill:"red", shape:"ring", text:"Closed"});
            });

            node.child.on('error', function (err) {
                if (err.errno === "ENOENT") { node.warn('Command not found'); }
                else if (err.errno === "EACCES") { node.warn('Command not executable'); }
                else { node.log('error: ' + err); }
            });

        } else {
            node.error("Invalid ENER314 socket: "+node.socket);
        }

        node.on("close", function() {
            if (node.child != null) {
                node.child.stdin.write("exit");
                node.child.kill('SIGKILL');
            }
            node.status({fill:"red", shape:"circle", text:"Closed"});
            if (RED.settings.verbose) { node.log("end"); }
        });
*/

    }
    RED.nodes.registerType("pimote",pimote);

/*
    RED.httpAdmin.get('/rpi-pibpins/:id',RED.auth.needsPermission('rpi-pibrella.read'),function(req,res) {
        res.json(pinsInUse);
    });
*/
}
<commit_msg>Log Pimote node details on startup of ener002 node<commit_after>/**
 * Copyright 2016 Dave Thwaites
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

module.exports = function(RED) {
    "use strict";
    var util = require("util");
    var spawn = require('child_process').spawn;
    var fs = require('fs');

    var gpioCommand = __dirname+'/ener314';

    if (!fs.existsSync("/dev/ttyAMA0")) { // unlikely if not on a Pi
        util.log("Info : Ignoring Raspberry Pi specific node (rpi-ener314).");
        throw "Info : Ignoring Raspberry Pi specific node (rpi-ener314).";
    }

    if (!fs.existsSync("/usr/share/doc/python-rpi.gpio")) {
        util.log("[rpi-ener314] Warning : Can't find RPi.GPIO python library.");
        throw "Warning : Can't find RPi.GPIO python library.";
    }

    if ( !(1 & parseInt ((fs.statSync(gpioCommand).mode & parseInt ("777", 8)).toString (8)[0]) )) {
        util.log("[rpi-ener314] Error : "+gpioCommand+" needs to be executable.");
        throw "Error : ever314.py needs to be executable.";
    }

/*
    function PibrellaIn(n) {
        RED.nodes.createNode(this,n);
        this.buttonState = -1;
        this.pin = pintable[n.pin];
        this.read = n.read || false;
        if (this.read) { this.buttonState = -2; }
        var node = this;
        if (!pinsInUse.hasOwnProperty(this.pin)) {
            pinsInUse[this.pin] = "tri";
        }
        else {
            if ((pinsInUse[this.pin] !== "tri")||(pinsInUse[this.pin] === "pwm")) {
                node.error("GPIO pin "+this.pin+" already set as "+pinTypes[pinsInUse[this.pin]]);
            }
        }

        if (node.pin !== undefined) {
            node.child = spawn(gpioCommand, ["in",node.pin]);
            node.running = true;
            node.status({fill:"green",shape:"dot",text:"OK"});

            node.child.stdout.on('data', function (data) {
                data = data.toString().trim();
                if (data.length > 0) {
                    if (node.buttonState !== -1) {
                        node.send({ topic:"pibrella/"+tablepin[node.pin], payload:Number(data) });
                    }
                    node.buttonState = data;
                    node.status({fill:"green",shape:"dot",text:data});
                    if (RED.settings.verbose) { node.log("out: "+data+" :"); }
                }
            });

            node.child.stderr.on('data', function (data) {
                if (RED.settings.verbose) { node.log("err: "+data+" :"); }
            });

            node.child.on('close', function (code) {
                if (RED.settings.verbose) { node.log("ret: "+code+" :"); }
                node.child = null;
                node.running = false;
                node.status({fill:"red",shape:"circle",text:""});
            });

            node.child.on('error', function (err) {
                if (err.errno === "ENOENT") { node.warn('Command not found'); }
                else if (err.errno === "EACCES") { node.warn('Command not executable'); }
                else { node.log('error: ' + err); }
            });

        }
        else {
            node.error("Invalid GPIO pin: "+node.pin);
        }

        node.on("close", function() {
            if (node.child != null) {
                node.child.stdin.write(" close "+node.pin);
                node.child.kill('SIGKILL');
            }
            node.status({fill:"red",shape:"circle",text:""});
            delete pinsInUse[node.pin];
            if (RED.settings.verbose) { node.log("end"); }
        });
    }
    RED.nodes.registerType("rpi-pibrella in",PibrellaIn);
*/

    function ener002(n) {
        RED.nodes.createNode(this,n);
        this.pimote = RED.nodes.getNode(n.pimote);
        this.socket = n.socket;
        this.set = n.set || false;
        this.state = n.state || 0;
        var node = this;

        if (this.pimote) {
            // Pi-mote node configured! :-)
            if (RED.settings.verbose) { node.log("Pi-mote node: "+n.pimote); }
            if (RED.settings.verbose) { node.log("Pi-mote board: "+node.pimote.board); }
        } else {
            // No Pi-mote node configured...
            if (RED.settings.verbose) { node.log("No Pi-mote node configured..."); }
        }

        function inputlistener(msg) {
            if (msg.payload === "true") { msg.payload = true; }
            if (msg.payload === "false") { msg.payload = false; }
            var out = msg.payload.toString().trim().toLowerCase();
            if (out == "on" || out == "off") {
                out = "O"+out.substring(1);
                if (RED.settings.verbose) { node.log("inp: "+msg.payload); }
                if (node.child !== null) {
                    node.child.stdin.write(this.socket+" "+out+"\n");
                    node.status({fill:"green", shape:"ring", text:out});
                } else {
                    node.warn("Command not running");
                    node.status({fill:"red", shape:"circle", text:"Not Running"});
                }
            }
            else { node.warn("Invalid input: "+out); }
        }

        if (node.socket !== undefined) {
            node.child = spawn(gpioCommand, []);
            if (node.set) {
                node.child.stdin.write(node.socket+" "+node.state+"\n");
                node.status({fill:"green",shape:"ring",text:node.state});
            } else {
                node.status({fill:"green",shape:"ring",text:"OK"});
            }
            node.running = true;

            node.on("input", inputlistener);

            node.child.stdout.on('data', function (data) {
                if (RED.settings.verbose) { node.log("out: "+data+" :"); }
                if (data.toString().trim() == "Starting background thread...") { node.status({fill:"green",shape:"dot",text:"OK"}); }
            });

            node.child.stderr.on('data', function (data) {
                if (RED.settings.verbose) { node.log("err: "+data+" :"); }
            });

            node.child.on('close', function (code) {
                if (RED.settings.verbose) { node.log("ret: "+code+" :"); }
                node.child = null;
                node.running = false;
                node.status({fill:"red", shape:"ring", text:"Closed"});
            });

            node.child.on('error', function (err) {
                if (err.errno === "ENOENT") { node.warn('Command not found'); }
                else if (err.errno === "EACCES") { node.warn('Command not executable'); }
                else { node.log('error: ' + err); }
            });

        } else {
            node.error("Invalid ENER314 socket: "+node.socket);
        }

        node.on("close", function() {
            if (node.child != null) {
                node.child.stdin.write("exit");
                node.child.kill('SIGKILL');
            }
            node.status({fill:"red", shape:"circle", text:"Closed"});
            if (RED.settings.verbose) { node.log("end"); }
        });

    }
    RED.nodes.registerType("ener002",ener002);

    function pimote(n) {
        RED.nodes.createNode(this,n);
        this.board = n.board;
        this.defaultpins = n.defaultpins || false;
        this.d0 = n.d0 || 0;
        this.d1 = n.d1 || 0;
        this.d2 = n.d2 || 0;
        this.d3 = n.d3 || 0;
        this.modsel = n.modsel || 0;
        this.enable = n.enable || 0;
        var node = this;
        if (RED.settings.verbose) {
            node.log("board type: "+this.board+" :");
            node.log("use default pins: "+this.defaultpins+" :");
            node.log("node name: "+n.name+" :");
        }

/*
        if (node.socket !== undefined) {
            node.child = spawn(gpioCommand, []);
            if (node.set) {
                node.child.stdin.write(node.socket+" "+node.state+"\n");
                node.status({fill:"green",shape:"ring",text:node.state});
            } else {
                node.status({fill:"green",shape:"ring",text:"OK"});
            }
            node.running = true;

            node.on("input", inputlistener);

            node.child.stdout.on('data', function (data) {
                if (RED.settings.verbose) { node.log("out: "+data+" :"); }
                if (data.toString().trim() == "Starting background thread...") { node.status({fill:"green",shape:"dot",text:"OK"}); }
            });

            node.child.stderr.on('data', function (data) {
                if (RED.settings.verbose) { node.log("err: "+data+" :"); }
            });

            node.child.on('close', function (code) {
                if (RED.settings.verbose) { node.log("ret: "+code+" :"); }
                node.child = null;
                node.running = false;
                node.status({fill:"red", shape:"ring", text:"Closed"});
            });

            node.child.on('error', function (err) {
                if (err.errno === "ENOENT") { node.warn('Command not found'); }
                else if (err.errno === "EACCES") { node.warn('Command not executable'); }
                else { node.log('error: ' + err); }
            });

        } else {
            node.error("Invalid ENER314 socket: "+node.socket);
        }

        node.on("close", function() {
            if (node.child != null) {
                node.child.stdin.write("exit");
                node.child.kill('SIGKILL');
            }
            node.status({fill:"red", shape:"circle", text:"Closed"});
            if (RED.settings.verbose) { node.log("end"); }
        });
*/

    }
    RED.nodes.registerType("pimote",pimote);

/*
    RED.httpAdmin.get('/rpi-pibpins/:id',RED.auth.needsPermission('rpi-pibrella.read'),function(req,res) {
        res.json(pinsInUse);
    });
*/
}
<|endoftext|>


<commit_before>'use strict';
const semver = require('semver');
const detectIndent = require('detect-indent');
const parseArgs = require('yargs-parser');

const fix = (ctx, method) => {
	return () => {
		const fixers = {
			esnext: pkg => {
				if (!pkg.xo) {
					pkg.xo = {};
				}

				pkg.xo.esnext = true;
			},
			script: pkg => {
				if (!pkg.scripts) {
					pkg.scripts = {};
				}

				if (pkg.scripts.test && pkg.scripts.test.length !== 0 && pkg.scripts.test.indexOf('exit 1') === -1) {
					pkg.scripts.test = `xo && ${pkg.scripts.test}`;
				} else {
					pkg.scripts.test = `xo`;
				}
			},
			clioptions: pkg => {
				const regex = /\bxo\b([^&]*)/;

				const command = pkg.scripts.test.match(regex)[1];
				const args = parseArgs(command.trim());

				delete args._;

				pkg.xo = Object.assign({}, pkg.xo, args);
				pkg.scripts.test = pkg.scripts.test.replace(regex, 'xo ').trim();
			}
		};

		return ctx.fs.readFile('package.json', false)
			.then(pkg => {
				// Detect formatting options
				const indentation = detectIndent(pkg).indent;
				const lastchar = pkg.split('\n').pop().trim().length === 0 ? '\n' : '';

				pkg = JSON.parse(pkg);

				fixers[method](pkg);

				const contents = JSON.stringify(pkg, undefined, indentation);
				return ctx.fs.writeFile('package.json', `${contents}${lastchar}`, 'utf8');
			});
	};
};

module.exports = ctx => {
	const requiredVersion = ctx.options[0];
	const file = ctx.fs.resolve('package.json');

	return ctx.fs.readFile('package.json').then(pkg => {
		const installedVersion = pkg.devDependencies && pkg.devDependencies.xo;

		if (!installedVersion) {
			return {
				message: 'XO is not installed as devDependency.',
				file
			};
		}

		const errors = [];

		if (pkg.engines && pkg.engines.node && !semver.satisfies('0.0.10', pkg.engines.node) && !semver.satisfies('0.0.12', pkg.engines.node)) {
			if (!pkg.xo || pkg.xo.esnext !== true) {
				errors.push({
					message: 'Enforce ES2015+ rules in XO with the `esnext` option.',
					fix: fix(ctx, 'esnext'),
					file
				});
			}
		}

		if (requiredVersion) {
			if (requiredVersion === '*' && installedVersion !== '*') {
				errors.push({
					message: `Expected unicorn version '*' but found '${installedVersion}'.`,
					file
				});
			} else if (requiredVersion !== '*' && !semver.gte(installedVersion, requiredVersion)) {
				errors.push({
					message: `Expected version '${requiredVersion}' but found '${installedVersion}'.`,
					file
				});
			}
		}

		if (!pkg.scripts || !pkg.scripts.test || !/\bxo\b/.test(pkg.scripts.test)) {
			errors.push({
				message: 'XO is not used in the test script.',
				fix: fix(ctx, 'script'),
				file
			});
		}

		if (pkg.scripts && pkg.scripts.test && /\bxo\b[^&]*[\-]{2}/.test(pkg.scripts.test)) {
			errors.push({
				message: 'Specify XO config in `package.json` instead of passing it through via the CLI.',
				fix: fix(ctx, 'clioptions'),
				file
			});
		}

		return errors;
	});
};
<commit_msg>fix `xo/esnext` rule - fixes #37<commit_after>'use strict';
const semver = require('semver');
const detectIndent = require('detect-indent');
const parseArgs = require('yargs-parser');

const fix = (ctx, method) => {
	return () => {
		const fixers = {
			esnext: pkg => {
				if (!pkg.xo) {
					pkg.xo = {};
				}

				pkg.xo.esnext = true;
			},
			script: pkg => {
				if (!pkg.scripts) {
					pkg.scripts = {};
				}

				if (pkg.scripts.test && pkg.scripts.test.length !== 0 && pkg.scripts.test.indexOf('exit 1') === -1) {
					pkg.scripts.test = `xo && ${pkg.scripts.test}`;
				} else {
					pkg.scripts.test = `xo`;
				}
			},
			clioptions: pkg => {
				const regex = /\bxo\b([^&]*)/;

				const command = pkg.scripts.test.match(regex)[1];
				const args = parseArgs(command.trim());

				delete args._;

				pkg.xo = Object.assign({}, pkg.xo, args);
				pkg.scripts.test = pkg.scripts.test.replace(regex, 'xo ').trim();
			}
		};

		return ctx.fs.readFile('package.json', false)
			.then(pkg => {
				// Detect formatting options
				const indentation = detectIndent(pkg).indent;
				const lastchar = pkg.split('\n').pop().trim().length === 0 ? '\n' : '';

				pkg = JSON.parse(pkg);

				fixers[method](pkg);

				const contents = JSON.stringify(pkg, undefined, indentation);
				return ctx.fs.writeFile('package.json', `${contents}${lastchar}`, 'utf8');
			});
	};
};

module.exports = ctx => {
	const requiredVersion = ctx.options[0];
	const file = ctx.fs.resolve('package.json');

	return ctx.fs.readFile('package.json').then(pkg => {
		const installedVersion = pkg.devDependencies && pkg.devDependencies.xo;

		if (!installedVersion) {
			return {
				message: 'XO is not installed as devDependency.',
				file
			};
		}

		const errors = [];

		if (pkg.engines && pkg.engines.node && !semver.satisfies('0.10.0', pkg.engines.node) && !semver.satisfies('0.12.0', pkg.engines.node)) {
			if (!pkg.xo || pkg.xo.esnext !== true) {
				errors.push({
					message: 'Enforce ES2015+ rules in XO with the `esnext` option.',
					fix: fix(ctx, 'esnext'),
					file
				});
			}
		}

		if (requiredVersion) {
			if (requiredVersion === '*' && installedVersion !== '*') {
				errors.push({
					message: `Expected unicorn version '*' but found '${installedVersion}'.`,
					file
				});
			} else if (requiredVersion !== '*' && !semver.gte(installedVersion, requiredVersion)) {
				errors.push({
					message: `Expected version '${requiredVersion}' but found '${installedVersion}'.`,
					file
				});
			}
		}

		if (!pkg.scripts || !pkg.scripts.test || !/\bxo\b/.test(pkg.scripts.test)) {
			errors.push({
				message: 'XO is not used in the test script.',
				fix: fix(ctx, 'script'),
				file
			});
		}

		if (pkg.scripts && pkg.scripts.test && /\bxo\b[^&]*[\-]{2}/.test(pkg.scripts.test)) {
			errors.push({
				message: 'Specify XO config in `package.json` instead of passing it through via the CLI.',
				fix: fix(ctx, 'clioptions'),
				file
			});
		}

		return errors;
	});
};
<|endoftext|>


<commit_before><commit_msg>marklet formatter utils<commit_after>var util = {
  fetchTextFile: function(path) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", path, false);
    xmlhttp.send();
    return xmlhttp.responseText;
  },

  formatMarklet: function(text) {
    return 'javascript:{' + text.replace(/[\040\n]/gi, '%20'); + '};void(0)';
  }
};
<|endoftext|>


<commit_before>function(head, req) {
    registerType("hal", "application/hal+json");
    provides("hal", function() {
        start({
            "headers": {
                "Content-Type": "application/hal+json",
                "Vary": "Accept"
            }
        });
        var resource = {};
        var row;
        while (row = getRow()) {
            if (0 == row.key[1]) {
                resource = row.value;
                resource._links.item = [];
            } else if (1 == row.key[1] && resource._links) {
                resource._links.item.push({
                    "href": "/" + row.id
                });
            }
        }
        send(JSON.stringify(resource));
        send("\n");
    });
}
<commit_msg>Provide item title.<commit_after>function(head, req) {
    registerType("hal", "application/hal+json");
    provides("hal", function() {
        start({
            "headers": {
                "Content-Type": "application/hal+json",
                "Vary": "Accept"
            }
        });
        var resource = {};
        var row;
        while (row = getRow()) {
            if (0 == row.key[1]) {
                resource = row.value;
                resource._links.item = [];
            } else if (1 == row.key[1] && resource._links) {
                resource._links.item.push({
                    "href": "/" + row.id,
                    "title": row.value.title
                });
            }
        }
        send(JSON.stringify(resource));
        send("\n");
    });
}
<|endoftext|>


<commit_before>var path = require('path');
var pkg = require('../package.json');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

var constantPack = new webpack.DefinePlugin({
  QUILL_VERSION: JSON.stringify(pkg.version)
});

module.exports = {
  context: path.resolve(__dirname, '..'),
  entry: {
    'quill.js': ['./quill.js'],
    'quill.css': './assets/core.styl',
    'quill.bubble.css': './assets/bubble.styl',
    'quill.snow.css': './assets/snow.styl',
    'unit.js': './test/unit.js'
  },
  output: {
    filename: '[name]',
    library: 'Quill',
    libraryTarget: 'umd',
    path: 'dist/'
  },
  resolve: {
    alias: {
      'parchment'     : path.resolve(__dirname, '..', 'node_modules/parchment/src/parchment'),
      'quill/core'    : path.resolve(__dirname, '..', 'core.js'),
      'quill/assets'  : path.resolve(__dirname, '..', 'assets'),
      'quill/blots'   : path.resolve(__dirname, '..', 'blots'),
      'quill/formats' : path.resolve(__dirname, '..', 'formats'),
      'quill/modules' : path.resolve(__dirname, '..', 'modules'),
      'quill/themes'  : path.resolve(__dirname, '..', 'themes'),
      'quill/ui'      : path.resolve(__dirname, '..', 'ui'),
      'quill'         : path.resolve(__dirname, '..', 'core')
    },
    extensions: ['', '.js', '.styl', '.ts']
  },
  // TODO remove
  isparta: {
    embedSource: true,
    noAutoWrap: true,
    babel: {
      presets: ['es2015']
    }
  },
  module: {
    loaders: [
      { test: /parchment\/src\/.*\.ts$/, loader: 'ts' },
      { test: /\.styl$/, loader: ExtractTextPlugin.extract('style', 'css!stylus') },
      { test: /(?!node_modules)\/.*\.js$/, loader: 'babel?presets[]=es2015' },
      { test: /\.svg$/, loader: 'html?minimize=true' }
    ],
    noParse: [
      /\/node_modules\/clone\/clone\.js$/,
      /\/node_modules\/eventemitter3\/index\.js$/,
      /\/node_modules\/extend\/index\.js$/
    ]
  },
  ts: {
    configFileName: 'nonexistent.json',   // Parchment tsconfig wants to build tests, we don't
    compilerOptions: {
      target: 'es5',
      module: 'commonjs'
    },
    silent: true
  },
  plugins: [ constantPack, new ExtractTextPlugin('[name]', { allChunks: true }) ],
  devtool: 'source-map',
  devServer: {
    hot: false,
    port: 9080,
    stats: {
      assets: false,
      chunks: false,
      errorDetails: true,
      errors: true,
      hash: false,
      timings: false,
      version: false,
      warnings: true
    }
  }
};
<commit_msg>not using isparta<commit_after>var path = require('path');
var pkg = require('../package.json');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

var constantPack = new webpack.DefinePlugin({
  QUILL_VERSION: JSON.stringify(pkg.version)
});

module.exports = {
  context: path.resolve(__dirname, '..'),
  entry: {
    'quill.js': ['./quill.js'],
    'quill.css': './assets/core.styl',
    'quill.bubble.css': './assets/bubble.styl',
    'quill.snow.css': './assets/snow.styl',
    'unit.js': './test/unit.js'
  },
  output: {
    filename: '[name]',
    library: 'Quill',
    libraryTarget: 'umd',
    path: 'dist/'
  },
  resolve: {
    alias: {
      'parchment'     : path.resolve(__dirname, '..', 'node_modules/parchment/src/parchment'),
      'quill/core'    : path.resolve(__dirname, '..', 'core.js'),
      'quill/assets'  : path.resolve(__dirname, '..', 'assets'),
      'quill/blots'   : path.resolve(__dirname, '..', 'blots'),
      'quill/formats' : path.resolve(__dirname, '..', 'formats'),
      'quill/modules' : path.resolve(__dirname, '..', 'modules'),
      'quill/themes'  : path.resolve(__dirname, '..', 'themes'),
      'quill/ui'      : path.resolve(__dirname, '..', 'ui'),
      'quill'         : path.resolve(__dirname, '..', 'core')
    },
    extensions: ['', '.js', '.styl', '.ts']
  },
  module: {
    loaders: [
      { test: /parchment\/src\/.*\.ts$/, loader: 'ts' },
      { test: /\.styl$/, loader: ExtractTextPlugin.extract('style', 'css!stylus') },
      { test: /(?!node_modules)\/.*\.js$/, loader: 'babel?presets[]=es2015' },
      { test: /\.svg$/, loader: 'html?minimize=true' }
    ],
    noParse: [
      /\/node_modules\/clone\/clone\.js$/,
      /\/node_modules\/eventemitter3\/index\.js$/,
      /\/node_modules\/extend\/index\.js$/
    ]
  },
  ts: {
    configFileName: 'nonexistent.json',   // Parchment tsconfig wants to build tests, we don't
    compilerOptions: {
      target: 'es5',
      module: 'commonjs'
    },
    silent: true
  },
  plugins: [ constantPack, new ExtractTextPlugin('[name]', { allChunks: true }) ],
  devtool: 'source-map',
  devServer: {
    hot: false,
    port: 9080,
    stats: {
      assets: false,
      chunks: false,
      errorDetails: true,
      errors: true,
      hash: false,
      timings: false,
      version: false,
      warnings: true
    }
  }
};
<|endoftext|>


<commit_before>module.exports = function(config,grunt) {
  var _c = {
    build: {
      options: {
        appDir: '<%= tempDir %>',
        dir: '<%= destDir %>',

        mainConfigFile: '<%= tempDir %>/app/components/require.config.js',
        modules: [], // populated below

        optimize: 'none',
        optimizeCss: 'none',
        optimizeAllPluginResources: false,

        paths: { config: '../config.sample' }, // fix, fallbacks need to be specified

        removeCombined: true,
        findNestedDependencies: true,
        normalizeDirDefines: 'all',
        inlineText: true,
        skipPragmas: true,

        done: function (done, output) {
          var duplicates = require('rjs-build-analysis').duplicates(output);

          if (duplicates.length > 0) {
            grunt.log.subhead('Duplicates found in requirejs build:');
            grunt.log.warn(duplicates);
            done(new Error('r.js built duplicate modules, please check the excludes option.'));
          }

          done();
        }
      }
    }
  };

  // setup the modules require will build
  var requireModules = _c.build.options.modules = [
    {
      // main/common module
      name: 'app',
      include: [
        'css',
        'kbn',
        'text',
        'jquery',
        'angular',
        'settings',
        'bootstrap',
        'modernizr',
        'timepicker',
        'datepicker',
        'underscore',
        'filters/all',
        'jquery.flot',
        'services/all',
        'angular-strap',
        'directives/all',
        'jquery.flot.pie',
        'angular-dragdrop',
      ]
    }
  ];

  var fs = require('fs');
  var panelPath = config.srcDir+'/app/panels'

  // create a module for each directory in src/app/panels/
  fs.readdirSync(panelPath).forEach(function (panelName) {
    requireModules[0].include.push('panels/'+panelName+'/module');
    requireModules[0].include.push('text!panels/'+panelName+'/module.html');
  });

  // exclude the literal config definition from all modules
  requireModules
    .forEach(function (module) {
      module.excludeShallow = module.excludeShallow || [];
      module.excludeShallow.push('config');
    });

  return _c;
};
<commit_msg>Fix release build rules following 23c9f97 and #659<commit_after>module.exports = function(config,grunt) {
  var _c = {
    build: {
      options: {
        appDir: '<%= tempDir %>',
        dir: '<%= destDir %>',

        mainConfigFile: '<%= tempDir %>/app/components/require.config.js',
        modules: [], // populated below

        optimize: 'none',
        optimizeCss: 'none',
        optimizeAllPluginResources: false,

        paths: { config: '../config.sample' }, // fix, fallbacks need to be specified

        removeCombined: true,
        findNestedDependencies: true,
        normalizeDirDefines: 'all',
        inlineText: true,
        skipPragmas: true,

        done: function (done, output) {
          var duplicates = require('rjs-build-analysis').duplicates(output);

          if (duplicates.length > 0) {
            grunt.log.subhead('Duplicates found in requirejs build:');
            grunt.log.warn(duplicates);
            done(new Error('r.js built duplicate modules, please check the excludes option.'));
          }

          done();
        }
      }
    }
  };

  // setup the modules require will build
  var requireModules = _c.build.options.modules = [
    {
      // main/common module
      name: 'app',
      include: [
        'css',
        'kbn',
        'text',
        'jquery',
        'angular',
        'settings',
        'bootstrap',
        'modernizr',
        'timepicker',
        'datepicker',
        'lodash',
        'filters/all',
        'jquery.flot',
        'services/all',
        'angular-strap',
        'directives/all',
        'jquery.flot.pie',
        'angular-dragdrop',
      ]
    }
  ];

  var fs = require('fs');
  var panelPath = config.srcDir+'/app/panels'

  // create a module for each directory in src/app/panels/
  fs.readdirSync(panelPath).forEach(function (panelName) {
    requireModules[0].include.push('panels/'+panelName+'/module');
    requireModules[0].include.push('text!panels/'+panelName+'/module.html');
  });

  // exclude the literal config definition from all modules
  requireModules
    .forEach(function (module) {
      module.excludeShallow = module.excludeShallow || [];
      module.excludeShallow.push('config');
    });

  return _c;
};
<|endoftext|>